blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
5a6ec8c195ffb983e044836745ec4031de7e735b
670f828aea8b44507fd64ba84cf2b765baadf95d
/AR_cylReactor/processor15/constant/polyMesh/neighbour
f79460a581171faa4ce63080c6c5bec83c251d4a
[]
no_license
rashwin1989/sharedOFCases
c6d224ac11669ca7b8e69e292e6aa8aa82961803
df459380195835b2967393bfe05f89910b7ae3a5
refs/heads/master
2020-03-16T19:57:37.472882
2018-08-13T21:41:43
2018-08-13T21:41:43
132,940,021
1
0
null
null
null
null
UTF-8
C++
false
false
14,453
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class labelList; note "nPoints: 3405 nCells: 1611 nFaces: 6525 nInternalFaces: 3121"; location "constant/polyMesh"; object neighbour; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 3121 ( 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18 37 19 38 39 21 40 22 41 23 42 24 43 25 44 26 45 27 46 28 47 29 48 30 49 31 50 32 51 33 52 34 53 35 54 36 55 37 56 38 57 39 58 59 41 60 42 61 43 62 44 63 45 64 46 65 47 66 48 67 49 68 50 69 51 70 52 71 53 72 54 73 55 74 56 75 57 76 58 77 59 78 79 61 80 62 81 63 82 64 83 65 84 66 85 67 86 68 87 69 88 70 89 71 90 72 91 73 92 74 93 75 94 76 95 77 96 78 97 79 98 99 81 100 82 101 83 102 84 103 85 104 86 105 87 106 88 107 89 108 90 109 91 110 92 111 93 112 94 113 95 114 96 115 97 116 98 117 99 118 119 101 120 102 121 103 122 104 123 105 124 106 125 107 126 108 127 109 128 110 129 111 130 112 131 113 132 114 133 115 134 116 135 117 136 118 137 119 138 139 121 140 122 141 123 142 124 143 125 144 126 145 127 146 128 147 129 148 130 149 131 150 132 151 133 152 134 153 135 154 136 155 137 156 138 157 139 158 159 141 160 142 161 143 162 144 163 145 164 146 165 147 166 148 167 149 168 150 169 151 170 152 171 153 172 154 173 155 174 156 175 157 176 158 177 159 178 179 161 180 162 181 163 182 164 183 165 184 166 185 167 186 168 187 169 188 170 189 171 190 172 191 173 192 174 193 175 194 176 195 177 196 178 197 179 198 199 181 200 182 201 183 202 184 203 185 204 186 205 187 206 188 207 189 208 190 209 191 210 192 211 193 212 194 213 195 214 196 215 197 216 198 217 199 218 219 201 220 202 221 203 222 204 223 205 224 206 225 207 226 208 227 209 228 210 229 211 230 212 231 213 232 214 233 215 234 216 235 217 236 218 237 219 238 239 221 240 222 241 223 242 224 243 225 244 226 245 227 246 228 247 229 248 230 249 231 250 232 251 233 252 234 253 235 254 236 255 237 256 238 257 239 258 259 241 260 242 261 243 262 244 263 245 264 246 265 247 266 248 267 249 268 250 269 251 270 252 271 253 272 254 273 255 274 256 275 257 276 258 277 259 278 279 261 280 262 281 263 282 264 283 265 284 266 285 267 286 268 287 269 288 270 289 271 290 272 291 273 292 274 293 275 294 276 295 277 296 278 297 279 298 299 281 300 282 301 283 302 284 303 285 304 286 305 287 306 288 307 289 308 290 309 291 310 292 311 293 312 294 313 295 314 296 315 297 316 298 317 299 318 319 301 320 302 321 303 322 304 323 305 324 306 325 307 326 308 327 309 328 310 329 311 330 312 331 313 332 314 333 315 334 316 335 317 336 318 337 319 338 339 321 340 322 341 323 342 324 343 325 344 326 345 327 346 328 347 329 348 330 349 331 350 332 351 333 352 334 353 335 354 336 355 337 356 338 357 339 358 359 341 360 342 361 343 362 344 363 345 364 346 365 347 366 348 367 349 368 350 369 351 370 352 371 353 372 354 373 355 374 356 375 357 376 358 377 359 378 379 361 380 362 381 363 382 364 383 365 384 366 385 367 386 368 387 369 388 370 389 371 390 372 391 373 392 374 393 375 394 376 395 377 396 378 397 379 398 399 381 400 382 401 383 402 384 403 385 404 386 405 387 406 388 407 389 408 390 409 391 410 392 411 393 412 394 413 395 414 396 415 397 416 398 417 399 418 419 401 420 402 421 403 422 404 423 405 424 406 425 407 426 408 427 409 428 410 429 411 430 412 431 413 432 414 433 415 434 416 435 417 436 418 437 419 438 439 421 440 422 441 423 442 424 443 425 444 426 445 427 446 428 447 429 448 430 449 431 450 432 451 433 452 434 453 435 454 436 455 437 456 438 457 439 458 459 441 460 442 461 443 462 444 463 445 464 446 465 447 466 448 467 449 468 450 469 451 470 452 471 453 472 454 473 455 474 456 475 457 476 458 477 459 478 479 461 480 462 481 463 482 464 483 465 484 466 485 467 486 468 487 469 488 470 489 471 490 472 491 473 492 474 493 475 494 476 495 477 496 478 497 479 498 499 481 500 482 501 483 502 484 503 485 504 486 505 487 506 488 507 489 508 490 509 491 510 492 511 493 512 494 513 495 514 496 515 497 516 498 517 499 518 519 501 520 502 521 503 522 504 523 505 524 506 525 507 526 508 527 509 528 510 529 511 530 512 531 513 532 514 533 515 534 516 535 517 536 518 537 519 538 539 521 540 522 541 523 542 524 543 525 544 526 545 527 546 528 547 529 548 530 549 531 550 532 551 533 552 534 553 535 554 536 555 537 556 538 557 539 558 559 541 560 542 561 543 562 544 563 545 564 546 565 547 566 548 567 549 568 550 569 551 570 552 571 553 572 554 573 555 574 556 575 557 576 558 577 559 578 579 561 580 562 581 563 582 564 583 565 584 566 585 567 586 568 587 569 588 570 589 571 590 572 591 573 592 574 593 575 594 576 595 577 596 578 597 579 598 599 581 600 582 601 583 602 584 603 585 604 586 605 587 606 588 607 589 608 590 609 591 610 592 611 593 612 594 613 595 614 596 615 597 616 598 617 599 618 619 601 620 602 621 603 622 604 623 605 624 606 625 607 626 608 627 609 628 610 629 611 630 612 631 613 632 614 633 615 634 616 635 617 636 618 637 619 638 639 621 640 622 641 623 642 624 643 625 644 626 645 627 646 628 647 629 648 630 649 631 650 632 651 633 652 634 653 635 654 636 655 637 656 638 657 639 658 659 641 660 642 661 643 662 644 663 645 664 646 665 647 666 648 667 649 668 650 669 651 670 652 671 653 672 654 673 655 674 656 675 657 676 658 677 659 678 679 661 680 662 681 663 682 664 683 665 684 666 685 667 686 668 687 669 688 670 689 671 690 672 691 673 692 674 693 675 694 676 695 677 696 678 697 679 698 699 681 700 682 701 683 702 684 703 685 704 686 705 687 706 688 707 689 708 690 709 691 710 692 711 693 712 694 713 695 714 696 715 697 716 698 717 699 718 719 701 720 702 721 703 722 704 723 705 724 706 725 707 726 708 727 709 728 710 729 711 730 712 731 713 732 714 733 715 734 716 735 717 736 718 737 719 738 739 721 741 722 742 723 743 724 744 725 745 726 746 727 747 728 748 729 749 730 750 731 751 732 752 733 753 734 754 735 755 736 756 737 757 738 758 739 759 760 741 761 742 762 743 763 744 764 745 765 746 766 747 767 748 768 749 769 750 770 751 771 752 772 753 773 754 774 755 775 756 776 757 777 758 778 759 779 760 780 781 762 782 763 783 764 784 765 785 766 786 767 787 768 788 769 789 770 790 771 791 772 792 773 793 774 794 775 795 776 796 777 797 778 798 779 799 780 800 781 801 802 783 803 784 804 785 805 786 806 787 807 788 808 789 809 790 810 791 811 792 812 793 813 794 814 795 815 796 816 797 817 798 818 799 819 800 820 801 821 802 822 823 804 824 805 825 806 826 807 827 808 828 809 829 810 830 811 831 812 832 813 833 814 834 815 835 816 836 817 837 818 838 819 839 820 840 821 841 822 842 823 843 844 825 845 826 846 827 847 828 848 829 849 830 850 831 851 832 852 833 853 834 854 835 855 836 856 837 857 838 858 839 859 840 860 841 861 842 862 843 863 844 864 865 846 866 847 867 848 868 849 869 850 870 851 871 852 872 853 873 854 874 855 875 856 876 857 877 858 878 859 879 860 880 861 881 862 882 863 883 864 884 865 885 886 867 887 868 888 869 889 870 890 871 891 872 892 873 893 874 894 875 895 876 896 877 897 878 898 879 899 880 900 881 901 882 902 883 903 884 904 885 905 886 906 907 888 908 889 909 890 910 891 911 892 912 893 913 894 914 895 915 896 916 897 917 898 918 899 919 900 920 901 921 902 922 903 923 904 924 905 925 906 926 907 927 928 909 929 910 930 911 931 912 932 913 933 914 934 915 935 916 936 917 937 918 938 919 939 920 940 921 941 922 942 923 943 924 944 925 945 926 946 927 947 928 948 949 930 950 931 951 932 952 933 953 934 954 935 955 936 956 937 957 938 958 939 959 940 960 941 961 942 962 943 963 944 964 945 965 946 966 947 967 948 968 949 969 970 951 971 952 972 953 973 954 974 955 975 956 976 957 977 958 978 959 979 960 980 961 981 962 982 963 983 964 984 965 985 966 986 967 987 968 988 969 989 970 990 972 991 973 992 974 993 975 994 976 995 977 996 978 997 979 998 980 999 981 1000 982 1001 983 1002 984 1003 985 1004 986 1005 987 1006 988 1007 989 1008 990 1009 1010 992 1011 993 1012 994 1013 995 1014 996 1015 997 1016 998 1017 999 1018 1000 1019 1001 1020 1002 1021 1003 1022 1004 1023 1005 1024 1006 1025 1007 1026 1008 1027 1009 1028 1010 1029 1030 1012 1031 1013 1032 1014 1033 1015 1034 1016 1035 1017 1036 1018 1037 1019 1038 1020 1039 1021 1040 1022 1041 1023 1042 1024 1043 1025 1044 1026 1045 1027 1046 1028 1047 1029 1048 1030 1049 1050 1032 1051 1033 1052 1034 1053 1035 1054 1036 1055 1037 1056 1038 1057 1039 1058 1040 1059 1041 1060 1042 1061 1043 1062 1044 1063 1045 1064 1046 1065 1047 1066 1048 1067 1049 1068 1050 1069 1070 1052 1071 1053 1072 1054 1073 1055 1074 1056 1075 1057 1076 1058 1077 1059 1078 1060 1079 1061 1080 1062 1081 1063 1082 1064 1083 1065 1084 1066 1085 1067 1086 1068 1087 1069 1088 1070 1089 1090 1072 1091 1073 1092 1074 1093 1075 1094 1076 1095 1077 1096 1078 1097 1079 1098 1080 1099 1081 1100 1082 1101 1083 1102 1084 1103 1085 1104 1086 1105 1087 1106 1088 1107 1089 1108 1090 1109 1110 1092 1111 1093 1112 1094 1113 1095 1114 1096 1115 1097 1116 1098 1117 1099 1118 1100 1119 1101 1120 1102 1121 1103 1122 1104 1123 1105 1124 1106 1125 1107 1126 1108 1127 1109 1128 1110 1129 1130 1112 1131 1113 1132 1114 1133 1115 1134 1116 1135 1117 1136 1118 1137 1119 1138 1120 1139 1121 1140 1122 1141 1123 1142 1124 1143 1125 1144 1126 1145 1127 1146 1128 1147 1129 1148 1130 1149 1150 1132 1151 1133 1152 1134 1153 1135 1154 1136 1155 1137 1156 1138 1157 1139 1158 1140 1159 1141 1160 1142 1161 1143 1162 1144 1163 1145 1164 1146 1165 1147 1166 1148 1167 1149 1168 1150 1169 1170 1152 1171 1153 1172 1154 1173 1155 1174 1156 1175 1157 1176 1158 1177 1159 1178 1160 1179 1161 1180 1162 1181 1163 1182 1164 1183 1165 1184 1166 1185 1167 1186 1168 1187 1169 1188 1170 1189 1190 1172 1191 1173 1192 1174 1193 1175 1194 1176 1195 1177 1196 1178 1197 1179 1198 1180 1199 1181 1200 1182 1201 1183 1202 1184 1203 1185 1204 1186 1205 1187 1206 1188 1207 1189 1208 1190 1209 1210 1192 1211 1193 1212 1194 1213 1195 1214 1196 1215 1197 1216 1198 1217 1199 1218 1200 1219 1201 1220 1202 1221 1203 1222 1204 1223 1205 1224 1206 1225 1207 1226 1208 1227 1209 1228 1210 1229 1230 1212 1231 1213 1232 1214 1233 1215 1234 1216 1235 1217 1236 1218 1237 1219 1238 1220 1239 1221 1240 1222 1241 1223 1242 1224 1243 1225 1244 1226 1245 1227 1246 1228 1247 1229 1248 1230 1249 1250 1232 1251 1233 1252 1234 1253 1235 1254 1236 1255 1237 1256 1238 1257 1239 1258 1240 1259 1241 1260 1242 1261 1243 1262 1244 1263 1245 1264 1246 1265 1247 1266 1248 1267 1249 1268 1250 1269 1270 1252 1271 1253 1272 1254 1273 1255 1274 1256 1275 1257 1276 1258 1277 1259 1278 1260 1279 1261 1280 1262 1281 1263 1282 1264 1283 1265 1284 1266 1285 1267 1286 1268 1287 1269 1288 1270 1289 1290 1272 1291 1273 1292 1274 1293 1275 1294 1276 1295 1277 1296 1278 1297 1279 1298 1280 1299 1281 1300 1282 1301 1283 1302 1284 1303 1285 1304 1286 1305 1287 1306 1288 1307 1289 1308 1290 1309 1310 1292 1311 1293 1312 1294 1313 1295 1314 1296 1315 1297 1316 1298 1317 1299 1318 1300 1319 1301 1320 1302 1321 1303 1322 1304 1323 1305 1324 1306 1325 1307 1326 1308 1327 1309 1328 1310 1329 1330 1312 1331 1313 1332 1314 1333 1315 1334 1316 1335 1317 1336 1318 1337 1319 1338 1320 1339 1321 1340 1322 1341 1323 1342 1324 1343 1325 1344 1326 1345 1327 1346 1328 1347 1329 1348 1330 1349 1350 1332 1351 1333 1352 1334 1353 1335 1354 1336 1355 1337 1356 1338 1357 1339 1358 1340 1359 1341 1360 1342 1361 1343 1362 1344 1363 1345 1364 1346 1365 1347 1366 1348 1367 1349 1368 1350 1369 1370 1352 1371 1353 1372 1354 1373 1355 1374 1356 1375 1357 1376 1358 1377 1359 1378 1360 1379 1361 1380 1362 1381 1363 1382 1364 1383 1365 1384 1366 1385 1367 1386 1368 1387 1369 1388 1370 1389 1390 1372 1391 1373 1392 1374 1393 1375 1394 1376 1395 1377 1396 1378 1397 1379 1398 1380 1399 1381 1400 1382 1401 1383 1402 1384 1403 1385 1404 1386 1405 1387 1406 1388 1407 1389 1408 1390 1409 1410 1392 1411 1393 1412 1394 1413 1395 1414 1396 1415 1397 1416 1398 1417 1399 1418 1400 1419 1401 1420 1402 1421 1403 1422 1404 1423 1405 1424 1406 1425 1407 1426 1408 1427 1409 1428 1410 1429 1430 1412 1431 1413 1432 1414 1433 1415 1434 1416 1435 1417 1436 1418 1437 1419 1438 1420 1439 1421 1440 1422 1441 1423 1442 1424 1443 1425 1444 1426 1445 1427 1446 1428 1447 1429 1448 1430 1449 1450 1432 1451 1433 1452 1434 1453 1435 1454 1436 1455 1437 1456 1438 1457 1439 1458 1440 1459 1441 1460 1442 1461 1443 1462 1444 1463 1445 1464 1446 1465 1447 1466 1448 1467 1449 1468 1450 1469 1470 1452 1471 1453 1472 1454 1473 1455 1474 1456 1475 1457 1476 1458 1477 1459 1478 1460 1479 1461 1480 1462 1481 1463 1482 1464 1483 1465 1484 1466 1485 1467 1486 1468 1487 1469 1488 1470 1489 1490 1472 1491 1473 1492 1474 1493 1475 1494 1476 1495 1477 1496 1478 1497 1479 1498 1480 1499 1481 1500 1482 1501 1483 1502 1484 1503 1485 1504 1486 1505 1487 1506 1488 1507 1489 1508 1490 1509 1510 1492 1511 1493 1512 1494 1513 1495 1514 1496 1515 1497 1516 1498 1517 1499 1518 1500 1519 1501 1520 1502 1521 1503 1522 1504 1523 1505 1524 1506 1525 1507 1526 1508 1527 1509 1528 1510 1529 1530 1512 1531 1513 1532 1514 1533 1515 1534 1516 1535 1517 1536 1518 1537 1519 1538 1520 1539 1521 1540 1522 1541 1523 1542 1524 1543 1525 1544 1526 1545 1527 1546 1528 1547 1529 1548 1530 1549 1550 1532 1551 1533 1552 1534 1553 1535 1554 1536 1555 1537 1556 1538 1557 1539 1558 1540 1559 1541 1560 1542 1561 1543 1562 1544 1563 1545 1564 1546 1565 1547 1566 1548 1567 1549 1568 1550 1569 1570 1552 1571 1553 1572 1554 1573 1555 1574 1556 1575 1557 1576 1558 1577 1559 1578 1560 1579 1561 1580 1562 1581 1563 1582 1564 1583 1565 1584 1566 1585 1567 1586 1568 1587 1569 1588 1570 1589 1590 1572 1591 1573 1592 1574 1593 1575 1594 1576 1595 1577 1596 1578 1597 1579 1598 1580 1599 1581 1600 1582 1601 1583 1602 1584 1603 1585 1604 1586 1605 1587 1606 1588 1607 1589 1608 1590 1609 1610 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 ) // ************************************************************************* //
[ "aniket119955@gmail.com" ]
aniket119955@gmail.com
34f4d40aea19317ee7a583c33ccf33190faaeca1
ce35e84f327e064429030e2a45a257fca2cf5564
/Multiplayer/C++/Ultimate_Tic_Tac_Toe/Bronze_League.cpp
cbd590fa6f51a12cc2b9d4d15380c75acd15009f
[]
no_license
jackysz/CodinGame-3
302d935e629757e30ef91cb55a4623173db45816
2cdd0d549313c390b2f77404653a730c9ea97135
refs/heads/master
2020-05-15T10:03:09.468811
2018-05-26T19:58:28
2018-05-26T19:58:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,156
cpp
/*~~~~~~~~~~~~~~~~~~* * * * $DollarAkshay$ * * * *~~~~~~~~~~~~~~~~~~*/ //https://www.codingame.com/ide/puzzle/tic-tac-toe #include <algorithm> #include <assert.h> #include <ctype.h> #include <deque> #include <iostream> #include <map> #include <math.h> #include <queue> #include <set> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <time.h> #include <vector> using namespace std; #define REP(i, n) for (int i = 0; i < n; i++) #define FOR(i, a, b) for (int i = a; i <= b; i++) #define FORD(i, a, b) for (int i = a; i >= b; --i) #define DB(format, ...) fprintf(stderr, format, ##__VA_ARGS__) #define MSX(a, row) memset(a, row, sizeof(a)) #define SORT(a, n) sort(begin(a), begin(a) + n) #define ll long long #define MOD 1000000007 #define SMALL_BOARD_SIZE 3 #define BOARD_SIZE 9 class Move { public: int row, col; Move() { row = -1; col = -1; } Move(int row, int col) { this->row = row; this->col = col; } string toString() { return to_string(row) + " " + to_string(col); } bool operator==(const class Move rhs) const { return row == rhs.row && col == rhs.col; } bool operator<(const class Move rhs) const { return (row < rhs.row) || (row == rhs.row && col < rhs.col); } }; class GameState { public: char blank, player, opponent; int turn; class Move prevMove; char smallBoardWinner[SMALL_BOARD_SIZE][SMALL_BOARD_SIZE]; char fullBoard[BOARD_SIZE][BOARD_SIZE]; GameState() { blank = '-'; player = blank; opponent = blank; turn = -1; prevMove = Move(); MSX(fullBoard, blank); MSX(smallBoardWinner, blank); } // Initialize the game state void init(class Move move) { if (move.col == -1 && move.row == -1) { player = 'X'; opponent = 'O'; turn = 0; } else { player = 'O'; opponent = 'X'; turn = 1; } } void printGameState() { DB("PREV MOVE : %s\n\n", prevMove.toString().c_str()); // Print the Small Board DB("SMALL BOARD : \n"); REP(i, SMALL_BOARD_SIZE) { REP(j, SMALL_BOARD_SIZE) { DB("%c ", smallBoardWinner[i][j]); } DB("\n"); } DB("\n"); // Print the Full Board DB("FULL BOARD : \n"); REP(i, BOARD_SIZE) { REP(j, BOARD_SIZE) { DB("%c ", fullBoard[i][j]); if (j % SMALL_BOARD_SIZE == SMALL_BOARD_SIZE - 1 && j != BOARD_SIZE - 1) { DB("# "); } } DB("\n"); if (i % SMALL_BOARD_SIZE == SMALL_BOARD_SIZE - 1 && i != BOARD_SIZE - 1) { REP(j, BOARD_SIZE + SMALL_BOARD_SIZE - 1) { DB("##"); } DB("\n"); } } DB("\n"); } // Update the small board and check if anyone has won it. Else reset it void updateSmallBoard(int smallBoardRow, int smallBoardCol) { int rowOff = smallBoardRow * 3; int colOff = smallBoardCol * 3; // Horizontal REP(i, 3) { if (fullBoard[i + rowOff][0 + colOff] == fullBoard[i + rowOff][1 + colOff] && fullBoard[i + rowOff][1 + colOff] == fullBoard[i + rowOff][2 + colOff] && fullBoard[i + rowOff][2 + colOff] != blank) { smallBoardWinner[smallBoardRow][smallBoardCol] = fullBoard[i + rowOff][2 + colOff]; return; } } // Vertical REP(i, 3) { if (fullBoard[0 + rowOff][i + colOff] == fullBoard[1 + rowOff][i + colOff] && fullBoard[1 + rowOff][i + colOff] == fullBoard[2 + rowOff][i + colOff] && fullBoard[2 + rowOff][i + colOff] != blank) { smallBoardWinner[smallBoardRow][smallBoardCol] = fullBoard[2 + rowOff][i + colOff]; return; } } // Diagonal 0,0 - 2,2 if (fullBoard[0 + rowOff][0 + colOff] == fullBoard[1 + rowOff][1 + colOff] && fullBoard[1 + rowOff][1 + colOff] == fullBoard[2 + rowOff][2 + colOff] && fullBoard[2 + rowOff][2 + colOff] != blank) { smallBoardWinner[smallBoardRow][smallBoardCol] = fullBoard[2 + rowOff][2 + colOff]; return; } // Diagonal 0,2 - 2,0 if (fullBoard[0 + rowOff][2 + colOff] == fullBoard[1 + rowOff][1 + colOff] && fullBoard[1 + rowOff][1 + colOff] == fullBoard[2 + rowOff][0 + colOff] && fullBoard[2 + rowOff][0 + colOff] != blank) { smallBoardWinner[smallBoardRow][smallBoardCol] = fullBoard[2 + rowOff][0 + colOff]; return; } smallBoardWinner[smallBoardRow][smallBoardCol] = blank; } // Make a move on the full board void doMove(class Move move, bool isPlayer) { if (move.row != -1 && move.col != -1) { prevMove = move; fullBoard[move.row][move.col] = isPlayer ? player : opponent; updateSmallBoard(move.row / SMALL_BOARD_SIZE, move.col / SMALL_BOARD_SIZE); } } // Undo the move on the full board void undoMove(class Move move, class Move prevMove) { if (move.row != -1 && move.col != -1) { this->prevMove = prevMove; fullBoard[move.row][move.col] = blank; updateSmallBoard(move.row / SMALL_BOARD_SIZE, move.col / SMALL_BOARD_SIZE); } } // Return the number of moves remaining in a small board int movesLeftInSmallBoard(int smallBoardRow, int smallBoardCol) { int rowOff = smallBoardRow * SMALL_BOARD_SIZE; int colOff = smallBoardCol * SMALL_BOARD_SIZE; // If the small board has already been won then there are no moves if (smallBoardWinner[rowOff][colOff] != blank) { return 0; } int movesLeft = 0; REP(i, SMALL_BOARD_SIZE) { REP(j, SMALL_BOARD_SIZE) { movesLeft += fullBoard[i][j] == blank ? 1 : 0; } } return movesLeft; } // Return the number of moves remaining in the entire board int movesLeftInFullBoard() { int movesLeft = 0; REP(i, BOARD_SIZE) { REP(j, BOARD_SIZE) { if (smallBoardWinner[i / SMALL_BOARD_SIZE][j / SMALL_BOARD_SIZE] == blank && fullBoard[i][j] == blank) { movesLeft += 1; } } } return movesLeft; } vector<class Move> generateMoves() { vector<class Move> moveList; int smallBoardRow = prevMove.row % SMALL_BOARD_SIZE; int smallBoardCol = prevMove.col % SMALL_BOARD_SIZE; int rowOff = smallBoardRow * SMALL_BOARD_SIZE; int colOff = smallBoardCol * SMALL_BOARD_SIZE; // Find all the moves in the small board if it is not won if (smallBoardWinner[smallBoardRow][smallBoardCol] == blank) { REP(i, SMALL_BOARD_SIZE) { REP(j, SMALL_BOARD_SIZE) { if (fullBoard[i + rowOff][j + colOff] == blank) { moveList.push_back(Move(i + rowOff, j + colOff)); } } } if (moveList.size() > 0) { return moveList; } } // If there are no moves in the small board, play anywhere REP(i, BOARD_SIZE) { REP(j, BOARD_SIZE) { if (smallBoardWinner[i / SMALL_BOARD_SIZE][j / SMALL_BOARD_SIZE] == blank && fullBoard[i][j] == blank) { moveList.push_back(Move(i, j)); } } } SORT(moveList, moveList.size()); return moveList; } // Return whether or not a certian player has won the game bool hasWonGame(char tokenType) { // Horizontal REP(i, 3) { if (smallBoardWinner[i][0] == smallBoardWinner[i][1] && smallBoardWinner[i][1] == smallBoardWinner[i][2] && smallBoardWinner[i][2] == tokenType) { return true; } } // Vertical REP(i, 3) { if (smallBoardWinner[0][i] == smallBoardWinner[1][i] && smallBoardWinner[1][i] == smallBoardWinner[2][i] && smallBoardWinner[2][i] == tokenType) { return true; } } // Diagonal 0,0 - 2,2 if (smallBoardWinner[0][0] == smallBoardWinner[1][1] && smallBoardWinner[1][1] == smallBoardWinner[2][2] && smallBoardWinner[2][2] == tokenType) { return true; } // Diagonal 0,2 - 2,0 if (smallBoardWinner[0][2] == smallBoardWinner[1][1] && smallBoardWinner[1][1] == smallBoardWinner[2][0] && smallBoardWinner[2][0] == tokenType) { return true; } return false; } // Return whether or not the game state is a draw bool isDraw() { return movesLeftInFullBoard() == 0; } }; const int MAX_DEPTH = 5; const int INF = 1E9; const int LOSS_HEURISTIC_COST = -1000; const int WIN_HEURISTIC_COST = 1000; int nodesEvaluated = 0; clock_t gameTime, moveTime; class Move bestMove; class GameState game; int minimax(int depth, int alpha, int beta, bool isPlayer) { nodesEvaluated++; // Evaluation if Leaf Node if (game.hasWonGame(game.player)) { return WIN_HEURISTIC_COST - depth; } if (game.hasWonGame(game.opponent)) { return LOSS_HEURISTIC_COST + depth; } if (depth >= MAX_DEPTH || game.isDraw() == true) { return 0; } if (isPlayer) { int bestVal = -INF; class Move prevMove = game.prevMove; vector<class Move> moveList = game.generateMoves(); for (class Move move : moveList) { game.doMove(move, isPlayer); int val = minimax(depth + 1, alpha, beta, !isPlayer); game.undoMove(move, prevMove); // Store the move if depth == 0 if (val > bestVal && depth == 0) { bestMove = move; } if (depth <= 0) { DB("%s = %d\n", move.toString().c_str(), val); } bestVal = max(bestVal, val); alpha = max(alpha, bestVal); if (beta <= alpha) { break; } } return bestVal; } else { int bestVal = INF; class Move prevMove = game.prevMove; vector<class Move> moveList = game.generateMoves(); for (class Move move : moveList) { game.doMove(move, isPlayer); int val = minimax(depth + 1, alpha, beta, !isPlayer); game.undoMove(move, prevMove); bestVal = min(bestVal, val); beta = min(beta, bestVal); if (beta <= alpha) { break; } } return bestVal; } } // Reset some variables every turn void readAndSimulateOpponentGameTurn() { nodesEvaluated = 0; bestMove = Move(); int row, col, moves; scanf("%d %d %d", &row, &col, &moves); REP(i, moves) { scanf("%*d %*d"); } class Move opponentMove = Move(row, col); if (game.turn == -1) { game.init(opponentMove); } game.doMove(opponentMove, false); } void makePlayerMove() { gameTime = clock(); int bestVal = minimax(0, -INF, INF, true); moveTime = clock() - gameTime; game.doMove(bestMove, true); printf("%s ", bestMove.toString().c_str()); printf("%d - %dk - %.4f\n", bestVal, nodesEvaluated / 1000, (double)moveTime / CLOCKS_PER_SEC); game.turn++; } int main() { readAndSimulateOpponentGameTurn(); game.printGameState(); makePlayerMove(); // Rest of the Turns while (true) { readAndSimulateOpponentGameTurn(); game.printGameState(); makePlayerMove(); } return 0; } //
[ "akshay95aradhya@gmail.com" ]
akshay95aradhya@gmail.com
538bfc2a8fb7fc0fd9b70e8d8709e806211c8f73
e759b26e849572d32252d6cde467e8edb3db3bc0
/kiam/math/funcprog/parsec/Parsec.Label.hpp
9d9e1291aba886880c37061fa7662104e8101e9b
[]
no_license
kmm1965/mathlib
d5c2ec1ea94a84ce4c5672f9f721d01398493320
f91282c1cbdccb83f53b7186c3cf00e9ca1d7e1c
refs/heads/master
2021-08-07T11:45:28.420776
2020-10-11T17:27:22
2020-10-11T17:27:22
223,895,424
0
0
null
null
null
null
UTF-8
C++
false
false
3,368
hpp
#pragma once _PARSEC_BEGIN /* labels :: ParsecT s u m a -> [String] -> ParsecT s u m a labels p msgs = ParsecT $ \s cok cerr eok eerr -> let eok' x s' error = eok x s' $ if errorIsUnknown error then error else setExpectErrors error msgs eerr' err = eerr $ setExpectErrors err msgs in unParser p s cok cerr eok' eerr' where setExpectErrors err [] = setErrorMessage (Expect "") err setExpectErrors err [msg] = setErrorMessage (Expect msg) err setExpectErrors err (msg:msgs) = foldr (\msg' err' -> addErrorMessage (Expect msg') err') (setErrorMessage (Expect msg) err) msgs */ template<typename S, typename U, typename _M, typename A, typename P> struct labels_unParser { using ParsecT_base_t = ParsecT_base<S, U, _M, A>; DECLARE_OK_ERR_TYPES(); labels_unParser(ParsecT<S, U, _M, A, P> const& p, List<std::string> const& msgs) : p(p), msgs(msgs){} template<typename B> constexpr auto run(State<S, U> const& s, ok_type<B> const& cok, err_type<B> const& cerr, ok_type<B> const& eok, err_type<B> const& eerr) const { const function_t<ParseError(ParseError const&, List<std::string> const&)> setExpectErrors = [](ParseError const& err, List<std::string> const& msgs) { const int lmsgs = length(msgs); if (lmsgs == 0) return setErrorMessage(Message(Expect, ""), err); else if (lmsgs == 1) return setErrorMessage(Message(Expect, msgs.front()), err); else return foldr(_([](std::string const& msg_, ParseError const& err_){ return addErrorMessage(Message(Expect, msg_), err_); }), setErrorMessage(Message(Expect, head(msgs)), err), tail(msgs)); }; /* let eok' x s' error = eok x s' $ if errorIsUnknown error then error else setExpectErrors error msgs eerr' err = eerr $ setExpectErrors err msgs */ ok_type<B> const eok_ = [this, &eok, &setExpectErrors](A const& x, State<S, U> const& s_, ParseError const& error){ return eok(x, s_, errorIsUnknown(error) ? error : setExpectErrors(error, msgs)); }; err_type<B> const eerr_ = [this, &eerr, &setExpectErrors](ParseError const& err){ return eerr(setExpectErrors(err, msgs)); }; return p.template run<B>(s, cok, cerr, eok_, eerr_); } private: const ParsecT<S, U, _M, A, P> p; const List<std::string> msgs; }; template<typename S, typename U, typename _M, typename A, typename P> constexpr auto labels(ParsecT<S, U, _M, A, P> const& p, List<std::string> const& msgs){ return ParsecT<S, U, _M, A, labels_unParser<S, U, _M, A, P> >(labels_unParser<S, U, _M, A, P>(p, msgs)); } /* -- | A synonym for @\<?>@, but as a function instead of an operator. label :: ParsecT s u m a -> String -> ParsecT s u m a label p msg = labels p [msg] */ template<typename S, typename U, typename _M, typename A, typename P> constexpr auto label(ParsecT<S, U, _M, A, P> const& p, std::string const& msg){ return labels(p, List<std::string>({ msg })); } template<typename S, typename U, typename _M, typename A, typename P> constexpr auto operator&(ParsecT<S, U, _M, A, P> const& p, std::string const& msg){ return label(p, msg); } _PARSEC_END
[ "kmm1965@mail.ru" ]
kmm1965@mail.ru
24a07a2d49296d27db52f8e3cd3c04777634e44e
afb4362bb6ee150cc81609b83d27075aaab3d407
/FinalProject/File.cpp
8e3e4138f0738ab7fd2317eda290889bba9891f6
[]
no_license
YoadZarka/FinalProject
9d773d1cedb5076d7ea5072e7e0673e71286d6cf
3d6558f86659edfae99f1d2a9a6a248003dd96ce
refs/heads/master
2021-01-18T22:22:16.535382
2017-07-03T14:10:07
2017-07-03T14:10:07
87,050,012
0
0
null
null
null
null
UTF-8
C++
false
false
2,245
cpp
/* * File.cpp * * Created on: Apr 3, 2017 * Author: yoad */ #include "File.h" using namespace std; /***** Important: All the errors in the system are not handle in the cpp code but in the python side * Therefore when an error occurs, a matching message will be print to STDout and the program breaks ******/ /*Constructor for opening a input file and count the files and blocks number*/ File::File(char* path, int reduce) { this->myfile.open(path,ios::in); if (!this->myfile.is_open()){ cout << "Unable to open file"; exit(1); } readNumFilesBlocks(); } /*Constructor for opening a input file without count the files and blocks number * ******When open a file, first the file in the path is deleted and then open again as new file****** */ File::File(char* path){ this->myfile.open(path, std::ofstream::out | std::ofstream::trunc); this->myfile.close(); this->myfile.open(path,ios::out); if (!this->myfile.is_open()){ cout << "Unable to open file"; exit(1); } this->numOfBlocks=0; this->numOfFiles=0; } /*Costructor for empty object - not in use*/ File::File(){this->numOfBlocks=0; this->numOfFiles=0;} /*Destructor - close the opened file*/ File::~File() { this->myfile.close(); } /*The function read the file pointed by 'myfile' and count the number of blocks and number of files * the numbers stored in 'numOfFiles' and 'numOfBlocks' respectively*/ void File::readNumFilesBlocks (){ string line=getLine(); int F_count=0, B_count=0; while (line != "***end***"){ if (line.at(0) == 'F') F_count++; if (line.at(0) == 'B') B_count++; line=getLine(); } this->numOfFiles = F_count; this->numOfBlocks = B_count; } /* The function read one line from the file pointed by 'myfile' and return it * If the file is empty the line will be - '***end***' */ string File::getLine(){ string line; if (getline(this->myfile,line)) return line; else{ line="***end***"; this->myfile.clear(); this->myfile.seekg(0, ios::beg); return line; } } /* The function write one line to the file pointed by 'myfile'*/ void File::writeLine (string line) { if (this->myfile.is_open()) { this->myfile << line+"\n"; } else { cout << "Unable to open file"; exit(1); } }
[ "yoad@ubuntu" ]
yoad@ubuntu
b255534457365b623148771a2ce044d48834a4d9
f9ae382eef2acaee3248c1dd562f242bcee65fb5
/AstralDebu/warp.h
9ffc1f41cc5e7c3c98fdbdc59c4d5b273c589705
[]
no_license
r-kou/AstralDebu
13ce5672fbf7fbea2e99fc4127a8b67c7ef1c895
c3b4a491211df54736a80d893c9cf690eb4e843d
refs/heads/master
2016-09-10T11:08:35.409564
2015-05-09T16:38:31
2015-05-09T16:38:31
29,817,260
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
889
h
#ifndef _WARP_H #define _WARP_H #define WIN32_LEAN_AND_MEAN #include "entity.h" namespace warpNS{ const int IMG_RED_WARP = 48; const int IMG_GREEN_WARP = 49; const int IMG_YELLOW_WARP = 50; const int IMG_EMPTY_WARP = 51; const int IMG_GOAL_BASE = 52; const int IMG_GOAL_START = 53; const int IMG_GOAL_END = 55; const int EDGE_X = 2; const int EDGE_Y = 1; const int EDGE_MAR_X = 0; const int EDGE_MAR_Y = 0; const int EDGE_SLIDE = 12; } class Warp : public Entity{ public: //コンストラクタ Warp(entityNS::ENTITY_TYPE t); //描画 virtual void draw(); //判定の位置を設定 virtual void setEdge(); }; class Goal : public Entity{ public: //コンストラクタ Goal(); //初期化 色を決める bool initialize(Game *game, Texture *t, int i, int j); //描画 virtual void draw(); //判定の位置を設定 virtual void setEdge(); }; #endif
[ "r-kou@ist.osaka-u.ac.jp" ]
r-kou@ist.osaka-u.ac.jp
9868cb3d3b2c11d18dace064fdaecb4c71ff135e
9fad4848e43f4487730185e4f50e05a044f865ab
/src/chrome/browser/ui/views/task_manager_view.cc
e5b87230a69cd7ae12b2e2bc43ddccf03c365e9f
[ "BSD-3-Clause" ]
permissive
dummas2008/chromium
d1b30da64f0630823cb97f58ec82825998dbb93e
82d2e84ce3ed8a00dc26c948219192c3229dfdaa
refs/heads/master
2020-12-31T07:18:45.026190
2016-04-14T03:17:45
2016-04-14T03:17:45
56,194,439
4
0
null
null
null
null
UTF-8
C++
false
false
22,383
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/task_manager/task_manager.h" #include <stddef.h> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/views/new_task_manager_view.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "ui/base/accelerators/accelerator.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/models/simple_menu_model.h" #include "ui/base/models/table_model.h" #include "ui/base/models/table_model_observer.h" #include "ui/events/event_constants.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" #include "ui/views/context_menu_controller.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/controls/table/table_grouper.h" #include "ui/views/controls/table/table_view.h" #include "ui/views/controls/table/table_view_observer.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" #include "ui/views/window/dialog_delegate.h" #if defined(USE_ASH) #include "ash/shelf/shelf_util.h" #include "ash/wm/window_util.h" #include "grit/ash_resources.h" #endif #if defined(OS_WIN) #include "chrome/browser/shell_integration.h" #include "ui/base/win/shell.h" #include "ui/views/win/hwnd_util.h" #endif namespace { //////////////////////////////////////////////////////////////////////////////// // TaskManagerTableModel class //////////////////////////////////////////////////////////////////////////////// class TaskManagerTableModel : public ui::TableModel, public views::TableGrouper, public TaskManagerModelObserver { public: explicit TaskManagerTableModel(TaskManagerModel* model) : model_(model), observer_(NULL) { model_->AddObserver(this); } ~TaskManagerTableModel() override { model_->RemoveObserver(this); } // TableModel overrides: int RowCount() override; base::string16 GetText(int row, int column) override; gfx::ImageSkia GetIcon(int row) override; void SetObserver(ui::TableModelObserver* observer) override; int CompareValues(int row1, int row2, int column_id) override; // TableGrouper overrides: void GetGroupRange(int model_index, views::GroupRange* range) override; // TaskManagerModelObserver overrides: void OnModelChanged() override; void OnItemsChanged(int start, int length) override; void OnItemsAdded(int start, int length) override; void OnItemsRemoved(int start, int length) override; private: TaskManagerModel* model_; ui::TableModelObserver* observer_; DISALLOW_COPY_AND_ASSIGN(TaskManagerTableModel); }; int TaskManagerTableModel::RowCount() { return model_->ResourceCount(); } base::string16 TaskManagerTableModel::GetText(int row, int col_id) { return model_->GetResourceById(row, col_id); } gfx::ImageSkia TaskManagerTableModel::GetIcon(int row) { return model_->GetResourceIcon(row); } void TaskManagerTableModel::SetObserver(ui::TableModelObserver* observer) { observer_ = observer; } int TaskManagerTableModel::CompareValues(int row1, int row2, int column_id) { return model_->CompareValues(row1, row2, column_id); } void TaskManagerTableModel::GetGroupRange(int model_index, views::GroupRange* range) { TaskManagerModel::GroupRange range_pair = model_->GetGroupRangeForResource(model_index); range->start = range_pair.first; range->length = range_pair.second; } void TaskManagerTableModel::OnModelChanged() { if (observer_) observer_->OnModelChanged(); } void TaskManagerTableModel::OnItemsChanged(int start, int length) { if (observer_) observer_->OnItemsChanged(start, length); } void TaskManagerTableModel::OnItemsAdded(int start, int length) { if (observer_) observer_->OnItemsAdded(start, length); } void TaskManagerTableModel::OnItemsRemoved(int start, int length) { if (observer_) observer_->OnItemsRemoved(start, length); } // The Task Manager UI container. class TaskManagerView : public views::ButtonListener, public views::DialogDelegateView, public views::TableViewObserver, public views::ContextMenuController, public ui::SimpleMenuModel::Delegate { public: TaskManagerView(); ~TaskManagerView() override; // Shows the Task Manager window, or re-activates an existing one. static void Show(Browser* browser); // Hides the Task Manager if it is showing. static void Hide(); // views::View: void Layout() override; gfx::Size GetPreferredSize() const override; bool AcceleratorPressed(const ui::Accelerator& accelerator) override; void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override; // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; // views::DialogDelegateView: bool CanResize() const override; bool CanMaximize() const override; bool CanMinimize() const override; bool ExecuteWindowsCommand(int command_id) override; base::string16 GetWindowTitle() const override; std::string GetWindowName() const override; int GetDialogButtons() const override; void WindowClosing() override; bool UseNewStyleForThisDialog() const override; // views::TableViewObserver: void OnSelectionChanged() override; void OnDoubleClick() override; void OnKeyDown(ui::KeyboardCode keycode) override; // views::ContextMenuController: void ShowContextMenuForView(views::View* source, const gfx::Point& point, ui::MenuSourceType source_type) override; // ui::SimpleMenuModel::Delegate: bool IsCommandIdChecked(int id) const override; bool IsCommandIdEnabled(int id) const override; bool GetAcceleratorForCommandId(int command_id, ui::Accelerator* accelerator) override; void ExecuteCommand(int id, int event_flags) override; private: // Creates the child controls. void Init(); // Initializes the state of the always-on-top setting as the window is shown. void InitAlwaysOnTopState(); // Activates the tab associated with the focused row. void ActivateFocusedTab(); // Restores saved always on top state from a previous session. bool GetSavedAlwaysOnTopState(bool* always_on_top) const; views::LabelButton* kill_button_; views::TableView* tab_table_; views::View* tab_table_parent_; TaskManager* task_manager_; TaskManagerModel* model_; // all possible columns, not necessarily visible std::vector<ui::TableColumn> columns_; std::unique_ptr<TaskManagerTableModel> table_model_; // True when the Task Manager window should be shown on top of other windows. bool is_always_on_top_; // We need to own the text of the menu, the Windows API does not copy it. base::string16 always_on_top_menu_text_; // An open Task manager window. There can only be one open at a time. This // is reset to NULL when the window is closed. static TaskManagerView* instance_; std::unique_ptr<views::MenuRunner> menu_runner_; DISALLOW_COPY_AND_ASSIGN(TaskManagerView); }; // static TaskManagerView* TaskManagerView::instance_ = NULL; TaskManagerView::TaskManagerView() : kill_button_(NULL), tab_table_(NULL), tab_table_parent_(NULL), task_manager_(TaskManager::GetInstance()), model_(TaskManager::GetInstance()->model()), is_always_on_top_(false) { Init(); } TaskManagerView::~TaskManagerView() { // Delete child views now, while our table model still exists. RemoveAllChildViews(true); } void TaskManagerView::Init() { table_model_.reset(new TaskManagerTableModel(model_)); // Page column has no header label. columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_TASK_COLUMN, ui::TableColumn::LEFT, -1, 1)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, ui::TableColumn::LEFT, -1, 0)); columns_.back().sortable = true; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PHYSICAL_MEM_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SHARED_MEM_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_CPU_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_NET_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROCESS_ID_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; #if defined(OS_WIN) columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_GDI_HANDLES_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_USER_HANDLES_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; #endif columns_.push_back(ui::TableColumn( IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn( IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_VIDEO_MEMORY_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; columns_.push_back(ui::TableColumn( IDS_TASK_MANAGER_NACL_DEBUG_STUB_PORT_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.push_back( ui::TableColumn(IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; // TODO(port) http://crbug.com/120488 for non-Linux. #if defined(OS_LINUX) columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_IDLE_WAKEUPS_COLUMN, ui::TableColumn::RIGHT, -1, 0)); columns_.back().sortable = true; columns_.back().initial_sort_is_ascending = false; #endif tab_table_ = new views::TableView( table_model_.get(), columns_, views::ICON_AND_TEXT, false); tab_table_->SetGrouper(table_model_.get()); // Hide some columns by default tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SHARED_MEM_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_VIDEO_MEMORY_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_NACL_DEBUG_STUB_PORT_COLUMN, false); tab_table_->SetColumnVisibility( IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_GDI_HANDLES_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_USER_HANDLES_COLUMN, false); tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_IDLE_WAKEUPS_COLUMN, false); tab_table_->SetObserver(this); tab_table_->set_context_menu_controller(this); set_context_menu_controller(this); kill_button_ = new views::LabelButton(this, l10n_util::GetStringUTF16(IDS_TASK_MANAGER_KILL)); kill_button_->SetStyle(views::Button::STYLE_BUTTON); // Makes sure our state is consistent. OnSelectionChanged(); ui::Accelerator ctrl_w(ui::VKEY_W, ui::EF_CONTROL_DOWN); AddAccelerator(ctrl_w); } void TaskManagerView::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { views::DialogDelegateView::ViewHierarchyChanged(details); // Since we want the Kill button to show up in the same visual row as the // close button, which is provided by the framework, we must add it to the // non-client view, which is the parent of this view. Similarly, when we're // removed from the view hierarchy, we must take care to clean up that item. if (details.child == this) { if (details.is_add) { details.parent->AddChildView(kill_button_); tab_table_parent_ = tab_table_->CreateParentIfNecessary(); AddChildView(tab_table_parent_); } else { details.parent->RemoveChildView(kill_button_); } } } void TaskManagerView::Layout() { gfx::Size size = kill_button_->GetPreferredSize(); gfx::Rect parent_bounds = parent()->GetContentsBounds(); const int horizontal_margin = views::kPanelHorizMargin; const int vertical_margin = views::kButtonVEdgeMargin; int x = width() - size.width() - horizontal_margin; int y_buttons = parent_bounds.bottom() - size.height() - vertical_margin; kill_button_->SetBounds(x, y_buttons, size.width(), size.height()); gfx::Rect rect = GetLocalBounds(); rect.Inset(horizontal_margin, views::kPanelVertMargin); rect.Inset(0, 0, 0, kill_button_->height() + views::kUnrelatedControlVerticalSpacing); tab_table_parent_->SetBoundsRect(rect); } gfx::Size TaskManagerView::GetPreferredSize() const { return gfx::Size(460, 270); } bool TaskManagerView::AcceleratorPressed(const ui::Accelerator& accelerator) { DCHECK_EQ(ui::VKEY_W, accelerator.key_code()); DCHECK_EQ(ui::EF_CONTROL_DOWN, accelerator.modifiers()); GetWidget()->Close(); return true; } // static void TaskManagerView::Show(Browser* browser) { if (instance_) { // If there's a Task manager window open already, just activate it. instance_->GetWidget()->Activate(); return; } instance_ = new TaskManagerView(); gfx::NativeWindow window = browser ? browser->window()->GetNativeWindow() : NULL; #if defined(USE_ASH) if (!window) window = ash::wm::GetActiveWindow(); #endif DialogDelegate::CreateDialogWidget(instance_, window, NULL); instance_->InitAlwaysOnTopState(); instance_->model_->StartUpdating(); #if defined(OS_WIN) // Set the app id for the task manager to the app id of its parent browser. If // no parent is specified, the app id will default to that of the initial // process. if (browser) { ui::win::SetAppIdForWindow(shell_integration::GetChromiumModelIdForProfile( browser->profile()->GetPath()), views::HWNDForWidget(instance_->GetWidget())); } #endif instance_->GetWidget()->Show(); // Set the initial focus to the list of tasks. views::FocusManager* focus_manager = instance_->GetFocusManager(); if (focus_manager) focus_manager->SetFocusedView(instance_->tab_table_); #if defined(USE_ASH) gfx::NativeWindow native_window = instance_->GetWidget()->GetNativeWindow(); ash::SetShelfItemDetailsForDialogWindow( native_window, IDR_ASH_SHELF_ICON_TASK_MANAGER, native_window->title()); #endif } // static void TaskManagerView::Hide() { if (instance_) instance_->GetWidget()->Close(); } // ButtonListener implementation. void TaskManagerView::ButtonPressed( views::Button* sender, const ui::Event& event) { typedef ui::ListSelectionModel::SelectedIndices SelectedIndices; DCHECK_EQ(kill_button_, sender); SelectedIndices selection(tab_table_->selection_model().selected_indices()); for (SelectedIndices::const_reverse_iterator i = selection.rbegin(); i != selection.rend(); ++i) { task_manager_->KillProcess(*i); } } // DialogDelegate implementation. bool TaskManagerView::CanResize() const { return true; } bool TaskManagerView::CanMaximize() const { return true; } bool TaskManagerView::CanMinimize() const { return true; } bool TaskManagerView::ExecuteWindowsCommand(int command_id) { return false; } base::string16 TaskManagerView::GetWindowTitle() const { return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_TITLE); } std::string TaskManagerView::GetWindowName() const { return prefs::kTaskManagerWindowPlacement; } int TaskManagerView::GetDialogButtons() const { return ui::DIALOG_BUTTON_NONE; } void TaskManagerView::WindowClosing() { // Now that the window is closed, we can allow a new one to be opened. // (WindowClosing comes in asynchronously from the call to Close() and we // may have already opened a new instance). if (instance_ == this) instance_ = NULL; task_manager_->OnWindowClosed(); } bool TaskManagerView::UseNewStyleForThisDialog() const { return false; } // views::TableViewObserver implementation. void TaskManagerView::OnSelectionChanged() { const ui::ListSelectionModel::SelectedIndices& selection( tab_table_->selection_model().selected_indices()); bool selection_contains_browser_process = false; for (size_t i = 0; i < selection.size(); ++i) { if (task_manager_->IsBrowserProcess(selection[i])) { selection_contains_browser_process = true; break; } } kill_button_->SetEnabled(!selection_contains_browser_process && !selection.empty()); } void TaskManagerView::OnDoubleClick() { ActivateFocusedTab(); } void TaskManagerView::OnKeyDown(ui::KeyboardCode keycode) { if (keycode == ui::VKEY_RETURN) ActivateFocusedTab(); } void TaskManagerView::ShowContextMenuForView(views::View* source, const gfx::Point& point, ui::MenuSourceType source_type) { ui::SimpleMenuModel menu_model(this); for (std::vector<ui::TableColumn>::iterator i(columns_.begin()); i != columns_.end(); ++i) { menu_model.AddCheckItem(i->id, l10n_util::GetStringUTF16(i->id)); } menu_runner_.reset( new views::MenuRunner(&menu_model, views::MenuRunner::CONTEXT_MENU)); if (menu_runner_->RunMenuAt(GetWidget(), NULL, gfx::Rect(point, gfx::Size()), views::MENU_ANCHOR_TOPLEFT, source_type) == views::MenuRunner::MENU_DELETED) { return; } } bool TaskManagerView::IsCommandIdChecked(int id) const { return tab_table_->IsColumnVisible(id); } bool TaskManagerView::IsCommandIdEnabled(int id) const { return true; } bool TaskManagerView::GetAcceleratorForCommandId( int command_id, ui::Accelerator* accelerator) { return false; } void TaskManagerView::ExecuteCommand(int id, int event_flags) { tab_table_->SetColumnVisibility(id, !tab_table_->IsColumnVisible(id)); } void TaskManagerView::InitAlwaysOnTopState() { is_always_on_top_ = false; if (GetSavedAlwaysOnTopState(&is_always_on_top_)) GetWidget()->SetAlwaysOnTop(is_always_on_top_); } void TaskManagerView::ActivateFocusedTab() { const int active_row = tab_table_->selection_model().active(); if (active_row != -1) task_manager_->ActivateProcess(active_row); } bool TaskManagerView::GetSavedAlwaysOnTopState(bool* always_on_top) const { if (!g_browser_process->local_state()) return false; const base::DictionaryValue* dictionary = g_browser_process->local_state()->GetDictionary(GetWindowName()); return dictionary && dictionary->GetBoolean("always_on_top", always_on_top) && always_on_top; } } // namespace namespace chrome { // Declared in browser_dialogs.h so others don't need to depend on our header. void ShowTaskManager(Browser* browser) { if (switches::NewTaskManagerEnabled()) { task_management::NewTaskManagerView::Show(browser); return; } TaskManagerView::Show(browser); } void HideTaskManager() { if (switches::NewTaskManagerEnabled()) { task_management::NewTaskManagerView::Hide(); return; } TaskManagerView::Hide(); } } // namespace chrome
[ "dummas@163.com" ]
dummas@163.com
38269c60111c6e3f3a4ff9852a952131585feadb
f0121f493a149c64e2abb96b98667384f522d01e
/platforms/include/baka_gl/buffer.h
2b566374beed01a3834e8234b0e6e7b0c0c9a351
[]
no_license
lahoising78/BakaEngine
770d7b17560de6c8a99be035132e388300dfd23a
dbd6a2879897c1769f06f764bd0dedff431c4392
refs/heads/master
2023-02-11T07:27:35.948373
2020-11-27T00:15:03
2020-11-27T00:15:03
261,653,160
0
0
null
null
null
null
UTF-8
C++
false
false
886
h
#ifndef _BAKA_GL_BUFFER_H_ #define _BAKA_GL_BUFFER_H_ #include <cstdint> #include <baka_buffer.h> namespace baka { namespace gl { class VertexBuffer : public baka::VertexBuffer { public: VertexBuffer(const void *data, std::size_t size); ~VertexBuffer(); void Bind() const override; void Unbind() const override; public: unsigned int GetBufferId() { return bufferId; } private: unsigned int bufferId; }; class IndexBuffer : public baka::IndexBuffer { public: IndexBuffer(std::uint32_t *data, std::uint32_t count); ~IndexBuffer(); void Bind() const override; void Unbind() const override; std::uint32_t GetCount() const override { return indexCount; } public: unsigned int GetBufferId() { return bufferId; } private: std::uint32_t indexCount; unsigned int bufferId; }; } // namespace gl } // namespace baka #endif
[ "lhc4@njit.edu" ]
lhc4@njit.edu
f5a364b6fd7378ad90e505320187d2af3ecd048d
b1594a544953555fee8252c53e9d99a4503cc786
/srm/314/GrasslandFencer.cpp
6fd4f2320cc2298dc798063ae932a0e8aaf5e5c8
[]
no_license
tatsukawa/contest
ea366d7d9ebcde8ff83099ca89d37cf9812d17d3
c42c4c6cc0536e4ebde9db1e865cd357e8f1cf07
refs/heads/master
2021-05-02T06:57:50.041043
2017-07-20T19:35:28
2017-07-20T19:35:28
12,034,439
0
0
null
null
null
null
UTF-8
C++
false
false
8,381
cpp
#include <vector> #include <map> #include <set> #include <stack> #include <queue> #include <algorithm> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <string> #include <cstring> using namespace std; class GrasslandFencer { public: int n; vector<int> fences; map<int, double> memo; double calcArea(int a, int b, int c) { if(a + b <= c) return 0; double p = 1.0 * (a + b + c) / 2; return sqrt(p * (p - a) * (p - b) * (p - c)); } double dfs(int S) { if(memo[S]) return memo[S]; double res = 0; for(int i = 0; i < n; i++) if(!(1 & (S >> i))) for(int j = i + 1; j < n; j++) if(!(1 & (S >> j))) for(int k = j + 1; k < n; k++) if(!(1 & (S >> k))) { res = max(res, dfs(S | (1 << i) | (1 << j) | (1 << k)) + calcArea(fences[i], fences[j], fences[k])); } return memo[S] = res; } double maximalFencedArea(vector <int> f) { n = f.size(); fences = f; return dfs(0); } }; // BEGIN CUT HERE namespace moj_harness { int run_test_case(int); void run_test(int casenum = -1, bool quiet = false) { if (casenum != -1) { if (run_test_case(casenum) == -1 && !quiet) { cerr << "Illegal input! Test case " << casenum << " does not exist." << endl; } return; } int correct = 0, total = 0; for (int i=0;; ++i) { int x = run_test_case(i); if (x == -1) { if (i >= 100) break; continue; } correct += x; ++total; } if (total == 0) { cerr << "No test cases run." << endl; } else if (correct < total) { cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl; } else { cerr << "All " << total << " tests passed!" << endl; } } static const double MAX_DOUBLE_ERROR = 1e-9; static bool topcoder_fequ(double expected, double result) { if (isnan(expected)) { return isnan(result); } else if (isinf(expected)) { if (expected > 0) { return result > 0 && isinf(result); } else { return result < 0 && isinf(result); } } else if (isnan(result) || isinf(result)) { return false; } else if (fabs(result - expected) < MAX_DOUBLE_ERROR) { return true; } else { double mmin = min(expected * (1.0 - MAX_DOUBLE_ERROR), expected * (1.0 + MAX_DOUBLE_ERROR)); double mmax = max(expected * (1.0 - MAX_DOUBLE_ERROR), expected * (1.0 + MAX_DOUBLE_ERROR)); return result > mmin && result < mmax; } } double moj_relative_error(double expected, double result) { if (isnan(expected) || isinf(expected) || isnan(result) || isinf(result) || expected == 0) return 0; return fabs(result-expected) / fabs(expected); } int verify_case(int casenum, const double &expected, const double &received, clock_t elapsed) { cerr << "Example " << casenum << "... "; string verdict; vector<string> info; char buf[100]; if (elapsed > CLOCKS_PER_SEC / 200) { sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC)); info.push_back(buf); } if (topcoder_fequ(expected, received)) { verdict = "PASSED"; double rerr = moj_relative_error(expected, received); if (rerr > 0) { sprintf(buf, "relative error %.3e", rerr); info.push_back(buf); } } else { verdict = "FAILED"; } cerr << verdict; if (!info.empty()) { cerr << " ("; for (int i=0; i<(int)info.size(); ++i) { if (i > 0) cerr << ", "; cerr << info[i]; } cerr << ")"; } cerr << endl; if (verdict == "FAILED") { cerr << " Expected: " << expected << endl; cerr << " Received: " << received << endl; } return verdict == "PASSED"; } int run_test_case(int casenum__) { switch (casenum__) { case 0: { int fences[] = {3,4,5,6,7,8,9}; double expected__ = 36.754383146489694; clock_t start__ = clock(); double received__ = GrasslandFencer().maximalFencedArea(vector <int>(fences, fences + (sizeof fences / sizeof fences[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } case 1: { int fences[] = {1,2,4,8}; double expected__ = 0.0; clock_t start__ = clock(); double received__ = GrasslandFencer().maximalFencedArea(vector <int>(fences, fences + (sizeof fences / sizeof fences[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } case 2: { int fences[] = {7,4,4,4}; double expected__ = 6.928203230275509; clock_t start__ = clock(); double received__ = GrasslandFencer().maximalFencedArea(vector <int>(fences, fences + (sizeof fences / sizeof fences[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } case 3: { int fences[] = {21,72,15,55,16,44,54,63,69,35,75,69,76,70,50,81}; double expected__ = 7512.322360676162; clock_t start__ = clock(); double received__ = GrasslandFencer().maximalFencedArea(vector <int>(fences, fences + (sizeof fences / sizeof fences[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); } // custom cases /* case 4: { int fences[] = ; double expected__ = ; clock_t start__ = clock(); double received__ = GrasslandFencer().maximalFencedArea(vector <int>(fences, fences + (sizeof fences / sizeof fences[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); }*/ /* case 5: { int fences[] = ; double expected__ = ; clock_t start__ = clock(); double received__ = GrasslandFencer().maximalFencedArea(vector <int>(fences, fences + (sizeof fences / sizeof fences[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); }*/ /* case 6: { int fences[] = ; double expected__ = ; clock_t start__ = clock(); double received__ = GrasslandFencer().maximalFencedArea(vector <int>(fences, fences + (sizeof fences / sizeof fences[0]))); return verify_case(casenum__, expected__, received__, clock()-start__); }*/ default: return -1; } } } int main(int argc, char *argv[]) { if (argc == 1) { moj_harness::run_test(); } else { for (int i=1; i<argc; ++i) moj_harness::run_test(atoi(argv[i])); } } // END CUT HERE
[ "ts.tatsukawa@gmail.com" ]
ts.tatsukawa@gmail.com
1cb419497ceb2b8edbd1c22e1a94da85a0f705cd
c7281646642483b075156bc3329e1e13589e1e0d
/labs/lab2/lab2/basketball.cpp
e140ce22b386ed3f5d769fcddc868bcdbd7f4096
[]
no_license
asjadathick/CSCI204
0202ed5e107c4114524294a3b6b25c87c5ebc263
e46047c312e524370c2c680452aa50f1366eb3a1
refs/heads/master
2021-01-20T03:35:01.544847
2017-04-27T05:29:15
2017-04-27T05:29:15
89,559,146
0
0
null
null
null
null
UTF-8
C++
false
false
505
cpp
// // main.cpp // lab2 // // Created by mama158, Asjad Athick on 13/03/2016. // Student: 4970512 // Copyright © 2016 Asjad Athick. All rights reserved. // #include <iostream> #include "competition.h" using namespace std; int main(int argc, const char * argv[]) { cout << "Input a basketball competition results' file name: "; char fileName[200]; cin>>fileName; Result result; result.loadData(fileName); result.sortData(); result.printData(); return 0; }
[ "asjadathick@gmail.com" ]
asjadathick@gmail.com
0e596f67a41ca9c532d1183c20235b6cb9fb4f6c
83146f64fa90d503733a8c59672d42afc4306ce5
/2019RobotTest/src/main/include/commands/Climber/WaitTrigger.h
1d5d20e54381abad4723d2a1318897c7cb5f2772
[]
no_license
FRC-4476-WAFFLES/Robot2019
76b55e28122df65aa0802cef502db8af9c0b107c
4cd02267409014df494ec7ec15e4b9b0bdd06e44
refs/heads/master
2022-04-04T18:57:36.137275
2020-02-01T23:41:45
2020-02-01T23:41:45
168,863,336
0
0
null
null
null
null
UTF-8
C++
false
false
748
h
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #pragma once #include <frc/commands/Command.h> class WaitTrigger : public frc::Command { public: WaitTrigger(); void Initialize() override; void Execute() override; bool IsFinished() override; void End() override; void Interrupted() override; };
[ "dmiester1965@gmail.com" ]
dmiester1965@gmail.com
e2f28ad6f8be2de9eeaeea0c19f28c672f592fa7
beb99ce64c80370c0df3812042db5269a66b9e9c
/Assign06/assign6.cpp
37f6579de57ea99a864f54e923ad1ad62725b3e7
[]
no_license
madhuis/OOProgram_in_Cplusplus
b60638e621a8f6e0648ad57cae7074b1575f0e2a
8d6553266b8e3079d7cb18d4ad2626825ec2a9ba
refs/heads/master
2020-12-23T11:34:14.387445
2016-11-11T17:46:41
2016-11-11T17:46:41
73,496,881
1
0
null
null
null
null
UTF-8
C++
false
false
5,952
cpp
/********************************************************************* PROGRAM: CSCI 241 Assignment 6 PROGRAMMER: ISHAN MADHU LOGON ID: z1763923 DUE DATE: April 7, 2015 FUNCTION: This program will test the functionality of the Queue class. *********************************************************************/ #include <iostream> #include <stdexcept> #include "Queue.h" using std::cout; using std::endl; using std::underflow_error; int main() { cout << "Testing default constructor\n\n"; Queue q1; cout << "q1: " << q1 << endl; cout << "q1 size: " << q1.size() << endl; cout << "q1 capacity: " << q1.capacity() << endl; cout << "q1 is " << ((q1.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "Testing push()\n\n"; for (int i = 10; i < 80; i+= 10) q1.push(i); cout << "q1: " << q1 << endl; cout << "q1 size: " << q1.size() << endl; cout << "q1 capacity: " << q1.capacity() << endl; cout << "q1 is " << ((q1.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "Testing pop()\n\n"; for (int i = 0; i < 3; ++i) { q1.pop(); } cout << "q1: " << q1 << endl; cout << "q1 size: " << q1.size() << endl; cout << "q1 capacity: " << q1.capacity() << endl; cout << "q1 is " << ((q1.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "Testing wrap-around on push()\n\n"; for (int i = 2; i <= 8; i+= 2) q1.push(i); cout << "q1: " << q1 << endl; cout << "q1 size: " << q1.size() << endl; cout << "q1 capacity: " << q1.capacity() << endl; cout << "q1 is " << ((q1.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "Testing wrap-around on pop()\n\n"; for (int i = 0; i < 6; ++i) { q1.pop(); } cout << "q1: " << q1 << endl; cout << "q1 size: " << q1.size() << endl; cout << "q1 capacity: " << q1.capacity() << endl; cout << "q1 is " << ((q1.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "Testing queue resize on push()\n\n"; for (int i = 5; i < 70; i+= 5) q1.push(i); cout << "q1: " << q1 << endl; cout << "q1 size: " << q1.size() << endl; cout << "q1 capacity: " << q1.capacity() << endl; cout << "q1 is " << ((q1.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "Testing copy constructor()\n\n"; Queue q2 = q1; cout << "q1: " << q1 << endl; cout << "q1 size: " << q1.size() << endl; cout << "q1 capacity: " << q1.capacity() << endl; cout << "q1 is " << ((q1.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "q2: " << q2 << endl; cout << "q2 size: " << q2.size() << endl; cout << "q2 capacity: " << q2.capacity() << endl; cout << "q2 is " << ((q2.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "Testing front() and back()\n\n"; cout << "Front item of q1: " << q1.front() << endl; cout << "Front item of q2: " << q2.front() << endl << endl; cout << "Rear item of q1: " << q1.back() << endl; cout << "Rear item of q2: " << q2.back() << endl << endl; cout << "q1: " << q1 << endl; cout << "q1 size: " << q1.size() << endl; cout << "q1 capacity: " << q1.capacity() << endl; cout << "q1 is " << ((q1.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "q2: " << q2 << endl; cout << "q2 size: " << q2.size() << endl; cout << "q2 capacity: " << q2.capacity() << endl; cout << "q2 is " << ((q2.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "Testing pop() to empty\n\n"; while (!q1.empty()) { cout << q1.front() << ' '; q1.pop(); } cout << endl; cout << "q1 size: " << q1.size() << endl; cout << "q1 capacity: " << q1.capacity() << endl; cout << "q1 is " << ((q1.empty()) ? "empty\n" : "not empty\n"); cout << endl; cout << "Testing assignment operator\n\n"; Queue q3; q3 = q2; cout << "q2 (size " << q2.size() << "): " << q2 << endl; cout << "q3 (size " << q3.size() << "): " << q3 << endl << endl; cout << "Testing clear()\n\n"; q2.clear(); cout << "q2 (size " << q2.size() << "): " << q2 << endl; cout << "q3 (size " << q3.size() << "): " << q3 << endl << endl; cout << "Testing assignment to self and swap\n\n"; q3 = q3; q2 = q3; q3.clear(); cout << "q2 (size " << q2.size() << "): " << q2 << endl; cout << "q3 (size " << q3.size() << "): " << q3 << endl << endl; cout << "Testing chained assignment\n\n"; Queue q4; q4 = q3 = q2; cout << "q2 (size " << q2.size() << "): " << q2 << endl; cout << "q3 (size " << q3.size() << "): " << q3 << endl; cout << "q4 (size " << q4.size() << "): " << q4 << endl << endl; cout << "Testing const correctness\n\n"; const Queue& r4 = q4; cout << "q4: " << r4 << endl; cout << "q4 size: " << r4.size() << endl; cout << "q4 capacity: " << r4.capacity() << endl; cout << "q4 is " << ((r4.empty()) ? "empty\n" : "not empty\n"); cout << "Front item of q4: " << r4.front() << endl; cout << "Rear item of q4: " << r4.back() << endl << endl; q1 = r4; cout << "q1: " << q1 << endl; cout << "q1 size: " << q1.size() << endl; cout << "q1 is " << ((q1.empty()) ? "empty\n" : "not empty\n"); cout << endl; q1.clear(); cout << "Testing front() with empty queue\n\n"; try { cout << q1.front() << endl; } catch (underflow_error e) { cout << "Caught "<< e.what() << endl << endl; } cout << "Testing back() with empty queue\n\n"; try { cout << q1.back() << endl; } catch (underflow_error e) { cout << "Caught "<< e.what() << endl << endl; } cout << "Testing pop() with empty queue\n\n"; try { q1.pop(); } catch (underflow_error e) { cout << "Caught "<< e.what() << endl; } return 0; }
[ "imadhu2991@gmail.com" ]
imadhu2991@gmail.com
6ac29effbc0beb0dee1a4728a989a292eaaa6dc7
da9c61e7de24b5510dcea4ef35493b596c6b8746
/Add_Two_Numbers.cpp
b41aa2d078f4f29b345798bd46ac21890464dafb
[]
no_license
Bupt-Wangfang/leetcode
f64a6bc8997c5afceb3d1dac9d18de429bce4a13
ce856878c705e102352964525e58868d012816f2
refs/heads/master
2020-05-14T13:05:07.233024
2019-05-22T10:09:53
2019-05-22T10:09:53
181,805,327
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* head=new ListNode(-1); int carried=0; ListNode *p1=l1, *p2=l2; ListNode* cur=head; while(p1 || p2){ int num1=p1 ? p1->val:0; int num2=p2 ? p2->val:0; cur->next=new ListNode((num1+num2+carried)%10); carried=(num1+num2+carried)/10; cur=cur->next; p1=p1?p1->next:NULL; p2=p2?p2->next:NULL; } cur->next=carried ? new ListNode(1):NULL; ListNode* res=head->next; delete head; return res; } };
[ "buptwfang@163.com" ]
buptwfang@163.com
40383aecc98b7d96d13c80d0c15c18630cee0b56
3ed05581d6fb5044115448e40cee43a6136daa27
/src/lv5/jserror.cc
b057a85782e32169a1eba5ce2d9b0d6829c16b3c
[]
no_license
rwaldron/iv
acb0addbcb682772d437ff738e9555147a108882
40bdb765d82d8e6fa09ffd39f0869f275d238a5a
refs/heads/master
2021-01-17T21:46:42.421227
2010-12-03T16:04:04
2010-12-03T16:04:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,634
cc
#include "jserror.h" #include "jsval.h" #include "context.h" namespace iv { namespace lv5 { JSError::JSError(Context* ctx, Error::Code code, JSString* str) : code_(code) { DefineOwnProperty(ctx, ctx->Intern("message"), DataDescriptor(str, PropertyDescriptor::WRITABLE), false, ctx->error()); } JSError* JSError::New(Context* ctx, Error::Code code, JSString* str) { JSError* const error = new JSError(ctx, code, str); const Class& cls = ctx->Cls("Error"); error->set_cls(cls.name); error->set_prototype(cls.prototype); return error; } JSVal JSError::Detail(Context* ctx, const Error* error) { assert(error && (error->code() != Error::Normal)); switch (error->code()) { case Error::Native: return JSError::NewNativeError( ctx, JSString::NewAsciiString(ctx, error->detail())); case Error::Eval: return JSError::NewEvalError( ctx, JSString::NewAsciiString(ctx, error->detail())); case Error::Range: return JSError::NewRangeError( ctx, JSString::NewAsciiString(ctx, error->detail())); case Error::Reference: return JSError::NewReferenceError( ctx, JSString::NewAsciiString(ctx, error->detail())); case Error::Syntax: return JSError::NewSyntaxError( ctx, JSString::NewAsciiString(ctx, error->detail())); case Error::Type: return JSError::NewTypeError( ctx, JSString::NewAsciiString(ctx, error->detail())); case Error::URI: return JSError::NewURIError( ctx, JSString::NewAsciiString(ctx, error->detail())); case Error::User: return error->value(); default: UNREACHABLE(); return JSUndefined; // make compiler happy }; } JSError* JSError::NewNativeError(Context* ctx, JSString* str) { JSError* const error = new JSError(ctx, Error::Native, str); const Class& cls = ctx->Cls("NativeError"); error->set_cls(cls.name); error->set_prototype(cls.prototype); return error; } JSError* JSError::NewEvalError(Context* ctx, JSString* str) { JSError* const error = new JSError(ctx, Error::Eval, str); const Class& cls = ctx->Cls("EvalError"); error->set_cls(cls.name); error->set_prototype(cls.prototype); return error; } JSError* JSError::NewRangeError(Context* ctx, JSString* str) { JSError* const error = new JSError(ctx, Error::Range, str); const Class& cls = ctx->Cls("RangeError"); error->set_cls(cls.name); error->set_prototype(cls.prototype); return error; } JSError* JSError::NewReferenceError(Context* ctx, JSString* str) { JSError* const error = new JSError(ctx, Error::Reference, str); const Class& cls = ctx->Cls("ReferenceError"); error->set_cls(cls.name); error->set_prototype(cls.prototype); return error; } JSError* JSError::NewSyntaxError(Context* ctx, JSString* str) { JSError* const error = new JSError(ctx, Error::Syntax, str); const Class& cls = ctx->Cls("SyntaxError"); error->set_cls(cls.name); error->set_prototype(cls.prototype); return error; } JSError* JSError::NewTypeError(Context* ctx, JSString* str) { JSError* const error = new JSError(ctx, Error::Type, str); const Class& cls = ctx->Cls("TypeError"); error->set_cls(cls.name); error->set_prototype(cls.prototype); return error; } JSError* JSError::NewURIError(Context* ctx, JSString* str) { JSError* const error = new JSError(ctx, Error::URI, str); const Class& cls = ctx->Cls("URIError"); error->set_cls(cls.name); error->set_prototype(cls.prototype); return error; } } } // namespace iv::lv5
[ "utatane.tea@gmail.com" ]
utatane.tea@gmail.com
4f039154a88f2000be435984fcc4b3d97c1c1cda
9bd04baa1432d13258f10327ca39f5c71ec39090
/base.h
bf942c6d7d5fcf31c01cfc01ace2b74c3f9eebe0
[]
no_license
AlexChang/SchemeCalculator
4712aa8be657abf196126b7b3874caec6e90ba5b
80407917e59e14868b1c542c474d6df82360a4dc
refs/heads/master
2021-01-20T12:21:09.259674
2017-02-21T07:33:10
2017-02-21T07:33:10
82,650,065
0
0
null
null
null
null
UTF-8
C++
false
false
500
h
// base.h #pragma once #include <iostream> class Base{ public: enum{ BOOLEAN = 1, NUMBER = 2, CHAR = 3, STRING = 4 } btype_; Base(){} virtual ~Base(){} virtual void print(std::ostream& o = std::cout) const = 0; virtual Base *judge_integer() = 0; virtual Base *judge_rational() = 0; virtual Base *judge_real() = 0; virtual Base *judge_complex() = 0; virtual Base *judge_number() = 0; virtual Base *judge_char() = 0; virtual Base *judge_string() = 0; };
[ "zfmedisonxfmt@126.com" ]
zfmedisonxfmt@126.com
d65a0db837977d0e8a102d6dc7036718dd912884
0fb25f28a326bd83f1f96edd3e5a025e9cbdb435
/aoc_4_1.cpp
cdf2f301582caac720e4b092189d5e1dc8d03c2e
[]
no_license
Ruxandra985/aoc-2019
53d2aa3752c10c8a3cc0e31f3668de423391bb29
03d950b416b36a459b2e9be298a4e2e77a67ade8
refs/heads/master
2020-09-26T20:53:48.836638
2019-12-26T18:39:13
2019-12-26T18:39:13
226,341,896
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
cpp
#include <cstdio> using namespace std; int check (int x){ int ok , curr , ant , egl = 1 , stop = 0,ok2; ok2 = ok = 0; while (x){ curr = x % 10; if (ok){ if (curr == ant) egl++; else { if (egl == 2) ok2 = 1; egl = 1; } if (curr > ant) stop = 1; } ok = 1; ant = curr; x/=10; } if (egl == 2) ok2 = 1; /*while (x){ curr = x % 10; if (ok){ if (curr == ant) egl = 1; if (curr > ant) stop = 1; } ok = 1; ant = curr; x/=10; }*/ if (stop || !ok2) return 0; return 1; } int main() { FILE *fin = fopen ("a.in","r"); FILE *fout = fopen ("a.out","w"); int a , b , i , sol; fscanf (fin,"%d%d",&a,&b); sol = 0; for (i=a;i<=b;i++){ sol = sol + check(i); } fprintf (fout,"%d",sol); return 0; }
[ "noreply@github.com" ]
noreply@github.com
cfe07c0b9e71c9c13c83ad2714a00763a5074da3
60c16c0ff9c60bd4e5462da6c18bb65c40da7ef3
/CSLP_work3_Cpp/Golomb.cpp
f5d2952e7d3d6500e79b80b96c1aee87c65b30ef
[]
no_license
ChicoUA/CSLP_work3
923d8ab2bb940c59fe9f7237602d7cb04569483a
e1fff3fc4e338e8ac58deb1c832fd3e28a4608d5
refs/heads/master
2020-09-14T18:31:03.823169
2020-01-07T12:17:31
2020-01-07T12:17:31
223,214,568
0
0
null
null
null
null
UTF-8
C++
false
false
1,886
cpp
/* * Golomb.cpp * * Created on: 21 Nov 2019 * Author: ghost */ #include "Golomb.h" #include <functional> #include <iostream> #include <cmath> #include <bitset> #include <string> using namespace std; Golomb::Golomb(int m1) { Bitstream bt; m = m1; } Bitstream Golomb::encode(int n){ int r = n % getM(); int q = n / getM(); for(int i = 0; i < q; i++){ bt.writeOneBit(1); } bt.writeOneBit(0); bt.writeNBits(r, getM()); return bt; } int Golomb::decode(){ int k = ceil(log2(getM())); int t = pow(2, k) - getM(); int r = 0; int q = 0; while(true){ //cout << "here: " << bt.getBitstream() << endl; char bit = bt.readOneBit(); if(bit == '0'){ break; } q += 1; } /* cout << q << "\n"; cout << k << "\n"; */ std::string temp = bt.readNBits(0, k - 1); r = std::stoi(temp, nullptr, 2); /* cout << r << "\n"; cout << t << "\n"; */ if(r < t){ return q * getM() + r; } else{ r = r * 2 + (int)bt.readOneBit() - 48; // 48 vem de 0 no tabela ascii ser 48 return q * getM() + r - t; } } Bitstream& Golomb::getBitstream(){ return bt; } int Golomb::getM(){ return m; } int main(){ Golomb g(5); cout << g.encode(15).getBitstream() << "\n"; cout << g.encode(4).getBitstream() << "\n"; cout << g.encode(16).getBitstream() << "\n"; cout << g.encode(12).getBitstream() << "\n"; if(g.getBitstream().getBitstream().length() > 0){ g.getBitstream().lastByteLength = g.getBitstream().getBitstream().length(); g.getBitstream().writeToFile(); } else g.getBitstream().lastByteLength = 8; g.getBitstream().readFile(); cout << g.decode() << "\n"; cout << "---------------------------------------" << endl; cout << g.decode() << "\n"; cout << "---------------------------------------" << endl; cout << g.decode() << "\n"; cout << "---------------------------------------" << endl; cout << g.decode() << "\n"; }
[ "franciscojesus@ua.pt" ]
franciscojesus@ua.pt
20c536e35b68335f2dab19935a7c6bd0de3a1c58
0841c948188711d194835bb19cf0b4dae04a5695
/mds/sources/thelib/src/proxy/proxycenterprocess.cpp
86a7113465ac15337731cf10109f50afb17f052b
[]
no_license
gjhbus/sh_project
0cfd311b7c0e167e098bc4ec010822f1af2d0289
1d4d7df4e92cff93aba9d28226d3dbce71639ed6
refs/heads/master
2020-06-15T16:11:33.335499
2016-06-15T03:41:22
2016-06-15T03:41:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,485
cpp
#include "netio/netio.h" #include "md/md.h" #include "proxy/proxycenterprocess.h" #include "proxy/proxymanager.h" extern class ProxyManager *proxyManager; ProxyCenterProcess::ProxyCenterProcess() : CenterProcess() { end_type_ = MD_END_PROXY; } ProxyCenterProcess::~ProxyCenterProcess() { } bool ProxyCenterProcess::SignalInputData(int32_t recvAmount) { uint8_t *buffer = GETIBPOINTER(input_buffer_); int32_t size = GETAVAILABLEBYTESCOUNT(input_buffer_); uint32_t op; while(4 <= size) { if (!head_.length) { head_.length = BinaryParser::DecodeInt32(buffer); if ( 0 == head_.length ) { FATAL("[%s] length of protocol is 0 in ProxyCenterProcess::SignalInputData", STR(getLocalTimeString("%Y-%m-%d %H:%M:%S", time(0)))); return false; } } if (head_.length > size) return true; parser_.SetDecode(buffer); parser_.DecodeBigHead(&head_); if (MD_MARK != head_.mark) { FATAL("Check mark 0x%X failed, size:%u, length:%u in ProxyCenterProcess::SignalInputData", head_.mark, size, head_.length); return false; } op = MD_PROC_SERIAL(head_.opType); if (MD_CENTER_JOIN == op) { key_ = parser_.DecodeString(); INFO("Join successfully KEY: %s", STR(key_)); } else if ( MD_CENTER_AND_PROXY_TRIMMDS == op ) { if ("" == key_) { WARN("No join center, so it don't trim mds"); } else { std::string old_track_info = parser_.DecodeBigString(); std::string new_track_info = parser_.DecodeBigString(); proxyManager->SetProxyCmd(op, old_track_info, new_track_info); } } else if ( MD_CENTER_AND_PROXY_ADJUSTMDS == op ) { if ("" == key_) { WARN("No join center, so it don't adjust mds"); } else { std::string track_info = parser_.DecodeBigString(); proxyManager->SetProxyCmd(op, track_info); } } else if (MD_CENTER_AND_PROXY_RESETMDS == op) { if ("" == key_) { WARN("No join center, so it don't reset mds"); } else { uint8_t result = parser_.DecodeInt8(); std::string tmp = "1"; if ( 0 == result ) tmp = "0"; proxyManager->SetProxyCmd(op, tmp); } } else if (MD_CENTER_AND_PROXY_CLEARMDS == op) { if ("" == key_) { WARN("No join center, so it don't clear mds"); } else { proxyManager->SetProxyCmd(op); } } else if (MD_CENTER_AND_PROXY_CHECKPOINT == op) { if ("" == key_) { WARN("No join center, so it don't checkpoint"); } else { proxyManager->Checkpoint(); } } else { WARN("Unknow %s", STR(key_)); } input_buffer_.Ignore(head_.length); buffer += head_.length; size -= head_.length; head_.length = 0; } return true; } void ProxyCenterProcess::ConnectData() { ((TCPCarrier*)io_handler_)->SetFlag(1); BigMDProcHead head; head.mark = MD_MARK; head.opType = MD_PROC_PACKAGE(MD_REQUEST, end_type_, MD_END_CENTER, MD_CENTER_JOIN); head.reserved = MD_RESERVED; parser_.SetBigEncode(); parser_.EncodeBigHead(&head); parser_.EncodeInt32(getpid()); // pid if ( proxyManager->IsR() ) parser_.EncodeInt8(0); else parser_.EncodeInt8(1); std::string data, tmp_data; proxyManager->GetJoinData(data, tmp_data); if ( "" == data) data = "E"; if ( "" == tmp_data) tmp_data = "E"; parser_.EncodeBigString(data); parser_.EncodeBigString(tmp_data); BinaryParser::BigAVal *pval = parser_.SetBigLength(); output_buffer_.ReadFromBuffer(pval->val, pval->len); io_handler_->GetManager()->EnableWriteData(io_handler_); } void ProxyCenterProcess::SendHeart() { if ("" == key_ || !io_handler_) return; INFO("Send heart for center KEY: %s", STR(key_)); BigMDProcHead head; head.mark = MD_MARK; head.opType = MD_PROC_PACKAGE(MD_REQUEST, end_type_, MD_END_CENTER, MD_HEART); head.reserved = MD_RESERVED; parser_.SetBigEncode(); parser_.EncodeBigHead(&head); parser_.EncodeInt8((uint8_t)1); parser_.EncodeString(key_); BinaryParser::BigAVal *pval = parser_.SetBigLength(); output_buffer_.ReadFromBuffer(pval->val, pval->len); io_handler_->GetManager()->EnableWriteData(io_handler_); }
[ "greatmiffa@gmail.com" ]
greatmiffa@gmail.com
ed28560d4c073c1a8a5939d64632aefcc301720c
e39e3a4b4dc3f9abf8c9c25d247e2c43085f399e
/chapter1/practise1_12/practise1_12/practise1_12.cpp
205793f02ba6366593396a8ab23c4670817b21e8
[]
no_license
dc-maggic/978-7-121-15535-2
fc52a91b3dd58ccede74f102eb31eb69a6a3583a
f3bbc221f4bc52241398bc6529c8e6e9dac2ab97
refs/heads/master
2021-10-07T09:40:53.387393
2018-12-04T14:29:04
2018-12-04T14:29:04
155,890,380
0
0
null
null
null
null
UTF-8
C++
false
false
95
cpp
#include <iostream> int main() { int sum = 0; for (int i = -100; i <= 100; ++i) sum += i; }
[ "dc-maggic@outlook.com" ]
dc-maggic@outlook.com
7b9e0c597bb6c9931bae35601796e0592eb23f97
9ffa99d905671834a87362c4e4e62b1bf58dfe08
/testSnake.cpp
8cc54e4c6baae1ff36a7ef526d8f0dc5ec0b3c7b
[]
no_license
coderlongren/someAlgorithms
2af6ce98236b082dc9529333b08c82052fff924d
97a34e26d1f47774384cd7440353ae673c49e4cc
refs/heads/master
2021-06-29T19:57:31.678251
2017-09-19T11:05:46
2017-09-19T11:05:46
59,566,030
0
0
null
null
null
null
GB18030
C++
false
false
5,243
cpp
#include <stdio.h> #include <conio.h> #include <stdlib.h> #include <time.h> #include <windows.h> const int W = 52;//地图的宽度 const int H = 22;//地图的高度 char map[22][52];//地图的大小 char key;//保存用户操作时候 输入的键 int direct = 4;//最开始 蛇运动的方向向右 ,上1H 下 2P 左 3K 右 4M int food[2] = {9,11};//food[0]是食物的横坐标 food[1]是 纵坐标 int head;//蛇的长度 int snake[900][3];//蛇的所有坐标点 以及蛇的身体:snake[0] = 0 蛇头:snake[0] = 1 void init(char map[22][52],int snake[900][3]);//游戏开始的时候初始化 void makeMap(char map[22][52],int snake[900][3],int food[2]);//根据move() 之后的蛇和生成的food食物更改map void move(int snake[900][3],int direct);//让蛇移动 void showView(char map[22][52]);//绘制map int ifEat(int head,int food[2]);//判断食物是否被吃掉 int ifRepeat(int snake[900][3],int x,int y);//判断生成的食物 是否和蛇有重复 int ifBump(int head);//是否撞墙 或者撞到了蛇的身体 void makeFood(int food[2]);//通过随机数制作一个 食物的坐标 void getKey();//读取键盘输入的键 设置新方向 int main() { init(map,snake); while(true) { system("cls");//刷新控制台屏幕 Sleep(40); move(snake,direct);//蛇向后面移动一下 if (!food[0] && !food[1])//食物被吃掉 再生成一个食物 { makeFood(food);//生成食物 } makeMap(map,snake,food); showView(map); if (ifBump(head))//是否撞到自己或者墙 { printf("game over your score is %d ",head); break; } getKey(); } return 0; } void init(char map[22][52],int snake[900][3]) { //初始化snake //sanke[i][0] = 0代表蛇身 snake[i][0] = 1 代表蛇头 snake[i][1] 横坐标 snake[i][2] 纵坐标 snake[0][0] = 0,snake[0][1] = 5,snake[0][2] = 2; snake[1][0] = 0,snake[1][1] = 5,snake[1][2] = 3; snake[2][0] = 1,snake[2][1] = 5,snake[2][2] = 4; //初始化map for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (i == 0 || j == 0 || i ==H - 1 || j == W - 1) { map[i][j] = '#'; } else { map[i][j] = ' '; } } } } void showView(char map[22][52]) { for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { printf("%c",map[i][j]); } printf("\n"); } } void makeMap(char map[22][52],int snake[900][3],int food[2]) { int k; //再重新绘制一遍地图 for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (i == 0 || j == 0 || i == H - 1 || j == W - 1) { map[i][j] = '#'; } else { map[i][j] = ' '; } } } //把蛇的形状 加入到map中去 for (k = 0; k < 900; k++) { if (snake[k][0] == 1)//到了蛇头 { break; } map[snake[k][1]][snake[k][2]] = '@'; } map[snake[k][1]][snake[k][2]] = '@'; map[food[0]][food[1]] = '*'; } void move(int snake[900][3],int direct) { int x,y;//用于存储蛇头的 坐标 for (int i = 0; i < 900; i ++) { if (snake[i][0] == 1) { head = i; break; } } x = snake[head][1]; y = snake[head][2]; switch(direct) { case 1://向上 { snake[head][1]--;//蛇头的纵坐标减一 } case 2: { snake[head][1]++;//蛇头的纵坐标加一 } case 3: { snake[head][2]--; } case 4: { snake[head][2]++; } } //蛇头已经到了下一个位置了 先判断是否吃掉了食物 把蛇的身体往前移动一位 if (ifEat(head,food)) { snake[head + 1][0] = 1; snake[head + 1][1] = food[0]; snake[head + 1][2] = food[1]; snake[head][0] = 0;//取消了之前的蛇头 food[0] = 0; food[1] = 0; } for (int j = head - 1; j >= 0; j--) { int temp; temp = x,x = snake[j][1],snake[j][1] = temp; temp = y,y = snake[j][2],snake[j][2] = temp; } } void makeFood(int food[2]) { srand(time(0));//随机种子 int x = rand()%50 + 1; int y = rand()%20 + 1; while (ifRepeat(snake,x,y)) { x = rand()%50 + 1; y = rand()%20 + 1; } food[0] = y; food[1] = x; } int ifEat(int head,int food[2]) { if (snake[head][1] == food[0] && snake[head][2] == food[1]) { return 1; } else { return 0; } } int ifRepeat(int snake[900][3],int x,int y) { for (int i = 0; i < 900; i++) { if (snake[i][0] == 1) { break; } if (snake[i][1] == x && snake[i][2] == y) { return 1; } } return 0; } int ifBump(int head) { //撞墙 if (snake[head][1] == 0 || snake[head][1] == 21 || snake[head][2] == 0 || snake[head][2] == 51) { return 1; } for (int i = 0; i < head - 1; i++) { if (snake[i][1] == snake[head][1] && snake[i][2] == snake[head][2]) { return 1; } } return 0; } void getKey() { if (_kbhit()) { key = _getch(); } switch (key) { case 'H': { if (direct != 2) { direct = 1; } } case 'P': { if (direct != 1) { direct = 2; } } case 'K': { if (direct != 4) { direct = 3; } } case 'M': { if (direct != 3) { direct = 4; } } } }
[ "coderlongren@gmail.com" ]
coderlongren@gmail.com
3d1b95d8b8b248b35152fd1648646982b67c871d
ecd6b8513bb9f96e5d0c1213545950c3ccaa296c
/CoordinateDevice/CoordinateDevice/LinePrimitives.cpp
b4c1834d01db6e00450d75630086a8651e8cc528
[]
no_license
whztt07/FunctionalUtilities
9ad7ed923e871a05a791a33370e9dfede3d70b2f
b4621cdda24067d01487d5a25d07110dba207154
refs/heads/master
2021-01-21T19:07:44.058746
2016-07-05T11:14:07
2016-07-05T11:14:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,298
cpp
#include "LinePrimitives.h" LinePrimitives::LinePrimitives() { _geometry = new osg::Geometry; _color = new osg::Vec4Array(1); _startPosition = { 0.0f, 0.0f, 0.0f }; _endPosition = { 0.0f, 0.0f, 0.0f }; } void LinePrimitives::drawGeometry() { _geometry->setDataVariance(osg::Object::DYNAMIC); _geometry->setUseDisplayList(false); _geometry->setUseVertexBufferObjects(true); _geometry->setVertexArray(new osg::Vec3Array(2)); _geometry->setColorArray(_color); _geometry->setColorBinding(osg::Geometry::BIND_OVERALL); _geometry->addPrimitiveSet(new osg::DrawArrays(GL_LINES, 0, 2)); auto stateSet = _geometry->getOrCreateStateSet(); stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF); //osg::ref_ptr<osg::Geode> geode = new osg::Geode; //geode->addDrawable(_geometry.get()); //geode->getOrCreateStateSet()->setAttributeAndModes(new osg::Point(10.0f)); //geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); //geode->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON); //geode->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); } void LinePrimitives::setLineWidth(float width) { osg::ref_ptr<osg::LineWidth>linewidth = new osg::LineWidth; linewidth->setWidth(width); _geometry->getOrCreateStateSet()->setAttributeAndModes(linewidth, osg::StateAttribute::ON); } void LinePrimitives::setColor(float red, float green, float blue) { osg::Vec4 color = { red, green, blue, 1.0f }; //osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(1); (*_color)[0] = color; //colors = dynamic_cast<osg::Vec4Array*>(_geometry->getColorArray()); _color->dirty(); _geometry->setColorArray(_color); _geometry->dirtyBound(); } void LinePrimitives::setVertex() { osg::ref_ptr<osg::Vec3Array>verties = new osg::Vec3Array(2); (*verties)[0] = _startPosition; (*verties)[1] = _endPosition; _geometry->setVertexArray(verties); //verties = dynamic_cast<osg::Vec3Array*>(_geometry->getVertexArray()); _geometry->dirtyBound(); } osg::Geometry* LinePrimitives::getGeometry() { return _geometry; } void LinePrimitives::setStartPosition(float x, float y, float z) { _startPosition = { x, y, z }; } void LinePrimitives::setEndPosition(float x, float y, float z) { _endPosition = { x, y, z }; setVertex(); }
[ "invoker1994@sina.com" ]
invoker1994@sina.com
4cc8d1b42c9c0e3c555fc55fdb955f52d624ad28
522ede61c05c8d9f4e3eb1551647b5f0c0f8341b
/imes_vision/src/shape_matcher.cpp
ff8f0cf36761dab72bf58045490d5e785c023da3
[]
no_license
johannesgaa/imesYPApps
a6b13b57cc10eed60f926757b31a5a6837e82175
7be5e541d21a5f3b10a6ecdaf04f6d23ba0a3cd2
refs/heads/master
2021-01-19T11:02:17.040392
2013-02-26T01:36:07
2013-02-26T01:36:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,271
cpp
/************************************************************************ * @brief Shape-Detection-class for IMES ButtlerBot Project. * * - This is a part of the IMES ButtlerBot, a demo exercise * for the YouBot * * @file shape_matcher.cpp * @author Andreas Fregin (A.Fregin@live.de) * @date 2012-03-13 * * Gottfried Wilhelm Leibniz Universität * Institut für Mechatronische Systeme * Appelstraße 11a * 30167 Hannover * ************************************************************************/ #include <imes_vision/shape_matcher.h> using namespace std; shape_matcher::shape_matcher() { this->referenceSet= false; //this->modeCount= 0; this->boundingMode= 1; this->Trackbar1= 77; // minLength in % of img.cols this->Trackbar2= 12; // gap in % of img.cols this->Trackbar3= 4; // gap in % of img.cols this->Trackbar4= 100; // ContourFilter Lower this->Trackbar5= 2800; // ContourFilter Higher this->Trackbar6= 501; // Compliance this->Trackbar7= 57; // Canny Lower this->Trackbar8= 155; // Canny Higher this->Trackbar9= 15; // Morph Kernelelement this->Trackbar10= 3; // Dilate KernelElement this->Trackbar11= 21603; // SizeFiler Lower this->Trackbar12= 100000; // SizeFiler Higher this->Trackbar13= 100; // Brightness aspectRatioFiltering = true; aspectDynRatioFiltering = false; sizeFiltering= false; contourFiltering= true; useDistanceCalc= true; roiSize = cv::Size(0,0); roiMiddle = cv::Point(0,0); roiOFFSET = cv::Point(0,0); } cv::Mat shape_matcher::OneCHtoThreeCH(cv::Mat grayMat) { cv::Mat grayMatVec[3] = {grayMat, grayMat, grayMat}; cv::Mat BGRMat; cv::merge(grayMatVec, 3, BGRMat); return BGRMat; } cv::Point3d shape_matcher::getDistance(int VectorIndex) { return this->distanceVec[VectorIndex]; } void shape_matcher::calculateDistance(cv::Mat Contour, cv::Mat image) { double _d[9] = {1, 0, 0, 0, -1, 0, 0, 0, -1}; //rotation: looking at -x axis cv::Mat rotM(3,3,CV_64FC1,_d); std::vector<cv::Point2f> imgP; imgP.clear(); // mode 2 -> RotatedRect // mode 1 -> boundingRect cv::Point3d actualDist; cv::Rect box = cv::boundingRect(Contour); cv::RotatedRect boxR = cv::minAreaRect(Contour); // for roi-Correction! (otherwise x,y - calculation will fail!) if (roiSize.height > 0 && roiSize.width > 0) { roiOFFSET.x = roiMiddle.x - 0.5 * roiSize.width; roiOFFSET.y = roiMiddle.y - 0.5 * roiSize.height; box.x = box.x + roiOFFSET.x; box.y = box.y + roiOFFSET.y; } if(this->boundingMode == 2){ this->shapeHeightVec.push_back(boxR.size.height); this->shapeWidthVec.push_back(boxR.size.width); if (boxR.size.width >= boxR.size.height){ boxR.size.width = boxR.size.height; boxR.size.height = boxR.size.width; } //P1 links-oben //P2 rechts-oben //P3 rechts-unten //P4 links-unten imgP.push_back(cv::Point(boxR.center.x - boxR.size.width/2, boxR.center.y - boxR.size.height)); imgP.push_back(cv::Point(boxR.center.x + boxR.size.width/2, boxR.center.y - boxR.size.height)); imgP.push_back(cv::Point(boxR.center.x + boxR.size.width/2, boxR.center.y + boxR.size.height)); imgP.push_back(cv::Point(boxR.center.x - boxR.size.width/2, boxR.center.y + boxR.size.height)); } else if(this->boundingMode == 1){ this->shapeHeightVec.push_back(box.height); this->shapeWidthVec.push_back(box.width); // x , y imgP.push_back(cv::Point(box.x, box.y)); imgP.push_back(cv::Point(box.x+box.width, box.y)); imgP.push_back(cv::Point(box.x+box.width, box.y + box.height)); imgP.push_back(cv::Point(box.x, box.y + box.height)); } else { ROS_ERROR("INVALIND BOUNDINGMODE! Press any key to continue."); cv::waitKey(0); } objP.clear(); objP.push_back(cv::Point3d(0., 0., 0.)); objP.push_back(cv::Point3d(this->objectWidth / 1000., 0., 0.)); objP.push_back(cv::Point3d(this->objectWidth / 1000., this->objectHeight / 1000., 0.)); objP.push_back(cv::Point3d(0., this->objectHeight / 1000., 0.)); //cv::Mat(objP).convertTo(objPM,CV_32F); cv::Mat rvec(3,1,cv::DataType<double>::type); cv::Mat tvec(3,1,cv::DataType<double>::type); cv::solvePnP(cv::Mat(objP), cv::Mat(imgP), camera_matrix, distortion_coefficients, rvec, tvec, false); cv::Rodrigues(rvec,rotM); actualDist.x= tvec.at<double>(0,0) + double(this->objectWidth/2) / 1000.; actualDist.y= tvec.at<double>(1,0) + double(this->objectHeight/2) / 1000.; actualDist.z= tvec.at<double>(2,0); this->distanceVec.push_back(actualDist); ROS_INFO("Distance calculated: (X/Y/Z): %.2f/%.2f/%.2f", actualDist.z, actualDist.x,actualDist.y); //ROI coords! } void shape_matcher::setCameraParams(int focalLength, cv::Mat cameraMatrix, cv::Mat distoritionCoeffs) { if (focalLength != 0) this->camFocalLength= focalLength; if (cameraMatrix.at<double>(0,0) > 0) cameraMatrix.copyTo(this->camera_matrix); if (distoritionCoeffs.at<double>(0,0) > 0) distoritionCoeffs.copyTo(this->distortion_coefficients); ROS_INFO("Camera parameters set!"); } std::vector<std::vector<cv::Point> > shape_matcher::contourDetector(cv::Mat image1CH) { std::vector<std::vector<cv::Point> > ContourVec; cv::findContours(image1CH, // input must be gray ContourVec, // Output-Vector (as created above) CV_RETR_EXTERNAL, // retrieve the external contours CV_CHAIN_APPROX_NONE); // all pixels of each contours // Eliminate too short or too long contours if (contourFiltering == true && (int)ContourVec.size() > 0) { std::vector<std::vector<cv::Point> >::iterator itc= ContourVec.begin(); while (itc!=ContourVec.end()) { if ((int)(*itc).size() < Trackbar4 || (int)(*itc).size() > Trackbar5) itc= ContourVec.erase(itc); else ++itc; } } if (this->sizeFiltering == true && (int)ContourVec.size() > 0) { //sizeFiltering = Inhalt des mitgedrehten Rechtecks als Ausschlusskriterium std::vector<std::vector<cv::Point> >::iterator itc= ContourVec.begin(); while (itc!=ContourVec.end()) { cv::RotatedRect box = cv::minAreaRect(*itc); if ((box.size.width * box.size.height < Trackbar11) || ((box.size.width * box.size.height) > Trackbar12)) itc= ContourVec.erase(itc); else ++itc; } } return ContourVec; } void shape_matcher::clearFilter(bool clear, cv::Size size) { cv::Mat tmp(size, CV_8UC1, cv::Scalar(255)); if (clear == true) { this->filterMask= tmp; this->colorMask= tmp; } } cv::Mat shape_matcher::lineFilter(cv::Mat image) { cv::Mat out, tempBin; cv::Mat check; image.copyTo(tempBin); cv::Mat element5(5,5,CV_8U,cv::Scalar(1)); check= OneCHtoThreeCH(image); image.copyTo(out); cv::dilate(tempBin, tempBin, element5); if (this->showWindows) { cv::namedWindow("Hough", CV_WINDOW_AUTOSIZE); } cv::createTrackbar("min. Line Length [%] : ", "Hough", &Trackbar1, 100, NULL); cv::createTrackbar("max gap [%]: ", "Hough", &Trackbar2, 25, NULL); cv::createTrackbar("accuracyInterval [0.1*%]: ", "Hough", &Trackbar3, 100, NULL); if (this->contourFiltering == true) { cv::createTrackbar("lower threshold ContourFilter: ", "Hough", &Trackbar4, 10000, NULL); cv::createTrackbar("higher threshold ContourFilter: ", "Hough", &Trackbar5, 10000, NULL); } cv::createTrackbar("compliance: ", "Hough", &Trackbar6, 1000, NULL); cv::createTrackbar("lower threshold Canny: ", "Hough", &Trackbar7, 1000, NULL); cv::createTrackbar("higher threshold Canny: ", "Hough", &Trackbar8, 1000, NULL); cv::createTrackbar("Element Morph: ", "Hough", &Trackbar9, 25, NULL); cv::createTrackbar("Element Dilataion: ", "Hough", &Trackbar10, 10, NULL); if (this->sizeFiltering == true) { cv::createTrackbar("lower threshold sizeFilter: ", "Hough", &Trackbar11, 100000, NULL); cv::createTrackbar("higher threshold sizeFilter: ", "Hough", &Trackbar12, 100000, NULL); } cv::createTrackbar("Brigthness: ", "Hough", &Trackbar13, 240, NULL); std::vector<cv::Vec4i> lines; std::vector<cv::Vec4i> lines2; double deltaRho= 1; double deltaTheta= (M_PI/180); // will only detect vertical (=0) and horizontal (=pi/2) lines! int minVote= 10; double minLength= 0.01*Trackbar1*image.cols; double maxGap= 0.01*Trackbar2*image.cols; cv::Mat imageROI(image.size(), CV_8UC1, cv::Scalar(0)); cv::Mat polyROI(image.size(), CV_8UC1, cv::Scalar(0)); cv::Mat mask(image.size(), CV_8UC1, cv::Scalar(0)); cv::Mat polyMask(image.size(), CV_8UC1, cv::Scalar(0)); std::vector <cv::Point> boxPoints, polyPoints; std::vector< std::vector <cv::Point> > polyPointsArray; boxPoints.clear(); int accuracyInterval= (image.rows * 0.001 * Trackbar3 ); // would be 1% = 4px when image.height is 480px double m; cv::HoughLinesP(tempBin,lines,deltaRho, deltaTheta, minVote,minLength, maxGap); for (uint i=0; i < lines.size() ; i++) { // ([x1] [y1]) , ([x2] [y2]) cv::line(check, cv::Point(1,lines[i][1]),cv::Point(image.cols,lines[i][3]), cv::Scalar(0,0,255), 1, 8 ); //cv::line(this->filterMask, cv::Point(1,lines[i][1]),cv::Point(image.cols,lines[i][3]), cv::Scalar(0), 1, 8 ); boxPoints.clear(); boxPoints.push_back(cv::Point(0,lines[i][1])); boxPoints.push_back(cv::Point(image.cols,lines[i][3])); // Nu version with bounding Polygon (not Rectangle!) polyPoints.clear(); polyPointsArray.clear(); // TODO: polyPoints.push_back(cv::Point(0,(lines[i][1] + accuracyInterval))); // to correct -> 0 polyPoints.push_back(cv::Point(image.cols,(lines[i][3] + accuracyInterval))); // to correct -> image.cols polyPoints.push_back(cv::Point(image.cols,(lines[i][3] - accuracyInterval))); // to correct -> image.cols polyPoints.push_back(cv::Point(0,(lines[i][1] - accuracyInterval))); // to correct -> 0 polyPointsArray.push_back(polyPoints); cv::fillPoly(polyMask, polyPointsArray, cv::Scalar(255), 8); cv::fillPoly(check, polyPointsArray, cv::Scalar(255,255,0), 8); out.copyTo(polyROI, polyMask); // detect smaller lines in imageROI and overpint them black in original Frame cv::HoughLinesP(polyROI,lines2, 1, (M_PI/180), 2, 5, 0); for (uint j=0; j < lines2.size() ; j++) { if ((lines2[j][0]) == (lines2[j][2])) { // line vertical m= -1; } else { m= 1. * abs(((lines2[j][3])-(lines2[j][1]))/((lines2[j][2])-(lines2[j][0]))); } // to improve: use m only if this is wanted!!!! if ((m < 2) && (m > -1)) { // ([x1] [y1]) , ([x2] [y2]) cv::line(check, cv::Point(lines2[j][0],lines2[j][1]),cv::Point(lines2[j][2],lines2[j][3]), cv::Scalar(255,0,0), 2, 8 ); cv::line(out, cv::Point(lines2[j][0],lines2[j][1]),cv::Point(lines2[j][2],lines2[j][3]), cv::Scalar(0,0,0), 2, 8 ); cv::line(this->filterMask, cv::Point(lines2[j][0],lines2[j][1]),cv::Point(lines2[j][2],lines2[j][3]), cv::Scalar(0), 3, 8 ); } } } if (this->showWindows) { cv::imshow("Hough", check); } return out; } cv::Mat shape_matcher::colorFilter(cv::Mat image, cv::Scalar hsv_min, cv::Scalar hsv_max, int maskMode) { std::vector <cv::Rect> boxVec, colorROI, cleanedROI; std::vector <cv::Point> bxPoints; cv::Mat boxMat(image.size(), CV_8UC3, cv::Scalar(0,0,0)); cv::Mat smoothedFrame; cv::GaussianBlur(image, smoothedFrame, cv::Size(5, 5), 2); // convert BGR to HSV cv::Mat hsv_frame(image.size(), CV_8UC3, cv::Scalar(0)); cv::cvtColor(smoothedFrame, hsv_frame ,CV_BGR2HSV); // execute the filtering cv::Mat mask(image.size(), CV_8UC3, cv::Scalar(0)); // Used as mask in origFrame cv::inRange(hsv_frame, hsv_min, hsv_max, mask); switch (maskMode) { case 1: { // Returns the mask cv::Mat FilterKernel(9,9,CV_8U,cv::Scalar(255)); cv::erode(mask, mask, FilterKernel); this->colorMask= mask; return mask; break; } case 2: { // Returns a wide bounding box around the colored areas cv::Mat FilterKernel(9,9,CV_8U,cv::Scalar(255)); cv::erode(mask, mask, FilterKernel); image.copyTo(boxMat, mask); // Konturen der Farbbereiche std::vector<std::vector<cv::Point> > ContourVec; cv::findContours(mask, ContourVec, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); // find the contours for (std::vector <std::vector <cv::Point> >::iterator it = ContourVec.begin(); it < ContourVec.end(); it++ ){ if (it->size() > 50) { // convert the contour point to a matrix std::vector <cv::Point> pts = *it; cv::Mat pointsMatrix = cv::Mat(pts); } } std::cout << "Number of colored Areas: " << ContourVec.size() << std::endl; boxVec.clear(); colorROI.clear(); cleanedROI.clear(); bxPoints.clear(); for (uint i =0; (i < ContourVec.size());i++) { cv::Rect box= cv::boundingRect(cv::Mat(ContourVec[i])); // Rect around shape boxVec.push_back(box); //cv::rectangle(boxMat,box,cv::Scalar(0,255,0),3); } int accuracyInterval= image.cols*0.02; for (uint j=0; j < boxVec.size(); j++) { for (uint k=0; k < boxVec.size(); k++) { if (((boxVec[j].width) >= (boxVec[k].width - accuracyInterval)) && ((boxVec[j].width) <= (boxVec[k].width + accuracyInterval)) && ((boxVec[j].x) >=(boxVec[k].x - accuracyInterval)) && ((boxVec[j].x) <= (boxVec[k].x + accuracyInterval))) { //Build new Rect around k and j-Rects: cv::Point k1= cv::Point((boxVec[k].x), (boxVec[k].y)); cv::Point k3= cv::Point((boxVec[k].x + boxVec[k].width), (boxVec[k].y + boxVec[k].height)); cv::Point j1= cv::Point(boxVec[j].x,boxVec[j].y); cv::Point j3= cv::Point((boxVec[j].x + boxVec[j].width), (boxVec[j].y + boxVec[j].height)); bxPoints.push_back(k1); bxPoints.push_back(k3); bxPoints.push_back(j1); bxPoints.push_back(j3); cv::Rect bx= cv::boundingRect(cv::Mat(bxPoints)); //cv::rectangle(boxMat,bx,cv::Scalar(0,0,255),2); colorROI.push_back(bx); bxPoints.clear(); } } } std::cout << "Built " << colorROI.size() << " big color-areas " ; for (uint z=0; z < colorROI.size(); z++) { std::cout << "size: " << colorROI.size() << std::endl; for (uint y=0; y < colorROI.size(); y++) { if (colorROI[z].contains(cv::Point(colorROI[y].x + colorROI[y].width/2,colorROI[y].y - colorROI[y].height/2))) { std::cout << "erasing element: " << y << std::endl; colorROI.erase((colorROI.begin()+y)); } } } std::cout << " filtered to " << colorROI.size() << std::endl; /* // draw biggest bounding boxes for (uint l=0; l <colorROI.size(); l++) { for (uint m=0; m <colorROI.size(); m++) { if ((((colorROI[l]) & (colorROI[m])).area()) > 0) { cleanedROI.push_back((colorROI[l]) | (colorROI[m])); } } } // for (uint z=0; z < cleanedROI.size(); z++) { std::cout << "size: " << cleanedROI.size() << std::endl; for (uint y=0; y < cleanedROI.size(); y++) { if (cleanedROI[z].contains(cv::Point(cleanedROI[y].x,cleanedROI[y].y))) { std::cout << "erasing element: " << y << std::endl; cleanedROI.erase((cleanedROI.begin()+y)); } } } */ for (uint x=0; x < colorROI.size(); x++) { cv::rectangle(boxMat,colorROI[x],cv::Scalar(0,0,255),1); } this->colorMask=boxMat; return boxMat; break; } case 3: { // Returns a wide bounding box around the colored areas cv::Mat FilterKernel(9,9,CV_8U,cv::Scalar(255)); cv::erode(mask, mask, FilterKernel); // Konturen der Farbbereiche std::vector<std::vector<cv::Point> > ContourVec; ContourVec= contourDetector(mask); std::cout << "Number of colored Areas: " << ContourVec.size() << std::endl; cv::Mat boxMat(image.size(), CV_8U, cv::Scalar(0)); for (uint i =0; (i < ContourVec.size());i++) { cv::Rect box= cv::boundingRect(cv::Mat(ContourVec[i])); // Rect around shape cv::rectangle(boxMat,box,cv::Scalar(255),2); } this->colorMask= boxMat; return boxMat; break; } default: { // Return the colored parts of the source-image cv::Mat result(image.size(), CV_8UC3, cv::Scalar(255,255,255)); image.copyTo(result, mask); this->colorMask= result; return result; } } } cv::Mat shape_matcher::BGR2BIN(cv::Mat imageMat, int mode, bool equalizing) { cv::Mat binMat; cv::Mat grayMat; // BGR2GRAY cv::cvtColor(imageMat, grayMat, CV_BGR2GRAY); // EQUALIZING if (equalizing == true) cv::equalizeHist(grayMat, grayMat); // GRAY2BIN: 3 Modes switch (mode) { case 2: { // Apply Canny algorithm cv::Mat contours; cv::Canny(grayMat, // gray-level image binMat, // output contours Trackbar7, // low threshold Trackbar8); // high threshold break; } case 1: { // GRAY2BIN (BIN has also 8 bit, but only 2 values) cv::adaptiveThreshold(grayMat, binMat, 255, CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV, 15, 10); break; } default: { // GRAY2BIN (BIN has also 8 bit, but only 2 values) cv::threshold(grayMat, binMat, 70, 255, CV_THRESH_BINARY_INV); break; } } this->binFrame= binMat; return binMat; } std::vector<std::vector<cv::Point> > shape_matcher::huller(std::vector<std::vector<cv::Point> > ContourVec) { std::vector<std::vector<cv::Point> >HullVec; std::vector<cv::Point> Hull; for (uint i=0; i < ContourVec.size(); i++) { cv::convexHull(cv::Mat(ContourVec[i]),Hull); HullVec.push_back(Hull); } return HullVec; } bool shape_matcher::setReference(std::string path, int height, int width) { this->referenceSet= false; // Get a reference shape: try { ROS_INFO_STREAM("Shape_path is: " << path); this->refShapeImg = cv::imread(path); } catch (cv::Exception &ex) { ROS_ERROR("--(!) Error reading Reference: %s ", ex.what()); cv::waitKey(); } if (!refShapeImg.data) { ROS_ERROR("--(!) Error reading Reference "); } cv::Mat Rev= BGR2BIN(this->refShapeImg, 5, 1); this->refContourVec.clear(); this->refContourVec.push_back(contourDetector(Rev)[0]); this->objectWidth= width; this->objectHeight= height; // User-Output ROS_INFO("%d Reverence loaded and converted.", (int)refContourVec.size()); this->referenceSet= true; return true; } void shape_matcher::setBoundingMode(int mode) { switch (mode) { case 1: this->boundingMode= 1; // boundingRect break; case 2: this->boundingMode= 2; // minRotatedRect break; default:this->boundingMode= 1; break; } } cv::Mat shape_matcher::binFilter(cv::Mat image) { cv::Mat filtered1(image.size(), CV_8UC1, cv::Scalar(0)); cv::Mat filtered2(image.size(), CV_8UC1, cv::Scalar(0)); cv::Mat element15(Trackbar9, Trackbar9, CV_8U, cv::Scalar(255)); cv::Mat element3(Trackbar10, Trackbar10, CV_8U, cv::Scalar(255)); cv::morphologyEx(image, filtered1, cv::MORPH_CLOSE, element15); cv::dilate(filtered1, filtered2, element3); filtered2.copyTo(this->filteredBinMat); return filtered2; } void shape_matcher::match(cv::Mat image) { // clear height, width and distance vectors: this->shapeHeightVec.clear(); this->shapeWidthVec.clear(); this->distanceVec.clear(); // set Filtering if you wanna use it!!!!!!!! this->ContourVec= contourDetector(image); if (this->refContourVec.size() == 0) { ROS_ERROR("Please provide a reference-contour in the reverence-vector!"); } if (this->refContourVec.size() > 1) ROS_INFO("This matcher will only use the first contour of the reverence-vector!"); double compliance; std::vector<std::vector<cv::Point> >::iterator itc= ContourVec.begin(); double shapeAspect; double shapeAspectHW; double shapeAspectWH; while ((itc != ContourVec.end())) { compliance = cv::matchShapes(cv::Mat(this->refContourVec[0]),cv::Mat(*itc), CV_CONTOURS_MATCH_I2, 0); //std::cout << "Compliance: " << compliance << std::endl; if (compliance > Trackbar6 * 0.01) { itc = ContourVec.erase(itc); } else { if (this->aspectRatioFiltering) { cv::Rect box = cv::boundingRect(cv::Mat(*itc)); // Rect around shape shapeAspect = (1. * (box.height) / (1. * (box.width))); if ((box.width >= box.height) || (shapeAspect > 5) || (shapeAspect < 3)) { itc = ContourVec.erase(itc); } else { // Time to calculate distance! // 1) Get height and width in pixels if (this->useDistanceCalc) calculateDistance(cv::Mat(*itc), image); ++itc; } } if (this->aspectDynRatioFiltering) { cv::RotatedRect box = cv::minAreaRect(cv::Mat(*itc)); // Rect around shape shapeAspectHW = (1. * (objectHeight) / (1. * (objectWidth))); shapeAspectWH = (1. * (objectWidth) / (1. * (objectHeight))); double WH = box.size.width / box.size.height; double HW = box.size.height / box.size.width; if (((WH > shapeAspectWH * (1+RatioPro/100)) && (WH < shapeAspectWH * (1-RatioPro/100))) || ((HW > shapeAspectHW * 1.2) && (HW > shapeAspectHW * 0.8))) { itc = ContourVec.erase(itc); } else { // Time to calculate distance! // 1) Get height and width in pixels if (this->useDistanceCalc) calculateDistance(cv::Mat(*itc), image); ++itc; } } if ((this->aspectDynRatioFiltering == false) && (this->aspectRatioFiltering == false)){ // Time to calculate distance! // 1) Get height and width in pixels if (this->useDistanceCalc) calculateDistance(cv::Mat(*itc), image); ++itc; } } } //std::cout << this->distanceVec.size() << " distances stored." << std::endl; }
[ "andreas@imesros04" ]
andreas@imesros04
51175d01902768bb2f0405dbccc1eb3999ecbbd4
19ccd5091acbc74618b5b2913c0a7062e8319c8d
/lib/MPPTLib/utils.cpp
e670bfa779d9e2efcbc93682e9e43cdb3a7d33d7
[]
no_license
ThatcherC/OSPController
3d4e5cd07716b15e4c38fdad460143719d0e1d87
c655a1dd8b6f5e1d9bd5f28c2bbf7fa416d788fc
refs/heads/main
2023-04-30T11:04:06.543225
2021-05-20T08:28:42
2021-05-20T08:29:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,882
cpp
#include <Arduino.h> #include <rom/rtc.h> #include "publishable.h" #include "utils.h" float mapfloat(long x, long in_min, long in_max, long out_min, long out_max) { return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + out_min; } String str(const char *fmtStr, ...) { static char buf[201] = {'\0'}; va_list arg_ptr; va_start(arg_ptr, fmtStr); vsnprintf(buf, 200, fmtStr, arg_ptr); va_end(arg_ptr); return String(buf); } String str(const std::string &s) { return String(s.c_str()); } String str(bool v) { return v ? " WIN" : " FAIL"; } StringPair split(const String &str, const String &del) { int at = str.indexOf(del); if (at >= 0) return StringPair(str.substring(0, at), str.substring(at + del.length())); return StringPair(str, ""); } bool suffixed(String *str, const String &suff) { if (!str) return false; bool res = str->endsWith(suff); if (res) str->remove(str->lastIndexOf(suff)); return res; } // float lifepo4_soc[] = {13.4, 13.3, 13.28, 13.}; Publishable* pub_; //static void log(const String &s) { pub_->log(s); } void addLogger(Publishable* p) { pub_ = p; } String timeAgo(int sec) { int days = (sec / (3600 * 24)); String ret = str("%ds", sec % 60); if (sec >= 60 ) ret = str("%dm ", (sec % 3600) / 60) + ret; if (sec >= 3600) ret = str("%dh ", ((sec % (3600 * 24)) / 3600)) + ret; if (days) ret = str("%dd ", days % 365) + ret; if (days >= 365) ret = str("%dy ", days / 365) + ret; return ret; } String getResetReason(RESET_REASON r) { switch (r) { case NO_MEAN: return ""; case POWERON_RESET : return "Vbat power on reset"; case SW_RESET : return "Software reset digital core"; case OWDT_RESET : return "Legacy watch dog reset digital core"; case DEEPSLEEP_RESET : return "Deep Sleep reset digital core"; case SDIO_RESET : return "Reset by SLC module, reset digital core"; case TG0WDT_SYS_RESET : return "Timer Group0 Watch dog reset digital core"; case TG1WDT_SYS_RESET : return "Timer Group1 Watch dog reset digital core"; case RTCWDT_SYS_RESET : return "RTC Watch dog Reset digital core"; case INTRUSION_RESET : return "Instrusion tested to reset CPU"; case TGWDT_CPU_RESET : return "Time Group reset CPU"; case SW_CPU_RESET : return "Software reset CPU"; case RTCWDT_CPU_RESET : return "RTC Watch dog Reset CPU"; case EXT_CPU_RESET : return "for APP CPU, reseted by PRO CPU"; case RTCWDT_BROWN_OUT_RESET: return "Reset when the vdd voltage is not stable"; case RTCWDT_RTC_RESET : return "RTC Watch dog reset digital core and rtc module"; } return ""; } String getResetReasons() { return "Reset0: " + getResetReason(rtc_get_reset_reason(0)) + ". Reason1: " + getResetReason(rtc_get_reset_reason(1)); }
[ "timo@t413.com" ]
timo@t413.com
2eff4b3fad9161b40445e298fc75bd447d71dbbc
9833b3a7d0ae0d2fea51d607400c7cd4e64299e3
/programmers/lifeboat.cpp
58cec46c47de5dceaccc2fff41e2fb383b57c7b5
[]
no_license
zerocy18/algorithms
ad9fa1aee6aa569e883bf7b796e7f980a0a622e9
fedef6d9ca4d5239089a403f332c62e1216f3147
refs/heads/master
2023-01-05T08:20:34.160782
2020-11-01T08:26:00
2020-11-01T08:26:00
259,630,633
0
0
null
null
null
null
UTF-8
C++
false
false
739
cpp
#include <string> #include <vector> #include <algorithm> using namespace std; bool cmp(int a, int b){ return a>b; } int solution(vector<int> people, int limit) { int answer = 0; int i = 0; int j = people.size()-1; sort(people.begin(), people.end(),cmp); int sum=0; int cnt=0; while(true){ sum+=people[i]; i++; while(sum+people[i]<=limit){ sum+= people[i]; i++; } while(sum+people[j] <= limit){ sum+= people[j]; j--; } cnt++; if(i > j) break; sum=0; } for(int i = 0 ;i < people.size(); i++) printf("%d", people[i]); answer = cnt; return answer; }
[ "noreply@github.com" ]
noreply@github.com
e7047dd16930b1ef1ccfefed0f72b6bc463c8ec8
60db84d8cb6a58bdb3fb8df8db954d9d66024137
/android-cpp-sdk/platforms/android-8/org/xml/sax/ext/Attributes2.hpp
0b469331424c5e04207dfd507816179d341b62df
[ "BSL-1.0" ]
permissive
tpurtell/android-cpp-sdk
ba853335b3a5bd7e2b5c56dcb5a5be848da6550c
8313bb88332c5476645d5850fe5fdee8998c2415
refs/heads/master
2021-01-10T20:46:37.322718
2012-07-17T22:06:16
2012-07-17T22:06:16
37,555,992
5
4
null
null
null
null
UTF-8
C++
false
false
5,245
hpp
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: org.xml.sax.ext.Attributes2 ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ORG_XML_SAX_EXT_ATTRIBUTES2_HPP_DECL #define J2CPP_ORG_XML_SAX_EXT_ATTRIBUTES2_HPP_DECL namespace j2cpp { namespace org { namespace xml { namespace sax { class Attributes; } } } } namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <org/xml/sax/Attributes.hpp> namespace j2cpp { namespace org { namespace xml { namespace sax { namespace ext { class Attributes2; class Attributes2 : public object<Attributes2> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) explicit Attributes2(jobject jobj) : object<Attributes2>(jobj) { } operator local_ref<org::xml::sax::Attributes>() const; operator local_ref<java::lang::Object>() const; jboolean isDeclared(jint); jboolean isDeclared(local_ref< java::lang::String > const&); jboolean isDeclared(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&); jboolean isSpecified(jint); jboolean isSpecified(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&); jboolean isSpecified(local_ref< java::lang::String > const&); }; //class Attributes2 } //namespace ext } //namespace sax } //namespace xml } //namespace org } //namespace j2cpp #endif //J2CPP_ORG_XML_SAX_EXT_ATTRIBUTES2_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ORG_XML_SAX_EXT_ATTRIBUTES2_HPP_IMPL #define J2CPP_ORG_XML_SAX_EXT_ATTRIBUTES2_HPP_IMPL namespace j2cpp { org::xml::sax::ext::Attributes2::operator local_ref<org::xml::sax::Attributes>() const { return local_ref<org::xml::sax::Attributes>(get_jobject()); } org::xml::sax::ext::Attributes2::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } jboolean org::xml::sax::ext::Attributes2::isDeclared(jint a0) { return call_method< org::xml::sax::ext::Attributes2::J2CPP_CLASS_NAME, org::xml::sax::ext::Attributes2::J2CPP_METHOD_NAME(0), org::xml::sax::ext::Attributes2::J2CPP_METHOD_SIGNATURE(0), jboolean >(get_jobject(), a0); } jboolean org::xml::sax::ext::Attributes2::isDeclared(local_ref< java::lang::String > const &a0) { return call_method< org::xml::sax::ext::Attributes2::J2CPP_CLASS_NAME, org::xml::sax::ext::Attributes2::J2CPP_METHOD_NAME(1), org::xml::sax::ext::Attributes2::J2CPP_METHOD_SIGNATURE(1), jboolean >(get_jobject(), a0); } jboolean org::xml::sax::ext::Attributes2::isDeclared(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1) { return call_method< org::xml::sax::ext::Attributes2::J2CPP_CLASS_NAME, org::xml::sax::ext::Attributes2::J2CPP_METHOD_NAME(2), org::xml::sax::ext::Attributes2::J2CPP_METHOD_SIGNATURE(2), jboolean >(get_jobject(), a0, a1); } jboolean org::xml::sax::ext::Attributes2::isSpecified(jint a0) { return call_method< org::xml::sax::ext::Attributes2::J2CPP_CLASS_NAME, org::xml::sax::ext::Attributes2::J2CPP_METHOD_NAME(3), org::xml::sax::ext::Attributes2::J2CPP_METHOD_SIGNATURE(3), jboolean >(get_jobject(), a0); } jboolean org::xml::sax::ext::Attributes2::isSpecified(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1) { return call_method< org::xml::sax::ext::Attributes2::J2CPP_CLASS_NAME, org::xml::sax::ext::Attributes2::J2CPP_METHOD_NAME(4), org::xml::sax::ext::Attributes2::J2CPP_METHOD_SIGNATURE(4), jboolean >(get_jobject(), a0, a1); } jboolean org::xml::sax::ext::Attributes2::isSpecified(local_ref< java::lang::String > const &a0) { return call_method< org::xml::sax::ext::Attributes2::J2CPP_CLASS_NAME, org::xml::sax::ext::Attributes2::J2CPP_METHOD_NAME(5), org::xml::sax::ext::Attributes2::J2CPP_METHOD_SIGNATURE(5), jboolean >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(org::xml::sax::ext::Attributes2,"org/xml/sax/ext/Attributes2") J2CPP_DEFINE_METHOD(org::xml::sax::ext::Attributes2,0,"isDeclared","(I)Z") J2CPP_DEFINE_METHOD(org::xml::sax::ext::Attributes2,1,"isDeclared","(Ljava/lang/String;)Z") J2CPP_DEFINE_METHOD(org::xml::sax::ext::Attributes2,2,"isDeclared","(Ljava/lang/String;Ljava/lang/String;)Z") J2CPP_DEFINE_METHOD(org::xml::sax::ext::Attributes2,3,"isSpecified","(I)Z") J2CPP_DEFINE_METHOD(org::xml::sax::ext::Attributes2,4,"isSpecified","(Ljava/lang/String;Ljava/lang/String;)Z") J2CPP_DEFINE_METHOD(org::xml::sax::ext::Attributes2,5,"isSpecified","(Ljava/lang/String;)Z") } //namespace j2cpp #endif //J2CPP_ORG_XML_SAX_EXT_ATTRIBUTES2_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
[ "baldzar@gmail.com" ]
baldzar@gmail.com
68ddaad539b2196b5f019c67c78e63d0e4e686c4
10efb971fcf3fc96e153b0f76ab17c11837e7701
/Include/tgd/System.hpp
dee1b9c6ca715b1541470b611ca0bc2f22241172
[]
no_license
jason-bunn/SFMLTests
aedb9c979a060704583a9606d868e25338189a15
10b04317d0cbf1e4aae5a560578436103659d1a4
refs/heads/master
2020-04-02T01:08:26.805700
2014-02-28T18:40:43
2014-02-28T18:40:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,607
hpp
#ifndef TGD_SYSTEM_HPP #define TGD_SYSTEM_HPP #include <ResourceHolder.hpp> #include <ResourceIdentifiers.hpp> #include <tgd/Entity.hpp> #include <entities/Player.hpp> #include <events/EventRouter.hpp> #include <tgd/Controller.hpp> #include <tgd/BaseFactory.hpp> #include <tgd/ControllerFactory.hpp> #include <tmx/MapLoader.h> #include <SFML/System/Time.hpp> #include <SFML/Graphics/RenderTarget.hpp> #include <SFML/Graphics/RenderStates.hpp> #include <unordered_map> #include <map> #include <vector> #include <memory> #include <bitset> #include <string> class RenderController; class Camera; namespace tgd { class System { public: System(TextureHolder& textures, sf::RenderTarget& target, Events::EventRouter* eventRouter, tmx::MapLoader* mMapLoader); ~System(); template <typename T> void registerEntity(std::shared_ptr<T> entity); void update(sf::Time dt); void draw(); template <typename T> void createEntity(); bool isPlayerCreated(); int assignControllerID(); std::shared_ptr<Entity> fetchEntity(int eID); std::shared_ptr<Entity> findEntityByName(std::string tag); void cleanup(); public: TextureHolder& textureHolder; sf::RenderTarget& mTarget; tmx::MapLoader* mMapPtr; private: void checkProperties(int id); void assignControllers(int id, std::bitset<32> newBits); template <typename T> void createFactory(System* system); private: std::unordered_map<int, std::vector<std::shared_ptr<Controller>>> controllerMap; std::map<unsigned int, std::shared_ptr<Entity>> mEntities; std::map<unsigned int, std::string> mEntityTags; unsigned int mEntityCount; int mControllerCount; bool mPlayerCreated; Events::EventRouter* mEventRouter; std::vector<std::shared_ptr<tgd::BaseFactory>> mFactories; }; } #include "System.inl" #include <controllers/RenderController.hpp> #include <controllers/PlayerController.hpp> #endif // TGD_SYSTEM_HPP
[ "jason.bunn009@gmail.com" ]
jason.bunn009@gmail.com
0d78042bdbf95dbba09ef81297d4c6db766af658
155fe60ca2f88c5270e543061ecefbcce6d1c819
/Plugins/MiscTools/Source/MiscTools/Public/EditorUITools.h
7307d8bd8fc3f23d704af227d967351775f83366
[]
no_license
zhurongjun/UnrealCheatSheet
96d84ab0281022e8ed69e78fed0e7b6095f7c08b
f045bfe1e0486076e9ae72dcc4098bad1b7b7a5d
refs/heads/master
2023-02-25T00:58:27.123892
2021-01-27T10:02:10
2021-01-27T10:02:10
293,776,319
13
1
null
2021-01-23T06:47:44
2020-09-08T10:25:56
C++
UTF-8
C++
false
false
545
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Kismet/BlueprintFunctionLibrary.h" #include "EditorUITools.generated.h" class UWidgetBlueprint; /** * Tools for editor UI */ UCLASS() class MISCTOOLS_API UEditorUITools : public UBlueprintFunctionLibrary { GENERATED_BODY() public: // an example that open Tab Window with UEditorUtilityWidget UFUNCTION(BlueprintCallable) static void OpenTabWindow(const FString& InTitle, UWidgetBlueprint* InContent); };
[ "211103376@qq.com" ]
211103376@qq.com
1bc4a96153adfcca60000dca6d3600fc6e500efe
adc86591cdae82d07e10f85c400938f764292de2
/src/fonction/fonction_source/fonction_source_entier.cpp
29118205ed7bcc52a8dce18f46105312566a9f1e
[]
no_license
sebangi/emgine
e88bbd9223ea978344d4e9be51abbaa1f124ed9e
9cd367f10f26c140bc02bab6a8257c46af66adce
refs/heads/master
2021-07-15T16:04:39.127717
2021-03-19T12:14:59
2021-03-19T12:14:59
78,368,305
0
0
null
null
null
null
UTF-8
C++
false
false
3,819
cpp
/** \file fonction_source_entier.cpp * \brief Fichier d'implémentation de la classe fonction_source_entier. * \author Sébastien Angibaud */ #include "entete/fonction/fonction_source/fonction_source_entier.h" #include "entete/compilation/compilateur.h" #include "entete/fonction_widget/fonction_source_widget/fonction_source_entier_widget.h" /** -------------------------------------------------------------------------------------- * \brief Constructeur de la classe fonction_source_entier. * \param conteneur Un pointeur sur le conteneur de la fonction. * \param valeur La valeur initiale de la fonction. */ fonction_source_entier::fonction_source_entier(fonctions_conteneur * conteneur, int valeur) : fonction_base_source(conteneur), m_valeur(valeur) { set_id(f_source_entier); augmenter_max_niveau_visibilite(1); } /** -------------------------------------------------------------------------------------- * \brief Destructeur de la classe fonction_source_entier. */ fonction_source_entier::~fonction_source_entier() { } /** -------------------------------------------------------------------------------------- * \brief Construit et retourne le widget associé à cette fonction. * \return Un pointeur sur le widget créé. */ base_fonction_widget *fonction_source_entier::generer_fonction_widget() { return new fonction_source_entier_widget(this); } /** -------------------------------------------------------------------------------------- * \brief Execute la fonction. * \param compil Le compilateur utilisé. * \param textes_in Le texte source en entrée. * \param textes_out Le texte de sortie généré. */ void fonction_source_entier::executer( compilateur &compil, textes & textes_in, textes & textes_out ) { textes_out = textes_in; base_element e(m_valeur); mot m; m.push_back(e); ligne l; l.ajouter_mot(m); texte t; t.ajouter_ligne(l); textes_out.push_back(t); } /** -------------------------------------------------------------------------------------- * \brief Retourne la valeur de la fonction en version raccourci. * \return La valeur courte de la fonction. */ QString fonction_source_entier::get_valeur_courte() const { return QString::number(m_valeur); } /** -------------------------------------------------------------------------------------- * \brief Accesseur de la valeur de la fonction. * \return La valeur de la fonction. */ int fonction_source_entier::get_valeur() const { return m_valeur; } /** -------------------------------------------------------------------------------------- * \brief Initialise la valeur de la fonction. * \param valeur La nouvelle valeur de la fonction. */ void fonction_source_entier::set_valeur(int valeur) { m_valeur = valeur; } /** -------------------------------------------------------------------------------------- * \brief Accesseur de la valeur de la fonction au format QString. * \return La valeur de la fonction au format QString. */ QString fonction_source_entier::get_string_valeur() const { return QString::number(m_valeur); } /** -------------------------------------------------------------------------------------- * \brief Initilialise la valeur de la fonction à partir d'un QString donné. * \param valeur La nouvelle valeur de la fonction au format QString. */ void fonction_source_entier::set_string_valeur(const QString &valeur) { m_valeur = valeur.toInt(); } /** -------------------------------------------------------------------------------------- \brief Teste si la fonction est valide. \param vue_logs Un pointeur sur le widget de vue des logs. \return \b True si la fonction est valide, \b False sinon. */ bool fonction_source_entier::est_valide(logs_compilation_widget * vue_logs) { return true; }
[ "sebastien_angibaud@yahoo.fr" ]
sebastien_angibaud@yahoo.fr
d4454e0ef41bcaa9c7b6528541dc235a0a400432
e7305bf4b50cedfbecf236a545f109bd825840fa
/core/FeElement.hpp
028344acbfd6c0eeec0f5728f6e5a9bb8436b09c
[]
no_license
lucmobz/pacs-project
df03257ccf4b745692b1daf30919e7db188ef573
e54500b96dcf0e3d44aa07fa2970f95a5ac5c4b5
refs/heads/main
2023-04-30T11:49:55.701913
2021-05-21T20:27:13
2021-05-21T20:27:13
369,647,056
0
0
null
null
null
null
UTF-8
C++
false
false
6,497
hpp
#pragma once #include <numeric> #include <utility> #include "Traits.hpp" #include "functional_include.hpp" #include "mesh_include.hpp" #include "utilities_include.hpp" namespace wave { /** \brief A FeElement is a finite element in a finite element space (FeSpace) This class is built on top of an underlying mesh Element (which is nothing but an index with methods to compute associated information) and stores the algorithm specific information associated with such element. */ class FeElement { public: using scalar_t = Traits::scalar_t; using point_t = Traits::point_t; /// \brief Construct a finite element from an Element and a polynomial degree FeElement(const Element &element, int degree); /// \brief Get the polynomial degree. auto degree() const -> int; /// \brief Get the number of degrees of freedom on the element. auto ndof() const -> int; /// \brief Get the indices of the degrees of freedom of the element. auto dof() const -> const std::vector<int> &; /// \brief Get the index of the i-th degree of freedom of the element. auto dof(int i) const -> int; /// \brief Compute the location in the reference cartesian bounding box from a /// physical point. \param x The physical point. \return The reference point /// in the box (-1,1)^3. auto map(const point_t &x) const -> point_t; /// \brief Get the jacobian of the transfomration that maps a reference point /// into a physical point. auto jacobian() const -> const point_t &; /// \brief Get the diameter of the underlying mesh Element. auto diameter() const -> scalar_t; /// \brief Set the diameter of the underlying mesh Element (normally by using /// the Element method). void diameter(scalar_t diameter); /// \brief Get the Triangulation of the Element used in quadrature rules. auto triangulation() const -> const Triangulation<Element> &; /// \brief Compute the Triangulation of the Element. void triangulate(); /// \brief Compute the basis functions on a set of points. /// \tparam Points The container type for the set of points. /// \param points The container for the set of points. /// \return Returns the values of the basis functions in a vector of scalars. template <typename Points> auto eval_basis(const Points &points) const -> std::vector<scalar_t>; /// \brief Compute the basis function derivatives on a set of points. /// \tparam Points The container type for the set of points. /// \param points The container for the set of points. /// \return Returns the gradients of the basis functions computed at the /// points as a vector of points. template <typename Points> auto eval_basis_derivatives(const Points &points) const -> std::vector<point_t>; /// \brief Compute the i-th basis function on a point given by x. auto eval_basis(int i, const point_t &x) const -> scalar_t; /// \brief Compute the i-th basis function gradient on a point given by x. /// \return Returns the gradient as a point. auto eval_basis_derivatives(int i, const point_t &x) const -> point_t; private: /// The underlying mesh Element. Element _element; /// The indices of the degrees of freedom. std::vector<int> _dof; /// The polynomial degree int _degree{0}; /// The reference to physical box map, represented as the jacobian and /// midpoint. std::pair<point_t, point_t> _map{point_t::Zero(), point_t::Zero()}; /// The Triangulation of the underlying Element. Triangulation<Element> _triangulation; /// The diameter of the element. scalar_t _diameter{0.0}; /// \brief Compute the number of degrees of freedom. static constexpr auto _compute_ndof(int dim, int degree) -> int; }; //------------------------------------------------------------------------------ inline FeElement::FeElement(const Element &element, int degree) : _element(element), _degree(degree) { int ndof = _compute_ndof(element.dim(), degree); _dof.resize(ndof); std::iota(_dof.begin(), _dof.end(), element.index() * ndof); const auto &bounds = element.bounds(); _map = std::make_pair((bounds.second - bounds.first) / 2, (bounds.first + bounds.second) / 2); } inline auto FeElement::degree() const -> int { return _degree; } inline auto FeElement::ndof() const -> int { return _dof.size(); } inline auto FeElement::dof() const -> const std::vector<int> & { return _dof; } inline auto FeElement::dof(int i) const -> int { return _dof[i]; } inline auto FeElement::diameter() const -> scalar_t { return _diameter; } inline void FeElement::diameter(scalar_t diameter) { _diameter = diameter; } inline auto FeElement::triangulation() const -> const Triangulation<Element> & { assert(!_triangulation.empty()); return _triangulation; } inline void FeElement::triangulate() { _triangulation = std::move(Triangulation<Element>(_element)); } inline auto FeElement::map(const point_t &x) const -> point_t { return (x - _map.second).array() / _map.first.array(); } inline auto FeElement::jacobian() const -> const point_t & { return _map.first; } constexpr auto FeElement::_compute_ndof(int dim, int degree) -> int { return utl::factorial(degree + dim) / utl::factorial(degree) / utl::factorial(dim); } inline auto FeElement::eval_basis(int i, const point_t &x) const -> scalar_t { return legendre::normalization(i) * legendre::phi(i, x); } inline auto FeElement::eval_basis_derivatives(int i, const point_t &x) const -> point_t { return point_t{ legendre::normalization(i) * legendre::phix(i, x) / jacobian()[0], legendre::normalization(i) * legendre::phiy(i, x) / jacobian()[1], legendre::normalization(i) * legendre::phiz(i, x) / jacobian()[2]}; } template <typename Points> inline auto FeElement::eval_basis(const Points &points) const -> std::vector<scalar_t> { int npoints = points.size(); std::vector<scalar_t> phi; phi.reserve(ndof() * npoints); for (int i = 0; i < ndof(); ++i) { for (int q = 0; q < npoints; ++q) { phi.emplace_back(eval_basis(i, points[q])); } } return phi; } template <typename Points> inline auto FeElement::eval_basis_derivatives(const Points &points) const -> std::vector<point_t> { int npoints = points.size(); std::vector<point_t> dphi; dphi.reserve(ndof() * npoints); for (int i = 0; i < ndof(); ++i) { for (int q = 0; q < npoints; ++q) { dphi.emplace_back(eval_basis_derivatives(i, points[q])); } } return dphi; } } // namespace wave
[ "luca.mobz.work@gmail.com" ]
luca.mobz.work@gmail.com
d82dd48e9680835ee72b2f9902a1cebdd9dc4698
1af43c4ba32d78c60f007a4d068136ce575d917f
/system/apps_ds213/118_dht_app/source/Pin.h
38f9f74df59a22f299ade89657b09fb80307e05d
[ "MIT" ]
permissive
gabonator/LA104
a4f1cdf2b3e513300d61c50fff091c5717abda9e
27d0eece7302c479da2cf86e881b6a51a535f93d
refs/heads/master
2023-08-31T22:09:36.272616
2023-08-27T20:08:08
2023-08-27T20:08:08
155,659,451
500
69
MIT
2023-08-17T08:44:32
2018-11-01T03:54:21
C
UTF-8
C++
false
false
1,559
h
#pragma once #include <library.h> class CPin { BIOS::ADC::EInput m_pin; public: void Create( BIOS::ADC::EInput input ) { //Setup ADC BIOS::ADC::Enable( true ); BIOS::ADC::ConfigureInput( BIOS::ADC::EInput::CH1, BIOS::ADC::ECouple::DC, BIOS::ADC::EResolution::_1V , 105*4); BIOS::ADC::ConfigureInput( BIOS::ADC::EInput::CH2, BIOS::ADC::ECouple::DC, BIOS::ADC::EResolution::_1V , 122*4); BIOS::ADC::ConfigureTimebase(50e-6f); // BIOS::ADC::ConfigureBuffer( arrLen[ (NATIVEENUM)Settings.Time.Resolution ] ); BIOS::ADC::Restart(0); BIOS::ADC::ConfigureTrigger(0, 0, BIOS::ADC::ETriggerType::None, BIOS::ADC::EInput::CH1 ); m_pin = input; } //ADC Cant output void High() { BIOS::DAC::SetMode(BIOS::DAC::EMode::LogicHigh, 0, 0); //BIOS::GPIO::PinMode(m_pin, BIOS::GPIO::Output); //BIOS::GPIO::DigitalWrite(m_pin, true); } void Low() { BIOS::DAC::SetMode(BIOS::DAC::EMode::LogicLow, 0, 0); //BIOS::GPIO::PinMode(m_pin, BIOS::GPIO::Output); //BIOS::GPIO::DigitalWrite(m_pin, false); } void Float() { //Low(); BIOS::DAC::SetMode(BIOS::DAC::EMode::LogicHigh, 0, 0); } /*bool Get() { data = BIOS::ADC::Get(); ch1 = (uint8_t)((data) & 0xff); //BIOS::DBG::Print("#%d#\n", ch1); BIOS::ADC::Restart(0); return (ch1 > 15) ? true : false; }*/ void operator =(bool b) { if (b) Float(); else High(); } /*operator const bool () { return Get(); }*/ };
[ "noreply@github.com" ]
noreply@github.com
0e93cc99f129d981cea6d3dcf60c8f4a758d683e
e8f97f496935d90f841f40a6292a0a24f0877aa5
/src/mouse.cpp
6b4982415cfd506843ba71d5c632dbe85e8ba5d2
[ "MIT" ]
permissive
johnfredcee/meistravimas
65d81609bc798c732748f6f6e9db38341063d5ec
4ee3168518525db0d3eddde5008115fc874dc249
refs/heads/master
2021-05-25T09:44:38.453184
2020-08-02T13:42:27
2020-08-02T13:42:27
31,008,802
0
0
null
null
null
null
UTF-8
C++
false
false
2,375
cpp
#include <SDL.h> #include <SDL_opengl.h> #include <string> #include <unordered_map> #include <iostream> #include <memory> #include <vector> #include <functional> #include "observer.h" #include "hashstring.h" #include "locator.h" #include "servicecounter.h" #include "service.h" #include "servicecheckout.h" #include "mouse.h" namespace venk { // service bool MouseService::initialise(MouseService* self) { if (self != nullptr) { self->state = new Mouse(); self->state->x = 0; self->state->y = 0; self->state->dx = 0; self->state->dy = 0; self->state->firstsample = true; self->state->sampleTime = SDL_GetTicks() / 1000.0f; self->state->wheel = 0; } return true; } bool MouseService::shutdown(MouseService* self) { if ( self != nullptr ) { delete self->state; } return true; } void MouseService::sample() { SDL_Event event; SDL_MouseMotionEvent *mouseMotionEvent; SDL_MouseButtonEvent *mouseButtonEvent; SDL_MouseWheelEvent *mouseWheelEvent; double sampleTime; state->dx = 0.0f; state->dy = 0.0f; while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_MOUSEMOTION, SDL_MOUSEWHEEL)) { switch (event.type) { case SDL_MOUSEMOTION: mouseMotionEvent = (SDL_MouseMotionEvent*)(&event); if (!state->firstsample) { state->dx = (float)( mouseMotionEvent->xrel ) * (sampleTime - mouseMotionEvent->timestamp) * 0.001f; state->dy = (float)( mouseMotionEvent->yrel ) * (sampleTime - mouseMotionEvent->timestamp) * 0.001f; } else { state->firstsample = false; sampleTime = mouseMotionEvent->timestamp; } state->sampleTime = sampleTime; state->x = mouseMotionEvent->x; state->y = mouseMotionEvent->y; observers.notify(&event); break; case SDL_MOUSEBUTTONUP: mouseButtonEvent = (SDL_MouseButtonEvent*)(&event); state->buttons[mouseButtonEvent->button] = SDL_RELEASED; observers.notify(&event); break; case SDL_MOUSEBUTTONDOWN: mouseButtonEvent = (SDL_MouseButtonEvent*)(&event); state->buttons[mouseButtonEvent->button] = SDL_PRESSED; observers.notify(&event); break; case SDL_MOUSEWHEEL: mouseWheelEvent = (SDL_MouseWheelEvent*)(&event); state->wheel += mouseWheelEvent->y; observers.notify(&event); break; } } } const Mouse& MouseService::mouse() { sample(); return *state; } }
[ "johnc@yagc.ndo.co.uk" ]
johnc@yagc.ndo.co.uk
86b65a8549459c4d654972088d70914105493b70
ae16c2c158968d270b48e19a50f43a4a93e36740
/repeatedDNA.cpp
dd0354f1367a5f800445cba61894fdf27caf3303
[]
no_license
Sanchit8146/ProgrammingQuestionsCpp
c8e533a8508892ac88146d0b50d7c099e732d484
e0ff6dd06c887a640402f14df6e25242f4fc606d
refs/heads/master
2023-09-03T13:07:42.860775
2021-10-30T10:42:02
2021-10-30T10:42:02
422,846,381
0
0
null
2021-10-30T10:13:03
2021-10-30T10:13:02
null
UTF-8
C++
false
false
491
cpp
vector<string> findRepeatedDnaSequences(string s) { // Hashmap based solution O(N) Time and O(N) Space vector<string> res; if(s.size()<=10) return res; unordered_map<string,int> m; for(int i=0;i<s.size()-9;i++){ m[s.substr(i,10)]++; } for(auto i:m){ if(i.second > 1){ res.emplace_back(i.first); } } return res; }
[ "noreply@github.com" ]
noreply@github.com
4671dc7b517bbe5684681fb8501103ca099a42ed
99eba6b9d3ce45d73d41502c55df0be282b4f4a3
/OnlineJudge/BOJ/1000/1009.cpp
a6203ede1acea31c60ed9a99d6161eb51d24ea74
[]
no_license
hajindvlp/Algorithm
ad7268b468c162bb9244d09b7c7f269c61bcacf9
f9b4b530a177013f386d4f7f1f038c006ccbd9f0
refs/heads/master
2021-06-28T21:13:25.849062
2020-11-06T10:14:02
2020-11-06T10:14:02
172,189,561
1
0
null
null
null
null
UTF-8
C++
false
false
343
cpp
#include <cstdio> using namespace std; int T, a, b, res; int main() { scanf("%d", &T); while (T--) { res = 1; scanf("%d %d", &a, &b); while (b--) { res = res * a % 10; } if (res == 0) printf("10\n"); else printf("%d\n", res); } return 0; }
[ "harryhajinchung@gmail.com" ]
harryhajinchung@gmail.com
ca1f5b73fec4a9d519ecb440e2a80a1a7478ea1d
7c63a96fad4257f4959ffeba0868059fc96566fb
/cpp/std-14/m_gregoire-prof_cpp-3_ed/ch_09-discovering_inheritance_techniques/01-extending_classes/Super.hpp
6196a10457ba83de3ddee7a99363d00eb2016b70
[ "MIT" ]
permissive
ordinary-developer/education
b426148f5690f48e0ed4853adfc3740bd038b72c
526e5cf86f90eab68063bb7c75744226f2c54b8d
refs/heads/master
2023-08-31T14:42:37.237690
2023-08-30T18:15:18
2023-08-30T18:15:18
91,232,306
8
0
null
null
null
null
UTF-8
C++
false
false
206
hpp
#ifndef SUPER_HPP #define SUPER_HPP class Super { public: Super(); virtual void someMethod(); protected: int mProtectedInt; private: int mPrivateInt; }; #endif
[ "merely.ordinary.developer@gmail.com" ]
merely.ordinary.developer@gmail.com
18af51ea60b95942c9369fecc2864349b82f9c35
115eff10a93f64f24640dd1e68e970247153f4c3
/testsuite/sort_array.cpp
27750550756ac7b7f0642910c4098a0607e7eee5
[ "MIT" ]
permissive
OptimalBucket/cpp-sort
e40cf59c927ce74650e5ba4ac491bd9a8a035e78
57aaff88e7b135b07ebf9362435160b905f41e3d
refs/heads/master
2020-04-01T10:56:16.241020
2018-07-13T08:06:26
2018-07-13T08:06:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,988
cpp
/* * The MIT License (MIT) * * Copyright (c) 2018 Morwenn * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <functional> #include <catch.hpp> #include <cpp-sort/sort.h> #include <cpp-sort/sorters/selection_sorter.h> #include <cpp-sort/utility/functional.h> #include "algorithm.h" TEST_CASE( "test sorting C arrays", "[sort]" ) { int arr[] = { 8, 1, 6, 7, 3, 5, 4, 9, 2 }; SECTION( "without anything" ) { cppsort::sort(arr); CHECK( helpers::is_sorted(std::begin(arr), std::end(arr)) ); } SECTION( "with comparison function" ) { cppsort::sort(arr, std::greater<>{}); CHECK( helpers::is_sorted(std::begin(arr), std::end(arr), std::greater<>{}) ); } SECTION( "with projection function" ) { cppsort::sort(arr, std::negate<>{}); CHECK( helpers::is_sorted(std::begin(arr), std::end(arr), std::greater<>{}) ); } SECTION( "with comparison and projection functions" ) { cppsort::sort(arr, std::greater<>{}, std::negate<>{}); CHECK( helpers::is_sorted(std::begin(arr), std::end(arr)) ); } SECTION( "with sorter" ) { cppsort::sort(cppsort::selection_sort, arr); CHECK( helpers::is_sorted(std::begin(arr), std::end(arr)) ); } SECTION( "with sorter and comparison function" ) { cppsort::sort(cppsort::selection_sort, arr, std::greater<>{}); CHECK( helpers::is_sorted(std::begin(arr), std::end(arr), std::greater<>{}) ); } SECTION( "with sorter and projection function" ) { cppsort::sort(cppsort::selection_sort, arr, std::negate<>{}); CHECK( helpers::is_sorted(std::begin(arr), std::end(arr), std::greater<>{}) ); } SECTION( "with sorter, comparison and projection function" ) { cppsort::sort(cppsort::selection_sort, arr, std::greater<>{}, std::negate<>{}); CHECK( helpers::is_sorted(std::begin(arr), std::end(arr)) ); } }
[ "morwenn29@hotmail.fr" ]
morwenn29@hotmail.fr
cbb29f4dd94f04e2234271a87d0f26c9a3b7e15e
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/14_4601_8.cpp
25cdabc8027eb77e4c41471c2ee632114ebeaee4
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
554
cpp
#include<iostream> #include<algorithm> #include<vector> #include<array> using namespace std; #define FOR(a,b,c) for(a = b;a < c;a++) #define REP(a,b) FOR(a,0,b) #define BG begin() #define ED end() vector <array <int, 1001>> andr(1001); int main() { int t, test, a, b, k, i, j, cnt; REP(i, 1001) REP(j, 1001) andr[i][j] = i & j; cin >> t; REP(test, t) { cnt = 0; cin >> a >> b >> k; REP(i, a) REP(j, b) if(andr[i][j] < k) cnt++; cout << "Case #" << test + 1 << ": " << cnt << endl; } }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
648bbf963a0b53bc706d13bbc3cb13e94562b5cc
9a1fba32fe46c41b450222e6f45408e53d9b6c23
/libs/androidfw/tests/ThemesIdmap_test.cpp
50f16c8ed24666334dbd28b70488572c1c98c9e8
[ "Apache-2.0", "LicenseRef-scancode-unicode" ]
permissive
FireHound/android_frameworks_base
779dda285e75a615d75150b8c10c21d13fa3e731
e9d54decbb07004f74e78b57f095f614362828b5
refs/heads/mm
2021-11-26T05:13:54.745879
2016-09-10T05:37:47
2016-12-18T06:50:12
64,948,641
4
38
NOASSERTION
2020-03-14T21:24:38
2016-08-04T16:06:28
Java
UTF-8
C++
false
false
4,406
cpp
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <androidfw/ResourceTypes.h> #include <utils/String8.h> #include <utils/String16.h> #include "TestHelpers.h" #include "data/cm/basic/R.h" #include <gtest/gtest.h> using namespace android; namespace { /** * Include a binary resource table. * * Package: com.android.test.basic */ #include "data/cm/basic/basic_arsc.h" /** * Include a binary resource table. * This table is an overlay. * * Package: com.android.test.basic */ #include "data/cm/overlay/overlay_arsc.h" enum { MAY_NOT_BE_BAG = false }; class IdmapTest : public ::testing::Test { protected: virtual void SetUp() { ASSERT_EQ(NO_ERROR, mTargetTable.add(basic_arsc, basic_arsc_len)); ASSERT_EQ(NO_ERROR, mOverlayTable.add(overlay_arsc, overlay_arsc_len)); char targetName[256] = "com.android.test.basic"; ASSERT_EQ(NO_ERROR, mTargetTable.createIdmap(mOverlayTable, 0, 0, 0, 0, targetName, targetName, &mData, &mDataSize)); } virtual void TearDown() { free(mData); } ResTable mTargetTable; ResTable mOverlayTable; void* mData; size_t mDataSize; }; TEST_F(IdmapTest, canLoadIdmap) { ASSERT_EQ(NO_ERROR, mTargetTable.add(overlay_arsc, overlay_arsc_len, mData, mDataSize)); } TEST_F(IdmapTest, overlayOverridesResourceValue) { Res_value val; ssize_t block = mTargetTable.getResource(base::R::dimen::dimen1, &val, false); ASSERT_GE(block, 0); ASSERT_EQ(Res_value::TYPE_DIMENSION, val.dataType); ASSERT_NE(val.data, 0); ASSERT_EQ(NO_ERROR, mTargetTable.add(overlay_arsc, overlay_arsc_len, mData, mDataSize)); Res_value newVal; ssize_t newBlock = mTargetTable.getResource(base::R::dimen::dimen1, &newVal, false); ASSERT_GE(newBlock, 0); ASSERT_NE(block, newBlock); ASSERT_EQ(Res_value::TYPE_DIMENSION, newVal.dataType); ASSERT_NE(val.data, newVal.data); } TEST_F(IdmapTest, overlaidResourceHasSameName) { ASSERT_EQ(NO_ERROR, mTargetTable.add(overlay_arsc, overlay_arsc_len, mData, mDataSize)); ResTable::resource_name resName; ASSERT_TRUE(mTargetTable.getResourceName(base::R::drawable::drawable1, false, &resName)); ASSERT_TRUE(resName.package != NULL); ASSERT_TRUE(resName.type != NULL); ASSERT_TRUE(resName.name != NULL); EXPECT_EQ(String16("com.android.test.basic"), String16(resName.package, resName.packageLen)); EXPECT_EQ(String16("drawable"), String16(resName.type, resName.typeLen)); EXPECT_EQ(String16("drawable1"), String16(resName.name, resName.nameLen)); } TEST_F(IdmapTest, overlayDoesNotOverlayStringResource) { Res_value val; ssize_t block = mTargetTable.getResource(base::R::string::test2, &val, false); ASSERT_GE(block, 0); ASSERT_EQ(Res_value::TYPE_STRING, val.dataType); const ResStringPool* pool = mTargetTable.getTableStringBlock(block); ASSERT_TRUE(pool != NULL); ASSERT_LT(val.data, pool->size()); size_t strLen; const char16_t* targetStr16 = pool->stringAt(val.data, &strLen); ASSERT_TRUE(targetStr16 != NULL); ASSERT_EQ(String16("test2"), String16(targetStr16, strLen)); ASSERT_EQ(NO_ERROR, mTargetTable.add(overlay_arsc, overlay_arsc_len, mData, mDataSize)); ssize_t newBlock = mTargetTable.getResource(base::R::string::test2, &val, false); ASSERT_GE(newBlock, 0); ASSERT_EQ(block, newBlock); // the above check should be enough but just to be sure we'll check the string ASSERT_EQ(Res_value::TYPE_STRING, val.dataType); pool = mTargetTable.getTableStringBlock(newBlock); ASSERT_TRUE(pool != NULL); ASSERT_LT(val.data, pool->size()); targetStr16 = pool->stringAt(val.data, &strLen); ASSERT_TRUE(targetStr16 != NULL); ASSERT_EQ(String16("test2"), String16(targetStr16, strLen)); } } // namespace
[ "clark@cyngn.com" ]
clark@cyngn.com
1123b58b2a7c7f90b35199236838fefc3ca82854
799d21efc423e5b8ea223afcf43a0ee67aa6bdbd
/common/includes/systems/IManager.hpp
d272a6b4f4402655d36babaa26feacedadd55a5d
[]
no_license
brucelevis/CPP-RType
8af517a1a167bbc39cf0cc8d45a8eba1468c2b69
ffe247694cdc61677c1546a3f5ac6ec336a44570
refs/heads/main
2023-02-08T09:29:23.594952
2021-01-05T15:36:41
2021-01-05T15:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
505
hpp
/* ** EPITECH PROJECT, 2020 ** B-CPP-501-PAR-5-1-rtype-aurele.auboin ** File description: ** System IManager */ #ifndef COMMONSYSTEMIMANAGER_HPP_ #define COMMONSYSTEMIMANAGER_HPP_ #include <string> #include <vector> #include "components/AManager.hpp" namespace rtype { namespace system { class IManager { public: virtual ~IManager() = default; virtual void loop(void) = 0; }; } } #endif /* !COMMONSYSTEMIMANAGER_HPP_ */
[ "46068106+AntoinePoisson@users.noreply.github.com" ]
46068106+AntoinePoisson@users.noreply.github.com
71e5b497cdf2bc6bc80ef357ff27ea97e0b990d9
aaa9c31f2d22650cbbd59c69114521641057bce4
/UVA/UVA 11997.cpp
716519f6e0ca69d9fb1a440d5da73a11e0a9dc0a
[]
no_license
ahmedsamir221/CompetitiveProgramming
501adbe01d37f0129516065f592d8eb79776c53c
bbd8af4e6c146e523d129ee16ade58eeacbd05b6
refs/heads/master
2020-04-09T04:00:57.861432
2020-03-18T16:20:56
2020-03-18T16:20:56
160,006,969
0
1
null
null
null
null
UTF-8
C++
false
false
1,745
cpp
//https://ideone.com/Vyo2Z5 #include<stdio.h> #include<vector> #include<algorithm> #include <iostream> #include <cmath> #include <complex> #include<queue> #include <string> #include<bits/stdc++.h> #define pi 3.141592654 #define forr(i,a,b) for(int i=a;i<=b;i++) #define F first #define S second #define input ios_base::sync_with_stdio(0);cin.tie(0); //#define x real() //#define y imag() using namespace std; typedef pair<double,double>pdd; typedef long long ll; typedef pair<ll, ll>pii; //typedef complex<double> point; //template<typename T>T gcd(T x, T y) { if(y == 0)return x; else return gcd(y, x%y); } //typedef bitset<30> mask; //int x[8]={1,0,0,-1,-1,-1,1,1}; //int y[8]={0,1,-1,0,-1,1,-1,1}; //const double PI = acos(-1.0); //const double EPS = 1e-9; //typedef complex<double> point; ll k,a[760][760]; int main() { //cout<<Pow((ll)1000000,(ll)110); //freopen("CAMP.IN","r",stdin); //freopen("CAMP.OUT","w",stdout); // char input[15]; // scanf("%s", &input); array of char // gets(c+1); array of char input; while(cin>>k) { forr(i,1,k) { forr(j,1,k)cin>>a[i][j]; sort(a[i]+1,a[i]+1+k); } vector<ll>v; forr(i,1,k)v.push_back(a[1][i]); forr(i,2,k) { priority_queue<ll>q; forr(j,1,k) { for(auto p:v) { if(q.size()<k)q.push(p+a[i][j]); else if(p+a[i][j]<q.top()) { q.pop(); q.push(p+a[i][j]); } else break; } } v.clear(); while(q.size())v.push_back(q.top()),q.pop(); reverse(v.begin(),v.end()); } forr(i,0,k-2)cout<<v[i]<<" "; cout<<v[k-1]<<endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
ca6ad0b1935c6af65241fa6f5e9e4a6ba2c3224d
a11f71993b2c99e0066be26e5f19caf23f9078b2
/src/ArduinoOcpp/MessagesV16/DataTransfer.h
ed3723a60376357ce8245ab90e12990fa7c6a9cf
[ "MIT" ]
permissive
swap-kazam/ArduinoOcpp
8b12f609085f36c886039fe0b9c1d659afba4da4
8331cc6fb722e8bbb5b43661c93b3590f2747df6
refs/heads/master
2023-08-18T01:42:47.453612
2021-10-14T13:32:13
2021-10-14T13:32:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
503
h
// matth-x/ArduinoOcpp // Copyright Matthias Akstaller 2019 - 2021 // MIT License #ifndef DATATRANSFER_H #define DATATRANSFER_H #include <ArduinoOcpp/Core/OcppMessage.h> namespace ArduinoOcpp { namespace Ocpp16 { class DataTransfer : public OcppMessage { private: String msg; public: DataTransfer(String &msg); const char* getOcppOperationType(); DynamicJsonDocument* createReq(); void processConf(JsonObject payload); }; } //end namespace Ocpp16 } //end namespace ArduinoOcpp #endif
[ "63792403+matth-x@users.noreply.github.com" ]
63792403+matth-x@users.noreply.github.com
c125a58b5616b0cd94ee139defe6a8d798732d8b
ad378a3d14b53b0cda7799ec3a7ac5254d577621
/include/macro/EnableIf.h
ca44a905777f752a14150a7700acf32eaa2cd92d
[ "MIT" ]
permissive
AnantaYudica/basic
2f537a3eda8f108ed79a8594c87c160beb0b1984
dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950
refs/heads/master
2021-07-10T01:50:46.784042
2020-06-17T08:21:37
2020-06-17T08:21:37
139,540,770
0
0
null
null
null
null
UTF-8
C++
false
false
7,256
h
#ifndef BASIC_MACRO_ENABLEIF_H_ #define BASIC_MACRO_ENABLEIF_H_ #define __DEFINE_ENABLE_IF_TMPL_PARAM_LIST_PRIMARY_(\ __T_NAME__,\ __T_OUT_NAME__)\ typename __T_NAME__, typename __T_OUT_NAME__ = void #define __DEFINE_ENABLE_IF_TMPL_PARAM_LIST_SPECIALIZED_(\ __T_NAME__,\ __T_OUT_NAME__)\ typename __T_NAME__, typename __T_OUT_NAME__ #define __DEFINE_ENABLE_IF_TMPL_PARAM_PRIMARY_(\ __BOOL_TEST_NAME__,\ __T_NAME__,\ __T_OUT_NAME__,\ __TMPL_PARAM_LIST_PRIMARY_POSTFIX__,\ __TMPL_PARAM_LIST_SPECIALIZED_POSTFIX__,\ __CONDITIONAL__, ...)\ bool __BOOL_TEST_NAME__, __DEFINE_ENABLE_IF_TMPL_PARAM_LIST_PRIMARY_\ ##__TMPL_PARAM_LIST_PRIMARY_POSTFIX__(__T_NAME__, __T_OUT_NAME__),\ bool = __CONDITIONAL__,##__VA_ARGS__ #define __DEFINE_ENABLE_IF_TMPL_PARAM_SPECIALIZED_(\ __BOOL_TEST_NAME__,\ __T_NAME__,\ __T_OUT_NAME__,\ __TMPL_PARAM_LIST_PRIMARY_POSTFIX__,\ __TMPL_PARAM_LIST_SPECIALIZED_POSTFIX__,\ __CONDITIONAL__, ...)\ __DEFINE_ENABLE_IF_TMPL_PARAM_LIST_SPECIALIZED_\ ##__TMPL_PARAM_LIST_SPECIALIZED_POSTFIX__(__T_NAME__, __T_OUT_NAME__) #define __DEFINE_ENABLE_IF_TMPL_ARG_LIST_(\ __T_NAME__,\ __T_OUT_NAME__)\ __T_NAME__, __T_OUT_NAME__ #define __DEFINE_ENABLE_IF_TMPL_ARG_LIST_PRIMARY_(...) #define __DEFINE_ENABLE_IF_TMPL_ARG_LIST_SPECIALIZED_(\ __T_NAME__,\ __T_OUT_NAME__,\ __TEST_BOOL__,\ __CONDITIONAL_BOOL__,\ __TMPL_ARG_LIST_POSTFIX__)\ <__TEST_BOOL__, __DEFINE_ENABLE_IF_TMPL_ARG_LIST_\ ##__TMPL_ARG_LIST_POSTFIX__(__T_NAME__, __T_OUT_NAME__),\ __CONDITIONAL_BOOL__> #define __DEFINE_ENABLE_IF_T_OUT_NAME_(\ __T_OUT_NAME__,...)\ __T_OUT_NAME__ #define __DEFINE_ENABLE_IF_T_OUT_NAME_TMPL_(\ __T_OUT_NAME__,\ __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__)\ __T_OUT_NAME__<__DEFINE_ENABLE_IF_T_OUT_NAME_TMPL_ARG_LIST_\ ##__T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__()> #define __DEFINE_ENABLE_IF_ALIAS_TYPE_PRIMARY_(\ __ALIAS_TYPE_NAME__,\ __T_OUT_NAME__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__,\ __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__, ...)\ using __ALIAS_TYPE_NAME__ = __DEFINE_ENABLE_IF_\ ##__T_OUT_NAME_OR_T_OUT_NAME_TMPL__(__T_OUT_NAME__,\ __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__) #define __DEFINE_ENABLE_IF_ALIAS_TYPE_TMPL_PRIMARY_(\ __ALIAS_TYPE_NAME__,\ __T_OUT_NAME__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__,\ __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__,\ __ALIAS_TYPE_TMPL_PARAM_LIST_POSTFIX__)\ template<__DEFINE_ENABLE_IF_ALIAS_TYPE_TMPL_PARAM_LIST_\ ##__ALIAS_TYPE_TMPL_PARAM_LIST_POSTFIX__()>\ __DEFINE_ENABLE_IF_ALIAS_TYPE_PRIMARY_(__ALIAS_TYPE_NAME__, __T_OUT_NAME__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__, __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__) #define __DEFINE_ENABLE_IF_ALIAS_TYPE_SPECIALIZED_(...) #define __DEFINE_ENABLE_IF_ALIAS_TYPE_TMPL_SPECIALIZED_(...) #define __DEFINE_ENABLE_IF_STATIC_ASSERT_PRIMARY_(\ __BOOL_TEST_NAME__,\ __CONDITIONAL__, ...)\ static_assert(__BOOL_TEST_NAME__ && (__CONDITIONAL__,##__VA_ARGS__),\ "false condition not implementation"); #define __DEFINE_ENABLE_IF_STATIC_ASSERT_SPECIALIZED_(...) #define __DEFINE_ENABLE_IF_STRUCT_(\ __STRUCT_NAME__,\ __BOOL_TEST_NAME__,\ __T_NAME__,\ __T_OUT_NAME__,\ __TEST_BOOL__,\ __CONDITIONAL_BOOL__,\ __PRIMARY_OR_SPECIALIZED__,\ __TMPL_PARAM_LIST_PRIMARY_POSTFIX__,\ __TMPL_PARAM_LIST_SPECIALIZED_POSTFIX__,\ __TMPL_ARG_LIST_POSTFIX__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__,\ __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__,\ __ALIAS_TYPE_OR_ALIAS_TYPE_TMPL,\ __ALIAS_TYPE_TMPL_PARAM_LIST_POSTFIX__,\ __CONDITIONAL__,...)\ template<__DEFINE_ENABLE_IF_TMPL_PARAM_\ ##__PRIMARY_OR_SPECIALIZED__(__BOOL_TEST_NAME__, __T_NAME__,\ __T_OUT_NAME__, __TMPL_PARAM_LIST_PRIMARY_POSTFIX__,\ __TMPL_PARAM_LIST_SPECIALIZED_POSTFIX__,\ __CONDITIONAL__,##__VA_ARGS__)>\ struct __STRUCT_NAME__ __DEFINE_ENABLE_IF_TMPL_ARG_LIST_\ ##__PRIMARY_OR_SPECIALIZED__(__T_NAME__, __T_OUT_NAME__,\ __TEST_BOOL__, __CONDITIONAL_BOOL__, __TMPL_ARG_LIST_POSTFIX__)\ {\ __DEFINE_ENABLE_IF_STATIC_ASSERT_##__PRIMARY_OR_SPECIALIZED__(\ __BOOL_TEST_NAME__, __CONDITIONAL__,##__VA_ARGS__)\ __DEFINE_ENABLE_IF_##__ALIAS_TYPE_OR_ALIAS_TYPE_TMPL\ ##__PRIMARY_OR_SPECIALIZED__(type, __T_OUT_NAME__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__,\ __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__,\ __ALIAS_TYPE_TMPL_PARAM_LIST_POSTFIX__);\ __DEFINE_ENABLE_IF_##__ALIAS_TYPE_OR_ALIAS_TYPE_TMPL\ ##__PRIMARY_OR_SPECIALIZED__(Type, __T_OUT_NAME__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__,\ __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__,\ __ALIAS_TYPE_TMPL_PARAM_LIST_POSTFIX__);\ } #define __DEFINE_ENABLE_IF_(\ __STRUCT_NAME__,\ __BOOL_TEST_NAME__,\ __T_NAME__,\ __T_OUT_NAME__,\ __TMPL_PARAM_LIST_PRIMARY_POSTFIX__,\ __TMPL_PARAM_LIST_SPECIALIZED_POSTFIX__,\ __TMPL_ARG_LIST_POSTFIX__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__,\ __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__,\ __ALIAS_TYPE_OR_ALIAS_TYPE_TMPL,\ __ALIAS_TYPE_TMPL_PARAM_LIST_POSTFIX__,\ __CONDITIONAL__, ...)\ __DEFINE_ENABLE_IF_STRUCT_(__STRUCT_NAME__, __BOOL_TEST_NAME__, __T_NAME__,\ __T_OUT_NAME__,,, PRIMARY_,\ __TMPL_PARAM_LIST_PRIMARY_POSTFIX__,\ __TMPL_PARAM_LIST_SPECIALIZED_POSTFIX__, __TMPL_ARG_LIST_POSTFIX__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__, __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__,\ __ALIAS_TYPE_OR_ALIAS_TYPE_TMPL, __ALIAS_TYPE_TMPL_PARAM_LIST_POSTFIX__,\ __CONDITIONAL__,##__VA_ARGS__);\ __DEFINE_ENABLE_IF_STRUCT_(__STRUCT_NAME__, __BOOL_TEST_NAME__, __T_NAME__,\ __T_OUT_NAME__, true, false, SPECIALIZED_,\ __TMPL_PARAM_LIST_PRIMARY_POSTFIX__,\ __TMPL_PARAM_LIST_SPECIALIZED_POSTFIX__, __TMPL_ARG_LIST_POSTFIX__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__, __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__,\ __ALIAS_TYPE_OR_ALIAS_TYPE_TMPL, __ALIAS_TYPE_TMPL_PARAM_LIST_POSTFIX__,\ __CONDITIONAL__,##__VA_ARGS__);\ __DEFINE_ENABLE_IF_STRUCT_(__STRUCT_NAME__, __BOOL_TEST_NAME__, __T_NAME__,\ __T_OUT_NAME__, false, true, SPECIALIZED_,\ __TMPL_PARAM_LIST_PRIMARY_POSTFIX__,\ __TMPL_PARAM_LIST_SPECIALIZED_POSTFIX__, __TMPL_ARG_LIST_POSTFIX__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__, __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__,\ __ALIAS_TYPE_OR_ALIAS_TYPE_TMPL, __ALIAS_TYPE_TMPL_PARAM_LIST_POSTFIX__,\ __CONDITIONAL__,##__VA_ARGS__);\ __DEFINE_ENABLE_IF_STRUCT_(__STRUCT_NAME__, __BOOL_TEST_NAME__, __T_NAME__,\ __T_OUT_NAME__, false, false, SPECIALIZED_,\ __TMPL_PARAM_LIST_PRIMARY_POSTFIX__,\ __TMPL_PARAM_LIST_SPECIALIZED_POSTFIX__, __TMPL_ARG_LIST_POSTFIX__,\ __T_OUT_NAME_OR_T_OUT_NAME_TMPL__, __T_OUT_NAME_TMPL_ARG_LIST_POSTFIX__,\ __ALIAS_TYPE_OR_ALIAS_TYPE_TMPL, __ALIAS_TYPE_TMPL_PARAM_LIST_POSTFIX__,\ __CONDITIONAL__,##__VA_ARGS__) #define __DEFINE_ENABLE_IF_DEFAULT_(\ __STRUCT_NAME__,\ __BOOL_TEST_NAME__,\ __T_NAME__,\ __T_OUT_NAME__,\ __CONDITIONAL__, ...)\ __DEFINE_ENABLE_IF_(__STRUCT_NAME__, __BOOL_TEST_NAME__, __T_NAME__,\ __T_OUT_NAME__,,,, T_OUT_NAME_,, ALIAS_TYPE_,,\ __CONDITIONAL__,##__VA_ARGS__) #endif //!BASIC_MACRO_ENABLEIF_H_
[ "nta040689@gmail.com" ]
nta040689@gmail.com
eed6c6b1aa8a458b6d04ab9d2cc02e4c6e367d85
bf6f83428c02d8e0d349e9af0c17219ad4a7de3f
/TempConvert.ino
3fa111c2a95776514b0e2804256e75c835169d30
[]
no_license
GeneralBen/Arduino_Sketches
c6bafc19ed455d6fa33946c5ce9ce8e3cc3f67f3
c8416bf9842fe08bfb1eb9462ec1f71abdb10148
refs/heads/master
2021-01-18T03:58:41.955366
2016-03-19T01:25:59
2016-03-19T01:25:59
54,513,070
0
0
null
2016-03-22T22:30:33
2016-03-22T22:30:33
null
UTF-8
C++
false
false
623
ino
/*This application is intended to convert an integer temperature in degrees Celcius to degrees Fahreheit. Developer: Wes Urbat Last Modified: 03.16.16*/ void setup() { Serial.begin(9600); //Opens a serial connection at a baud rate of 9600 bps (bits per second) int degC = 20; //Declare local "setup" variable and assign initial value. int degF = ((degC * 9) / 5) + 32; // Declare local "setup" variable "degF" and assign value based on C to F conversion. Serial.println(degF); //print the result via serial (USB) to output window on PC. } void loop() { /* Empty, no continuous code. */ }
[ "thought_chasm@yahoo.com" ]
thought_chasm@yahoo.com
3c61ab463a8d311c24eaec723811160d26100044
043310689885c97b6c07124c125b7b8f5c7a4d7c
/src/sendmsg.hpp
827b0f8288fc77f1c70ddfd37389941414857fb8
[]
no_license
OpenWoS/ReMix
fbc857e91e90ac0b66afb3dc43d396b082f80e8b
4b177f97500a0e01f7c9e51cc6a9d790a2e05557
refs/heads/main
2023-03-23T12:52:09.415294
2020-10-14T16:16:57
2020-10-14T16:16:57
345,446,428
0
0
null
null
null
null
UTF-8
C++
false
false
610
hpp
#ifndef SENDMSG_HPP #define SENDMSG_HPP #include "prototypes.hpp" //Required Qt Includes. #include <QDialog> namespace Ui { class SendMsg; } class SendMsg : public QDialog { Q_OBJECT public: explicit SendMsg(const QString& serNum, QWidget* parent = nullptr); ~SendMsg() override; bool sendToAll() const; private: bool eventFilter(QObject* obj, QEvent* event) override; private slots: void on_sendMsg_clicked(); signals: void forwardMessageSignal(const QString&); private: Ui::SendMsg* ui; }; #endif // SENDMSG_HPP
[ "StarixWoS@gmail.com" ]
StarixWoS@gmail.com
92a9bf44474010711adc3543904ccdc23c003852
175e294d66ab54fb1897a7371881e51882641b56
/BattleGame/Weapons.cpp
f9bc543b9df030ce37f2647b494b21e01ddc5cae
[]
no_license
SimonaLyubenova/BattleGame-Project
dff0a463e0602f22c3b5b9da44e6973443289d32
4453cdb54c3c33cd8e066fbaaae989986bf80b7a
refs/heads/master
2022-11-08T05:37:55.836655
2020-06-29T19:47:54
2020-06-29T19:47:54
271,035,744
0
0
null
null
null
null
UTF-8
C++
false
false
3,553
cpp
#include "Weapons.h" Weapons::Weapons() { setWeaponID(countWeapons + 1); setName("Unknown weapon"); setWeaponType(WeaponType::None); setWeight(0.0); setDamage(0); setStartDefense(0); setDefense(0); setMovementSpeed(0); setRange(0.0); setStatus(WeaponStatus::Strong); countWeapons++; } Weapons::Weapons(const Weapons& weapon) { setWeaponID(countWeapons + 1); setName(weapon.getName()); setWeaponType(weapon.getWeaponType()); setWeight(weapon.getWeight()); setDamage(weapon.getDamage()); setStartDefense(weapon.getStartDefense()); setDefense(weapon.getDefense()); setMovementSpeed(weapon.getMovementSpeed()); setRange(weapon.getRange()); setStatus(weapon.getStatus()); countWeapons++; } Weapons& Weapons::operator=(const Weapons& weapon) //we need to take only the type and the status, other attributes are the same { if (this != &weapon) { setWeaponType(weapon.getWeaponType()); setStatus(weapon.getStatus()); } return *this; } void Weapons::setWeaponID(const unsigned long newWeaponID) { this->weaponID = newWeaponID; } unsigned long Weapons::getWeaponID() const { return this->weaponID; } void Weapons::setName(const std::string newName) { this->name = newName; } std::string Weapons::getName() const { return this->name; } void Weapons::setWeight(const double newWeight) { this->weight = newWeight; } double Weapons::getWeight() const { return this->weight; } void Weapons::setMovementSpeed(const int newMovementSpeed) { this->movementSpeed = newMovementSpeed; } int Weapons::getMovementSpeed() const { return this->movementSpeed; } void Weapons::setDamage(const int newDamage) { this->damage = newDamage; } int Weapons::getDamage() const { return this->damage; } void Weapons::setStartDefense(const int newStartDefense) { this->startDefense = newStartDefense; } int Weapons::getStartDefense() const { return this->startDefense; } void Weapons::setDefense(const int newDefense) { this->defense = newDefense; } int Weapons::getDefense() const { return this->defense; } void Weapons::setRange(const double newRange) { this->range = newRange; } double Weapons::getRange() const { return this->range; } void Weapons::setStatus(const WeaponStatus newStatus) { this->status = newStatus; } WeaponStatus Weapons::getStatus() const { return this->status; } void Weapons::setWeaponType(const WeaponType newType) { this->type = newType; } WeaponType Weapons::getWeaponType() const { return this->type; } bool Weapons::isShooter() const { if (getWeaponType() == WeaponType::Shooter) { return true; } return false; } void Weapons::printStatus() const { std::cout << "Status: "; switch (getStatus()) { case 0: std::cout << "Strong" << std::endl; break; case 1: std::cout << "Damaged" << std::endl; break; case 2: std::cout << "Broken" << std::endl; break; } } void Weapons::print() const { std::cout << "ID: " << getWeaponID() << std::endl; std::cout << "Weapon: " << getName() << std::endl; std::cout << "Type: "; switch (getWeaponType()) { case 0: std::cout << "None" << std::endl; break; case 1: std::cout << "Shooters" << std::endl; break; case 2: std::cout << "Handguns" << std::endl; break; } std::cout << "Weight: " << getWeight() << " kg" << std::endl; std::cout << "Damage: " << getDamage() << std::endl; std::cout << "Defense: " << getDefense() << "/" << getStartDefense() << std::endl; std::cout << "Movement speed: " << getMovementSpeed() << " units per second" << std::endl; std::cout << "Range: " << getRange() << " m" << std::endl; }
[ "m0ni1999@abv.bg" ]
m0ni1999@abv.bg
d6dbf1292ec97cbd1e4af98e9da6c6b7e544f40e
a3b109746e9c599bff9fa782fd27801c4624b490
/src/dispatch/dispatch.cpp
965e427c40a85a00f59890f08dbf51c653913b46
[ "MIT" ]
permissive
fh-tech/CFLOP
65e1e80cb37d70b298635664dc347cdae7509db2
6df4bf40cf34b3b109adc18b622635f814b2f4f3
refs/heads/master
2020-03-09T17:25:57.748346
2018-06-03T19:46:21
2018-06-03T19:46:21
128,908,435
3
0
MIT
2018-06-03T18:15:36
2018-04-10T09:32:07
C++
UTF-8
C++
false
false
7,593
cpp
// // Created by daniel on 01.05.18. // #include "dispatcher.h" namespace dispatch_lib { //REVIEW: zum ausprobiern mit 'Strg+Alt+M' extract method heraus gehoben // sieht vl besser aus output_lib::Response dispatch_invalid(const input_lib::Request &r) { std::string message = "invalid json input"; output_lib::failure_r_s res{message}; return output_lib::Response(r.type, res); } output_lib::Response dispatch_nodes_post(const input_lib::Request &r, fsm::FinalStateMachine &fsm) {// get the struct from the request auto req = std::get<input_lib::nodes_post_s>(r.request); graph::node_id id = fsm.add_state(); // build the output_lib::Response struct with the return value of fsm output_lib::nodes_post_r_s res{id}; // make json from that return output_lib::Response(r.type, res); } output_lib::Response dispatch(input_lib::Request &r, fsm::FinalStateMachine &fsm) { json j; switch (r.type) { case input_lib::INVALID_TYPE: { return dispatch_invalid(r); } case input_lib::NODES_POST: { return dispatch_nodes_post(r, fsm); } case input_lib::NODES_DELETE: { auto req = std::get<input_lib::nodes_delete_s>(r.request); fsm.remove_node(req.id); output_lib::nodes_delete_r_s res{}; return output_lib::Response(r.type, res); } case input_lib::NODES_GET: { auto req = std::get<input_lib::nodes_get_s>(r.request); auto node_pair = fsm.get_state(req.id); if (node_pair) { size_t id = node_pair->first; std::vector<graph::edge_id> edges = fsm.get_adjacient_transitions(id); std::vector<size_t> edges_size_t = {edges.begin(), edges.end()}; output_lib::nodes_get_r_s res{id, edges_size_t}; return output_lib::Response(r.type, res); } else { std::string message = "Node with requested id does not exist"; output_lib::failure_r_s res{message}; return output_lib::Response(input_lib::INVALID_TYPE, res); } } case input_lib::NODES_PUT_START: { auto req = std::get<input_lib::nodes_put_start_s>(r.request); //TODO: can not fail? fsm.set_start(req.id); output_lib::nodes_put_start_r_s res{}; return output_lib::Response(r.type, res); } case input_lib::NODES_PUT_END: { auto req = std::get<input_lib::nodes_put_end_s>(r.request); //TODO: can not fail? fsm.set_end(req.id); output_lib::nodes_put_end_r_s res{}; return output_lib::Response(r.type, res); } case input_lib::EDGES_GET: { auto req = std::get<input_lib::edges_get_s>(r.request); auto edge_pair = fsm.get_transtion(req.id); size_t id = edge_pair->first; size_t from = edge_pair->second.from; size_t to = edge_pair->second.to; std::string transition = edge_pair->second.val.into(); output_lib::edges_get_r_s res{id, from, to, transition}; return output_lib::Response(r.type, res); } case input_lib::EDGES_POST: { auto req = std::get<input_lib::edges_post_s>(r.request); size_t id = fsm.add_transition( req.from, req.to, fsm::Transition<std::string>::from(req.transition) ); if (id) { output_lib::edges_post_r_s res{id}; return output_lib::Response(r.type, res); } else { std::string message = "Something went wrong... one of the nodes does not exists"; output_lib::failure_r_s res{message}; return output_lib::Response(input_lib::INVALID_TYPE, res); } } case input_lib::EDGES_DELETE: { auto req = std::get<input_lib::edges_delete_s>(r.request); fsm.remove_edge(req.id); output_lib::edges_delete_r_s res{}; return output_lib::Response(r.type, res); } case input_lib::STATE_GET: { //TODO: control that - i cant handle working with grap and fsm lib auto req = std::get<input_lib::state_get_s>(r.request); auto edges_fsm = fsm.get_Transitions(); std::vector<input_lib::edge> edges{}; // transform an fsm_edge vector into a input-lib edge vector std::transform(edges_fsm.begin(), edges_fsm.end(), edges.begin(), [](auto fsm_edge) -> input_lib::edge { //TODO: maybe not necessary idk size_t id = fsm_edge.first; size_t to = fsm_edge.second.to; size_t from = fsm_edge.second.from; std::string transition = fsm_edge.second.val.into(); //TODO: no idea why - constructor exists return input_lib::edge{id, to, from, transition}; }); auto nodes_fsm = fsm.get_States(); std::vector<input_lib::node> nodes{}; for(const auto& fsm_node: nodes_fsm){ auto edge_ids = fsm.get_adjacient_transitions(fsm_node.first); std::vector<size_t> edges_size_t = {edge_ids.begin(), edge_ids.end()}; nodes.push_back(input_lib::node{(size_t)(fsm_node.first), std::move(edges_size_t)}); } size_t active = fsm.get_current(); size_t start = fsm.get_start(); size_t end = fsm.get_end(); output_lib::state_get_r_s res{nodes, edges, active, start, end}; return output_lib::Response(r.type, res); } case input_lib::STATE_POST: { auto req = std::get<input_lib::state_post_s>(r.request); std::vector<input_lib::node> nodes = req.nodes; std::vector<input_lib::edge> edges = req.edges; size_t active = req.active; size_t start = req.start; size_t end = req.end; for(auto&node: nodes){ fsm.add_state_form_parts(node.id, fsm::State{}); } for(auto& edge: edges){ fsm.add_transition_from_parts( edge.id, fsm::Transition<std::string>::from(edge.transition), edge.to, edge.from ); } fsm.set_end(end); fsm.set_start(start); output_lib::state_post_r_s res{}; return output_lib::Response(r.type, res); } case input_lib::STATE_PUT: { auto req = std::get<input_lib::state_put_s>(r.request); size_t id = fsm.advance(req.input); output_lib::state_put_r_s res{id}; return output_lib::Response(r.type, res); } } } }
[ "d.kudernatsch@outlook.com" ]
d.kudernatsch@outlook.com
1d6402897f19198a0f2c806bf169e8297032def8
e8921f4f75122669c6d36ce2a7ecde558868da69
/src/CommCore/CommCore.cpp
bdba9f5326810b7b52893d1613f2c8a723023aea
[]
no_license
BoonXRay/CossacksBTW
ce693e1ff5b3d0ba26e16d44c9a47f8bfefafc40
9d0192fdd65e03d9bed3b94020782b1d366deb1a
refs/heads/master
2021-09-23T16:01:13.591109
2018-09-25T15:28:30
2018-09-25T15:28:30
114,782,767
0
0
null
null
null
null
UTF-8
C++
false
false
11,712
cpp
#include "CommCore.h" #include <stdlib.h> #include <stdio.h> // --------------------------------------------------------------------------------------------- LPCSTR CCommCore::GetUserName( PEER_ID PeerId ) { _log_message( "GetUserName()" ); if (PeerId == m_piNumber) return m_szUserName; u_short uPeerNum = GetPeerById( PeerId ); if (uPeerNum == BAD_PEER_ID) return NULL; return m_PeerList[uPeerNum].m_szUserName; } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SetUserName( LPCSTR lpcszUserName ) { _log_message( "SetUserName()" ); strcpy( m_szUserName, lpcszUserName ); return TRUE;//SendUserName(); } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendUserName() { _log_message( "SendUserName()" ); if (m_bServer) { strcpy( m_PeerList[0].m_szUserName, m_szUserName ); // return SendServerList(); return SendNewName( m_piNumber ); } else { CC_PK_SEND_USER_NAME SendUserNamePacket; strcpy( SendUserNamePacket.m_szUserName, m_szUserName ); return SendRawPacket( m_paServAddr, m_paServPort, CC_PT_SEND_USER_NAME, (LPBYTE) &SendUserNamePacket, sizeof( CC_PK_SEND_USER_NAME ), TRUE, FALSE ); } } // --------------------------------------------------------------------------------------------- BOOL CCommCore::GetUserData( PEER_ID PeerId, LPBYTE lpbUserData, u_short * puUserDataSize ) { _log_message( "GetUserData()" ); if (PeerId == m_piNumber) { memcpy( lpbUserData, m_lpbUserData, m_uUserDataSize ); if (puUserDataSize) { *puUserDataSize = m_uUserDataSize; } return TRUE; } u_short uPeerNum = GetPeerById( PeerId ); if (uPeerNum == BAD_PEER_ID) { if (puUserDataSize) { *puUserDataSize = 0; } return FALSE; } memcpy( lpbUserData, m_PeerList[uPeerNum].m_lpbUserData, m_PeerList[uPeerNum].m_uUserDataSize ); if (puUserDataSize) { *puUserDataSize = m_PeerList[uPeerNum].m_uUserDataSize; } return TRUE; } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SetUserData( const LPBYTE lpcbUserData, u_short uUserDataSize ) { _log_message( "SetUserData()" ); if (m_lpbUserData) { free( m_lpbUserData ); } m_lpbUserData = (LPBYTE) malloc( uUserDataSize ); assert( m_lpbUserData ); m_uUserDataSize = uUserDataSize; memcpy( m_lpbUserData, lpcbUserData, uUserDataSize ); return TRUE;//SendUserData(); } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendUserData() { _log_message( "SendUserData()" ); if (!m_lpbUserData) { return FALSE; } if (m_bServer) { free( m_PeerList[0].m_lpbUserData ); m_PeerList[0].m_uUserDataSize = m_uUserDataSize; m_PeerList[0].m_lpbUserData = (LPBYTE) malloc( m_uUserDataSize ); assert( m_PeerList[0].m_lpbUserData ); memcpy( m_PeerList[0].m_lpbUserData, m_lpbUserData, m_uUserDataSize ); m_PeerList[0].m_uUserDataSize = m_uUserDataSize; // return SendServerList(); return SendNewData( m_piNumber ); } else { LPCC_PK_SEND_USER_DATA lpSendUserDataPacket; lpSendUserDataPacket = (LPCC_PK_SEND_USER_DATA) malloc( sizeof( CC_PK_SEND_USER_DATA ) + m_uUserDataSize ); assert( lpSendUserDataPacket ); lpSendUserDataPacket->m_uUserDataSize = m_uUserDataSize; memcpy( lpSendUserDataPacket->m_UserData, m_lpbUserData, m_uUserDataSize ); BOOL bRes = SendRawPacket( m_paServAddr, m_paServPort, CC_PT_SEND_USER_DATA, (LPBYTE) lpSendUserDataPacket, sizeof( CC_PK_SEND_USER_DATA ) + m_uUserDataSize, TRUE, FALSE ); free( lpSendUserDataPacket ); return bRes; } } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendDropClient( PEER_ID PeerID ) { _log_message( "SendDropClient()" ); CC_PK_HOST_DROP HostDropPacket; u_short uPeerNum; uPeerNum = GetPeerById( PeerID ); if (BAD_PEER_ID == uPeerNum) { return FALSE; } HostDropPacket.m_dwReserved = 0xFF; return SendRawPacket( m_PeerList[uPeerNum].m_ex_Addr, m_PeerList[uPeerNum].m_ex_Port, CC_PT_HOST_DROP, (LPBYTE) &HostDropPacket, sizeof( CC_PK_HOST_DROP ), TRUE, FALSE ); } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendToAll( LPBYTE lpbBuffer, u_short u_Size, BOOL bSecure ) { _log_message( "SendToAll()" ); for (int i = 0; i < m_uPeerCount; i++) if (!SendToPeer( m_PeerList[i].m_Id, lpbBuffer, u_Size, bSecure )) return FALSE; return TRUE; } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendToPeer( PEER_ID piNumber, LPBYTE lpbBuffer, u_short uSize, BOOL bSecure ) { _log_message( "SendToPeer()" ); if (piNumber == m_piNumber) return TRUE; LPCC_PK_SEND_DATA lpFrame; u_short uFrameSize; uFrameSize = sizeof( CC_PK_SEND_DATA ) + uSize; lpFrame = (LPCC_PK_SEND_DATA) malloc( uFrameSize ); lpFrame->m_uSize = uSize; memcpy( lpFrame->m_bData, lpbBuffer, uSize ); u_short uPeerNum = GetPeerById( piNumber ); if (uPeerNum == BAD_PEER_ID) return FALSE; BOOL bRes = SendRawPacket( ( uPeerNum == 0 ) ? m_paServAddr : m_PeerList[uPeerNum].m_ex_Addr, m_PeerList[uPeerNum].m_ex_Port, CC_PT_SEND_DATA, (LPBYTE) lpFrame, uFrameSize, bSecure, FALSE ); free( lpFrame ); return bRes; } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendConfirmDataPacket( sockaddr_in *lpSender, u_long lStamp ) { _log_message( "SendConfirmDataPacket()" ); CC_PK_FRAME_CONFIRM ConfPacket; ConfPacket.m_lConfirmStamp = lStamp; if (!SendRawPacket( lpSender->sin_addr, lpSender->sin_port, CC_PT_FRAME_CONFIRM, (LPBYTE) &ConfPacket, sizeof( CC_PK_FRAME_CONFIRM ), FALSE, FALSE )) return FALSE; return TRUE; } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendConnectReject( sockaddr_in *lpSender, u_short uReason ) { _log_message( "SendConnectReject()" ); CC_PK_CONNECT_REJECT RejectPacket; RejectPacket.m_uReason = uReason; if (!SendRawPacket( lpSender->sin_addr, lpSender->sin_port, CC_PT_CONNECT_REJECT, (LPBYTE) &RejectPacket, sizeof( CC_PK_CONNECT_REJECT ), TRUE, FALSE )) return FALSE; return TRUE; } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendConnectOk( sockaddr_in *lpSender, PEER_ID PeerId ) { _log_message( "SendConnectOk()" ); CC_PK_CONNECT_OK ConnectOkPacket; ConnectOkPacket.m_Id = PeerId; ConnectOkPacket.m_dwOptions = m_dwOptions; strcpy( ConnectOkPacket.m_szSessionName, m_szSessionName ); if (!SendRawPacket( lpSender->sin_addr, lpSender->sin_port, CC_PT_CONNECT_OK, (LPBYTE) &ConnectOkPacket, sizeof( CC_PK_CONNECT_OK ), TRUE, FALSE )) return FALSE; return TRUE; } // --------------------------------------------------------------------------------------------- VOID CCommCore::SetCommCoreUID( LPCSTR lpcszCCUID ) { _log_message( "SetCommCoreUID()" ); HKEY hKey; RegCreateKeyEx( HKEY_CURRENT_USER, "Software\\GSC Game World", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL ); RegSetValueEx( hKey, "CCUID", 0, REG_SZ, (unsigned char*) lpcszCCUID, strlen( lpcszCCUID ) + 1 ); RegCloseKey( hKey ); } // --------------------------------------------------------------------------------------------- VOID CCommCore::NewCommCoreUID( LPSTR lpszCCUID ) { _log_message( "NewCommCoreUID()" ); CHAR szComputerName[255]; CHAR szCCUID[255]; DWORD dwSize = 64; // BoonXRay 09.09.2017 //DWORD dwTicks; unsigned int dwTicks; int iRand; GetComputerName( szComputerName, &dwSize ); for (iRand = dwSize; iRand < 8; iRand++) szComputerName[iRand] = '0'; szComputerName[iRand] = '\0'; dwTicks = GetTickCount(); srand( dwTicks ); iRand = rand(); sprintf( szCCUID, "%-8.8s-%8.8X-%4.4X", szComputerName, dwTicks, iRand ); SetCommCoreUID( szCCUID ); strcpy( lpszCCUID, szCCUID ); } // --------------------------------------------------------------------------------------------- VOID CCommCore::GetCommCoreUID( LPSTR lpszCCUID ) { _log_message( "GetCommCoreUID()" ); HKEY hKey; CHAR szCCUID[64]; DWORD dwSize = 64; if (RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\GSC Game World", 0, KEY_ALL_ACCESS, &hKey ) != ERROR_SUCCESS) { NewCommCoreUID( lpszCCUID ); return; } if (RegQueryValueEx( hKey, "CCUID", 0, NULL, (unsigned char*) szCCUID, &dwSize ) != ERROR_SUCCESS) { RegCloseKey( hKey ); NewCommCoreUID( lpszCCUID ); return; } RegCloseKey( hKey ); strcpy( lpszCCUID, szCCUID ); } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendNewName( PEER_ID PeerId ) // Отсылает информацию о имени (сервер) { _log_message( "SendNewName()" ); CC_PK_SEND_NEW_NAME SendNewNamePacket; u_short uPeerNum; uPeerNum = GetPeerById( PeerId ); SendNewNamePacket.m_PeerId = PeerId; strcpy( SendNewNamePacket.m_szUserName, m_PeerList[uPeerNum].m_szUserName ); for (int i = 1; i < m_uPeerCount; i++) if (m_PeerList[i].m_Id != PeerId) SendRawPacket( m_PeerList[i].m_ex_Addr, m_PeerList[i].m_ex_Port, CC_PT_SEND_NEW_NAME, (LPBYTE) &SendNewNamePacket, sizeof( CC_PK_SEND_NEW_NAME ), TRUE, FALSE ); return TRUE; } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendNewData( PEER_ID PeerId ) // Отсылает информацию о дате (сервер) { _log_message( "SendNewData()" ); LPCC_PK_SEND_NEW_DATA pSendNewDataPacket = NULL; u_short uPacketSize = 0; u_short uPeerNum; uPeerNum = GetPeerById( PeerId ); if (uPeerNum == BAD_PEER_ID) return FALSE; uPacketSize = sizeof( CC_PK_SEND_NEW_DATA ) + m_PeerList[uPeerNum].m_uUserDataSize; pSendNewDataPacket = (LPCC_PK_SEND_NEW_DATA) malloc( uPacketSize ); pSendNewDataPacket->m_PeerId = PeerId; pSendNewDataPacket->m_uUserDataSize = m_PeerList[uPeerNum].m_uUserDataSize; memcpy( pSendNewDataPacket->m_UserData, m_PeerList[uPeerNum].m_lpbUserData, m_PeerList[uPeerNum].m_uUserDataSize ); for (int i = 1; i < m_uPeerCount; i++) if (m_PeerList[i].m_Id != PeerId) { SendRawPacket( m_PeerList[i].m_ex_Addr, m_PeerList[i].m_ex_Port, CC_PT_SEND_NEW_DATA, (LPBYTE) pSendNewDataPacket, uPacketSize, TRUE, FALSE ); } free( pSendNewDataPacket ); return TRUE; } // --------------------------------------------------------------------------------------------- BOOL CCommCore::IsOverNAT( PEER_ID PeerId ) { _log_message( "IsOverNAT()" ); if (PeerId == 1) return FALSE; u_short uPeerNum; uPeerNum = GetPeerById( PeerId ); if (uPeerNum == BAD_PEER_ID) return FALSE; return m_PeerList[uPeerNum].m_bOverNAT; } // --------------------------------------------------------------------------------------------- VOID CCommCore::GetServerAddress( LPSTR lpszServerAddress ) { if (lpszServerAddress) { strcpy( lpszServerAddress, inet_ntoa( m_paServAddr ) ); } } // --------------------------------------------------------------------------------------------- BOOL CCommCore::SendUdpHolePunch( sockaddr *server, char *content, const int content_len ) { const int res = sendto( m_DataSocket, content, content_len, 0, server, sizeof( sockaddr_in ) ); if (SOCKET_ERROR == res) { return FALSE; } return TRUE; }
[ "BoonXRay@ya.ru" ]
BoonXRay@ya.ru
6de4c38b191ad85b99f74792a84c5f60a1ce50f8
55388fae80034a2b0ad694aef37b54787b14384a
/Tea Bag Dropper/src/main.cpp
6d48c2f8096233f17f71704d08d077f1fa7b74ce
[]
no_license
Brandon2255p/Kettle
94f9a2568fef871e182d12d51ee0677275312652
d451b83a5444eb0d72aeddeb9f8a02ceaf7a3a11
refs/heads/master
2022-01-20T07:04:25.654795
2019-07-26T19:58:39
2019-07-26T19:58:39
106,245,125
0
0
null
null
null
null
UTF-8
C++
false
false
4,554
cpp
#include <Arduino.h> #include <Servo.h> int PinLightSensor = 2; int PinPumpPWM = 5; int PinCupSensor = A0; int PinLed = 12; Servo servoBag; Servo servoPour; volatile bool RunDrop = true; volatile bool Pumping = true; volatile bool Pouring = true; String command = ""; // a String to hold incoming data bool commandComplete = false; // whether the string is complete void serialEvent(); void HandleInput(); bool signalDrop = false; bool signalPump = false; bool signalBoil = false; bool signalPour = false; void StopTheDrop() { RunDrop = false; } void setup() { Serial.println("Starting!!"); command.reserve(20); Serial.begin(9600); servoBag.attach(9); servoPour.attach(7); servoBag.writeMicroseconds(1200); // sets the servo position according to the scaled value pinMode(PinLightSensor, INPUT_PULLUP); pinMode(PinCupSensor, INPUT_PULLUP); pinMode(PinLed, OUTPUT); digitalWrite(PinLed, LOW); attachInterrupt(digitalPinToInterrupt(PinLightSensor), StopTheDrop, RISING); } void DropBag() { digitalWrite(PinLed, HIGH); delay(200); RunDrop = true; Serial.println("Dropping a bag..."); auto StartTime_ms = millis(); unsigned long TimeLimit_ms = 15000; bool TimedOut = false; while(RunDrop) { signalDrop = false; serialEvent(); HandleInput(); TimedOut = millis() - StartTime_ms > TimeLimit_ms; if(TimedOut) { Serial.println("Timeout!"); break; } servoBag.writeMicroseconds(1290); if(!RunDrop) break; delay(300); servoBag.writeMicroseconds(1150); if(!RunDrop) break; delay(600); } signalPump = !TimedOut; servoBag.writeMicroseconds(1200); // sets the servo position according to the scaled value digitalWrite(PinLed, LOW); } void PumpWater() { signalPump = false; Pumping = true; Serial.println("Pumping water..."); servoPour.write(170); auto StartTime_ms = millis(); unsigned long TimeLimit_ms = 5000; digitalWrite(PinPumpPWM, HIGH); while(Pumping) { serialEvent(); HandleInput(); delay(300); bool TimedOut = millis() - StartTime_ms > TimeLimit_ms; if(TimedOut) { Pumping = false; signalBoil = true; Serial.println("Timeout!"); break; } } digitalWrite(PinPumpPWM, 0); } void PourWater() { Pouring = true; Serial.println("Pouring water..."); servoPour.write(5); signalPour = false; } void loop() { HandleInput(); if(signalDrop) DropBag(); if(signalPump) PumpWater(); if(signalPour) PourWater(); if(signalBoil) { Serial.println("cmdboil"); signalBoil = false; } if(digitalRead(PinCupSensor) == 0) { signalDrop = true; } delay(10); } void serialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); if (inChar == '\n') { commandComplete = true; return; } command += inChar; } } void HandleInput() { if (commandComplete) { Serial.print("Echo:"); Serial.println(command); if(command.charAt(command.length() - 1) == '\r') { Serial.println("WINDOWS END LINE"); command.remove(command.length() - 1); } if(command.equals("cmdx")) { Serial.println("CANCELLING"); RunDrop = false; Pumping = false; Pouring = false; servoPour.write(175); } else if(command.equals("cmddrop")) { Serial.println("Dropping"); signalDrop = true; } else if(command.equals("cmdpump")) { Serial.println("Pumping"); signalPump = true; } else if(command.equals("cmdpour")) { Serial.println("Pouring"); signalPour = true; } else { Serial.println("UNKNOWN"); // int servoValue = command.toInt(); // if(servoValue){ // Serial.print("SERVO:"); // Serial.println(servoValue); // servoBag.writeMicroseconds(servoValue); // } // else // servoBag.writeMicroseconds(1200); } commandComplete = false; command = ""; } }
[ "brandon2255p@gmail.com" ]
brandon2255p@gmail.com
14d723137f2f9943e3644334fbd2ca77b13b5253
7c5e57bc7f6804c4f0bc33cf9c82c2f542e4b6aa
/motif_tree.cpp
c387dc9ecd027284248894cca7911d41dc0f9316
[ "MIT" ]
permissive
gkno/vt
312cab4ea82a7dc5e57c68e00abe6435a8bc4408
cd35a6c78dc0093709751d6ba3d5b83728ce9bc2
refs/heads/master
2021-01-22T11:21:57.023592
2015-11-03T16:23:27
2015-11-03T16:23:27
29,372,774
0
0
null
2015-01-16T23:35:18
2015-01-16T23:35:18
null
UTF-8
C++
false
false
11,320
cpp
/* The MIT License Copyright (c) 2015 Adrian Tan <atks@umich.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "motif_tree.h" #define A 0 #define C 1 #define G 2 #define T 3 #define N 4 /** * Constructor. */ MotifTree::MotifTree(uint32_t max_len, bool debug) { this->max_len = max_len; mm = new MotifMap(max_len); this->debug = debug; lc.resize(max_len+1,0); tree = (node *) malloc(sizeof(node)*mm->max_index+1); //perform mapping. for (uint32_t len=1; len<=max_len; ++len) { for (uint32_t index=mm->len_count[len-1]; index<mm->len_count[len]; ++index) { uint32_t seq = mm->index2seq(index); tree[index] = {index, mm->seq2index(mm->canonical(seq, len), len), 0, len, seq}; uint32_t c = mm->canonical(seq, len); //bool a = mm->is_aperiodic(c, len); //std::cerr << " " << mm->seq2str(c, len) << " " << mm->is_aperiodic(c, len) << "\n"; } } }; /** * Destructor. */ MotifTree::~MotifTree() { if (tree) delete tree; if (mm) delete mm; }; /** * Gets subsequence from a string at the spos0 position of length cmax_len. */ uint32_t MotifTree::get_sub_seq(char* seq, uint32_t len, uint32_t spos0, uint32_t& s) { if (spos0==0) { s = 0; for (uint32_t i=0; i<cmax_len; ++i) { uint32_t j = base2index(seq[i]); s = set_seqi(s, i, j); } return cmax_len; } else { uint32_t slen = 0; //shorter than max_len if (len-spos0<cmax_len) { slen = len-spos0; s = shift(s, slen+1); s = set_seqi(s, len-spos0, 0); } else { slen = cmax_len; s = shift(s, cmax_len); //std::cerr << seq[spos0+max_len-1] << " " << spos0+max_len-1 <<" " << base2index(seq[spos0+max_len-1]) << "\n"; s = set_seqi(s, cmax_len-1, base2index(seq[spos0+cmax_len-1])); } return slen; } } /** * Construct suffix tree based on sequence of length len. */ void MotifTree::set_sequence(char* seq, uint32_t len) { //computes the relevant maximum possible length of motif to check cmax_len = (len >> 1) < max_len ? (len >> 1) : max_len; if (debug) { std::cerr << "len : " << len << "\n"; std::cerr << "cmax_len : " << cmax_len << "\n"; } uint32_t s = 0; for (uint32_t i=0; i<len; ++i) { //update as uint32_t representation uint32_t l = get_sub_seq(seq, len, i, s); //mm->print_seq(s,l); //insert prefix insert_prefix(s, l); } }; /** * Inserts prefix s into tree. */ void MotifTree::insert_prefix(uint32_t s, uint32_t len) { for (uint32_t i=1; i<=len; ++i) { uint32_t index = mm->seq2index(s, i); ++tree[index].count; } } /** * Consolidate motif counts. */ void MotifTree::consolidate_motif_counts() { cm.clear(); std::fill(lc.begin(), lc.end(), 0); while (!pcm.empty()) pcm.pop(); consolidate_motif_counts(&tree[0]); consolidate_motif_counts(&tree[1]); consolidate_motif_counts(&tree[2]); consolidate_motif_counts(&tree[3]); } /** * Consolidate motif counts. */ void MotifTree::consolidate_motif_counts(node* n) { if (n->count) { if (cm.find(n->cindex)==cm.end()) { cm[n->cindex] = n->count; } else { cm[n->cindex] += n->count; } lc[n->len] += n->count; n->count = 0; if (n->len != cmax_len) { uint32_t index = get_first_child(n->seq, n->len); consolidate_motif_counts(&tree[index]); consolidate_motif_counts(&tree[index+1]); consolidate_motif_counts(&tree[index+2]); consolidate_motif_counts(&tree[index+3]); } } } /** * Shifts a string. */ std::string MotifTree::shift_str(std::string& seq, uint32_t i) { std::string sseq = seq; if (i) { sseq = seq.substr(i) + seq.substr(0,i); } return sseq; } /** * Checks if two copies of a motif exists in a seq. */ bool MotifTree::exist_two_copies(std::string& seq, std::string& motif) { //all phases of motif for (uint32_t i=0; i<motif.size(); ++i) { std::string ru = shift_str(motif, i); const char* s = seq.c_str(); if ((s = strstr(s, ru.c_str()))) { s += ru.size(); if ((s = strstr(s, ru.c_str()))) { return true; } } } return false; } /** * Compute fit of expected content of nucleotides. */ float MotifTree::compute_fit(uint32_t index, scontent* sc) { uint32_t e[] = {0,0,0,0}; node* n = &tree[index]; // std::cerr << "compute fit: " << mm->seq2str(n->seq, n->len) << "\n"; //compute expected fit for (uint32_t i=0; i<n->len; ++i) { ++e[get_seqi(n->seq, i)]; } // std::cerr << e[0] << " " << e[1] << " " << e[2] << " " << e[3] << "\n"; float fit = 0; float t = 0; // std::cerr << "n " << sc->n << " (" << sc->base[A] << "," << sc->base[C] << "," << sc->base[G] << "," << sc->base[T] << ")\n"; for (uint32_t i=0; i<4; ++i) { t = (float)sc->base[i]/sc->n - (float)e[i]/n->len; fit += t*t; } // std::cerr << "compute fit " << fit << "\n"; return fit; } /** * Gets candidate motifs up to max_motif_len. */ void MotifTree::detect_candidate_motifs(std::string& seq) { detect_candidate_motifs(const_cast<char*>(seq.c_str()), seq.size()); } /** * Detects candidate motifs from seq of length len. */ void MotifTree::detect_candidate_motifs(char* seq, uint32_t len) { if (debug) { std::cerr << "detecting motifs for an str\n"; std::cerr << "seq: " << seq << "\n"; } std::string s(seq); if (strchr(seq, 'N')) { uint32_t len = s.size(); s.clear(); for (uint32_t i=0; i<len; ++i) { if (seq[i]!='N') { s.append(1,seq[i]); } } } //construct tree set_sequence(const_cast<char*>(s.c_str()), s.size()); // print_tree(); //gather distribution scontent sc; sc.base[A] = tree[A].count; sc.base[C] = tree[C].count; sc.base[G] = tree[G].count; sc.base[T] = tree[T].count; sc.n = sc.base[A] + sc.base[C] + sc.base[G] + sc.base[T]; //count occurrences consolidate_motif_counts(); if (debug) std::cerr << "candidate motifs: " << cm.size() << "\n"; float sthreshold = std::min(0.80, (s.size()-1.0)/s.size()); for (std::map<uint32_t, uint32_t>::iterator i = cm.begin(); i!=cm.end(); ++i) { if (mm->is_aperiodic(mm->index2seq(i->first), tree[i->first].len)) { //p - purity proportion float p = (float)i->second/(lc[tree[i->first].len]); //f - fit based on content float f = compute_fit(i->first, &sc); //p -= f; //if ((tree[i->first].len==1 && p+f>sthreshold) || (tree[i->first].len>1 && p>0.2)) if (len<10 || (tree[i->first].len==1 && p>0.6) || (tree[i->first].len>1)) { std::string motif = mm->seq2str(mm->index2seq(i->first), tree[i->first].len); if (exist_two_copies(s, motif)) { if (debug) std::cerr << motif << " : " << p << " " << tree[i->first].len << " " << f << "\n"; pcm.push(CandidateMotif(motif, p, tree[i->first].len, f)); } else { if (debug) std::cerr << motif << " : " << p << " " << tree[i->first].len << " " << f << " (< 2 copies)\n"; pcm.push(CandidateMotif(motif, p, tree[i->first].len, f)); } } } } //if no pickups if (pcm.size()==0) { std::map<uint32_t, uint32_t>::iterator i = cm.begin(); float p = (float)i->second/(lc[tree[i->first].len]); float f = compute_fit(i->first, &sc); p -= f; if (debug) std::cerr << mm->seq2str(mm->index2seq(i->first), tree[i->first].len) << " : " << p << " " << tree[i->first].len << " " << f << "\n"; pcm.push(CandidateMotif(mm->seq2str(mm->index2seq(i->first), tree[i->first].len), p, tree[i->first].len, f)); } // print_tree(); }; /** * Gets index of first child. */ uint32_t MotifTree::get_first_child(uint32_t seq, uint32_t len) { //not necessary sequence should be zeroed out after valid length. //uint32_t cseq = set_seq(s, len, 0); uint32_t index = mm->seq2index(seq, len+1); return index; } /** * Converts base to index. */ int32_t MotifTree::base2index(char base) { switch (base) { case 'A': return A; break; case 'C': return C; break; case 'G': return G; break; case 'T': return T; break; default: return N; } }; /** * Print node. */ void MotifTree::print_node(node* n) { std::cerr << std::string(n->len, '\t') << "seq: " << mm->seq2str(n->seq, n->len) << "\n"; std::cerr << std::string(n->len, '\t') << "cnt: " << n->count << "\n"; std::cerr << std::string(n->len, '\t') << "len: " << n->len << "\n"; std::cerr << std::string(n->len, '\t') << "can: " << mm->seq2str(mm->canonical(n->seq, n->len), n->len) << "\n"; std::cerr << "\n"; } /** * Print tree. */ void MotifTree::print_tree() { print_tree(&tree[0]); print_tree(&tree[1]); print_tree(&tree[2]); print_tree(&tree[3]); } /** * Print tree. */ void MotifTree::print_tree(node* n) { if (n->count) { print_node(n); if (n->len != max_len) { uint32_t index = get_first_child(n->seq, n->len); print_tree(&tree[index]); print_tree(&tree[index+1]); print_tree(&tree[index+2]); print_tree(&tree[index+3]); } } } #undef A #undef C #undef G #undef T #undef N
[ "atks@umich.edu" ]
atks@umich.edu
87029d85e34844077ec9156c3eb8f2e8d889edbd
b098555c46548f4eefa1cea27ea5474fe372bbb9
/src/B3PrimaryGeneratorAction.cc
d5a6f6122853bf1eb4f96ff375853d3027a0bc54
[]
no_license
HirokiSato915/NinjaSat_geant4
8faa4f8985d551c97ec7dc9e8e74be6554779772
3d9c971bbc1d18616b3e2e86a2e84cbbfbbe6e7e
refs/heads/master
2023-07-07T18:39:26.420328
2023-06-22T16:24:07
2023-06-22T16:24:07
245,993,220
2
0
null
null
null
null
UTF-8
C++
false
false
4,355
cc
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // /// \file B3A.cc /// \brief Implementation of the B3PrimaryGeneratorAction class #include "B3PrimaryGeneratorAction.hh" #include "G4RunManager.hh" #include "G4Event.hh" #include "G4GeneralParticleSource.hh" #include "G4ParticleTable.hh" #include "G4IonTable.hh" #include "G4ParticleDefinition.hh" #include "G4ChargedGeantino.hh" #include "G4SystemOfUnits.hh" #include "Randomize.hh" #include "G4RandomDirection.hh" #include "B3Constants.hh" #include "B3aEventAction.hh" #include "G4RotationMatrix.hh" #include "G4SPSAngDistribution.hh" #include "G4SPSEneDistribution.hh" #include "G4SPSPosDistribution.hh" #include "G4ThreeVector.hh" #include <iostream> #include <string> // useful for reading and writing #include <fstream> // ifstream, ofstream //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... B3PrimaryGeneratorAction::B3PrimaryGeneratorAction( B3aEventAction *eventAction) : G4VUserPrimaryGeneratorAction(), fEventAction(eventAction) { particleGun = new G4GeneralParticleSource(); G4ParticleTable *particleTable = G4ParticleTable::GetParticleTable(); G4ParticleDefinition *particle = particleTable->FindParticle("gamma"); //....PARTICLE DEFINITIONS particleGun->SetParticleDefinition(particle); // DEFINE A Pow-ENERGETIC SOURCE G4SPSEneDistribution *eneDist = particleGun->GetCurrentSource()->GetEneDist(); eneDist->SetEnergyDisType("Pow"); eneDist->SetAlpha(-1.29); eneDist->SetEmax(200 * keV); eneDist->SetEmin(1 * keV); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... B3PrimaryGeneratorAction::~B3PrimaryGeneratorAction() { delete particleGun; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... void B3PrimaryGeneratorAction::GeneratePrimaries(G4Event *anEvent) { G4double targetR = 5.4 * cm; G4double length = 8. * cm; G4ThreeVector dir1 = G4RandomDirection(); G4ThreeVector dir2 = dir1.orthogonal(); dir2.setR(targetR * sqrt(G4UniformRand())); dir2.rotate(2 * CLHEP::pi * G4UniformRand(), dir1); G4ThreeVector center(0, 0, 7.5 * mm); G4ThreeVector position = center + dir1 * length + dir2; G4ThreeVector mom = -dir1; G4SPSPosDistribution *posDist = particleGun->GetCurrentSource()->GetPosDist(); G4SPSAngDistribution *angDist = particleGun->GetCurrentSource()->GetAngDist(); posDist->SetPosDisType("Point"); posDist->SetCentreCoords(position); angDist->SetParticleMomentumDirection(mom); particleGun->GeneratePrimaryVertex(anEvent); G4double initEnergy = particleGun->GetParticleEnergy(); fEventAction->AddEn(initEnergy); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
[ "xxxxxx@gmail.com" ]
xxxxxx@gmail.com
6cbf0f915bc851ecd053292d345cc8e0b58712af
2de766db3b23b1ae845396fbb30615c01cc1604e
/lightoj/10/1050.cpp
d22cdcda025495d1ba7c4791662f63ee55157e02
[]
no_license
delta4d/AlgoSolution
313c5d0ff72673927ad3862ee7b8fb432943b346
5f6f89578d5aa37247a99b2d289d638f76c71281
refs/heads/master
2020-04-21T01:28:35.690529
2015-01-29T13:38:54
2015-01-29T13:38:54
8,221,423
1
0
null
2013-04-09T15:10:20
2013-02-15T16:09:33
C++
UTF-8
C++
false
false
597
cpp
#include <cstdio> using namespace std; const int N = 1 << 9; double f[N][N]; void init() { for (int i=0; i<N; ++i) f[0][i] = i & 1, f[i][0] = 1 ^ (i & 1); for (int i=1; i<N; ++i) for (int j=1; j<N; ++j) { if ((i + j) & 1) { f[i][j] = i * (1 - f[i-1][j]) + j * (1 - f[i][j-1]); f[i][j] /= i + j; } else { f[i][j] = 1 - f[i][j-1]; } } } int main() { init(); int tc, cn = 0, r, b; for (scanf("%d", &tc); tc--; ) { scanf("%d%d", &r, &b); printf("Case %d: %.15lf\n", ++cn, f[r][b]); } return 0; } // 290660 2013-11-23 17:48:32 1050 - Marbles C++ 0.016 3136 Accepted
[ "delta4d@gmail.com" ]
delta4d@gmail.com
05794d5f5287bf21d35958390c78ae8dad25ccc5
43c499ef9887e1994851fc77c2affbfc3dce8829
/분산처리.cpp
a895dddaf51ce2e4376a1bb6dcfdba2cf8be69db
[]
no_license
ShinDongHwans/BaekJoon
34e19cc32a85c269ecd5dbc61cab8ad44599c9e5
25fe6935840a9ee90b51e95372fecd4b502f3d4a
refs/heads/master
2021-06-28T16:05:24.060196
2021-03-11T05:24:36
2021-03-11T05:24:36
219,939,628
0
0
null
null
null
null
UTF-8
C++
false
false
752
cpp
#include<stdio.h> #include<math.h> int start_game(int n, int k){ if(k==1) return n%10; if(n%10==1||n%10==5||n%10==6) return n%10; if(n%10==0) return 10; if(k==0){ int x; if(n!=4 && n!=9) x=(int)pow(n, 4)%10; else x=(int)pow(n, 2)%10; return x; } if(k>5){ switch(n%10){ case 2: return start_game(n, k%4); case 3: return start_game(n, k%4); case 4: return start_game(n, k%2); case 7: return start_game(n, k%4); case 8: return start_game(n, k%4); case 9: return start_game(n, k%2); } } return start_game(n, k-1)*n%10; } int main(){ int t; scanf("%d", &t); for(int i=0;i<t;i++){ int num, k; scanf("%d %d", &num, &k); printf("%d\n", start_game(num, k)); } }
[ "sdhqaz3034@gmail.com" ]
sdhqaz3034@gmail.com
b7ed5a1aa499ef79f16bd388876aaa1afc7563c7
38c10c01007624cd2056884f25e0d6ab85442194
/media/capture/video/linux/v4l2_capture_delegate.h
1bb1735944ae25fdd9244625bf92caccc74582d4
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
6,387
h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_VIDEO_CAPTURE_LINUX_V4L2_VIDEO_CAPTURE_DELEGATE_H_ #define MEDIA_VIDEO_CAPTURE_LINUX_V4L2_VIDEO_CAPTURE_DELEGATE_H_ #if defined(OS_OPENBSD) #include <sys/videoio.h> #else #include <linux/videodev2.h> #endif #include "base/files/scoped_file.h" #include "base/memory/ref_counted.h" #include "media/capture/video/video_capture_device.h" namespace media { // Class doing the actual Linux capture using V4L2 API. V4L2 SPLANE/MPLANE // capture specifics are implemented in derived classes. Created and destroyed // on the owner's thread, otherwise living and operating on |v4l2_task_runner_|. class V4L2CaptureDelegate : public base::RefCountedThreadSafe<V4L2CaptureDelegate> { public: // Creates the appropiate VideoCaptureDelegate according to parameters. static scoped_refptr<V4L2CaptureDelegate> CreateV4L2CaptureDelegate( const VideoCaptureDevice::Name& device_name, const scoped_refptr<base::SingleThreadTaskRunner>& v4l2_task_runner, int power_line_frequency); // Retrieves the #planes for a given |fourcc|, or 0 if unknown. static size_t GetNumPlanesForFourCc(uint32_t fourcc); // Returns the Chrome pixel format for |v4l2_fourcc| or PIXEL_FORMAT_UNKNOWN. static VideoPixelFormat V4l2FourCcToChromiumPixelFormat( uint32_t v4l2_fourcc); // Composes a list of usable and supported pixel formats, in order of // preference, with MJPEG prioritised depending on |prefer_mjpeg|. static std::list<uint32_t> GetListOfUsableFourCcs(bool prefer_mjpeg); // Forward-to versions of VideoCaptureDevice virtual methods. void AllocateAndStart(int width, int height, float frame_rate, scoped_ptr<VideoCaptureDevice::Client> client); void StopAndDeAllocate(); void SetRotation(int rotation); protected: // Class keeping track of SPLANE/MPLANE V4L2 buffers, mmap()ed on construction // and munmap()ed on destruction. Destruction is syntactically equal for // S/MPLANE but not construction, so this is implemented in derived classes. // Internally it has a vector of planes, which for SPLANE will contain only // one element. class BufferTracker : public base::RefCounted<BufferTracker> { public: BufferTracker(); // Abstract method to mmap() given |fd| according to |buffer|, planarity // specific. virtual bool Init(int fd, const v4l2_buffer& buffer) = 0; uint8_t* const GetPlaneStart(size_t plane) const { DCHECK_LT(plane, planes_.size()); return planes_[plane].start; } size_t GetPlanePayloadSize(size_t plane) const { DCHECK_LT(plane, planes_.size()); return planes_[plane].payload_size; } void SetPlanePayloadSize(size_t plane, size_t payload_size) { DCHECK_LT(plane, planes_.size()); DCHECK_LE(payload_size, planes_[plane].length); planes_[plane].payload_size = payload_size; } protected: friend class base::RefCounted<BufferTracker>; virtual ~BufferTracker(); // Adds a given mmap()ed plane to |planes_|. void AddMmapedPlane(uint8_t* const start, size_t length); private: struct Plane { uint8_t* start; size_t length; size_t payload_size; }; std::vector<Plane> planes_; }; V4L2CaptureDelegate( const VideoCaptureDevice::Name& device_name, const scoped_refptr<base::SingleThreadTaskRunner>& v4l2_task_runner, int power_line_frequency); virtual ~V4L2CaptureDelegate(); // Creates the necessary, planarity-specific, internal tracking schemes, virtual scoped_refptr<BufferTracker> CreateBufferTracker() const = 0; // Fill in |format| with the given parameters, in a planarity dependent way. virtual bool FillV4L2Format(v4l2_format* format, uint32_t width, uint32_t height, uint32_t pixelformat_fourcc) const = 0; // Finish filling |buffer| struct with planarity-dependent data. virtual void FinishFillingV4L2Buffer(v4l2_buffer* buffer) const = 0; // Fetch the number of bytes occupied by data in |buffer| and set to // |buffer_tracker|. virtual void SetPayloadSize( const scoped_refptr<BufferTracker>& buffer_tracker, const v4l2_buffer& buffer) const = 0; // Sends the captured |buffer| to the |client_|, synchronously. virtual void SendBuffer(const scoped_refptr<BufferTracker>& buffer_tracker, const v4l2_format& format) const = 0; // A few accessors for SendBuffer()'s to access private member variables. VideoCaptureFormat capture_format() const { return capture_format_; } VideoCaptureDevice::Client* client() const { return client_.get(); } int rotation() const { return rotation_; } private: friend class base::RefCountedThreadSafe<V4L2CaptureDelegate>; // Returns the input |fourcc| as a std::string four char representation. static std::string FourccToString(uint32_t fourcc); // VIDIOC_QUERYBUFs a buffer from V4L2, creates a BufferTracker for it and // enqueues it (VIDIOC_QBUF) back into V4L2. bool MapAndQueueBuffer(int index); // Fills all common parts of |buffer|. Delegates to FinishFillingV4L2Buffer() // for filling in the planar-dependent parts. void FillV4L2Buffer(v4l2_buffer* buffer, int i) const; void DoCapture(); void SetErrorState(const std::string& reason); const v4l2_buf_type capture_type_; const scoped_refptr<base::SingleThreadTaskRunner> v4l2_task_runner_; const VideoCaptureDevice::Name device_name_; const int power_line_frequency_; // The following members are only known on AllocateAndStart(). VideoCaptureFormat capture_format_; v4l2_format video_fmt_; scoped_ptr<VideoCaptureDevice::Client> client_; base::ScopedFD device_fd_; // Vector of BufferTracker to keep track of mmap()ed pointers and their use. std::vector<scoped_refptr<BufferTracker>> buffer_tracker_pool_; bool is_capturing_; int timeout_count_; // Clockwise rotation in degrees. This value should be 0, 90, 180, or 270. int rotation_; DISALLOW_COPY_AND_ASSIGN(V4L2CaptureDelegate); }; } // namespace media #endif // MEDIA_VIDEO_CAPTURE_LINUX_V4L2_VIDEO_CAPTURE_DELEGATE_H_
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
350f828f534e66757e20ea1f11e51ae52533b0ce
568d064a62ba65d391ffdf3f813834795cee5ca0
/include/caffe/layers/elementhingeloss_layer.hpp
decbf5052120b7588b9a6f5f8733e6d072aa65ce
[]
no_license
zhjwustc/cvpr17_iter_deblur_matcaffe
5afb709333c95f8227ab3883ac9af074f6ef0d4a
4ad166f8234fff1a1c53070ea6dd120b955d71bb
refs/heads/master
2021-04-11T06:43:51.438868
2020-03-22T07:40:26
2020-03-22T07:40:26
249,000,935
2
0
null
null
null
null
UTF-8
C++
false
false
1,234
hpp
#ifndef CAFFE_CONCAT_LAYER_HPP_ #define CAFFE_CONCAT_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/layers/loss_layer.hpp" namespace caffe { template <typename Dtype> class ElementHingeLossLayer : public LossLayer<Dtype> { public: explicit ElementHingeLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param), sign_() {} virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "ElementHingeLoss"; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); Blob<Dtype> sign_; Blob<Dtype> one_; Dtype scale_factor_; }; } // namespace caffe #endif // CAFFE_CONCAT_LAYER_HPP_
[ "zhangjiawei@sensetime.com" ]
zhangjiawei@sensetime.com
202c4734f09b357109ad0043ddc026f45fcab6b9
ac6cf4c5cca2279cdf1f915173fc7f32e2ad23a3
/objects/rmp.pb.cc
277f5d1758ab3fd386d6ab0303a6141dba733cda
[ "Zlib" ]
permissive
johnpatek/record-manager
abbf584cd0253fe540289e492a550696aea7fff8
af28877c6a7f47a4c33e2e9c0c7baa8fa0a4a944
refs/heads/master
2023-02-28T18:42:00.776381
2021-02-11T02:48:10
2021-02-11T02:48:10
310,980,589
1
0
Zlib
2021-02-11T02:34:49
2020-11-08T03:51:26
C++
UTF-8
C++
false
true
50,511
cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: rmp.proto #include "rmp.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG extern PROTOBUF_INTERNAL_EXPORT_rmp_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_info_rmp_2eproto; extern PROTOBUF_INTERNAL_EXPORT_rmp_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_record_rmp_2eproto; namespace rmp { class infoDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<info> _instance; } _info_default_instance_; class recordDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<record> _instance; } _record_default_instance_; class bucketDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<bucket> _instance; } _bucket_default_instance_; class requestDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<request> _instance; } _request_default_instance_; class responseDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<response> _instance; } _response_default_instance_; } // namespace rmp static void InitDefaultsscc_info_bucket_rmp_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::rmp::_bucket_default_instance_; new (ptr) ::rmp::bucket(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_bucket_rmp_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_bucket_rmp_2eproto}, { &scc_info_record_rmp_2eproto.base,}}; static void InitDefaultsscc_info_info_rmp_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::rmp::_info_default_instance_; new (ptr) ::rmp::info(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_info_rmp_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_info_rmp_2eproto}, {}}; static void InitDefaultsscc_info_record_rmp_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::rmp::_record_default_instance_; new (ptr) ::rmp::record(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_record_rmp_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_record_rmp_2eproto}, { &scc_info_info_rmp_2eproto.base,}}; static void InitDefaultsscc_info_request_rmp_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::rmp::_request_default_instance_; new (ptr) ::rmp::request(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_request_rmp_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_request_rmp_2eproto}, { &scc_info_record_rmp_2eproto.base,}}; static void InitDefaultsscc_info_response_rmp_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::rmp::_response_default_instance_; new (ptr) ::rmp::response(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_response_rmp_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_response_rmp_2eproto}, {}}; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_rmp_2eproto[5]; static const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* file_level_enum_descriptors_rmp_2eproto[2]; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_rmp_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_rmp_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::rmp::info, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::rmp::info, name_), PROTOBUF_FIELD_OFFSET(::rmp::info, phone_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::rmp::record, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::rmp::record, email_), PROTOBUF_FIELD_OFFSET(::rmp::record, contact_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::rmp::bucket, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::rmp::bucket, records_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::rmp::request, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::rmp::request, command_), PROTOBUF_FIELD_OFFSET(::rmp::request, payload_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::rmp::response, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::rmp::response, status_), PROTOBUF_FIELD_OFFSET(::rmp::response, payload_), }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::rmp::info)}, { 7, -1, sizeof(::rmp::record)}, { 14, -1, sizeof(::rmp::bucket)}, { 20, -1, sizeof(::rmp::request)}, { 27, -1, sizeof(::rmp::response)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::rmp::_info_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::rmp::_record_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::rmp::_bucket_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::rmp::_request_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::rmp::_response_default_instance_), }; const char descriptor_table_protodef_rmp_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\trmp.proto\022\003rmp\"#\n\004info\022\014\n\004name\030\001 \001(\t\022\r" "\n\005phone\030\002 \001(\t\"3\n\006record\022\r\n\005email\030\001 \001(\t\022\032" "\n\007contact\030\002 \001(\0132\t.rmp.info\"&\n\006bucket\022\034\n\007" "records\030\001 \003(\0132\013.rmp.record\"8\n\007request\022\017\n" "\007command\030\001 \001(\r\022\034\n\007payload\030\002 \001(\0132\013.rmp.re" "cord\"+\n\010response\022\016\n\006status\030\001 \001(\r\022\017\n\007payl" "oad\030\002 \001(\t*=\n\rcommand_codes\022\n\n\006CREATE_RECORD\020\000\022\010" "\n\004READ_RECORD\020\001\022\n\n\006UPDATE_RECORD\020\002\022\n\n\006DELETE_RECORD\020\003*!\n\014stat" "us_codes\022\010\n\004GOOD\020\000\022\007\n\003BAD\020\001b\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_rmp_2eproto_deps[1] = { }; static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_rmp_2eproto_sccs[5] = { &scc_info_bucket_rmp_2eproto.base, &scc_info_info_rmp_2eproto.base, &scc_info_record_rmp_2eproto.base, &scc_info_request_rmp_2eproto.base, &scc_info_response_rmp_2eproto.base, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_rmp_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_rmp_2eproto = { false, false, descriptor_table_protodef_rmp_2eproto, "rmp.proto", 355, &descriptor_table_rmp_2eproto_once, descriptor_table_rmp_2eproto_sccs, descriptor_table_rmp_2eproto_deps, 5, 0, schemas, file_default_instances, TableStruct_rmp_2eproto::offsets, file_level_metadata_rmp_2eproto, 5, file_level_enum_descriptors_rmp_2eproto, file_level_service_descriptors_rmp_2eproto, }; // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_rmp_2eproto(&descriptor_table_rmp_2eproto); namespace rmp { const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* command_codes_descriptor() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_rmp_2eproto); return file_level_enum_descriptors_rmp_2eproto[0]; } bool command_codes_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: return true; default: return false; } } const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* status_codes_descriptor() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_rmp_2eproto); return file_level_enum_descriptors_rmp_2eproto[1]; } bool status_codes_IsValid(int value) { switch (value) { case 0: case 1: return true; default: return false; } } // =================================================================== class info::_Internal { public: }; info::info(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:rmp.info) } info::info(const info& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_name().empty()) { name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_name(), GetArena()); } phone_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_phone().empty()) { phone_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_phone(), GetArena()); } // @@protoc_insertion_point(copy_constructor:rmp.info) } void info::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_info_rmp_2eproto.base); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); phone_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } info::~info() { // @@protoc_insertion_point(destructor:rmp.info) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void info::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); phone_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void info::ArenaDtor(void* object) { info* _this = reinterpret_cast< info* >(object); (void)_this; } void info::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void info::SetCachedSize(int size) const { _cached_size_.Set(size); } const info& info::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_info_rmp_2eproto.base); return *internal_default_instance(); } void info::Clear() { // @@protoc_insertion_point(message_clear_start:rmp.info) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; name_.ClearToEmpty(); phone_.ClearToEmpty(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* info::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // string name = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "rmp.info.name")); CHK_(ptr); } else goto handle_unusual; continue; // string phone = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_phone(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "rmp.info.phone")); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* info::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:rmp.info) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_name().data(), static_cast<int>(this->_internal_name().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "rmp.info.name"); target = stream->WriteStringMaybeAliased( 1, this->_internal_name(), target); } // string phone = 2; if (this->phone().size() > 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_phone().data(), static_cast<int>(this->_internal_phone().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "rmp.info.phone"); target = stream->WriteStringMaybeAliased( 2, this->_internal_phone(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:rmp.info) return target; } size_t info::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:rmp.info) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_name()); } // string phone = 2; if (this->phone().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_phone()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void info::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:rmp.info) GOOGLE_DCHECK_NE(&from, this); const info* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<info>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:rmp.info) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:rmp.info) MergeFrom(*source); } } void info::MergeFrom(const info& from) { // @@protoc_insertion_point(class_specific_merge_from_start:rmp.info) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.name().size() > 0) { _internal_set_name(from._internal_name()); } if (from.phone().size() > 0) { _internal_set_phone(from._internal_phone()); } } void info::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:rmp.info) if (&from == this) return; Clear(); MergeFrom(from); } void info::CopyFrom(const info& from) { // @@protoc_insertion_point(class_specific_copy_from_start:rmp.info) if (&from == this) return; Clear(); MergeFrom(from); } bool info::IsInitialized() const { return true; } void info::InternalSwap(info* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); phone_.Swap(&other->phone_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } ::PROTOBUF_NAMESPACE_ID::Metadata info::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== class record::_Internal { public: static const ::rmp::info& contact(const record* msg); }; const ::rmp::info& record::_Internal::contact(const record* msg) { return *msg->contact_; } record::record(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:rmp.record) } record::record(const record& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); email_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_email().empty()) { email_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_email(), GetArena()); } if (from._internal_has_contact()) { contact_ = new ::rmp::info(*from.contact_); } else { contact_ = nullptr; } // @@protoc_insertion_point(copy_constructor:rmp.record) } void record::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_record_rmp_2eproto.base); email_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); contact_ = nullptr; } record::~record() { // @@protoc_insertion_point(destructor:rmp.record) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void record::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); email_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete contact_; } void record::ArenaDtor(void* object) { record* _this = reinterpret_cast< record* >(object); (void)_this; } void record::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void record::SetCachedSize(int size) const { _cached_size_.Set(size); } const record& record::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_record_rmp_2eproto.base); return *internal_default_instance(); } void record::Clear() { // @@protoc_insertion_point(message_clear_start:rmp.record) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; email_.ClearToEmpty(); if (GetArena() == nullptr && contact_ != nullptr) { delete contact_; } contact_ = nullptr; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* record::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // string email = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_email(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "rmp.record.email")); CHK_(ptr); } else goto handle_unusual; continue; // .rmp.info contact = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ctx->ParseMessage(_internal_mutable_contact(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* record::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:rmp.record) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string email = 1; if (this->email().size() > 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_email().data(), static_cast<int>(this->_internal_email().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "rmp.record.email"); target = stream->WriteStringMaybeAliased( 1, this->_internal_email(), target); } // .rmp.info contact = 2; if (this->has_contact()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 2, _Internal::contact(this), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:rmp.record) return target; } size_t record::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:rmp.record) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string email = 1; if (this->email().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_email()); } // .rmp.info contact = 2; if (this->has_contact()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *contact_); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void record::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:rmp.record) GOOGLE_DCHECK_NE(&from, this); const record* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<record>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:rmp.record) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:rmp.record) MergeFrom(*source); } } void record::MergeFrom(const record& from) { // @@protoc_insertion_point(class_specific_merge_from_start:rmp.record) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.email().size() > 0) { _internal_set_email(from._internal_email()); } if (from.has_contact()) { _internal_mutable_contact()->::rmp::info::MergeFrom(from._internal_contact()); } } void record::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:rmp.record) if (&from == this) return; Clear(); MergeFrom(from); } void record::CopyFrom(const record& from) { // @@protoc_insertion_point(class_specific_copy_from_start:rmp.record) if (&from == this) return; Clear(); MergeFrom(from); } bool record::IsInitialized() const { return true; } void record::InternalSwap(record* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); email_.Swap(&other->email_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); swap(contact_, other->contact_); } ::PROTOBUF_NAMESPACE_ID::Metadata record::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== class bucket::_Internal { public: }; bucket::bucket(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), records_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:rmp.bucket) } bucket::bucket(const bucket& from) : ::PROTOBUF_NAMESPACE_ID::Message(), records_(from.records_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:rmp.bucket) } void bucket::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_bucket_rmp_2eproto.base); } bucket::~bucket() { // @@protoc_insertion_point(destructor:rmp.bucket) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void bucket::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void bucket::ArenaDtor(void* object) { bucket* _this = reinterpret_cast< bucket* >(object); (void)_this; } void bucket::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void bucket::SetCachedSize(int size) const { _cached_size_.Set(size); } const bucket& bucket::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_bucket_rmp_2eproto.base); return *internal_default_instance(); } void bucket::Clear() { // @@protoc_insertion_point(message_clear_start:rmp.bucket) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; records_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* bucket::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // repeated .rmp.record records = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_records(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr)); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* bucket::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:rmp.bucket) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .rmp.record records = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_records_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(1, this->_internal_records(i), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:rmp.bucket) return target; } size_t bucket::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:rmp.bucket) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .rmp.record records = 1; total_size += 1UL * this->_internal_records_size(); for (const auto& msg : this->records_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void bucket::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:rmp.bucket) GOOGLE_DCHECK_NE(&from, this); const bucket* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<bucket>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:rmp.bucket) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:rmp.bucket) MergeFrom(*source); } } void bucket::MergeFrom(const bucket& from) { // @@protoc_insertion_point(class_specific_merge_from_start:rmp.bucket) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; records_.MergeFrom(from.records_); } void bucket::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:rmp.bucket) if (&from == this) return; Clear(); MergeFrom(from); } void bucket::CopyFrom(const bucket& from) { // @@protoc_insertion_point(class_specific_copy_from_start:rmp.bucket) if (&from == this) return; Clear(); MergeFrom(from); } bool bucket::IsInitialized() const { return true; } void bucket::InternalSwap(bucket* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); records_.InternalSwap(&other->records_); } ::PROTOBUF_NAMESPACE_ID::Metadata bucket::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== class request::_Internal { public: static const ::rmp::record& payload(const request* msg); }; const ::rmp::record& request::_Internal::payload(const request* msg) { return *msg->payload_; } request::request(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:rmp.request) } request::request(const request& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_payload()) { payload_ = new ::rmp::record(*from.payload_); } else { payload_ = nullptr; } command_ = from.command_; // @@protoc_insertion_point(copy_constructor:rmp.request) } void request::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_request_rmp_2eproto.base); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&payload_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&command_) - reinterpret_cast<char*>(&payload_)) + sizeof(command_)); } request::~request() { // @@protoc_insertion_point(destructor:rmp.request) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void request::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); if (this != internal_default_instance()) delete payload_; } void request::ArenaDtor(void* object) { request* _this = reinterpret_cast< request* >(object); (void)_this; } void request::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void request::SetCachedSize(int size) const { _cached_size_.Set(size); } const request& request::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_request_rmp_2eproto.base); return *internal_default_instance(); } void request::Clear() { // @@protoc_insertion_point(message_clear_start:rmp.request) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArena() == nullptr && payload_ != nullptr) { delete payload_; } payload_ = nullptr; command_ = 0u; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* request::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // uint32 command = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { command_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // .rmp.record payload = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ctx->ParseMessage(_internal_mutable_payload(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* request::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:rmp.request) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 command = 1; if (this->command() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_command(), target); } // .rmp.record payload = 2; if (this->has_payload()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 2, _Internal::payload(this), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:rmp.request) return target; } size_t request::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:rmp.request) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // .rmp.record payload = 2; if (this->has_payload()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *payload_); } // uint32 command = 1; if (this->command() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_command()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void request::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:rmp.request) GOOGLE_DCHECK_NE(&from, this); const request* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<request>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:rmp.request) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:rmp.request) MergeFrom(*source); } } void request::MergeFrom(const request& from) { // @@protoc_insertion_point(class_specific_merge_from_start:rmp.request) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.has_payload()) { _internal_mutable_payload()->::rmp::record::MergeFrom(from._internal_payload()); } if (from.command() != 0) { _internal_set_command(from._internal_command()); } } void request::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:rmp.request) if (&from == this) return; Clear(); MergeFrom(from); } void request::CopyFrom(const request& from) { // @@protoc_insertion_point(class_specific_copy_from_start:rmp.request) if (&from == this) return; Clear(); MergeFrom(from); } bool request::IsInitialized() const { return true; } void request::InternalSwap(request* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(request, command_) + sizeof(request::command_) - PROTOBUF_FIELD_OFFSET(request, payload_)>( reinterpret_cast<char*>(&payload_), reinterpret_cast<char*>(&other->payload_)); } ::PROTOBUF_NAMESPACE_ID::Metadata request::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== class response::_Internal { public: }; response::response(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:rmp.response) } response::response(const response& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); payload_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (!from._internal_payload().empty()) { payload_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_payload(), GetArena()); } status_ = from.status_; // @@protoc_insertion_point(copy_constructor:rmp.response) } void response::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_response_rmp_2eproto.base); payload_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); status_ = 0u; } response::~response() { // @@protoc_insertion_point(destructor:rmp.response) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void response::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); payload_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void response::ArenaDtor(void* object) { response* _this = reinterpret_cast< response* >(object); (void)_this; } void response::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void response::SetCachedSize(int size) const { _cached_size_.Set(size); } const response& response::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_response_rmp_2eproto.base); return *internal_default_instance(); } void response::Clear() { // @@protoc_insertion_point(message_clear_start:rmp.response) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; payload_.ClearToEmpty(); status_ = 0u; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* response::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // uint32 status = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // string payload = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_payload(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "rmp.response.payload")); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* response::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:rmp.response) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 status = 1; if (this->status() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_status(), target); } // string payload = 2; if (this->payload().size() > 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_payload().data(), static_cast<int>(this->_internal_payload().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "rmp.response.payload"); target = stream->WriteStringMaybeAliased( 2, this->_internal_payload(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:rmp.response) return target; } size_t response::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:rmp.response) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string payload = 2; if (this->payload().size() > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_payload()); } // uint32 status = 1; if (this->status() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_status()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void response::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:rmp.response) GOOGLE_DCHECK_NE(&from, this); const response* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<response>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:rmp.response) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:rmp.response) MergeFrom(*source); } } void response::MergeFrom(const response& from) { // @@protoc_insertion_point(class_specific_merge_from_start:rmp.response) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.payload().size() > 0) { _internal_set_payload(from._internal_payload()); } if (from.status() != 0) { _internal_set_status(from._internal_status()); } } void response::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:rmp.response) if (&from == this) return; Clear(); MergeFrom(from); } void response::CopyFrom(const response& from) { // @@protoc_insertion_point(class_specific_copy_from_start:rmp.response) if (&from == this) return; Clear(); MergeFrom(from); } bool response::IsInitialized() const { return true; } void response::InternalSwap(response* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); payload_.Swap(&other->payload_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); swap(status_, other->status_); } ::PROTOBUF_NAMESPACE_ID::Metadata response::GetMetadata() const { return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace rmp PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::rmp::info* Arena::CreateMaybeMessage< ::rmp::info >(Arena* arena) { return Arena::CreateMessageInternal< ::rmp::info >(arena); } template<> PROTOBUF_NOINLINE ::rmp::record* Arena::CreateMaybeMessage< ::rmp::record >(Arena* arena) { return Arena::CreateMessageInternal< ::rmp::record >(arena); } template<> PROTOBUF_NOINLINE ::rmp::bucket* Arena::CreateMaybeMessage< ::rmp::bucket >(Arena* arena) { return Arena::CreateMessageInternal< ::rmp::bucket >(arena); } template<> PROTOBUF_NOINLINE ::rmp::request* Arena::CreateMaybeMessage< ::rmp::request >(Arena* arena) { return Arena::CreateMessageInternal< ::rmp::request >(arena); } template<> PROTOBUF_NOINLINE ::rmp::response* Arena::CreateMaybeMessage< ::rmp::response >(Arena* arena) { return Arena::CreateMessageInternal< ::rmp::response >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
[ "johnpatek2@gmail.com" ]
johnpatek2@gmail.com
2286e748ca8c1cac89e57d4142f5f017e42cfeaf
4928540346a07792d83c06471be0307f03b6c106
/source/modules/core/core.cpp
e17a5d44db66ee1a44679373c353445788fdee0d
[]
no_license
n-suudai/Waffle
ef89198450731496410ec80a7e40945178fa714e
ba40886aeaf58b385be91bfdcf0be7f00fbc8943
refs/heads/main
2023-02-10T04:06:32.676694
2021-01-13T07:55:54
2021-01-13T07:55:54
313,647,359
0
0
null
null
null
null
UTF-8
C++
false
false
1,651
cpp
#include "modules/core/core.h" namespace waffle { namespace core { bool initialize() { logging::put("[core] initialized."); return true; } void finalize() { logging::put("[core] finalized."); } class CoreEntry final : public modules::Entry { public: [[nodiscard]] static bool createShared( SharedPtr<modules::Entry>& moduleEntry, modules::RuntimeModules& runtimeModules) { SharedPtr<CoreEntry> ptr = WFL_MAKE_SHARED(CoreEntry, runtimeModules); if (ptr) { moduleEntry = wfl::move(ptr); return true; } return false; } CoreEntry(modules::RuntimeModules& modules) : Entry(modules) {} bool entry() override { using namespace modules; if (!moduleEntry(EntryPoint::Initialize, wfl::bind(&CoreEntry::initialize, this))) { return false; } if (!moduleEntry(EntryPoint::Finalize, wfl::bind(&CoreEntry::finalize, this))) { return false; } return true; } String moduleName() const override { return "core"; } const void* getProperty(const String&) const override { return nullptr; } private: bool initialize() { return core::initialize(); } bool finalize() { core::finalize(); return true; } }; bool moduleEntry( SharedPtr<modules::Entry>& moduleEntry, modules::RuntimeModules& runtimeModules) { return CoreEntry::createShared( moduleEntry, runtimeModules); } } // namespace core } // namespace waffle
[ "34059792+n-suudai@users.noreply.github.com" ]
34059792+n-suudai@users.noreply.github.com
7bb04c33d883105187c505f75ef974b6f595092f
9f6e21f2bf4c972f7eb316e2e4871df001c7cd10
/SEM II/CSE/C++ PRACTICALS/PRACTICALx1x3.cpp
26ffc059a17031977937d783a8acf2593846defc
[]
no_license
sarthakjain95/UPESx162
261569d8efe280fe81fd7e2424426b7bff3f2f1a
61f6ce8b4d191c50be32fe8d16777a2663adfc39
refs/heads/master
2022-10-30T00:44:20.124446
2022-10-11T10:24:50
2022-10-11T10:24:50
200,659,523
6
2
null
2019-09-25T13:12:11
2019-08-05T13:21:02
Python
UTF-8
C++
false
false
662
cpp
// Practical 1 // Title: Classes and Objects // Objective: To understand the concept of classes and objects, data hiding and encapsulation // Convert Decimal number into a Binary Number using 1D array. #include<iostream> #include<cstdio> #include<cstdlib> int main(){ int n; printf("\nEnter Number:"); std::cin>>n; int size= sizeof(int)*8; bool bin[ size ]; for(int x=0; x<size; x++) bin[x]= false; int pos=0; while(n!=0){ if( n&0x1 ) bin[pos]= true; else bin[pos]= false; n>>=1; pos++; } pos--; printf("\nBinary Equivalent:"); while(pos>=0){ if(bin[pos]) printf("1"); else printf("0"); pos--; } printf("\n"); return 0; }
[ "saarthakjain95@gmail.com" ]
saarthakjain95@gmail.com
86c3916d7c89723fffba5d642f8e8deafe7f6b8f
297497957c531d81ba286bc91253fbbb78b4d8be
/third_party/libwebrtc/rtc_tools/psnr_ssim_analyzer/psnr_ssim_analyzer.cc
cef9171681f870afecee6f274af8bbc4492d0b4b
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
marco-c/gecko-dev-comments-removed
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
61942784fb157763e65608e5a29b3729b0aa66fa
refs/heads/master
2023-08-09T18:55:25.895853
2023-08-01T00:40:39
2023-08-01T00:40:39
211,297,481
0
0
NOASSERTION
2019-09-29T01:27:49
2019-09-27T10:44:24
C++
UTF-8
C++
false
false
2,886
cc
#include <stdio.h> #include <stdlib.h> #include <algorithm> #include <string> #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "absl/flags/usage.h" #include "api/scoped_refptr.h" #include "api/video/video_frame_buffer.h" #include "rtc_tools/frame_analyzer/video_quality_analysis.h" #include "rtc_tools/video_file_reader.h" ABSL_FLAG(std::string, results_file, "results.txt", "The full name of the file where the results will be written"); ABSL_FLAG(std::string, reference_file, "ref.yuv", "The reference YUV file to compare against"); ABSL_FLAG(std::string, test_file, "test.yuv", "The test YUV file to run the analysis for"); void CompareFiles( const rtc::scoped_refptr<webrtc::test::Video>& reference_video, const rtc::scoped_refptr<webrtc::test::Video>& test_video, const char* results_file_name) { FILE* results_file = fopen(results_file_name, "w"); const size_t num_frames = std::min(reference_video->number_of_frames(), test_video->number_of_frames()); for (size_t i = 0; i < num_frames; ++i) { const rtc::scoped_refptr<webrtc::I420BufferInterface> ref_buffer = reference_video->GetFrame(i); const rtc::scoped_refptr<webrtc::I420BufferInterface> test_buffer = test_video->GetFrame(i); double result_psnr = webrtc::test::Psnr(ref_buffer, test_buffer); double result_ssim = webrtc::test::Ssim(ref_buffer, test_buffer); fprintf(results_file, "Frame: %zu, PSNR: %f, SSIM: %f\n", i, result_psnr, result_ssim); } fclose(results_file); } int main(int argc, char* argv[]) { absl::SetProgramUsageMessage( "Runs PSNR and SSIM on two I420 videos and write the" "results in a file.\n" "Example usage:\n" "./psnr_ssim_analyzer --reference_file=ref.yuv " "--test_file=test.yuv --results_file=results.txt\n"); absl::ParseCommandLine(argc, argv); rtc::scoped_refptr<webrtc::test::Video> reference_video = webrtc::test::OpenY4mFile(absl::GetFlag(FLAGS_reference_file)); rtc::scoped_refptr<webrtc::test::Video> test_video = webrtc::test::OpenY4mFile(absl::GetFlag(FLAGS_test_file)); if (!reference_video || !test_video) { fprintf(stderr, "Error opening video files\n"); return 0; } if (reference_video->width() != test_video->width() || reference_video->height() != test_video->height()) { fprintf(stderr, "Reference and test video files do not have same size: %dx%d " "versus %dx%d\n", reference_video->width(), reference_video->height(), test_video->width(), test_video->height()); return 0; } CompareFiles(reference_video, test_video, absl::GetFlag(FLAGS_results_file).c_str()); return 0; }
[ "mcastelluccio@mozilla.com" ]
mcastelluccio@mozilla.com
5883a7c34c3ffe083a44504403e1603a57b18117
5057e85af9fbcff05b5235caa0e64bad447d4626
/Code Forces/Code forces 1073 B - Vasya and Books.cpp
68fe79125825aa4dd83f04089e3229a93ac8c723
[ "MIT" ]
permissive
mayankrajput843/Competitive-Programming-Solutions
5bf96bac502dbd620e4e21c41bff1afc814ab840
6a992f3240f2369236829524f2f3798f80bd3219
refs/heads/master
2023-08-02T06:04:11.283446
2021-10-03T11:37:17
2021-10-03T11:37:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,494
cpp
Author Sofen Hoque Anonta #Problm #include iostream #include sstream #include cstdio #include climits #include map #include vector #include cmath #include queue #include algorithm #include utility #include string #include cstring using namespace std; namespace { typedef long long LL; typedef vectorint vint; typedef pairint,int pint; typedef unsigned long long ULL; int CC_; #define sf scanf #define pf printf #define PP cin.get(); #define NL coutendl; template class Tvoid DA(T i,T e){while(i!=e){coutCon( ++CC_ ) i++endl;}} template class Tvoid DA(T x, int l){for(int i=0; il;i++)cout[i] x[i]endl;} #define DC(x_) cout #x_n;DA(x_.begin(), x_.end()); #define DD(x_) cout( ++CC_ ) #x_ x_endl; #define SS printf(_LOOOOOK@MEEEEEEEEEEEEEEE( %d )n,++CC_); int ABS(int n){ return n 0 -1n n; } const double EPS= 1E-9; const double PI= 2acos(0.0); const long long MOD= 1000000007; } int rmap[200005]; int arr[200005]; void solve(){ int n; scanf(%d, &n); for(int i= 0; in; i++){ scanf(%d, &arr[i]); cinarr[i]; rmap[arr[i]] = i; } int m, upto= -1; for(int i= 0; in; i++){ cinm; scanf(%d, &m); int taken = rmap[m]-upto; if(taken 0){ taken = 0; } cout taken ; printf(%d , taken); upto = max(upto, rmap[m]); } } int main(){ ios_basesync_with_stdio(false); cin.tie(NULL); freopen(Finput.txt, r, stdin); solve(); return 0; }
[ "SH-anonta@users.noreply.github.com" ]
SH-anonta@users.noreply.github.com
31b22d6190a16701a4997c9fb5adf19d27a2c9c5
c7a0a74ec7470fa3051e398ca879599c9f58e39c
/include/bb/MetricsBinaryAccuracy.h
d310dc9cc1dfb63f443554b10c69bf587b7af908
[ "MIT" ]
permissive
ryuz/BinaryBrain
cd79019f4b1cbc5b7c03889f4274b7b06d082eeb
d03c890e2da046f5cb5567856a748f31a3726cba
refs/heads/master
2023-08-29T11:32:01.912092
2023-08-15T09:26:18
2023-08-15T09:26:18
143,534,336
105
15
MIT
2023-08-15T09:26:20
2018-08-04T14:10:46
C++
UTF-8
C++
false
false
2,493
h
// -------------------------------------------------------------------------- // Binary Brain -- binary neural net framework // // Copyright (C) 2018 by Ryuji Fuchikami // https://github.com/ryuz // ryuji.fuchikami@nifty.com // -------------------------------------------------------------------------- #pragma once #include <iostream> #include <vector> #include "bb/MetricsFunction.h" namespace bb { template <typename T = float> class MetricsBinaryAccuracy : public MetricsFunction { using _super = MetricsFunction; public: static inline std::string MetricsFunctionName(void) { return "MetricsBinaryAccuracy"; } static inline std::string ObjectName(void){ return MetricsFunctionName() + "_" + DataType<T>::Name(); } std::string GetMetricsFunctionName(void) const override { return MetricsFunctionName(); } std::string GetObjectName(void) const override { return ObjectName(); } protected: index_t m_frames = 0; double m_accuracy = 0; protected: MetricsBinaryAccuracy() {} public: ~MetricsBinaryAccuracy() {} static std::shared_ptr<MetricsBinaryAccuracy> Create() { auto self = std::shared_ptr<MetricsBinaryAccuracy>(new MetricsBinaryAccuracy); return self; } void Clear(void) { m_accuracy = 0; m_frames = 0; } double GetMetrics(void) const { return m_accuracy/ (double)m_frames; } void CalculateMetrics(FrameBuffer y, FrameBuffer t) { BB_ASSERT(y.GetType() == DataType<T>::type); BB_ASSERT(t.GetType() == DataType<T>::type); index_t frame_size = y.GetFrameSize(); index_t node_size = y.GetNodeSize(); auto y_ptr = y.LockConst<T>(); auto t_ptr = t.LockConst<T>(); for (index_t frame = 0; frame < frame_size; ++frame) { for (index_t node = 0; node < node_size; ++node) { T sig_val = y_ptr.Get(frame, node); T exp_val = t_ptr.Get(frame, node); bool sig = (y_ptr.Get(frame, node) >= (T)0.5); bool exp = (t_ptr.Get(frame, node) >= (T)0.5); // std::cout << " " << exp << " " << sig << std::endl; if (sig == exp) { m_accuracy += 1.0; } } } m_frames += frame_size; } }; }
[ "ryuji.fuchikami@nifty.com" ]
ryuji.fuchikami@nifty.com
d376141e1759916358a7371d04c494a9660f0c12
947ecfef4e859bb0e26fe61acc93f1760b5abc24
/Demos/WkeBrowser/MainWnd.h
eefe35f23029d78f2c272f222d081cb2f79e9453
[]
no_license
justdone32/DuiLib_Ultimate
3869b350848fd955404c2bc420b1da5b87928ef7
7165b75f08b9e6a8b5f942aebb27f8fbed0404e9
refs/heads/master
2021-05-15T13:23:13.430804
2017-10-15T15:33:18
2017-10-15T15:33:18
107,084,475
1
0
null
2017-10-16T06:02:36
2017-10-16T06:02:36
null
GB18030
C++
false
false
2,423
h
#pragma once ////////////////////////////////////////////////////////////////////////// /// #include "3rd/TroyControls/Include/TroyControls.h" #include "WkeWebkit.h" typedef struct _tagTabInfo { UINT64 nID; TCHAR szUrl[2048]; TCHAR szTitle[256]; TCHAR szFavUrl[2048]; TCHAR szFavName[256]; CBrowserTab* pTab; CWkeWebkitUI* pWebBrowser; }TabInfo; class CMainWnd : public WindowImplBase, public IWkeCallback { public: CMainWnd(void); ~CMainWnd(void); public: // 初始化资源管理器 virtual void InitWindow(); virtual void OnFinalMessage( HWND ); virtual CDuiString GetSkinFile(); virtual LPCTSTR GetWindowClassName( void ) const; DUI_DECLARE_MESSAGE_MAP() virtual void OnClick(TNotifyUI& msg); virtual void OnSelectChanged( TNotifyUI &msg ); virtual void OnTabIndexChanged( TNotifyUI &msg ); virtual void OnTabClosed( TNotifyUI &msg ); virtual void OnReturn( TNotifyUI &msg ); virtual LRESULT OnSysCommand( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled ); LRESULT HandleCustomMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); public: int CreateNewTab(int nIndex, LPCTSTR pstrUrl = NULL); int CreateNewTabAndGo(LPCTSTR pstrUrl = NULL); CWkeWebkitUI* GetCurWeb(); void AddressGo(); void SearchGo(); void Back(); void Forward(); void Home(); void Refresh(); public: virtual void OnWkeTitleChanged(CWkeWebkitUI* webView, LPCTSTR title); virtual void OnWkeURLChanged(CWkeWebkitUI* webView, LPCTSTR url); virtual void OnWkeAlertBox(CWkeWebkitUI* webView, LPCTSTR msg); virtual bool OnWkeNavigation(CWkeWebkitUI* webView, wkeNavigationType navigationType, LPCTSTR url); virtual wkeWebView OnWkeCreateView(CWkeWebkitUI* webView, const wkeNewViewInfo* info); virtual void OnWkeDocumentReady(CWkeWebkitUI* webView, const wkeDocumentReadyInfo* info); virtual void OnWkeLoadingFinish(CWkeWebkitUI* webView, const LPCTSTR url, wkeLoadingResult result, LPCTSTR failedReason); virtual LPCTSTR OnJS2Native(CWkeWebkitUI *pWeb, LPCTSTR lpMethod, LPCTSTR lpContent, void *pListenObj); private: CButtonUI* m_pCloseBtn; CButtonUI* m_pMaxBtn; CButtonUI* m_pRestoreBtn; CButtonUI* m_pMinBtn; CButtonUI* m_pMenuBtn; CEditUI* m_pAddressEdit; CEditUI* m_pSearchEdit; CBrowserTabBar* m_pBrowserTabBar; CTabLayoutUI* m_pBrowserTabBody; std::vector<TabInfo*> m_vTabs; int m_nTabID; };
[ "qdtroy@qq.com" ]
qdtroy@qq.com
d573745762da5f7a9af31d11be768500137789a3
bb5b047319ab327acc1363df5a94bdcd2a8a430e
/SENSITIVE_COUTURE/main.cpp
287719b74cca80b6466f8ca9a86bc741ee213984
[]
no_license
CAD-Works/Sensitive-Couture-for-Interactive-Garment-Modeling-and-Editing
eb7aa2ad3f99a494681ee6947d4cc7fc3e02e6ae
f476f964980784ab49df8b42ebfe75ab359827ee
refs/heads/master
2022-01-05T10:25:24.169475
2018-09-05T01:28:23
2018-09-05T01:28:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
37,093
cpp
/* * main.cpp * sensitive couture * * Created by Nobuyuki Umetani on 9/14/10. * Copyright 2010 The University of Tokyo and Columbia University. All rights reserved. * */ //#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"") #pragma warning( disable : 4786 ) #include <iostream> #include <iomanip> #include <sstream> #include <fstream> #include <vector> #include <set> #include <string> #include <assert.h> #include <math.h> #include <stdlib.h> #if defined(__APPLE__) && defined(__MACH__) #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include "delfem/camera.h" #include "analysis2d_cloth_static.h" #include "designer2d_cloth.h" double mov_begin_x, mov_begin_y; // ÉJÅ[É\Éãà íuÇÃê≥ãKç¿ïW int imodifier; bool is_lighting = true; bool is_animation = true; CDesigner2D_Cloth gui_listner; CAnalysis2D_Cloth_Static* pAnalysis = 0; Com::View::CCamera camera_l; Com::View::CCamera camera_r; Com::View::CDrawerCoord drawer_coord; unsigned int iclass_type = 0; int iwin_des, iwin_sim; int imenu_right_click; // 0:drag // 1:dart cut // 2:curve_edit // 3:smooth // 4:slider 0 // 5:dart_cut not sew unsigned int imode_ope = 0; int islider_active = -1; std::string slider_name; bool is_active_slider = false; double pick_org[3]; double pick_sns[3]; //std::vector<double> aXY_Stroke; Com::CVector2D pos_pick, pos_relese; bool is_rubber_band = false; bool is_tex_mouse_pos = false; unsigned int m_texWidth, m_texHeight; unsigned int m_texName = 0; bool is_display_rotation = false; double display_rotation_theta = 0; void RenderBitmapString(float x, float y, void *font, char *string) { char *c; ::glRasterPos2f(x, y); for (c = string; *c != '\0'; c++) { ::glutBitmapCharacter(font, *c); } } void ShowTextDesign() { const bool is_lighting = glIsEnabled(GL_LIGHTING); int* pFont = (int*)GLUT_BITMAP_8_BY_13; GLint viewport[4]; ::glGetIntegerv(GL_VIEWPORT, viewport); const int win_w = viewport[2]; const int win_h = viewport[3]; ::glMatrixMode(GL_PROJECTION); ::glPushMatrix(); ::glLoadIdentity(); ::gluOrtho2D(0, win_w, 0, win_h); ::glMatrixMode(GL_MODELVIEW); ::glPushMatrix(); ::glLoadIdentity(); ::glScalef(1, -1, 1); ::glTranslatef(0, -win_h, 0); ::glDisable(GL_LIGHTING); // ::glDisable(GL_DEPTH_TEST); // 0:drag // 1:dart cut // 2:curve_edit // 3:smooth // 4:slider 0 char s_tmp[256]; { strcpy(s_tmp, "Press \' \' button to try different 3D model"); ::glColor3d(0.0, 0.0, 1.0); RenderBitmapString(10, 15, pFont, s_tmp); } { strcpy(s_tmp, "Click right button of mouse to change tool"); ::glColor3d(0.0, 0.0, 1.0); RenderBitmapString(10, 45, pFont, s_tmp); } { if (pAnalysis != 0) { if (pAnalysis->GetMode() == CLOTH_INITIAL_LOCATION) { strcpy(s_tmp, "Press \'b\' button to start simulation"); } else { strcpy(s_tmp, "Press \'b\' button to initialize"); } ::glColor3d(0.0, 0.0, 1.0); RenderBitmapString(10, 30, pFont, s_tmp); } } { strcpy(s_tmp, "Pan : Shift+Left drag, Zoom : Page Up/Down"); ::glColor3d(0.0, 0.0, 1.0); RenderBitmapString(10, 60, pFont, s_tmp); } if (imode_ope == 0) { strcpy(s_tmp, "Tool : Drag"); } else if (imode_ope == 1) { strcpy(s_tmp, "Tool : Dart Cutter"); } else if (imode_ope == 2) { strcpy(s_tmp, "Tool : Curve Edit"); } else if (imode_ope == 3) { strcpy(s_tmp, "Tool : Smooth"); } else if (imode_ope == 4) { strcpy(s_tmp, "Tool : Slider"); } else if (imode_ope == 5) { strcpy(s_tmp, "Tool : Hole"); } ::glColor3d(1.0, 0.0, 0.0); RenderBitmapString(10, 80, pFont, s_tmp); if (imode_ope == 4) { s_tmp[32]; strcpy(s_tmp, slider_name.c_str()); ::glColor3d(1, 0, 0); RenderBitmapString(10, win_h*0.95 - 13, pFont, s_tmp); } { strcpy(s_tmp, "Please wait a second at the beginning of mouse drag."); ::glColor3d(0.0, 0.0, 1.0); RenderBitmapString(10, win_h*0.95 - 26, pFont, s_tmp); } if (is_lighting) { ::glEnable(GL_LIGHTING); } ::glEnable(GL_DEPTH_TEST); ::glPopMatrix(); ::glMatrixMode(GL_PROJECTION); ::glPopMatrix(); ::glMatrixMode(GL_MODELVIEW); } void ShowTextSimulation() { int* pFont = (int*)GLUT_BITMAP_8_BY_13; static char s_fps[32]; { static int frame, timebase; int time; frame++; time = glutGet(GLUT_ELAPSED_TIME); if (time - timebase > 500) { // if (time - timebase > 5000) { sprintf(s_fps, "FPS:%4.2f", frame*1000.0 / (time - timebase)); timebase = time; frame = 0; } } GLint viewport[4]; ::glGetIntegerv(GL_VIEWPORT, viewport); const int win_w = viewport[2]; const int win_h = viewport[3]; ::glMatrixMode(GL_PROJECTION); ::glPushMatrix(); ::glLoadIdentity(); ::gluOrtho2D(0, win_w, 0, win_h); ::glMatrixMode(GL_MODELVIEW); ::glPushMatrix(); ::glLoadIdentity(); ::glScalef(1, -1, 1); ::glTranslatef(0, -win_h, 0); const bool is_lighting = glIsEnabled(GL_LIGHTING); ::glDisable(GL_LIGHTING); char s_tmp[256]; { strcpy(s_tmp, "Pan : Shift+Left drag, Zoom : Page Up/Down"); ::glColor3d(0.0, 0.0, 1.0); RenderBitmapString(10, 15, pFont, s_tmp); } { strcpy(s_tmp, "Rotation : Ctrl+Left drag"); ::glColor3d(0.0, 0.0, 1.0); RenderBitmapString(10, 30, pFont, s_tmp); } ::glColor3d(1.0, 0.0, 0.0); RenderBitmapString(10, 45, pFont, s_fps); if (is_lighting) { ::glEnable(GL_LIGHTING); } ::glEnable(GL_DEPTH_TEST); ::glPopMatrix(); ::glMatrixMode(GL_PROJECTION); ::glPopMatrix(); ::glMatrixMode(GL_MODELVIEW); } void myGlutMotion(int x, int y) { int viewport[4]; ::glGetIntegerv(GL_VIEWPORT, viewport); const int win_w = viewport[2]; const int win_h = viewport[3]; const double mov_end_x = (2.0*x - win_w) / win_w; const double mov_end_y = (win_h - 2.0*y) / win_h; //////////////// if (imodifier == GLUT_ACTIVE_SHIFT) { // pan if (glutGetWindow() == iwin_sim) { camera_r.MousePan(mov_begin_x, mov_begin_y, mov_end_x, mov_end_y); drawer_coord.SetTrans(camera_r); } else { camera_l.MousePan(mov_begin_x, mov_begin_y, mov_end_x, mov_end_y); drawer_coord.SetTrans(camera_l); } } else if (imodifier == GLUT_ACTIVE_CTRL) { // rotation if (glutGetWindow() == iwin_sim) { camera_r.MouseRotation(mov_begin_x, mov_begin_y, mov_end_x, mov_end_y); drawer_coord.SetTrans(camera_r); } } else { // pick and move if (glutGetWindow() == iwin_des) { if (imode_ope == 0) { Com::CVector3D oloc0, oloc1; oloc0 = camera_l.ProjectionOnPlane(mov_begin_x, mov_begin_y); if (is_tex_mouse_pos) { gui_listner.SetTextureCenter_FaceCAD(-0.5 + oloc0.x, -0.5 + oloc0.y); pAnalysis->SetTextureCenter(-0.5 + oloc0.x, -0.5 + oloc0.y); } oloc1 = camera_l.ProjectionOnPlane(mov_end_x, mov_end_y); Cad::CAD_ELEM_TYPE itype_cad_part; unsigned int id_cad_part; double tmp_x, tmp_y; gui_listner.Cad_GetPicked(itype_cad_part, id_cad_part, tmp_x, tmp_y); if (id_cad_part != 0) { bool res = gui_listner.Cad_Move(itype_cad_part, id_cad_part, Com::CVector2D(oloc0.x, oloc0.y), Com::CVector2D(oloc1.x, oloc1.y)); if (res && pAnalysis->GetMode() == SENSITIVITY_DONE) { pAnalysis->GuessSolutionMouseMove(oloc0.x, oloc0.y, oloc1.x, oloc1.y); } } } else if (imode_ope == 1 || imode_ope == 5) { const Com::CVector3D& oloc1 = camera_l.ProjectionOnPlane(mov_end_x, mov_end_y); pos_relese = Com::CVector2D(oloc1.x, oloc1.y); } else if (imode_ope == 2) { Cad::CAD_ELEM_TYPE itype_cad_part; unsigned int id_cad_part; double tmp_x, tmp_y; gui_listner.Cad_GetPicked(itype_cad_part, id_cad_part, tmp_x, tmp_y); if (itype_cad_part == Cad::EDGE && gui_listner.GetCad().IsElemID(itype_cad_part, id_cad_part)) { const Com::CVector3D& oloc = camera_l.ProjectionOnPlane(mov_end_x, mov_end_y); if (gui_listner.GetCad().GetEdgeCurveType(id_cad_part) == 1) { bool res = gui_listner.Cad_DragArc(id_cad_part, Com::CVector2D(oloc.x, oloc.y)); } else if (gui_listner.GetCad().GetEdgeCurveType(id_cad_part) == 2) { bool res = gui_listner.Cad_DragPolyline(id_cad_part, Com::CVector2D(oloc.x, oloc.y)); } if (pAnalysis->GetMode() != SIMULATION_STATIC && pAnalysis->GetMode() != CLOTH_INITIAL_LOCATION) { pAnalysis->PerformStaticSolver(); } } } else if (imode_ope == 3) { Cad::CAD_ELEM_TYPE itype_cad_part; unsigned int id_cad_part; double tmp_x, tmp_y; gui_listner.Cad_GetPicked(itype_cad_part, id_cad_part, tmp_x, tmp_y); if (itype_cad_part == Cad::EDGE && gui_listner.GetCad().IsElemID(itype_cad_part, id_cad_part)) { const Com::CVector3D& oloc = camera_l.ProjectionOnPlane(mov_begin_x, mov_begin_y); gui_listner.Cad_SmoothingPolylineEdge(id_cad_part, 3, Com::CVector2D(oloc.x, oloc.y), 0.1); if (pAnalysis->GetMode() != SIMULATION_STATIC && pAnalysis->GetMode() != CLOTH_INITIAL_LOCATION) { pAnalysis->PerformStaticSolver(); } } } else if (imode_ope == 4) { if (islider_active >= 0 && is_active_slider) { double min, max; const double val0 = gui_listner.GetValueSlider(islider_active, min, max); const double val1 = min + (mov_end_x + 1)*0.5*(max - min); gui_listner.SetValueSlider(islider_active, val1); const double val2 = gui_listner.GetValueSlider(islider_active, min, max); if (pAnalysis->GetMode() == SENSITIVITY_DONE) { pAnalysis->GuessSolutionSliderMove(val0, val2); } } } if (is_tex_mouse_pos) { Com::CVector3D oloc0 = camera_l.ProjectionOnPlane(mov_begin_x, mov_begin_y); pAnalysis->SetTextureCenter(-0.5 + oloc0.x, -0.5 + oloc0.y); gui_listner.SetTextureCenter_FaceCAD(-0.5 + oloc0.x, -0.5 + oloc0.y); } } else if (glutGetWindow() == iwin_sim) { if (imode_ope == 0) { if (pAnalysis->GetMode() == CLOTH_INITIAL_LOCATION) { Cad::CAD_ELEM_TYPE itype_cad_part; unsigned int id_cad_part; double tmp_x, tmp_y; gui_listner.Cad_GetPicked(itype_cad_part, id_cad_part, tmp_x, tmp_y); if (itype_cad_part == Cad::LOOP && gui_listner.GetCad().IsElemID(itype_cad_part, id_cad_part)) { double dir[3]; { const double hvh = camera_r.GetHalfViewHeight() / camera_r.GetScale(); const double asp = camera_r.GetWindowAspect(); double d0[3] = { (mov_end_x - mov_begin_x)*hvh*asp, (mov_end_y - mov_begin_y)*hvh, 0 }; double rot[9]; camera_r.RotMatrix33(rot); dir[0] = rot[0] * d0[0] + rot[3] * d0[1] + rot[6] * d0[2]; dir[1] = rot[1] * d0[0] + rot[4] * d0[1] + rot[7] * d0[2]; dir[2] = rot[2] * d0[0] + rot[5] * d0[1] + rot[8] * d0[2]; } pAnalysis->MoveClothLoopInitialPosition(id_cad_part, dir); } } } if (imode_ope == 4) { if (is_active_slider) { double rot[9]; camera_r.RotMatrix33(rot); const double sns1[3] = { rot[0] * pick_sns[0] + rot[1] * pick_sns[1] + rot[2] * pick_sns[2], rot[3] * pick_sns[0] + rot[4] * pick_sns[1] + rot[5] * pick_sns[2], rot[6] * pick_sns[0] + rot[7] * pick_sns[1] + rot[8] * pick_sns[2] }; const double hvh = camera_r.GetHalfViewHeight() / camera_r.GetScale(); // const double hvh = camera_r.GetHalfViewHeight(); const double asp = camera_r.GetWindowAspect(); const double mus1[2] = { (mov_end_x - mov_begin_x)*hvh*asp, (mov_end_y - mov_begin_y)*hvh }; double dot = (mus1[0] * sns1[0] + mus1[1] * sns1[1]) / (sns1[0] * sns1[0] + sns1[1] * sns1[1]); double min, max; const double val0 = gui_listner.GetValueSlider(islider_active, min, max); gui_listner.SetValueSlider(islider_active, val0 + dot); const double val2 = gui_listner.GetValueSlider(islider_active, min, max); if (pAnalysis->GetMode() == SENSITIVITY_DONE) { pAnalysis->GuessSolutionSliderMove(val0, val2); } } } } } //////////////// mov_begin_x = mov_end_x; mov_begin_y = mov_end_y; ::glutPostRedisplay(); } void myGlutPassive(int x, int y) { if (glutGetWindow() == iwin_sim) { return; } int viewport[4]; ::glGetIntegerv(GL_VIEWPORT, viewport); const int win_w = viewport[2]; const int win_h = viewport[3]; const double mov_end_x = (2.0*x - win_w) / win_w; const double mov_end_y = (win_h - 2.0*y) / win_h; //// const unsigned int size_buffer = 128; unsigned int select_buffer[size_buffer]; std::vector<Com::View::SSelectedObject> aSelecObj; Com::View::PickPre(size_buffer, select_buffer, x, y, 12, 12, camera_l); gui_listner.DrawSelection(); aSelecObj = Com::View::PickPost(select_buffer, x, y, camera_l); gui_listner.SetSelection(aSelecObj); //// Cad::CAD_ELEM_TYPE itype_cad_part; unsigned int id_cad_part; double tmp_x, tmp_y; gui_listner.Cad_GetPicked(itype_cad_part, id_cad_part, tmp_x, tmp_y); if (is_tex_mouse_pos) { Com::CVector3D oloc0 = camera_l.ProjectionOnPlane(mov_begin_x, mov_begin_y); pAnalysis->SetTextureCenter(-0.5 + oloc0.x, -0.5 + oloc0.y); gui_listner.SetTextureCenter_FaceCAD(-0.5 + oloc0.x, -0.5 + oloc0.y); } // if( itype_cad_part == Cad::EDGE || itype_cad_part == Cad::VERTEX ){ pAnalysis->SetHilight(itype_cad_part, id_cad_part); // } //////////////// mov_begin_x = mov_end_x; mov_begin_y = mov_end_y; ::glutPostRedisplay(); } void myGlutMouse(int button, int state, int x, int y) { ///// imodifier = glutGetModifiers(); int viewport[4]; ::glGetIntegerv(GL_VIEWPORT, viewport); const int win_w = viewport[2]; const int win_h = viewport[3]; mov_begin_x = (2.0*x - win_w) / (double)win_w; mov_begin_y = (win_h - 2.0*y) / (double)win_h; //// if (glutGetWindow() == iwin_des) { if (imode_ope == 1) { // cut line if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { is_rubber_band = true; const Com::CVector3D& oloc0 = camera_l.ProjectionOnPlane(mov_begin_x, mov_begin_y); pos_pick = Com::CVector2D(oloc0.x, oloc0.y); pos_relese = pos_pick; } if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) { if (is_rubber_band) { gui_listner.Cad_AddCutLine(pos_pick, pos_relese); is_rubber_band = false; } } return; } if (imode_ope == 5) { // cut line if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { const Com::CVector3D& oloc0 = camera_l.ProjectionOnPlane(mov_begin_x, mov_begin_y); pos_pick = Com::CVector2D(oloc0.x, oloc0.y); pos_relese = pos_pick; } if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) { if (is_rubber_band) { gui_listner.Cad_AddCutLine(pos_pick, pos_relese); is_rubber_band = false; } } return; } if (imode_ope == 2) { // polygon pull if (state == GLUT_DOWN) { const unsigned int size_buffer = 128; unsigned int select_buffer[size_buffer]; std::vector<Com::View::SSelectedObject> aSelecObj; Com::View::PickPre(size_buffer, select_buffer, x, y, 8, 8, camera_l); gui_listner.DrawSelection(); aSelecObj = Com::View::PickPost(select_buffer, x, y, camera_l); gui_listner.SetSelection(aSelecObj); ///// Cad::CAD_ELEM_TYPE itype_cad_part; unsigned int id_cad_part; double tmp_x, tmp_y; gui_listner.Cad_GetPicked(itype_cad_part, id_cad_part, tmp_x, tmp_y); if (itype_cad_part == Cad::EDGE && gui_listner.GetCad().IsElemID(itype_cad_part, id_cad_part)) { const Com::CVector3D& oloc = camera_l.ProjectionOnPlane(mov_begin_x, mov_begin_y); if (gui_listner.GetCad().GetEdgeCurveType(id_cad_part) == 2) { bool res = gui_listner.Cad_PreCompDragPolyline(id_cad_part, Com::CVector2D(oloc.x, oloc.y)); } return; } } } if (imode_ope == 4) { if (state == GLUT_DOWN) { if (mov_begin_y < -0.9) { is_active_slider = true; double min, max; const double val = gui_listner.GetValueSlider(islider_active, min, max); const double ratio = (val - min) / (max - min) * 2 - 1; if (fabs(ratio - mov_begin_x) < 0.05) { gui_listner.Msh_PrecompSlider(islider_active); if (pAnalysis->GetMode() != CLOTH_INITIAL_LOCATION) { std::vector<double> har; gui_listner.Msh_GetHarmonicPrecomp(har); // Get mesh harmonic function if (har.size() == 0) return; pAnalysis->SetSensitivity_Slider(islider_active, har, val); } } } else { is_active_slider = false; } } else if (state == GLUT_UP) { is_active_slider = false; if (pAnalysis->GetMode() == SENSITIVITY_DONE) { pAnalysis->PerformStaticSolver(); return; } } } if (imode_ope == 0) { if (state == GLUT_UP) { if (pAnalysis->GetMode() == SENSITIVITY_DONE) { pAnalysis->PerformStaticSolver(); { double max_aspect = 0; bool is_inverted = false; pAnalysis->MeshQualityInfo(max_aspect, is_inverted); std::cout << "ratio " << max_aspect << " " << is_inverted << std::endl; if (max_aspect > 10 || is_inverted) { gui_listner.Solve_fromCad_InterpValue(); } } return; } } if (state == GLUT_DOWN) { if (!pAnalysis->IsBlowUp()) { gui_listner.SaveTimeStamp(); } ///// const unsigned int size_buffer = 128; unsigned int select_buffer[size_buffer]; std::vector<Com::View::SSelectedObject> aSelecObj; Com::View::PickPre(size_buffer, select_buffer, x, y, 8, 8, camera_l); gui_listner.DrawSelection(); aSelecObj = Com::View::PickPost(select_buffer, x, y, camera_l); gui_listner.SetSelection(aSelecObj); //////////////// Cad::CAD_ELEM_TYPE itype_cad_part; unsigned int id_cad_part; double tmp_x, tmp_y; gui_listner.Cad_GetPicked(itype_cad_part, id_cad_part, tmp_x, tmp_y); if (itype_cad_part == Cad::NOT_SET) return; gui_listner.Msh_PrecompDrag(itype_cad_part, id_cad_part); if (pAnalysis->GetMode() != CLOTH_INITIAL_LOCATION && !gui_listner.IsntMeshDeformSensitivity()) { std::vector<double> har; gui_listner.Msh_GetHarmonicPrecomp(har); // Get mesh harmonic function if (har.size() == 0) return; const Com::CVector3D& oloc0 = camera_l.ProjectionOnPlane(mov_begin_x, mov_begin_y); pAnalysis->SetSensitivity(itype_cad_part, id_cad_part, har, oloc0.x, oloc0.y); } } } } if (glutGetWindow() == iwin_sim) { if (imode_ope == 0) { if (state == GLUT_DOWN) { double trans0[3]; camera_r.GetObjectCenter(trans0[0], trans0[1], trans0[2]); trans0[0] = -trans0[0]; trans0[1] = -trans0[1]; trans0[2] = -trans0[2]; double rot[9]; camera_r.RotMatrix33(rot); double trans1[3]; camera_r.GetCenterPosition(trans1[0], trans1[1], trans1[2]); const double hvh = camera_r.GetHalfViewHeight() / camera_r.GetScale(); const double asp = camera_r.GetWindowAspect(); unsigned int no[3]; double r[3]; unsigned int id_l; bool res = pAnalysis->Pick(hvh*asp*mov_begin_x, hvh*mov_begin_y, trans0, rot, trans1, no, r, id_l);//, dir,org); if (!res) { gui_listner.HilightCadTypeID(Cad::NOT_SET, 0); gui_listner.Cad_SetPicked(Cad::NOT_SET, 0, 0, 0); return; } gui_listner.HilightCadTypeID(Cad::LOOP, id_l); gui_listner.Cad_SetPicked(Cad::LOOP, id_l, 0, 0); } } if (imode_ope == 4) { if (state == GLUT_DOWN) { double trans0[3]; camera_r.GetObjectCenter(trans0[0], trans0[1], trans0[2]); trans0[0] = -trans0[0]; trans0[1] = -trans0[1]; trans0[2] = -trans0[2]; double rot[9]; camera_r.RotMatrix33(rot); double trans1[3]; camera_r.GetCenterPosition(trans1[0], trans1[1], trans1[2]); const double hvh = camera_r.GetHalfViewHeight() / camera_r.GetScale(); const double asp = camera_r.GetWindowAspect(); unsigned int no[3]; double r[3]; unsigned int id_l; bool res = pAnalysis->Pick(hvh*asp*mov_begin_x, hvh*mov_begin_y, trans0, rot, trans1, no, r, id_l);//, dir,org); if (!res) { std::cout << "pick none" << std::endl; is_active_slider = false; return; } is_active_slider = true; gui_listner.Msh_PrecompSlider(islider_active); if (pAnalysis->GetMode() != CLOTH_INITIAL_LOCATION) { std::vector<double> har; gui_listner.Msh_GetHarmonicPrecomp(har); // Get mesh harmonic function if (har.size() == 0) return; double min, max; const double val = gui_listner.GetValueSlider(islider_active, min, max); pAnalysis->SetSensitivity_Slider(islider_active, har, val); pAnalysis->GetSensitivityElem_Slider(no, r, pick_org, pick_sns); // std::cout << "org : " << org[0] << " " << org[1] << " " << org[2] << std::endl; // std::cout << "sns : " << sns[0] << " " << sns[1] << " " << sns[2] << std::endl; } } else if (state == GLUT_UP) { if (pAnalysis->GetMode() == SENSITIVITY_DONE) { pAnalysis->PerformStaticSolver(); return; } } } } } void myGlutIdle() { if (is_animation) { gui_listner.FollowMshToCad_ifNeeded(); gui_listner.Solve_ifNeeded(); if (pAnalysis->IsBlowUp()) { std::cout << "BlowUp" << std::endl; gui_listner.LoadTimeStamp(); } } // redraw left window ::glutSetWindow(iwin_des); ::glutPostRedisplay(); if (pAnalysis->GetMode() != SIMULATION_STATIC) { ::glutSetCursor(GLUT_CURSOR_INHERIT); } // redraw right window ::glutSetWindow(iwin_sim); ::glutPostRedisplay(); if (pAnalysis->GetMode() != SIMULATION_STATIC) { ::glutSetCursor(GLUT_CURSOR_INHERIT); } } void myGlutResize(int w, int h) { if (glutGetWindow() == iwin_des) { ::glViewport(0, 0, w, h); camera_l.SetWindowAspect((double)w / h); drawer_coord.SetTrans(camera_l, h); ::glMatrixMode(GL_PROJECTION); ::glLoadIdentity(); Com::View::SetProjectionTransform(camera_l); } else { ::glViewport(0, 0, w, h); camera_r.SetWindowAspect((double)w / h); drawer_coord.SetTrans(camera_r, h); ::glMatrixMode(GL_PROJECTION); ::glLoadIdentity(); Com::View::SetProjectionTransform(camera_r); } ::glutPostRedisplay(); } void myGlutMenu_Des(int value) { Cad::CAD_ELEM_TYPE itype_cad_part; unsigned int id_cad_part; double tmp_x, tmp_y; gui_listner.Cad_GetPicked(itype_cad_part, id_cad_part, tmp_x, tmp_y); switch (value) { case 5: imode_ope = 0; std::cout << "Mode Drag" << std::endl; break; case 1: imode_ope = 2; std::cout << "Edit Curve" << std::endl; break; case 6: imode_ope = 3; std::cout << "Smooth Polyline" << std::endl; break; case 7: imode_ope = 1; std::cout << "DartCutter" << std::endl; break; case 8: imode_ope = 5; std::cout << "DartCutter" << std::endl; break; case 2: // ChangeToLine if (itype_cad_part != Cad::EDGE) break; std::cout << "ChangeToLine" << std::endl; gui_listner.Cad_SetCurveType(id_cad_part, 0); break; case 3: // ChangeToArc if (itype_cad_part != Cad::EDGE) break; std::cout << "ChangeToArc" << std::endl; gui_listner.Cad_SetCurveType(id_cad_part, 1); break; case 4: // ChangeToArc if (itype_cad_part != Cad::EDGE) break; std::cout << "ChangeToPolyline" << std::endl; gui_listner.Cad_SetCurveType(id_cad_part, 2); break; } if (value >= 8) { imode_ope = 4; islider_active = value - 8; is_active_slider = false; slider_name = gui_listner.GetNameSlider(islider_active); } } void SetNewProblem() { const unsigned int indprob[4] = { 6,9,11,10 }; static int iprob = 0; unsigned int nprob = 4; if (pAnalysis != 0) { ::glutSetWindow(iwin_des); ::glutDetachMenu(GLUT_RIGHT_BUTTON); ::glutDestroyMenu(imenu_right_click); // unsigned int nsl = gui_listner.GetNumberOfSlider(); // for(unsigned int isl=0;isl<nsl;isl++){ glutDestroyMenu(isl+8); } delete pAnalysis; pAnalysis = 0; } pAnalysis = new CAnalysis2D_Cloth_Static(); gui_listner.SetAnalysisInitialize(pAnalysis, indprob[iprob]); if (is_tex_mouse_pos) { pAnalysis->SetColor_FaceFEM(0.8, 0.8, 0.8); gui_listner.SetColor_CadFace(0.8, 0.8, 0.8); pAnalysis->SetTextureScale_FaceFEM(1); gui_listner.SetTextureScale_CadFace(1); } else { pAnalysis->SetColor_FaceFEM(1.0, 1.0, 1.0); gui_listner.SetColor_CadFace(1, 1, 1); // pAnalysis->SetTextureScale_FaceFEM(1); // gui_listner.SetTextureScale_CadFace(1); pAnalysis->SetTextureScale_FaceFEM(5); gui_listner.SetTextureScale_CadFace(5); } //////////////// { camera_r.SetRotationMode(Com::View::ROT_2DH); double rot[9]; camera_r.RotMatrix33(rot); Com::CBoundingBox3D bb = pAnalysis->GetBoundingBox(rot); bb.z_max *= 1.5; camera_r.SetObjectBoundingBox(bb); camera_r.Fit(); camera_r.SetScale(1.7); //// ::glutSetWindow(iwin_sim); ::glMatrixMode(GL_PROJECTION); ::glLoadIdentity(); Com::View::SetProjectionTransform(camera_r); ::glutPostRedisplay(); // drawer_coord.SetTrans(camera_r); } { camera_l.SetRotationMode(Com::View::ROT_2D); double rot[9]; camera_l.RotMatrix33(rot); const Com::CBoundingBox3D& bb = gui_listner.GetBoundingBox(rot); camera_l.SetObjectBoundingBox(bb); camera_l.Fit(); camera_l.SetScale(1.2); // camera_l.SetScale(1.0); //// ::glutSetWindow(iwin_des); ::glMatrixMode(GL_PROJECTION); ::glLoadIdentity(); Com::View::SetProjectionTransform(camera_l); ::glutPostRedisplay(); drawer_coord.SetTrans(camera_l); } { ::glutSetWindow(iwin_des); imenu_right_click = ::glutCreateMenu(myGlutMenu_Des); ::glutAddMenuEntry("Drag", 5); ::glutAddMenuEntry("Dart Cutter", 7); ::glutAddMenuEntry("EditCurve", 1); ::glutAddMenuEntry("ChangeToLine", 2); // ::glutAddMenuEntry("ChangeToArc", 3); ::glutAddMenuEntry("ChangeToPolyline", 4); ::glutAddMenuEntry("SmoothPolyline", 6); //// unsigned int nsl = gui_listner.GetNumberOfSlider(); for (unsigned int isl = 0; isl < nsl; isl++) { const std::string& name = gui_listner.GetNameSlider(isl); char str_sl[256]; sprintf(str_sl, "Slider [ %s ]", name.c_str()); ::glutAddMenuEntry(str_sl, isl + 8); } ::glutAttachMenu(GLUT_RIGHT_BUTTON); } imode_ope = 0; pAnalysis->SetIsLighting(is_lighting); pAnalysis->PerformStaticSolver(); //////////////// iprob++; if (iprob == nprob) { iprob = 0; } } void myGlutSpecial(int Key, int x, int y) { Com::View::CCamera& camera = (glutGetWindow() == iwin_sim) ? camera_r : camera_l; switch (Key) { case GLUT_KEY_PAGE_UP: { const double tmp_scale = camera.GetScale() * 1.111; camera.SetScale(tmp_scale); } break; case GLUT_KEY_PAGE_DOWN: { const double tmp_scale = camera.GetScale() * 0.9; camera.SetScale(tmp_scale); } break; case GLUT_KEY_HOME: { double rot[9]; camera.RotMatrix33(rot); Com::CBoundingBox3D bb = gui_listner.GetBoundingBox(rot); camera.SetObjectBoundingBox(bb); // drawer_ary.InitTrans(camera); camera.Fit(); } break; default: break; } glMatrixMode(GL_PROJECTION); glLoadIdentity(); Com::View::SetProjectionTransform(camera); ::glutPostRedisplay(); } void myGlutDisplay(void) { ::glClearColor(1.f, 1.f, 1.f, 1.0f); ::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ::glEnable(GL_DEPTH_TEST); ::glEnable(GL_POLYGON_OFFSET_FILL); ::glPolygonOffset(1.1f, 4.0f); if (glutGetWindow() == iwin_sim) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); Com::View::SetModelViewTransform(camera_r); gui_listner.Draw(4); ShowTextSimulation(); } else { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); Com::View::SetModelViewTransform(camera_l); gui_listner.Draw(1); ShowTextDesign(); drawer_coord.Draw(); if (is_rubber_band) { ::glColor3d(1, 0, 0); ::glBegin(GL_LINES); ::glVertex2d(pos_pick.x, pos_pick.y); ::glVertex2d(pos_relese.x, pos_relese.y); ::glEnd(); } if (imode_ope == 4) { double min, max; const double val = gui_listner.GetValueSlider(islider_active, min, max); const double ratio = (val - min) / (max - min) * 2 - 1; ::glMatrixMode(GL_PROJECTION); ::glPushMatrix(); ::glLoadIdentity(); ::glMatrixMode(GL_MODELVIEW); ::glPushMatrix(); ::glLoadIdentity(); ::glColor3d(0, 0, 0); ::glBegin(GL_LINES); ::glVertex2d(-1, -0.9); ::glVertex2d(+1, -0.9); ::glEnd(); if (is_active_slider == -1) { ::glColor3d(0, 0, 0); } else { ::glColor3d(1, 0, 0); } ::glBegin(GL_QUADS); ::glVertex2d(ratio - 0.05, -1.0); ::glVertex2d(ratio + 0.05, -1.0); ::glVertex2d(ratio + 0.05, -0.9); ::glVertex2d(ratio - 0.05, -0.9); ::glEnd(); ::glMatrixMode(GL_MODELVIEW); ::glPopMatrix(); ::glMatrixMode(GL_PROJECTION); ::glPopMatrix(); } } ::glutSwapBuffers(); } void myGlutKeyboard(unsigned char key, int x, int y) { switch (key) { case 'q': case 'Q': case '\033': exit(0); break; case 'f': gui_listner.File_WriteDXF("cloth_pattern.dxf", 4); break; case 'g': if (pAnalysis != 0) { pAnalysis->WriteObjMeshSTL("object.stl", 100); } break; case 'k': gui_listner.HilightCadTypeID(Cad::NOT_SET, 0); if (imode_ope == 0) { imode_ope = 1; } else { imode_ope = 0; } break; case 'h': // gui_listner.Serialize( Com::CSerializer("hoge.txt",true ) ); break; case 'r': gui_listner.Solve_fromCad_InitValue(); break; case 't': gui_listner.Solve_fromCad_InterpValue(); break; case 'y': gui_listner.LoadTimeStamp(); break; case 'u': gui_listner.SaveTimeStamp(); break; case ' ': SetNewProblem(); break; case 'a': is_animation = !is_animation; // gui_listner.Enable_SolveCadChange(is_animation); break; case 'b': if (pAnalysis->GetMode() == CLOTH_INITIAL_LOCATION) { gui_listner.Solve_fromCad_InitValue(); pAnalysis->PerformStaticSolver(); ::glutSetWindow(iwin_des); ::glutSetCursor(GLUT_CURSOR_WAIT); ::glutSetWindow(iwin_sim); ::glutSetCursor(GLUT_CURSOR_WAIT); } else { pAnalysis->SetClothPiecePlacingMode(); } break; case 'c': break; case 'l': is_lighting = !is_lighting; if (is_lighting) { ::glEnable(GL_LIGHTING); } else { ::glDisable(GL_LIGHTING); } pAnalysis->SetIsLighting(is_lighting); case 'e': pAnalysis->SetIsShowEdge(!pAnalysis->IsShowEdge()); break; case 'd': if (pAnalysis->IsDetail()) { pAnalysis->SetIsDetail(false, gui_listner.GetCad(), gui_listner.GetMesh()); } else { pAnalysis->SetIsDetail(true, gui_listner.GetCad(), gui_listner.GetMesh()); } break; case 'p': is_display_rotation = !is_display_rotation; if (is_display_rotation) { display_rotation_theta = -10; pAnalysis->SetIsDrawPatternBoundary(false); { camera_r.SetRotationMode(Com::View::ROT_2DH); double rot[9]; camera_r.RotMatrix33(rot); Com::CBoundingBox3D bb = pAnalysis->GetBoundingBox(rot); camera_r.SetObjectBoundingBox(bb); camera_r.Fit(); camera_r.SetScale(1.8); //// ::glutSetWindow(iwin_sim); ::glMatrixMode(GL_PROJECTION); ::glLoadIdentity(); Com::View::SetProjectionTransform(camera_r); ::glutPostRedisplay(); // drawer_coord.SetTrans(camera_r); } gui_listner.Enable_SolveCadChange(false); } else { pAnalysis->SetIsDrawPatternBoundary(true); gui_listner.Enable_SolveCadChange(true); } break; default: break; } } void Initialize_OpenGL_Texture(int ival) { // ReadPPM_SetTexture("cb.ppm"); std::string tex_name; if (ival == 0) { tex_name = "texture/red_point.ppm"; } else if (ival == 1) { tex_name = "texture/tex1.ppm"; } else if (ival == 2) { tex_name = "texture/tex2.ppm"; } else if (ival == 3) { tex_name = "texture/tex3.ppm"; } else if (ival == 4) { tex_name = "texture/tex4.ppm"; } else if (ival == 5) { tex_name = "texture/tex5.ppm"; } else if (ival == 6) { tex_name = "texture/tex6.ppm"; } else if (ival == 7) { tex_name = "texture/tex7.ppm"; } else if (ival == 8) { tex_name = "texture/tex8.ppm"; } else if (ival == 9) { tex_name = "texture/tex9.ppm"; } else if (ival == 10) { tex_name = "texture/tex10.ppm"; } if (ival == 0) { is_tex_mouse_pos = true; } else { is_tex_mouse_pos = false; } ::glutSetWindow(iwin_sim); Com::View::ReadPPM_SetTexture(tex_name.c_str(), m_texName, m_texWidth, m_texHeight); if (is_tex_mouse_pos) { float tex_border_Color[4] = { 1,1,1,1 }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, tex_border_Color); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); ///// ::glutSetWindow(iwin_des); Com::View::ReadPPM_SetTexture(tex_name.c_str(), m_texName, m_texWidth, m_texHeight); if (is_tex_mouse_pos) { float tex_border_Color[4] = { 1,1,1,1 }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, tex_border_Color); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (pAnalysis == 0) return; if (is_tex_mouse_pos) { pAnalysis->SetColor_FaceFEM(0.8, 0.8, 0.8); gui_listner.SetColor_CadFace(0.8, 0.8, 0.8); pAnalysis->SetTextureScale_FaceFEM(1); gui_listner.SetTextureScale_CadFace(1); } else if (ival == 7) { pAnalysis->SetColor_FaceFEM(1.0, 1.0, 1.0); gui_listner.SetColor_CadFace(1, 1, 1); pAnalysis->SetTextureScale_FaceFEM(2); gui_listner.SetTextureScale_CadFace(2); } else if (ival == 10 || ival == 8) { pAnalysis->SetColor_FaceFEM(1.0, 1.0, 1.0); gui_listner.SetColor_CadFace(1, 1, 1); pAnalysis->SetTextureScale_FaceFEM(4); gui_listner.SetTextureScale_CadFace(4); } else { pAnalysis->SetColor_FaceFEM(1.0, 1.0, 1.0); gui_listner.SetColor_CadFace(1, 1, 1); pAnalysis->SetTextureScale_FaceFEM(5); gui_listner.SetTextureScale_CadFace(5); } } void myGlutMenu_Sim(int ivalue) { if (ivalue < 11) { Initialize_OpenGL_Texture(ivalue); } else if (ivalue == 11) { // very thin std::cout << "very thin" << std::endl; CClothParam cp = pAnalysis->GetParam_Cloth(); cp.stiff_bend = 0; cp.rho = 0.02; pAnalysis->SetParam_Cloth(cp); } else if (ivalue == 12) { // thin (default) std::cout << "thin" << std::endl; CClothParam cp = pAnalysis->GetParam_Cloth(); cp.stiff_bend = 1.0e-10; cp.rho = 0.02; pAnalysis->SetParam_Cloth(cp); } else if (ivalue == 13) { // medium std::cout << "mdium" << std::endl; CClothParam cp = pAnalysis->GetParam_Cloth(); cp.stiff_bend = 1.0e-5; cp.rho = 0.02; pAnalysis->SetParam_Cloth(cp); } else if (ivalue == 14) { // thick std::cout << "thick" << std::endl; CClothParam cp = pAnalysis->GetParam_Cloth(); cp.stiff_bend = 1.0e-2; cp.stiff_myu = 20; // cp.rho = 0.001; // sent to takeo // cp.stiff_bend = 5.0e-7; // cp.rho = 0.0001; pAnalysis->SetParam_Cloth(cp); } } int main(int argc, char *argv[]) { ::glutInit(&argc, argv); // left window ::glutInitWindowPosition(50, 50); ::glutInitWindowSize(500, 650); camera_l.SetWindowAspect(500.0 / 650); ::glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); iwin_des = glutCreateWindow("Design Window"); ::glutDisplayFunc(myGlutDisplay); ::glutIdleFunc(myGlutIdle); ::glutReshapeFunc(myGlutResize); ::glutKeyboardFunc(myGlutKeyboard); ::glutSpecialFunc(myGlutSpecial); ::glutMouseFunc(myGlutMouse); ::glutPassiveMotionFunc(myGlutPassive); ::glutMotionFunc(myGlutMotion); // right window ::glutInitWindowPosition(600, 50); ::glutInitWindowSize(500, 650); camera_r.SetWindowAspect(500.0 / 650); ::glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); iwin_sim = glutCreateWindow("Simulation Window"); ::glutDisplayFunc(myGlutDisplay); ::glutIdleFunc(myGlutIdle); ::glutReshapeFunc(myGlutResize); ::glutKeyboardFunc(myGlutKeyboard); ::glutSpecialFunc(myGlutSpecial); ::glutMouseFunc(myGlutMouse); ::glutMotionFunc(myGlutMotion); { ::glutSetWindow(iwin_sim); //// ::glEnable(GL_LIGHTING); ::glEnable(GL_LIGHT0); float light0pos[4] = { 0,10,+20,0 }; ::glLightfv(GL_LIGHT0, GL_POSITION, light0pos); float white[3] = { 0.8,0.8,0.8 }; ::glLightfv(GL_LIGHT0, GL_DIFFUSE, white); ::glEnable(GL_LIGHT1); float light1pos[4] = { 3,10,+10,0 }; ::glLightfv(GL_LIGHT1, GL_POSITION, light1pos); float white2[3] = { 0.4,0.4,0.4 }; ::glLightfv(GL_LIGHT1, GL_DIFFUSE, white2); } { ::glutSetWindow(iwin_des); glEnable(GL_TEXTURE_2D); ::glutSetWindow(iwin_sim); glEnable(GL_TEXTURE_2D); } { ::glutSetWindow(iwin_sim); int imenu_tex = ::glutCreateMenu(myGlutMenu_Sim); ::glutAddMenuEntry("Red Point", 0); ::glutAddMenuEntry("Brown Check", 1); ::glutAddMenuEntry("Olive Check", 2); ::glutAddMenuEntry("Red Blue Line Check", 3); ::glutAddMenuEntry("Red Check", 4); ::glutAddMenuEntry("Blue Gingham Check", 5); ::glutAddMenuEntry("Pink Plait", 6); ::glutAddMenuEntry("Floral Black/White", 7); ::glutAddMenuEntry("Floral Color", 8); ::glutAddMenuEntry("Blue Plait", 9); ::glutAddMenuEntry("Hart", 10); int imenu_bend = ::glutCreateMenu(myGlutMenu_Sim); ::glutAddMenuEntry("very thin", 11); ::glutAddMenuEntry("thin (default)", 12); ::glutAddMenuEntry("medium", 13); ::glutAddMenuEntry("thick", 14); ::glutCreateMenu(myGlutMenu_Sim); ::glutAddSubMenu("texture", imenu_tex); ::glutAddSubMenu("cloth thickness", imenu_bend); ::glutAttachMenu(GLUT_RIGHT_BUTTON); } ::SetNewProblem(); Initialize_OpenGL_Texture(4); std::cout << "enter main loop" << std::endl; ::glutMainLoop(); return 0; }
[ "michael2345@live.cn" ]
michael2345@live.cn
a7c459c85563a99b9697f0c9257559b46567e020
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_2/processor35/15/phi
c8ee05c45498ac37bc94334447da7b7ced991bda
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
12,424
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "15"; object phi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 3 -1 0 0 0 0]; internalField nonuniform List<scalar> 647 ( 0.000752285 -3.23843e-05 -3.2311e-09 0.000784066 -3.17765e-05 -3.99162e-09 -3.11671e-05 -4.74619e-09 0.000756476 -6.465e-05 0.000788138 -6.34387e-05 -6.22243e-05 0.000764805 -9.66732e-05 0.000796232 -9.48658e-05 -9.30536e-05 0.000777168 -0.000128336 0.000808246 -0.000125943 -0.000123544 0.000793412 -0.000159525 0.000824029 -0.000156561 -0.000153589 0.000813332 -0.00019013 0.000843385 -0.000186614 -0.000183087 0.000836682 -0.00022005 0.00086607 -0.000216003 -0.000211941 0.00086317 -0.00024919 0.000891803 -0.000244636 -0.000240064 0.000892469 -0.000277464 0.000920263 -0.00027243 -0.000267376 0.000924215 -0.000304793 0.000951096 -0.000299311 0.000977524 -0.000293804 -0.000288293 0.000958016 0.00098392 -0.000325215 0.0010094 -0.000319288 -0.000313354 0.00101833 -0.000350089 0.00104282 -0.000343778 -0.000337454 0.0010539 -0.000373891 0.00107736 -0.000367232 -0.000360556 0.0010902 -0.00039659 0.00111259 -0.000389624 -0.000382633 0.00112677 -0.000418169 0.00114808 -0.000410936 -0.00040367 0.00116317 -0.000438619 0.00118339 -0.000431162 -0.000423663 0.00119895 -0.000457948 0.0012181 -0.00045031 -0.00044262 0.00123368 0.00125176 -0.000468398 0.0012697 -0.000460558 -0.000452683 0.00128397 -0.000485453 0.00130092 -0.000477508 -0.000469513 0.00131433 -0.000501517 0.00133033 -0.000493508 -0.000485435 0.00134245 -0.00051664 0.00135755 -0.000508609 -0.000500497 0.00136795 -0.000530881 0.00138222 -0.000522871 -0.00051476 0.0013905 0.00140399 -0.000536362 0.00141752 -0.000528291 -0.000520136 0.00142273 -0.000549148 0.0014356 -0.000541154 -0.000533055 0.00536711 -0.000565258 0.00538361 -0.000557648 -0.000549883 0.0058803 -0.000572332 0.00588802 -0.000565365 -0.000558183 0.00639313 -0.000570624 0.00639231 -0.000564545 -0.00055818 0.00689396 -0.000560768 0.0068852 -0.000555787 -0.000550443 0.00737236 -0.000543722 0.00735657 -0.000539997 -0.000535829 0.0078195 -0.000520689 0.00779782 -0.000518315 -0.000515419 0.00822851 -0.000493018 0.00820222 -0.000492023 -0.000490436 0.00859465 -0.000462108 0.00856508 -0.000462457 -0.000462153 0.00891535 -0.000429306 0.0088838 -0.00043091 -0.000431812 0.00919012 -0.000395825 0.00915777 -0.000398555 -0.000400547 0.00942025 -0.000362692 0.00938809 -0.00036639 -0.000369331 0.00960848 -0.000330709 0.0095773 -0.000335209 -0.000338942 0.00975857 -0.000300454 0.00972895 -0.000305588 -0.000309959 0.00987495 -0.00027229 0.00984727 -0.000277902 -0.000282763 0.00996229 -0.000246399 0.00993674 -0.00025235 -0.000257568 0.0100252 -0.000222816 0.0100019 -0.000228986 -0.000234445 0.0100681 -0.00020147 0.0100469 -0.000207758 -0.000213361 0.010095 -0.000182219 0.0100758 -0.000188542 -0.000194208 0.0101093 -0.000164879 0.0100919 -0.000171171 -0.000176835 0.010114 -0.000149251 0.0100983 -0.000155459 -0.000161068 0.0101115 -0.000135138 0.0100972 -0.000141218 -0.000146729 0.0101037 -0.000122352 0.0100908 -0.000128268 -0.000133647 0.0100924 -0.000110724 0.0100806 -0.000116448 -0.000121663 0.0100786 -0.000100107 0.0100678 -0.000105612 -0.000110638 0.0100634 -9.03721e-05 0.0100534 -9.56347e-05 -0.00010045 0.0100474 -8.14096e-05 0.0100382 -8.641e-05 -9.09927e-05 0.0100313 -7.3126e-05 0.0100227 -7.78452e-05 -8.21772e-05 0.0100154 -6.54407e-05 0.0100074 -6.98617e-05 -7.39258e-05 0.01 -5.82843e-05 0.00999257 -6.23911e-05 -6.61716e-05 0.00998545 -5.15953e-05 0.00997843 -5.53738e-05 -5.88561e-05 0.00997182 -4.5319e-05 0.0099652 -4.87559e-05 -5.19271e-05 0.00995928 -3.94051e-05 0.00995301 -4.24892e-05 -4.53372e-05 0.00994793 -3.38075e-05 0.00994197 -3.65282e-05 -3.90427e-05 0.00993786 -2.84824e-05 0.00993217 -3.08308e-05 -3.30028e-05 0.00992913 -2.33881e-05 0.00992366 -2.53565e-05 -2.71782e-05 0.0099218 -1.84842e-05 0.00991651 -2.00664e-05 -2.15315e-05 0.00991588 -1.37316e-05 0.00991074 -1.49228e-05 -1.60258e-05 0.00991143 -9.09203e-06 0.00990639 -9.88807e-06 -1.06256e-05 0.00990844 -4.52719e-06 0.00990348 -4.92595e-06 -5.29536e-06 0.00990695 0.00990202 -0.000565266 0.00536713 0.000549156 -0.00057234 0.00588032 -0.000570632 0.00639315 -0.000560776 0.00689397 -0.00054373 0.00737237 -0.000520697 0.00781951 -0.000493026 0.00822852 -0.000462115 0.00859465 -0.000429312 0.00891536 -0.000395832 0.00919013 -0.000362698 0.00942026 -0.000330715 0.00960848 -0.00030046 0.00975858 -0.000272295 0.00987495 -0.000246404 0.00996229 -0.000222821 0.0100252 -0.000201474 0.0100681 -0.000182223 0.010095 -0.000164883 0.0101093 -0.000149255 0.010114 -0.000135141 0.0101115 -0.000122355 0.0101037 -0.000110727 0.0100924 -0.00010011 0.0100786 -9.03744e-05 0.0100634 -8.14117e-05 0.0100474 -7.31279e-05 0.0100313 -6.54425e-05 0.0100154 -5.82858e-05 0.01 -5.15966e-05 0.00998545 -4.53202e-05 0.00997182 -3.94061e-05 0.00995928 -3.38084e-05 0.00994793 -2.84832e-05 0.00993786 -2.33887e-05 0.00992913 -1.84847e-05 0.00992179 -1.3732e-05 0.00991588 -9.09228e-06 0.00991142 -4.52732e-06 0.00990844 0.00990695 -0.000557657 0.00538362 0.000541164 -0.000565374 0.00588803 -0.000564554 0.00639232 -0.000555796 0.00688522 -0.000540006 0.00735658 -0.000518323 0.00779783 -0.000492031 0.00820223 -0.000462465 0.00856509 -0.000430917 0.00888381 -0.000398562 0.00915777 -0.000366397 0.00938809 -0.000335215 0.0095773 -0.000305594 0.00972895 -0.000277908 0.00984727 -0.000252355 0.00993674 -0.000228991 0.0100019 -0.000207763 0.0100469 -0.000188546 0.0100758 -0.000171175 0.0100919 -0.000155463 0.0100983 -0.000141221 0.0100972 -0.000128272 0.0100908 -0.000116451 0.0100806 -0.000105614 0.0100678 -9.56372e-05 0.0100534 -8.64121e-05 0.0100382 -7.78472e-05 0.0100227 -6.98635e-05 0.0100074 -6.23928e-05 0.00999257 -5.53752e-05 0.00997843 -4.87572e-05 0.0099652 -4.24902e-05 0.00995301 -3.65291e-05 0.00994197 -3.08315e-05 0.00993216 -2.53571e-05 0.00992366 -2.0067e-05 0.0099165 -1.49232e-05 0.00991074 -9.88833e-06 0.00990639 -4.92613e-06 0.00990348 0.00990202 -0.000549893 0.000533065 -0.000558192 -0.00055819 -0.000550453 -0.000535838 -0.000515428 -0.000490444 -0.000462161 -0.00043182 -0.000400554 -0.000369338 -0.000338949 -0.000309965 -0.000282769 -0.000257573 -0.00023445 -0.000213365 -0.000194212 -0.000176839 -0.000161072 -0.000146733 -0.00013365 -0.000121666 -0.00011064 -0.000100452 -9.09948e-05 -8.21791e-05 -7.39276e-05 -6.61732e-05 -5.88575e-05 -5.19284e-05 -4.53383e-05 -3.90438e-05 -3.30036e-05 -2.71789e-05 -2.1532e-05 -1.60263e-05 -1.06259e-05 -5.29543e-06 0.00142274 0.00053637 0.0014356 0.000528301 0.000520146 0.0013905 0.000530889 0.00140399 0.000522879 0.00141752 0.00051477 0.00136796 0.000516647 0.00138222 0.000508618 0.000500507 0.00134245 0.000501525 0.00135756 0.000493517 0.000485445 0.00131433 0.000485461 0.00133033 0.000477517 0.000469523 0.00128398 0.000468406 0.00130092 0.000460567 0.000452693 0.00123368 0.000457955 0.00125177 0.000450318 0.0012697 0.000442629 0.00119895 0.000438626 0.0012181 0.000431171 0.000423673 0.00116317 0.000418176 0.0011834 0.000410944 0.00040368 0.00112677 0.000396598 0.00114808 0.000389633 0.000382643 0.0010902 0.000373898 0.00111259 0.000367241 0.000360566 0.0010539 0.000350097 0.00107736 0.000343787 0.000337464 0.00101833 0.000325223 0.00104282 0.000319297 0.000313364 0.000958019 0.000304799 0.000983923 0.000299319 0.00100941 0.000293813 0.000288303 0.000924217 0.00027747 0.000951099 0.000272437 0.000977527 0.000267385 0.000892471 0.000249197 0.000920265 0.000244643 0.000240073 0.000863172 0.000220057 0.000891805 0.00021601 0.000211951 0.000836684 0.000190137 0.000866072 0.000186622 0.000183096 0.000813334 0.000159531 0.000843387 0.000156569 0.000153599 0.000793413 0.000128342 0.000824031 0.000125951 0.000123554 0.00077717 9.66796e-05 0.000808247 9.48737e-05 9.3063e-05 0.000764806 6.46564e-05 0.000796233 6.34467e-05 6.22338e-05 0.000756477 3.23908e-05 0.000788139 3.17845e-05 3.11766e-05 0.000752286 0.000784066 ) ; boundaryField { inlet { type calculated; value nonuniform 0(); } outlet { type calculated; value nonuniform 0(); } cylinder { type calculated; value nonuniform 0(); } top { type symmetryPlane; value uniform 0; } bottom { type symmetryPlane; value uniform 0; } defaultFaces { type empty; value nonuniform 0(); } procBoundary35to34 { type processor; value nonuniform List<scalar> 134 ( -0.000719898 -0.00072421 -0.000732782 -0.000745505 -0.000762223 -0.000782726 -0.000806761 -0.00083403 -0.000864195 -0.000896885 -0.000931697 -0.000331112 -0.000993456 -0.0010301 -0.0010675 -0.00110519 -0.00114272 -0.00117962 -0.00121545 -0.000476171 -0.00126692 -0.00129826 -0.00132733 -0.00135371 -0.00137707 -0.000544312 -0.00140995 -0.005351 -0.00587323 -0.00639484 -0.00690382 -0.00738941 -0.00784254 -0.00825618 -0.00862556 -0.00894815 -0.0092236 -0.00945338 -0.00964046 -0.00978883 -0.00990312 -0.00998818 -0.0100488 -0.0100895 -0.0101143 -0.0101267 -0.0101296 -0.0101256 -0.0101165 -0.010104 -0.0100892 -0.0100731 -0.0100564 -0.0100396 -0.0100231 -0.0100072 -0.00999214 -0.0099781 -0.00996519 -0.00995353 -0.00994319 -0.00993423 -0.0099267 -0.00992064 -0.00991607 -0.00991301 -0.00991148 -0.00535102 -0.00587324 -0.00639485 -0.00690383 -0.00738942 -0.00784255 -0.00825619 -0.00862556 -0.00894816 -0.00922361 -0.00945339 -0.00964046 -0.00978883 -0.00990312 -0.00998818 -0.0100488 -0.0100895 -0.0101143 -0.0101267 -0.0101296 -0.0101256 -0.0101165 -0.010104 -0.0100892 -0.0100731 -0.0100564 -0.0100396 -0.0100231 -0.0100072 -0.00999214 -0.00997809 -0.00996519 -0.00995353 -0.00994319 -0.00993423 -0.0099267 -0.00992063 -0.00991606 -0.00991301 -0.00991147 -0.00140995 -0.000544319 -0.00137707 -0.00135372 -0.00132733 -0.00129827 -0.00126692 -0.000476178 -0.00121546 -0.00117963 -0.00114272 -0.00110519 -0.0010675 -0.0010301 -0.000993459 -0.000331118 -0.0009317 -0.000896888 -0.000864198 -0.000834033 -0.000806764 -0.000782728 -0.000762224 -0.000745507 -0.000732783 -0.000724211 -0.000719898 ) ; } procBoundary35to36 { type processor; value nonuniform List<scalar> 134 ( 0.000815238 0.000819195 0.000827061 0.000838737 0.000854074 0.000872882 0.000894925 0.000919926 0.000947574 0.000262319 0.0010035 0.00103447 0.00106692 0.00110046 0.00113466 0.00116912 0.00120339 0.00123705 0.000434905 0.00128748 0.00131775 0.00134625 0.00137262 0.00139648 0.000506584 0.00143107 0.00144852 0.00540044 0.00589632 0.00639231 0.00687747 0.00734196 0.00777741 0.00817724 0.0085368 0.00885346 0.0091265 0.00935687 0.00954691 0.00969997 0.00982007 0.00991154 0.00997874 0.0100258 0.0100567 0.0100746 0.0100825 0.0100829 0.0100777 0.0100686 0.0100568 0.0100432 0.0100288 0.0100139 0.00999917 0.00998481 0.00997112 0.00995827 0.00994642 0.00993568 0.00992613 0.00991784 0.00991086 0.00990523 0.00990099 0.00989815 0.00989673 0.00540045 0.00589633 0.00639232 0.00687748 0.00734197 0.00777742 0.00817724 0.0085368 0.00885347 0.00912651 0.00935687 0.00954691 0.00969997 0.00982007 0.00991154 0.00997874 0.0100258 0.0100567 0.0100746 0.0100825 0.0100829 0.0100777 0.0100686 0.0100567 0.0100432 0.0100288 0.0100139 0.00999917 0.00998481 0.00997112 0.00995827 0.00994642 0.00993567 0.00992612 0.00991783 0.00991086 0.00990523 0.00990099 0.00989815 0.00989673 0.00144852 0.00143107 0.000506595 0.00139648 0.00137262 0.00134625 0.00131775 0.00128748 0.000434915 0.00123706 0.00120339 0.00116912 0.00113467 0.00110046 0.00106692 0.00103447 0.0010035 0.00026233 0.000947576 0.000919928 0.000894927 0.000872884 0.000854076 0.000838738 0.000827062 0.000819196 0.000815238 ) ; } } // ************************************************************************* //
[ "chaseh13@login4.stampede2.tacc.utexas.edu" ]
chaseh13@login4.stampede2.tacc.utexas.edu
4a27d64e0ebcbd83e1667aa39f30354ef35a6188
528bc42b61e9f2849fae1e44cb1f7541b8453032
/Satellitenbahn/Sinkflug.h
3e21a7f2de33f13153e572864298f9f6e2e32f49
[]
no_license
AnnaVorl/Satellitenbahn
5193bf0cd874d18173ab5797e52148fbd2b305d1
e7555edbe7f13ddc419e3f874c20f34b316ca0c6
refs/heads/master
2020-03-21T21:13:54.649901
2018-07-18T11:11:19
2018-07-18T11:11:19
139,053,491
1
0
null
null
null
null
UTF-8
C++
false
false
528
h
/* * Sinkflug.h * * Created on: Jun 29, 2018 * Author: m1741169 */ #ifndef SINKFLUG_H_ #define SINKFLUG_H_ #include <stdio.h> #include <math.h> class Sinkflug { double G=6.67*pow(10, -11); //Gravitationskonstante double M=5.97*pow(10, 24); //Masse der Erde double R=6371000; //Erdradius double pi=3.14; double t; //Zeit double r; //Summe aus R und h double h; //Flughoehe ueber der Erdoberflaeche public: Sinkflug(); virtual ~Sinkflug(); }; #endif /* SINKFLUG_H_ */
[ "1741169@uni-wuppertal.de" ]
1741169@uni-wuppertal.de
677e2af6a213fc8db734bb56732c370fa87a7432
cd5d0059e97efe6c6f64ac77e0040d23d1c5340b
/D3D12/External/SimpleMath/SimpleMath.h
9f9d6bc766d153e290d8a544eb87b5de86f3759b
[]
no_license
ajweeks/D3D12_Research
31444940dfa94eee43964587e7d06d850c8f261a
69174156ba05398d54ba860d79a2e2e5ab9c9f4b
refs/heads/master
2020-04-30T10:47:50.469412
2019-03-24T11:40:30
2019-03-24T11:40:30
176,785,963
1
0
null
2019-03-24T11:40:31
2019-03-20T17:39:18
C++
UTF-8
C++
false
false
50,555
h
//------------------------------------------------------------------------------------- // SimpleMath.h -- Simplified C++ Math wrapper for DirectXMath // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 // http://go.microsoft.com/fwlink/?LinkID=615561 //------------------------------------------------------------------------------------- #pragma once #if !defined(__d3d11_h__) && !defined(__d3d11_x_h__) && !defined(__d3d12_h__) && !defined(__d3d12_x_h__) //#error include d3d11.h or d3d12.h before including SimpleMath.h #endif #if !defined(_XBOX_ONE) || !defined(_TITLE) #include <dxgi1_2.h> #endif #include <functional> #include <assert.h> #include <memory.h> #include <DirectXMath.h> #include <DirectXPackedVector.h> #include <DirectXCollision.h> #ifndef XM_CONSTEXPR #define XM_CONSTEXPR #endif namespace DirectX { namespace SimpleMath { struct Vector2; struct Vector4; struct Matrix; struct Quaternion; struct Plane; //------------------------------------------------------------------------------ // 2D rectangle struct Rectangle { long x; long y; long width; long height; // Creators Rectangle() noexcept : x(0), y(0), width(0), height(0) {} XM_CONSTEXPR Rectangle(long ix, long iy, long iw, long ih) : x(ix), y(iy), width(iw), height(ih) {} explicit Rectangle(const RECT& rct) : x(rct.left), y(rct.top), width(rct.right - rct.left), height(rct.bottom - rct.top) {} Rectangle(const Rectangle&) = default; Rectangle& operator=(const Rectangle&) = default; Rectangle(Rectangle&&) = default; Rectangle& operator=(Rectangle&&) = default; operator RECT() { RECT rct; rct.left = x; rct.top = y; rct.right = (x + width); rct.bottom = (y + height); return rct; } #ifdef __cplusplus_winrt operator Windows::Foundation::Rect() { return Windows::Foundation::Rect(float(x), float(y), float(width), float(height)); } #endif // Comparison operators bool operator == (const Rectangle& r) const { return (x == r.x) && (y == r.y) && (width == r.width) && (height == r.height); } bool operator == (const RECT& rct) const { return (x == rct.left) && (y == rct.top) && (width == (rct.right - rct.left)) && (height == (rct.bottom - rct.top)); } bool operator != (const Rectangle& r) const { return (x != r.x) || (y != r.y) || (width != r.width) || (height != r.height); } bool operator != (const RECT& rct) const { return (x != rct.left) || (y != rct.top) || (width != (rct.right - rct.left)) || (height != (rct.bottom - rct.top)); } // Assignment operators Rectangle& operator=(_In_ const RECT& rct) { x = rct.left; y = rct.top; width = (rct.right - rct.left); height = (rct.bottom - rct.top); return *this; } // Rectangle operations Vector2 Location() const; Vector2 Center() const; bool IsEmpty() const { return (width == 0 && height == 0 && x == 0 && y == 0); } bool Contains(long ix, long iy) const { return (x <= ix) && (ix < (x + width)) && (y <= iy) && (iy < (y + height)); } bool Contains(const Vector2& point) const; bool Contains(const Rectangle& r) const { return (x <= r.x) && ((r.x + r.width) <= (x + width)) && (y <= r.y) && ((r.y + r.height) <= (y + height)); } bool Contains(const RECT& rct) const { return (x <= rct.left) && (rct.right <= (x + width)) && (y <= rct.top) && (rct.bottom <= (y + height)); } void Inflate(long horizAmount, long vertAmount); bool Intersects(const Rectangle& r) const { return (r.x < (x + width)) && (x < (r.x + r.width)) && (r.y < (y + height)) && (y < (r.y + r.height)); } bool Intersects(const RECT& rct) const { return (rct.left < (x + width)) && (x < rct.right) && (rct.top < (y + height)) && (y < rct.bottom); } void Offset(long ox, long oy) { x += ox; y += oy; } // Static functions static Rectangle Intersect(const Rectangle& ra, const Rectangle& rb); static RECT Intersect(const RECT& rcta, const RECT& rctb); static Rectangle Union(const Rectangle& ra, const Rectangle& rb); static RECT Union(const RECT& rcta, const RECT& rctb); }; //------------------------------------------------------------------------------ // 2D vector struct Vector2 : public XMFLOAT2 { Vector2() noexcept : XMFLOAT2(0.f, 0.f) {} XM_CONSTEXPR explicit Vector2(float x) : XMFLOAT2(x, x) {} XM_CONSTEXPR Vector2(float _x, float _y) : XMFLOAT2(_x, _y) {} explicit Vector2(_In_reads_(2) const float *pArray) : XMFLOAT2(pArray) {} Vector2(FXMVECTOR V) { XMStoreFloat2(this, V); } Vector2(const XMFLOAT2& V) { this->x = V.x; this->y = V.y; } explicit Vector2(const XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; } Vector2(const Vector2&) = default; Vector2& operator=(const Vector2&) = default; Vector2(Vector2&&) = default; Vector2& operator=(Vector2&&) = default; operator XMVECTOR() const { return XMLoadFloat2(this); } // Comparison operators bool operator == (const Vector2& V) const; bool operator != (const Vector2& V) const; // Assignment operators Vector2& operator= (const XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; return *this; } Vector2& operator+= (const Vector2& V); Vector2& operator-= (const Vector2& V); Vector2& operator*= (const Vector2& V); Vector2& operator*= (float S); Vector2& operator/= (float S); // Unary operators Vector2 operator+ () const { return *this; } Vector2 operator- () const { return Vector2(-x, -y); } // Vector operations bool InBounds(const Vector2& Bounds) const; float Length() const; float LengthSquared() const; float Dot(const Vector2& V) const; void Cross(const Vector2& V, Vector2& result) const; Vector2 Cross(const Vector2& V) const; void Normalize(); void Normalize(Vector2& result) const; void Clamp(const Vector2& vmin, const Vector2& vmax); void Clamp(const Vector2& vmin, const Vector2& vmax, Vector2& result) const; // Static functions static float Distance(const Vector2& v1, const Vector2& v2); static float DistanceSquared(const Vector2& v1, const Vector2& v2); static void Min(const Vector2& v1, const Vector2& v2, Vector2& result); static Vector2 Min(const Vector2& v1, const Vector2& v2); static void Max(const Vector2& v1, const Vector2& v2, Vector2& result); static Vector2 Max(const Vector2& v1, const Vector2& v2); static void Lerp(const Vector2& v1, const Vector2& v2, float t, Vector2& result); static Vector2 Lerp(const Vector2& v1, const Vector2& v2, float t); static void SmoothStep(const Vector2& v1, const Vector2& v2, float t, Vector2& result); static Vector2 SmoothStep(const Vector2& v1, const Vector2& v2, float t); static void Barycentric(const Vector2& v1, const Vector2& v2, const Vector2& v3, float f, float g, Vector2& result); static Vector2 Barycentric(const Vector2& v1, const Vector2& v2, const Vector2& v3, float f, float g); static void CatmullRom(const Vector2& v1, const Vector2& v2, const Vector2& v3, const Vector2& v4, float t, Vector2& result); static Vector2 CatmullRom(const Vector2& v1, const Vector2& v2, const Vector2& v3, const Vector2& v4, float t); static void Hermite(const Vector2& v1, const Vector2& t1, const Vector2& v2, const Vector2& t2, float t, Vector2& result); static Vector2 Hermite(const Vector2& v1, const Vector2& t1, const Vector2& v2, const Vector2& t2, float t); static void Reflect(const Vector2& ivec, const Vector2& nvec, Vector2& result); static Vector2 Reflect(const Vector2& ivec, const Vector2& nvec); static void Refract(const Vector2& ivec, const Vector2& nvec, float refractionIndex, Vector2& result); static Vector2 Refract(const Vector2& ivec, const Vector2& nvec, float refractionIndex); static void Transform(const Vector2& v, const Quaternion& quat, Vector2& result); static Vector2 Transform(const Vector2& v, const Quaternion& quat); static void Transform(const Vector2& v, const Matrix& m, Vector2& result); static Vector2 Transform(const Vector2& v, const Matrix& m); static void Transform(_In_reads_(count) const Vector2* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector2* resultArray); static void Transform(const Vector2& v, const Matrix& m, Vector4& result); static void Transform(_In_reads_(count) const Vector2* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector4* resultArray); static void TransformNormal(const Vector2& v, const Matrix& m, Vector2& result); static Vector2 TransformNormal(const Vector2& v, const Matrix& m); static void TransformNormal(_In_reads_(count) const Vector2* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector2* resultArray); // Constants static const Vector2 Zero; static const Vector2 One; static const Vector2 UnitX; static const Vector2 UnitY; }; // Binary operators Vector2 operator+ (const Vector2& V1, const Vector2& V2); Vector2 operator- (const Vector2& V1, const Vector2& V2); Vector2 operator* (const Vector2& V1, const Vector2& V2); Vector2 operator* (const Vector2& V, float S); Vector2 operator/ (const Vector2& V1, const Vector2& V2); Vector2 operator* (float S, const Vector2& V); //------------------------------------------------------------------------------ // 3D vector struct Vector3 : public XMFLOAT3 { Vector3() noexcept : XMFLOAT3(0.f, 0.f, 0.f) {} XM_CONSTEXPR explicit Vector3(float x) : XMFLOAT3(x, x, x) {} XM_CONSTEXPR Vector3(float _x, float _y, float _z) : XMFLOAT3(_x, _y, _z) {} explicit Vector3(_In_reads_(3) const float *pArray) : XMFLOAT3(pArray) {} Vector3(FXMVECTOR V) { XMStoreFloat3(this, V); } Vector3(const XMFLOAT3& V) { this->x = V.x; this->y = V.y; this->z = V.z; } explicit Vector3(const XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; } Vector3(const Vector3&) = default; Vector3& operator=(const Vector3&) = default; Vector3(Vector3&&) = default; Vector3& operator=(Vector3&&) = default; operator XMVECTOR() const { return XMLoadFloat3(this); } // Comparison operators bool operator == (const Vector3& V) const; bool operator != (const Vector3& V) const; // Assignment operators Vector3& operator= (const XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; z = F.f[2]; return *this; } Vector3& operator+= (const Vector3& V); Vector3& operator-= (const Vector3& V); Vector3& operator*= (const Vector3& V); Vector3& operator*= (float S); Vector3& operator/= (float S); // Unary operators Vector3 operator+ () const { return *this; } Vector3 operator- () const; // Vector operations bool InBounds(const Vector3& Bounds) const; float Length() const; float LengthSquared() const; float Dot(const Vector3& V) const; void Cross(const Vector3& V, Vector3& result) const; Vector3 Cross(const Vector3& V) const; void Normalize(); void Normalize(Vector3& result) const; void Clamp(const Vector3& vmin, const Vector3& vmax); void Clamp(const Vector3& vmin, const Vector3& vmax, Vector3& result) const; // Static functions static float Distance(const Vector3& v1, const Vector3& v2); static float DistanceSquared(const Vector3& v1, const Vector3& v2); static void Min(const Vector3& v1, const Vector3& v2, Vector3& result); static Vector3 Min(const Vector3& v1, const Vector3& v2); static void Max(const Vector3& v1, const Vector3& v2, Vector3& result); static Vector3 Max(const Vector3& v1, const Vector3& v2); static void Lerp(const Vector3& v1, const Vector3& v2, float t, Vector3& result); static Vector3 Lerp(const Vector3& v1, const Vector3& v2, float t); static void SmoothStep(const Vector3& v1, const Vector3& v2, float t, Vector3& result); static Vector3 SmoothStep(const Vector3& v1, const Vector3& v2, float t); static void Barycentric(const Vector3& v1, const Vector3& v2, const Vector3& v3, float f, float g, Vector3& result); static Vector3 Barycentric(const Vector3& v1, const Vector3& v2, const Vector3& v3, float f, float g); static void CatmullRom(const Vector3& v1, const Vector3& v2, const Vector3& v3, const Vector3& v4, float t, Vector3& result); static Vector3 CatmullRom(const Vector3& v1, const Vector3& v2, const Vector3& v3, const Vector3& v4, float t); static void Hermite(const Vector3& v1, const Vector3& t1, const Vector3& v2, const Vector3& t2, float t, Vector3& result); static Vector3 Hermite(const Vector3& v1, const Vector3& t1, const Vector3& v2, const Vector3& t2, float t); static void Reflect(const Vector3& ivec, const Vector3& nvec, Vector3& result); static Vector3 Reflect(const Vector3& ivec, const Vector3& nvec); static void Refract(const Vector3& ivec, const Vector3& nvec, float refractionIndex, Vector3& result); static Vector3 Refract(const Vector3& ivec, const Vector3& nvec, float refractionIndex); static void Transform(const Vector3& v, const Quaternion& quat, Vector3& result); static Vector3 Transform(const Vector3& v, const Quaternion& quat); static void Transform(const Vector3& v, const Matrix& m, Vector3& result); static Vector3 Transform(const Vector3& v, const Matrix& m); static void Transform(_In_reads_(count) const Vector3* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector3* resultArray); static void Transform(const Vector3& v, const Matrix& m, Vector4& result); static void Transform(_In_reads_(count) const Vector3* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector4* resultArray); static void TransformNormal(const Vector3& v, const Matrix& m, Vector3& result); static Vector3 TransformNormal(const Vector3& v, const Matrix& m); static void TransformNormal(_In_reads_(count) const Vector3* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector3* resultArray); // Constants static const Vector3 Zero; static const Vector3 One; static const Vector3 UnitX; static const Vector3 UnitY; static const Vector3 UnitZ; static const Vector3 Up; static const Vector3 Down; static const Vector3 Right; static const Vector3 Left; static const Vector3 Forward; static const Vector3 Backward; }; // Binary operators Vector3 operator+ (const Vector3& V1, const Vector3& V2); Vector3 operator- (const Vector3& V1, const Vector3& V2); Vector3 operator* (const Vector3& V1, const Vector3& V2); Vector3 operator* (const Vector3& V, float S); Vector3 operator/ (const Vector3& V1, const Vector3& V2); Vector3 operator* (float S, const Vector3& V); //------------------------------------------------------------------------------ // 4D vector struct Vector4 : public XMFLOAT4 { Vector4() noexcept : XMFLOAT4(0.f, 0.f, 0.f, 0.f) {} XM_CONSTEXPR explicit Vector4(float x) : XMFLOAT4(x, x, x, x) {} XM_CONSTEXPR Vector4(float _x, float _y, float _z, float _w) : XMFLOAT4(_x, _y, _z, _w) {} explicit Vector4(_In_reads_(4) const float *pArray) : XMFLOAT4(pArray) {} Vector4(FXMVECTOR V) { XMStoreFloat4(this, V); } Vector4(const XMFLOAT4& V) { this->x = V.x; this->y = V.y; this->z = V.z; this->w = V.w; } explicit Vector4(const XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } Vector4(const Vector4&) = default; Vector4& operator=(const Vector4&) = default; Vector4(Vector4&&) = default; Vector4& operator=(Vector4&&) = default; operator XMVECTOR() const { return XMLoadFloat4(this); } // Comparison operators bool operator == (const Vector4& V) const; bool operator != (const Vector4& V) const; // Assignment operators Vector4& operator= (const XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } Vector4& operator+= (const Vector4& V); Vector4& operator-= (const Vector4& V); Vector4& operator*= (const Vector4& V); Vector4& operator*= (float S); Vector4& operator/= (float S); // Unary operators Vector4 operator+ () const { return *this; } Vector4 operator- () const; // Vector operations bool InBounds(const Vector4& Bounds) const; float Length() const; float LengthSquared() const; float Dot(const Vector4& V) const; void Cross(const Vector4& v1, const Vector4& v2, Vector4& result) const; Vector4 Cross(const Vector4& v1, const Vector4& v2) const; void Normalize(); void Normalize(Vector4& result) const; void Clamp(const Vector4& vmin, const Vector4& vmax); void Clamp(const Vector4& vmin, const Vector4& vmax, Vector4& result) const; // Static functions static float Distance(const Vector4& v1, const Vector4& v2); static float DistanceSquared(const Vector4& v1, const Vector4& v2); static void Min(const Vector4& v1, const Vector4& v2, Vector4& result); static Vector4 Min(const Vector4& v1, const Vector4& v2); static void Max(const Vector4& v1, const Vector4& v2, Vector4& result); static Vector4 Max(const Vector4& v1, const Vector4& v2); static void Lerp(const Vector4& v1, const Vector4& v2, float t, Vector4& result); static Vector4 Lerp(const Vector4& v1, const Vector4& v2, float t); static void SmoothStep(const Vector4& v1, const Vector4& v2, float t, Vector4& result); static Vector4 SmoothStep(const Vector4& v1, const Vector4& v2, float t); static void Barycentric(const Vector4& v1, const Vector4& v2, const Vector4& v3, float f, float g, Vector4& result); static Vector4 Barycentric(const Vector4& v1, const Vector4& v2, const Vector4& v3, float f, float g); static void CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t, Vector4& result); static Vector4 CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t); static void Hermite(const Vector4& v1, const Vector4& t1, const Vector4& v2, const Vector4& t2, float t, Vector4& result); static Vector4 Hermite(const Vector4& v1, const Vector4& t1, const Vector4& v2, const Vector4& t2, float t); static void Reflect(const Vector4& ivec, const Vector4& nvec, Vector4& result); static Vector4 Reflect(const Vector4& ivec, const Vector4& nvec); static void Refract(const Vector4& ivec, const Vector4& nvec, float refractionIndex, Vector4& result); static Vector4 Refract(const Vector4& ivec, const Vector4& nvec, float refractionIndex); static void Transform(const Vector2& v, const Quaternion& quat, Vector4& result); static Vector4 Transform(const Vector2& v, const Quaternion& quat); static void Transform(const Vector3& v, const Quaternion& quat, Vector4& result); static Vector4 Transform(const Vector3& v, const Quaternion& quat); static void Transform(const Vector4& v, const Quaternion& quat, Vector4& result); static Vector4 Transform(const Vector4& v, const Quaternion& quat); static void Transform(const Vector4& v, const Matrix& m, Vector4& result); static Vector4 Transform(const Vector4& v, const Matrix& m); static void Transform(_In_reads_(count) const Vector4* varray, size_t count, const Matrix& m, _Out_writes_(count) Vector4* resultArray); // Constants static const Vector4 Zero; static const Vector4 One; static const Vector4 UnitX; static const Vector4 UnitY; static const Vector4 UnitZ; static const Vector4 UnitW; }; // Binary operators Vector4 operator+ (const Vector4& V1, const Vector4& V2); Vector4 operator- (const Vector4& V1, const Vector4& V2); Vector4 operator* (const Vector4& V1, const Vector4& V2); Vector4 operator* (const Vector4& V, float S); Vector4 operator/ (const Vector4& V1, const Vector4& V2); Vector4 operator* (float S, const Vector4& V); //------------------------------------------------------------------------------ // 4x4 Matrix (assumes right-handed cooordinates) struct Matrix : public XMFLOAT4X4 { Matrix() noexcept : XMFLOAT4X4(1.f, 0, 0, 0, 0, 1.f, 0, 0, 0, 0, 1.f, 0, 0, 0, 0, 1.f) {} XM_CONSTEXPR Matrix(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) : XMFLOAT4X4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {} explicit Matrix(const Vector3& r0, const Vector3& r1, const Vector3& r2) : XMFLOAT4X4(r0.x, r0.y, r0.z, 0, r1.x, r1.y, r1.z, 0, r2.x, r2.y, r2.z, 0, 0, 0, 0, 1.f) {} explicit Matrix(const Vector4& r0, const Vector4& r1, const Vector4& r2, const Vector4& r3) : XMFLOAT4X4(r0.x, r0.y, r0.z, r0.w, r1.x, r1.y, r1.z, r1.w, r2.x, r2.y, r2.z, r2.w, r3.x, r3.y, r3.z, r3.w) {} Matrix(const XMFLOAT4X4& M) { memcpy_s(this, sizeof(float) * 16, &M, sizeof(XMFLOAT4X4)); } Matrix(const XMFLOAT3X3& M); Matrix(const XMFLOAT4X3& M); explicit Matrix(_In_reads_(16) const float *pArray) : XMFLOAT4X4(pArray) {} Matrix(CXMMATRIX M) { XMStoreFloat4x4(this, M); } Matrix(const Matrix&) = default; Matrix& operator=(const Matrix&) = default; Matrix(Matrix&&) = default; Matrix& operator=(Matrix&&) = default; operator XMMATRIX() const { return XMLoadFloat4x4(this); } // Comparison operators bool operator == (const Matrix& M) const; bool operator != (const Matrix& M) const; // Assignment operators Matrix& operator= (const XMFLOAT3X3& M); Matrix& operator= (const XMFLOAT4X3& M); Matrix& operator+= (const Matrix& M); Matrix& operator-= (const Matrix& M); Matrix& operator*= (const Matrix& M); Matrix& operator*= (float S); Matrix& operator/= (float S); Matrix& operator/= (const Matrix& M); // Element-wise divide // Unary operators Matrix operator+ () const { return *this; } Matrix operator- () const; // Properties Vector3 Up() const { return Vector3(_21, _22, _23); } void Up(const Vector3& v) { _21 = v.x; _22 = v.y; _23 = v.z; } Vector3 Down() const { return Vector3(-_21, -_22, -_23); } void Down(const Vector3& v) { _21 = -v.x; _22 = -v.y; _23 = -v.z; } Vector3 Right() const { return Vector3(_11, _12, _13); } void Right(const Vector3& v) { _11 = v.x; _12 = v.y; _13 = v.z; } Vector3 Left() const { return Vector3(-_11, -_12, -_13); } void Left(const Vector3& v) { _11 = -v.x; _12 = -v.y; _13 = -v.z; } Vector3 Forward() const { return Vector3(-_31, -_32, -_33); } void Forward(const Vector3& v) { _31 = -v.x; _32 = -v.y; _33 = -v.z; } Vector3 Backward() const { return Vector3(_31, _32, _33); } void Backward(const Vector3& v) { _31 = v.x; _32 = v.y; _33 = v.z; } Vector3 Translation() const { return Vector3(_41, _42, _43); } void Translation(const Vector3& v) { _41 = v.x; _42 = v.y; _43 = v.z; } // Matrix operations bool Decompose(Vector3& scale, Quaternion& rotation, Vector3& translation); Matrix Transpose() const; void Transpose(Matrix& result) const; Matrix Invert() const; void Invert(Matrix& result) const; float Determinant() const; // Static functions static Matrix CreateBillboard(const Vector3& object, const Vector3& cameraPosition, const Vector3& cameraUp, _In_opt_ const Vector3* cameraForward = nullptr); static Matrix CreateConstrainedBillboard(const Vector3& object, const Vector3& cameraPosition, const Vector3& rotateAxis, _In_opt_ const Vector3* cameraForward = nullptr, _In_opt_ const Vector3* objectForward = nullptr); static Matrix CreateTranslation(const Vector3& position); static Matrix CreateTranslation(float x, float y, float z); static Matrix CreateScale(const Vector3& scales); static Matrix CreateScale(float xs, float ys, float zs); static Matrix CreateScale(float scale); static Matrix CreateRotationX(float radians); static Matrix CreateRotationY(float radians); static Matrix CreateRotationZ(float radians); static Matrix CreateFromAxisAngle(const Vector3& axis, float angle); static Matrix CreatePerspectiveFieldOfView(float fov, float aspectRatio, float nearPlane, float farPlane); static Matrix CreatePerspective(float width, float height, float nearPlane, float farPlane); static Matrix CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlane, float farPlane); static Matrix CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane); static Matrix CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane); static Matrix CreateLookAt(const Vector3& position, const Vector3& target, const Vector3& up); static Matrix CreateWorld(const Vector3& position, const Vector3& forward, const Vector3& up); static Matrix CreateFromQuaternion(const Quaternion& quat); static Matrix CreateFromYawPitchRoll(float yaw, float pitch, float roll); static Matrix CreateShadow(const Vector3& lightDir, const Plane& plane); static Matrix CreateReflection(const Plane& plane); static void Lerp(const Matrix& M1, const Matrix& M2, float t, Matrix& result); static Matrix Lerp(const Matrix& M1, const Matrix& M2, float t); static void Transform(const Matrix& M, const Quaternion& rotation, Matrix& result); static Matrix Transform(const Matrix& M, const Quaternion& rotation); // Constants static const Matrix Identity; }; // Binary operators Matrix operator+ (const Matrix& M1, const Matrix& M2); Matrix operator- (const Matrix& M1, const Matrix& M2); Matrix operator* (const Matrix& M1, const Matrix& M2); Matrix operator* (const Matrix& M, float S); Matrix operator/ (const Matrix& M, float S); Matrix operator/ (const Matrix& M1, const Matrix& M2); // Element-wise divide Matrix operator* (float S, const Matrix& M); //----------------------------------------------------------------------------- // Plane struct Plane : public XMFLOAT4 { Plane() noexcept : XMFLOAT4(0.f, 1.f, 0.f, 0.f) {} XM_CONSTEXPR Plane(float _x, float _y, float _z, float _w) : XMFLOAT4(_x, _y, _z, _w) {} Plane(const Vector3& normal, float d) : XMFLOAT4(normal.x, normal.y, normal.z, d) {} Plane(const Vector3& point1, const Vector3& point2, const Vector3& point3); Plane(const Vector3& point, const Vector3& normal); explicit Plane(const Vector4& v) : XMFLOAT4(v.x, v.y, v.z, v.w) {} explicit Plane(_In_reads_(4) const float *pArray) : XMFLOAT4(pArray) {} Plane(FXMVECTOR V) { XMStoreFloat4(this, V); } Plane(const XMFLOAT4& p) { this->x = p.x; this->y = p.y; this->z = p.z; this->w = p.w; } explicit Plane(const XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } Plane(const Plane&) = default; Plane& operator=(const Plane&) = default; Plane(Plane&&) = default; Plane& operator=(Plane&&) = default; operator XMVECTOR() const { return XMLoadFloat4(this); } // Comparison operators bool operator == (const Plane& p) const; bool operator != (const Plane& p) const; // Assignment operators Plane& operator= (const XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } // Properties Vector3 Normal() const { return Vector3(x, y, z); } void Normal(const Vector3& normal) { x = normal.x; y = normal.y; z = normal.z; } float D() const { return w; } void D(float d) { w = d; } // Plane operations void Normalize(); void Normalize(Plane& result) const; float Dot(const Vector4& v) const; float DotCoordinate(const Vector3& position) const; float DotNormal(const Vector3& normal) const; // Static functions static void Transform(const Plane& plane, const Matrix& M, Plane& result); static Plane Transform(const Plane& plane, const Matrix& M); static void Transform(const Plane& plane, const Quaternion& rotation, Plane& result); static Plane Transform(const Plane& plane, const Quaternion& rotation); // Input quaternion must be the inverse transpose of the transformation }; //------------------------------------------------------------------------------ // Quaternion struct Quaternion : public XMFLOAT4 { Quaternion() noexcept : XMFLOAT4(0, 0, 0, 1.f) {} XM_CONSTEXPR Quaternion(float _x, float _y, float _z, float _w) : XMFLOAT4(_x, _y, _z, _w) {} Quaternion(const Vector3& v, float scalar) : XMFLOAT4(v.x, v.y, v.z, scalar) {} explicit Quaternion(const Vector4& v) : XMFLOAT4(v.x, v.y, v.z, v.w) {} explicit Quaternion(_In_reads_(4) const float *pArray) : XMFLOAT4(pArray) {} Quaternion(FXMVECTOR V) { XMStoreFloat4(this, V); } Quaternion(const XMFLOAT4& q) { this->x = q.x; this->y = q.y; this->z = q.z; this->w = q.w; } explicit Quaternion(const XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } Quaternion(const Quaternion&) = default; Quaternion& operator=(const Quaternion&) = default; Quaternion(Quaternion&&) = default; Quaternion& operator=(Quaternion&&) = default; operator XMVECTOR() const { return XMLoadFloat4(this); } // Comparison operators bool operator == (const Quaternion& q) const; bool operator != (const Quaternion& q) const; // Assignment operators Quaternion& operator= (const XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } Quaternion& operator+= (const Quaternion& q); Quaternion& operator-= (const Quaternion& q); Quaternion& operator*= (const Quaternion& q); Quaternion& operator*= (float S); Quaternion& operator/= (const Quaternion& q); // Unary operators Quaternion operator+ () const { return *this; } Quaternion operator- () const; // Quaternion operations float Length() const; float LengthSquared() const; void Normalize(); void Normalize(Quaternion& result) const; void Conjugate(); void Conjugate(Quaternion& result) const; void Inverse(Quaternion& result) const; float Dot(const Quaternion& Q) const; // Static functions static Quaternion CreateFromAxisAngle(const Vector3& axis, float angle); static Quaternion CreateFromYawPitchRoll(float yaw, float pitch, float roll); static Quaternion CreateFromRotationMatrix(const Matrix& M); static void Lerp(const Quaternion& q1, const Quaternion& q2, float t, Quaternion& result); static Quaternion Lerp(const Quaternion& q1, const Quaternion& q2, float t); static void Slerp(const Quaternion& q1, const Quaternion& q2, float t, Quaternion& result); static Quaternion Slerp(const Quaternion& q1, const Quaternion& q2, float t); static void Concatenate(const Quaternion& q1, const Quaternion& q2, Quaternion& result); static Quaternion Concatenate(const Quaternion& q1, const Quaternion& q2); // Constants static const Quaternion Identity; }; // Binary operators Quaternion operator+ (const Quaternion& Q1, const Quaternion& Q2); Quaternion operator- (const Quaternion& Q1, const Quaternion& Q2); Quaternion operator* (const Quaternion& Q1, const Quaternion& Q2); Quaternion operator* (const Quaternion& Q, float S); Quaternion operator/ (const Quaternion& Q1, const Quaternion& Q2); Quaternion operator* (float S, const Quaternion& Q); //------------------------------------------------------------------------------ // Color struct Color : public XMFLOAT4 { Color() noexcept : XMFLOAT4(0, 0, 0, 1.f) {} XM_CONSTEXPR Color(float _r, float _g, float _b) : XMFLOAT4(_r, _g, _b, 1.f) {} XM_CONSTEXPR Color(float _r, float _g, float _b, float _a) : XMFLOAT4(_r, _g, _b, _a) {} explicit Color(const Vector3& clr) : XMFLOAT4(clr.x, clr.y, clr.z, 1.f) {} explicit Color(const Vector4& clr) : XMFLOAT4(clr.x, clr.y, clr.z, clr.w) {} explicit Color(_In_reads_(4) const float *pArray) : XMFLOAT4(pArray) {} Color(FXMVECTOR V) { XMStoreFloat4(this, V); } Color(const XMFLOAT4& c) { this->x = c.x; this->y = c.y; this->z = c.z; this->w = c.w; } explicit Color(const XMVECTORF32& F) { this->x = F.f[0]; this->y = F.f[1]; this->z = F.f[2]; this->w = F.f[3]; } explicit Color(const DirectX::PackedVector::XMCOLOR& Packed); // BGRA Direct3D 9 D3DCOLOR packed color explicit Color(const DirectX::PackedVector::XMUBYTEN4& Packed); // RGBA XNA Game Studio packed color Color(const Color&) = default; Color& operator=(const Color&) = default; Color(Color&&) = default; Color& operator=(Color&&) = default; operator XMVECTOR() const { return XMLoadFloat4(this); } operator const float*() const { return reinterpret_cast<const float*>(this); } // Comparison operators bool operator == (const Color& c) const; bool operator != (const Color& c) const; // Assignment operators Color& operator= (const XMVECTORF32& F) { x = F.f[0]; y = F.f[1]; z = F.f[2]; w = F.f[3]; return *this; } Color& operator= (const DirectX::PackedVector::XMCOLOR& Packed); Color& operator= (const DirectX::PackedVector::XMUBYTEN4& Packed); Color& operator+= (const Color& c); Color& operator-= (const Color& c); Color& operator*= (const Color& c); Color& operator*= (float S); Color& operator/= (const Color& c); // Unary operators Color operator+ () const { return *this; } Color operator- () const; // Properties float R() const { return x; } void R(float r) { x = r; } float G() const { return y; } void G(float g) { y = g; } float B() const { return z; } void B(float b) { z = b; } float A() const { return w; } void A(float a) { w = a; } // Color operations DirectX::PackedVector::XMCOLOR BGRA() const; DirectX::PackedVector::XMUBYTEN4 RGBA() const; Vector3 ToVector3() const; Vector4 ToVector4() const; void Negate(); void Negate(Color& result) const; void Saturate(); void Saturate(Color& result) const; void Premultiply(); void Premultiply(Color& result) const; void AdjustSaturation(float sat); void AdjustSaturation(float sat, Color& result) const; void AdjustContrast(float contrast); void AdjustContrast(float contrast, Color& result) const; // Static functions static void Modulate(const Color& c1, const Color& c2, Color& result); static Color Modulate(const Color& c1, const Color& c2); static void Lerp(const Color& c1, const Color& c2, float t, Color& result); static Color Lerp(const Color& c1, const Color& c2, float t); }; // Binary operators Color operator+ (const Color& C1, const Color& C2); Color operator- (const Color& C1, const Color& C2); Color operator* (const Color& C1, const Color& C2); Color operator* (const Color& C, float S); Color operator/ (const Color& C1, const Color& C2); Color operator* (float S, const Color& C); //------------------------------------------------------------------------------ // Ray class Ray { public: Vector3 position; Vector3 direction; Ray() noexcept : position(0, 0, 0), direction(0, 0, 1) {} Ray(const Vector3& pos, const Vector3& dir) : position(pos), direction(dir) {} Ray(const Ray&) = default; Ray& operator=(const Ray&) = default; Ray(Ray&&) = default; Ray& operator=(Ray&&) = default; // Comparison operators bool operator == (const Ray& r) const; bool operator != (const Ray& r) const; // Ray operations bool Intersects(const BoundingSphere& sphere, _Out_ float& Dist) const; bool Intersects(const BoundingBox& box, _Out_ float& Dist) const; bool Intersects(const Vector3& tri0, const Vector3& tri1, const Vector3& tri2, _Out_ float& Dist) const; bool Intersects(const Plane& plane, _Out_ float& Dist) const; }; //------------------------------------------------------------------------------ // Viewport class Viewport { public: float x; float y; float width; float height; float minDepth; float maxDepth; Viewport() noexcept : x(0.f), y(0.f), width(0.f), height(0.f), minDepth(0.f), maxDepth(1.f) {} XM_CONSTEXPR Viewport(float ix, float iy, float iw, float ih, float iminz = 0.f, float imaxz = 1.f) : x(ix), y(iy), width(iw), height(ih), minDepth(iminz), maxDepth(imaxz) {} explicit Viewport(const RECT& rct) : x(float(rct.left)), y(float(rct.top)), width(float(rct.right - rct.left)), height(float(rct.bottom - rct.top)), minDepth(0.f), maxDepth(1.f) {} #if defined(__d3d11_h__) || defined(__d3d11_x_h__) // Direct3D 11 interop explicit Viewport(const D3D11_VIEWPORT& vp) : x(vp.TopLeftX), y(vp.TopLeftY), width(vp.Width), height(vp.Height), minDepth(vp.MinDepth), maxDepth(vp.MaxDepth) {} operator D3D11_VIEWPORT() { return *reinterpret_cast<const D3D11_VIEWPORT*>(this); } const D3D11_VIEWPORT* Get11() const { return reinterpret_cast<const D3D11_VIEWPORT*>(this); } Viewport& operator= (const D3D11_VIEWPORT& vp); #endif #if defined(__d3d12_h__) || defined(__d3d12_x_h__) // Direct3D 12 interop explicit Viewport(const D3D12_VIEWPORT& vp) : x(vp.TopLeftX), y(vp.TopLeftY), width(vp.Width), height(vp.Height), minDepth(vp.MinDepth), maxDepth(vp.MaxDepth) {} operator D3D12_VIEWPORT() { return *reinterpret_cast<const D3D12_VIEWPORT*>(this); } const D3D12_VIEWPORT* Get12() const { return reinterpret_cast<const D3D12_VIEWPORT*>(this); } Viewport& operator= (const D3D12_VIEWPORT& vp); #endif Viewport(const Viewport&) = default; Viewport& operator=(const Viewport&) = default; Viewport(Viewport&&) = default; Viewport& operator=(Viewport&&) = default; // Comparison operators bool operator == (const Viewport& vp) const; bool operator != (const Viewport& vp) const; // Assignment operators Viewport& operator= (const RECT& rct); // Viewport operations float AspectRatio() const; Vector3 Project(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world) const; void Project(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world, Vector3& result) const; Vector3 Unproject(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world) const; void Unproject(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world, Vector3& result) const; // Static methods static RECT __cdecl ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UINT backBufferHeight, int outputWidth, int outputHeight); static RECT __cdecl ComputeTitleSafeArea(UINT backBufferWidth, UINT backBufferHeight); }; #include "SimpleMath.inl" } // namespace SimpleMath } // namespace DirectX //------------------------------------------------------------------------------ // Support for SimpleMath and Standard C++ Library containers namespace std { template<> struct less<DirectX::SimpleMath::Rectangle> { bool operator()(const DirectX::SimpleMath::Rectangle& r1, const DirectX::SimpleMath::Rectangle& r2) const { return ((r1.x < r2.x) || ((r1.x == r2.x) && (r1.y < r2.y)) || ((r1.x == r2.x) && (r1.y == r2.y) && (r1.width < r2.width)) || ((r1.x == r2.x) && (r1.y == r2.y) && (r1.width == r2.width) && (r1.height < r2.height))); } }; template<> struct less<DirectX::SimpleMath::Vector2> { bool operator()(const DirectX::SimpleMath::Vector2& V1, const DirectX::SimpleMath::Vector2& V2) const { return ((V1.x < V2.x) || ((V1.x == V2.x) && (V1.y < V2.y))); } }; template<> struct less<DirectX::SimpleMath::Vector3> { bool operator()(const DirectX::SimpleMath::Vector3& V1, const DirectX::SimpleMath::Vector3& V2) const { return ((V1.x < V2.x) || ((V1.x == V2.x) && (V1.y < V2.y)) || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z < V2.z))); } }; template<> struct less<DirectX::SimpleMath::Vector4> { bool operator()(const DirectX::SimpleMath::Vector4& V1, const DirectX::SimpleMath::Vector4& V2) const { return ((V1.x < V2.x) || ((V1.x == V2.x) && (V1.y < V2.y)) || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z < V2.z)) || ((V1.x == V2.x) && (V1.y == V2.y) && (V1.z == V2.z) && (V1.w < V2.w))); } }; template<> struct less<DirectX::SimpleMath::Matrix> { bool operator()(const DirectX::SimpleMath::Matrix& M1, const DirectX::SimpleMath::Matrix& M2) const { if (M1._11 != M2._11) return M1._11 < M2._11; if (M1._12 != M2._12) return M1._12 < M2._12; if (M1._13 != M2._13) return M1._13 < M2._13; if (M1._14 != M2._14) return M1._14 < M2._14; if (M1._21 != M2._21) return M1._21 < M2._21; if (M1._22 != M2._22) return M1._22 < M2._22; if (M1._23 != M2._23) return M1._23 < M2._23; if (M1._24 != M2._24) return M1._24 < M2._24; if (M1._31 != M2._31) return M1._31 < M2._31; if (M1._32 != M2._32) return M1._32 < M2._32; if (M1._33 != M2._33) return M1._33 < M2._33; if (M1._34 != M2._34) return M1._34 < M2._34; if (M1._41 != M2._41) return M1._41 < M2._41; if (M1._42 != M2._42) return M1._42 < M2._42; if (M1._43 != M2._43) return M1._43 < M2._43; if (M1._44 != M2._44) return M1._44 < M2._44; return false; } }; template<> struct less<DirectX::SimpleMath::Plane> { bool operator()(const DirectX::SimpleMath::Plane& P1, const DirectX::SimpleMath::Plane& P2) const { return ((P1.x < P2.x) || ((P1.x == P2.x) && (P1.y < P2.y)) || ((P1.x == P2.x) && (P1.y == P2.y) && (P1.z < P2.z)) || ((P1.x == P2.x) && (P1.y == P2.y) && (P1.z == P2.z) && (P1.w < P2.w))); } }; template<> struct less<DirectX::SimpleMath::Quaternion> { bool operator()(const DirectX::SimpleMath::Quaternion& Q1, const DirectX::SimpleMath::Quaternion& Q2) const { return ((Q1.x < Q2.x) || ((Q1.x == Q2.x) && (Q1.y < Q2.y)) || ((Q1.x == Q2.x) && (Q1.y == Q2.y) && (Q1.z < Q2.z)) || ((Q1.x == Q2.x) && (Q1.y == Q2.y) && (Q1.z == Q2.z) && (Q1.w < Q2.w))); } }; template<> struct less<DirectX::SimpleMath::Color> { bool operator()(const DirectX::SimpleMath::Color& C1, const DirectX::SimpleMath::Color& C2) const { return ((C1.x < C2.x) || ((C1.x == C2.x) && (C1.y < C2.y)) || ((C1.x == C2.x) && (C1.y == C2.y) && (C1.z < C2.z)) || ((C1.x == C2.x) && (C1.y == C2.y) && (C1.z == C2.z) && (C1.w < C2.w))); } }; template<> struct less<DirectX::SimpleMath::Ray> { bool operator()(const DirectX::SimpleMath::Ray& R1, const DirectX::SimpleMath::Ray& R2) const { if (R1.position.x != R2.position.x) return R1.position.x < R2.position.x; if (R1.position.y != R2.position.y) return R1.position.y < R2.position.y; if (R1.position.z != R2.position.z) return R1.position.z < R2.position.z; if (R1.direction.x != R2.direction.x) return R1.direction.x < R2.direction.x; if (R1.direction.y != R2.direction.y) return R1.direction.y < R2.direction.y; if (R1.direction.z != R2.direction.z) return R1.direction.z < R2.direction.z; return false; } }; template<> struct less<DirectX::SimpleMath::Viewport> { bool operator()(const DirectX::SimpleMath::Viewport& vp1, const DirectX::SimpleMath::Viewport& vp2) const { if (vp1.x != vp2.x) return (vp1.x < vp2.x); if (vp1.y != vp2.y) return (vp1.y < vp2.y); if (vp1.width != vp2.width) return (vp1.width < vp2.width); if (vp1.height != vp2.height) return (vp1.height < vp2.height); if (vp1.minDepth != vp2.minDepth) return (vp1.minDepth < vp2.minDepth); if (vp1.maxDepth != vp2.maxDepth) return (vp1.maxDepth < vp2.maxDepth); return false; } }; } // namespace std
[ "sim2.coenen@gmail.com" ]
sim2.coenen@gmail.com
b17bfb9ce3db2ae824e44ad98e5b916c7342905a
8cb9bbe6b8128930c72bf7f0fb1527e1d9b572ce
/GSP420 Team Project/Font.cpp
b37237115419ca050e7d5d0d92721c118331acc2
[]
no_license
Derejin/GSP420-Team-Project
efe46e253c6b7e5f0497a397bade3b99a46bb99f
880cf3779a71d4817e4f88d33bcc352dba059262
refs/heads/master
2021-01-17T12:42:40.862688
2016-06-22T20:53:49
2016-06-22T20:53:49
59,066,390
0
3
null
2016-06-22T20:53:49
2016-05-17T23:29:50
C++
UTF-8
C++
false
false
1,551
cpp
//created 5/20, 14:37PST, by Richard #include "Font.h" #include "Graphics.h" #pragma comment(lib, "dwrite.lib") #include "Text.h" //defining statics Graphics* Font::gfx = nullptr; //this needs to be set during bootstrap CComPtr<IDWriteFactory> Font::factory; Font::Font(const std::wstring& faceName, float size) : faceName(faceName), size(size) { //init the static factory if it's not already present if(!factory.p) { DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), (IUnknown**)&factory); } gfx->renderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &brush); } //The dirty/clean strategy used to avoid needless thrashing of the format object. //The Text::draw() function will check the dirty flag and reset the format object //only when needed. void Font::setSize(float size) { this->size = size; dirty = true; } void Font::setBold(bool bold) { this->bold = bold; dirty = true; } void Font::setItalic(bool italic) { this->italic = italic; dirty = true; } void Font::setColor(D2D1::ColorF color) { brush->SetColor(color); } void Font::resetFormat() { if(format.p) { format.Release(); } factory->CreateTextFormat(faceName.c_str(), NULL, bold ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_REGULAR, italic ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, size, L"en-us", &format); format->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); format->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); dirty = false; }
[ "khatharr@gmail.com" ]
khatharr@gmail.com
6beff957b865a023a1969ba0d2582f963c0a69f8
c0c44b30d6a9fd5896fd3dce703c98764c0c447f
/cpp/Targets/GUBI/src/View/View.cpp
f6ba4e600069b57a85cbb129cc5cb75f72f5c5d6
[ "BSD-3-Clause" ]
permissive
wayfinder/Wayfinder-CppCore-v2
59d703b3a9fdf4a67f9b75fbbf4474933aeda7bf
f1d41905bf7523351bc0a1a6b08d04b06c533bd4
refs/heads/master
2020-05-19T15:54:41.035880
2010-06-29T11:56:03
2010-06-29T11:56:03
744,294
1
0
null
null
null
null
UTF-8
C++
false
false
3,363
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "View/View.h" namespace gubi { View::View( void ) { m_bVisible = true; // TODO: Remove this and change to a view-render-queue } View::~View( void ) { } unsigned int View::AddReference( void ) const { return InternalAddReference(); } unsigned int View::Release( void ) const { return InternalRelease(); } bool View::GetProperties( gubi::IPropertyBag** ppProperties ) { return false; } bool View::GetProperties( const gubi::IPropertyBag** ppProperties ) const { return false; } bool View::GetSignal( const gubi::Identifier& eSignalId, gubi::ISignalHub** ppSignalHub ) { return InternalGetSignal(eSignalId, ppSignalHub); } bool View::Show( const gubi::ViewShowFlag& eFlag ) { return m_bVisible = true; } void View::Hide( void ) { m_bVisible = false; } bool View::AddWidget( gubi::IWidget* pWidget, const gubi::ViewSpace& eViewSpace ) { bool bReturn = false; if (pWidget != NULL) { std::vector<SmartPointer<gubi::IWidget> >& vRoots = m_vRoots[eViewSpace]; vRoots.push_back(pWidget); bReturn = true; } return bReturn; } bool View::AddWidgetArray( gubi::IWidgetArray* pWidgetArray, const gubi::ViewSpace& eViewSpace ) { return false; } bool View::FetchNodes( const gubi::ViewSpace& eViewSpace, gubi::RenderQueue& renderQueue ) { bool bReturn = false; std::vector<SmartPointer<gubi::IWidget> >& vRoots = m_vRoots[eViewSpace]; for (unsigned int i = 0; i < vRoots.size(); ++i) { SmartPointer<gubi::IWidget> pWidget = vRoots[i]; if (!pWidget.IsEmpty()) { bReturn = pWidget->update(renderQueue, false) ? true : bReturn; } } return bReturn; } bool View::Visible( void ) { return m_bVisible; } }
[ "hlars@sema-ovpn-morpheus.itinerary.com" ]
hlars@sema-ovpn-morpheus.itinerary.com
dbdc4fe32dfbe726fe85fedcd91b72c38fefc060
c6936c9ea44289c67d9abf0ce45072a03248455c
/cpp/test/mojo/parser/expression/object_literal_test.cpp
2618b437eb3c223d2d618e2986196b0b4ee59fa4
[]
no_license
mojo-lang/mojo
76eb91d728f2b8ffa2779140fb2d4e6ad4e06f58
1424532f49ee2a0e8d4a4525342bd1b839d0a4a5
refs/heads/main
2023-07-08T08:04:32.047515
2023-06-30T09:13:09
2023-06-30T09:13:09
85,015,407
78
6
null
2023-07-27T01:58:19
2017-03-15T01:36:33
Java
UTF-8
C++
false
false
733
cpp
#include <chrono> #include <iostream> #include <mojo/mojo_test.hpp> namespace { using namespace mojo; TEST_CASE("object_literal_parser", "[expression]") { const char* object_str = "{" "id: 'MapEMG'," "name: 'Map for EMG'," "sources: [{ id: '4445', host: 'localhost'}]," "layers: [" " island | category == 999 | zoom in 1..16 | attach_style({" " fill.color: rgb(244, 243, 239)," " fill.outline.color: rgb(246, 242, 239)" " })" "]" "}"; simple_success_parse<grammar::expression>(object_str); } }
[ "noreply@github.com" ]
noreply@github.com
31c35fe03674285622053624991676dd0d54261e
76e09052f5bfa405697b26b88f658619d87a13ee
/gen/memobj_test.cpp
8284de81760fcb184ca1bff6e7148c9f300748ed
[ "Zlib" ]
permissive
iceignatius/genutil
6f92401917dee67e6daecaaa3ee57111f1db14aa
c682bd245d5dbe5dda39c7450be63545346c16ea
refs/heads/master
2020-02-26T16:27:28.017187
2018-04-13T06:06:26
2018-04-13T06:06:26
71,210,497
0
0
null
null
null
null
UTF-8
C++
false
false
17,022
cpp
/* * memobj 測試程式 */ #include <assert.h> #include <string.h> #include <stdio.h> #ifdef __BORLANDC__ #pragma hdrstop #endif #include "memobj.h" #ifdef NDEBUG #error This test program must work with macro "ASSERT" enabled! #endif void test_global_tools(void) { // Data search { const byte_t sample[] = { 0x01, 0x05, 0x05, 0x07, 0x02, 0x04, 0x06, 0x08, 0x01, 0x03, 0x05, 0x07, 0x02, 0x04, 0x06, 0x08, 0x05, 0x07 }; const byte_t pattern[] = { 0x05, 0x07, 0x02 }; assert( 2 == (byte_t*) memfind (sample, sizeof(sample), pattern, sizeof(pattern)) - sample ); assert( 10 == (byte_t*) memrfind(sample, sizeof(sample), pattern, sizeof(pattern)) - sample ); assert( NULL == (byte_t*) memfind (sample, sizeof(sample), "\x03\x08\x09\x02", 4) ); assert( NULL == (byte_t*) memrfind(sample, sizeof(sample), "\x03\x08\x09\x02", 4) ); } // Data search count and replace; { const byte_t src[] = { 0x0D, 0x0A, 's', 't', 'r', 'i', 'n', 'g', 0x0D, 0x0A, 'f', 'i', 'l', 'l', 'e', 'd', 0x0D, 0x0A, 0x0D, 0x0A, 'b', 'e', 't', 'w', 'e', 'e', 'n', }; const byte_t pattern[] = { 0x0D, 0x0A }; const byte_t target [] = { 0x1C, 0x1D, 0x1E }; const byte_t finaldata[] = { 0x1C, 0x1D, 0x1E, 's', 't', 'r', 'i', 'n', 'g', 0x1C, 0x1D, 0x1E, 'f', 'i', 'l', 'l', 'e', 'd', 0x1C, 0x1D, 0x1E, 0x1C, 0x1D, 0x1E, 'b', 'e', 't', 'w', 'e', 'e', 'n', }; byte_t buf[64] = {0}; assert( 4 == memfindcount(src, sizeof(src), pattern, sizeof(pattern)) ); assert( sizeof(finaldata) == memfindreplace(NULL, 0, src, sizeof(src), pattern, sizeof(pattern), target, sizeof(target)) ); assert( sizeof(finaldata) == memfindreplace(buf, sizeof(buf), src, sizeof(src), pattern, sizeof(pattern), target, sizeof(target)) ); assert( 0 == memcmp(buf, finaldata, sizeof(finaldata)) ); } // memobj_calc_recommended_size { size_t size1 = -1; size_t size2 = memobj_calc_recommended_size(size1); assert( size2 >= size1 ); for(size1=0; size1<0xFFFFFF; ++size1) { size2 = memobj_calc_recommended_size(size1); assert( size2 >= size1 ); } } } void test_memory_object(void) { // Object create and release { static const size_t size = 0; mem_t *mem = NULL; assert( mem = mem_create(size) ); assert( mem->size == size ); assert( mem->size_total >= size ); mem_release_s(NULL); mem_release_s(&mem); mem_release_s(&mem); assert( !mem ); } // Object create and import and move { static const byte_t testdata[] = {1,3,5,7,9}; mem_t *memsrc = NULL; mem_t *memdest = NULL; // Create and import assert( memsrc = mem_create_import(testdata, sizeof(testdata)) ); assert( memsrc->buf ); assert( memsrc->size == sizeof(testdata) ); assert( 0 == memcmp(memsrc->buf, testdata, sizeof(testdata)) ); // Create and move assert( memdest = mem_create_move(memsrc) ); assert( memdest->buf ); assert( memdest->size == sizeof(testdata) ); assert( 0 == memcmp(memdest->buf, testdata, sizeof(testdata)) ); assert( memsrc ); assert( memsrc->buf ); assert( memsrc->size == 0 ); mem_release(memsrc); mem_release(memdest); } // Object create and clone { static const byte_t testdata[] = {1,3,5,7,9}; mem_t *memsrc = NULL; mem_t *memdest = NULL; assert( memsrc = mem_create(sizeof(testdata)) ); memcpy(memsrc->buf, testdata, sizeof(testdata)); assert( memdest = mem_create_clone(memsrc) ); assert( memdest != memsrc ); assert( memdest->buf != memsrc->buf ); assert( 0 == memcmp(memdest->buf, memsrc->buf, memsrc->size) ); mem_release(memsrc); mem_release(memdest); } // Set zeros { static const byte_t zeros[] = "\x0\x0\x0\x0\x0\x0\x0\x0"; static const size_t size = sizeof(zeros); mem_t *mem = NULL; assert( mem = mem_create(size) ); memset(mem->buf, -1, size); mem_set_zeros(mem); assert( 0 == memcmp(mem->buf, zeros, size) ); mem_release(mem); } // Resize { static const byte_t testdata[] = "\x01\x02\x03\x04\x05\x06\x07\x08"; static const size_t testsize = sizeof(testdata); mem_t *mem = NULL; size_t newsize; assert( mem = mem_create(testsize) ); memcpy(mem->buf, testdata, testsize); newsize = testsize + testsize/2; assert( mem_resize(mem, newsize) ); assert( mem->size == newsize ); assert( 0 == memcmp(mem->buf, testdata, std::min(newsize,testsize)) ); newsize = testsize/2; assert( mem_resize(mem, newsize) ); assert( mem->size == newsize ); assert( 0 == memcmp(mem->buf, testdata, std::min(newsize,testsize)) ); mem_release(mem); } // Import { static const byte_t testdata[] = "\x01\x02\x03\x04\x05\x06\x07\x08"; mem_t *mem = NULL; assert( mem = mem_create(128) ); assert( mem_import(mem, testdata, sizeof(testdata)) ); assert( mem->size == sizeof(testdata) ); assert( 0 == memcmp(mem->buf, testdata, mem->size) ); mem_release(mem); } // Append { static const byte_t data_1 [] = "\x01\x02\x03\x04"; static const byte_t data_2 [] = "\x05\x06\x07\x08"; static const byte_t data_all[] = "\x01\x02\x03\x04\x00\x05\x06\x07\x08"; mem_t *mem = NULL; assert( mem = mem_create(0) ); assert( mem_import(mem, data_1, sizeof(data_1)) ); assert( mem_append(mem, data_2, sizeof(data_2)) ); assert( mem->size == sizeof(data_all) ); assert( 0 == memcmp(mem->buf, data_all, mem->size) ); mem_release(mem); } // Move { static const byte_t testdata[] = "\x01\x02\x03\x04\x05\x06\x07\x08"; mem_t *memsrc = NULL; mem_t *memdest = NULL; assert( memsrc = mem_create_import(testdata, sizeof(testdata)) ); assert( memdest = mem_create(0) ); mem_move_from(memdest, memsrc); assert( memdest->buf ); assert( memdest->size == sizeof(testdata) ); assert( 0 == memcmp(memdest->buf, testdata, sizeof(testdata)) ); assert( memsrc->buf ); assert( memsrc->size == 0 ); mem_release(memsrc); mem_release(memdest); } // Pop front { static const byte_t testdata[] = "\x01\x02\x03\x04\x05\x06\x07\x08"; static const size_t popsz = 4; mem_t *mem = NULL; assert( mem = mem_create(0) ); assert( mem_import(mem, testdata, sizeof(testdata)) ); mem_pop_front(mem, popsz); assert( mem->size = sizeof(testdata) - popsz ); assert( 0 == memcmp(mem->buf, testdata+popsz, sizeof(testdata)-popsz) ); mem_pop_front(mem, sizeof(testdata)); assert( mem->size == 0 ); mem_release_s(&mem); } // Binary file read and write { static const char filename[] = "memobj-binary-temp-file"; static const byte_t testdata[] = "mem_t load save test string."; mem_t *mem = NULL; // Save file assert( mem = mem_create(0) ); assert( mem_import(mem, testdata, sizeof(testdata)) ); assert( mem_save_file(mem, filename) ); memset(mem->buf, 0, mem->size_total); mem_release_s(&mem); // Load file assert( mem = mem_create(0) ); assert( mem_load_file(mem, filename) ); assert( mem->size == sizeof(testdata) ); assert( 0 == memcmp(mem->buf, testdata, mem->size) ); mem_release_s(&mem); // Create object and load file assert( mem = mem_create_load_file(filename) ); assert( mem->size == sizeof(testdata) ); assert( 0 == memcmp(mem->buf, testdata, mem->size) ); mem_release_s(&mem); // Remove the temporary file remove(filename); } // Text format file output { static const char filename[] = "memobj-text-temp-file"; static const byte_t testdata[] = { 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, }; mem_t *mem = NULL; assert( mem = mem_create_import(testdata, sizeof(testdata)) ); assert( mem_save_text(mem, filename) ); mem_release_s(&mem); printf("Test of the text information output : \n\n"); assert( mem = mem_create_load_file(filename) ); assert( mem_append(mem, "\x00", 1) ); // Add null terminator printf("%s\n", (char*)mem->buf); mem_release_s(&mem); remove(filename); } } void test_fixed_buffer_memory_object(void) { // Initialize { byte_t buffer[128]; memfx_t *mem; assert( mem = memfx_init(buffer, sizeof(buffer), sizeof(buffer)) ); assert( mem->size < sizeof(buffer) ); memfx_deinit(mem); assert( mem = memfx_init(buffer, sizeof(buffer), sizeof(buffer)/2) ); assert( mem->size == sizeof(buffer)/2 ); memfx_deinit(mem); assert( mem = memfx_init(buffer, sizeof(buffer), 0) ); assert( mem->size == 0 ); memfx_deinit(mem); assert( mem = memfx_init(buffer, sizeof(memfx_header_t)) ); assert( mem->size == 0 ); memfx_deinit(mem); assert( !( mem = memfx_init(buffer, sizeof(memfx_header_t)-1) ) ); } // Set zeros { static const byte_t zeros[] = "\x0\x0\x0\x0\x0\x0\x0\x0"; static const size_t size = sizeof(zeros); byte_t buffer[128]; memfx_t *mem = NULL; memset(buffer, -1, sizeof(buffer)); assert( mem = memfx_init(buffer, sizeof(buffer), sizeof(buffer)) ); memfx_set_zeros(mem); assert( 0 == memcmp(mem->buf, zeros, size) ); memfx_deinit(mem); } // Resize { static const byte_t testdata[] = "\x01\x02\x03\x04\x05\x06\x07\x08"; static const size_t testsize = sizeof(testdata); byte_t buffer[128]; memfx_t *mem = NULL; size_t newsize; assert( mem = memfx_init(buffer, sizeof(buffer), testsize) ); memcpy(mem->buf, testdata, testsize); newsize = testsize + testsize/2; assert( memfx_resize(mem, newsize) ); assert( mem->size == newsize ); assert( 0 == memcmp(mem->buf, testdata, std::min(newsize,testsize)) ); newsize = testsize/2; assert( memfx_resize(mem, newsize) ); assert( mem->size == newsize ); assert( 0 == memcmp(mem->buf, testdata, std::min(newsize,testsize)) ); assert( !memfx_resize(mem, sizeof(buffer)+1) ); memfx_deinit(mem); } // Import { static const byte_t testdata[] = "\x01\x02\x03\x04\x05\x06\x07\x08"; static const byte_t largedata[128+1] = {0}; byte_t buffer[128]; memfx_t *mem = NULL; assert( mem = memfx_init(buffer, sizeof(buffer), sizeof(buffer)) ); // Normal import assert( memfx_import(mem, testdata, sizeof(testdata)) ); assert( mem->size == sizeof(testdata) ); assert( 0 == memcmp(mem->buf, testdata, mem->size) ); // Import data that large then the object can hold assert( !memfx_import(mem, largedata, sizeof(largedata)) ); // - Check that the object has not be changed assert( mem->size == sizeof(testdata) ); assert( 0 == memcmp(mem->buf, testdata, mem->size) ); memfx_deinit(mem); } // Append { static const byte_t data_1 [] = "\x01\x02\x03\x04"; static const byte_t data_2 [] = "\x05\x06\x07\x08"; static const byte_t data_all[] = "\x01\x02\x03\x04\x00\x05\x06\x07\x08"; static const byte_t largedata[128-1] = {0}; byte_t buffer[128]; memfx_t *mem = NULL; assert( mem = memfx_init(buffer, sizeof(buffer)) ); // Normal append assert( memfx_import(mem, data_1, sizeof(data_1)) ); assert( memfx_append(mem, data_2, sizeof(data_2)) ); assert( mem->size == sizeof(data_all) ); assert( 0 == memcmp(mem->buf, data_all, mem->size) ); // Append data that large then the object can hold assert( !memfx_append(mem, largedata, sizeof(largedata)) ); // - Check that the object has not be changed assert( mem->size == sizeof(data_all) ); assert( 0 == memcmp(mem->buf, data_all, mem->size) ); memfx_deinit(mem); } // Pop front { static const byte_t testdata[] = "\x01\x02\x03\x04\x05\x06\x07\x08"; static const size_t popsz = 4; byte_t buffer[128]; memfx_t *mem = NULL; assert( mem = memfx_init(buffer, sizeof(buffer)) ); assert( memfx_import(mem, testdata, sizeof(testdata)) ); memfx_pop_front(mem, popsz); assert( mem->size = sizeof(testdata) - popsz ); assert( 0 == memcmp(mem->buf, testdata+popsz, sizeof(testdata)-popsz) ); memfx_pop_front(mem, sizeof(testdata)); assert( mem->size == 0 ); memfx_deinit(mem); } // Binary file read and write { static const char filename[] = "memobj-binary-temp-file"; static const byte_t testdata[] = "mem_t load save test string."; byte_t buffer[128]; memfx_t *mem = NULL; // Save file assert( mem = memfx_init(buffer, sizeof(buffer)) ); assert( memfx_import(mem, testdata, sizeof(testdata)) ); assert( memfx_save_file(mem, filename) ); memfx_deinit(mem); memset(buffer, 0, sizeof(buffer)); // Load file assert( mem = memfx_init(buffer, sizeof(buffer)) ); assert( memfx_load_file(mem, filename) ); assert( mem->size == sizeof(testdata) ); assert( 0 == memcmp(mem->buf, testdata, mem->size) ); memfx_deinit(mem); memset(buffer, 0, sizeof(buffer)); // Load with small buffer that cannot hold the data assert( mem = memfx_init(buffer, sizeof(testdata)-1) ); assert( !memfx_load_file(mem, filename) ); memfx_deinit(mem); memset(buffer, 0, sizeof(buffer)); // Remove the temporary file remove(filename); } // Text format file output { static const char filename[] = "memobj-text-temp-file"; static const byte_t testdata[] = { 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, }; byte_t buffer[128*4]; memfx_t *mem = NULL; assert( mem = memfx_init(buffer, sizeof(buffer)) ); assert( memfx_import(mem, testdata, sizeof(testdata)) ); assert( memfx_save_text(mem, filename) ); memfx_deinit(mem); printf("Test of the text information output : \n\n"); assert( mem = memfx_init(buffer, sizeof(buffer)) ); assert( memfx_load_file(mem, filename) ); assert( memfx_append(mem, "\x00", 1) ); // Add null terminator printf("%s\n", (char*)mem->buf); memfx_deinit(mem); remove(filename); } } int main(void) { test_global_tools(); test_memory_object(); test_fixed_buffer_memory_object(); return 0; }
[ "ice.emissary@gmail.com" ]
ice.emissary@gmail.com
3725e1d731485dbd09964d302526164b576c352b
79201adb23e3633bfe0d1274f9b006117eb04a6d
/Convert Sorted Array to Binary Search Tree.cpp
469e485e4bb893f5d9893ee0a765e2365e8ae147
[]
no_license
abhigrover101/leetcode
76a5438636c2841d4f9502221a556c03e946b692
1e827de8f039c08725ae8ef6708ba1bb03a302a9
refs/heads/master
2021-01-10T14:47:48.653116
2015-11-04T04:02:32
2015-11-04T04:02:32
45,512,476
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *convert(vector<int> &num,int start,int end) { if(start>end) return NULL; TreeNode *head=new TreeNode(num[(start+end)/2]); head->left=convert(num,start,(start+end)/2-1); head->right=convert(num,(start+end)/2+1,end); return head; } TreeNode *sortedArrayToBST(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function return convert(num,0,num.size()-1); } };
[ "abgrover@ucsc.edu" ]
abgrover@ucsc.edu
31e5123a7315ff361dc0d79eb4a203143fb7b2cd
9e59291f6401e2efce6de345dcf9510eaf9f56de
/mgen-cpplib/src/main/cpp/mgen/serialization/StringOutputStream.h
e48fecc0da5dca54e3f22944598ff19157fd13db
[ "MIT" ]
permissive
culvertsoft/mgen
8c3b70ef15cfe8ff3e8658e5da982854542dfc31
9f6d4f4a80235ccca73a16c7c92776a54c541a2f
refs/heads/master
2016-09-06T13:01:42.346872
2015-06-17T18:18:26
2015-06-17T18:18:26
20,562,279
7
1
null
null
null
null
UTF-8
C++
false
false
1,835
h
#ifndef MGEN_STRINGOUTPUTSTREAM_H_ #define MGEN_STRINGOUTPUTSTREAM_H_ #include <string> namespace mgen { /** * Represents an in-memory data output for MGen writers. A StringOutputStream * wraps a provided std::string without making a copy, or allocates its own string * (depending on choice of constructor). When data is written to this * StringOutputStream it is added to the underlying string. */ class StringOutputStream { public: /** * Wraps a provided string in this StringOutputStream. No copy is made, * so the caller is responsible for keeping the string alive for as long * as this StringOutputStream exists. */ StringOutputStream(std::string& output) : m_internalString(0), m_writeTarget(&output) { } /** * Creates a StringOutputStream around an internally allocated std::string. */ StringOutputStream() : m_writeTarget(&m_internalString) { } /** * Writes nBytes bytes to the underlying string. The bytes are pushed back * at the end of the underlying string. */ void write(const void* src, const int nBytes) { str().insert( str().end(), reinterpret_cast<const char*>(src), reinterpret_cast<const char*>(src) + nBytes); } /** * Clears the underlying wrapped string (std::string::clear()) */ void reset() { str().clear(); } /** * Gets the underlying string */ std::string& str() { return *m_writeTarget; } private: std::string m_internalString; std::string * m_writeTarget; StringOutputStream(const StringOutputStream&); StringOutputStream& operator=(const StringOutputStream&); }; } /* namespace mgen */ #endif /* MGEN_STRINGOUTPUTSTREAM_H_ */
[ "kjolhede@telia.com" ]
kjolhede@telia.com
bfa65e053c9b6cbcd2b53e18a8479b0bb9eeabb5
486daa9b1945e65f59db8877fae2eca52844b0ef
/model/src/ActionImpl.h
630578bdcb8be73edf8307c456ce4452e385a194
[ "Apache-2.0" ]
permissive
mballance-sf/open-ps
2a20d146d3d4c00a6d709f3a45efaed5c0678eb4
a5ed44ce30bfe59462801ca7de4361d16950bcd2
refs/heads/master
2020-03-17T04:05:02.416863
2018-06-01T02:17:07
2018-06-01T02:17:07
133,262,113
0
0
null
null
null
null
UTF-8
C++
false
false
1,613
h
/* * ActionImpl.h * * Copyright 2016 Mentor Graphics Corporation * All Rights Reserved Worldwide * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in * compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in * writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing * permissions and limitations under the License. * * Created on: Apr 26, 2016 * Author: ballance */ #pragma once #include <string> #include "BaseItemImpl.h" #include "NamedItemImpl.h" #include "ScopeItemImpl.h" #include "IAction.h" #include "IField.h" #include "IItemFactory.h" class ActionImpl: public virtual IAction, public virtual BaseItemImpl, public virtual NamedItemImpl, public virtual ScopeItemImpl { public: ActionImpl( const std::string &name, IBaseItem *super_type); virtual ~ActionImpl(); virtual IBaseItem *getSuperType() const { return m_super_type; } virtual IActivityStmt *getActivity() const { return m_graph; } virtual void setActivity(IActivityStmt *activity); virtual void setParent(IBaseItem *it); virtual IBaseItem *clone() const; private: IBaseItem *m_super_type; IActivityStmt *m_graph; IField *m_comp; };
[ "matt.ballance@gmail.com" ]
matt.ballance@gmail.com
63cebf1790aeeaf015176467de2353153967c310
760474b6b3c7db3a06d09ad1816df09009ebfcb2
/lib/PCA9685.cpp
24b131f3e00e78de794708bb405c24c22b0018a6
[]
no_license
jedichen121/PCA9685-Driver
432bf3fd2fcd9d33834e99ece400f949bf676b96
90d3eb51a207ed50d5f5fe60ce08d43a55ca632d
refs/heads/master
2020-08-06T22:27:43.774401
2019-10-07T13:15:36
2019-10-07T13:15:36
213,181,684
0
0
null
null
null
null
UTF-8
C++
false
false
5,276
cpp
/* * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Name : PCA9685.cpp * Original Author : Georgi Todorov * Edited by : Tord Wessman * Version : * Created on : Dec 9, 2012 * * Copyright © 2012 Georgi Todorov <terahz@geodar.com> */ #include <sys/stat.h> #include <sys/ioctl.h> #include <unistd.h> #include <linux/i2c-dev.h> #include <stdio.h> /* Standard I/O functions */ #include <fcntl.h> #include <syslog.h> /* Syslog functionallity */ #include <inttypes.h> #include <errno.h> #include <math.h> #include <stdio.h> #include <unistd.h> // #include "PCA9685.h" //! Constructor takes bus and address arguments /*! \param bus the bus to use in /dev/i2c-%d. \param address the device address on bus */ void PCA9685::init(int bus, int address) { _i2cbus = bus; _i2caddr = address; snprintf(busfile, sizeof(busfile), "/dev/i2c-%d", bus); puts(busfile); reset(); usleep(10*1000); } PCA9685::PCA9685() { } PCA9685::~PCA9685() { reset(); } //! Sets PCA9685 mode to 00 void PCA9685::reset() { int fd = openfd(); if (fd != -1) { write_byte(fd, MODE1, 0x80); //Normal mode // write_byte(fd, MODE2, 0x04); //Normal mode close(fd); } } //! Set the frequency of PWM /*! \param freq desired frequency. 40Hz to 1000Hz using internal 25MHz oscillator. */ void PCA9685::setPWMFreq(int freq) { int fd = openfd(); if (fd != -1) { uint8_t prescale = (CLOCK_FREQ / 4096 / freq) - 1; //printf ("Setting prescale value to: %d\n", prescale); //printf ("Using Frequency: %d\n", freq); uint8_t oldmode = read_byte(fd, MODE1); uint8_t newmode = (oldmode & 0x7F) | 0x10; //sleep write_byte(fd, MODE1, newmode); // go to sleep write_byte(fd, PRE_SCALE, prescale); write_byte(fd, MODE1, oldmode); usleep(10*1000); write_byte(fd, MODE1, oldmode | 0x80); close(fd); } } //! PWM a single channel /*! \param led channel to set PWM value for \param value 0-4095 value for PWM */ void PCA9685::setPWM(uint8_t led, int value) { setPWM(led, 0, value); } //! PWM a single channel with custom on time /*! \param led channel to set PWM value for \param on_value 0-4095 value to turn on the pulse \param off_value 0-4095 value to turn off the pulse */ void PCA9685::setPWM(uint8_t led, int on_value, int off_value) { int fd = openfd(); if (fd != -1) { write_byte(fd, LED0_ON_L + LED_MULTIPLYER * led, on_value & 0xFF); write_byte(fd, LED0_ON_H + LED_MULTIPLYER * led, on_value >> 8); write_byte(fd, LED0_OFF_L + LED_MULTIPLYER * led, off_value & 0xFF); write_byte(fd, LED0_OFF_H + LED_MULTIPLYER * led, off_value >> 8); close(fd); } } //! Read a single byte from PCA9685 /*! \param fd file descriptor for I/O \param address register address to read from */ uint8_t PCA9685::read_byte(int fd, uint8_t address) { return 0; uint8_t buff[BUFFER_SIZE]; buff[0] = address; if (write(fd, buff, BUFFER_SIZE) != BUFFER_SIZE) { printf("I2C slave 0x%x failed to go to register 0x%x [read_byte():write %d]", _i2caddr, address, errno); return (-1); } else { if (read(fd, dataBuffer, BUFFER_SIZE) != BUFFER_SIZE) { printf ("Could not read from I2C slave 0x%x, register 0x%x [read_byte():read %d]", _i2caddr, address, errno); return (-1); } } } //! Write a single byte from PCA9685 /*! \param fd file descriptor for I/O \param address register address to write to \param data 8 bit data to write */ void PCA9685::write_byte(int fd, uint8_t address, uint8_t data) { uint8_t buff[2]; buff[0] = address; buff[1] = data; if (write(fd, buff, sizeof(buff)) != 2) { printf("Failed to write to I2C Slave 0x%x @ register 0x%x [write_byte():write %d]", _i2caddr, address, errno); usleep(5000); }else{ //printf("Wrote to I2C Slave 0x%x @ register 0x%x [0x%x]\n", _i2caddr, address, data); } } //! Open device file for PCA9685 I2C bus /*! \return fd returns the file descriptor number or -1 on error */ int PCA9685::openfd() { int fd; if ((fd = open(busfile, O_RDWR)) < 0) { printf ("Couldn't open I2C Bus %d [openfd():open %d]", _i2cbus, errno); return -1; } if (ioctl(fd, I2C_SLAVE, _i2caddr) < 0) { printf ("I2C slave %d failed [openfd():ioctl %d]", _i2caddr, errno); return -1; } return fd; }
[ "jiyang.chen@weride.ai" ]
jiyang.chen@weride.ai
13b6c59cece58983a738489d9b8ef7cde4d910d1
e5b5ee7ee4a5abb77e2438223a5b02cdb7e07b38
/29.2_code_snippet.cpp
178721f382c7af2b012c69c84e66beea0fca8f8c
[]
no_license
sgchoi5/algorithm
2333c11d4d22bc5a9729a07730866cbd18f650a3
a7778a998eca145182ab3469f950dd3a846e0e24
refs/heads/master
2021-01-09T05:48:10.685073
2019-04-09T13:46:45
2019-04-09T13:46:45
80,838,658
0
0
null
null
null
null
UTF-8
C++
false
false
1,338
cpp
// 코드 29.2 차단 경로를 계산하는 너비 우선 탐색 // start에서 시작해 그래프를 너비 우선 탐색하고 시작점부터 각 정점까지의 // 최단 거리와 너비 우선 탐색 스패닝 트리를 계산한다 // distance[i] = start부터 i까지의 최단 거리 // parent[i] = 너비 우선 탐색 스패닝 트리에서 i의 부모의 번호, 루트인 경우 자신의 번호 void bfs2(int start, vector<int>& distance, vector<int>& parent) { distance = vector<int>(adj.size(), -1); parent = vector<int>(adj.size(), -1); // 방문할 정점 목록을 유지하는 큐 queue<int> q; distance[start] = 0; parent[start] = start; q.push(start); while (!q.empty()) { int here = q.front(); q.pop(); // here의 모든 인접한 정점을 검사한다 for (int i = 0; i < adj[here].size(); ++i) { int there = adj[here][i]; // 처음 보는 정점이면 방문 목록에 집어넣는다 if (distance[there] == -1) { q.push(there); distance[there] = distance[here] + 1; parent[there] = here; } } } } // v로부터 시작점까지의 최단 경로를 계산한다 vector<int> shortestPath(int v, const vector<int>& parent) { vector<int> path(1, v); while (parent[v] != v) { v = parent[v]; path.push_back(v); } reverse(path.begin(), path.end()); return path; }
[ "noreply@github.com" ]
noreply@github.com
cc2491a5c3dd570149004daaee595d2903d187d8
83d302f3687e2546f27fae8e56b7eae265bb1a1a
/src/Plate.cpp
980c54bc0f5a25470568ac3c606ce9efa01b485a
[]
no_license
mafraba/ANPR
7743860ce6e5da06a050108109cca1e55bc08992
96c678f1ba61ef9b521362d8b3466a3b8f608562
refs/heads/master
2021-01-19T03:23:35.199788
2014-07-20T19:26:51
2014-07-20T19:26:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
641
cpp
/* * Plate.cpp * * Created on: 21/01/2011 * Author: SEMDFF */ #include <cv.h> #include "Plate.h" namespace anpr { Plate::~Plate() { if (cloned) data.release(); } Plate::Plate(Mat input, int x0, int y0, int x1, int y1, bool clone) : data(input), top(y0), bottom(y1), left(x0), right(x1), cloned(clone) { if (clone) { data = input.clone(); } } Mat Plate::getData() { return data; } Size Plate::getSize() { return Size(right - left, bottom - top); } int Plate::getRight() { return right; } int Plate::getTop() { return top; } int Plate::getBottom() { return bottom; } int Plate::getLeft() { return left; } }
[ "mafraba@gmail.com" ]
mafraba@gmail.com
37377acf00bb15d4bdffc78a414ef8f19b0b04e9
0a3a009fa93539a2b45b5642341f4cb0c5c62df5
/Axis.Capsicum/services/memory/commands/MemoryCommand.cpp
ac1e407bdbcabf6d5612830eee9b2921f384647a
[ "MIT" ]
permissive
renato-yuzup/axis-fem
5bdb610457013d78a9f62496d4a0ba5e68a5a966
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
refs/heads/master
2020-04-28T19:54:21.273024
2019-03-31T22:04:22
2019-03-31T22:04:22
175,526,004
4
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
#include "MemoryCommand.hpp" namespace asmc = axis::services::memory::commands; asmc::MemoryCommand::MemoryCommand(void) { // nothing to do here } asmc::MemoryCommand::~MemoryCommand(void) { // nothing to do here }
[ "renato@yuzu-project.com" ]
renato@yuzu-project.com
da77349e6a6b19898703ea7907eb84746d6c4a4e
b2d51d7fcf45f2570a48ebc39f4a61d2b4259594
/include/pearl/RmaGetEnd_rep.h
ad798c193ccf531afc543b6e93fa6bc837606b71
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
AishwaryaDoosa/scalasca-2.5
6429e8265585e14ef89e1ff96c151c9004179bc9
25067c279eed0280b219b41b3617fa6ae4151263
refs/heads/master
2022-04-17T17:34:45.531794
2020-04-19T19:56:29
2020-04-19T19:56:29
257,089,613
0
0
null
null
null
null
UTF-8
C++
false
false
2,745
h
/**************************************************************************** ** SCALASCA http://www.scalasca.org/ ** ***************************************************************************** ** Copyright (c) 1998-2013 ** ** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre ** ** ** ** Copyright (c) 2009-2013 ** ** German Research School for Simulation Sciences GmbH, ** ** Laboratory for Parallel Programming ** ** ** ** This software may be modified and distributed under the terms of ** ** a BSD-style license. See the COPYING file in the package base ** ** directory for details. ** ****************************************************************************/ #ifndef PEARL_RMAGETEND_REP_H #define PEARL_RMAGETEND_REP_H #include <pearl/Event_rep.h> /*-------------------------------------------------------------------------*/ /** * @file RmaGetEnd_rep.h * @ingroup PEARL_base * @brief Declaration of the class RmaGetEnd_rep. * * This header file provides the declaration of the class RmaGetEnd_rep. **/ /*-------------------------------------------------------------------------*/ namespace pearl { /*-------------------------------------------------------------------------*/ /** * @internal * * @class RmaGetEnd_rep * @ingroup PEARL_base * @brief %Event representation for RMA_GET_END events. **/ /*-------------------------------------------------------------------------*/ class PEARL_NOPAD_ATTR RmaGetEnd_rep : public Event_rep { public: /// @name Constructors & destructor /// @{ RmaGetEnd_rep(timestamp_t timestamp, uint32_t rma_id); RmaGetEnd_rep(const GlobalDefs& defs, Buffer& buffer); /// @} /// @name Event type information /// @{ virtual event_t getType() const; virtual bool isOfType(event_t type) const; /// @} /// @name Access event data /// @{ virtual uint32_t get_rma_id() const; /// @} protected: /// @name Serialize event data /// @{ virtual void pack(Buffer& buffer) const; /// @} /// @name Generate human-readable output of event data /// @{ virtual std::ostream& output(std::ostream& stream) const; /// @} private: /// RMA ID uint32_t m_rma_id; }; } // namespace pearl #endif // !PEARL_RMAGETEND_REP_H
[ "aiswaryadoosa@gmail.com" ]
aiswaryadoosa@gmail.com
0fab5f24b47f5071e9c54672b1e0d51bca1be5fc
4eb58b82b857edde83e8ed99dc10f59e8ea2c71f
/00908/00908.cpp
cbdaa19d53894d3bb8e84a5a6007ff0f4f2e8e39
[]
no_license
RezaMokaram/Solutions-to-UVAonlinejudge-problems
18be6d1d7ca302c233e077546d7ad4bffa9f1448
e4117ed247ff3f707cd71e84df662835affb1077
refs/heads/master
2023-06-11T06:47:05.602555
2023-06-03T01:59:10
2023-06-03T01:59:10
248,146,437
0
0
null
null
null
null
UTF-8
C++
false
false
1,685
cpp
//#include <bits/stdc++.h> #include <iostream> #include <fstream> #include <string> #include <cstdio> #include <cstring> #include <cmath> #include <stdio.h> #include <vector> #include <iomanip> #include <queue> #include <algorithm> #include <set> #include <stack> #include <functional> #include <map> #include <set> // using namespace std; typedef long long int ll; typedef long long unsigned int llu; const ll MAX = 100000; typedef pair<ll, pair<int, int>> nod; nod ndc(int a, int b, ll val) { nod t; t.first = val; t.second.second = b; t.second.first = a; return t; } typedef pair<int, int> no; // const int zero = 1010; bool ui(nod a, nod b) { return (b.first > a.first); } vector<int>pr; int getp(int n) { return pr[n] == n ? n : getp(pr[n]); } int main() { int n,cs=0; bool f = 0; while (cin >> n) { if (f)cout << endl; f = 1; pr.clear(); for (size_t i = 0; i < n+1; i++) pr.push_back(i); vector<nod>list(n - 1); ll sum = 0; for (size_t i = 0; i < n-1; i++) { int s, e; ll val; cin >> s >> e >> val; list[i] = ndc(s, e, val); sum += val; } int A; cin >> A; for (size_t i = 0; i < A; i++) { int s, e; ll val; cin >> s >> e >> val; list.push_back(ndc(s, e, val)); } cin >> A; for (size_t i = 0; i < A; i++) { int s, e; ll val; cin >> s >> e >> val; list.push_back(ndc(s, e, val)); } sort(list.begin(), list.end(), ui); ll mst = 0; for (size_t i = 0; i < list.size(); i++) { if (getp(list[i].second.first)!=getp(list[i].second.second)) { mst += list[i].first; pr[getp(list[i].second.first)] = getp(list[i].second.second); } } cout << sum << endl << mst << endl; } }
[ "noreply@github.com" ]
noreply@github.com
b2f9cacd5ead426024e3bc9cfe292901524d32fd
11525b5baa183425c555212d96fa8d03f10544b4
/src/demo/premiere/procedures.h
1c7a5f3c6a77a13f4050a128df1ea02ab95bd05d
[]
no_license
heusunduo/gamemachine
4f9e19f7900b43b75061db7295130d967dd9ef82
a3b1082519c8526855ec862af3378e46de335f93
refs/heads/master
2023-03-17T23:17:04.231411
2020-10-14T02:28:06
2020-10-14T02:28:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,161
h
#ifndef __PROCEDURES_H__ #define __PROCEDURES_H__ #include <gamemachine.h> #include <gm2dgameobject.h> #include <gmanimation.h> #include "timeline.h" using namespace gm; class Handler; class Procedures; struct ProceduresPrivate { ProceduresPrivate(Procedures& p); void finalize(); void showLogo(GMDuration dt); void loadingScene(GMDuration dt); void play(GMDuration dt); void invokeInMainThread(std::function<void()>); void callMainThreadFunctions(); void async(GMFuture<void>&& asyncFuture); private: Procedures& m_procedures; GMTextGameObject* m_title; Stack<std::function<void()>> m_funcQueue; List<GMFuture<void>> m_managedFutures; GMAnimation m_titleAnimation; Timeline m_timeline; bool m_assetsLoaded; bool m_timelineStarted; }; class Procedures { friend struct ProceduresPrivate; public: // Procedures enum { ShowLogo = 0, LoadingScene, Play, }; public: Procedures(Handler* handler); public: void run(GMDuration dt); void update(GMDuration dt); void finalize(); private: Handler* m_handler; ProceduresPrivate m_p; GMint32 m_procedure; }; #endif
[ "hellofroser@hotmail.com" ]
hellofroser@hotmail.com
c8159b658fde59b7f6a0c651e0897f170006829a
e49aeb5d0602bc9ee9c83565b8b0cc6cb1ac76cd
/B50/KNOW32/Include/Action.h
53f28effbff44b994937633bd8fd2b73ede55dc0
[]
no_license
genanr2/Artificial-Intelligence
c237b50e80c8b7c2d40bc8f25f6547996e73714c
818c18a89d9471c0482b463a531446ba766093e9
refs/heads/master
2022-01-20T12:41:13.137038
2021-12-27T18:57:42
2021-12-27T18:57:42
137,275,524
0
0
null
null
null
null
UTF-8
C++
false
false
2,954
h
// Action.h: interface for the Action class. ////////////////////////////////////////////////////////////////////// #if !defined(AFX_ACTION_H__C504D8A6_D6CB_11D2_862A_00A024384FCF__INCLUDED_) #define AFX_ACTION_H__C504D8A6_D6CB_11D2_862A_00A024384FCF__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef _INC_CTYPE #include <CTYPE.H> #endif #ifndef _STRING_ #include "string" #endif using namespace std; #include "NxpAtom.h" typedef CTypedPtrMap<CMapWordToOb,DWORD,Action*>CMapDWordToAction; typedef CTypedPtrArray<CObArray, Action*>ActionsList; // ListOfRhsActions typedef CTypedPtrArray<CObArray, CAssignAssignment*>AssignAssignmentList; // ListOfRhsActions typedef CTypedPtrArray<CObArray, CResetAssignment*>CResetAssignmentList; // ListOfRhsActions //CAssignAssignment*assignAssignment; class AFX_EXT_CLASS Action : public NxpAtom { public: Action(); virtual~Action() { // assignAssignmentLst = new AssignAssignmentList; // resetAssignmentLst = new CResetAssignmentList; } Action(const Action&c) { secondStr=c.secondStr; aType=c.aType; thirdStr=c.thirdStr; atomType=c.atomType; assignAssignmentLst = new AssignAssignmentList; resetAssignmentLst = new CResetAssignmentList; } void operator=(const Action&c) { secondStr=c.secondStr; aType=c.aType; thirdStr=c.thirdStr; atomType=c.atomType; assignAssignmentLst = new AssignAssignmentList; resetAssignmentLst = new CResetAssignmentList; } void operator=(const Action*c) { secondStr=c->secondStr; aType=c->aType; thirdStr=c->thirdStr; atomType=c->atomType; assignAssignmentLst = new AssignAssignmentList; resetAssignmentLst = new CResetAssignmentList; } bool operator==(const Action&c)const{return this==&c;} bool operator==(const Action*c)const{return this==c;} // enum actionType { AssignmentTypeActs, DynamicType, InterfaceTypeActs }; actionType aType; _NxAtomTypeEnum atomType; int actValue; CString*secondStr; CString*thirdStr; virtual void printOn(std::ostream&ofStream)const; union { // LhsAssignments*assignments; CMapDWordToLhsAssignment*assignments; CMapDWordToInterfaceAction*interfaceActions; // CMapDWordToDynObjectsAction*dynActions; CDynObjectsAction*dynActions; CMapDWordToInheritanceControl*inheritanceControls; CMapDWordToLhsTest*tests; }gen; CAssignAssignment*assignAssignment; AssignAssignmentList*assignAssignmentLst; CResetAssignmentList*resetAssignmentLst; void SetAssingments(RhsAssignments*rhsA); void SetDynObjectsActions(DynObjectsActions*rhsDA); void SetInterfaceActions(InterfaceActions*rhsDA); void SetInheritanceControls(InheritanceControls*rhsA); // InterfaceActions*rhsA = ac->gen.interfaceActions; virtual void Serialize(CArchive&ar); #ifdef _DEBUG void AssertValid()const; // virtual void Dump(CDumpContext&dc)const; #endif protected: DECLARE_SERIAL(Action) }; #endif // !defined(AFX_ACTION_H__C504D8A6_D6CB_11D2_862A_00A024384FCF__INCLUDED_)
[ "genanr@mail.ru" ]
genanr@mail.ru
8ef239f1e2e24e441afe773652d401a691e13127
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/content/common/child_process.mojom-shared.cc
fce6573d2d559e70c6e008977a128440e13f3499
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
19,617
cc
// content/common/child_process.mojom-shared.cc is auto generated by mojom_bindings_generator.py, do not edit // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4065) #endif #include "content/common/child_process.mojom-shared.h" #include <utility> #include "base/logging.h" #include "base/stl_util.h" // for base::size() #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/bindings/lib/validation_util.h" #include "content/common/child_process.mojom-params-data.h" namespace content { namespace mojom { namespace internal { // static bool ChildProcessHost_BindHostReceiver_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ChildProcessHost_BindHostReceiver_Params_Data* object = static_cast<const ChildProcessHost_BindHostReceiver_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 16 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!mojo::internal::ValidatePointerNonNullable( object->receiver, 1, validation_context)) { return false; } if (!mojo::internal::ValidateStruct(object->receiver, validation_context)) return false; return true; } ChildProcessHost_BindHostReceiver_Params_Data::ChildProcessHost_BindHostReceiver_Params_Data() : header_({sizeof(*this), 0}) {} // static bool ChildProcessHostBootstrap_BindProcessHost_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ChildProcessHostBootstrap_BindProcessHost_Params_Data* object = static_cast<const ChildProcessHostBootstrap_BindProcessHost_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 16 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->receiver, 1, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->receiver, validation_context)) { return false; } return true; } ChildProcessHostBootstrap_BindProcessHost_Params_Data::ChildProcessHostBootstrap_BindProcessHost_Params_Data() : header_({sizeof(*this), 0}) {} // static bool ChildProcess_Initialize_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ChildProcess_Initialize_Params_Data* object = static_cast<const ChildProcess_Initialize_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 16 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->boostrap, 1, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->boostrap, validation_context)) { return false; } return true; } ChildProcess_Initialize_Params_Data::ChildProcess_Initialize_Params_Data() : header_({sizeof(*this), 0}) {} // static bool ChildProcess_ProcessShutdown_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ChildProcess_ProcessShutdown_Params_Data* object = static_cast<const ChildProcess_ProcessShutdown_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 8 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } return true; } ChildProcess_ProcessShutdown_Params_Data::ChildProcess_ProcessShutdown_Params_Data() : header_({sizeof(*this), 0}) {} // static bool ChildProcess_GetBackgroundTracingAgentProvider_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ChildProcess_GetBackgroundTracingAgentProvider_Params_Data* object = static_cast<const ChildProcess_GetBackgroundTracingAgentProvider_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 16 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->receiver, 1, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->receiver, validation_context)) { return false; } return true; } ChildProcess_GetBackgroundTracingAgentProvider_Params_Data::ChildProcess_GetBackgroundTracingAgentProvider_Params_Data() : header_({sizeof(*this), 0}) {} // static bool ChildProcess_CrashHungProcess_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ChildProcess_CrashHungProcess_Params_Data* object = static_cast<const ChildProcess_CrashHungProcess_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 8 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } return true; } ChildProcess_CrashHungProcess_Params_Data::ChildProcess_CrashHungProcess_Params_Data() : header_({sizeof(*this), 0}) {} // static bool ChildProcess_BootstrapLegacyIpc_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ChildProcess_BootstrapLegacyIpc_Params_Data* object = static_cast<const ChildProcess_BootstrapLegacyIpc_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 16 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->receiver, 1, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->receiver, validation_context)) { return false; } return true; } ChildProcess_BootstrapLegacyIpc_Params_Data::ChildProcess_BootstrapLegacyIpc_Params_Data() : header_({sizeof(*this), 0}) {} // static bool ChildProcess_RunService_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ChildProcess_RunService_Params_Data* object = static_cast<const ChildProcess_RunService_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 24 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!mojo::internal::ValidatePointerNonNullable( object->service_name, 1, validation_context)) { return false; } const mojo::internal::ContainerValidateParams service_name_validate_params( 0, false, nullptr); if (!mojo::internal::ValidateContainer(object->service_name, validation_context, &service_name_validate_params)) { return false; } if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->receiver, 2, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->receiver, validation_context)) { return false; } return true; } ChildProcess_RunService_Params_Data::ChildProcess_RunService_Params_Data() : header_({sizeof(*this), 0}) {} // static bool ChildProcess_BindServiceInterface_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ChildProcess_BindServiceInterface_Params_Data* object = static_cast<const ChildProcess_BindServiceInterface_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 16 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!mojo::internal::ValidatePointerNonNullable( object->receiver, 1, validation_context)) { return false; } if (!mojo::internal::ValidateStruct(object->receiver, validation_context)) return false; return true; } ChildProcess_BindServiceInterface_Params_Data::ChildProcess_BindServiceInterface_Params_Data() : header_({sizeof(*this), 0}) {} // static bool ChildProcess_BindReceiver_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const ChildProcess_BindReceiver_Params_Data* object = static_cast<const ChildProcess_BindReceiver_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 16 }}; if (object->header_.version <= kVersionSizes[base::size(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!mojo::internal::ValidatePointerNonNullable( object->receiver, 1, validation_context)) { return false; } if (!mojo::internal::ValidateStruct(object->receiver, validation_context)) return false; return true; } ChildProcess_BindReceiver_Params_Data::ChildProcess_BindReceiver_Params_Data() : header_({sizeof(*this), 0}) {} } // namespace internal } // namespace mojom } // namespace content #if defined(_MSC_VER) #pragma warning(pop) #endif
[ "xueqi@zjmedia.net" ]
xueqi@zjmedia.net
e71a78450bcd7cf808d3f7dc7779f698afa4c3fc
496d2f4e71950269e9aba98f56c62f5c4fc52a99
/patching_arry.cpp
fc4f839c200326d43d582282815be75930318fcf
[]
no_license
XBOOS/leetcode-solutions
044ddad93f116cd71e11df34120392e06b5cf50b
cd1f1138e85ed69f3ae87b0bd49a1f6b6f343527
refs/heads/master
2020-12-28T20:53:54.408330
2017-01-06T06:04:03
2017-01-06T06:04:03
44,537,161
0
0
null
null
null
null
UTF-8
C++
false
false
3,673
cpp
/* *Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required. Example 1: nums = [1, 3], n = 6 Return 1. Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. Example 2: nums = [1, 5, 10], n = 20 Return 2. The two patches can be [2, 4]. Example 3: nums = [1, 2, 2], n = 5 Return 0. * */ /* Very good explaination. From bravejia! * The question asked for the "minimum number of patches required". In other words, it asked for an optimal solution. Lots of problems involving optimal solution can be solved by dynamic programming and/or greedy algorithm. I started with greedy algorithm which is conceptually easy to design. Typically, a greedy algorithm needs selection of best moves for a subproblem. So what is our best move? * * Think about this example: nums = [1, 2, 3, 9]. We naturally want to iterate through nums from left to right and see what we would discover. After we encountered 1, we know 1...1 is patched completely. After encountered 2, we know 1...3 (1+2) is patched completely. After we encountered 3, we know 1...6 (1+2+3) is patched completely. After we encountered 9, the smallest number we can get is 9. So we must patch a new number here so that we don't miss 7, 8. To have 7, the numbers we can patch is 1, 2, 3 ... 7. Any number greater than 7 won't help here. Patching 8 will not help you get 7. So we have 7 numbers (1...7) to choose from. I hope you can see number 7 works best here because if we chose number 7, we can move all the way up to 1+2+3+7 = 13. (1...13 is patched completely) and it makes us reach n as quickly as possible. After we patched 7 and reach 13, we can consider last element 9 in nums. Having 9 makes us reach 13+9 = 22, which means 1...22 is completely patched. If we still did't reach n, we can then patch 23, which makes 1...45 (22+23) completely patched. We continue until we reach n. * */ /* Be careful to use long for maxCover otherwise it will overflow.I used int at the baginging it will execeeds 2147483647*/ class Solution { public: int minPatches(vector<int>& nums, int n) { int leng = nums.size(); long maxCover = 0; int idxInclude = 0; int res = 0; while(maxCover<n){ if(idxInclude>=leng){ maxCover = maxCover*2+1; res++;//to patch maxCover+1 } else if(nums[idxInclude]==(maxCover+1)){ maxCover = maxCover*2+1; idxInclude++; }else if(nums[idxInclude]>(maxCover+1)){ maxCover = maxCover*2+1; res++;//to patch maxCover+1 }else{ maxCover = maxCover+nums[idxInclude++]; } } return res; } }; /*Some modification to combine the same effect conditions*/ class Solution { public: int minPatches(vector<int>& nums, int n) { int leng = nums.size(); long maxCover = 0; int idxInclude = 0; int res = 0; while(maxCover<n){ if(idxInclude>=leng||nums[idxInclude]>(maxCover+1)){ maxCover = maxCover*2+1; res++;//to patch maxCover+1 }else{ maxCover = maxCover+nums[idxInclude++]; } } return res; } };
[ "xubinghku@gmail.com" ]
xubinghku@gmail.com
8235748c520a8e948fffec29922289c91e083909
de8d2d2695af50079be88bf2832aef734f10060e
/GPA4/FaceCube.h
d70876518e5dd31bd6d97c602b3f0a71b2586273
[]
no_license
gbudiman/gpa4grp1
c984f1a2bd7037c405c647270ac77999d03a56d0
08641f01520ea9fbb01444780e62ee818d332ab0
refs/heads/master
2021-01-25T05:16:25.721799
2010-12-05T19:24:11
2010-12-05T19:24:11
32,118,257
0
0
null
null
null
null
UTF-8
C++
false
false
619
h
/* * File: FaceCube.h * Author: Wan Kuk * * Created on December 1, 2010, 9:49 PM */ #ifndef FACECUBE_H #define FACECUBE_H #include <string> #include "Definition.h" #include "Tools.h" #include "CubieCube.h" using namespace std; class FaceCube { public: FaceCube(); FaceCube(string cubeString); string to_String(); CubieCube toCubieCube(); static FaceCube toFaceCube(CubieCube &cube); Color f[54]; static Facelet cornerFacelet[8][3]; static Facelet edgeFacelet[12][2]; static Color cornerColor[8][3]; static Color edgeColor[12][2]; private: }; #endif /* FACECUBE_H */
[ "ryrhodes89@abf12c61-3e4e-1e1d-b3fc-2f84d3efec81" ]
ryrhodes89@abf12c61-3e4e-1e1d-b3fc-2f84d3efec81
df42843278763905ae149923de04a49b96d9bd1d
8795c9a13cf38a1b064203033d0b81ea9c23c2bb
/src/host/nfcemu/NfcEmuUsbDevice.cpp
2d5ad3d4215c49e79501f2be35feb225304a9fa7
[]
no_license
0xee/NfcEmu
85dddedc31cb5d62a4b70debd34cfee446465a08
000554863342b73f8b3e7a2736eda5704af38a90
refs/heads/master
2021-01-23T11:09:10.478584
2014-12-05T17:48:10
2014-12-05T17:48:10
23,524,769
15
5
null
null
null
null
UTF-8
C++
false
false
3,642
cpp
/** * @file UsbStreamDevice.c * @author Lukas Schuller * @date Fri Aug 23 13:10:52 2013 * * @brief * */ #include "NfcEmuUsbDevice.h" #include <iostream> #include "NfcConstants.h" #include "Exception.h" #include "IntelHexFile.h" #include "NfcEmuPacket.h" #include <unistd.h> #include "Debug.h" #include <thread> #include <chrono> using namespace boost::asio; using namespace std; namespace NfcEmu { UsbDevice::UsbDevice(boost::asio::io_service & io, std::string const & fx2FwFile) : Device(io), fx2(io), mCanContinue(true) { Open(fx2FwFile); mReadBuf.resize(512); } bool UsbDevice::CheckFx2Fw() { if(!fx2.IsConnected()) return false; try { unsigned char c = FX2_POLL_FW; fx2.BulkWrite(1, const_buffer(&c, sizeof(c)), 100); return (fx2.BulkRead(0x81, buffer(&c, sizeof(c)), 10) == 1) && (c == FX2_FW_OK); } catch(Usb::Error e) { Error(string(e.code().message()) + " " + e.what()); return false; } } bool UsbDevice::Open(std::string const & fx2FwFile) { int ret; if(!fx2.IsConnected()) { return false; } if(CheckFx2Fw()) { Info("Found FX2 with valid bridge firmware"); } else { Warning("FX2 not responding, updating firmware"); try { fx2.DownloadFirmware(fx2FwFile); if(!CheckFx2Fw()) { Fatal("FX2 still not responding"); } } catch (runtime_error & e) { Fatal("Error downloading firmware to FX2"); throw(runtime_error("communication error")); } } return ResetFpga(); } bool UsbDevice::ResetFpga() { unsigned char buf[1<<12]; buf[0] = FX2_RESET_FPGA; fx2.BulkWrite(0x01, const_buffer(buf, 1)); size_t leftOver = 0; size_t ret; do { ret = Read(buffer(buf)); leftOver += ret; usleep(10000); } while(ret); if(leftOver) cout << ":: Read " << leftOver << " leftover bytes from fpga" << endl; ret = fx2.BulkRead(0x81, buffer(buf, 1), 10); //cout << "reset: read: " << ret << endl; return (ret == 1) && (buf[0] == FX2_FPGA_RESET_ACK); } bool UsbDevice::IsOpen() const { return fx2.IsConnected(); } bool UsbDevice::Close() { return ResetFpga(); } size_t UsbDevice::Read(boost::asio::mutable_buffer buf) { size_t maxLen = boost::asio::buffer_size(buf); int const epIn = 0x86; int ret = 0; int rec = 0; do { ret = fx2.BulkRead(epIn, buf+rec, 10); // cout << "read: ret = " << ret << endl; rec += ret; } while(ret > 0 && rec < maxLen); // cout << "read return" << endl; return rec; } void UsbDevice::Write(boost::asio::const_buffer buf) { int const epOut = 0x02; size_t const maxPacketSize = 32; auto p = boost::asio::buffer_cast<unsigned char const*>(buf); auto p2 = p + boost::asio::buffer_size(buf); while(p < p2) { //D("Sending: " + std::to_string(size_t(p2-p)));//+ Util::FormatHex(p, p2)); size_t nTx = std::min(size_t(p2-p), maxPacketSize); fx2.BulkWrite(epOut, boost::asio::buffer(p, nTx)); p += nTx; } } }
[ "lukas@schuller.uk.to" ]
lukas@schuller.uk.to
63bd3f735590c025293812c2441adbb4685b6d28
bad16e02969e473e06d7a2748bd5bb3245e1973a
/Arrays/main.cpp
4058019640732e929152ba5011a1d2694e36abbd
[]
no_license
moveactive/CppFund
b308d16b45140a2f3636f0f4ec0f091b4c832d0b
2d7e443a5e2db255ab8c181008279a6d3ee2cd1e
refs/heads/master
2023-04-01T10:48:14.467912
2021-04-11T07:45:29
2021-04-11T07:45:29
356,800,223
0
0
null
null
null
null
UTF-8
C++
false
false
1,239
cpp
#include <iostream> #include <cmath> #include <array> const int CAPACITY{100}; std::array<int, CAPACITY> readInput(int & arrLenght); int findMinDistanceBetweenTwoNumbers(std::array<int, CAPACITY> & myArray, int & arrLenght); int main(int argc, char const *argv[]) { int arrLenght{0}; std::array<int, CAPACITY> myArray = readInput(arrLenght); std::cout << findMinDistanceBetweenTwoNumbers(myArray, arrLenght) << std::endl; return 0; } std::array<int, CAPACITY> readInput(int & arrLenght) { std::cin >> arrLenght; std::array<int, CAPACITY> myArray; for(int i = 0; i < arrLenght; ++i) { std::cin >> myArray[i]; } return myArray; } int findMinDistanceBetweenTwoNumbers(std::array<int, CAPACITY> & myArray, int & arrLenght) { int currentDistance{0}; int minDistance{INT32_MAX}; for(int i = 0; i < arrLenght; ++i) { for(int j = i; j < arrLenght; ++j) { if(i == j) { continue; } currentDistance = abs((myArray[i] - myArray[j])); if(currentDistance <= minDistance) { minDistance = currentDistance; } } } return minDistance; }
[ "boyanddreev@gmail.com" ]
boyanddreev@gmail.com
4e90013f6017dd8dc986167b2821340876851b14
e5a2eed530086b4b3772886f1daad8ed6d6b5152
/projects/savefile/src/pse-savefile/expanded/world/worldevents.cpp
8943f9e01818a2c8039ca3167dd7c49aacdf4865
[ "Apache-2.0" ]
permissive
junebug12851/pokered-save-editor-2
f7cf5013652737ef24f0c7a400c6520e4df5f54b
af883fd4c12097d408e1756c7181709cf2b797d8
refs/heads/master
2020-06-06T09:17:16.194569
2020-03-18T09:45:34
2020-03-18T09:45:34
192,697,866
0
0
null
null
null
null
UTF-8
C++
false
false
2,131
cpp
/* * Copyright 2020 June Hanabi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QRandomGenerator> #include <string.h> #include "./worldevents.h" #include "../../savefile.h" #include "../../savefiletoolset.h" #include "../../savefileiterator.h" #include <pse-db/eventsdb.h> WorldEvents::WorldEvents(SaveFile* saveFile) { load(saveFile); } WorldEvents::~WorldEvents() {} int WorldEvents::eventsCount() { return eventCount; } bool WorldEvents::eventsAt(int ind) { return completedEvents[ind]; } void WorldEvents::eventsSet(int ind, bool val) { completedEvents[ind] = val; completedEventsChanged(); } void WorldEvents::load(SaveFile* saveFile) { reset(); if(saveFile == nullptr) return; auto toolset = saveFile->toolset; for(var16 i = 0; i < EventsDB::store.size(); i++) { auto event = EventsDB::store.at(i); completedEvents[i] = toolset->getBit(event->byte, 1, event->bit); } completedEventsChanged(); } void WorldEvents::save(SaveFile* saveFile) { auto toolset = saveFile->toolset; for(var16 i = 0; i < EventsDB::store.size(); i++) { auto event = EventsDB::store.at(i); toolset->setBit(event->byte, 1, event->bit, completedEvents[i]); } } void WorldEvents::reset() { memset(completedEvents, 0, eventCount); completedEventsChanged(); } // Competed world events is too complicated to make happen randomly right now // Furthermore we do want the player to still play the game fully when // randomized void WorldEvents::randomize() { reset(); }
[ "junehanabi@gmail.com" ]
junehanabi@gmail.com
820e0e1d6d747b0802d38ca34f969852b2918e08
f8e87d106e49d4ebf97a81548359aaaa124193ca
/lab_11/ex1_Pair/Main.cpp
55cc64ba39c506310f9fec6b2dbac0927d010665
[]
no_license
NewShon/ItStep_Cpp
fed3d46fee2e4fe752e05c45dda2a36f51275b3c
b811171f1c28c45c3aad7ba6c33a3fb782131674
refs/heads/master
2021-01-22T08:02:20.921257
2017-07-20T13:50:02
2017-07-20T13:50:02
92,597,989
0
1
null
null
null
null
UTF-8
C++
false
false
519
cpp
#include <iostream> #include "Pair.h" int main() { Pair<int, int> p(3, 4); std::cout << p.getFirst() << std::endl; std::cout << p.getSecond() << std::endl; p.make_pair(5, 6); std::cout << p.getFirst() << std::endl; std::cout << p.getSecond() << std::endl; Pair<bool, bool> p2(true); std::cout << p2.getFirst() << std::endl; std::cout << p2.getSecond() << std::endl; p2.make_pair(false); std::cout << p2.getFirst() << std::endl; std::cout << p2.getSecond() << std::endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
7ae67396dabb4f5e8d9ad4791a97007536f79265
532e3c14b0388ace10ab46a230c4d3481199eedb
/members codes/Ahmed Talaat/sketch_apr07a.ino
d0d9b45f5999364d7b36857f6e75bc8623536cbc
[]
no_license
EL-SHREIF/ASUMobiCarG66
206c4d472474f99f9016a28e434fa5ab33227858
8ca56861236aecbae12c9f7dc4ec437a866f7eaf
refs/heads/master
2020-04-02T07:45:09.866113
2018-10-22T20:33:44
2018-10-22T20:33:44
126,717,418
0
0
null
2018-03-25T16:34:07
2018-03-25T16:34:06
null
UTF-8
C++
false
false
3,178
ino
// Right Side Motors int enA = 9,in1=8,in2=7; // Left Side Motors int enB = 3,in3=5,in4=4; //reading data for the 3 sensors //zero for black and 1 for white int data1,data2,data3;//data1 for center, data2 for right,data3 for left int r1=10,r2=11,r3=12;// r1 for center,r2 for right, r3 for left; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(enA , OUTPUT); pinMode(in1 , OUTPUT); pinMode(in2 , OUTPUT); pinMode(enB , OUTPUT); pinMode(in3 , OUTPUT); pinMode(in4 , OUTPUT); pinMode(r1,INPUT); pinMode(r2,INPUT); pinMode(r3,INPUT); } void loop() { data1 =digitalRead(r1); data2 =digitalRead(r2); data3 =digitalRead(r3); Serial.print("data1 = "); Serial.println(data1); Serial.print("data2 = "); Serial.println(data2); Serial.print("data3 = "); Serial.println(data3); if(data1==HIGH&&data2==HIGH&&data3==HIGH)//the three sensors see white {//stop } else if(data1==LOW&&data2==HIGH&&data3==HIGH)//the middle sees black while the others white { //FORWARD digitalWrite(in1,HIGH); digitalWrite(in2,LOW); analogWrite(enA,60); digitalWrite(in3,HIGH); digitalWrite(in4,LOW); analogWrite(enB,60); } else if(data1==LOW&&data2==HIGH&&data3==LOW)//the middle and left see black while the right sees others white { //FORWARD LEFT digitalWrite(in1,HIGH); digitalWrite(in2,LOW); analogWrite(enA,60); digitalWrite(in3,LOW); digitalWrite(in4,LOW); analogWrite(enB,0); } else if(data1==LOW&&data2==LOW&&data3==HIGH)//the middle and right see black while the left sees white { // FORWARD RIGHT digitalWrite(in1,LOW); digitalWrite(in2,LOW); analogWrite(enA,0); digitalWrite(in3,HIGH); digitalWrite(in4,LOW); analogWrite(enB,60); } else if(data1==HIGH&&data2==HIGH&&data3==LOW)//the middle and right see white while the left sees black { //FORWARD LEFT digitalWrite(in1,HIGH); digitalWrite(in2,LOW); analogWrite(enA,60); digitalWrite(in3,LOW); digitalWrite(in4,LOW); analogWrite(enB,0); } else if(data1==HIGH&&data2==LOW&&data3==HIGH)//the middle and left see white while the right sees black { // FORWARD RIGHT digitalWrite(in1,LOW); digitalWrite(in2,LOW); analogWrite(enA,0); digitalWrite(in3,HIGH); digitalWrite(in4,LOW); analogWrite(enB,60); } /* //REVERSE digitalWrite(in1,LOW); digitalWrite(in2,HIGH); analogWrite(enA,250); digitalWrite(in3,LOW); digitalWrite(in4,HIGH); analogWrite(enB,250); //BACKWARD LEFT digitalWrite(in1,LOW); digitalWrite(in2,HIGH); analogWrite(enA,250); digitalWrite(in3,LOW); digitalWrite(in4,LOW); analogWrite(enB,0); //BACKWARD RIGHT digitalWrite(in1,LOW); digitalWrite(in2,LOW); analogWrite(enA,0); digitalWrite(in3,LOW); digitalWrite(in4,HIGH); analogWrite(enB,250);*/ }
[ "36492402+EL-SHREIF@users.noreply.github.com" ]
36492402+EL-SHREIF@users.noreply.github.com
bab3bdeb9a97adb22900964d725eed57cedcd75e
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_1/MP+dmb.sy+data-wsi-rfi-ctrl-rfi.c.cbmc_out.cpp
228e2feaa534b73f237503f88f7322d7acbd3b93
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
46,385
cpp
// 0:vars:3 // 3:atom_1_X0_1:1 // 4:atom_1_X5_2:1 // 5:atom_1_X8_1:1 // 6:thr0:1 // 7:thr1:1 #define ADDRSIZE 8 #define NPROC 3 #define NCONTEXT 1 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NPROC*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NPROC*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NPROC*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NPROC*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NPROC*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NPROC*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NPROC*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NPROC*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NPROC*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NPROC]; int cdy[NPROC]; int cds[NPROC]; int cdl[NPROC]; int cisb[NPROC]; int caddr[NPROC]; int cctrl[NPROC]; int cstart[NPROC]; int creturn[NPROC]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; int r0= 0; char creg_r0; int r1= 0; char creg_r1; int r2= 0; char creg_r2; int r3= 0; char creg_r3; int r4= 0; char creg_r4; int r5= 0; char creg_r5; int r6= 0; char creg_r6; int r7= 0; char creg_r7; int r8= 0; char creg_r8; int r9= 0; char creg_r9; int r10= 0; char creg_r10; int r11= 0; char creg_r11; int r12= 0; char creg_r12; int r13= 0; char creg_r13; int r14= 0; char creg_r14; int r15= 0; char creg_r15; int r16= 0; char creg_r16; int r17= 0; char creg_r17; int r18= 0; char creg_r18; int r19= 0; char creg_r19; char old_cctrl= 0; char old_cr= 0; char old_cdy= 0; char old_cw= 0; char new_creg= 0; buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; buff(0,6) = 0; pw(0,6) = 0; cr(0,6) = 0; iw(0,6) = 0; cw(0,6) = 0; cx(0,6) = 0; is(0,6) = 0; cs(0,6) = 0; crmax(0,6) = 0; buff(0,7) = 0; pw(0,7) = 0; cr(0,7) = 0; iw(0,7) = 0; cw(0,7) = 0; cx(0,7) = 0; is(0,7) = 0; cs(0,7) = 0; crmax(0,7) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; buff(1,6) = 0; pw(1,6) = 0; cr(1,6) = 0; iw(1,6) = 0; cw(1,6) = 0; cx(1,6) = 0; is(1,6) = 0; cs(1,6) = 0; crmax(1,6) = 0; buff(1,7) = 0; pw(1,7) = 0; cr(1,7) = 0; iw(1,7) = 0; cw(1,7) = 0; cx(1,7) = 0; is(1,7) = 0; cs(1,7) = 0; crmax(1,7) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; buff(2,6) = 0; pw(2,6) = 0; cr(2,6) = 0; iw(2,6) = 0; cw(2,6) = 0; cx(2,6) = 0; is(2,6) = 0; cs(2,6) = 0; crmax(2,6) = 0; buff(2,7) = 0; pw(2,7) = 0; cr(2,7) = 0; iw(2,7) = 0; cw(2,7) = 0; cx(2,7) = 0; is(2,7) = 0; cs(2,7) = 0; crmax(2,7) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(3+0,0) = 0; mem(4+0,0) = 0; mem(5+0,0) = 0; mem(6+0,0) = 0; mem(7+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; co(1,0) = 0; delta(1,0) = -1; co(2,0) = 0; delta(2,0) = -1; co(3,0) = 0; delta(3,0) = -1; co(4,0) = 0; delta(4,0) = -1; co(5,0) = 0; delta(5,0) = -1; co(6,0) = 0; delta(6,0) = -1; co(7,0) = 0; delta(7,0) = -1; // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !37, metadata !DIExpression()), !dbg !46 // br label %label_1, !dbg !47 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !45), !dbg !48 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !38, metadata !DIExpression()), !dbg !49 // call void @llvm.dbg.value(metadata i64 2, metadata !41, metadata !DIExpression()), !dbg !49 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !50 // ST: Guess iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 2; mem(0,cw(1,0)) = 2; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; ASSUME(creturn[1] >= cw(1,0)); // call void (...) @dmbsy(), !dbg !51 // dumbsy: Guess old_cdy = cdy[1]; cdy[1] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[1] >= old_cdy); ASSUME(cdy[1] >= cisb[1]); ASSUME(cdy[1] >= cdl[1]); ASSUME(cdy[1] >= cds[1]); ASSUME(cdy[1] >= cctrl[1]); ASSUME(cdy[1] >= cw(1,0+0)); ASSUME(cdy[1] >= cw(1,0+1)); ASSUME(cdy[1] >= cw(1,0+2)); ASSUME(cdy[1] >= cw(1,3+0)); ASSUME(cdy[1] >= cw(1,4+0)); ASSUME(cdy[1] >= cw(1,5+0)); ASSUME(cdy[1] >= cw(1,6+0)); ASSUME(cdy[1] >= cw(1,7+0)); ASSUME(cdy[1] >= cr(1,0+0)); ASSUME(cdy[1] >= cr(1,0+1)); ASSUME(cdy[1] >= cr(1,0+2)); ASSUME(cdy[1] >= cr(1,3+0)); ASSUME(cdy[1] >= cr(1,4+0)); ASSUME(cdy[1] >= cr(1,5+0)); ASSUME(cdy[1] >= cr(1,6+0)); ASSUME(cdy[1] >= cr(1,7+0)); ASSUME(creturn[1] >= cdy[1]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !42, metadata !DIExpression()), !dbg !52 // call void @llvm.dbg.value(metadata i64 1, metadata !44, metadata !DIExpression()), !dbg !52 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !53 // ST: Guess iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; ASSUME(creturn[1] >= cw(1,0+1*1)); // ret i8* null, !dbg !54 ret_thread_1 = (- 1); // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !57, metadata !DIExpression()), !dbg !96 // br label %label_2, !dbg !78 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !94), !dbg !98 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !60, metadata !DIExpression()), !dbg !99 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !81 // LD: Guess old_cr = cr(2,0+1*1); cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+1*1)] == 2); ASSUME(cr(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cr(2,0+1*1) >= 0); ASSUME(cr(2,0+1*1) >= cdy[2]); ASSUME(cr(2,0+1*1) >= cisb[2]); ASSUME(cr(2,0+1*1) >= cdl[2]); ASSUME(cr(2,0+1*1) >= cl[2]); // Update creg_r0 = cr(2,0+1*1); crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+1*1) < cw(2,0+1*1)) { r0 = buff(2,0+1*1); } else { if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) { ASSUME(cr(2,0+1*1) >= old_cr); } pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1)); r0 = mem(0+1*1,cr(2,0+1*1)); } ASSUME(creturn[2] >= cr(2,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !62, metadata !DIExpression()), !dbg !99 // %conv = trunc i64 %0 to i32, !dbg !82 // call void @llvm.dbg.value(metadata i32 %conv, metadata !58, metadata !DIExpression()), !dbg !96 // %xor = xor i32 %conv, %conv, !dbg !83 creg_r1 = max(creg_r0,creg_r0); ASSUME(active[creg_r1] == 2); r1 = r0 ^ r0; // call void @llvm.dbg.value(metadata i32 %xor, metadata !63, metadata !DIExpression()), !dbg !96 // %add = add nsw i32 %xor, 1, !dbg !84 creg_r2 = max(creg_r1,0); ASSUME(active[creg_r2] == 2); r2 = r1 + 1; // call void @llvm.dbg.value(metadata i32 %add, metadata !64, metadata !DIExpression()), !dbg !96 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !65, metadata !DIExpression()), !dbg !104 // %conv1 = sext i32 %add to i64, !dbg !86 // call void @llvm.dbg.value(metadata i64 %conv1, metadata !67, metadata !DIExpression()), !dbg !104 // store atomic i64 %conv1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !86 // ST: Guess iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,0+2*1); cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,0+2*1)] == 2); ASSUME(active[cw(2,0+2*1)] == 2); ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0); ASSUME(iw(2,0+2*1) >= creg_r2); ASSUME(iw(2,0+2*1) >= 0); ASSUME(cw(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cw(2,0+2*1) >= old_cw); ASSUME(cw(2,0+2*1) >= cr(2,0+2*1)); ASSUME(cw(2,0+2*1) >= cl[2]); ASSUME(cw(2,0+2*1) >= cisb[2]); ASSUME(cw(2,0+2*1) >= cdy[2]); ASSUME(cw(2,0+2*1) >= cdl[2]); ASSUME(cw(2,0+2*1) >= cds[2]); ASSUME(cw(2,0+2*1) >= cctrl[2]); ASSUME(cw(2,0+2*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+2*1) = r2; mem(0+2*1,cw(2,0+2*1)) = r2; co(0+2*1,cw(2,0+2*1))+=1; delta(0+2*1,cw(2,0+2*1)) = -1; ASSUME(creturn[2] >= cw(2,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !68, metadata !DIExpression()), !dbg !106 // call void @llvm.dbg.value(metadata i64 2, metadata !70, metadata !DIExpression()), !dbg !106 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !88 // ST: Guess iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,0+2*1); cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,0+2*1)] == 2); ASSUME(active[cw(2,0+2*1)] == 2); ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(cw(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cw(2,0+2*1) >= old_cw); ASSUME(cw(2,0+2*1) >= cr(2,0+2*1)); ASSUME(cw(2,0+2*1) >= cl[2]); ASSUME(cw(2,0+2*1) >= cisb[2]); ASSUME(cw(2,0+2*1) >= cdy[2]); ASSUME(cw(2,0+2*1) >= cdl[2]); ASSUME(cw(2,0+2*1) >= cds[2]); ASSUME(cw(2,0+2*1) >= cctrl[2]); ASSUME(cw(2,0+2*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+2*1) = 2; mem(0+2*1,cw(2,0+2*1)) = 2; co(0+2*1,cw(2,0+2*1))+=1; delta(0+2*1,cw(2,0+2*1)) = -1; ASSUME(creturn[2] >= cw(2,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !72, metadata !DIExpression()), !dbg !108 // %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !90 // LD: Guess old_cr = cr(2,0+2*1); cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+2*1)] == 2); ASSUME(cr(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cr(2,0+2*1) >= 0); ASSUME(cr(2,0+2*1) >= cdy[2]); ASSUME(cr(2,0+2*1) >= cisb[2]); ASSUME(cr(2,0+2*1) >= cdl[2]); ASSUME(cr(2,0+2*1) >= cl[2]); // Update creg_r3 = cr(2,0+2*1); crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+2*1) < cw(2,0+2*1)) { r3 = buff(2,0+2*1); } else { if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) { ASSUME(cr(2,0+2*1) >= old_cr); } pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1)); r3 = mem(0+2*1,cr(2,0+2*1)); } ASSUME(creturn[2] >= cr(2,0+2*1)); // call void @llvm.dbg.value(metadata i64 %1, metadata !74, metadata !DIExpression()), !dbg !108 // %conv7 = trunc i64 %1 to i32, !dbg !91 // call void @llvm.dbg.value(metadata i32 %conv7, metadata !71, metadata !DIExpression()), !dbg !96 // %tobool = icmp ne i32 %conv7, 0, !dbg !92 // br i1 %tobool, label %if.then, label %if.else, !dbg !94 old_cctrl = cctrl[2]; cctrl[2] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[2] >= old_cctrl); ASSUME(cctrl[2] >= creg_r3); ASSUME(cctrl[2] >= 0); if((r3!=0)) { goto T2BLOCK2; } else { goto T2BLOCK3; } T2BLOCK2: // br label %lbl_LC00, !dbg !95 goto T2BLOCK4; T2BLOCK3: // br label %lbl_LC00, !dbg !96 goto T2BLOCK4; T2BLOCK4: // call void @llvm.dbg.label(metadata !95), !dbg !116 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !75, metadata !DIExpression()), !dbg !117 // call void @llvm.dbg.value(metadata i64 1, metadata !77, metadata !DIExpression()), !dbg !117 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !99 // ST: Guess iw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,0); cw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,0)] == 2); ASSUME(active[cw(2,0)] == 2); ASSUME(sforbid(0,cw(2,0))== 0); ASSUME(iw(2,0) >= 0); ASSUME(iw(2,0) >= 0); ASSUME(cw(2,0) >= iw(2,0)); ASSUME(cw(2,0) >= old_cw); ASSUME(cw(2,0) >= cr(2,0)); ASSUME(cw(2,0) >= cl[2]); ASSUME(cw(2,0) >= cisb[2]); ASSUME(cw(2,0) >= cdy[2]); ASSUME(cw(2,0) >= cdl[2]); ASSUME(cw(2,0) >= cds[2]); ASSUME(cw(2,0) >= cctrl[2]); ASSUME(cw(2,0) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0) = 1; mem(0,cw(2,0)) = 1; co(0,cw(2,0))+=1; delta(0,cw(2,0)) = -1; ASSUME(creturn[2] >= cw(2,0)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !79, metadata !DIExpression()), !dbg !119 // %2 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !101 // LD: Guess old_cr = cr(2,0); cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0)] == 2); ASSUME(cr(2,0) >= iw(2,0)); ASSUME(cr(2,0) >= 0); ASSUME(cr(2,0) >= cdy[2]); ASSUME(cr(2,0) >= cisb[2]); ASSUME(cr(2,0) >= cdl[2]); ASSUME(cr(2,0) >= cl[2]); // Update creg_r4 = cr(2,0); crmax(2,0) = max(crmax(2,0),cr(2,0)); caddr[2] = max(caddr[2],0); if(cr(2,0) < cw(2,0)) { r4 = buff(2,0); } else { if(pw(2,0) != co(0,cr(2,0))) { ASSUME(cr(2,0) >= old_cr); } pw(2,0) = co(0,cr(2,0)); r4 = mem(0,cr(2,0)); } ASSUME(creturn[2] >= cr(2,0)); // call void @llvm.dbg.value(metadata i64 %2, metadata !81, metadata !DIExpression()), !dbg !119 // %conv13 = trunc i64 %2 to i32, !dbg !102 // call void @llvm.dbg.value(metadata i32 %conv13, metadata !78, metadata !DIExpression()), !dbg !96 // %cmp = icmp eq i32 %conv, 1, !dbg !103 // %conv14 = zext i1 %cmp to i32, !dbg !103 // call void @llvm.dbg.value(metadata i32 %conv14, metadata !82, metadata !DIExpression()), !dbg !96 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !83, metadata !DIExpression()), !dbg !123 // %3 = zext i32 %conv14 to i64 // call void @llvm.dbg.value(metadata i64 %3, metadata !85, metadata !DIExpression()), !dbg !123 // store atomic i64 %3, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !105 // ST: Guess iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,3); cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,3)] == 2); ASSUME(active[cw(2,3)] == 2); ASSUME(sforbid(3,cw(2,3))== 0); ASSUME(iw(2,3) >= max(creg_r0,0)); ASSUME(iw(2,3) >= 0); ASSUME(cw(2,3) >= iw(2,3)); ASSUME(cw(2,3) >= old_cw); ASSUME(cw(2,3) >= cr(2,3)); ASSUME(cw(2,3) >= cl[2]); ASSUME(cw(2,3) >= cisb[2]); ASSUME(cw(2,3) >= cdy[2]); ASSUME(cw(2,3) >= cdl[2]); ASSUME(cw(2,3) >= cds[2]); ASSUME(cw(2,3) >= cctrl[2]); ASSUME(cw(2,3) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,3) = (r0==1); mem(3,cw(2,3)) = (r0==1); co(3,cw(2,3))+=1; delta(3,cw(2,3)) = -1; ASSUME(creturn[2] >= cw(2,3)); // %cmp18 = icmp eq i32 %conv7, 2, !dbg !106 // %conv19 = zext i1 %cmp18 to i32, !dbg !106 // call void @llvm.dbg.value(metadata i32 %conv19, metadata !86, metadata !DIExpression()), !dbg !96 // call void @llvm.dbg.value(metadata i64* @atom_1_X5_2, metadata !87, metadata !DIExpression()), !dbg !126 // %4 = zext i32 %conv19 to i64 // call void @llvm.dbg.value(metadata i64 %4, metadata !89, metadata !DIExpression()), !dbg !126 // store atomic i64 %4, i64* @atom_1_X5_2 seq_cst, align 8, !dbg !108 // ST: Guess iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,4); cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,4)] == 2); ASSUME(active[cw(2,4)] == 2); ASSUME(sforbid(4,cw(2,4))== 0); ASSUME(iw(2,4) >= max(creg_r3,0)); ASSUME(iw(2,4) >= 0); ASSUME(cw(2,4) >= iw(2,4)); ASSUME(cw(2,4) >= old_cw); ASSUME(cw(2,4) >= cr(2,4)); ASSUME(cw(2,4) >= cl[2]); ASSUME(cw(2,4) >= cisb[2]); ASSUME(cw(2,4) >= cdy[2]); ASSUME(cw(2,4) >= cdl[2]); ASSUME(cw(2,4) >= cds[2]); ASSUME(cw(2,4) >= cctrl[2]); ASSUME(cw(2,4) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,4) = (r3==2); mem(4,cw(2,4)) = (r3==2); co(4,cw(2,4))+=1; delta(4,cw(2,4)) = -1; ASSUME(creturn[2] >= cw(2,4)); // %cmp23 = icmp eq i32 %conv13, 1, !dbg !109 // %conv24 = zext i1 %cmp23 to i32, !dbg !109 // call void @llvm.dbg.value(metadata i32 %conv24, metadata !90, metadata !DIExpression()), !dbg !96 // call void @llvm.dbg.value(metadata i64* @atom_1_X8_1, metadata !91, metadata !DIExpression()), !dbg !129 // %5 = zext i32 %conv24 to i64 // call void @llvm.dbg.value(metadata i64 %5, metadata !93, metadata !DIExpression()), !dbg !129 // store atomic i64 %5, i64* @atom_1_X8_1 seq_cst, align 8, !dbg !111 // ST: Guess iw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,5); cw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,5)] == 2); ASSUME(active[cw(2,5)] == 2); ASSUME(sforbid(5,cw(2,5))== 0); ASSUME(iw(2,5) >= max(creg_r4,0)); ASSUME(iw(2,5) >= 0); ASSUME(cw(2,5) >= iw(2,5)); ASSUME(cw(2,5) >= old_cw); ASSUME(cw(2,5) >= cr(2,5)); ASSUME(cw(2,5) >= cl[2]); ASSUME(cw(2,5) >= cisb[2]); ASSUME(cw(2,5) >= cdy[2]); ASSUME(cw(2,5) >= cdl[2]); ASSUME(cw(2,5) >= cds[2]); ASSUME(cw(2,5) >= cctrl[2]); ASSUME(cw(2,5) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,5) = (r4==1); mem(5,cw(2,5)) = (r4==1); co(5,cw(2,5))+=1; delta(5,cw(2,5)) = -1; ASSUME(creturn[2] >= cw(2,5)); // ret i8* null, !dbg !112 ret_thread_2 = (- 1); // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !139, metadata !DIExpression()), !dbg !196 // call void @llvm.dbg.value(metadata i8** %argv, metadata !140, metadata !DIExpression()), !dbg !196 // %0 = bitcast i64* %thr0 to i8*, !dbg !100 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !100 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !141, metadata !DIExpression()), !dbg !198 // %1 = bitcast i64* %thr1 to i8*, !dbg !102 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !102 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !145, metadata !DIExpression()), !dbg !200 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !146, metadata !DIExpression()), !dbg !201 // call void @llvm.dbg.value(metadata i64 0, metadata !148, metadata !DIExpression()), !dbg !201 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !105 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !149, metadata !DIExpression()), !dbg !203 // call void @llvm.dbg.value(metadata i64 0, metadata !151, metadata !DIExpression()), !dbg !203 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !107 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !152, metadata !DIExpression()), !dbg !205 // call void @llvm.dbg.value(metadata i64 0, metadata !154, metadata !DIExpression()), !dbg !205 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !109 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !155, metadata !DIExpression()), !dbg !207 // call void @llvm.dbg.value(metadata i64 0, metadata !157, metadata !DIExpression()), !dbg !207 // store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !111 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // call void @llvm.dbg.value(metadata i64* @atom_1_X5_2, metadata !158, metadata !DIExpression()), !dbg !209 // call void @llvm.dbg.value(metadata i64 0, metadata !160, metadata !DIExpression()), !dbg !209 // store atomic i64 0, i64* @atom_1_X5_2 monotonic, align 8, !dbg !113 // ST: Guess iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,4); cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,4)] == 0); ASSUME(active[cw(0,4)] == 0); ASSUME(sforbid(4,cw(0,4))== 0); ASSUME(iw(0,4) >= 0); ASSUME(iw(0,4) >= 0); ASSUME(cw(0,4) >= iw(0,4)); ASSUME(cw(0,4) >= old_cw); ASSUME(cw(0,4) >= cr(0,4)); ASSUME(cw(0,4) >= cl[0]); ASSUME(cw(0,4) >= cisb[0]); ASSUME(cw(0,4) >= cdy[0]); ASSUME(cw(0,4) >= cdl[0]); ASSUME(cw(0,4) >= cds[0]); ASSUME(cw(0,4) >= cctrl[0]); ASSUME(cw(0,4) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,4) = 0; mem(4,cw(0,4)) = 0; co(4,cw(0,4))+=1; delta(4,cw(0,4)) = -1; ASSUME(creturn[0] >= cw(0,4)); // call void @llvm.dbg.value(metadata i64* @atom_1_X8_1, metadata !161, metadata !DIExpression()), !dbg !211 // call void @llvm.dbg.value(metadata i64 0, metadata !163, metadata !DIExpression()), !dbg !211 // store atomic i64 0, i64* @atom_1_X8_1 monotonic, align 8, !dbg !115 // ST: Guess iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,5); cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,5)] == 0); ASSUME(active[cw(0,5)] == 0); ASSUME(sforbid(5,cw(0,5))== 0); ASSUME(iw(0,5) >= 0); ASSUME(iw(0,5) >= 0); ASSUME(cw(0,5) >= iw(0,5)); ASSUME(cw(0,5) >= old_cw); ASSUME(cw(0,5) >= cr(0,5)); ASSUME(cw(0,5) >= cl[0]); ASSUME(cw(0,5) >= cisb[0]); ASSUME(cw(0,5) >= cdy[0]); ASSUME(cw(0,5) >= cdl[0]); ASSUME(cw(0,5) >= cds[0]); ASSUME(cw(0,5) >= cctrl[0]); ASSUME(cw(0,5) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,5) = 0; mem(5,cw(0,5)) = 0; co(5,cw(0,5))+=1; delta(5,cw(0,5)) = -1; ASSUME(creturn[0] >= cw(0,5)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !116 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call11 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !117 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %2 = load i64, i64* %thr0, align 8, !dbg !118, !tbaa !119 // LD: Guess old_cr = cr(0,6); cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,6)] == 0); ASSUME(cr(0,6) >= iw(0,6)); ASSUME(cr(0,6) >= 0); ASSUME(cr(0,6) >= cdy[0]); ASSUME(cr(0,6) >= cisb[0]); ASSUME(cr(0,6) >= cdl[0]); ASSUME(cr(0,6) >= cl[0]); // Update creg_r6 = cr(0,6); crmax(0,6) = max(crmax(0,6),cr(0,6)); caddr[0] = max(caddr[0],0); if(cr(0,6) < cw(0,6)) { r6 = buff(0,6); } else { if(pw(0,6) != co(6,cr(0,6))) { ASSUME(cr(0,6) >= old_cr); } pw(0,6) = co(6,cr(0,6)); r6 = mem(6,cr(0,6)); } ASSUME(creturn[0] >= cr(0,6)); // %call12 = call i32 @pthread_join(i64 noundef %2, i8** noundef null), !dbg !123 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %3 = load i64, i64* %thr1, align 8, !dbg !124, !tbaa !119 // LD: Guess old_cr = cr(0,7); cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,7)] == 0); ASSUME(cr(0,7) >= iw(0,7)); ASSUME(cr(0,7) >= 0); ASSUME(cr(0,7) >= cdy[0]); ASSUME(cr(0,7) >= cisb[0]); ASSUME(cr(0,7) >= cdl[0]); ASSUME(cr(0,7) >= cl[0]); // Update creg_r7 = cr(0,7); crmax(0,7) = max(crmax(0,7),cr(0,7)); caddr[0] = max(caddr[0],0); if(cr(0,7) < cw(0,7)) { r7 = buff(0,7); } else { if(pw(0,7) != co(7,cr(0,7))) { ASSUME(cr(0,7) >= old_cr); } pw(0,7) = co(7,cr(0,7)); r7 = mem(7,cr(0,7)); } ASSUME(creturn[0] >= cr(0,7)); // %call13 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !125 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !165, metadata !DIExpression()), !dbg !223 // %4 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !127 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r8 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r8 = buff(0,0); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r8 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %4, metadata !167, metadata !DIExpression()), !dbg !223 // %conv = trunc i64 %4 to i32, !dbg !128 // call void @llvm.dbg.value(metadata i32 %conv, metadata !164, metadata !DIExpression()), !dbg !196 // %cmp = icmp eq i32 %conv, 2, !dbg !129 // %conv14 = zext i1 %cmp to i32, !dbg !129 // call void @llvm.dbg.value(metadata i32 %conv14, metadata !168, metadata !DIExpression()), !dbg !196 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !170, metadata !DIExpression()), !dbg !227 // %5 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) seq_cst, align 8, !dbg !131 // LD: Guess old_cr = cr(0,0+1*1); cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0+1*1)] == 0); ASSUME(cr(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cr(0,0+1*1) >= 0); ASSUME(cr(0,0+1*1) >= cdy[0]); ASSUME(cr(0,0+1*1) >= cisb[0]); ASSUME(cr(0,0+1*1) >= cdl[0]); ASSUME(cr(0,0+1*1) >= cl[0]); // Update creg_r9 = cr(0,0+1*1); crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+1*1) < cw(0,0+1*1)) { r9 = buff(0,0+1*1); } else { if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) { ASSUME(cr(0,0+1*1) >= old_cr); } pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1)); r9 = mem(0+1*1,cr(0,0+1*1)); } ASSUME(creturn[0] >= cr(0,0+1*1)); // call void @llvm.dbg.value(metadata i64 %5, metadata !172, metadata !DIExpression()), !dbg !227 // %conv18 = trunc i64 %5 to i32, !dbg !132 // call void @llvm.dbg.value(metadata i32 %conv18, metadata !169, metadata !DIExpression()), !dbg !196 // %cmp19 = icmp eq i32 %conv18, 1, !dbg !133 // %conv20 = zext i1 %cmp19 to i32, !dbg !133 // call void @llvm.dbg.value(metadata i32 %conv20, metadata !173, metadata !DIExpression()), !dbg !196 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !175, metadata !DIExpression()), !dbg !231 // %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) seq_cst, align 8, !dbg !135 // LD: Guess old_cr = cr(0,0+2*1); cr(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0+2*1)] == 0); ASSUME(cr(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cr(0,0+2*1) >= 0); ASSUME(cr(0,0+2*1) >= cdy[0]); ASSUME(cr(0,0+2*1) >= cisb[0]); ASSUME(cr(0,0+2*1) >= cdl[0]); ASSUME(cr(0,0+2*1) >= cl[0]); // Update creg_r10 = cr(0,0+2*1); crmax(0,0+2*1) = max(crmax(0,0+2*1),cr(0,0+2*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+2*1) < cw(0,0+2*1)) { r10 = buff(0,0+2*1); } else { if(pw(0,0+2*1) != co(0+2*1,cr(0,0+2*1))) { ASSUME(cr(0,0+2*1) >= old_cr); } pw(0,0+2*1) = co(0+2*1,cr(0,0+2*1)); r10 = mem(0+2*1,cr(0,0+2*1)); } ASSUME(creturn[0] >= cr(0,0+2*1)); // call void @llvm.dbg.value(metadata i64 %6, metadata !177, metadata !DIExpression()), !dbg !231 // %conv24 = trunc i64 %6 to i32, !dbg !136 // call void @llvm.dbg.value(metadata i32 %conv24, metadata !174, metadata !DIExpression()), !dbg !196 // %cmp25 = icmp eq i32 %conv24, 2, !dbg !137 // %conv26 = zext i1 %cmp25 to i32, !dbg !137 // call void @llvm.dbg.value(metadata i32 %conv26, metadata !178, metadata !DIExpression()), !dbg !196 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !180, metadata !DIExpression()), !dbg !235 // %7 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !139 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r11 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r11 = buff(0,3); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r11 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i64 %7, metadata !182, metadata !DIExpression()), !dbg !235 // %conv30 = trunc i64 %7 to i32, !dbg !140 // call void @llvm.dbg.value(metadata i32 %conv30, metadata !179, metadata !DIExpression()), !dbg !196 // call void @llvm.dbg.value(metadata i64* @atom_1_X5_2, metadata !184, metadata !DIExpression()), !dbg !238 // %8 = load atomic i64, i64* @atom_1_X5_2 seq_cst, align 8, !dbg !142 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r12 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r12 = buff(0,4); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r12 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // call void @llvm.dbg.value(metadata i64 %8, metadata !186, metadata !DIExpression()), !dbg !238 // %conv34 = trunc i64 %8 to i32, !dbg !143 // call void @llvm.dbg.value(metadata i32 %conv34, metadata !183, metadata !DIExpression()), !dbg !196 // call void @llvm.dbg.value(metadata i64* @atom_1_X8_1, metadata !188, metadata !DIExpression()), !dbg !241 // %9 = load atomic i64, i64* @atom_1_X8_1 seq_cst, align 8, !dbg !145 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r13 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r13 = buff(0,5); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r13 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // call void @llvm.dbg.value(metadata i64 %9, metadata !190, metadata !DIExpression()), !dbg !241 // %conv38 = trunc i64 %9 to i32, !dbg !146 // call void @llvm.dbg.value(metadata i32 %conv38, metadata !187, metadata !DIExpression()), !dbg !196 // %and = and i32 %conv34, %conv38, !dbg !147 creg_r14 = max(creg_r12,creg_r13); ASSUME(active[creg_r14] == 0); r14 = r12 & r13; // call void @llvm.dbg.value(metadata i32 %and, metadata !191, metadata !DIExpression()), !dbg !196 // %and39 = and i32 %conv30, %and, !dbg !148 creg_r15 = max(creg_r11,creg_r14); ASSUME(active[creg_r15] == 0); r15 = r11 & r14; // call void @llvm.dbg.value(metadata i32 %and39, metadata !192, metadata !DIExpression()), !dbg !196 // %and40 = and i32 %conv26, %and39, !dbg !149 creg_r16 = max(max(creg_r10,0),creg_r15); ASSUME(active[creg_r16] == 0); r16 = (r10==2) & r15; // call void @llvm.dbg.value(metadata i32 %and40, metadata !193, metadata !DIExpression()), !dbg !196 // %and41 = and i32 %conv20, %and40, !dbg !150 creg_r17 = max(max(creg_r9,0),creg_r16); ASSUME(active[creg_r17] == 0); r17 = (r9==1) & r16; // call void @llvm.dbg.value(metadata i32 %and41, metadata !194, metadata !DIExpression()), !dbg !196 // %and42 = and i32 %conv14, %and41, !dbg !151 creg_r18 = max(max(creg_r8,0),creg_r17); ASSUME(active[creg_r18] == 0); r18 = (r8==2) & r17; // call void @llvm.dbg.value(metadata i32 %and42, metadata !195, metadata !DIExpression()), !dbg !196 // %cmp43 = icmp eq i32 %and42, 1, !dbg !152 // br i1 %cmp43, label %if.then, label %if.end, !dbg !154 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg_r18); ASSUME(cctrl[0] >= 0); if((r18==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([116 x i8], [116 x i8]* @.str.1, i64 0, i64 0), i32 noundef 79, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !155 // unreachable, !dbg !155 r19 = 1; T0BLOCK2: // %10 = bitcast i64* %thr1 to i8*, !dbg !158 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !158 // %11 = bitcast i64* %thr0 to i8*, !dbg !158 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !158 // ret i32 0, !dbg !159 ret_thread_0 = 0; ASSERT(r19== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
91c1f7920b01b463f5c56b173a43613dcd9eb7c9
f75650b72c6f394e1c1e31560cbc27aec946d823
/循环7.cpp
6a65408a3e56a93eb949357dda868a85dd059424
[]
no_license
miracleke/learncpp
eb881c3da0dd37118a3f909820991b5ef637c6b3
7efd50aab5ae4286f10f2c4101498d4ade2c610b
refs/heads/master
2022-02-20T09:23:40.830697
2019-08-14T13:57:50
2019-08-14T13:57:50
197,947,346
1
0
null
null
null
null
UTF-8
C++
false
false
248
cpp
#include<iostream> using namespace std; int main() { int sum1=0,sum2=0; for(int i=1;i<=100;i++) if(i%2==0) sum1+=i; else sum2+=i; cout<<"偶数和:" <<sum1<< " "<<"奇数和:" <<sum2 <<endl; return 0; }
[ "3205244665@qq.com" ]
3205244665@qq.com
0a0b785db1f9b8291070c0700e5e73613e8a4191
a8001d9d7b18d44137972525d81a3decbba54d21
/pa3/autoCompleterGUI/wordlist.h
8d93cf1f14253b7eb3c1a4db37a9c229ef06af1e
[]
no_license
ykw1225/CSE-100
871eccdc341731df3c294b85a071a3bdc2a0058c
e5849c6997ba7ede691e2a59004a92533ecc2e3f
refs/heads/master
2021-07-12T07:10:17.946805
2017-10-16T22:13:19
2017-10-16T22:13:19
107,187,864
2
0
null
null
null
null
UTF-8
C++
false
false
968
h
/* * Author: Huayin Zhou * Description: WordList is a customized QListWidget to keep track of the text * changes in QLineEdit and print strings to the changes accordingly by * calling pa3 function: * vector<std::string> autocomplete(unsigned int num_words, std::string prefix). * Date: 01/28/2015 */ #ifndef WORDLIST_H #define WORDLIST_H #include <QListWidget> #include <QString> #include <QLineEdit> #include <string> #include "mainwindow.h" #include "../DictionaryTrie.hpp" #include "../util.hpp" #define MAX_DISPLAY 10 #define MAX_POSTFIX_TO_SEARCH 5 class MainWindow; class WordList : public QListWidget { Q_OBJECT public: WordList(QWidget *parent = 0); void selectNext(); void selectPrev(); ~WordList(); public slots: void setItems(const QString &newString); void clearItems(); void mouseClickClearItems(QListWidgetItem * item); private: MainWindow *mainWindow; DictionaryTrie * trie; }; #endif // WORDLIST_H
[ "ykw005@ucsd.edu" ]
ykw005@ucsd.edu
370d9d82a4b36bf1708d93867cf91d2ce3d4958a
2e3e2c742c155fbe9a8c25bc64d46fdf7067dd4f
/src/wasm/function-body-decoder-impl.h
fe614ff87476baeeeacf99c10ba2b4a7a3fc62ff
[ "BSD-3-Clause", "Apache-2.0", "SunPro", "bzip2-1.0.6" ]
permissive
Gitindexjs/v8
15993be53b476fe0c1a8afe03a8adad3d6fe5040
895c52ddcb783fed5637cb1e6e31b6fd730872da
refs/heads/master
2022-11-01T02:00:29.922433
2020-06-22T08:15:01
2020-06-22T17:49:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
143,433
h
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_ #define V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_ // Do only include this header for implementing new Interface of the // WasmFullDecoder. #include "src/base/platform/elapsed-timer.h" #include "src/base/small-vector.h" #include "src/utils/bit-vector.h" #include "src/wasm/decoder.h" #include "src/wasm/function-body-decoder.h" #include "src/wasm/value-type.h" #include "src/wasm/wasm-features.h" #include "src/wasm/wasm-limits.h" #include "src/wasm/wasm-module.h" #include "src/wasm/wasm-opcodes.h" #include "src/wasm/wasm-subtyping.h" namespace v8 { namespace internal { namespace wasm { struct WasmGlobal; struct WasmException; #define TRACE(...) \ do { \ if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \ } while (false) #define TRACE_INST_FORMAT " @%-8d #%-20s|" // Return the evaluation of `condition` if validate==true, DCHECK that it's // true and always return true otherwise. #define VALIDATE(condition) \ (validate ? (condition) : [&] { \ DCHECK(condition); \ return true; \ }()) #define CHECK_PROTOTYPE_OPCODE_GEN(feat, opt_break) \ DCHECK(this->module_->origin == kWasmOrigin); \ if (!this->enabled_.has_##feat()) { \ this->error("Invalid opcode (enable with --experimental-wasm-" #feat ")"); \ opt_break \ } else { \ this->detected_->Add(kFeature_##feat); \ } #define CHECK_PROTOTYPE_OPCODE(feat) CHECK_PROTOTYPE_OPCODE_GEN(feat, break;) #define RET_ON_PROTOTYPE_OPCODE(feat) CHECK_PROTOTYPE_OPCODE_GEN(feat, ) #define OPCODE_ERROR(opcode, message) \ (this->errorf(this->pc_, "%s: %s", WasmOpcodes::OpcodeName(opcode), \ (message))) #define ATOMIC_OP_LIST(V) \ V(AtomicNotify, Uint32) \ V(I32AtomicWait, Uint32) \ V(I64AtomicWait, Uint64) \ V(I32AtomicLoad, Uint32) \ V(I64AtomicLoad, Uint64) \ V(I32AtomicLoad8U, Uint8) \ V(I32AtomicLoad16U, Uint16) \ V(I64AtomicLoad8U, Uint8) \ V(I64AtomicLoad16U, Uint16) \ V(I64AtomicLoad32U, Uint32) \ V(I32AtomicAdd, Uint32) \ V(I32AtomicAdd8U, Uint8) \ V(I32AtomicAdd16U, Uint16) \ V(I64AtomicAdd, Uint64) \ V(I64AtomicAdd8U, Uint8) \ V(I64AtomicAdd16U, Uint16) \ V(I64AtomicAdd32U, Uint32) \ V(I32AtomicSub, Uint32) \ V(I64AtomicSub, Uint64) \ V(I32AtomicSub8U, Uint8) \ V(I32AtomicSub16U, Uint16) \ V(I64AtomicSub8U, Uint8) \ V(I64AtomicSub16U, Uint16) \ V(I64AtomicSub32U, Uint32) \ V(I32AtomicAnd, Uint32) \ V(I64AtomicAnd, Uint64) \ V(I32AtomicAnd8U, Uint8) \ V(I32AtomicAnd16U, Uint16) \ V(I64AtomicAnd8U, Uint8) \ V(I64AtomicAnd16U, Uint16) \ V(I64AtomicAnd32U, Uint32) \ V(I32AtomicOr, Uint32) \ V(I64AtomicOr, Uint64) \ V(I32AtomicOr8U, Uint8) \ V(I32AtomicOr16U, Uint16) \ V(I64AtomicOr8U, Uint8) \ V(I64AtomicOr16U, Uint16) \ V(I64AtomicOr32U, Uint32) \ V(I32AtomicXor, Uint32) \ V(I64AtomicXor, Uint64) \ V(I32AtomicXor8U, Uint8) \ V(I32AtomicXor16U, Uint16) \ V(I64AtomicXor8U, Uint8) \ V(I64AtomicXor16U, Uint16) \ V(I64AtomicXor32U, Uint32) \ V(I32AtomicExchange, Uint32) \ V(I64AtomicExchange, Uint64) \ V(I32AtomicExchange8U, Uint8) \ V(I32AtomicExchange16U, Uint16) \ V(I64AtomicExchange8U, Uint8) \ V(I64AtomicExchange16U, Uint16) \ V(I64AtomicExchange32U, Uint32) \ V(I32AtomicCompareExchange, Uint32) \ V(I64AtomicCompareExchange, Uint64) \ V(I32AtomicCompareExchange8U, Uint8) \ V(I32AtomicCompareExchange16U, Uint16) \ V(I64AtomicCompareExchange8U, Uint8) \ V(I64AtomicCompareExchange16U, Uint16) \ V(I64AtomicCompareExchange32U, Uint32) #define ATOMIC_STORE_OP_LIST(V) \ V(I32AtomicStore, Uint32) \ V(I64AtomicStore, Uint64) \ V(I32AtomicStore8U, Uint8) \ V(I32AtomicStore16U, Uint16) \ V(I64AtomicStore8U, Uint8) \ V(I64AtomicStore16U, Uint16) \ V(I64AtomicStore32U, Uint32) namespace value_type_reader { // Read a value type starting at address 'pc' in 'decoder'. // No bytes are consumed. The result is written into the 'result' parameter. // Returns the amount of bytes read, or 0 if decoding failed. // Registers an error if the type opcode is invalid iff validate is set. template <Decoder::ValidateFlag validate> ValueType read_value_type(Decoder* decoder, const byte* pc, uint32_t* const length, const WasmFeatures& enabled) { *length = 1; byte val = decoder->read_u8<validate>(pc, "value type opcode"); if (decoder->failed()) { return kWasmBottom; } ValueTypeCode code = static_cast<ValueTypeCode>(val); #define REF_TYPE_CASE(heap_type, nullable, feature) \ case kLocal##heap_type##Ref: { \ ValueType result = ValueType::Ref(kHeap##heap_type, nullable); \ if (enabled.has_##feature()) { \ return result; \ } \ decoder->errorf( \ pc, "invalid value type '%s', enable with --experimental-wasm-%s", \ result.type_name().c_str(), #feature); \ return kWasmBottom; \ } switch (code) { REF_TYPE_CASE(Func, kNullable, reftypes) REF_TYPE_CASE(Extern, kNullable, reftypes) REF_TYPE_CASE(Eq, kNullable, gc) REF_TYPE_CASE(Exn, kNullable, eh) case kLocalI32: return kWasmI32; case kLocalI64: return kWasmI64; case kLocalF32: return kWasmF32; case kLocalF64: return kWasmF64; case kLocalRef: case kLocalOptRef: { // Set length for the macro-defined cases: *length += 1; Nullability nullability = code == kLocalOptRef ? kNullable : kNonNullable; uint8_t heap_index = decoder->read_u8<validate>(pc + 1, "heap type"); switch (static_cast<ValueTypeCode>(heap_index)) { REF_TYPE_CASE(Func, nullability, typed_funcref) REF_TYPE_CASE(Extern, nullability, typed_funcref) REF_TYPE_CASE(Eq, nullability, gc) REF_TYPE_CASE(Exn, nullability, eh) default: uint32_t type_index = decoder->read_u32v<validate>(pc + 1, length, "type index"); *length += 1; if (!enabled.has_gc()) { decoder->error( pc, "invalid value type '(ref [null] (type $t))', enable with " "--experimental-wasm-typed-gc"); return kWasmBottom; } if (!VALIDATE(type_index < kV8MaxWasmTypes)) { decoder->errorf(pc + 1, "Type index %u is greater than the maximum " "number %zu of type definitions supported by V8", type_index, kV8MaxWasmTypes); return kWasmBottom; } return ValueType::Ref(static_cast<HeapType>(type_index), nullability); } decoder->errorf( pc, "invalid value type '(ref%s $t)', enable with --experimental-wasm-gc", nullability ? " null" : ""); return kWasmBottom; } #undef REF_TYPE_CASE case kLocalRtt: if (enabled.has_gc()) { // TODO(7748): Implement decoder->error(pc, "'rtt' is unimplemented"); } decoder->error( pc, "invalid value type 'rtt', enable with --experimental-wasm-gc"); return kWasmBottom; case kLocalS128: if (enabled.has_simd()) { return kWasmS128; } decoder->error( pc, "invalid value type 'Simd128', enable with --experimental-wasm-simd"); return kWasmBottom; case kLocalVoid: case kLocalI8: case kLocalI16: // Although these types are included in ValueType, they are technically // not value types and are only used in specific contexts. The caller of // this function is responsible to check for them separately. break; } // Malformed modules specifying invalid types can get here. return kWasmBottom; } } // namespace value_type_reader // Helpers for decoding different kinds of immediates which follow bytecodes. template <Decoder::ValidateFlag validate> struct LocalIndexImmediate { uint32_t index; ValueType type = kWasmStmt; uint32_t length; inline LocalIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "local index"); } }; template <Decoder::ValidateFlag validate> struct ExceptionIndexImmediate { uint32_t index; const WasmException* exception = nullptr; uint32_t length; inline ExceptionIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "exception index"); } }; template <Decoder::ValidateFlag validate> struct ImmI32Immediate { int32_t value; uint32_t length; inline ImmI32Immediate(Decoder* decoder, const byte* pc) { value = decoder->read_i32v<validate>(pc + 1, &length, "immi32"); } }; template <Decoder::ValidateFlag validate> struct ImmI64Immediate { int64_t value; uint32_t length; inline ImmI64Immediate(Decoder* decoder, const byte* pc) { value = decoder->read_i64v<validate>(pc + 1, &length, "immi64"); } }; template <Decoder::ValidateFlag validate> struct ImmF32Immediate { float value; uint32_t length = 4; inline ImmF32Immediate(Decoder* decoder, const byte* pc) { // We can't use bit_cast here because calling any helper function that // returns a float would potentially flip NaN bits per C++ semantics, so we // have to inline the memcpy call directly. uint32_t tmp = decoder->read_u32<validate>(pc + 1, "immf32"); memcpy(&value, &tmp, sizeof(value)); } }; template <Decoder::ValidateFlag validate> struct ImmF64Immediate { double value; uint32_t length = 8; inline ImmF64Immediate(Decoder* decoder, const byte* pc) { // Avoid bit_cast because it might not preserve the signalling bit of a NaN. uint64_t tmp = decoder->read_u64<validate>(pc + 1, "immf64"); memcpy(&value, &tmp, sizeof(value)); } }; template <Decoder::ValidateFlag validate> struct RefNullImmediate { ValueType type; uint32_t length = 1; inline RefNullImmediate(const WasmFeatures& enabled, Decoder* decoder, const byte* pc) { type = value_type_reader::read_value_type<validate>(decoder, pc + 1, &length, enabled); } }; template <Decoder::ValidateFlag validate> struct GlobalIndexImmediate { uint32_t index; ValueType type = kWasmStmt; const WasmGlobal* global = nullptr; uint32_t length; inline GlobalIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "global index"); } }; template <Decoder::ValidateFlag validate> struct SelectTypeImmediate { uint32_t length; ValueType type; inline SelectTypeImmediate(const WasmFeatures& enabled, Decoder* decoder, const byte* pc) { uint8_t num_types = decoder->read_u32v<validate>(pc + 1, &length, "number of select types"); if (!VALIDATE(num_types == 1)) { decoder->error( pc + 1, "Invalid number of types. Select accepts exactly one type"); return; } uint32_t type_length; type = value_type_reader::read_value_type<validate>( decoder, pc + length + 1, &type_length, enabled); length += type_length; if (type == kWasmBottom) { decoder->error(pc + 1, "invalid select type"); } } }; template <Decoder::ValidateFlag validate> struct BlockTypeImmediate { uint32_t length = 1; ValueType type = kWasmStmt; uint32_t sig_index = 0; const FunctionSig* sig = nullptr; inline BlockTypeImmediate(const WasmFeatures& enabled, Decoder* decoder, const byte* pc) { if (decoder->read_u8<validate>(pc + 1, "block type") == kLocalVoid) { // 1st case: void block. Struct fields stay at default values. return; } type = value_type_reader::read_value_type<validate>(decoder, pc + 1, &length, enabled); if (type != kWasmBottom) { // 2nd case: block with val type immediate. return; } // It has to be the 3rd case: multi-value block, // which is represented by a type index. if (!VALIDATE(enabled.has_mv())) { decoder->error(pc + 1, "invalid block type"); return; } if (!VALIDATE(decoder->ok())) return; int32_t index = decoder->read_i32v<validate>(pc + 1, &length, "block type index"); if (!VALIDATE(length > 0 && index >= 0)) { decoder->error(pc + 1, "invalid block type index"); return; } sig_index = static_cast<uint32_t>(index); } uint32_t in_arity() const { if (type != kWasmBottom) return 0; return static_cast<uint32_t>(sig->parameter_count()); } uint32_t out_arity() const { if (type == kWasmStmt) return 0; if (type != kWasmBottom) return 1; return static_cast<uint32_t>(sig->return_count()); } ValueType in_type(uint32_t index) { DCHECK_EQ(kWasmBottom, type); return sig->GetParam(index); } ValueType out_type(uint32_t index) { if (type == kWasmBottom) return sig->GetReturn(index); DCHECK_NE(kWasmStmt, type); DCHECK_EQ(0, index); return type; } }; template <Decoder::ValidateFlag validate> struct BranchDepthImmediate { uint32_t depth; uint32_t length; inline BranchDepthImmediate(Decoder* decoder, const byte* pc) { depth = decoder->read_u32v<validate>(pc + 1, &length, "branch depth"); } }; template <Decoder::ValidateFlag validate> struct BranchOnExceptionImmediate { BranchDepthImmediate<validate> depth; ExceptionIndexImmediate<validate> index; uint32_t length = 0; inline BranchOnExceptionImmediate(Decoder* decoder, const byte* pc) : depth(BranchDepthImmediate<validate>(decoder, pc)), index(ExceptionIndexImmediate<validate>(decoder, pc + depth.length)) { length = depth.length + index.length; } }; template <Decoder::ValidateFlag validate> struct FunctionIndexImmediate { uint32_t index = 0; uint32_t length = 1; inline FunctionIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "function index"); } }; template <Decoder::ValidateFlag validate> struct MemoryIndexImmediate { uint32_t index = 0; uint32_t length = 1; inline MemoryIndexImmediate() = default; inline MemoryIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u8<validate>(pc + 1, "memory index"); if (!VALIDATE(index == 0)) { decoder->errorf(pc + 1, "expected memory index 0, found %u", index); } } }; template <Decoder::ValidateFlag validate> struct TableIndexImmediate { uint32_t index = 0; unsigned length = 1; inline TableIndexImmediate() = default; inline TableIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "table index"); } }; template <Decoder::ValidateFlag validate> struct StructIndexImmediate { uint32_t index = 0; uint32_t length = 0; const StructType* struct_type = nullptr; inline StructIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc, &length, "struct index"); } }; template <Decoder::ValidateFlag validate> struct FieldIndexImmediate { StructIndexImmediate<validate> struct_index; uint32_t index = 0; uint32_t length = 0; inline FieldIndexImmediate(Decoder* decoder, const byte* pc) : struct_index(decoder, pc) { index = decoder->read_u32v<validate>(pc + struct_index.length, &length, "field index"); length += struct_index.length; } }; template <Decoder::ValidateFlag validate> struct ArrayIndexImmediate { uint32_t index = 0; uint32_t length = 0; const ArrayType* array_type = nullptr; inline ArrayIndexImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc, &length, "array index"); } }; template <Decoder::ValidateFlag validate> struct CallIndirectImmediate { uint32_t table_index; uint32_t sig_index; const FunctionSig* sig = nullptr; uint32_t length = 0; inline CallIndirectImmediate(const WasmFeatures enabled, Decoder* decoder, const byte* pc) { uint32_t len = 0; sig_index = decoder->read_u32v<validate>(pc + 1, &len, "signature index"); TableIndexImmediate<validate> table(decoder, pc + len); if (!VALIDATE((table.index == 0 && table.length == 1) || enabled.has_reftypes())) { decoder->errorf(pc + 1 + len, "expected table index 0, found %u", table.index); } table_index = table.index; length = len + table.length; } }; template <Decoder::ValidateFlag validate> struct CallFunctionImmediate { uint32_t index; const FunctionSig* sig = nullptr; uint32_t length; inline CallFunctionImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 1, &length, "function index"); } }; template <Decoder::ValidateFlag validate> struct BranchTableImmediate { uint32_t table_count; const byte* start; const byte* table; inline BranchTableImmediate(Decoder* decoder, const byte* pc) { DCHECK_EQ(kExprBrTable, decoder->read_u8<validate>(pc, "opcode")); start = pc + 1; uint32_t len = 0; table_count = decoder->read_u32v<validate>(pc + 1, &len, "table count"); table = pc + 1 + len; } }; // A helper to iterate over a branch table. template <Decoder::ValidateFlag validate> class BranchTableIterator { public: uint32_t cur_index() { return index_; } bool has_next() { return VALIDATE(decoder_->ok()) && index_ <= table_count_; } uint32_t next() { DCHECK(has_next()); index_++; uint32_t length; uint32_t result = decoder_->read_u32v<validate>(pc_, &length, "branch table entry"); pc_ += length; return result; } // length, including the length of the {BranchTableImmediate}, but not the // opcode. uint32_t length() { while (has_next()) next(); return static_cast<uint32_t>(pc_ - start_); } const byte* pc() { return pc_; } BranchTableIterator(Decoder* decoder, const BranchTableImmediate<validate>& imm) : decoder_(decoder), start_(imm.start), pc_(imm.table), table_count_(imm.table_count) {} private: Decoder* decoder_; const byte* start_; const byte* pc_; uint32_t index_ = 0; // the current index. uint32_t table_count_; // the count of entries, not including default. }; template <Decoder::ValidateFlag validate> struct MemoryAccessImmediate { uint32_t alignment; uint32_t offset; uint32_t length = 0; inline MemoryAccessImmediate(Decoder* decoder, const byte* pc, uint32_t max_alignment) { uint32_t alignment_length; alignment = decoder->read_u32v<validate>(pc + 1, &alignment_length, "alignment"); if (!VALIDATE(alignment <= max_alignment)) { decoder->errorf(pc + 1, "invalid alignment; expected maximum alignment is %u, " "actual alignment is %u", max_alignment, alignment); } uint32_t offset_length; offset = decoder->read_u32v<validate>(pc + 1 + alignment_length, &offset_length, "offset"); length = alignment_length + offset_length; } }; // Immediate for SIMD lane operations. template <Decoder::ValidateFlag validate> struct SimdLaneImmediate { uint8_t lane; uint32_t length = 1; inline SimdLaneImmediate(Decoder* decoder, const byte* pc, uint32_t opcode_length) { // Callers should pass in pc unchanged from where the decoding happens. 1 is // added to account for the SIMD prefix byte, and opcode_length is the // number of bytes the LEB encoding of the SIMD opcode takes. lane = decoder->read_u8<validate>(pc + 1 + opcode_length, "lane"); } }; // Immediate for SIMD S8x16 shuffle operations. template <Decoder::ValidateFlag validate> struct Simd8x16ShuffleImmediate { uint8_t shuffle[kSimd128Size] = {0}; inline Simd8x16ShuffleImmediate(Decoder* decoder, const byte* pc, uint32_t opcode_length) { // Callers should pass in pc unchanged from where the decoding happens. 1 is // added to account for the SIMD prefix byte, and opcode_length is the // number of bytes the LEB encoding of the SIMD opcode takes. for (uint32_t i = 0; i < kSimd128Size; ++i) { shuffle[i] = decoder->read_u8<validate>(pc + 1 + opcode_length + i, "shuffle"); } } }; template <Decoder::ValidateFlag validate> struct MemoryInitImmediate { uint32_t data_segment_index = 0; MemoryIndexImmediate<validate> memory; unsigned length = 0; inline MemoryInitImmediate(Decoder* decoder, const byte* pc) { uint32_t len = 0; data_segment_index = decoder->read_u32v<validate>(pc + 2, &len, "data segment index"); memory = MemoryIndexImmediate<validate>(decoder, pc + 1 + len); length = len + memory.length; } }; template <Decoder::ValidateFlag validate> struct DataDropImmediate { uint32_t index; unsigned length; inline DataDropImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 2, &length, "data segment index"); } }; template <Decoder::ValidateFlag validate> struct MemoryCopyImmediate { MemoryIndexImmediate<validate> memory_src; MemoryIndexImmediate<validate> memory_dst; unsigned length = 0; inline MemoryCopyImmediate(Decoder* decoder, const byte* pc) { memory_src = MemoryIndexImmediate<validate>(decoder, pc + 1); memory_dst = MemoryIndexImmediate<validate>(decoder, pc + 1 + memory_src.length); length = memory_src.length + memory_dst.length; } }; template <Decoder::ValidateFlag validate> struct TableInitImmediate { uint32_t elem_segment_index = 0; TableIndexImmediate<validate> table; unsigned length = 0; inline TableInitImmediate(Decoder* decoder, const byte* pc) { uint32_t len = 0; elem_segment_index = decoder->read_u32v<validate>(pc + 2, &len, "elem segment index"); table = TableIndexImmediate<validate>(decoder, pc + 1 + len); length = len + table.length; } }; template <Decoder::ValidateFlag validate> struct ElemDropImmediate { uint32_t index; unsigned length; inline ElemDropImmediate(Decoder* decoder, const byte* pc) { index = decoder->read_u32v<validate>(pc + 2, &length, "elem segment index"); } }; template <Decoder::ValidateFlag validate> struct TableCopyImmediate { TableIndexImmediate<validate> table_dst; TableIndexImmediate<validate> table_src; unsigned length = 0; inline TableCopyImmediate(Decoder* decoder, const byte* pc) { table_dst = TableIndexImmediate<validate>(decoder, pc + 1); table_src = TableIndexImmediate<validate>(decoder, pc + 1 + table_dst.length); length = table_src.length + table_dst.length; } }; // An entry on the value stack. struct ValueBase { const byte* pc = nullptr; ValueType type = kWasmStmt; ValueBase(const byte* pc, ValueType type) : pc(pc), type(type) {} }; template <typename Value> struct Merge { uint32_t arity = 0; union { // Either multiple values or a single value. Value* array; Value first; } vals = {nullptr}; // Initialize {array} with {nullptr}. // Tracks whether this merge was ever reached. Uses precise reachability, like // Reachability::kReachable. bool reached; explicit Merge(bool reached = false) : reached(reached) {} Value& operator[](uint32_t i) { DCHECK_GT(arity, i); return arity == 1 ? vals.first : vals.array[i]; } }; enum ControlKind : uint8_t { kControlIf, kControlIfElse, kControlBlock, kControlLoop, kControlLet, kControlTry, kControlTryCatch }; enum Reachability : uint8_t { // reachable code. kReachable, // reachable code in unreachable block (implies normal validation). kSpecOnlyReachable, // code unreachable in its own block (implies polymorphic validation). kUnreachable }; // An entry on the control stack (i.e. if, block, loop, or try). template <typename Value> struct ControlBase { ControlKind kind = kControlBlock; uint32_t locals_count = 0; uint32_t stack_depth = 0; // stack height at the beginning of the construct. const uint8_t* pc = nullptr; Reachability reachability = kReachable; // Values merged into the start or end of this control construct. Merge<Value> start_merge; Merge<Value> end_merge; MOVE_ONLY_NO_DEFAULT_CONSTRUCTOR(ControlBase); ControlBase(ControlKind kind, uint32_t locals_count, uint32_t stack_depth, const uint8_t* pc, Reachability reachability) : kind(kind), locals_count(locals_count), stack_depth(stack_depth), pc(pc), reachability(reachability), start_merge(reachability == kReachable) { DCHECK(kind == kControlLet || locals_count == 0); } // Check whether the current block is reachable. bool reachable() const { return reachability == kReachable; } // Check whether the rest of the block is unreachable. // Note that this is different from {!reachable()}, as there is also the // "indirect unreachable state", for which both {reachable()} and // {unreachable()} return false. bool unreachable() const { return reachability == kUnreachable; } // Return the reachability of new control structs started in this block. Reachability innerReachability() const { return reachability == kReachable ? kReachable : kSpecOnlyReachable; } bool is_if() const { return is_onearmed_if() || is_if_else(); } bool is_onearmed_if() const { return kind == kControlIf; } bool is_if_else() const { return kind == kControlIfElse; } bool is_block() const { return kind == kControlBlock; } bool is_let() const { return kind == kControlLet; } bool is_loop() const { return kind == kControlLoop; } bool is_incomplete_try() const { return kind == kControlTry; } bool is_try_catch() const { return kind == kControlTryCatch; } bool is_try() const { return is_incomplete_try() || is_try_catch(); } inline Merge<Value>* br_merge() { return is_loop() ? &this->start_merge : &this->end_merge; } }; // This is the list of callback functions that an interface for the // WasmFullDecoder should implement. // F(Name, args...) #define INTERFACE_FUNCTIONS(F) \ /* General: */ \ F(StartFunction) \ F(StartFunctionBody, Control* block) \ F(FinishFunction) \ F(OnFirstError) \ F(NextInstruction, WasmOpcode) \ /* Control: */ \ F(Block, Control* block) \ F(Loop, Control* block) \ F(Try, Control* block) \ F(Catch, Control* block, Value* exception) \ F(If, const Value& cond, Control* if_block) \ F(FallThruTo, Control* c) \ F(PopControl, Control* block) \ F(EndControl, Control* block) \ /* Instructions: */ \ F(UnOp, WasmOpcode opcode, const Value& value, Value* result) \ F(BinOp, WasmOpcode opcode, const Value& lhs, const Value& rhs, \ Value* result) \ F(I32Const, Value* result, int32_t value) \ F(I64Const, Value* result, int64_t value) \ F(F32Const, Value* result, float value) \ F(F64Const, Value* result, double value) \ F(RefNull, Value* result) \ F(RefFunc, uint32_t function_index, Value* result) \ F(RefAsNonNull, const Value& arg, Value* result) \ F(Drop, const Value& value) \ F(DoReturn, Vector<Value> values) \ F(LocalGet, Value* result, const LocalIndexImmediate<validate>& imm) \ F(LocalSet, const Value& value, const LocalIndexImmediate<validate>& imm) \ F(LocalTee, const Value& value, Value* result, \ const LocalIndexImmediate<validate>& imm) \ F(AllocateLocals, Vector<Value> local_values) \ F(DeallocateLocals, uint32_t count) \ F(GlobalGet, Value* result, const GlobalIndexImmediate<validate>& imm) \ F(GlobalSet, const Value& value, const GlobalIndexImmediate<validate>& imm) \ F(TableGet, const Value& index, Value* result, \ const TableIndexImmediate<validate>& imm) \ F(TableSet, const Value& index, const Value& value, \ const TableIndexImmediate<validate>& imm) \ F(Unreachable) \ F(Select, const Value& cond, const Value& fval, const Value& tval, \ Value* result) \ F(Br, Control* target) \ F(BrIf, const Value& cond, uint32_t depth) \ F(BrTable, const BranchTableImmediate<validate>& imm, const Value& key) \ F(Else, Control* if_block) \ F(LoadMem, LoadType type, const MemoryAccessImmediate<validate>& imm, \ const Value& index, Value* result) \ F(LoadTransform, LoadType type, LoadTransformationKind transform, \ MemoryAccessImmediate<validate>& imm, const Value& index, Value* result) \ F(StoreMem, StoreType type, const MemoryAccessImmediate<validate>& imm, \ const Value& index, const Value& value) \ F(CurrentMemoryPages, Value* result) \ F(MemoryGrow, const Value& value, Value* result) \ F(CallDirect, const CallFunctionImmediate<validate>& imm, \ const Value args[], Value returns[]) \ F(CallIndirect, const Value& index, \ const CallIndirectImmediate<validate>& imm, const Value args[], \ Value returns[]) \ F(ReturnCall, const CallFunctionImmediate<validate>& imm, \ const Value args[]) \ F(ReturnCallIndirect, const Value& index, \ const CallIndirectImmediate<validate>& imm, const Value args[]) \ F(BrOnNull, const Value& ref_object, uint32_t depth) \ F(SimdOp, WasmOpcode opcode, Vector<Value> args, Value* result) \ F(SimdLaneOp, WasmOpcode opcode, const SimdLaneImmediate<validate>& imm, \ const Vector<Value> inputs, Value* result) \ F(Simd8x16ShuffleOp, const Simd8x16ShuffleImmediate<validate>& imm, \ const Value& input0, const Value& input1, Value* result) \ F(Throw, const ExceptionIndexImmediate<validate>& imm, \ const Vector<Value>& args) \ F(Rethrow, const Value& exception) \ F(BrOnException, const Value& exception, \ const ExceptionIndexImmediate<validate>& imm, uint32_t depth, \ Vector<Value> values) \ F(AtomicOp, WasmOpcode opcode, Vector<Value> args, \ const MemoryAccessImmediate<validate>& imm, Value* result) \ F(AtomicFence) \ F(MemoryInit, const MemoryInitImmediate<validate>& imm, const Value& dst, \ const Value& src, const Value& size) \ F(DataDrop, const DataDropImmediate<validate>& imm) \ F(MemoryCopy, const MemoryCopyImmediate<validate>& imm, const Value& dst, \ const Value& src, const Value& size) \ F(MemoryFill, const MemoryIndexImmediate<validate>& imm, const Value& dst, \ const Value& value, const Value& size) \ F(TableInit, const TableInitImmediate<validate>& imm, Vector<Value> args) \ F(ElemDrop, const ElemDropImmediate<validate>& imm) \ F(TableCopy, const TableCopyImmediate<validate>& imm, Vector<Value> args) \ F(TableGrow, const TableIndexImmediate<validate>& imm, const Value& value, \ const Value& delta, Value* result) \ F(TableSize, const TableIndexImmediate<validate>& imm, Value* result) \ F(TableFill, const TableIndexImmediate<validate>& imm, const Value& start, \ const Value& value, const Value& count) \ F(StructNew, const StructIndexImmediate<validate>& imm, const Value args[], \ Value* result) \ F(StructGet, const Value& struct_object, \ const FieldIndexImmediate<validate>& field, bool is_signed, Value* result) \ F(StructSet, const Value& struct_object, \ const FieldIndexImmediate<validate>& field, const Value& field_value) \ F(ArrayNew, const ArrayIndexImmediate<validate>& imm, const Value& length, \ const Value& initial_value, Value* result) \ F(ArrayGet, const Value& array_obj, \ const ArrayIndexImmediate<validate>& imm, const Value& index, \ bool is_signed, Value* result) \ F(ArraySet, const Value& array_obj, \ const ArrayIndexImmediate<validate>& imm, const Value& index, \ const Value& value) \ F(ArrayLen, const Value& array_obj, Value* result) \ F(PassThrough, const Value& from, Value* to) // Generic Wasm bytecode decoder with utilities for decoding immediates, // lengths, etc. template <Decoder::ValidateFlag validate> class WasmDecoder : public Decoder { public: WasmDecoder(const WasmModule* module, const WasmFeatures& enabled, WasmFeatures* detected, const FunctionSig* sig, const byte* start, const byte* end, uint32_t buffer_offset = 0) : Decoder(start, end, buffer_offset), module_(module), enabled_(enabled), detected_(detected), sig_(sig), local_types_(nullptr) {} const WasmModule* module_; const WasmFeatures enabled_; WasmFeatures* detected_; const FunctionSig* sig_; ZoneVector<ValueType>* local_types_; uint32_t total_locals() const { return local_types_ == nullptr ? 0 : static_cast<uint32_t>(local_types_->size()); } void InitializeLocalsFromSig() { if (sig_ != nullptr) { local_types_->assign(sig_->parameters().begin(), sig_->parameters().end()); } } // Decodes local definitions in the current decoder. // Returns true iff locals are found. // Writes the total length of decoded locals in 'total_length'. // If insert_postion is present, the decoded locals will be inserted into the // 'local_types_' of this decoder. Otherwise, this function is used just to // check validity and determine the encoding length of the locals in bytes. // The decoder's pc is not advanced. If no locals are found (i.e., no // compressed uint32 is found at pc), this will exit as 'false' and without an // error. bool DecodeLocals(const byte* pc, uint32_t* total_length, const base::Optional<uint32_t> insert_position) { DCHECK_NOT_NULL(local_types_); uint32_t length; *total_length = 0; // The 'else' value is useless, we pass it for convenience. ZoneVector<ValueType>::iterator insert_iterator = insert_position.has_value() ? local_types_->begin() + insert_position.value() : local_types_->begin(); // Decode local declarations, if any. uint32_t entries = read_u32v<kValidate>(pc, &length, "local decls count"); if (failed()) { error(pc + *total_length, "invalid local decls count"); return false; } *total_length += length; TRACE("local decls count: %u\n", entries); while (entries-- > 0) { if (!more()) { error(end(), "expected more local decls but reached end of input"); return false; } uint32_t count = read_u32v<kValidate>(pc + *total_length, &length, "local count"); if (failed()) { error(pc + *total_length, "invalid local count"); return false; } DCHECK_LE(local_types_->size(), kV8MaxWasmFunctionLocals); if (count > kV8MaxWasmFunctionLocals - local_types_->size()) { error(pc + *total_length, "local count too large"); return false; } *total_length += length; ValueType type = value_type_reader::read_value_type<kValidate>( this, pc + *total_length, &length, enabled_); if (type == kWasmBottom) { error(pc + *total_length, "invalid local type"); return false; } *total_length += length; if (insert_position.has_value()) { // Move the insertion iterator to the end of the newly inserted locals. insert_iterator = local_types_->insert(insert_iterator, count, type) + count; } } DCHECK(ok()); return true; } static BitVector* AnalyzeLoopAssignment(WasmDecoder* decoder, const byte* pc, uint32_t locals_count, Zone* zone) { if (pc >= decoder->end()) return nullptr; if (*pc != kExprLoop) return nullptr; // The number of locals_count is augmented by 2 so that 'locals_count - 2' // can be used to track mem_size, and 'locals_count - 1' to track mem_start. BitVector* assigned = new (zone) BitVector(locals_count, zone); int depth = 0; // Iteratively process all AST nodes nested inside the loop. while (pc < decoder->end() && VALIDATE(decoder->ok())) { WasmOpcode opcode = static_cast<WasmOpcode>(*pc); uint32_t length = 1; switch (opcode) { case kExprLoop: case kExprIf: case kExprBlock: case kExprTry: length = OpcodeLength(decoder, pc); depth++; break; case kExprLocalSet: // fallthru case kExprLocalTee: { LocalIndexImmediate<validate> imm(decoder, pc); if (assigned->length() > 0 && imm.index < static_cast<uint32_t>(assigned->length())) { // Unverified code might have an out-of-bounds index. assigned->Add(imm.index); } length = 1 + imm.length; break; } case kExprMemoryGrow: case kExprCallFunction: case kExprCallIndirect: case kExprReturnCall: case kExprReturnCallIndirect: // Add instance cache nodes to the assigned set. // TODO(titzer): make this more clear. assigned->Add(locals_count - 1); length = OpcodeLength(decoder, pc); break; case kExprEnd: depth--; break; default: length = OpcodeLength(decoder, pc); break; } if (depth <= 0) break; pc += length; } return VALIDATE(decoder->ok()) ? assigned : nullptr; } inline bool Validate(const byte* pc, LocalIndexImmediate<validate>& imm) { if (!VALIDATE(imm.index < total_locals())) { errorf(pc + 1, "invalid local index: %u", imm.index); return false; } imm.type = local_types_ ? local_types_->at(imm.index) : kWasmStmt; return true; } inline bool Validate(const byte* pc, RefNullImmediate<validate>& imm) { if (!VALIDATE(imm.type.is_nullable())) { errorf(pc + 1, "ref.null does not exist for %s", imm.type.type_name().c_str()); return false; } return true; } inline bool Complete(const byte* pc, ExceptionIndexImmediate<validate>& imm) { if (!VALIDATE(imm.index < module_->exceptions.size())) return false; imm.exception = &module_->exceptions[imm.index]; return true; } inline bool Validate(const byte* pc, ExceptionIndexImmediate<validate>& imm) { if (!Complete(pc, imm)) { errorf(pc + 1, "Invalid exception index: %u", imm.index); return false; } return true; } inline bool Validate(const byte* pc, GlobalIndexImmediate<validate>& imm) { if (!VALIDATE(imm.index < module_->globals.size())) { errorf(pc + 1, "invalid global index: %u", imm.index); return false; } imm.global = &module_->globals[imm.index]; imm.type = imm.global->type; return true; } inline bool Complete(const byte* pc, StructIndexImmediate<validate>& imm) { if (!VALIDATE(module_->has_struct(imm.index))) return false; imm.struct_type = module_->struct_type(imm.index); return true; } inline bool Validate(const byte* pc, StructIndexImmediate<validate>& imm) { if (Complete(pc, imm)) return true; errorf(pc, "invalid struct index: %u", imm.index); return false; } inline bool Validate(const byte* pc, FieldIndexImmediate<validate>& imm) { if (!Validate(pc, imm.struct_index)) return false; if (imm.index < imm.struct_index.struct_type->field_count()) return true; errorf(pc + imm.struct_index.length, "invalid field index: %u", imm.index); return false; } inline bool Complete(const byte* pc, ArrayIndexImmediate<validate>& imm) { if (!VALIDATE(module_->has_array(imm.index))) return false; imm.array_type = module_->array_type(imm.index); return true; } inline bool Validate(const byte* pc, ArrayIndexImmediate<validate>& imm) { if (Complete(pc, imm)) return true; errorf(pc, "invalid array index: %u", imm.index); return false; } inline bool CanReturnCall(const FunctionSig* target_sig) { if (target_sig == nullptr) return false; size_t num_returns = sig_->return_count(); if (num_returns != target_sig->return_count()) return false; for (size_t i = 0; i < num_returns; ++i) { if (sig_->GetReturn(i) != target_sig->GetReturn(i)) return false; } return true; } inline bool Complete(const byte* pc, CallFunctionImmediate<validate>& imm) { if (!VALIDATE(imm.index < module_->functions.size())) return false; imm.sig = module_->functions[imm.index].sig; if (imm.sig->return_count() > 1) { this->detected_->Add(kFeature_mv); } return true; } inline bool Validate(const byte* pc, CallFunctionImmediate<validate>& imm) { if (Complete(pc, imm)) { return true; } errorf(pc + 1, "invalid function index: %u", imm.index); return false; } inline bool Complete(const byte* pc, CallIndirectImmediate<validate>& imm) { if (!VALIDATE(module_->has_signature(imm.sig_index))) return false; imm.sig = module_->signature(imm.sig_index); if (imm.sig->return_count() > 1) { this->detected_->Add(kFeature_mv); } return true; } inline bool Validate(const byte* pc, CallIndirectImmediate<validate>& imm) { if (!VALIDATE(imm.table_index < module_->tables.size())) { error("function table has to exist to execute call_indirect"); return false; } if (!VALIDATE(module_->tables[imm.table_index].type == kWasmFuncRef)) { error("table of call_indirect must be of type funcref"); return false; } if (!Complete(pc, imm)) { errorf(pc + 1, "invalid signature index: #%u", imm.sig_index); return false; } return true; } inline bool Validate(const byte* pc, BranchDepthImmediate<validate>& imm, size_t control_depth) { if (!VALIDATE(imm.depth < control_depth)) { errorf(pc + 1, "invalid branch depth: %u", imm.depth); return false; } return true; } bool Validate(const byte* pc, BranchTableImmediate<validate>& imm, size_t block_depth) { if (!VALIDATE(imm.table_count <= kV8MaxWasmFunctionBrTableSize)) { errorf(pc + 1, "invalid table count (> max br_table size): %u", imm.table_count); return false; } return checkAvailable(imm.table_count); } inline bool Validate(const byte* pc, WasmOpcode opcode, SimdLaneImmediate<validate>& imm) { uint8_t num_lanes = 0; switch (opcode) { case kExprF64x2ExtractLane: case kExprF64x2ReplaceLane: case kExprI64x2ExtractLane: case kExprI64x2ReplaceLane: num_lanes = 2; break; case kExprF32x4ExtractLane: case kExprF32x4ReplaceLane: case kExprI32x4ExtractLane: case kExprI32x4ReplaceLane: num_lanes = 4; break; case kExprI16x8ExtractLaneS: case kExprI16x8ExtractLaneU: case kExprI16x8ReplaceLane: num_lanes = 8; break; case kExprI8x16ExtractLaneS: case kExprI8x16ExtractLaneU: case kExprI8x16ReplaceLane: num_lanes = 16; break; default: UNREACHABLE(); break; } if (!VALIDATE(imm.lane >= 0 && imm.lane < num_lanes)) { error(pc_ + 2, "invalid lane index"); return false; } else { return true; } } inline bool Validate(const byte* pc, Simd8x16ShuffleImmediate<validate>& imm) { uint8_t max_lane = 0; for (uint32_t i = 0; i < kSimd128Size; ++i) { max_lane = std::max(max_lane, imm.shuffle[i]); } // Shuffle indices must be in [0..31] for a 16 lane shuffle. if (!VALIDATE(max_lane < 2 * kSimd128Size)) { error(pc_ + 2, "invalid shuffle mask"); return false; } return true; } inline bool Complete(BlockTypeImmediate<validate>& imm) { if (imm.type != kWasmBottom) return true; if (!VALIDATE(module_->has_signature(imm.sig_index))) return false; imm.sig = module_->signature(imm.sig_index); if (imm.sig->return_count() > 1) { this->detected_->Add(kFeature_mv); } return true; } inline bool Validate(BlockTypeImmediate<validate>& imm) { if (!Complete(imm)) { errorf(pc_, "block type index %u out of bounds (%zu types)", imm.sig_index, module_->types.size()); return false; } return true; } inline bool Validate(const byte* pc, FunctionIndexImmediate<validate>& imm) { if (!VALIDATE(imm.index < module_->functions.size())) { errorf(pc, "invalid function index: %u", imm.index); return false; } if (!VALIDATE(module_->functions[imm.index].declared)) { this->errorf(pc, "undeclared reference to function #%u", imm.index); return false; } return true; } inline bool Validate(const byte* pc, MemoryIndexImmediate<validate>& imm) { if (!VALIDATE(module_->has_memory)) { errorf(pc + 1, "memory instruction with no memory"); return false; } return true; } inline bool Validate(MemoryInitImmediate<validate>& imm) { if (!VALIDATE(imm.data_segment_index < module_->num_declared_data_segments)) { errorf(pc_ + 2, "invalid data segment index: %u", imm.data_segment_index); return false; } if (!Validate(pc_ + imm.length - imm.memory.length - 1, imm.memory)) return false; return true; } inline bool Validate(DataDropImmediate<validate>& imm) { if (!VALIDATE(imm.index < module_->num_declared_data_segments)) { errorf(pc_ + 2, "invalid data segment index: %u", imm.index); return false; } return true; } inline bool Validate(MemoryCopyImmediate<validate>& imm) { if (!Validate(pc_ + 1, imm.memory_src)) return false; if (!Validate(pc_ + 2, imm.memory_dst)) return false; return true; } inline bool Validate(const byte* pc, TableIndexImmediate<validate>& imm) { if (!VALIDATE(imm.index < module_->tables.size())) { errorf(pc, "invalid table index: %u", imm.index); return false; } return true; } inline bool Validate(TableInitImmediate<validate>& imm) { if (!VALIDATE(imm.elem_segment_index < module_->elem_segments.size())) { errorf(pc_ + 2, "invalid element segment index: %u", imm.elem_segment_index); return false; } if (!Validate(pc_ + imm.length - imm.table.length - 1, imm.table)) { return false; } ValueType elem_type = module_->elem_segments[imm.elem_segment_index].type; if (!VALIDATE(IsSubtypeOf(elem_type, module_->tables[imm.table.index].type, module_))) { errorf(pc_ + 2, "table %u is not a super-type of %s", imm.table.index, elem_type.type_name().c_str()); return false; } return true; } inline bool Validate(ElemDropImmediate<validate>& imm) { if (!VALIDATE(imm.index < module_->elem_segments.size())) { errorf(pc_ + 2, "invalid element segment index: %u", imm.index); return false; } return true; } inline bool Validate(TableCopyImmediate<validate>& imm) { if (!Validate(pc_ + 1, imm.table_src)) return false; if (!Validate(pc_ + 2, imm.table_dst)) return false; ValueType src_type = module_->tables[imm.table_src.index].type; if (!VALIDATE(IsSubtypeOf( src_type, module_->tables[imm.table_dst.index].type, module_))) { errorf(pc_ + 2, "table %u is not a super-type of %s", imm.table_dst.index, src_type.type_name().c_str()); return false; } return true; } static uint32_t OpcodeLength(WasmDecoder* decoder, const byte* pc) { WasmOpcode opcode = static_cast<WasmOpcode>(*pc); switch (opcode) { #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE) FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE { MemoryAccessImmediate<validate> imm(decoder, pc, UINT32_MAX); return 1 + imm.length; } case kExprBr: case kExprBrIf: { BranchDepthImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprGlobalGet: case kExprGlobalSet: { GlobalIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprTableGet: case kExprTableSet: { TableIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprCallFunction: case kExprReturnCall: { CallFunctionImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprCallIndirect: case kExprReturnCallIndirect: { CallIndirectImmediate<validate> imm(WasmFeatures::All(), decoder, pc); return 1 + imm.length; } case kExprTry: case kExprIf: // fall through case kExprLoop: case kExprBlock: { BlockTypeImmediate<validate> imm(WasmFeatures::All(), decoder, pc); return 1 + imm.length; } case kExprLet: { BlockTypeImmediate<validate> imm(WasmFeatures::All(), decoder, pc); uint32_t locals_length; bool locals_result = decoder->DecodeLocals(decoder->pc() + 1 + imm.length, &locals_length, base::Optional<uint32_t>()); return 1 + imm.length + (locals_result ? locals_length : 0); } case kExprThrow: { ExceptionIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprBrOnExn: { BranchOnExceptionImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprBrOnNull: { BranchDepthImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprLocalGet: case kExprLocalSet: case kExprLocalTee: { LocalIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprSelectWithType: { SelectTypeImmediate<validate> imm(WasmFeatures::All(), decoder, pc); return 1 + imm.length; } case kExprBrTable: { BranchTableImmediate<validate> imm(decoder, pc); BranchTableIterator<validate> iterator(decoder, imm); return 1 + iterator.length(); } case kExprI32Const: { ImmI32Immediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprI64Const: { ImmI64Immediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprRefNull: { RefNullImmediate<validate> imm(WasmFeatures::All(), decoder, pc); return 1 + imm.length; } case kExprRefIsNull: { RefNullImmediate<validate> imm(WasmFeatures::All(), decoder, pc); return 1 + imm.length; } case kExprRefFunc: { FunctionIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprMemoryGrow: case kExprMemorySize: { MemoryIndexImmediate<validate> imm(decoder, pc); return 1 + imm.length; } case kExprF32Const: return 5; case kExprF64Const: return 9; case kNumericPrefix: { byte numeric_index = decoder->read_u8<validate>(pc + 1, "numeric_index"); WasmOpcode opcode = static_cast<WasmOpcode>(kNumericPrefix << 8 | numeric_index); switch (opcode) { case kExprI32SConvertSatF32: case kExprI32UConvertSatF32: case kExprI32SConvertSatF64: case kExprI32UConvertSatF64: case kExprI64SConvertSatF32: case kExprI64UConvertSatF32: case kExprI64SConvertSatF64: case kExprI64UConvertSatF64: return 2; case kExprMemoryInit: { MemoryInitImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprDataDrop: { DataDropImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprMemoryCopy: { MemoryCopyImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprMemoryFill: { MemoryIndexImmediate<validate> imm(decoder, pc + 1); return 2 + imm.length; } case kExprTableInit: { TableInitImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprElemDrop: { ElemDropImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprTableCopy: { TableCopyImmediate<validate> imm(decoder, pc); return 2 + imm.length; } case kExprTableGrow: case kExprTableSize: case kExprTableFill: { TableIndexImmediate<validate> imm(decoder, pc); return 2 + imm.length; } default: decoder->error(pc, "invalid numeric opcode"); return 2; } } case kSimdPrefix: { uint32_t length = 0; opcode = decoder->read_prefixed_opcode<validate>(pc, &length); switch (opcode) { #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_SIMD_0_OPERAND_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE return 1 + length; #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_SIMD_1_OPERAND_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE return 2 + length; #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_SIMD_MEM_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE { MemoryAccessImmediate<validate> imm(decoder, pc + length, UINT32_MAX); return 1 + length + imm.length; } // Shuffles require a byte per lane, or 16 immediate bytes. case kExprS8x16Shuffle: return 1 + length + kSimd128Size; default: decoder->error(pc, "invalid SIMD opcode"); return 1 + length; } } case kAtomicPrefix: { byte atomic_index = decoder->read_u8<validate>(pc + 1, "atomic_index"); WasmOpcode opcode = static_cast<WasmOpcode>(kAtomicPrefix << 8 | atomic_index); switch (opcode) { #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_ATOMIC_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE { MemoryAccessImmediate<validate> imm(decoder, pc + 1, UINT32_MAX); return 2 + imm.length; } #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: FOREACH_ATOMIC_0_OPERAND_OPCODE(DECLARE_OPCODE_CASE) #undef DECLARE_OPCODE_CASE { return 2 + 1; } default: decoder->error(pc, "invalid Atomics opcode"); return 2; } } case kGCPrefix: { byte gc_index = decoder->read_u8<validate>(pc + 1, "gc_index"); WasmOpcode opcode = static_cast<WasmOpcode>(kGCPrefix << 8 | gc_index); switch (opcode) { case kExprStructNew: case kExprStructNewSub: case kExprStructNewDefault: { StructIndexImmediate<validate> imm(decoder, pc + 2); return 2 + imm.length; } case kExprStructGet: case kExprStructGetS: case kExprStructGetU: case kExprStructSet: { FieldIndexImmediate<validate> imm(decoder, pc + 2); return 2 + imm.length; } case kExprArrayNew: case kExprArrayNewSub: case kExprArrayNewDefault: case kExprArrayGet: case kExprArrayGetS: case kExprArrayGetU: case kExprArraySet: case kExprArrayLen: { ArrayIndexImmediate<validate> imm(decoder, pc + 2); return 2 + imm.length; } case kExprBrOnCast: { BranchDepthImmediate<validate> imm(decoder, pc + 2); return 2 + imm.length; } case kExprRttGet: case kExprRttSub: { // TODO(7748): Implement. decoder->error(pc, "rtt opcodes not implemented yet"); return 2; } case kExprI31New: case kExprI31GetS: case kExprI31GetU: case kExprRefTest: case kExprRefCast: return 2; default: // This is unreachable except for malformed modules. decoder->error(pc, "invalid gc opcode"); return 2; } } default: return 1; } } std::pair<uint32_t, uint32_t> StackEffect(const byte* pc) { WasmOpcode opcode = static_cast<WasmOpcode>(*pc); // Handle "simple" opcodes with a fixed signature first. const FunctionSig* sig = WasmOpcodes::Signature(opcode); if (!sig) sig = WasmOpcodes::AsmjsSignature(opcode); if (sig) return {sig->parameter_count(), sig->return_count()}; #define DECLARE_OPCODE_CASE(name, opcode, sig) case kExpr##name: // clang-format off switch (opcode) { case kExprSelect: case kExprSelectWithType: return {3, 1}; case kExprTableSet: FOREACH_STORE_MEM_OPCODE(DECLARE_OPCODE_CASE) return {2, 0}; FOREACH_LOAD_MEM_OPCODE(DECLARE_OPCODE_CASE) case kExprTableGet: case kExprLocalTee: case kExprMemoryGrow: case kExprRefAsNonNull: case kExprBrOnNull: case kExprRefIsNull: return {1, 1}; case kExprLocalSet: case kExprGlobalSet: case kExprDrop: case kExprBrIf: case kExprBrTable: case kExprIf: case kExprRethrow: return {1, 0}; case kExprLocalGet: case kExprGlobalGet: case kExprI32Const: case kExprI64Const: case kExprF32Const: case kExprF64Const: case kExprRefNull: case kExprRefFunc: case kExprMemorySize: return {0, 1}; case kExprCallFunction: { CallFunctionImmediate<validate> imm(this, pc); CHECK(Complete(pc, imm)); return {imm.sig->parameter_count(), imm.sig->return_count()}; } case kExprCallIndirect: { CallIndirectImmediate<validate> imm(this->enabled_, this, pc); CHECK(Complete(pc, imm)); // Indirect calls pop an additional argument for the table index. return {imm.sig->parameter_count() + 1, imm.sig->return_count()}; } case kExprThrow: { ExceptionIndexImmediate<validate> imm(this, pc); CHECK(Complete(pc, imm)); DCHECK_EQ(0, imm.exception->sig->return_count()); return {imm.exception->sig->parameter_count(), 0}; } case kExprBr: case kExprBlock: case kExprLoop: case kExprEnd: case kExprElse: case kExprTry: case kExprCatch: case kExprBrOnExn: case kExprNop: case kExprReturn: case kExprReturnCall: case kExprReturnCallIndirect: case kExprUnreachable: return {0, 0}; case kExprLet: // TODO(7748): Implement return {0, 0}; case kNumericPrefix: case kAtomicPrefix: case kSimdPrefix: { opcode = this->read_prefixed_opcode<validate>(pc); switch (opcode) { FOREACH_SIMD_1_OPERAND_1_PARAM_OPCODE(DECLARE_OPCODE_CASE) return {1, 1}; FOREACH_SIMD_1_OPERAND_2_PARAM_OPCODE(DECLARE_OPCODE_CASE) FOREACH_SIMD_MASK_OPERAND_OPCODE(DECLARE_OPCODE_CASE) return {2, 1}; default: { sig = WasmOpcodes::Signature(opcode); if (sig) { return {sig->parameter_count(), sig->return_count()}; } } } V8_FALLTHROUGH; } default: FATAL("unimplemented opcode: %x (%s)", opcode, WasmOpcodes::OpcodeName(opcode)); return {0, 0}; } #undef DECLARE_OPCODE_CASE // clang-format on } }; #define CALL_INTERFACE(name, ...) interface_.name(this, ##__VA_ARGS__) #define CALL_INTERFACE_IF_REACHABLE(name, ...) \ do { \ DCHECK(!control_.empty()); \ DCHECK_EQ(current_code_reachable_, \ this->ok() && control_.back().reachable()); \ if (current_code_reachable_) { \ interface_.name(this, ##__VA_ARGS__); \ } \ } while (false) #define CALL_INTERFACE_IF_PARENT_REACHABLE(name, ...) \ do { \ DCHECK(!control_.empty()); \ if (VALIDATE(this->ok()) && \ (control_.size() == 1 || control_at(1)->reachable())) { \ interface_.name(this, ##__VA_ARGS__); \ } \ } while (false) template <Decoder::ValidateFlag validate, typename Interface> class WasmFullDecoder : public WasmDecoder<validate> { using Value = typename Interface::Value; using Control = typename Interface::Control; using ArgVector = base::SmallVector<Value, 8>; // All Value types should be trivially copyable for performance. We push, pop, // and store them in local variables. ASSERT_TRIVIALLY_COPYABLE(Value); public: template <typename... InterfaceArgs> WasmFullDecoder(Zone* zone, const WasmModule* module, const WasmFeatures& enabled, WasmFeatures* detected, const FunctionBody& body, InterfaceArgs&&... interface_args) : WasmDecoder<validate>(module, enabled, detected, body.sig, body.start, body.end, body.offset), zone_(zone), interface_(std::forward<InterfaceArgs>(interface_args)...), local_type_vec_(zone), stack_(zone), control_(zone) { this->local_types_ = &local_type_vec_; } Interface& interface() { return interface_; } bool Decode() { DCHECK(stack_.empty()); DCHECK(control_.empty()); if (this->end_ < this->pc_) { this->error("function body end < start"); return false; } DCHECK_EQ(0, this->local_types_->size()); this->InitializeLocalsFromSig(); uint32_t locals_length; this->DecodeLocals(this->pc(), &locals_length, static_cast<uint32_t>(this->local_types_->size())); this->consume_bytes(locals_length); CALL_INTERFACE(StartFunction); DecodeFunctionBody(); if (!this->failed()) CALL_INTERFACE(FinishFunction); // Generate a better error message whether the unterminated control // structure is the function body block or an innner structure. if (control_.size() > 1) { this->error(control_.back().pc, "unterminated control structure"); } else if (control_.size() == 1) { this->error("function body must end with \"end\" opcode"); } if (this->failed()) return this->TraceFailed(); TRACE("wasm-decode %s\n\n", VALIDATE(this->ok()) ? "ok" : "failed"); return true; } bool TraceFailed() { TRACE("wasm-error module+%-6d func+%d: %s\n\n", this->error_.offset(), this->GetBufferRelativeOffset(this->error_.offset()), this->error_.message().c_str()); return false; } const char* SafeOpcodeNameAt(const byte* pc) { if (pc >= this->end_) return "<end>"; WasmOpcode opcode = static_cast<WasmOpcode>(*pc); if (!WasmOpcodes::IsPrefixOpcode(opcode)) { return WasmOpcodes::OpcodeName(static_cast<WasmOpcode>(opcode)); } opcode = this->template read_prefixed_opcode<Decoder::kValidate>(pc); return WasmOpcodes::OpcodeName(opcode); } inline Zone* zone() const { return zone_; } inline uint32_t num_locals() const { return static_cast<uint32_t>(local_type_vec_.size()); } inline ValueType GetLocalType(uint32_t index) { return local_type_vec_[index]; } inline WasmCodePosition position() { int offset = static_cast<int>(this->pc_ - this->start_); DCHECK_EQ(this->pc_ - this->start_, offset); // overflows cannot happen return offset; } inline uint32_t control_depth() const { return static_cast<uint32_t>(control_.size()); } inline Control* control_at(uint32_t depth) { DCHECK_GT(control_.size(), depth); return &control_.back() - depth; } inline uint32_t stack_size() const { DCHECK_GE(kMaxUInt32, stack_.size()); return static_cast<uint32_t>(stack_.size()); } inline Value* stack_value(uint32_t depth) { DCHECK_LT(0, depth); DCHECK_GE(stack_.size(), depth); return &*(stack_.end() - depth); } void SetSucceedingCodeDynamicallyUnreachable() { Control* current = &control_.back(); if (current->reachable()) { current->reachability = kSpecOnlyReachable; current_code_reachable_ = false; } } private: Zone* zone_; Interface interface_; ZoneVector<ValueType> local_type_vec_; // types of local variables. ZoneVector<Value> stack_; // stack of values. ZoneVector<Control> control_; // stack of blocks, loops, and ifs. // Controls whether code should be generated for the current block (basically // a cache for {ok() && control_.back().reachable()}). bool current_code_reachable_ = true; static Value UnreachableValue(const uint8_t* pc) { return Value{pc, kWasmBottom}; } bool CheckHasMemory() { if (!VALIDATE(this->module_->has_memory)) { this->error(this->pc_ - 1, "memory instruction with no memory"); return false; } return true; } bool CheckHasMemoryForAtomics() { if (FLAG_wasm_atomics_on_non_shared_memory && CheckHasMemory()) return true; if (!VALIDATE(this->module_->has_shared_memory)) { this->error(this->pc_ - 1, "Atomic opcodes used without shared memory"); return false; } return true; } class TraceLine { public: static constexpr int kMaxLen = 512; ~TraceLine() { if (!FLAG_trace_wasm_decoder) return; PrintF("%.*s\n", len_, buffer_); } // Appends a formatted string. PRINTF_FORMAT(2, 3) void Append(const char* format, ...) { if (!FLAG_trace_wasm_decoder) return; va_list va_args; va_start(va_args, format); size_t remaining_len = kMaxLen - len_; Vector<char> remaining_msg_space(buffer_ + len_, remaining_len); int len = VSNPrintF(remaining_msg_space, format, va_args); va_end(va_args); len_ += len < 0 ? remaining_len : len; } private: char buffer_[kMaxLen]; int len_ = 0; }; // Helper to avoid calling member methods (which are more expensive to call // indirectly). template <WasmOpcode opcode> static int DecodeOp(WasmFullDecoder* decoder) { return decoder->DecodeOp<opcode>(); } template <WasmOpcode opcode> int DecodeOp() { #if DEBUG TraceLine trace_msg; #define TRACE_PART(...) trace_msg.Append(__VA_ARGS__) if (!WasmOpcodes::IsPrefixOpcode(opcode)) { TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(opcode)); } #else #define TRACE_PART(...) #endif int len = 1; // TODO(clemensb): Break this up into individual functions. switch (opcode) { #define BUILD_SIMPLE_OPCODE(op, _, sig) \ case kExpr##op: \ BuildSimpleOperator_##sig(opcode); \ break; FOREACH_SIMPLE_OPCODE(BUILD_SIMPLE_OPCODE) #undef BUILD_SIMPLE_OPCODE case kExprNop: break; case kExprBlock: { BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; ArgVector args = PopArgs(imm.sig); Control* block = PushControl(kControlBlock); SetBlockType(block, imm, args.begin()); CALL_INTERFACE_IF_REACHABLE(Block, block); PushMergeValues(block, &block->start_merge); len = 1 + imm.length; break; } case kExprRethrow: { CHECK_PROTOTYPE_OPCODE(eh); Value exception = Pop(0, kWasmExnRef); CALL_INTERFACE_IF_REACHABLE(Rethrow, exception); EndControl(); break; } case kExprThrow: { CHECK_PROTOTYPE_OPCODE(eh); ExceptionIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; ArgVector args = PopArgs(imm.exception->ToFunctionSig()); CALL_INTERFACE_IF_REACHABLE(Throw, imm, VectorOf(args)); EndControl(); break; } case kExprTry: { CHECK_PROTOTYPE_OPCODE(eh); BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; ArgVector args = PopArgs(imm.sig); Control* try_block = PushControl(kControlTry); SetBlockType(try_block, imm, args.begin()); len = 1 + imm.length; CALL_INTERFACE_IF_REACHABLE(Try, try_block); PushMergeValues(try_block, &try_block->start_merge); break; } case kExprCatch: { CHECK_PROTOTYPE_OPCODE(eh); if (!VALIDATE(!control_.empty())) { this->error("catch does not match any try"); break; } Control* c = &control_.back(); if (!VALIDATE(c->is_try())) { this->error("catch does not match any try"); break; } if (!VALIDATE(c->is_incomplete_try())) { this->error("catch already present for try"); break; } c->kind = kControlTryCatch; FallThruTo(c); stack_.erase(stack_.begin() + c->stack_depth, stack_.end()); c->reachability = control_at(1)->innerReachability(); current_code_reachable_ = this->ok() && c->reachable(); Value* exception = Push(kWasmExnRef); CALL_INTERFACE_IF_PARENT_REACHABLE(Catch, c, exception); break; } case kExprBrOnExn: { CHECK_PROTOTYPE_OPCODE(eh); BranchOnExceptionImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm.depth, control_.size())) break; if (!this->Validate(this->pc_ + imm.depth.length, imm.index)) break; Control* c = control_at(imm.depth.depth); Value exception = Pop(0, kWasmExnRef); const WasmExceptionSig* sig = imm.index.exception->sig; size_t value_count = sig->parameter_count(); // TODO(wasm): This operand stack mutation is an ugly hack to make // both type checking here as well as environment merging in the // graph builder interface work out of the box. We should introduce // special handling for both and do minimal/no stack mutation here. for (size_t i = 0; i < value_count; ++i) Push(sig->GetParam(i)); Vector<Value> values(stack_.data() + c->stack_depth, value_count); TypeCheckBranchResult check_result = TypeCheckBranch(c, true); if (this->failed()) break; if (V8_LIKELY(check_result == kReachableBranch)) { CALL_INTERFACE(BrOnException, exception, imm.index, imm.depth.depth, values); c->br_merge()->reached = true; } else if (check_result == kInvalidStack) { break; } len = 1 + imm.length; for (size_t i = 0; i < value_count; ++i) Pop(); Value* pexception = Push(kWasmExnRef); *pexception = exception; break; } case kExprBrOnNull: { CHECK_PROTOTYPE_OPCODE(typed_funcref); BranchDepthImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm, control_.size())) break; len = 1 + imm.length; Value ref_object = Pop(); if (this->failed()) break; Control* c = control_at(imm.depth); TypeCheckBranchResult check_result = TypeCheckBranch(c, true); if (V8_LIKELY(check_result == kReachableBranch)) { switch (ref_object.type.kind()) { case ValueType::kRef: { Value* result = Push(ref_object.type); CALL_INTERFACE(PassThrough, ref_object, result); break; } case ValueType::kOptRef: { // We need to Push the result value after calling BrOnNull on // the interface. Therefore we must sync the ref_object and // result nodes afterwards (in PassThrough). CALL_INTERFACE(BrOnNull, ref_object, imm.depth); Value* result = Push( ValueType::Ref(ref_object.type.heap_type(), kNonNullable)); CALL_INTERFACE(PassThrough, ref_object, result); c->br_merge()->reached = true; break; } default: this->error(this->pc_, "invalid agrument type to ref.as_non_null"); break; } } break; } case kExprLet: { CHECK_PROTOTYPE_OPCODE(typed_funcref); BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; uint32_t current_local_count = static_cast<uint32_t>(local_type_vec_.size()); // Temporarily add the let-defined values // to the beginning of the function locals. uint32_t locals_length; if (!this->DecodeLocals(this->pc() + 1 + imm.length, &locals_length, 0)) { break; } len = 1 + imm.length + locals_length; uint32_t locals_count = static_cast<uint32_t>(local_type_vec_.size() - current_local_count); ArgVector let_local_values = PopArgs(static_cast<uint32_t>(imm.in_arity()), VectorOf(local_type_vec_.data(), locals_count)); ArgVector args = PopArgs(imm.sig); Control* let_block = PushControl(kControlLet, locals_count); SetBlockType(let_block, imm, args.begin()); CALL_INTERFACE_IF_REACHABLE(Block, let_block); PushMergeValues(let_block, &let_block->start_merge); CALL_INTERFACE_IF_REACHABLE(AllocateLocals, VectorOf(let_local_values)); break; } case kExprLoop: { BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; ArgVector args = PopArgs(imm.sig); Control* block = PushControl(kControlLoop); SetBlockType(&control_.back(), imm, args.begin()); len = 1 + imm.length; CALL_INTERFACE_IF_REACHABLE(Loop, block); PushMergeValues(block, &block->start_merge); break; } case kExprIf: { BlockTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(imm)) break; Value cond = Pop(0, kWasmI32); ArgVector args = PopArgs(imm.sig); if (!VALIDATE(this->ok())) break; Control* if_block = PushControl(kControlIf); SetBlockType(if_block, imm, args.begin()); CALL_INTERFACE_IF_REACHABLE(If, cond, if_block); len = 1 + imm.length; PushMergeValues(if_block, &if_block->start_merge); break; } case kExprElse: { if (!VALIDATE(!control_.empty())) { this->error("else does not match any if"); break; } Control* c = &control_.back(); if (!VALIDATE(c->is_if())) { this->error(this->pc_, "else does not match an if"); break; } if (c->is_if_else()) { this->error(this->pc_, "else already present for if"); break; } if (!TypeCheckFallThru()) break; c->kind = kControlIfElse; CALL_INTERFACE_IF_PARENT_REACHABLE(Else, c); if (c->reachable()) c->end_merge.reached = true; PushMergeValues(c, &c->start_merge); c->reachability = control_at(1)->innerReachability(); current_code_reachable_ = this->ok() && c->reachable(); break; } case kExprEnd: { if (!VALIDATE(!control_.empty())) { this->error("end does not match any if, try, or block"); break; } Control* c = &control_.back(); if (!VALIDATE(!c->is_incomplete_try())) { this->error(this->pc_, "missing catch or catch-all in try"); break; } if (c->is_onearmed_if()) { if (!VALIDATE(c->end_merge.arity == c->start_merge.arity)) { this->error(c->pc, "start-arity and end-arity of one-armed if must match"); break; } if (!TypeCheckOneArmedIf(c)) break; } if (c->is_let()) { this->local_types_->erase( this->local_types_->begin(), this->local_types_->begin() + c->locals_count); CALL_INTERFACE_IF_REACHABLE(DeallocateLocals, c->locals_count); } if (!TypeCheckFallThru()) break; if (control_.size() == 1) { // If at the last (implicit) control, check we are at end. if (!VALIDATE(this->pc_ + 1 == this->end_)) { this->error(this->pc_ + 1, "trailing code after function end"); break; } // The result of the block is the return value. TRACE_PART("\n" TRACE_INST_FORMAT, startrel(this->pc_), "(implicit) return"); DoReturn(); control_.clear(); break; } PopControl(c); break; } case kExprSelect: { Value cond = Pop(2, kWasmI32); Value fval = Pop(); Value tval = Pop(0, fval.type); ValueType type = tval.type == kWasmBottom ? fval.type : tval.type; if (type.is_reference_type()) { this->error( "select without type is only valid for value type inputs"); break; } Value* result = Push(type); CALL_INTERFACE_IF_REACHABLE(Select, cond, fval, tval, result); break; } case kExprSelectWithType: { CHECK_PROTOTYPE_OPCODE(reftypes); SelectTypeImmediate<validate> imm(this->enabled_, this, this->pc_); if (this->failed()) break; Value cond = Pop(2, kWasmI32); Value fval = Pop(1, imm.type); Value tval = Pop(0, imm.type); Value* result = Push(imm.type); CALL_INTERFACE_IF_REACHABLE(Select, cond, fval, tval, result); len = 1 + imm.length; break; } case kExprBr: { BranchDepthImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm, control_.size())) break; Control* c = control_at(imm.depth); TypeCheckBranchResult check_result = TypeCheckBranch(c, false); if (V8_LIKELY(check_result == kReachableBranch)) { if (imm.depth == control_.size() - 1) { DoReturn(); } else { CALL_INTERFACE(Br, c); c->br_merge()->reached = true; } } else if (check_result == kInvalidStack) { break; } len = 1 + imm.length; EndControl(); break; } case kExprBrIf: { BranchDepthImmediate<validate> imm(this, this->pc_); Value cond = Pop(0, kWasmI32); if (this->failed()) break; if (!this->Validate(this->pc_, imm, control_.size())) break; Control* c = control_at(imm.depth); TypeCheckBranchResult check_result = TypeCheckBranch(c, true); if (V8_LIKELY(check_result == kReachableBranch)) { CALL_INTERFACE(BrIf, cond, imm.depth); c->br_merge()->reached = true; } else if (check_result == kInvalidStack) { break; } len = 1 + imm.length; break; } case kExprBrTable: { BranchTableImmediate<validate> imm(this, this->pc_); BranchTableIterator<validate> iterator(this, imm); Value key = Pop(0, kWasmI32); if (this->failed()) break; if (!this->Validate(this->pc_, imm, control_.size())) break; // Cache the branch targets during the iteration, so that we can set // all branch targets as reachable after the {CALL_INTERFACE} call. std::vector<bool> br_targets(control_.size()); // The result types of the br_table instruction. We have to check the // stack against these types. Only needed during validation. std::vector<ValueType> result_types; while (iterator.has_next()) { const uint32_t index = iterator.cur_index(); const byte* pos = iterator.pc(); uint32_t target = iterator.next(); if (!VALIDATE(ValidateBrTableTarget(target, pos, index))) break; // Avoid redundant branch target checks. if (br_targets[target]) continue; br_targets[target] = true; if (validate) { if (index == 0) { // With the first branch target, initialize the result types. result_types = InitializeBrTableResultTypes(target); } else if (!UpdateBrTableResultTypes(&result_types, target, pos, index)) { break; } } } if (!VALIDATE(TypeCheckBrTable(result_types))) break; DCHECK(this->ok()); if (current_code_reachable_) { CALL_INTERFACE(BrTable, imm, key); for (int i = 0, e = control_depth(); i < e; ++i) { if (!br_targets[i]) continue; control_at(i)->br_merge()->reached = true; } } len = 1 + iterator.length(); EndControl(); break; } case kExprReturn: { if (V8_LIKELY(current_code_reachable_)) { if (!VALIDATE(TypeCheckReturn())) break; DoReturn(); } else { // We pop all return values from the stack to check their type. // Since we deal with unreachable code, we do not have to keep the // values. int num_returns = static_cast<int>(this->sig_->return_count()); for (int i = num_returns - 1; i >= 0; --i) { Pop(i, this->sig_->GetReturn(i)); } } EndControl(); break; } case kExprUnreachable: { CALL_INTERFACE_IF_REACHABLE(Unreachable); EndControl(); break; } case kExprI32Const: { ImmI32Immediate<validate> imm(this, this->pc_); Value* value = Push(kWasmI32); CALL_INTERFACE_IF_REACHABLE(I32Const, value, imm.value); len = 1 + imm.length; break; } case kExprI64Const: { ImmI64Immediate<validate> imm(this, this->pc_); Value* value = Push(kWasmI64); CALL_INTERFACE_IF_REACHABLE(I64Const, value, imm.value); len = 1 + imm.length; break; } case kExprF32Const: { ImmF32Immediate<validate> imm(this, this->pc_); Value* value = Push(kWasmF32); CALL_INTERFACE_IF_REACHABLE(F32Const, value, imm.value); len = 1 + imm.length; break; } case kExprF64Const: { ImmF64Immediate<validate> imm(this, this->pc_); Value* value = Push(kWasmF64); CALL_INTERFACE_IF_REACHABLE(F64Const, value, imm.value); len = 1 + imm.length; break; } case kExprRefNull: { CHECK_PROTOTYPE_OPCODE(reftypes); RefNullImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(this->pc_, imm)) break; Value* value = Push(imm.type); CALL_INTERFACE_IF_REACHABLE(RefNull, value); len = 1 + imm.length; break; } case kExprRefIsNull: { CHECK_PROTOTYPE_OPCODE(reftypes); RefNullImmediate<validate> imm(this->enabled_, this, this->pc_); if (!this->Validate(this->pc_, imm)) break; Value value = Pop(0, imm.type); Value* result = Push(kWasmI32); CALL_INTERFACE_IF_REACHABLE(UnOp, opcode, value, result); len = 1 + imm.length; break; } case kExprRefFunc: { CHECK_PROTOTYPE_OPCODE(reftypes); FunctionIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; Value* value = Push(ValueType::Ref(kHeapFunc, kNonNullable)); CALL_INTERFACE_IF_REACHABLE(RefFunc, imm.index, value); len = 1 + imm.length; break; } case kExprRefAsNonNull: { CHECK_PROTOTYPE_OPCODE(typed_funcref); Value value = Pop(); switch (value.type.kind()) { case ValueType::kRef: { Value* result = Push(value.type); CALL_INTERFACE_IF_REACHABLE(PassThrough, value, result); break; } case ValueType::kOptRef: { Value* result = Push(ValueType::Ref(value.type.heap_type(), kNonNullable)); CALL_INTERFACE_IF_REACHABLE(RefAsNonNull, value, result); break; } default: this->error(this->pc_ + 1, "invalid agrument type to ref.as_non_null"); break; } break; } case kExprLocalGet: { LocalIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; Value* value = Push(imm.type); CALL_INTERFACE_IF_REACHABLE(LocalGet, value, imm); len = 1 + imm.length; break; } case kExprLocalSet: { LocalIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; Value value = Pop(0, local_type_vec_[imm.index]); CALL_INTERFACE_IF_REACHABLE(LocalSet, value, imm); len = 1 + imm.length; break; } case kExprLocalTee: { LocalIndexImmediate<validate> imm(this, this->pc_); if (!this->Validate(this->pc_, imm)) break; Value value = Pop(0, local_type_vec_[imm.index]); Value* result = Push(value.type); CALL_INTERFACE_IF_REACHABLE(LocalTee, value, result, imm); len = 1 + imm.length; break; } case kExprDrop: { Value value = Pop(); CALL_INTERFACE_IF_REACHABLE(Drop, value); break; } case kExprGlobalGet: { GlobalIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; Value* result = Push(imm.type); CALL_INTERFACE_IF_REACHABLE(GlobalGet, result, imm); break; } case kExprGlobalSet: { GlobalIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; if (!VALIDATE(imm.global->mutability)) { this->errorf(this->pc_, "immutable global #%u cannot be assigned", imm.index); break; } Value value = Pop(0, imm.type); CALL_INTERFACE_IF_REACHABLE(GlobalSet, value, imm); break; } case kExprTableGet: { CHECK_PROTOTYPE_OPCODE(reftypes); TableIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; Value index = Pop(0, kWasmI32); Value* result = Push(this->module_->tables[imm.index].type); CALL_INTERFACE_IF_REACHABLE(TableGet, index, result, imm); break; } case kExprTableSet: { CHECK_PROTOTYPE_OPCODE(reftypes); TableIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; Value value = Pop(1, this->module_->tables[imm.index].type); Value index = Pop(0, kWasmI32); CALL_INTERFACE_IF_REACHABLE(TableSet, index, value, imm); break; } case kExprI32LoadMem8S: len = 1 + DecodeLoadMem(LoadType::kI32Load8S); break; case kExprI32LoadMem8U: len = 1 + DecodeLoadMem(LoadType::kI32Load8U); break; case kExprI32LoadMem16S: len = 1 + DecodeLoadMem(LoadType::kI32Load16S); break; case kExprI32LoadMem16U: len = 1 + DecodeLoadMem(LoadType::kI32Load16U); break; case kExprI32LoadMem: len = 1 + DecodeLoadMem(LoadType::kI32Load); break; case kExprI64LoadMem8S: len = 1 + DecodeLoadMem(LoadType::kI64Load8S); break; case kExprI64LoadMem8U: len = 1 + DecodeLoadMem(LoadType::kI64Load8U); break; case kExprI64LoadMem16S: len = 1 + DecodeLoadMem(LoadType::kI64Load16S); break; case kExprI64LoadMem16U: len = 1 + DecodeLoadMem(LoadType::kI64Load16U); break; case kExprI64LoadMem32S: len = 1 + DecodeLoadMem(LoadType::kI64Load32S); break; case kExprI64LoadMem32U: len = 1 + DecodeLoadMem(LoadType::kI64Load32U); break; case kExprI64LoadMem: len = 1 + DecodeLoadMem(LoadType::kI64Load); break; case kExprF32LoadMem: len = 1 + DecodeLoadMem(LoadType::kF32Load); break; case kExprF64LoadMem: len = 1 + DecodeLoadMem(LoadType::kF64Load); break; case kExprI32StoreMem8: len = 1 + DecodeStoreMem(StoreType::kI32Store8); break; case kExprI32StoreMem16: len = 1 + DecodeStoreMem(StoreType::kI32Store16); break; case kExprI32StoreMem: len = 1 + DecodeStoreMem(StoreType::kI32Store); break; case kExprI64StoreMem8: len = 1 + DecodeStoreMem(StoreType::kI64Store8); break; case kExprI64StoreMem16: len = 1 + DecodeStoreMem(StoreType::kI64Store16); break; case kExprI64StoreMem32: len = 1 + DecodeStoreMem(StoreType::kI64Store32); break; case kExprI64StoreMem: len = 1 + DecodeStoreMem(StoreType::kI64Store); break; case kExprF32StoreMem: len = 1 + DecodeStoreMem(StoreType::kF32Store); break; case kExprF64StoreMem: len = 1 + DecodeStoreMem(StoreType::kF64Store); break; case kExprMemoryGrow: { if (!CheckHasMemory()) break; MemoryIndexImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!VALIDATE(this->module_->origin == kWasmOrigin)) { this->error("grow_memory is not supported for asmjs modules"); break; } Value value = Pop(0, kWasmI32); Value* result = Push(kWasmI32); CALL_INTERFACE_IF_REACHABLE(MemoryGrow, value, result); break; } case kExprMemorySize: { if (!CheckHasMemory()) break; MemoryIndexImmediate<validate> imm(this, this->pc_); Value* result = Push(kWasmI32); len = 1 + imm.length; CALL_INTERFACE_IF_REACHABLE(CurrentMemoryPages, result); break; } case kExprCallFunction: { CallFunctionImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; ArgVector args = PopArgs(imm.sig); Value* returns = PushReturns(imm.sig); CALL_INTERFACE_IF_REACHABLE(CallDirect, imm, args.begin(), returns); break; } case kExprCallIndirect: { CallIndirectImmediate<validate> imm(this->enabled_, this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; Value index = Pop(0, kWasmI32); ArgVector args = PopArgs(imm.sig); Value* returns = PushReturns(imm.sig); CALL_INTERFACE_IF_REACHABLE(CallIndirect, index, imm, args.begin(), returns); break; } case kExprReturnCall: { CHECK_PROTOTYPE_OPCODE(return_call); CallFunctionImmediate<validate> imm(this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; if (!this->CanReturnCall(imm.sig)) { OPCODE_ERROR(opcode, "tail call return types mismatch"); break; } ArgVector args = PopArgs(imm.sig); CALL_INTERFACE_IF_REACHABLE(ReturnCall, imm, args.begin()); EndControl(); break; } case kExprReturnCallIndirect: { CHECK_PROTOTYPE_OPCODE(return_call); CallIndirectImmediate<validate> imm(this->enabled_, this, this->pc_); len = 1 + imm.length; if (!this->Validate(this->pc_, imm)) break; if (!this->CanReturnCall(imm.sig)) { OPCODE_ERROR(opcode, "tail call return types mismatch"); break; } Value index = Pop(0, kWasmI32); ArgVector args = PopArgs(imm.sig); CALL_INTERFACE_IF_REACHABLE(ReturnCallIndirect, index, imm, args.begin()); EndControl(); break; } case kNumericPrefix: { ++len; byte numeric_index = this->template read_u8<validate>(this->pc_ + 1, "numeric index"); WasmOpcode full_opcode = static_cast<WasmOpcode>(opcode << 8 | numeric_index); if (full_opcode == kExprTableGrow || full_opcode == kExprTableSize || full_opcode == kExprTableFill) { CHECK_PROTOTYPE_OPCODE(reftypes); } else if (full_opcode >= kExprMemoryInit) { CHECK_PROTOTYPE_OPCODE(bulk_memory); } TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(full_opcode)); len += DecodeNumericOpcode(full_opcode); break; } case kSimdPrefix: { CHECK_PROTOTYPE_OPCODE(simd); uint32_t length = 0; WasmOpcode full_opcode = this->template read_prefixed_opcode<validate>(this->pc_, &length); if (!VALIDATE(this->ok())) break; len += length; TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(full_opcode)); len += DecodeSimdOpcode(full_opcode, length); break; } case kAtomicPrefix: { CHECK_PROTOTYPE_OPCODE(threads); len++; byte atomic_index = this->template read_u8<validate>(this->pc_ + 1, "atomic index"); WasmOpcode full_opcode = static_cast<WasmOpcode>(opcode << 8 | atomic_index); TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(full_opcode)); len += DecodeAtomicOpcode(full_opcode); break; } case kGCPrefix: { CHECK_PROTOTYPE_OPCODE(gc); byte gc_index = this->template read_u8<validate>(this->pc_ + 1, "gc index"); WasmOpcode full_opcode = static_cast<WasmOpcode>(opcode << 8 | gc_index); TRACE_PART(TRACE_INST_FORMAT, startrel(this->pc_), WasmOpcodes::OpcodeName(full_opcode)); len = DecodeGCOpcode(full_opcode); break; } // Note that prototype opcodes are not handled in the fastpath // above this switch, to avoid checking a feature flag. #define SIMPLE_PROTOTYPE_CASE(name, opc, sig) \ case kExpr##name: /* fallthrough */ FOREACH_SIMPLE_PROTOTYPE_OPCODE(SIMPLE_PROTOTYPE_CASE) #undef SIMPLE_PROTOTYPE_CASE BuildSimplePrototypeOperator(opcode); break; default: { // Deal with special asmjs opcodes. if (is_asmjs_module(this->module_)) { const FunctionSig* sig = WasmOpcodes::AsmjsSignature(opcode); if (sig) { BuildSimpleOperator(opcode, sig); } } else { this->error("Invalid opcode"); return 0; } } } #if DEBUG if (FLAG_trace_wasm_decoder) { TRACE_PART(" "); for (Control& c : control_) { switch (c.kind) { case kControlIf: TRACE_PART("I"); break; case kControlBlock: TRACE_PART("B"); break; case kControlLoop: TRACE_PART("L"); break; case kControlTry: TRACE_PART("T"); break; case kControlIfElse: case kControlTryCatch: case kControlLet: // TODO(7748): Implement break; } if (c.start_merge.arity) TRACE_PART("%u-", c.start_merge.arity); TRACE_PART("%u", c.end_merge.arity); if (!c.reachable()) TRACE_PART("%c", c.unreachable() ? '*' : '#'); } TRACE_PART(" | "); for (size_t i = 0; i < stack_.size(); ++i) { Value& val = stack_[i]; WasmOpcode val_opcode = static_cast<WasmOpcode>(*val.pc); if (WasmOpcodes::IsPrefixOpcode(val_opcode)) { val_opcode = this->template read_prefixed_opcode<Decoder::kNoValidate>(val.pc); } TRACE_PART(" %c@%d:%s", val.type.short_name(), static_cast<int>(val.pc - this->start_), WasmOpcodes::OpcodeName(val_opcode)); // If the decoder failed, don't try to decode the immediates, as this // can trigger a DCHECK failure. if (this->failed()) continue; switch (val_opcode) { case kExprI32Const: { ImmI32Immediate<Decoder::kNoValidate> imm(this, val.pc); TRACE_PART("[%d]", imm.value); break; } case kExprLocalGet: case kExprLocalSet: case kExprLocalTee: { LocalIndexImmediate<Decoder::kNoValidate> imm(this, val.pc); TRACE_PART("[%u]", imm.index); break; } case kExprGlobalGet: case kExprGlobalSet: { GlobalIndexImmediate<Decoder::kNoValidate> imm(this, val.pc); TRACE_PART("[%u]", imm.index); break; } default: break; } } } #endif return len; } using OpcodeHandler = int (*)(WasmFullDecoder*); template <size_t idx> struct GetOpcodeHandlerTableEntry : public std::integral_constant< OpcodeHandler, &WasmFullDecoder::DecodeOp<static_cast<WasmOpcode>(idx)>> {}; OpcodeHandler GetOpcodeHandler(uint8_t opcode) { static constexpr std::array<OpcodeHandler, 256> kOpcodeHandlers = base::make_array<256, GetOpcodeHandlerTableEntry>(); return kOpcodeHandlers[opcode]; } void DecodeFunctionBody() { TRACE("wasm-decode %p...%p (module+%u, %d bytes)\n", this->start(), this->end(), this->pc_offset(), static_cast<int>(this->end() - this->start())); // Set up initial function block. { Control* c = PushControl(kControlBlock); InitMerge(&c->start_merge, 0, [](uint32_t) -> Value { UNREACHABLE(); }); InitMerge(&c->end_merge, static_cast<uint32_t>(this->sig_->return_count()), [&](uint32_t i) { return Value{this->pc_, this->sig_->GetReturn(i)}; }); CALL_INTERFACE(StartFunctionBody, c); } // Decode the function body. while (this->pc_ < this->end_) { uint8_t first_byte = *this->pc_; CALL_INTERFACE_IF_REACHABLE(NextInstruction, static_cast<WasmOpcode>(first_byte)); OpcodeHandler handler = GetOpcodeHandler(first_byte); int len = (*handler)(this); this->pc_ += len; } if (!VALIDATE(this->pc_ == this->end_) && this->ok()) { this->error("Beyond end of code"); } } void EndControl() { DCHECK(!control_.empty()); Control* current = &control_.back(); stack_.erase(stack_.begin() + current->stack_depth, stack_.end()); CALL_INTERFACE_IF_REACHABLE(EndControl, current); current->reachability = kUnreachable; current_code_reachable_ = false; } template <typename func> void InitMerge(Merge<Value>* merge, uint32_t arity, func get_val) { merge->arity = arity; if (arity == 1) { merge->vals.first = get_val(0); } else if (arity > 1) { merge->vals.array = zone_->NewArray<Value>(arity); for (uint32_t i = 0; i < arity; i++) { merge->vals.array[i] = get_val(i); } } } void SetBlockType(Control* c, BlockTypeImmediate<validate>& imm, Value* args) { const byte* pc = this->pc_; InitMerge(&c->end_merge, imm.out_arity(), [pc, &imm](uint32_t i) { return Value{pc, imm.out_type(i)}; }); InitMerge(&c->start_merge, imm.in_arity(), [args](uint32_t i) { return args[i]; }); } // Pops arguments as required by signature. V8_INLINE ArgVector PopArgs(const FunctionSig* sig) { int count = sig ? static_cast<int>(sig->parameter_count()) : 0; ArgVector args(count); for (int i = count - 1; i >= 0; --i) { args[i] = Pop(i, sig->GetParam(i)); } return args; } V8_INLINE ArgVector PopArgs(const StructType* type) { int count = static_cast<int>(type->field_count()); ArgVector args(count); for (int i = count - 1; i >= 0; i--) { args[i] = Pop(i, type->field(i).Unpacked()); } return args; } V8_INLINE ArgVector PopArgs(uint32_t base_index, Vector<ValueType> arg_types) { ArgVector args(arg_types.size()); for (int i = static_cast<int>(arg_types.size()) - 1; i >= 0; i--) { args[i] = Pop(base_index + i, arg_types[i]); } return args; } ValueType GetReturnType(const FunctionSig* sig) { DCHECK_GE(1, sig->return_count()); return sig->return_count() == 0 ? kWasmStmt : sig->GetReturn(); } Control* PushControl(ControlKind kind, uint32_t locals_count = 0) { Reachability reachability = control_.empty() ? kReachable : control_.back().innerReachability(); control_.emplace_back(kind, locals_count, stack_size(), this->pc_, reachability); current_code_reachable_ = this->ok() && reachability == kReachable; return &control_.back(); } void PopControl(Control* c) { DCHECK_EQ(c, &control_.back()); CALL_INTERFACE_IF_PARENT_REACHABLE(PopControl, c); // A loop just leaves the values on the stack. if (!c->is_loop()) PushMergeValues(c, &c->end_merge); bool parent_reached = c->reachable() || c->end_merge.reached || c->is_onearmed_if(); control_.pop_back(); // If the parent block was reachable before, but the popped control does not // return to here, this block becomes "spec only reachable". if (!parent_reached) SetSucceedingCodeDynamicallyUnreachable(); current_code_reachable_ = control_.back().reachable(); } int DecodeLoadMem(LoadType type, int prefix_len = 0) { if (!CheckHasMemory()) return 0; MemoryAccessImmediate<validate> imm(this, this->pc_ + prefix_len, type.size_log_2()); Value index = Pop(0, kWasmI32); Value* result = Push(type.value_type()); CALL_INTERFACE_IF_REACHABLE(LoadMem, type, imm, index, result); return imm.length; } int DecodeLoadTransformMem(LoadType type, LoadTransformationKind transform, uint32_t opcode_length) { if (!CheckHasMemory()) return 0; // Load extends always load 64-bits. uint32_t max_alignment = transform == LoadTransformationKind::kExtend ? 3 : type.size_log_2(); MemoryAccessImmediate<validate> imm(this, this->pc_ + opcode_length, max_alignment); Value index = Pop(0, kWasmI32); Value* result = Push(kWasmS128); CALL_INTERFACE_IF_REACHABLE(LoadTransform, type, transform, imm, index, result); return imm.length; } int DecodeStoreMem(StoreType store, int prefix_len = 0) { if (!CheckHasMemory()) return 0; MemoryAccessImmediate<validate> imm(this, this->pc_ + prefix_len, store.size_log_2()); Value value = Pop(1, store.value_type()); Value index = Pop(0, kWasmI32); CALL_INTERFACE_IF_REACHABLE(StoreMem, store, imm, index, value); return imm.length; } bool ValidateBrTableTarget(uint32_t target, const byte* pos, int index) { if (!VALIDATE(target < this->control_.size())) { this->errorf(pos, "improper branch in br_table target %u (depth %u)", index, target); return false; } return true; } std::vector<ValueType> InitializeBrTableResultTypes(uint32_t target) { Merge<Value>* merge = control_at(target)->br_merge(); int br_arity = merge->arity; std::vector<ValueType> result(br_arity); for (int i = 0; i < br_arity; ++i) { result[i] = (*merge)[i].type; } return result; } bool UpdateBrTableResultTypes(std::vector<ValueType>* result_types, uint32_t target, const byte* pos, int index) { Merge<Value>* merge = control_at(target)->br_merge(); int br_arity = merge->arity; // First we check if the arities match. if (br_arity != static_cast<int>(result_types->size())) { this->errorf(pos, "inconsistent arity in br_table target %u (previous was " "%zu, this one is %u)", index, result_types->size(), br_arity); return false; } for (int i = 0; i < br_arity; ++i) { if (this->enabled_.has_reftypes()) { // The expected type is the biggest common sub type of all targets. ValueType type = (*result_types)[i]; (*result_types)[i] = CommonSubtype((*result_types)[i], (*merge)[i].type, this->module_); if ((*result_types)[i] == kWasmBottom) { this->errorf(pos, "inconsistent type in br_table target %u (previous " "was %s, this one is %s)", index, type.type_name().c_str(), (*merge)[i].type.type_name().c_str()); return false; } } else { // All target must have the same signature. if ((*result_types)[i] != (*merge)[i].type) { this->errorf(pos, "inconsistent type in br_table target %u (previous " "was %s, this one is %s)", index, (*result_types)[i].type_name().c_str(), (*merge)[i].type.type_name().c_str()); return false; } } } return true; } bool TypeCheckBrTable(const std::vector<ValueType>& result_types) { int br_arity = static_cast<int>(result_types.size()); if (V8_LIKELY(!control_.back().unreachable())) { int available = static_cast<int>(stack_.size()) - control_.back().stack_depth; // There have to be enough values on the stack. if (available < br_arity) { this->errorf(this->pc_, "expected %u elements on the stack for branch to " "@%d, found %u", br_arity, startrel(control_.back().pc), available); return false; } Value* stack_values = &*(stack_.end() - br_arity); // Type-check the topmost br_arity values on the stack. for (int i = 0; i < br_arity; ++i) { Value& val = stack_values[i]; if (!IsSubtypeOf(val.type, result_types[i], this->module_)) { this->errorf(this->pc_, "type error in merge[%u] (expected %s, got %s)", i, result_types[i].type_name().c_str(), val.type.type_name().c_str()); return false; } } } else { // !control_.back().reachable() // Pop values from the stack, accoring to the expected signature. for (int i = 0; i < br_arity; ++i) Pop(i + 1, result_types[i]); } return this->ok(); } uint32_t SimdExtractLane(WasmOpcode opcode, ValueType type, uint32_t opcode_length) { SimdLaneImmediate<validate> imm(this, this->pc_, opcode_length); if (this->Validate(this->pc_, opcode, imm)) { Value inputs[] = {Pop(0, kWasmS128)}; Value* result = Push(type); CALL_INTERFACE_IF_REACHABLE(SimdLaneOp, opcode, imm, ArrayVector(inputs), result); } return imm.length; } uint32_t SimdReplaceLane(WasmOpcode opcode, ValueType type, uint32_t opcode_length) { SimdLaneImmediate<validate> imm(this, this->pc_, opcode_length); if (this->Validate(this->pc_, opcode, imm)) { Value inputs[2] = {UnreachableValue(this->pc_), UnreachableValue(this->pc_)}; inputs[1] = Pop(1, type); inputs[0] = Pop(0, kWasmS128); Value* result = Push(kWasmS128); CALL_INTERFACE_IF_REACHABLE(SimdLaneOp, opcode, imm, ArrayVector(inputs), result); } return imm.length; } uint32_t Simd8x16ShuffleOp(uint32_t opcode_length) { Simd8x16ShuffleImmediate<validate> imm(this, this->pc_, opcode_length); if (this->Validate(this->pc_, imm)) { Value input1 = Pop(1, kWasmS128); Value input0 = Pop(0, kWasmS128); Value* result = Push(kWasmS128); CALL_INTERFACE_IF_REACHABLE(Simd8x16ShuffleOp, imm, input0, input1, result); } return 16; } uint32_t DecodeSimdOpcode(WasmOpcode opcode, uint32_t opcode_length) { // opcode_length is the number of bytes that this SIMD-specific opcode takes // up in the LEB128 encoded form. uint32_t len = 0; switch (opcode) { case kExprF64x2ExtractLane: { len = SimdExtractLane(opcode, kWasmF64, opcode_length); break; } case kExprF32x4ExtractLane: { len = SimdExtractLane(opcode, kWasmF32, opcode_length); break; } case kExprI64x2ExtractLane: { len = SimdExtractLane(opcode, kWasmI64, opcode_length); break; } case kExprI32x4ExtractLane: case kExprI16x8ExtractLaneS: case kExprI16x8ExtractLaneU: case kExprI8x16ExtractLaneS: case kExprI8x16ExtractLaneU: { len = SimdExtractLane(opcode, kWasmI32, opcode_length); break; } case kExprF64x2ReplaceLane: { len = SimdReplaceLane(opcode, kWasmF64, opcode_length); break; } case kExprF32x4ReplaceLane: { len = SimdReplaceLane(opcode, kWasmF32, opcode_length); break; } case kExprI64x2ReplaceLane: { len = SimdReplaceLane(opcode, kWasmI64, opcode_length); break; } case kExprI32x4ReplaceLane: case kExprI16x8ReplaceLane: case kExprI8x16ReplaceLane: { len = SimdReplaceLane(opcode, kWasmI32, opcode_length); break; } case kExprS8x16Shuffle: { len = Simd8x16ShuffleOp(opcode_length); break; } case kExprS128LoadMem: len = DecodeLoadMem(LoadType::kS128Load, opcode_length); break; case kExprS128StoreMem: len = DecodeStoreMem(StoreType::kS128Store, opcode_length); break; case kExprS8x16LoadSplat: len = DecodeLoadTransformMem(LoadType::kI32Load8S, LoadTransformationKind::kSplat, opcode_length); break; case kExprS16x8LoadSplat: len = DecodeLoadTransformMem(LoadType::kI32Load16S, LoadTransformationKind::kSplat, opcode_length); break; case kExprS32x4LoadSplat: len = DecodeLoadTransformMem( LoadType::kI32Load, LoadTransformationKind::kSplat, opcode_length); break; case kExprS64x2LoadSplat: len = DecodeLoadTransformMem( LoadType::kI64Load, LoadTransformationKind::kSplat, opcode_length); break; case kExprI16x8Load8x8S: len = DecodeLoadTransformMem(LoadType::kI32Load8S, LoadTransformationKind::kExtend, opcode_length); break; case kExprI16x8Load8x8U: len = DecodeLoadTransformMem(LoadType::kI32Load8U, LoadTransformationKind::kExtend, opcode_length); break; case kExprI32x4Load16x4S: len = DecodeLoadTransformMem(LoadType::kI32Load16S, LoadTransformationKind::kExtend, opcode_length); break; case kExprI32x4Load16x4U: len = DecodeLoadTransformMem(LoadType::kI32Load16U, LoadTransformationKind::kExtend, opcode_length); break; case kExprI64x2Load32x2S: len = DecodeLoadTransformMem(LoadType::kI64Load32S, LoadTransformationKind::kExtend, opcode_length); break; case kExprI64x2Load32x2U: len = DecodeLoadTransformMem(LoadType::kI64Load32U, LoadTransformationKind::kExtend, opcode_length); break; default: { if (!FLAG_wasm_simd_post_mvp && WasmOpcodes::IsSimdPostMvpOpcode(opcode)) { this->error( "simd opcode not available, enable with --wasm-simd-post-mvp"); break; } const FunctionSig* sig = WasmOpcodes::Signature(opcode); if (!VALIDATE(sig != nullptr)) { this->error("invalid simd opcode"); break; } ArgVector args = PopArgs(sig); Value* results = sig->return_count() == 0 ? nullptr : Push(GetReturnType(sig)); CALL_INTERFACE_IF_REACHABLE(SimdOp, opcode, VectorOf(args), results); } } return len; } uint32_t DecodeGCOpcode(WasmOpcode opcode) { uint32_t len = 2; switch (opcode) { case kExprStructNew: { StructIndexImmediate<validate> imm(this, this->pc_ + len); len += imm.length; if (!this->Validate(this->pc_, imm)) break; ArgVector args = PopArgs(imm.struct_type); Value* value = Push( ValueType::Ref(static_cast<HeapType>(imm.index), kNonNullable)); CALL_INTERFACE_IF_REACHABLE(StructNew, imm, args.begin(), value); break; } case kExprStructGet: { FieldIndexImmediate<validate> field(this, this->pc_ + len); if (!this->Validate(this->pc_ + len, field)) break; ValueType field_type = field.struct_index.struct_type->field(field.index); if (field_type.is_packed()) { this->error(this->pc_, "struct.get used with a field of packed type. " "Use struct.get_s or struct.get_u instead."); break; } len += field.length; Value struct_obj = Pop( 0, ValueType::Ref(static_cast<HeapType>(field.struct_index.index), kNullable)); Value* value = Push(field_type); CALL_INTERFACE_IF_REACHABLE(StructGet, struct_obj, field, true, value); break; } case kExprStructGetU: case kExprStructGetS: { FieldIndexImmediate<validate> field(this, this->pc_ + len); if (!this->Validate(this->pc_ + len, field)) break; len += field.length; ValueType field_type = field.struct_index.struct_type->field(field.index); if (!field_type.is_packed()) { this->errorf(this->pc_, "%s is only valid for packed struct fields. " "Use struct.get instead.", WasmOpcodes::OpcodeName(opcode)); break; } Value struct_obj = Pop( 0, ValueType::Ref(static_cast<HeapType>(field.struct_index.index), kNullable)); Value* value = Push(field_type.Unpacked()); CALL_INTERFACE_IF_REACHABLE(StructGet, struct_obj, field, opcode == kExprStructGetS, value); break; } case kExprStructSet: { FieldIndexImmediate<validate> field(this, this->pc_ + len); if (!this->Validate(this->pc_ + len, field)) break; len += field.length; const StructType* struct_type = field.struct_index.struct_type; if (!struct_type->mutability(field.index)) { this->error(this->pc_, "setting immutable struct field"); break; } Value field_value = Pop(1, struct_type->field(field.index).Unpacked()); Value struct_obj = Pop( 0, ValueType::Ref(static_cast<HeapType>(field.struct_index.index), kNullable)); CALL_INTERFACE_IF_REACHABLE(StructSet, struct_obj, field, field_value); break; } case kExprArrayNew: { ArrayIndexImmediate<validate> imm(this, this->pc_ + len); len += imm.length; if (!this->Validate(this->pc_, imm)) break; Value length = Pop(1, kWasmI32); Value initial_value = Pop(0, imm.array_type->element_type().Unpacked()); Value* value = Push( ValueType::Ref(static_cast<HeapType>(imm.index), kNonNullable)); CALL_INTERFACE_IF_REACHABLE(ArrayNew, imm, length, initial_value, value); break; } case kExprArrayGetS: case kExprArrayGetU: { ArrayIndexImmediate<validate> imm(this, this->pc_ + len); len += imm.length; if (!this->Validate(this->pc_ + len, imm)) break; if (!imm.array_type->element_type().is_packed()) { this->errorf(this->pc_, "%s is only valid for packed arrays. " "Use or array.get instead.", WasmOpcodes::OpcodeName(opcode)); break; } Value index = Pop(1, kWasmI32); Value array_obj = Pop(0, ValueType::Ref(static_cast<HeapType>(imm.index), kNullable)); Value* value = Push(imm.array_type->element_type().Unpacked()); // TODO(7748): Optimize this when array_obj is non-nullable ref. CALL_INTERFACE_IF_REACHABLE(ArrayGet, array_obj, imm, index, opcode == kExprArrayGetS, value); break; } case kExprArrayGet: { ArrayIndexImmediate<validate> imm(this, this->pc_ + len); len += imm.length; if (!this->Validate(this->pc_ + len, imm)) break; if (imm.array_type->element_type().is_packed()) { this->error(this->pc_, "array.get used with a field of packed type. " "Use array.get_s or array.get_u instead."); break; } Value index = Pop(1, kWasmI32); Value array_obj = Pop(0, ValueType::Ref(static_cast<HeapType>(imm.index), kNullable)); Value* value = Push(imm.array_type->element_type()); // TODO(7748): Optimize this when array_obj is non-nullable ref. CALL_INTERFACE_IF_REACHABLE(ArrayGet, array_obj, imm, index, true, value); break; } case kExprArraySet: { ArrayIndexImmediate<validate> imm(this, this->pc_ + len); len += imm.length; if (!this->Validate(this->pc_ + len, imm)) break; if (!imm.array_type->mutability()) { this->error(this->pc_, "setting element of immutable array"); break; } Value value = Pop(2, imm.array_type->element_type().Unpacked()); Value index = Pop(1, kWasmI32); Value array_obj = Pop(0, ValueType::Ref(static_cast<HeapType>(imm.index), kNullable)); // TODO(7748): Optimize this when array_obj is non-nullable ref. CALL_INTERFACE_IF_REACHABLE(ArraySet, array_obj, imm, index, value); break; } case kExprArrayLen: { ArrayIndexImmediate<validate> imm(this, this->pc_ + len); len += imm.length; if (!this->Validate(this->pc_ + len, imm)) break; Value array_obj = Pop(0, ValueType::Ref(static_cast<HeapType>(imm.index), kNullable)); Value* value = Push(kWasmI32); CALL_INTERFACE_IF_REACHABLE(ArrayLen, array_obj, value); break; } default: this->error("invalid gc opcode"); return 0; } return len; } uint32_t DecodeAtomicOpcode(WasmOpcode opcode) { uint32_t len = 0; ValueType ret_type; const FunctionSig* sig = WasmOpcodes::Signature(opcode); if (!VALIDATE(sig != nullptr)) { this->error("invalid atomic opcode"); return 0; } MachineType memtype; switch (opcode) { #define CASE_ATOMIC_STORE_OP(Name, Type) \ case kExpr##Name: { \ memtype = MachineType::Type(); \ ret_type = kWasmStmt; \ break; \ } ATOMIC_STORE_OP_LIST(CASE_ATOMIC_STORE_OP) #undef CASE_ATOMIC_OP #define CASE_ATOMIC_OP(Name, Type) \ case kExpr##Name: { \ memtype = MachineType::Type(); \ ret_type = GetReturnType(sig); \ break; \ } ATOMIC_OP_LIST(CASE_ATOMIC_OP) #undef CASE_ATOMIC_OP case kExprAtomicFence: { byte zero = this->template read_u8<validate>(this->pc_ + 2, "zero"); if (!VALIDATE(zero == 0)) { this->error(this->pc_ + 2, "invalid atomic operand"); return 0; } CALL_INTERFACE_IF_REACHABLE(AtomicFence); return 1; } default: this->error("invalid atomic opcode"); return 0; } if (!CheckHasMemoryForAtomics()) return 0; MemoryAccessImmediate<validate> imm( this, this->pc_ + 1, ElementSizeLog2Of(memtype.representation())); len += imm.length; ArgVector args = PopArgs(sig); Value* result = ret_type == kWasmStmt ? nullptr : Push(GetReturnType(sig)); CALL_INTERFACE_IF_REACHABLE(AtomicOp, opcode, VectorOf(args), imm, result); return len; } unsigned DecodeNumericOpcode(WasmOpcode opcode) { unsigned len = 0; const FunctionSig* sig = WasmOpcodes::Signature(opcode); if (sig != nullptr) { switch (opcode) { case kExprI32SConvertSatF32: case kExprI32UConvertSatF32: case kExprI32SConvertSatF64: case kExprI32UConvertSatF64: case kExprI64SConvertSatF32: case kExprI64UConvertSatF32: case kExprI64SConvertSatF64: case kExprI64UConvertSatF64: BuildSimpleOperator(opcode, sig); break; case kExprMemoryInit: { MemoryInitImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; Value size = Pop(2, sig->GetParam(2)); Value src = Pop(1, sig->GetParam(1)); Value dst = Pop(0, sig->GetParam(0)); CALL_INTERFACE_IF_REACHABLE(MemoryInit, imm, dst, src, size); break; } case kExprDataDrop: { DataDropImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; CALL_INTERFACE_IF_REACHABLE(DataDrop, imm); break; } case kExprMemoryCopy: { MemoryCopyImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; Value size = Pop(2, sig->GetParam(2)); Value src = Pop(1, sig->GetParam(1)); Value dst = Pop(0, sig->GetParam(0)); CALL_INTERFACE_IF_REACHABLE(MemoryCopy, imm, dst, src, size); break; } case kExprMemoryFill: { MemoryIndexImmediate<validate> imm(this, this->pc_ + 1); if (!this->Validate(this->pc_ + 1, imm)) break; len += imm.length; Value size = Pop(2, sig->GetParam(2)); Value value = Pop(1, sig->GetParam(1)); Value dst = Pop(0, sig->GetParam(0)); CALL_INTERFACE_IF_REACHABLE(MemoryFill, imm, dst, value, size); break; } case kExprTableInit: { TableInitImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; ArgVector args = PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(TableInit, imm, VectorOf(args)); break; } case kExprElemDrop: { ElemDropImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; CALL_INTERFACE_IF_REACHABLE(ElemDrop, imm); break; } case kExprTableCopy: { TableCopyImmediate<validate> imm(this, this->pc_); if (!this->Validate(imm)) break; len += imm.length; ArgVector args = PopArgs(sig); CALL_INTERFACE_IF_REACHABLE(TableCopy, imm, VectorOf(args)); break; } case kExprTableGrow: { TableIndexImmediate<validate> imm(this, this->pc_ + 1); if (!this->Validate(this->pc_, imm)) break; len += imm.length; Value delta = Pop(1, sig->GetParam(1)); Value value = Pop(0, this->module_->tables[imm.index].type); Value* result = Push(kWasmI32); CALL_INTERFACE_IF_REACHABLE(TableGrow, imm, value, delta, result); break; } case kExprTableSize: { TableIndexImmediate<validate> imm(this, this->pc_ + 1); if (!this->Validate(this->pc_, imm)) break; len += imm.length; Value* result = Push(kWasmI32); CALL_INTERFACE_IF_REACHABLE(TableSize, imm, result); break; } case kExprTableFill: { TableIndexImmediate<validate> imm(this, this->pc_ + 1); if (!this->Validate(this->pc_, imm)) break; len += imm.length; Value count = Pop(2, sig->GetParam(2)); Value value = Pop(1, this->module_->tables[imm.index].type); Value start = Pop(0, sig->GetParam(0)); CALL_INTERFACE_IF_REACHABLE(TableFill, imm, start, value, count); break; } default: this->error("invalid numeric opcode"); break; } } else { this->error("invalid numeric opcode"); } return len; } void DoReturn() { size_t return_count = this->sig_->return_count(); if (return_count > 1) { this->detected_->Add(kFeature_mv); } DCHECK_GE(stack_.size(), return_count); Vector<Value> return_values = return_count == 0 ? Vector<Value>{} : Vector<Value>{&*(stack_.end() - return_count), return_count}; CALL_INTERFACE_IF_REACHABLE(DoReturn, return_values); } inline Value* Push(ValueType type) { DCHECK_NE(kWasmStmt, type); stack_.emplace_back(this->pc_, type); return &stack_.back(); } void PushMergeValues(Control* c, Merge<Value>* merge) { DCHECK_EQ(c, &control_.back()); DCHECK(merge == &c->start_merge || merge == &c->end_merge); stack_.erase(stack_.begin() + c->stack_depth, stack_.end()); if (merge->arity == 1) { stack_.push_back(merge->vals.first); } else { for (uint32_t i = 0; i < merge->arity; i++) { stack_.push_back(merge->vals.array[i]); } } DCHECK_EQ(c->stack_depth + merge->arity, stack_.size()); } Value* PushReturns(const FunctionSig* sig) { size_t return_count = sig->return_count(); if (return_count == 0) return nullptr; size_t old_size = stack_.size(); for (size_t i = 0; i < return_count; ++i) { Push(sig->GetReturn(i)); } return stack_.data() + old_size; } V8_INLINE Value Pop(int index, ValueType expected) { Value val = Pop(); if (!VALIDATE(IsSubtypeOf(val.type, expected, this->module_) || val.type == kWasmBottom || expected == kWasmBottom)) { this->errorf(val.pc, "%s[%d] expected type %s, found %s of type %s", SafeOpcodeNameAt(this->pc_), index, expected.type_name().c_str(), SafeOpcodeNameAt(val.pc), val.type.type_name().c_str()); } return val; } V8_INLINE Value Pop() { DCHECK(!control_.empty()); uint32_t limit = control_.back().stack_depth; if (stack_.size() <= limit) { // Popping past the current control start in reachable code. if (!VALIDATE(control_.back().unreachable())) { this->errorf(this->pc_, "%s found empty stack", SafeOpcodeNameAt(this->pc_)); } return UnreachableValue(this->pc_); } Value val = stack_.back(); stack_.pop_back(); return val; } // Pops values from the stack, as defined by {merge}. Thereby we type-check // unreachable merges. Afterwards the values are pushed again on the stack // according to the signature in {merge}. This is done so follow-up validation // is possible. bool TypeCheckUnreachableMerge(Merge<Value>& merge, bool conditional_branch) { int arity = merge.arity; // For conditional branches, stack value '0' is the condition of the branch, // and the result values start at index '1'. int index_offset = conditional_branch ? 1 : 0; for (int i = arity - 1; i >= 0; --i) Pop(index_offset + i, merge[i].type); // Push values of the correct type back on the stack. for (int i = 0; i < arity; ++i) Push(merge[i].type); return this->ok(); } int startrel(const byte* ptr) { return static_cast<int>(ptr - this->start_); } void FallThruTo(Control* c) { DCHECK_EQ(c, &control_.back()); if (!TypeCheckFallThru()) return; if (!c->reachable()) return; if (!c->is_loop()) CALL_INTERFACE(FallThruTo, c); c->end_merge.reached = true; } bool TypeCheckMergeValues(Control* c, Merge<Value>* merge) { // This is a CHECK instead of a DCHECK because {validate} is a constexpr, // and a CHECK makes the whole function unreachable. static_assert(validate, "Call this function only within VALIDATE"); DCHECK(merge == &c->start_merge || merge == &c->end_merge); DCHECK_GE(stack_.size(), c->stack_depth + merge->arity); // The computation of {stack_values} is only valid if {merge->arity} is >0. DCHECK_LT(0, merge->arity); Value* stack_values = &*(stack_.end() - merge->arity); // Typecheck the topmost {merge->arity} values on the stack. for (uint32_t i = 0; i < merge->arity; ++i) { Value& val = stack_values[i]; Value& old = (*merge)[i]; if (!IsSubtypeOf(val.type, old.type, this->module_)) { this->errorf(this->pc_, "type error in merge[%u] (expected %s, got %s)", i, old.type.type_name().c_str(), val.type.type_name().c_str()); return false; } } return true; } bool TypeCheckOneArmedIf(Control* c) { static_assert(validate, "Call this function only within VALIDATE"); DCHECK(c->is_onearmed_if()); DCHECK_EQ(c->start_merge.arity, c->end_merge.arity); for (uint32_t i = 0; i < c->start_merge.arity; ++i) { Value& start = c->start_merge[i]; Value& end = c->end_merge[i]; if (!IsSubtypeOf(start.type, end.type, this->module_)) { this->errorf(this->pc_, "type error in merge[%u] (expected %s, got %s)", i, end.type.type_name().c_str(), start.type.type_name().c_str()); return false; } } return true; } bool TypeCheckFallThru() { static_assert(validate, "Call this function only within VALIDATE"); Control& c = control_.back(); if (V8_LIKELY(c.reachable())) { uint32_t expected = c.end_merge.arity; DCHECK_GE(stack_.size(), c.stack_depth); uint32_t actual = static_cast<uint32_t>(stack_.size()) - c.stack_depth; // Fallthrus must match the arity of the control exactly. if (actual != expected) { this->errorf( this->pc_, "expected %u elements on the stack for fallthru to @%d, found %u", expected, startrel(c.pc), actual); return false; } if (expected == 0) return true; // Fast path. return TypeCheckMergeValues(&c, &c.end_merge); } // Type-check an unreachable fallthru. First we do an arity check, then a // type check. Note that type-checking may require an adjustment of the // stack, if some stack values are missing to match the block signature. Merge<Value>& merge = c.end_merge; int arity = static_cast<int>(merge.arity); int available = static_cast<int>(stack_.size()) - c.stack_depth; // For fallthrus, not more than the needed values should be available. if (available > arity) { this->errorf( this->pc_, "expected %u elements on the stack for fallthru to @%d, found %u", arity, startrel(c.pc), available); return false; } // Pop all values from the stack for type checking of existing stack // values. return TypeCheckUnreachableMerge(merge, false); } enum TypeCheckBranchResult { kReachableBranch, kUnreachableBranch, kInvalidStack, }; TypeCheckBranchResult TypeCheckBranch(Control* c, bool conditional_branch) { if (V8_LIKELY(control_.back().reachable())) { // We only do type-checking here. This is only needed during validation. if (!validate) return kReachableBranch; // Branches must have at least the number of values expected; can have // more. uint32_t expected = c->br_merge()->arity; if (expected == 0) return kReachableBranch; // Fast path. DCHECK_GE(stack_.size(), control_.back().stack_depth); uint32_t actual = static_cast<uint32_t>(stack_.size()) - control_.back().stack_depth; if (expected > actual) { this->errorf( this->pc_, "expected %u elements on the stack for br to @%d, found %u", expected, startrel(c->pc), actual); return kInvalidStack; } return TypeCheckMergeValues(c, c->br_merge()) ? kReachableBranch : kInvalidStack; } return TypeCheckUnreachableMerge(*c->br_merge(), conditional_branch) ? kUnreachableBranch : kInvalidStack; } bool TypeCheckReturn() { int num_returns = static_cast<int>(this->sig_->return_count()); // No type checking is needed if there are no returns. if (num_returns == 0) return true; // Returns must have at least the number of values expected; can have more. int num_available = static_cast<int>(stack_.size()) - control_.back().stack_depth; if (num_available < num_returns) { this->errorf(this->pc_, "expected %u elements on the stack for return, found %u", num_returns, num_available); return false; } // Typecheck the topmost {num_returns} values on the stack. // This line requires num_returns > 0. Value* stack_values = &*(stack_.end() - num_returns); for (int i = 0; i < num_returns; ++i) { Value& val = stack_values[i]; ValueType expected_type = this->sig_->GetReturn(i); if (!IsSubtypeOf(val.type, expected_type, this->module_)) { this->errorf( this->pc_, "type error in return[%u] (expected %s, got %s)", i, expected_type.type_name().c_str(), val.type.type_name().c_str()); return false; } } return true; } void onFirstError() override { this->end_ = this->pc_; // Terminate decoding loop. this->current_code_reachable_ = false; TRACE(" !%s\n", this->error_.message().c_str()); CALL_INTERFACE(OnFirstError); } void BuildSimplePrototypeOperator(WasmOpcode opcode) { if (opcode == kExprRefEq) { RET_ON_PROTOTYPE_OPCODE(gc); } const FunctionSig* sig = WasmOpcodes::Signature(opcode); BuildSimpleOperator(opcode, sig); } void BuildSimpleOperator(WasmOpcode opcode, const FunctionSig* sig) { DCHECK_GE(1, sig->return_count()); ValueType ret = sig->return_count() == 0 ? kWasmStmt : sig->GetReturn(0); if (sig->parameter_count() == 1) { BuildSimpleOperator(opcode, ret, sig->GetParam(0)); } else { DCHECK_EQ(2, sig->parameter_count()); BuildSimpleOperator(opcode, ret, sig->GetParam(0), sig->GetParam(1)); } } void BuildSimpleOperator(WasmOpcode opcode, ValueType return_type, ValueType arg_type) { Value val = Pop(0, arg_type); Value* ret = return_type == kWasmStmt ? nullptr : Push(return_type); CALL_INTERFACE_IF_REACHABLE(UnOp, opcode, val, ret); } void BuildSimpleOperator(WasmOpcode opcode, ValueType return_type, ValueType lhs_type, ValueType rhs_type) { Value rval = Pop(1, rhs_type); Value lval = Pop(0, lhs_type); Value* ret = return_type == kWasmStmt ? nullptr : Push(return_type); CALL_INTERFACE_IF_REACHABLE(BinOp, opcode, lval, rval, ret); } #define DEFINE_SIMPLE_SIG_OPERATOR(sig, ...) \ void BuildSimpleOperator_##sig(WasmOpcode opcode) { \ BuildSimpleOperator(opcode, __VA_ARGS__); \ } FOREACH_SIGNATURE(DEFINE_SIMPLE_SIG_OPERATOR) #undef DEFINE_SIMPLE_SIG_OPERATOR }; #undef CALL_INTERFACE #undef CALL_INTERFACE_IF_REACHABLE #undef CALL_INTERFACE_IF_PARENT_REACHABLE class EmptyInterface { public: static constexpr Decoder::ValidateFlag validate = Decoder::kValidate; using Value = ValueBase; using Control = ControlBase<Value>; using FullDecoder = WasmFullDecoder<validate, EmptyInterface>; #define DEFINE_EMPTY_CALLBACK(name, ...) \ void name(FullDecoder* decoder, ##__VA_ARGS__) {} INTERFACE_FUNCTIONS(DEFINE_EMPTY_CALLBACK) #undef DEFINE_EMPTY_CALLBACK }; #undef TRACE #undef TRACE_INST_FORMAT #undef VALIDATE #undef CHECK_PROTOTYPE_OPCODE #undef RET_ON_PROTOTYPE_OPCODE #undef CHECK_PROTOTYPE_OPCODE_GEN #undef OPCODE_ERROR } // namespace wasm } // namespace internal } // namespace v8 #endif // V8_WASM_FUNCTION_BODY_DECODER_IMPL_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
7ec037078657fdd0867185094951461e712fd02e
3ef9dbe0dd6b8161b75950f682ec2fc24f79a90e
/Huawei-EU-Challenge/BFS/serial_bfs_improved-IO/fopen/bfs.cpp
17d14eae59ef33de467df1ca76323b4f2224a5c0
[ "MIT" ]
permissive
JackBai0914/Competitive-Programming-Codebase
abc0cb911e5f6b32d1bd14416f9eb398b7c65bb9
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
refs/heads/main
2023-03-29T14:17:36.190798
2021-04-14T23:15:12
2021-04-14T23:15:12
358,065,977
0
0
null
null
null
null
UTF-8
C++
false
false
1,747
cpp
#include <iostream> #include <algorithm> #include <sstream> #include <cstring> #include <cstdio> #include <unordered_map> #include <queue> #define TIME (double)clock()/CLOCKS_PER_SEC using namespace std; queue <int> q; unordered_map<int, vector <int> > points; unordered_map<int, bool> vis; // unordered_map<int, int> pt; int pt[2000020]; int egf[2000020], egs[2000020]; int est = 0; int hp[1000010]; int hst = 0; const int BUF = 65536; char buf[BUF + 1]; char *head = buf, *tail = buf; inline char inputchar() { if(head == tail) *(tail = (head = buf) + fread(buf, 1, BUF, stdin)) = 0; return *head++; } template <typename T> inline void read(T &x) { char ch = inputchar(); int f = 1; x = 0; while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = inputchar();} while(ch >= '0' && ch <= '9') x = x*10+ch-'0', ch = inputchar(); x *= f; } template <typename T, typename... Args> inline void read(T &x, Args &...args) { read(x), read(args...); } int main() { int u, v; while(inputchar() != ']') { read(u, v); est ++; egf[est] = v; egs[est] = pt[u]; pt[u] = est; } // cerr << "time taken to input: " << TIME << endl; q.push(0); vis[0] = true; printf("[0"); int last = 0, x, to; int e, i; while (!q.empty()) { x = q.front(); if (x) printf(",%d", x); q.pop(); hst = 0; for (e = pt[x]; e; e = egs[e]) hp[hst++] = egf[e]; for (i = hst - 1; i >= 0; i --) { to = hp[i]; if (!vis[to]) { vis[to] = true; q.push(to); } } } printf("]"); // cerr << "time taken to finish: " << TIME << endl; return 0; }
[ "xingjianbai0914@sina.com" ]
xingjianbai0914@sina.com
f94e58bda11d6acf37b0ef14aea42e596ca10488
e02b9bb81111d68084791293d0345838e543fcdb
/DDSL-Antlr/DDSL-Antlr/antlr4-runtime/tree/TerminalNodeImpl.h
4510de4189bf80f41f6d4a9a35498a9fb573ef3b
[]
no_license
czqasngit/DDSL
e3e612cd4113826877032f42c7ff255be130769c
95fe861508d32c9f68209e56f9d6000a8255f140
refs/heads/master
2023-05-15T03:23:49.706314
2021-06-10T12:04:54
2021-06-10T12:04:54
281,632,566
9
1
null
null
null
null
UTF-8
C++
false
false
936
h
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ #pragma once #include "TerminalNode.h" namespace antlr4 { namespace tree { class ANTLR4CPP_PUBLIC TerminalNodeImpl : public virtual TerminalNode { public: Token *symbol; TerminalNodeImpl(Token *symbol); virtual Token* getSymbol() override; virtual void setParent(RuleContext *parent) override; virtual misc::Interval getSourceInterval() override; virtual antlrcpp::Any accept(ParseTreeVisitor *visitor) override; virtual std::string getText() override; virtual std::string toStringTree(Parser *parser, bool pretty = false) override; virtual std::string toString() override; virtual std::string toStringTree(bool pretty = false) override; }; } // namespace tree } // namespace antlr4
[ "305107316@qq.com" ]
305107316@qq.com
7b55238737acc7b7f85df3f0839451a374fc3215
fec81bfe0453c5646e00c5d69874a71c579a103d
/blazetest/src/mathtest/traits/expandtrait/ClassTest.cpp
2547be4655caf6d87cda18fb96d959a8b7b7130a
[ "BSD-3-Clause" ]
permissive
parsa/blaze
801b0f619a53f8c07454b80d0a665ac0a3cf561d
6ce2d5d8951e9b367aad87cc55ac835b054b5964
refs/heads/master
2022-09-19T15:46:44.108364
2022-07-30T04:47:03
2022-07-30T04:47:03
105,918,096
52
7
null
null
null
null
UTF-8
C++
false
false
19,184
cpp
//================================================================================================= /*! // \file src/mathtest/traits/expandtrait/ClassTest.cpp // \brief Source file for the ExpandTrait class test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <utility> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/CompressedVector.h> #include <blaze/math/CustomVector.h> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/DynamicVector.h> #include <blaze/math/HybridMatrix.h> #include <blaze/math/HybridVector.h> #include <blaze/math/InitializerVector.h> #include <blaze/math/StaticMatrix.h> #include <blaze/math/StaticVector.h> #include <blaze/math/traits/ExpandTrait.h> #include <blaze/math/typetraits/StorageOrder.h> #include <blaze/math/UniformMatrix.h> #include <blaze/math/UniformVector.h> #include <blaze/math/ZeroVector.h> #include <blaze/util/Complex.h> #include <blaze/util/typetraits/IsSame.h> #include <blaze/util/typetraits/RemoveCVRef.h> #include <blazetest/mathtest/traits/expandtrait/ClassTest.h> namespace blazetest { namespace mathtest { namespace traits { namespace expandtrait { //================================================================================================= // // CONSTRUCTORS // //================================================================================================= //************************************************************************************************* /*!\brief Constructor for the ExpandTrait class test. // // \exception std::runtime_error Error detected. */ ClassTest::ClassTest() { testVectorExpansion(); } //************************************************************************************************* //================================================================================================= // // TEST FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Test of the 'ExpandTrait' class template for vector expansions. // // \return void // \exception std::runtime_error Error detected. // // This function performs a compile time test of the 'ExpandTrait' class template for vector // expansions. In case an error is detected, a compilation error is created. */ void ClassTest::testVectorExpansion() { using namespace blaze; // StaticVector { { using VT = StaticVector<int,3UL,columnVector>; using RT = DynamicMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = StaticVector<int,3UL,rowVector>; using RT = DynamicMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = StaticVector<int,3UL,columnVector>; using RT = StaticMatrix<int,3UL,5UL,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = StaticVector<int,3UL,rowVector>; using RT = StaticMatrix<int,5UL,3UL,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } } // HybridVector { { using VT = HybridVector<int,3UL,columnVector>; using RT = DynamicMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = HybridVector<int,3UL,rowVector>; using RT = DynamicMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = HybridVector<int,3UL,columnVector>; using RT = HybridMatrix<int,3UL,5UL,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = HybridVector<int,3UL,rowVector>; using RT = HybridMatrix<int,5UL,3UL,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } } // DynamicVector { { using VT = DynamicVector<int,columnVector>; using RT = DynamicMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = DynamicVector<int,rowVector>; using RT = DynamicMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = DynamicVector<int,columnVector>; using RT = DynamicMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = DynamicVector<int,rowVector>; using RT = DynamicMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } } // CustomVector { { using VT = CustomVector<int,unaligned,unpadded,columnVector>; using RT = DynamicMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = CustomVector<int,unaligned,unpadded,rowVector>; using RT = DynamicMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = CustomVector<int,unaligned,unpadded,columnVector>; using RT = DynamicMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = CustomVector<int,unaligned,unpadded,rowVector>; using RT = DynamicMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } } // UniformVector { { using VT = UniformVector<int,columnVector>; using RT = UniformMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = UniformVector<int,rowVector>; using RT = UniformMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = UniformVector<int,columnVector>; using RT = UniformMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = UniformVector<int,rowVector>; using RT = UniformMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } } // InitializerVector { { using VT = InitializerVector<int,columnVector>; using RT = DynamicMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = InitializerVector<int,rowVector>; using RT = DynamicMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = InitializerVector<int,columnVector>; using RT = DynamicMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = InitializerVector<int,rowVector>; using RT = DynamicMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } } // CompressedVector { { using VT = CompressedVector<int,columnVector>; using RT = CompressedMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = CompressedVector<int,rowVector>; using RT = CompressedMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = CompressedVector<int,columnVector>; using RT = CompressedMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = CompressedVector<int,rowVector>; using RT = CompressedMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } } // ZeroVector { { using VT = ZeroVector<int,columnVector>; using RT = ZeroMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = ZeroVector<int,rowVector>; using RT = ZeroMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand( std::declval<VT>(), std::declval<size_t>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = ZeroVector<int,columnVector>; using RT = ZeroMatrix<int,columnMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } { using VT = ZeroVector<int,rowVector>; using RT = ZeroMatrix<int,rowMajor>; static_assert( IsSame_v< ExpandTrait_t<VT,5UL>, RT >, "Non-matching type detected" ); using Expr = RemoveCVRef_t< decltype( expand<5UL>( std::declval<VT>() ) ) >; static_assert( StorageOrder_v<Expr> == StorageOrder_v<RT>, "Non-matching storage order detected" ); } } } //************************************************************************************************* } // namespace expandtrait } // namespace traits } // namespace mathtest } // namespace blazetest //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running ExpandTrait class test..." << std::endl; try { RUN_EXPANDTRAIT_CLASS_TEST; } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during ExpandTrait class test:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
e4177dd828c691e3e63e3e8b8ae113d573421471
0381e635c0faf699b41f3e7bc78c29ca10eda074
/BasicLib/BasicLibTime.h
6fb374d1fdada9e26b94a0685a0c61563a70307c
[]
no_license
ysbbswork/Chatroom
884b83704b579de8aa0215b4836057d6054a13a6
ebb97378c646aead31c9167dee0199fc3c6e65da
refs/heads/master
2020-03-20T09:58:03.401148
2018-06-15T14:41:33
2018-06-15T14:41:33
137,354,538
4
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,699
h
// BasicLibTime.h #ifndef BASICLIBTIME_H #define BASICLIBTIME_H #include "BasicLibTypes.h" #include <string> namespace BasicLib { sint64 GetTimeMS(); sint64 GetTimeS(); sint64 GetTimeM(); sint64 GetTimeH(); // ============================================================ // This prints a timestamp in 24 hours hh:mm:ss format // ============================================================ std::string TimeStamp(); // ============================================================ // This prints a datestamp in YYYY:MM:DD format // ============================================================ std::string DateStamp(); // ============================================================ // The Timer Class¶¨Ê±Æ÷Àà // ============================================================ class Timer { public: Timer(); void Reset( sint64 p_timepassed = 0 ); sint64 GetMS(); sint64 GetS(); sint64 GetM(); sint64 GetH(); sint64 GetD(); sint64 GetY(); std::string GetString(); protected: sint64 m_inittime; sint64 m_starttime; }; inline sint64 seconds( sint64 t ) { return t * 1000; } inline sint64 minutes( sint64 t ) { return t * 60 * 1000; } inline sint64 hours( sint64 t ) { return t * 60 * 60 * 1000; } inline sint64 days( sint64 t ) { return t * 24 * 60 * 60 * 1000; } inline sint64 weeks( sint64 t ) { return t * 7 * 24 * 60 * 60 * 1000; } inline sint64 years( sint64 t ) { return t * 365 * 24 * 60 * 60 * 1000; } } #endif
[ "ysbbs@qq.com" ]
ysbbs@qq.com
20a4cb22383310716279556f00f03f3cba61bbfa
ad822f849322c5dcad78d609f28259031a96c98e
/SDK/CatalogItemRecipeIngredient_classes.h
92b4148241edc2fd2c6a93259cf4e6438a06e06a
[]
no_license
zH4x-SDK/zAstroneer-SDK
1cdc9c51b60be619202c0258a0dd66bf96898ac4
35047f506eaef251a161792fcd2ddd24fe446050
refs/heads/main
2023-07-24T08:20:55.346698
2021-08-27T13:33:33
2021-08-27T13:33:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,870
h
#pragma once // Name: Astroneer-SDK, Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass CatalogItemRecipeIngredient.CatalogItemRecipeIngredient_C // 0x0090 (0x0298 - 0x0208) class UCatalogItemRecipeIngredient_C : public UUserWidget { public: class UImage* BG; // 0x0208(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UTextBlock* IngredientName; // 0x0210(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* ResourceIcon; // 0x0218(0x0008) (ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) struct FSlateBrush IconBrush; // 0x0220(0x0078) (Edit, BlueprintVisible, DisableEditOnInstance) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass CatalogItemRecipeIngredient.CatalogItemRecipeIngredient_C"); return ptr; } void SetIngredientType(class UClass* IngredientType, int Quantity); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
3d9372fecd343633f9907330f9fe082475b0163f
3f84e550f46760e67330b9d1c24a62b5cae3c7eb
/pfms-2019a-Johnson15177-master/scratch/assignment/a1/assignment.h
98c6b17d6e319d53347acf641a8f95ce578dc9c3
[]
no_license
esteban-andrade/projects
58f303a6901b5eba340ca8c856eaea8ddd633f63
b569f241b6dd1302811cce91407df7ac54a9ffa5
refs/heads/master
2020-07-03T11:59:43.915046
2020-05-15T02:58:18
2020-05-15T02:58:18
201,897,707
0
0
null
null
null
null
UTF-8
C++
false
false
490
h
#ifndef ASSIGNMENT_H #define ASSIGNMENT_H #include <iostream> #include <vector> #include <chrono> #include <random> #include <thread> class HyperCamera { public: HyperCamera(int seed, int n); void RandNumTo(std::vector<double> &num_vec1); private: int Max_Amount_; std::default_random_engine generator_; //using uniform real distribution for the random number generator std::uniform_real_distribution<double> distribution_; }; #endif // ASSIGNMENT_H
[ "esgaanza98@gmail.com" ]
esgaanza98@gmail.com
9c2c975ecb53cbd55d6036a1ffa806fe52d36370
62b192e7dd22492b71bc4b255c12b690d69501fd
/flexy_tilty__mouse.ino
91105f01c01fa6a001d7b68439118f87dfb968f9
[]
no_license
ZFudge/flexy_tilty_mouse
b59368d16c59a5d5e24850949fbf6ba4cdedafe0
94ceed244f787e5c758dd40fea59ce8da73542d5
refs/heads/master
2020-05-02T01:40:08.809587
2019-03-25T15:27:06
2019-03-25T15:27:06
177,690,061
0
0
null
null
null
null
UTF-8
C++
false
false
2,062
ino
#include <Mouse.h> // Flex sensor pins - 47K ohms const int X_FLEX_PIN = A0; const int Y_FLEX_PIN = A1; const float VCC = 4.98; // Measured voltage of 5V line const float R_DIV = 47000.0; // Measured resistance of 47k resistor const float STRAIGHT_R = 37300.0; // resistance when straight const float BEND_R = 90000.0; // resistance at 90 deg const int bend_threshold = 600; // Tilt sensor pins const int xTiltPin = 11; const int yTiltPin = 13; const int buttonPin = 2; // the number of the pushbutton pin int print_readings = 1; void setup() { Serial.begin(9600); Mouse.begin(); pinMode(xTiltPin, INPUT); pinMode(yTiltPin, INPUT); pinMode(X_FLEX_PIN, INPUT); pinMode(Y_FLEX_PIN, INPUT); pinMode(buttonPin, INPUT); } void loop() { int buttonState = digitalRead(buttonPin); int xFlexADC = analogRead(X_FLEX_PIN); int yFlexADC = analogRead(Y_FLEX_PIN); int xInput = check_bend_threshold(xFlexADC); int yInput = check_bend_threshold(yFlexADC); if (xInput || yInput) { mouseMovement(xInput, yInput, xFlexADC, yFlexADC); } if (print_readings) { int readings[4] = { xFlexADC, yFlexADC, xInput, yInput }; printReadings(readings); } delay(100); } void mouseMovement(int xInt, int yInt, int xFlex, int yFlex) { int x = 0; int y = 0; if (xInt) { int xTiltVal = digitalRead(xTiltPin); Serial.println("X TILT: " + String(xTiltVal)); x = 670 - xFlex; x = xTiltVal ? 5 : -5; } if (yInt) { int yTiltVal = digitalRead(yTiltPin); Serial.println("Y TILT: " + String(yTiltVal)); y = 670 - yFlex; y = yTiltVal ? 5 : -5; } Mouse.move(x, y, 0); } int check_bend_threshold(float bend) { return bend < bend_threshold; } void printReadings(int readings[4]) { Serial.println("X ADC: " + String(readings[0])); Serial.println("Y ADC: " + String(readings[1])); Serial.println("X Input: " + String(readings[2])); Serial.println("Y Input: " + String(readings[3])); Serial.println("\n\n\n"); }
[ "zfudge@spotx.tv" ]
zfudge@spotx.tv
ec00a4aab7587046f0b8865e5b26761b9c86780f
9de148c018880306f441aa7b69a8957e41675746
/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorContext.h
8b62c08a8c72f92e10a70940000642f05162e2d0
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
JosephTom/USD
3cdf332fc54b3a8eb5cb11a763bdb865a2abb89a
5ec16f41af30ed446dfd3ea7b30f9ddb277ee50f
refs/heads/master
2021-01-02T09:05:04.867296
2017-07-31T06:17:22
2017-07-31T06:17:22
99,138,429
2
0
null
null
null
null
UTF-8
C++
false
false
10,574
h
// // Copyright 2017 Animal Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License.// // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include "AL/usdmaya/Common.h" #include "maya/MPxData.h" #include "maya/MGlobal.h" #include "maya/MObject.h" #include "maya/MObjectHandle.h" #include "maya/MObjectArray.h" #include "maya/MDGModifier.h" #include "pxr/pxr.h" #include "pxr/base/tf/refPtr.h" #include "pxr/usd/usd/prim.h" #include <map> #include <unordered_map> #include <string> PXR_NAMESPACE_USING_DIRECTIVE namespace AL { namespace usdmaya { namespace fileio { namespace translators { typedef std::vector<MObjectHandle> MObjectHandleArray; //---------------------------------------------------------------------------------------------------------------------- /// \brief This class provides a context to store mappings between UsdPrims, and the Maya nodes that represent them. /// /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- struct TranslatorContext : public TfRefBase { public: typedef TranslatorContext This; ///< this type typedef TfRefPtr<This> RefPtr; ///< pointer to this type /// \brief construct a new context for the specified proxy shape node /// \param proxyShape the proxy shape to associate the context with /// \return a new context static RefPtr create(nodes::ProxyShape* proxyShape) { return TfCreateRefPtr(new This(proxyShape)); } /// \brief return the proxy shape associated with this context /// \return the proxy shape const nodes::ProxyShape* getProxyShape() const { return m_proxyShape; } /// \brief return the usd stage associated with this context /// \return the usd stage UsdStageRefPtr getUsdStage() const; /// \brief given a USD prim, this will see whether a maya node exists for it. If it does, that will /// be returned in the object handle. If the object is found, true is returned, otherwise false. /// \param prim the usd prim /// \param object the returned handle /// \return true if the prim exists bool getTransform(const UsdPrim& prim, MObjectHandle& object) { return getTransform(prim.GetPath(), object); } /// \brief given a USD prim path, this will see whether a maya node exists for it. If it does, that will /// be returned in the object handle. If the object is found, true is returned, otherwise false. /// \param path the usd prim path /// \param object the returned handle /// \return true if the prim exists bool getTransform(const SdfPath& path, MObjectHandle& object); /// \brief given a USD prim, this will see whether a maya node exists for it. If it does, that will /// be returned in the object handle. If the object is found, true is returned, otherwise false. /// \param prim the usd prim /// \param object the returned handle /// \param type the type ID of the maya object you wish to retrieve. If the type ID is 0, the first node /// found will be returned. This may be useful if a prim type may create a type of node /// that is not known at compile time (e.g. a prim that creates a lambert, blinn, or phong based on /// some enum attribute). Another alternative would be to query all of the maya nodes via getMObjects /// \return true if the prim exists bool getMObject(const UsdPrim& prim, MObjectHandle& object, MTypeId type) { return getMObject(prim.GetPath(), object, type); } /// \brief given a USD prim path, this will see whether a maya node exists for it. If it does, that will /// be returned in the object handle. If the object is found, true is returned, otherwise false. /// \param path the usd prim path /// \param object the returned handle /// \param type the type ID of the maya object you wish to retrieve. If the type ID is 0, the first node /// found will be returned. This may be useful if a prim type may create a type of node /// that is not known at compile time (e.g. a prim that creates a lambert, blinn, or phong based on /// some enum attribute). Another alternative would be to query all of the maya nodes via getMObjects /// \return true if the prim exists bool getMObject(const SdfPath& path, MObjectHandle& object, MTypeId type); /// \brief given a USD prim, this will see whether a maya node exists for it. If it does, that will /// be returned in the object handle. If the object is found, true is returned, otherwise false. /// \param prim the usd prim /// \param object the returned handle /// \param type the type of the maya object you wish to retrieve. If the type is MFn::kInvalid, then the /// first node found will be returned. This may be useful if a prim type may create a type of node /// that is not known at compile time (e.g. a prim that creates a lambert, blinn, or phong based on /// some enum attribute). Another alternative would be to query all of the maya nodes via getMObjects /// \return true if the prim exists bool getMObject(const UsdPrim& prim, MObjectHandle& object, MFn::Type type) { return getMObject(prim.GetPath(), object, type); } /// \brief given a USD prim path, this will see whether a maya node exists for it. If it does, that will /// be returned in the object handle. If the object is found, true is returned, otherwise false. /// \param path the usd prim path /// \param object the returned handle /// \param type the type of the maya object you wish to retrieve. If the type is MFn::kInvalid, then the /// first node found will be returned. This may be useful if a prim type may create a type of node /// that is not known at compile time (e.g. a prim that creates a lambert, blinn, or phong based on /// some enum attribute). Another alternative would be to query all of the maya nodes via getMObjects /// \return true if the prim exists bool getMObject(const SdfPath& path, MObjectHandle& object, MFn::Type type); /// \brief returns all of the maya nodes that were created by the specific prim /// \param prim the prim to query /// \param returned the returned list of MObjects /// \return true if a reference to the prim was found bool getMObjects(const UsdPrim& prim, MObjectHandleArray& returned) { return getMObjects(prim.GetPath(), returned); } /// \brief returns all of the maya nodes that were created by the specific prim /// \param path the path to the prim to query /// \param returned the returned list of MObjects /// \return true if a reference to the prim was found bool getMObjects(const SdfPath& path, MObjectHandleArray& returned); /// \brief If within your custom translator plug-in you need to create any maya nodes, associate that maya /// node with the prim path by calling this method /// \param prim the prim you are currently importing in a translator /// \param object the handle to the maya node you have created. void insertItem(const UsdPrim& prim, MObjectHandle object); /// \brief during a variant switch, if we lose a prim, then it's path will be passed into this method, and /// all the maya nodes that were created for it will be nuked. /// \param prim the usd prim that was removed due to a variant switch void removeItems(const UsdPrim& prim) { removeItems(prim.GetPath()); } /// \brief during a variant switch, if we lose a prim, then it's path will be passed into this method, and /// all the maya nodes that were created for it will be nuked. /// \param path path to the usd prim that was removed due to a variant switch void removeItems(const SdfPath& path); /// \brief dtor ~TranslatorContext(); /// \brief given a path to a prim, return the prim type we are aware of at that path /// \param path the prim path of a prim that was imported via a custom translator plug-in /// \return the type name for that prim TfToken getTypeForPath(SdfPath path) const { const auto it = m_primMapping.find(path.GetString()); if(it != m_primMapping.end()) { return it->second.m_type; } return TfToken(); } /// \brief this method is used after a variant switch to check to see if the prim types have changed in the /// stage, and will update the internal state accordingly. void updatePrimTypes(); /// \brief Internal method. /// If within your custom translator plug-in you need to create any maya nodes, associate that maya /// node with the prim path by calling this method /// \param prim the prim you are currently importing in a translator /// \param object the handle to the maya node you have created. void registerItem(const UsdPrim& prim, MObjectHandle object); /// \brief serialises the content of the translator context to a text string. /// \return the translator context serialised into a string MString serialise() const; /// \brief deserialises the string back into the translator context /// \param string the string to deserialised void deserialise(const MString& string); /// \brief debugging utility to help keep track of prims during a variant switch void validatePrims(); private: TranslatorContext(const nodes::ProxyShape* proxyShape) : m_proxyShape(proxyShape), m_primMapping() {} const nodes::ProxyShape* m_proxyShape; struct PrimLookup { TfToken m_type; MObjectHandle m_object; MObjectHandleArray m_createdNodes; }; // map between a usd prim path and either a dag parent node or // a dependency node std::unordered_map<std::string, PrimLookup> m_primMapping; }; typedef TfRefPtr<TranslatorContext> TranslatorContextPtr; //---------------------------------------------------------------------------------------------------------------------- } // translators } // fileio } // usdmaya } // AL //----------------------------------------------------------------------------------------------------------------------
[ "fabrice.macagno@al.com.au" ]
fabrice.macagno@al.com.au
61afdeae91ffec8d30dc30dbd99894a1cc68287c
611fc0940b78862ca89de79a8bbeab991f5f471a
/src/Teki/Boss/Ookami/OokamiJumpAttack.cpp
55a461bd2a448e49a9a4d03ae90163cd274b4cc8
[]
no_license
LakeIshikawa/splstage2
df1d8f59319a4e8d9375b9d3379c3548bc520f44
b4bf7caadf940773a977edd0de8edc610cd2f736
refs/heads/master
2021-01-10T21:16:45.430981
2010-01-29T08:57:34
2010-01-29T08:57:34
37,068,575
0
0
null
null
null
null
UTF-8
C++
false
false
623
cpp
#include <string> #include <vector> #include <exception> using namespace std; #include "OokamiJumpAttack.h" #include "ActionState.h" #include "OokamiBaseAction.h" OokamiJumpAttack::OokamiJumpAttack(int rStartX, int rStartY) { } OokamiJumpAttack::OokamiJumpAttack(ActionState* rPrevState) { } void OokamiJumpAttack::BuildState(ActionState* rPrevState) { throw "Not yet implemented"; } void OokamiJumpAttack::OnEnter() { throw "Not yet implemented"; } bool OokamiJumpAttack::Update() { throw "Not yet implemented"; } void OokamiJumpAttack::OnExit() { throw "Not yet implemented"; }
[ "lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b" ]
lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b
f796ad424345180f956cc00b506d409a7116584b
d5c436ee059bede2b8af4de15b2a12c9964cbc14
/dsArrayAsParameter.cpp
deca06a987f9ae21e1161da635c6daa84702991a
[]
no_license
sparshgoyal2014/cppCodes
805e10536c853d9bd2235f058f7f2ad1e27c99d3
bf9f4021e771de46b332dba0e76aede2e4febf47
refs/heads/master
2023-04-01T09:16:01.831508
2021-04-07T16:45:28
2021-04-07T16:45:28
257,046,189
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
#include<iostream> using namespace std; // void displayArray(int arr[]){ // for(int i=0; i<(sizeof(arr)/sizeof(arr[0])); i++){ // cout << arr[i] ; // } // } int main(){ int arr[6] = {1, 2, 3, 4, 5, 6}; // displayArray(arr); cout<< sizeof(arr) << endl; // here arr is used only in context of simple array and not as a pointere (as in cout<< arr << endl;) cout << sizeof(&arr) << endl; // that's why we are using & operator in front of arr otherwise arr will be give us an addresss // also watch all abt strings/chars / charArray/ char poionter discussions return 0; } //must watch...https://stackoverflow.com/questions/33523585/how-do-sizeofarr-sizeofarr0-work // must watch..bari's video on array passed as parameter in data structures and algorithms course
[ "sparshgoyal2014@gmail.com" ]
sparshgoyal2014@gmail.com