row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
46,082
New-ADUser : The object name has bad syntax At C:\Users\lbTechAdmin\desktop\NETWaddUsers_v25.2.22.ps1:30 char:1 + New-ADUser ` + ~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CN=\\ ,Exec_gp:String) [New-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser -AccountPassword : The term '-AccountPassword' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Users\lbTechAdmin\desktop\NETWaddUsers_v25.2.22.ps1:44 char:13 + -AccountPassword (convertto-securestring Passw0rd2023 -As ... + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (-AccountPassword:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
7664ac8066e06084916a78563104d46b
{ "intermediate": 0.22819843888282776, "beginner": 0.555689811706543, "expert": 0.21611174941062927 }
46,083
New-ADUser : The object name has bad syntax At C:\Users\lbTechAdmin\desktop\NETWaddUsers_v25.2.22.ps1:30 char:1 + New-ADUser ` + ~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CN=\\ ,Exec_gp:String) [New-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser -AccountPassword : The term '-AccountPassword' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Users\lbTechAdmin\desktop\NETWaddUsers_v25.2.22.ps1:44 char:13 + -AccountPassword (convertto-securestring Passw0rd2023 -As ... + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (-AccountPassword:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
e7504de635fbb28e003626390d33e7b4
{ "intermediate": 0.22819843888282776, "beginner": 0.555689811706543, "expert": 0.21611174941062927 }
46,084
New-ADUser : The object name has bad syntax At C:\Users\lbTechAdmin\desktop\NETWaddUsers_v25.2.22.ps1:30 char:1 + New-ADUser ` + ~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CN=\ ,Exec_gp:String) [New-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser -AccountPassword : The term ‘-AccountPassword’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Users\lbTechAdmin\desktop\NETWaddUsers_v25.2.22.ps1:44 char:13 + -AccountPassword (convertto-securestring Passw0rd2023 -As … + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (-AccountPassword:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
0002285d400a6aa3e1ff1d5c822490e2
{ "intermediate": 0.2439446747303009, "beginner": 0.5448411703109741, "expert": 0.21121422946453094 }
46,085
In the Incident table, there's a short description with a suggestion. When the suggestion is clicked, a pop-up box appears. However, the user only wants to see 2 of them
e08fa0791603e7fc76dd5f7a1630bf89
{ "intermediate": 0.2751133143901825, "beginner": 0.2783287763595581, "expert": 0.4465579092502594 }
46,086
hi
b229d6f3d0e4461d17906228dde9f482
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
46,087
in servicenow, Around one requirement we need to create ritm based on string filed value like user can add multi user ids on this filed (hr234;hr235;hr236), based on particular hr id create separate ritm for each Hr id. So How can I achieve this requirement
9678317b18cefc55f058693a523c11d7
{ "intermediate": 0.49664101004600525, "beginner": 0.1695849597454071, "expert": 0.33377403020858765 }
46,088
Write the body of the following static method, which, given a components.map.Map<String, Integer> representing employee names and corresponding salaries, raises (by the given percentage) the salary of every employee whose name starts with the given initial. Note that only simple integer arithmetic is needed to satisfy the postcondition. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 /** * Raises the salary of all the employees in {@code map} whose name starts * with the given {@code initial} by the given {@code raisePercent}. * * @param map * the name to salary map * @param initial * the initial of names of employees to be given a raise * @param raisePercent * the raise to be given as a percentage of the current salary * @updates map * @requires [the salaries in map are positive] and raisePercent > 0 * @ensures <pre> * DOMAIN(map) = DOMAIN(#map) and * [the salaries of the employees in map whose names start with the given * initial have been increased by raisePercent percent (and truncated to * the nearest integer); all other employees have the same salary] * </pre> */ private static void giveRaise(components.map.Map<String, Integer> map, char initial, int raisePercent) {...} Write the body of the following static method. It has the exact same contract as the previous one, but uses only standard Java components, including java.util.Map<String, Integer>. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 /** * Raises the salary of all the employees in {@code map} whose name starts * with the given {@code initial} by the given {@code raisePercent}. * * @param map * the name to salary map * @param initial * the initial of names of employees to be given a raise * @param raisePercent * the raise to be given as a percentage of the current salary * @updates map * @requires <pre> * [the salaries in map are positive] and raisePercent > 0 and * [the dynamic types of map and of all objects reachable from map * (including any objects returned by operations (such as entrySet() and, * from there, iterator()), and so on, recursively) support all * optional operations] * </pre> * @ensures <pre> * DOMAIN(map) = DOMAIN(#map) and * [the salaries of the employees in map whose names start with the given * initial have been increased by raisePercent percent (and truncated to * the nearest integer); all other employees have the same salary] * </pre> */ private static void giveRaise(java.util.Map<String, Integer> map, char initial, int raisePercent) {...}
ec036809153f19689a04f76552d29fb8
{ "intermediate": 0.374060720205307, "beginner": 0.2522340714931488, "expert": 0.3737052083015442 }
46,089
review this test contract // SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import { Test } from "forge-std/Test.sol"; import { Vm } from "forge-std/Vm.sol"; import { DisputeGameFactory_Init } from "test/dispute/DisputeGameFactory.t.sol"; import { DisputeGameFactory } from "src/dispute/DisputeGameFactory.sol"; import { FaultDisputeGame } from "src/dispute/FaultDisputeGame.sol"; import { DelayedWETH } from "src/dispute/weth/DelayedWETH.sol"; import { PreimageOracle } from "src/cannon/PreimageOracle.sol"; import "src/libraries/DisputeTypes.sol"; import "src/libraries/DisputeErrors.sol"; import { LibClock } from "src/dispute/lib/LibUDT.sol"; import { LibPosition } from "src/dispute/lib/LibPosition.sol"; import { IPreimageOracle } from "src/dispute/interfaces/IBigStepper.sol"; import { IAnchorStateRegistry } from "src/dispute/interfaces/IAnchorStateRegistry.sol"; import { AlphabetVM } from "test/mocks/AlphabetVM.sol"; import { DisputeActor, HonestDisputeActor } from "test/actors/FaultDisputeActors.sol"; contract FaultDisputeGame_Init is DisputeGameFactory_Init { /// @dev The type of the game being tested. GameType internal constant GAME_TYPE = GameType.wrap(0); /// @dev The implementation of the game. FaultDisputeGame internal gameImpl; /// @dev The `Clone` proxy of the game. FaultDisputeGame internal gameProxy; /// @dev The extra data passed to the game for initialization. bytes internal extraData; event Move(uint256 indexed parentIndex, Claim indexed pivot, address indexed claimant); function init(Claim rootClaim, Claim absolutePrestate, uint256 l2BlockNumber) public { // Set the time to a realistic date. vm.warp(1690906994); // Set the extra data for the game creation extraData = abi.encode(l2BlockNumber); AlphabetVM _vm = new AlphabetVM(absolutePrestate, new PreimageOracle(0, 0)); // Deploy an implementation of the fault game gameImpl = new FaultDisputeGame({ _gameType: GAME_TYPE, _absolutePrestate: absolutePrestate, _maxGameDepth: 2 ** 3, _splitDepth: 2 ** 2, _gameDuration: Duration.wrap(7 days), _vm: _vm, _weth: delayedWeth, _anchorStateRegistry: anchorStateRegistry, _l2ChainId: 10 }); // Register the game implementation with the factory. disputeGameFactory.setImplementation(GAME_TYPE, gameImpl); // Create a new game. gameProxy = FaultDisputeGame(payable(address(disputeGameFactory.create(GAME_TYPE, rootClaim, extraData)))); // Check immutables assertEq(gameProxy.gameType().raw(), GAME_TYPE.raw()); assertEq(gameProxy.absolutePrestate().raw(), absolutePrestate.raw()); assertEq(gameProxy.maxGameDepth(), 2 ** 3); assertEq(gameProxy.splitDepth(), 2 ** 2); assertEq(gameProxy.gameDuration().raw(), 7 days); assertEq(address(gameProxy.vm()), address(_vm)); // Label the proxy vm.label(address(gameProxy), "FaultDisputeGame_Clone"); } fallback() external payable { } receive() external payable { } } contract FaultDisputeGame_Test is FaultDisputeGame_Init { /// @dev The root claim of the game. Claim internal constant ROOT_CLAIM = Claim.wrap(bytes32((uint256(1) << 248) | uint256(10))); /// @dev The preimage of the absolute prestate claim bytes internal absolutePrestateData; /// @dev The absolute prestate of the trace. Claim internal absolutePrestate; function setUp() public override { absolutePrestateData = abi.encode(0); absolutePrestate = _changeClaimStatus(Claim.wrap(keccak256(absolutePrestateData)), VMStatuses.UNFINISHED); super.setUp(); super.init({ rootClaim: ROOT_CLAIM, absolutePrestate: absolutePrestate, l2BlockNumber: 0x10 }); } //////////////////////////////////////////////////////////////// // `IDisputeGame` Implementation Tests // //////////////////////////////////////////////////////////////// /// @dev Tests that the constructor of the `FaultDisputeGame` reverts when the `_splitDepth` /// parameter is greater than or equal to the `MAX_GAME_DEPTH` function test_constructor_wrongArgs_reverts(uint256 _splitDepth) public { AlphabetVM alphabetVM = new AlphabetVM(absolutePrestate, new PreimageOracle(0, 0)); // Test that the constructor reverts when the `_splitDepth` parameter is greater than or equal // to the `MAX_GAME_DEPTH` parameter. _splitDepth = bound(_splitDepth, 2 ** 3, type(uint256).max); vm.expectRevert(InvalidSplitDepth.selector); new FaultDisputeGame({ _gameType: GAME_TYPE, _absolutePrestate: absolutePrestate, _maxGameDepth: 2 ** 3, _splitDepth: _splitDepth, _gameDuration: Duration.wrap(7 days), _vm: alphabetVM, _weth: DelayedWETH(payable(address(0))), _anchorStateRegistry: IAnchorStateRegistry(address(0)), _l2ChainId: 10 }); } /// @dev Tests that the game's root claim is set correctly. function test_rootClaim_succeeds() public { assertEq(gameProxy.rootClaim().raw(), ROOT_CLAIM.raw()); } /// @dev Tests that the game's extra data is set correctly. function test_extraData_succeeds() public { assertEq(gameProxy.extraData(), extraData); } /// @dev Tests that the game's starting timestamp is set correctly. function test_createdAt_succeeds() public { assertEq(gameProxy.createdAt().raw(), block.timestamp); } /// @dev Tests that the game's type is set correctly. function test_gameType_succeeds() public { assertEq(gameProxy.gameType().raw(), GAME_TYPE.raw()); } /// @dev Tests that the game's data is set correctly. function test_gameData_succeeds() public { (GameType gameType, Claim rootClaim, bytes memory _extraData) = gameProxy.gameData(); assertEq(gameType.raw(), GAME_TYPE.raw()); assertEq(rootClaim.raw(), ROOT_CLAIM.raw()); assertEq(_extraData, extraData); } //////////////////////////////////////////////////////////////// // `IFaultDisputeGame` Implementation Tests // //////////////////////////////////////////////////////////////// /// @dev Tests that the game cannot be initialized with an output root that commits to <= the configured starting /// block number function testFuzz_initialize_cannotProposeGenesis_reverts(uint256 _blockNumber) public { (, uint256 startingL2Block) = gameProxy.startingOutputRoot(); _blockNumber = bound(_blockNumber, 0, startingL2Block); Claim claim = _dummyClaim(); vm.expectRevert(abi.encodeWithSelector(UnexpectedRootClaim.selector, claim)); gameProxy = FaultDisputeGame(payable(address(disputeGameFactory.create(GAME_TYPE, claim, abi.encode(_blockNumber))))); } /// @dev Tests that the proxy receives ETH from the dispute game factory. function test_initialize_receivesETH_succeeds() public { uint256 _value = disputeGameFactory.initBonds(GAME_TYPE); vm.deal(address(this), _value); assertEq(address(gameProxy).balance, 0); gameProxy = FaultDisputeGame( payable(address(disputeGameFactory.create{ value: _value }(GAME_TYPE, ROOT_CLAIM, abi.encode(1)))) ); assertEq(address(gameProxy).balance, 0); assertEq(delayedWeth.balanceOf(address(gameProxy)), _value); } /// @dev Tests that the game cannot be initialized with extra data > 64 bytes long (root claim + l2 block number /// concatenated) function testFuzz_initialize_extraDataTooLong_reverts(uint256 _extraDataLen) public { // The `DisputeGameFactory` will pack the root claim and the extra data into a single array, which is enforced // to be at least 64 bytes long. // We bound the upper end to 23.5KB to ensure that the minimal proxy never surpasses the contract size limit // in this test, as CWIA proxies store the immutable args in their bytecode. // [33 bytes, 23.5 KB] _extraDataLen = bound(_extraDataLen, 33, 23_500); bytes memory _extraData = new bytes(_extraDataLen); // Assign the first 32 bytes in `extraData` to a valid L2 block number passed the starting block. (, uint256 startingL2Block) = gameProxy.startingOutputRoot(); assembly { mstore(add(_extraData, 0x20), add(startingL2Block, 1)) } Claim claim = _dummyClaim(); vm.expectRevert(abi.encodeWithSelector(ExtraDataTooLong.selector)); gameProxy = FaultDisputeGame(payable(address(disputeGameFactory.create(GAME_TYPE, claim, _extraData)))); } /// @dev Tests that the game is initialized with the correct data. function test_initialize_correctData_succeeds() public { // Assert that the root claim is initialized correctly. ( uint32 parentIndex, address counteredBy, address claimant, uint128 bond, Claim claim, Position position, Clock clock ) = gameProxy.claimData(0); assertEq(parentIndex, type(uint32).max); assertEq(counteredBy, address(0)); assertEq(claimant, DEFAULT_SENDER); assertEq(bond, 0); assertEq(claim.raw(), ROOT_CLAIM.raw()); assertEq(position.raw(), 1); assertEq(clock.raw(), LibClock.wrap(Duration.wrap(0), Timestamp.wrap(uint64(block.timestamp))).raw()); // Assert that the `createdAt` timestamp is correct. assertEq(gameProxy.createdAt().raw(), block.timestamp); // Assert that the blockhash provided is correct. assertEq(gameProxy.l1Head().raw(), blockhash(block.number - 1)); } /// @dev Tests that the game cannot be initialized twice. function test_initialize_onlyOnce_succeeds() public { vm.expectRevert(AlreadyInitialized.selector); gameProxy.initialize(); } /// @dev Tests that the bond during the bisection game depths is correct. function test_getRequiredBond_succeeds() public { for (uint64 i = 0; i < uint64(gameProxy.splitDepth()); i++) { Position pos = LibPosition.wrap(i, 0); uint256 bond = gameProxy.getRequiredBond(pos); // Reasonable approximation for a max depth of 8. uint256 expected = 0.08 ether; for (uint64 j = 0; j < i; j++) { expected = expected * 217456; expected = expected / 100000; } assertApproxEqAbs(bond, expected, 0.01 ether); } } /// @dev Tests that the bond at a depth greater than the maximum game depth reverts. function test_getRequiredBond_outOfBounds_reverts() public { Position pos = LibPosition.wrap(uint64(gameProxy.maxGameDepth() + 1), 0); vm.expectRevert(GameDepthExceeded.selector); gameProxy.getRequiredBond(pos); } /// @dev Tests that a move while the game status is not `IN_PROGRESS` causes the call to revert /// with the `GameNotInProgress` error function test_move_gameNotInProgress_reverts() public { uint256 chalWins = uint256(GameStatus.CHALLENGER_WINS); // Replace the game status in storage. It exists in slot 0 at offset 16. uint256 slot = uint256(vm.load(address(gameProxy), bytes32(0))); uint256 offset = 16 << 3; uint256 mask = 0xFF << offset; // Replace the byte in the slot value with the challenger wins status. slot = (slot & ~mask) | (chalWins << offset); vm.store(address(gameProxy), bytes32(0), bytes32(slot)); // Ensure that the game status was properly updated. GameStatus status = gameProxy.status(); assertEq(uint256(status), chalWins); // Attempt to make a move. Should revert. vm.expectRevert(GameNotInProgress.selector); gameProxy.attack(0, Claim.wrap(0)); } /// @dev Tests that an attempt to defend the root claim reverts with the `CannotDefendRootClaim` error. function test_move_defendRoot_reverts() public { vm.expectRevert(CannotDefendRootClaim.selector); gameProxy.defend(0, _dummyClaim()); } /// @dev Tests that an attempt to move against a claim that does not exist reverts with the /// `ParentDoesNotExist` error. function test_move_nonExistentParent_reverts() public { Claim claim = _dummyClaim(); // Expect an out of bounds revert for an attack vm.expectRevert(abi.encodeWithSignature("Panic(uint256)", 0x32)); gameProxy.attack(1, claim); // Expect an out of bounds revert for a defense vm.expectRevert(abi.encodeWithSignature("Panic(uint256)", 0x32)); gameProxy.defend(1, claim); } /// @dev Tests that an attempt to move at the maximum game depth reverts with the /// `GameDepthExceeded` error. function test_move_gameDepthExceeded_reverts() public { Claim claim = _changeClaimStatus(_dummyClaim(), VMStatuses.PANIC); uint256 maxDepth = gameProxy.maxGameDepth(); for (uint256 i = 0; i <= maxDepth; i++) { // At the max game depth, the `_move` function should revert with // the `GameDepthExceeded` error. if (i == maxDepth) { vm.expectRevert(GameDepthExceeded.selector); gameProxy.attack{ value: 100 ether }(i, claim); } else { gameProxy.attack{ value: _getRequiredBond(i) }(i, claim); } } } /// @dev Tests that a move made after the clock time has exceeded reverts with the /// `ClockTimeExceeded` error. function test_move_clockTimeExceeded_reverts() public { // Warp ahead past the clock time for the first move (3 1/2 days) vm.warp(block.timestamp + 3 days + 12 hours + 1); uint256 bond = _getRequiredBond(0); vm.expectRevert(ClockTimeExceeded.selector); gameProxy.attack{ value: bond }(0, _dummyClaim()); } /// @notice Static unit test for the correctness of the chess clock incrementation. function test_move_clockCorrectness_succeeds() public { (,,,,,, Clock clock) = gameProxy.claimData(0); assertEq(clock.raw(), LibClock.wrap(Duration.wrap(0), Timestamp.wrap(uint64(block.timestamp))).raw()); Claim claim = _dummyClaim(); vm.warp(block.timestamp + 15); uint256 bond = _getRequiredBond(0); gameProxy.attack{ value: bond }(0, claim); (,,,,,, clock) = gameProxy.claimData(1); assertEq(clock.raw(), LibClock.wrap(Duration.wrap(15), Timestamp.wrap(uint64(block.timestamp))).raw()); vm.warp(block.timestamp + 10); bond = _getRequiredBond(1); gameProxy.attack{ value: bond }(1, claim); (,,,,,, clock) = gameProxy.claimData(2); assertEq(clock.raw(), LibClock.wrap(Duration.wrap(10), Timestamp.wrap(uint64(block.timestamp))).raw()); // We are at the split depth, so we need to set the status byte of the claim // for the next move. claim = _changeClaimStatus(claim, VMStatuses.PANIC); vm.warp(block.timestamp + 10); bond = _getRequiredBond(2); gameProxy.attack{ value: bond }(2, claim); (,,,,,, clock) = gameProxy.claimData(3); assertEq(clock.raw(), LibClock.wrap(Duration.wrap(25), Timestamp.wrap(uint64(block.timestamp))).raw()); vm.warp(block.timestamp + 10); bond = _getRequiredBond(3); gameProxy.attack{ value: bond }(3, claim); (,,,,,, clock) = gameProxy.claimData(4); assertEq(clock.raw(), LibClock.wrap(Duration.wrap(20), Timestamp.wrap(uint64(block.timestamp))).raw()); } /// @dev Tests that an identical claim cannot be made twice. The duplicate claim attempt should /// revert with the `ClaimAlreadyExists` error. function test_move_duplicateClaim_reverts() public { Claim claim = _dummyClaim(); // Make the first move. This should succeed. uint256 bond = _getRequiredBond(0); gameProxy.attack{ value: bond }(0, claim); // Attempt to make the same move again. vm.expectRevert(ClaimAlreadyExists.selector); gameProxy.attack{ value: bond }(0, claim); } /// @dev Static unit test asserting that identical claims at the same position can be made in different subgames. function test_move_duplicateClaimsDifferentSubgames_succeeds() public { Claim claimA = _dummyClaim(); Claim claimB = _dummyClaim(); // Make the first moves. This should succeed. uint256 bond = _getRequiredBond(0); gameProxy.attack{ value: bond }(0, claimA); gameProxy.attack{ value: bond }(0, claimB); // Perform an attack at the same position with the same claim value in both subgames. // These both should succeed. bond = _getRequiredBond(1); gameProxy.attack{ value: bond }(1, claimA); bond = _getRequiredBond(2); gameProxy.attack{ value: bond }(2, claimA); } /// @dev Static unit test for the correctness of an opening attack. function test_move_simpleAttack_succeeds() public { // Warp ahead 5 seconds. vm.warp(block.timestamp + 5); Claim counter = _dummyClaim(); // Perform the attack. uint256 reqBond = _getRequiredBond(0); vm.expectEmit(true, true, true, false); emit Move(0, counter, address(this)); gameProxy.attack{ value: reqBond }(0, counter); // Grab the claim data of the attack. ( uint32 parentIndex, address counteredBy, address claimant, uint128 bond, Claim claim, Position position, Clock clock ) = gameProxy.claimData(1); // Assert correctness of the attack claim's data. assertEq(parentIndex, 0); assertEq(counteredBy, address(0)); assertEq(claimant, address(this)); assertEq(bond, reqBond); assertEq(claim.raw(), counter.raw()); assertEq(position.raw(), Position.wrap(1).move(true).raw()); assertEq(clock.raw(), LibClock.wrap(Duration.wrap(5), Timestamp.wrap(uint64(block.timestamp))).raw()); // Grab the claim data of the parent. (parentIndex, counteredBy, claimant, bond, claim, position, clock) = gameProxy.claimData(0); // Assert correctness of the parent claim's data. assertEq(parentIndex, type(uint32).max); assertEq(counteredBy, address(0)); assertEq(claimant, DEFAULT_SENDER); assertEq(bond, 0); assertEq(claim.raw(), ROOT_CLAIM.raw()); assertEq(position.raw(), 1); assertEq(clock.raw(), LibClock.wrap(Duration.wrap(0), Timestamp.wrap(uint64(block.timestamp - 5))).raw()); } /// @dev Tests that making a claim at the execution trace bisection root level with an invalid status /// byte reverts with the `UnexpectedRootClaim` error. function test_move_incorrectStatusExecRoot_reverts() public { for (uint256 i; i < 4; i++) { gameProxy.attack{ value: _getRequiredBond(i) }(i, _dummyClaim()); } uint256 bond = _getRequiredBond(4); vm.expectRevert(abi.encodeWithSelector(UnexpectedRootClaim.selector, bytes32(0))); gameProxy.attack{ value: bond }(4, Claim.wrap(bytes32(0))); } /// @dev Tests that making a claim at the execution trace bisection root level with a valid status /// byte succeeds. function test_move_correctStatusExecRoot_succeeds() public { for (uint256 i; i < 4; i++) { uint256 bond = _getRequiredBond(i); gameProxy.attack{ value: bond }(i, _dummyClaim()); } uint256 lastBond = _getRequiredBond(4); gameProxy.attack{ value: lastBond }(4, _changeClaimStatus(_dummyClaim(), VMStatuses.PANIC)); } /// @dev Static unit test asserting that a move reverts when the bonded amount is incorrect. function test_move_incorrectBondAmount_reverts() public { vm.expectRevert(IncorrectBondAmount.selector); gameProxy.attack{ value: 0 }(0, _dummyClaim()); } /// @dev Tests that a claim cannot be stepped against twice. function test_step_duplicateStep_reverts() public { // Give the test contract some ether vm.deal(address(this), 1000 ether); // Make claims all the way down the tree. gameProxy.attack{ value: _getRequiredBond(0) }(0, _dummyClaim()); gameProxy.attack{ value: _getRequiredBond(1) }(1, _dummyClaim()); gameProxy.attack{ value: _getRequiredBond(2) }(2, _dummyClaim()); gameProxy.attack{ value: _getRequiredBond(3) }(3, _dummyClaim()); gameProxy.attack{ value: _getRequiredBond(4) }(4, _changeClaimStatus(_dummyClaim(), VMStatuses.PANIC)); gameProxy.attack{ value: _getRequiredBond(5) }(5, _dummyClaim()); gameProxy.attack{ value: _getRequiredBond(6) }(6, _dummyClaim()); gameProxy.attack{ value: _getRequiredBond(7) }(7, _dummyClaim()); gameProxy.addLocalData(LocalPreimageKey.DISPUTED_L2_BLOCK_NUMBER, 8, 0); gameProxy.step(8, true, absolutePrestateData, hex""); vm.expectRevert(DuplicateStep.selector); gameProxy.step(8, true, absolutePrestateData, hex""); } /// @dev Static unit test for the correctness an uncontested root resolution. function test_resolve_rootUncontested_succeeds() public { vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); gameProxy.resolveClaim(0); assertEq(uint8(gameProxy.resolve()), uint8(GameStatus.DEFENDER_WINS)); } /// @dev Static unit test for the correctness an uncontested root resolution. function test_resolve_rootUncontestedClockNotExpired_succeeds() public { vm.warp(block.timestamp + 3 days + 12 hours); vm.expectRevert(ClockNotExpired.selector); gameProxy.resolveClaim(0); } /// @dev Static unit test asserting that resolve reverts when the absolute root /// subgame has not been resolved. function test_resolve_rootUncontestedButUnresolved_reverts() public { vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); vm.expectRevert(OutOfOrderResolution.selector); gameProxy.resolve(); } /// @dev Static unit test asserting that resolve reverts when the game state is /// not in progress. function test_resolve_notInProgress_reverts() public { uint256 chalWins = uint256(GameStatus.CHALLENGER_WINS); // Replace the game status in storage. It exists in slot 0 at offset 16. uint256 slot = uint256(vm.load(address(gameProxy), bytes32(0))); uint256 offset = 16 << 3; uint256 mask = 0xFF << offset; // Replace the byte in the slot value with the challenger wins status. slot = (slot & ~mask) | (chalWins << offset); vm.store(address(gameProxy), bytes32(uint256(0)), bytes32(slot)); vm.expectRevert(GameNotInProgress.selector); gameProxy.resolveClaim(0); } /// @dev Static unit test for the correctness of resolving a single attack game state. function test_resolve_rootContested_succeeds() public { gameProxy.attack{ value: _getRequiredBond(0) }(0, _dummyClaim()); vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); gameProxy.resolveClaim(0); assertEq(uint8(gameProxy.resolve()), uint8(GameStatus.CHALLENGER_WINS)); } /// @dev Static unit test for the correctness of resolving a game with a contested challenge claim. function test_resolve_challengeContested_succeeds() public { gameProxy.attack{ value: _getRequiredBond(0) }(0, _dummyClaim()); gameProxy.defend{ value: _getRequiredBond(1) }(1, _dummyClaim()); vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); gameProxy.resolveClaim(1); gameProxy.resolveClaim(0); assertEq(uint8(gameProxy.resolve()), uint8(GameStatus.DEFENDER_WINS)); } /// @dev Static unit test for the correctness of resolving a game with multiplayer moves. function test_resolve_teamDeathmatch_succeeds() public { gameProxy.attack{ value: _getRequiredBond(0) }(0, _dummyClaim()); gameProxy.attack{ value: _getRequiredBond(0) }(0, _dummyClaim()); gameProxy.defend{ value: _getRequiredBond(1) }(1, _dummyClaim()); gameProxy.defend{ value: _getRequiredBond(1) }(1, _dummyClaim()); vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); gameProxy.resolveClaim(1); gameProxy.resolveClaim(0); assertEq(uint8(gameProxy.resolve()), uint8(GameStatus.CHALLENGER_WINS)); } /// @dev Static unit test for the correctness of resolving a game that reaches max game depth. function test_resolve_stepReached_succeeds() public { Claim claim = _dummyClaim(); for (uint256 i; i < gameProxy.splitDepth(); i++) { gameProxy.attack{ value: _getRequiredBond(i) }(i, claim); } claim = _changeClaimStatus(claim, VMStatuses.PANIC); for (uint256 i = gameProxy.claimDataLen() - 1; i < gameProxy.maxGameDepth(); i++) { gameProxy.attack{ value: _getRequiredBond(i) }(i, claim); } vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); // resolving claim at 8 isn't necessary for (uint256 i = 8; i > 0; i--) { gameProxy.resolveClaim(i - 1); } assertEq(uint8(gameProxy.resolve()), uint8(GameStatus.DEFENDER_WINS)); } /// @dev Static unit test asserting that resolve reverts when attempting to resolve a subgame multiple times function test_resolve_claimAlreadyResolved_reverts() public { Claim claim = _dummyClaim(); uint256 firstBond = _getRequiredBond(0); vm.deal(address(this), firstBond); gameProxy.attack{ value: firstBond }(0, claim); uint256 secondBond = _getRequiredBond(1); vm.deal(address(this), secondBond); gameProxy.attack{ value: secondBond }(1, claim); vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); assertEq(address(this).balance, 0); gameProxy.resolveClaim(1); // Wait for the withdrawal delay. vm.warp(block.timestamp + delayedWeth.delay() + 1 seconds); gameProxy.claimCredit(address(this)); assertEq(address(this).balance, firstBond); vm.expectRevert(ClaimAlreadyResolved.selector); gameProxy.resolveClaim(1); assertEq(address(this).balance, firstBond); } /// @dev Static unit test asserting that resolve reverts when attempting to resolve a subgame at max depth function test_resolve_claimAtMaxDepthAlreadyResolved_reverts() public { Claim claim = _dummyClaim(); for (uint256 i; i < gameProxy.splitDepth(); i++) { gameProxy.attack{ value: _getRequiredBond(i) }(i, claim); } vm.deal(address(this), 10000 ether); claim = _changeClaimStatus(claim, VMStatuses.PANIC); for (uint256 i = gameProxy.claimDataLen() - 1; i < gameProxy.maxGameDepth(); i++) { gameProxy.attack{ value: _getRequiredBond(i) }(i, claim); } vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); // Resolve to claim bond uint256 balanceBefore = address(this).balance; gameProxy.resolveClaim(8); // Wait for the withdrawal delay. vm.warp(block.timestamp + delayedWeth.delay() + 1 seconds); gameProxy.claimCredit(address(this)); assertEq(address(this).balance, balanceBefore + _getRequiredBond(7)); vm.expectRevert(ClaimAlreadyResolved.selector); gameProxy.resolveClaim(8); } /// @dev Static unit test asserting that resolve reverts when attempting to resolve subgames out of order function test_resolve_outOfOrderResolution_reverts() public { gameProxy.attack{ value: _getRequiredBond(0) }(0, _dummyClaim()); gameProxy.attack{ value: _getRequiredBond(1) }(1, _dummyClaim()); vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); vm.expectRevert(OutOfOrderResolution.selector); gameProxy.resolveClaim(0); } /// @dev Static unit test asserting that resolve pays out bonds on step, output bisection, and execution trace /// moves. function test_resolve_bondPayouts_succeeds() public { // Give the test contract some ether uint256 bal = 1000 ether; vm.deal(address(this), bal); // Make claims all the way down the tree. uint256 bond = _getRequiredBond(0); uint256 totalBonded = bond; gameProxy.attack{ value: bond }(0, _dummyClaim()); bond = _getRequiredBond(1); totalBonded += bond; gameProxy.attack{ value: bond }(1, _dummyClaim()); bond = _getRequiredBond(2); totalBonded += bond; gameProxy.attack{ value: bond }(2, _dummyClaim()); bond = _getRequiredBond(3); totalBonded += bond; gameProxy.attack{ value: bond }(3, _dummyClaim()); bond = _getRequiredBond(4); totalBonded += bond; gameProxy.attack{ value: bond }(4, _changeClaimStatus(_dummyClaim(), VMStatuses.PANIC)); bond = _getRequiredBond(5); totalBonded += bond; gameProxy.attack{ value: bond }(5, _dummyClaim()); bond = _getRequiredBond(6); totalBonded += bond; gameProxy.attack{ value: bond }(6, _dummyClaim()); bond = _getRequiredBond(7); totalBonded += bond; gameProxy.attack{ value: bond }(7, _dummyClaim()); gameProxy.addLocalData(LocalPreimageKey.DISPUTED_L2_BLOCK_NUMBER, 8, 0); gameProxy.step(8, true, absolutePrestateData, hex""); // Ensure that the step successfully countered the leaf claim. (, address counteredBy,,,,,) = gameProxy.claimData(8); assertEq(counteredBy, address(this)); // Ensure we bonded the correct amounts assertEq(address(this).balance, bal - totalBonded); assertEq(address(gameProxy).balance, 0); assertEq(delayedWeth.balanceOf(address(gameProxy)), totalBonded); // Resolve all claims vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); for (uint256 i = gameProxy.claimDataLen(); i > 0; i--) { (bool success,) = address(gameProxy).call(abi.encodeCall(gameProxy.resolveClaim, (i - 1))); assertTrue(success); } gameProxy.resolve(); // Wait for the withdrawal delay. vm.warp(block.timestamp + delayedWeth.delay() + 1 seconds); gameProxy.claimCredit(address(this)); // Ensure that bonds were paid out correctly. assertEq(address(this).balance, bal); assertEq(address(gameProxy).balance, 0); assertEq(delayedWeth.balanceOf(address(gameProxy)), 0); // Ensure that the init bond for the game is 0, in case we change it in the test suite in the future. assertEq(disputeGameFactory.initBonds(GAME_TYPE), 0); } /// @dev Static unit test asserting that resolve pays out bonds on step, output bisection, and execution trace /// moves with 2 actors and a dishonest root claim. function test_resolve_bondPayoutsSeveralActors_succeeds() public { // Give the test contract and bob some ether uint256 bal = 1000 ether; address bob = address(0xb0b); vm.deal(address(this), bal); vm.deal(bob, bal); // Make claims all the way down the tree, trading off between bob and the test contract. uint256 firstBond = _getRequiredBond(0); uint256 thisBonded = firstBond; gameProxy.attack{ value: firstBond }(0, _dummyClaim()); uint256 secondBond = _getRequiredBond(1); uint256 bobBonded = secondBond; vm.prank(bob); gameProxy.attack{ value: secondBond }(1, _dummyClaim()); uint256 thirdBond = _getRequiredBond(2); thisBonded += thirdBond; gameProxy.attack{ value: thirdBond }(2, _dummyClaim()); uint256 fourthBond = _getRequiredBond(3); bobBonded += fourthBond; vm.prank(bob); gameProxy.attack{ value: fourthBond }(3, _dummyClaim()); uint256 fifthBond = _getRequiredBond(4); thisBonded += fifthBond; gameProxy.attack{ value: fifthBond }(4, _changeClaimStatus(_dummyClaim(), VMStatuses.PANIC)); uint256 sixthBond = _getRequiredBond(5); bobBonded += sixthBond; vm.prank(bob); gameProxy.attack{ value: sixthBond }(5, _dummyClaim()); uint256 seventhBond = _getRequiredBond(6); thisBonded += seventhBond; gameProxy.attack{ value: seventhBond }(6, _dummyClaim()); uint256 eighthBond = _getRequiredBond(7); bobBonded += eighthBond; vm.prank(bob); gameProxy.attack{ value: eighthBond }(7, _dummyClaim()); gameProxy.addLocalData(LocalPreimageKey.DISPUTED_L2_BLOCK_NUMBER, 8, 0); gameProxy.step(8, true, absolutePrestateData, hex""); // Ensure that the step successfully countered the leaf claim. (, address counteredBy,,,,,) = gameProxy.claimData(8); assertEq(counteredBy, address(this)); // Ensure we bonded the correct amounts assertEq(address(this).balance, bal - thisBonded); assertEq(bob.balance, bal - bobBonded); assertEq(address(gameProxy).balance, 0); assertEq(delayedWeth.balanceOf(address(gameProxy)), thisBonded + bobBonded); // Resolve all claims vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); for (uint256 i = gameProxy.claimDataLen(); i > 0; i--) { (bool success,) = address(gameProxy).call(abi.encodeCall(gameProxy.resolveClaim, (i - 1))); assertTrue(success); } gameProxy.resolve(); // Wait for the withdrawal delay. vm.warp(block.timestamp + delayedWeth.delay() + 1 seconds); gameProxy.claimCredit(address(this)); // Bob's claim should revert since it's value is 0 vm.expectRevert(NoCreditToClaim.selector); gameProxy.claimCredit(bob); // Ensure that bonds were paid out correctly. assertEq(address(this).balance, bal + bobBonded); assertEq(bob.balance, bal - bobBonded); assertEq(address(gameProxy).balance, 0); assertEq(delayedWeth.balanceOf(address(gameProxy)), 0); // Ensure that the init bond for the game is 0, in case we change it in the test suite in the future. assertEq(disputeGameFactory.initBonds(GAME_TYPE), 0); } /// @dev Static unit test asserting that resolve pays out bonds on moves to the leftmost actor /// in subgames containing successful counters. function test_resolve_leftmostBondPayout_succeeds() public { uint256 bal = 1000 ether; address alice = address(0xa11ce); address bob = address(0xb0b); address charlie = address(0xc0c); vm.deal(address(this), bal); vm.deal(alice, bal); vm.deal(bob, bal); vm.deal(charlie, bal); // Make claims with bob, charlie and the test contract on defense, and alice as the challenger // charlie is successfully countered by alice // alice is successfully countered by both bob and the test contract uint256 firstBond = _getRequiredBond(0); vm.prank(alice); gameProxy.attack{ value: firstBond }(0, _dummyClaim()); uint256 secondBond = _getRequiredBond(1); vm.prank(bob); gameProxy.defend{ value: secondBond }(1, _dummyClaim()); vm.prank(charlie); gameProxy.attack{ value: secondBond }(1, _dummyClaim()); gameProxy.attack{ value: secondBond }(1, _dummyClaim()); uint256 thirdBond = _getRequiredBond(3); vm.prank(alice); gameProxy.attack{ value: thirdBond }(3, _dummyClaim()); // Resolve all claims vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); for (uint256 i = gameProxy.claimDataLen(); i > 0; i--) { (bool success,) = address(gameProxy).call(abi.encodeCall(gameProxy.resolveClaim, (i - 1))); assertTrue(success); } gameProxy.resolve(); // Wait for the withdrawal delay. vm.warp(block.timestamp + delayedWeth.delay() + 1 seconds); gameProxy.claimCredit(address(this)); gameProxy.claimCredit(alice); gameProxy.claimCredit(bob); // Charlie's claim should revert since it's value is 0 vm.expectRevert(NoCreditToClaim.selector); gameProxy.claimCredit(charlie); // Ensure that bonds were paid out correctly. uint256 aliceLosses = firstBond; uint256 charlieLosses = secondBond; assertEq(address(this).balance, bal + aliceLosses, "incorrect this balance"); assertEq(alice.balance, bal - aliceLosses + charlieLosses, "incorrect alice balance"); assertEq(bob.balance, bal, "incorrect bob balance"); assertEq(charlie.balance, bal - charlieLosses, "incorrect charlie balance"); assertEq(address(gameProxy).balance, 0); // Ensure that the init bond for the game is 0, in case we change it in the test suite in the future. assertEq(disputeGameFactory.initBonds(GAME_TYPE), 0); } /// @dev Static unit test asserting that the anchor state updates when the game resolves in /// favor of the defender and the anchor state is older than the game state. function test_resolve_validNewerStateUpdatesAnchor_succeeds() public { // Confirm that the anchor state is older than the game state. (Hash root, uint256 l2BlockNumber) = anchorStateRegistry.anchors(gameProxy.gameType()); assert(l2BlockNumber < gameProxy.l2BlockNumber()); // Resolve the game. vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); gameProxy.resolveClaim(0); assertEq(uint8(gameProxy.resolve()), uint8(GameStatus.DEFENDER_WINS)); // Confirm that the anchor state is now the same as the game state. (root, l2BlockNumber) = anchorStateRegistry.anchors(gameProxy.gameType()); assertEq(l2BlockNumber, gameProxy.l2BlockNumber()); assertEq(root.raw(), gameProxy.rootClaim().raw()); } /// @dev Static unit test asserting that the anchor state does not change when the game /// resolves in favor of the defender but the game state is not newer than the anchor state. function test_resolve_validOlderStateSameAnchor_succeeds() public { // Mock the game block to be older than the game state. vm.mockCall(address(gameProxy), abi.encodeWithSelector(gameProxy.l2BlockNumber.selector), abi.encode(0)); // Confirm that the anchor state is newer than the game state. (Hash root, uint256 l2BlockNumber) = anchorStateRegistry.anchors(gameProxy.gameType()); assert(l2BlockNumber >= gameProxy.l2BlockNumber()); // Resolve the game. vm.mockCall(address(gameProxy), abi.encodeWithSelector(gameProxy.l2BlockNumber.selector), abi.encode(0)); vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); gameProxy.resolveClaim(0); assertEq(uint8(gameProxy.resolve()), uint8(GameStatus.DEFENDER_WINS)); // Confirm that the anchor state is the same as the initial anchor state. (Hash updatedRoot, uint256 updatedL2BlockNumber) = anchorStateRegistry.anchors(gameProxy.gameType()); assertEq(updatedL2BlockNumber, l2BlockNumber); assertEq(updatedRoot.raw(), root.raw()); } /// @dev Static unit test asserting that the anchor state does not change when the game /// resolves in favor of the challenger, even if the game state is newer than the anchor. function test_resolve_invalidStateSameAnchor_succeeds() public { // Confirm that the anchor state is older than the game state. (Hash root, uint256 l2BlockNumber) = anchorStateRegistry.anchors(gameProxy.gameType()); assert(l2BlockNumber < gameProxy.l2BlockNumber()); // Challenge the claim and resolve it. gameProxy.attack{ value: _getRequiredBond(0) }(0, _dummyClaim()); vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); gameProxy.resolveClaim(0); assertEq(uint8(gameProxy.resolve()), uint8(GameStatus.CHALLENGER_WINS)); // Confirm that the anchor state is the same as the initial anchor state. (Hash updatedRoot, uint256 updatedL2BlockNumber) = anchorStateRegistry.anchors(gameProxy.gameType()); assertEq(updatedL2BlockNumber, l2BlockNumber); assertEq(updatedRoot.raw(), root.raw()); } /// @dev Static unit test asserting that credit may not be drained past allowance through reentrancy. function test_claimCredit_claimAlreadyResolved_reverts() public { ClaimCreditReenter reenter = new ClaimCreditReenter(gameProxy, vm); vm.startPrank(address(reenter)); // Give the game proxy 1 extra ether, unregistered. vm.deal(address(gameProxy), 1 ether); // Perform a bonded move. Claim claim = _dummyClaim(); uint256 firstBond = _getRequiredBond(0); vm.deal(address(reenter), firstBond); gameProxy.attack{ value: firstBond }(0, claim); uint256 secondBond = _getRequiredBond(1); vm.deal(address(reenter), secondBond); gameProxy.attack{ value: secondBond }(1, claim); uint256 reenterBond = firstBond + secondBond; // Warp past the finalization period vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); // Ensure that we bonded all the test contract's ETH assertEq(address(reenter).balance, 0); // Ensure the game proxy has 1 ether in it. assertEq(address(gameProxy).balance, 1 ether); // Ensure the game has a balance of reenterBond in the delayedWeth contract. assertEq(delayedWeth.balanceOf(address(gameProxy)), reenterBond); // Resolve the claim at gindex 1 and claim the reenter contract's credit. gameProxy.resolveClaim(1); // Ensure that the game registered the `reenter` contract's credit. assertEq(gameProxy.credit(address(reenter)), firstBond); // Wait for the withdrawal delay. vm.warp(block.timestamp + delayedWeth.delay() + 1 seconds); // Initiate the reentrant credit claim. reenter.claimCredit(address(reenter)); // The reenter contract should have performed 2 calls to `claimCredit`. // Once all the credit is claimed, all subsequent calls will revert since there is 0 credit left to claim. // The claimant must only have received the amount bonded for the gindex 1 subgame. // The root claim bond and the unregistered ETH should still exist in the game proxy. assertEq(reenter.numCalls(), 2); assertEq(address(reenter).balance, firstBond); assertEq(address(gameProxy).balance, 1 ether); assertEq(delayedWeth.balanceOf(address(gameProxy)), secondBond); vm.stopPrank(); } /// @dev Tests that adding local data with an out of bounds identifier reverts. function testFuzz_addLocalData_oob_reverts(uint256 _ident) public { // Get a claim below the split depth so that we can add local data for an execution trace subgame. for (uint256 i; i < 4; i++) { uint256 bond = _getRequiredBond(i); gameProxy.attack{ value: bond }(i, _dummyClaim()); } uint256 lastBond = _getRequiredBond(4); gameProxy.attack{ value: lastBond }(4, _changeClaimStatus(_dummyClaim(), VMStatuses.PANIC)); // [1, 5] are valid local data identifiers. if (_ident <= 5) _ident = 0; vm.expectRevert(InvalidLocalIdent.selector); gameProxy.addLocalData(_ident, 5, 0); } /// @dev Tests that local data is loaded into the preimage oracle correctly in the subgame /// that is disputing the transition from `GENESIS -> GENESIS + 1` function test_addLocalDataGenesisTransition_static_succeeds() public { IPreimageOracle oracle = IPreimageOracle(address(gameProxy.vm().oracle())); // Get a claim below the split depth so that we can add local data for an execution trace subgame. for (uint256 i; i < 4; i++) { uint256 bond = _getRequiredBond(i); gameProxy.attack{ value: bond }(i, Claim.wrap(bytes32(i))); } uint256 lastBond = _getRequiredBond(4); gameProxy.attack{ value: lastBond }(4, _changeClaimStatus(_dummyClaim(), VMStatuses.PANIC)); // Expected start/disputed claims (Hash root,) = gameProxy.startingOutputRoot(); bytes32 startingClaim = root.raw(); bytes32 disputedClaim = bytes32(uint256(3)); Position disputedPos = LibPosition.wrap(4, 0); // Expected local data bytes32[5] memory data = [ gameProxy.l1Head().raw(), startingClaim, disputedClaim, bytes32(uint256(1) << 0xC0), bytes32(gameProxy.l2ChainId() << 0xC0) ]; for (uint256 i = 1; i <= 5; i++) { uint256 expectedLen = i > 3 ? 8 : 32; bytes32 key = _getKey(i, keccak256(abi.encode(disputedClaim, disputedPos))); gameProxy.addLocalData(i, 5, 0); (bytes32 dat, uint256 datLen) = oracle.readPreimage(key, 0); assertEq(dat >> 0xC0, bytes32(expectedLen)); // Account for the length prefix if i > 3 (the data stored // at identifiers i <= 3 are 32 bytes long, so the expected // length is already correct. If i > 3, the data is only 8 // bytes long, so the length prefix + the data is 16 bytes // total.) assertEq(datLen, expectedLen + (i > 3 ? 8 : 0)); gameProxy.addLocalData(i, 5, 8); (dat, datLen) = oracle.readPreimage(key, 8); assertEq(dat, data[i - 1]); assertEq(datLen, expectedLen); } } /// @dev Tests that local data is loaded into the preimage oracle correctly. function test_addLocalDataMiddle_static_succeeds() public { IPreimageOracle oracle = IPreimageOracle(address(gameProxy.vm().oracle())); // Get a claim below the split depth so that we can add local data for an execution trace subgame. for (uint256 i; i < 4; i++) { uint256 bond = _getRequiredBond(i); gameProxy.attack{ value: bond }(i, Claim.wrap(bytes32(i))); } uint256 lastBond = _getRequiredBond(4); gameProxy.defend{ value: lastBond }(4, _changeClaimStatus(ROOT_CLAIM, VMStatuses.VALID)); // Expected start/disputed claims bytes32 startingClaim = bytes32(uint256(3)); Position startingPos = LibPosition.wrap(4, 0); bytes32 disputedClaim = bytes32(uint256(2)); Position disputedPos = LibPosition.wrap(3, 0); // Expected local data bytes32[5] memory data = [ gameProxy.l1Head().raw(), startingClaim, disputedClaim, bytes32(uint256(2) << 0xC0), bytes32(gameProxy.l2ChainId() << 0xC0) ]; for (uint256 i = 1; i <= 5; i++) { uint256 expectedLen = i > 3 ? 8 : 32; bytes32 key = _getKey(i, keccak256(abi.encode(startingClaim, startingPos, disputedClaim, disputedPos))); gameProxy.addLocalData(i, 5, 0); (bytes32 dat, uint256 datLen) = oracle.readPreimage(key, 0); assertEq(dat >> 0xC0, bytes32(expectedLen)); // Account for the length prefix if i > 3 (the data stored // at identifiers i <= 3 are 32 bytes long, so the expected // length is already correct. If i > 3, the data is only 8 // bytes long, so the length prefix + the data is 16 bytes // total.) assertEq(datLen, expectedLen + (i > 3 ? 8 : 0)); gameProxy.addLocalData(i, 5, 8); (dat, datLen) = oracle.readPreimage(key, 8); assertEq(dat, data[i - 1]); assertEq(datLen, expectedLen); } } /// @dev Helper to get the required bond for the given claim index. function _getRequiredBond(uint256 _claimIndex) internal view returns (uint256 bond_) { (,,,,, Position parent,) = gameProxy.claimData(_claimIndex); Position pos = parent.move(true); bond_ = gameProxy.getRequiredBond(pos); } /// @dev Helper to return a pseudo-random claim function _dummyClaim() internal view returns (Claim) { return Claim.wrap(keccak256(abi.encode(gasleft()))); } /// @dev Helper to get the localized key for an identifier in the context of the game proxy. function _getKey(uint256 _ident, bytes32 _localContext) internal view returns (bytes32) { bytes32 h = keccak256(abi.encode(_ident | (1 << 248), address(gameProxy), _localContext)); return bytes32((uint256(h) & ~uint256(0xFF << 248)) | (1 << 248)); } } contract FaultDispute_1v1_Actors_Test is FaultDisputeGame_Init { /// @dev The honest actor DisputeActor internal honest; /// @dev The dishonest actor DisputeActor internal dishonest; function setUp() public override { // Setup the `FaultDisputeGame` super.setUp(); } /// @notice Fuzz test for a 1v1 output bisection dispute. /// @dev The alphabet game has a constant status byte, and is not safe from someone being dishonest in /// output bisection and then posting a correct execution trace bisection root claim. This test /// does not cover this case (i.e. root claim of output bisection is dishonest, root claim of /// execution trace bisection is made by the dishonest actor but is honest, honest actor cannot /// attack it without risk of losing). function testFuzz_outputBisection1v1honestRoot_succeeds(uint8 _divergeOutput, uint8 _divergeStep) public { uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } uint256 divergeAtOutput = bound(_divergeOutput, 0, 15); uint256 divergeAtStep = bound(_divergeStep, 0, 7); uint256 divergeStepOffset = (divergeAtOutput << 4) + divergeAtStep; uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i >= divergeAtOutput ? 0xFF : i + 1; } bytes memory dishonestTrace = new bytes(256); for (uint256 i; i < dishonestTrace.length; i++) { dishonestTrace[i] = i >= divergeStepOffset ? bytes1(uint8(0xFF)) : bytes1(uint8(i)); } // Run the actor test _actorTest({ _rootClaim: 16, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.DEFENDER_WINS }); } /// @notice Static unit test for a 1v1 output bisection dispute. function test_static_1v1honestRootGenesisAbsolutePrestate_succeeds() public { // The honest l2 outputs are from [1, 16] in this game. uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } // The honest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of bytes [0, 255]. bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } // The dishonest l2 outputs are from [2, 17] in this game. uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i + 2; } // The dishonest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of all set bits. bytes memory dishonestTrace = new bytes(256); for (uint256 i; i < dishonestTrace.length; i++) { dishonestTrace[i] = bytes1(0xFF); } // Run the actor test _actorTest({ _rootClaim: 16, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.DEFENDER_WINS }); } /// @notice Static unit test for a 1v1 output bisection dispute. function test_static_1v1dishonestRootGenesisAbsolutePrestate_succeeds() public { // The honest l2 outputs are from [1, 16] in this game. uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } // The honest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of bytes [0, 255]. bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } // The dishonest l2 outputs are from [2, 17] in this game. uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i + 2; } // The dishonest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of all set bits. bytes memory dishonestTrace = new bytes(256); for (uint256 i; i < dishonestTrace.length; i++) { dishonestTrace[i] = bytes1(0xFF); } // Run the actor test _actorTest({ _rootClaim: 17, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.CHALLENGER_WINS }); } /// @notice Static unit test for a 1v1 output bisection dispute. function test_static_1v1honestRoot_succeeds() public { // The honest l2 outputs are from [1, 16] in this game. uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } // The honest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of bytes [0, 255]. bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } // The dishonest l2 outputs are from [2, 17] in this game. uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i + 2; } // The dishonest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of all zeros. bytes memory dishonestTrace = new bytes(256); // Run the actor test _actorTest({ _rootClaim: 16, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.DEFENDER_WINS }); } /// @notice Static unit test for a 1v1 output bisection dispute. function test_static_1v1dishonestRoot_succeeds() public { // The honest l2 outputs are from [1, 16] in this game. uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } // The honest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of bytes [0, 255]. bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } // The dishonest l2 outputs are from [2, 17] in this game. uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i + 2; } // The dishonest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of all zeros. bytes memory dishonestTrace = new bytes(256); // Run the actor test _actorTest({ _rootClaim: 17, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.CHALLENGER_WINS }); } /// @notice Static unit test for a 1v1 output bisection dispute. function test_static_1v1correctRootHalfWay_succeeds() public { // The honest l2 outputs are from [1, 16] in this game. uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } // The honest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of bytes [0, 255]. bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } // The dishonest l2 outputs are half correct, half incorrect. uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i > 7 ? 0xFF : i + 1; } // The dishonest trace is half correct, half incorrect. bytes memory dishonestTrace = new bytes(256); for (uint256 i; i < dishonestTrace.length; i++) { dishonestTrace[i] = i > (127 + 4) ? bytes1(0xFF) : bytes1(uint8(i)); } // Run the actor test _actorTest({ _rootClaim: 16, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.DEFENDER_WINS }); } /// @notice Static unit test for a 1v1 output bisection dispute. function test_static_1v1dishonestRootHalfWay_succeeds() public { // The honest l2 outputs are from [1, 16] in this game. uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } // The honest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of bytes [0, 255]. bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } // The dishonest l2 outputs are half correct, half incorrect. uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i > 7 ? 0xFF : i + 1; } // The dishonest trace is half correct, half incorrect. bytes memory dishonestTrace = new bytes(256); for (uint256 i; i < dishonestTrace.length; i++) { dishonestTrace[i] = i > (127 + 4) ? bytes1(0xFF) : bytes1(uint8(i)); } // Run the actor test _actorTest({ _rootClaim: 0xFF, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.CHALLENGER_WINS }); } /// @notice Static unit test for a 1v1 output bisection dispute. function test_static_1v1correctAbsolutePrestate_succeeds() public { // The honest l2 outputs are from [1, 16] in this game. uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } // The honest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of bytes [0, 255]. bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } // The dishonest l2 outputs are half correct, half incorrect. uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i > 7 ? 0xFF : i + 1; } // The dishonest trace correct is half correct, half incorrect. bytes memory dishonestTrace = new bytes(256); for (uint256 i; i < dishonestTrace.length; i++) { dishonestTrace[i] = i > 127 ? bytes1(0xFF) : bytes1(uint8(i)); } // Run the actor test _actorTest({ _rootClaim: 16, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.DEFENDER_WINS }); } /// @notice Static unit test for a 1v1 output bisection dispute. function test_static_1v1dishonestAbsolutePrestate_succeeds() public { // The honest l2 outputs are from [1, 16] in this game. uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } // The honest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of bytes [0, 255]. bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } // The dishonest l2 outputs are half correct, half incorrect. uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i > 7 ? 0xFF : i + 1; } // The dishonest trace correct is half correct, half incorrect. bytes memory dishonestTrace = new bytes(256); for (uint256 i; i < dishonestTrace.length; i++) { dishonestTrace[i] = i > 127 ? bytes1(0xFF) : bytes1(uint8(i)); } // Run the actor test _actorTest({ _rootClaim: 0xFF, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.CHALLENGER_WINS }); } /// @notice Static unit test for a 1v1 output bisection dispute. function test_static_1v1honestRootFinalInstruction_succeeds() public { // The honest l2 outputs are from [1, 16] in this game. uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } // The honest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of bytes [0, 255]. bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } // The dishonest l2 outputs are half correct, half incorrect. uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i > 7 ? 0xFF : i + 1; } // The dishonest trace is half correct, and correct all the way up to the final instruction of the exec // subgame. bytes memory dishonestTrace = new bytes(256); for (uint256 i; i < dishonestTrace.length; i++) { dishonestTrace[i] = i > (127 + 7) ? bytes1(0xFF) : bytes1(uint8(i)); } // Run the actor test _actorTest({ _rootClaim: 16, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.DEFENDER_WINS }); } /// @notice Static unit test for a 1v1 output bisection dispute. function test_static_1v1dishonestRootFinalInstruction_succeeds() public { // The honest l2 outputs are from [1, 16] in this game. uint256[] memory honestL2Outputs = new uint256[](16); for (uint256 i; i < honestL2Outputs.length; i++) { honestL2Outputs[i] = i + 1; } // The honest trace covers all block -> block + 1 transitions, and is 256 bytes long, consisting // of bytes [0, 255]. bytes memory honestTrace = new bytes(256); for (uint256 i; i < honestTrace.length; i++) { honestTrace[i] = bytes1(uint8(i)); } // The dishonest l2 outputs are half correct, half incorrect. uint256[] memory dishonestL2Outputs = new uint256[](16); for (uint256 i; i < dishonestL2Outputs.length; i++) { dishonestL2Outputs[i] = i > 7 ? 0xFF : i + 1; } // The dishonest trace is half correct, and correct all the way up to the final instruction of the exec // subgame. bytes memory dishonestTrace = new bytes(256); for (uint256 i; i < dishonestTrace.length; i++) { dishonestTrace[i] = i > (127 + 7) ? bytes1(0xFF) : bytes1(uint8(i)); } // Run the actor test _actorTest({ _rootClaim: 0xFF, _absolutePrestateData: 0, _honestTrace: honestTrace, _honestL2Outputs: honestL2Outputs, _dishonestTrace: dishonestTrace, _dishonestL2Outputs: dishonestL2Outputs, _expectedStatus: GameStatus.CHALLENGER_WINS }); } //////////////////////////////////////////////////////////////// // HELPERS // //////////////////////////////////////////////////////////////// /// @dev Helper to run a 1v1 actor test function _actorTest( uint256 _rootClaim, uint256 _absolutePrestateData, bytes memory _honestTrace, uint256[] memory _honestL2Outputs, bytes memory _dishonestTrace, uint256[] memory _dishonestL2Outputs, GameStatus _expectedStatus ) internal { // Setup the environment bytes memory absolutePrestateData = _setup({ _absolutePrestateData: _absolutePrestateData, _rootClaim: _rootClaim }); // Create actors _createActors({ _honestTrace: _honestTrace, _honestPreStateData: absolutePrestateData, _honestL2Outputs: _honestL2Outputs, _dishonestTrace: _dishonestTrace, _dishonestPreStateData: absolutePrestateData, _dishonestL2Outputs: _dishonestL2Outputs }); // Exhaust all moves from both actors _exhaustMoves(); // Resolve the game and assert that the defender won _warpAndResolve(); assertEq(uint8(gameProxy.status()), uint8(_expectedStatus)); } /// @dev Helper to setup the 1v1 test function _setup( uint256 _absolutePrestateData, uint256 _rootClaim ) internal returns (bytes memory absolutePrestateData_) { absolutePrestateData_ = abi.encode(_absolutePrestateData); Claim absolutePrestateExec = _changeClaimStatus(Claim.wrap(keccak256(absolutePrestateData_)), VMStatuses.UNFINISHED); Claim rootClaim = Claim.wrap(bytes32(uint256(_rootClaim))); super.init({ rootClaim: rootClaim, absolutePrestate: absolutePrestateExec, l2BlockNumber: _rootClaim }); } /// @dev Helper to create actors for the 1v1 dispute. function _createActors( bytes memory _honestTrace, bytes memory _honestPreStateData, uint256[] memory _honestL2Outputs, bytes memory _dishonestTrace, bytes memory _dishonestPreStateData, uint256[] memory _dishonestL2Outputs ) internal { honest = new HonestDisputeActor({ _gameProxy: gameProxy, _l2Outputs: _honestL2Outputs, _trace: _honestTrace, _preStateData: _honestPreStateData }); dishonest = new HonestDisputeActor({ _gameProxy: gameProxy, _l2Outputs: _dishonestL2Outputs, _trace: _dishonestTrace, _preStateData: _dishonestPreStateData }); vm.deal(address(honest), 100 ether); vm.deal(address(dishonest), 100 ether); vm.label(address(honest), "HonestActor"); vm.label(address(dishonest), "DishonestActor"); } /// @dev Helper to exhaust all moves from both actors. function _exhaustMoves() internal { while (true) { // Allow the dishonest actor to make their moves, and then the honest actor. (uint256 numMovesA,) = dishonest.move(); (uint256 numMovesB, bool success) = honest.move(); require(success, "Honest actor's moves should always be successful"); // If both actors have run out of moves, we're done. if (numMovesA == 0 && numMovesB == 0) break; } } /// @dev Helper to warp past the chess clock and resolve all claims within the dispute game. function _warpAndResolve() internal { // Warp past the chess clock vm.warp(block.timestamp + 3 days + 12 hours + 1 seconds); // Resolve all claims in reverse order. We allow `resolveClaim` calls to fail due to // the check that prevents claims with no subgames attached from being passed to // `resolveClaim`. There's also a check in `resolve` to ensure all children have been // resolved before global resolution, which catches any unresolved subgames here. for (uint256 i = gameProxy.claimDataLen(); i > 0; i--) { (bool success,) = address(gameProxy).call(abi.encodeCall(gameProxy.resolveClaim, (i - 1))); assertTrue(success); } gameProxy.resolve(); } } contract ClaimCreditReenter { Vm internal immutable vm; FaultDisputeGame internal immutable GAME; uint256 public numCalls; constructor(FaultDisputeGame _gameProxy, Vm _vm) { GAME = _gameProxy; vm = _vm; } function claimCredit(address _recipient) public { numCalls += 1; if (numCalls > 1) { vm.expectRevert(NoCreditToClaim.selector); } GAME.claimCredit(_recipient); } receive() external payable { if (numCalls == 5) { return; } claimCredit(address(this)); } } /// @dev Helper to change the VM status byte of a claim. function _changeClaimStatus(Claim _claim, VMStatus _status) pure returns (Claim out_) { assembly { out_ := or(and(not(shl(248, 0xFF)), _claim), shl(248, _status)) } }which part is for this bug which is a slight adaptation of the test here is the bug Unvalidated Root Claim in _verifyExecBisectionRoot Summary logical flaw that can compromise the integrity of the game by allowing invalid root claims to pass under specific conditions. Vulnerability Detail The verifyExecBisectionRoot function is attempts to validate the root claim based on the status provided by the VM and whether the move is an attack or defense, but the logic fails to account for scenarios where the depth and type of move could result in an invalid claim being accepted as valid here Position disputedLeafPos = Position.wrap(_parentPos.raw() + 1); ClaimData storage disputed = _findTraceAncestor({ _pos: disputedLeafPos, _start: _parentIdx, _global: true }); uint8 vmStatus = uint8(_rootClaim.raw()[0]); if (_isAttack || disputed.position.depth() % 2 == SPLIT_DEPTH % 2) { // If the move is an attack, the parent output is always deemed to be disputed. In this case, we only need // to check that the root claim signals that the VM panicked or resulted in an invalid transition. // If the move is a defense, and the disputed output and creator of the execution trace subgame disagree, // the root claim should also signal that the VM panicked or resulted in an invalid transition. if (!(vmStatus == VMStatuses.INVALID.raw() || vmStatus == VMStatuses.PANIC.raw())) { revert UnexpectedRootClaim(_rootClaim); } } else if (vmStatus != VMStatuses.VALID.raw()) { // The disputed output and the creator of the execution trace subgame agree. The status byte should // have signaled that the VM succeeded. revert UnexpectedRootClaim(_rootClaim); } } he conditional check if (_isAttack || disputed.position.depth() % 2 == SPLIT_DEPTH % 2) and subsequent logic is flawed in how it determines the validity of a root claim based on the VM status and move type let's say a scenario of Attack to occur cause i fuzzed with scenario and i get the same result : An attacker initiates a defense move (_isAttack is false) against a root claim with a depth that unevenly aligns with SPLIT_DEPTH, ensuringdisputed.position.depth() % 2 == SPLIT_DEPTH % 2evaluates to false. The attacker submits a root claim with a VMStatus of VALID when, in reality, the claim should not be considered valid due to the game's state or previous moves. as result The contract fails to reject the invalid root claim due to the incorrect logic, allowing the attacker to potentially alter the game's course to their advantage. Impact the issue is allowing the participants to exploit the flaw to their advantage, leading to incorrect game outcomes Code Snippet https://github.com/sherlock-audit/2024-02-optimism-2024/blob/main/optimism/packages/contracts-bedrock/src/dispute/FaultDisputeGame.sol#L730C6-L743C6 Tool used Manual Review Recommendation in my opening it's need a checks or restructuring the conditional logic to prevent invalid claims from being accepted
d2141da0928797c023f835e5c68c13c2
{ "intermediate": 0.3907935321331024, "beginner": 0.3806760609149933, "expert": 0.22853034734725952 }
46,090
How to add empty object to jsonDocument. This ne object can contain more objects in future
21d2929495b68a9800d1963fb79e1b75
{ "intermediate": 0.4871615469455719, "beginner": 0.21845051646232605, "expert": 0.29438790678977966 }
46,091
Given two lists of strings, implement a function that calculates a similarity score between the two lists. Hint: You can do this by implementing a Jaccard Coefficient, where you take the count of items in the intersection of 2 sets divided by the union of items in the 2 sets. This will give you a value bounded between 0 and 1 for a similarity score. # test code list_1 = ['a', 'b', 'c', 'd'] list_2 = ['b', 'c', 'd', 'e'] 请用python解答这道问题
517f4228c7e9581364b48d1b53f7d5da
{ "intermediate": 0.3515455722808838, "beginner": 0.18639567494392395, "expert": 0.4620587229728699 }
46,092
Compiler output: Solution.java:10: error: cannot find symbol if (!contains(A, i)) { ^ symbol: method contains(int[],int) location: class Solution 1 error
0c2319b2d60c3292a5bdf31fa1be1422
{ "intermediate": 0.2792758047580719, "beginner": 0.6071847677230835, "expert": 0.11353939771652222 }
46,093
Do this in Java 11: Write a function: class Solution { public int solution(int[] A); } that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000].
36cd5c67c5bbf066b1a4625e3c3f5fbd
{ "intermediate": 0.21046394109725952, "beginner": 0.23228804767131805, "expert": 0.5572479963302612 }
46,094
How can we make embedded list mandatory or embedded list fields mandatory? i am unable to make mandatory using setMandatory() in client script.
ce6509d516185183169b2181c2a28594
{ "intermediate": 0.5150989890098572, "beginner": 0.1660870611667633, "expert": 0.3188140392303467 }
46,095
Solution in Java 11: A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D. Count the minimal number of jumps that the small frog must perform to reach its target. Write a function: class Solution { public int solution(int X, int Y, int D); } that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y. For example, given: X = 10 Y = 85 D = 30 the function should return 3, because the frog will be positioned as follows: after the first jump, at position 10 + 30 = 40 after the second jump, at position 10 + 30 + 30 = 70 after the third jump, at position 10 + 30 + 30 + 30 = 100 Write an efficient algorithm for the following assumptions: X, Y and D are integers within the range [1..1,000,000,000]; X ≤ Y.
5eabd8df71d9a25f5712765bb0bf4e37
{ "intermediate": 0.2413763552904129, "beginner": 0.1994560956954956, "expert": 0.5591675043106079 }
46,096
hello
9144f4deba5edfc863508ce2c4789d33
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
46,097
Solve in Java 11: A non-empty array A consisting of N integers is given. A permutation is a sequence containing each element from 1 to N once, and only once. For example, array A such that: A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2 is a permutation, but array A such that: A[0] = 4 A[1] = 1 A[2] = 3 is not a permutation, because value 2 is missing. The goal is to check whether array A is a permutation. Write a function: class Solution { public int solution(int[] A); } that, given an array A, returns 1 if array A is a permutation and 0 if it is not. For example, given array A such that: A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2 the function should return 1. Given array A such that: A[0] = 4 A[1] = 1 A[2] = 3 the function should return 0. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [1..1,000,000,000].
7656830ab17ad04735d6fe82b45283c0
{ "intermediate": 0.3450162708759308, "beginner": 0.23886534571647644, "expert": 0.41611844301223755 }
46,098
this javascript simulates a 24 hour clock. roundMinutes is meant to ensure that the clock only displays numbers ending in 0. But this doesn't always work - //24 hour clock display // Define a constant for time multiplier (1 day = 10 minutes) const TIME_MULTIPLIER = 60 * 10; // 10 minutes = 600 seconds // Function to format time in 24-hour format with leading zeros function formatTime(hours, minutes) { // Handle the case where minutes reach 60 (should display the next hour) if (minutes === 60) { hours++; minutes = 0; } return `${hours.toString().padStart(2, "0")}:${minutes .toString() .padStart(2, "0")}`; } // Function to round minutes to the nearest 10 minutes function roundMinutes(minutes) { const remainder = minutes % 10; if (remainder <= 5) { return minutes; } else { return minutes + (10 - remainder); } } // Function to update the clock display function updateClock() { const currentTime = new Date(); // Simulate game time by multiplying actual time with multiplier const gameTime = new Date(currentTime.getTime() * TIME_MULTIPLIER); // Get hours and minutes in 24-hour format const hours = gameTime.getHours(); let minutes = gameTime.getMinutes(); // Round minutes to the nearest 10 minutes = roundMinutes(minutes); // Format the time string const formattedTime = formatTime(hours, minutes); // Update the content of the div with the formatted time document.getElementById("timedisplay").textContent = formattedTime; // Check if it's midnight (00:00) if (hours === 0 && minutes === 0) { money += dailybonus; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; console.log(`Daily bonus of ${dailybonus} added! Total money: ${money}`); // You can replace console.log with your desired action } } // Call the updateClock function initially updateClock(); // Update the clock every second to simulate smooth time progression setInterval(updateClock, 1000);
1ff0fe05030ab2292cff988bdfcabafe
{ "intermediate": 0.3747673034667969, "beginner": 0.4327765107154846, "expert": 0.1924562305212021 }
46,099
Solve in Java 11: Write a function: class Solution { public int solution(int[] A); } that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000].
18da929b625d573745fb27585266e011
{ "intermediate": 0.19775237143039703, "beginner": 0.244485542178154, "expert": 0.5577621459960938 }
46,100
Solve in Java 11: A non-empty array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road. Array A contains only 0s and/or 1s: 0 represents a car traveling east, 1 represents a car traveling west. The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west. For example, consider array A such that: A[0] = 0 A[1] = 1 A[2] = 0 A[3] = 1 A[4] = 1 We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4). Write a function: class Solution { public int solution(int[] A); } that, given a non-empty array A of N integers, returns the number of pairs of passing cars. The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000. For example, given: A[0] = 0 A[1] = 1 A[2] = 0 A[3] = 1 A[4] = 1 the function should return 5, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer that can have one of the following values: 0, 1.
3330415a11e0877a387b929d0462757e
{ "intermediate": 0.2705487906932831, "beginner": 0.1928739696741104, "expert": 0.5365772843360901 }
46,101
I need to know that, in my previous code, i got the following error File d:\opamp circuits\rl_gnn\rl_gnn_cktenv_new2.py:324 in __init__ self.actor = actor_class(gnn_model.conv2.out_channels, action_dim, std) # Initialize actor TypeError: Actor.forward() takes 2 positional arguments but 4 were given My previous code: class PPOAgent: def __init__(self, actor_class, critic_class, gnn_model, action_dim, bounds_low, bounds_high, lr_actor=3e-4, lr_critic=1e-3, gamma=0.99, lamda=0.95, epsilon=0.2, std=0.0): self.actor = actor_class(gnn_model.conv2.out_channels, action_dim, std) # Initialize actor self.critic = critic_class(gnn_model.conv2.out_channels) # Initialize critic self.gnn_model = gnn_model # GNN model instance self.optimizer_actor = optim.Adam(self.actor.parameters(), lr=lr_actor) self.optimizer_critic = optim.Adam(self.critic.parameters(), lr=lr_critic) self.gamma = gamma self.lamda = lamda self.epsilon = epsilon #self.bounds_low = torch.tensor(bounds_low).float() #self.bounds_high = torch.tensor(bounds_high).float() self.bounds_low = bounds_low self.bounds_high = bounds_high self.std = std self.epochs = 10 # Define the number of epochs for policy update def select_action(self, state, edge_index, edge_attr): # Pass state through the GNN model first to get state’s embedding state_embedding = self.gnn_model(state, edge_index, edge_attr) # Then, pass the state embedding through the actor network to get action mean and std mean, std = self.actor(state_embedding) # Rearranging based on the specifications rearranged_mean = rearrange_action_output(mean) # Scale mean based on action bounds defined mean = self.bounds_low + (torch.sigmoid(rearranged_mean) * (self.bounds_high - self.bounds_low)) dist = Normal(mean, std) # Sample an action from the distribution and calculate its log probability action = dist.sample() action = torch.clamp(action, self.bounds_low, self.bounds_high) # Ensure action is within bounds action_log_prob = dist.log_prob(action) return action.detach(), action_log_prob.detach() # Create the environment env = CircuitEnvironment(server_address, username, password, bounds_low, bounds_high, target_metrics, netlist_content) gnn_model = EnhancedGNNModelWithSharedParams(num_node_features, num_edge_features, num_out_features) agent = PPOAgent(actor, critic, gnn_model, action_dim, bounds_low, bounds_high, lr_actor, lr_critic, gamma, lambda_, epsilon, std) # Train agent train(env, agent, env.num_episodes, env.max_timesteps, env.batch_size, env.epsilon) I made the following upgrade in my previous code, class PPOAgent: def init(self, actor, critic, gnn_model, action_dim, bounds_low, bounds_high, lr_actor=3e-4, lr_critic=1e-3, gamma=0.99, lamda=0.95, epsilon=0.2, std=0.0): self.actor = actor # Actor instance self.critic = critic # Critic instance self.gnn_model = gnn_model # GNN model instance self.optimizer_actor = Adam(self.actor.parameters(), lr=lr_actor) self.optimizer_critic = Adam(self.critic.parameters(), lr=lr_critic) self.gamma = gamma self.lamda = lamda self.epsilon = epsilon self.bounds_low = bounds_low self.bounds_high = bounds_high self.std = std self.epochs = 10 def select_action(self, state, edge_index, edge_attr): state_embedding = self.gnn_model(state, edge_index, edge_attr) mean, std = self.actor(state_embedding) # Assuming rearrange_action_output is a function you have defined elsewhere # rearranged_mean = rearrange_action_output(mean) # Treat ‘rearranged_mean’ as ‘mean’ if you do not need to rearrange dist = Normal(mean, std) action = dist.sample() action = torch.clamp(action, self.bounds_low, self.bounds_high) action_log_prob = dist.log_prob(action) return action.detach(), action_log_prob.detach() # Create the environment env = CircuitEnvironment(server_address, username, password, bounds_low, bounds_high, target_metrics, netlist_content) gnn_model = EnhancedGNNModelWithSharedParams(num_node_features, num_edge_features, num_out_features) agent = PPOAgent(actor, critic, gnn_model, action_dim, bounds_low, bounds_high, lr_actor, lr_critic, gamma, lambda_, epsilon, std) # Train agent train(env, agent, env.num_episodes, env.max_timesteps, env.batch_size, env.epsilon) I need to know that, do i need any upgrade in the update policy method with in the class PPOAgent to call the actor function with the gnn_model. class PPOAgent: def init(self, actor, critic, gnn_model, action_dim, bounds_low, bounds_high, lr_actor=3e-4, lr_critic=1e-3, gamma=0.99, lamda=0.95, epsilon=0.2, std=0.0): def select_action(self, state, edge_index, edge_attr): return action.detach(), action_log_prob.detach() def compute_gae(self, next_value, rewards, dones, values, gamma=0.99, lambda_=0.95): return returns def update_policy(self, states, actions, log_probs, returns, advantages): for epoch in range(self.epochs): sampler = BatchSampler(SubsetRandomSampler(range(len(states))), batch_size=64, drop_last=True) for indices in sampler: sampled_states = torch.stack([states[i] for i in indices]) sampled_actions = torch.stack([actions[i] for i in indices]) sampled_log_probs = torch.stack([log_probs[i] for i in indices]) sampled_returns = torch.stack([returns[i] for i in indices]) sampled_advantages = torch.stack([advantages[i] for i in indices]) # Assuming the actor model returns a distribution from which log probabilities can be computed mean, new_std = self.actor(sampled_states) dist = Normal(mean, new_std.exp()) new_log_probs = dist.log_prob(sampled_actions) ratio = (new_log_probs - sampled_log_probs).exp() # Incorporating stability loss stability_losses = [] for state in sampled_states: stability_loss_val = stability_loss(state, target_stability=1.0) # Assuming you want all nodes to be stable stability_losses.append(stability_loss_val) mean_stability_loss = torch.mean(torch.stack(stability_losses)) surr1 = ratio * sampled_advantages surr2 = torch.clamp(ratio, 1.0 - self.epsilon, 1.0 + self.epsilon) * sampled_advantages actor_loss = -torch.min(surr1, surr2).mean() + mean_stability_loss critic_loss = F.mse_loss(sampled_returns, self.critic(sampled_states)) self.optimizer_actor.zero_grad() actor_loss.backward() self.optimizer_actor.step() self.optimizer_critic.zero_grad() critic_loss.backward() self.optimizer_critic.step()
1b54e86fb8911a66b3bde45e6073c316
{ "intermediate": 0.3340359330177307, "beginner": 0.4212091565132141, "expert": 0.24475497007369995 }
46,102
Write in Java 11: Write a function class Solution { public int solution(int[] A); } that, given an array A consisting of N integers, returns the number of distinct values in array A. For example, given array A consisting of six elements such that: A[0] = 2 A[1] = 1 A[2] = 1 A[3] = 2 A[4] = 3 A[5] = 1 the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000].
c19f6a243d48ac71db5c8578a36f2ee6
{ "intermediate": 0.23308725655078888, "beginner": 0.16983260214328766, "expert": 0.5970801711082458 }
46,103
Write a function: class Solution { public int solution(int A, int B, int K); } that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.: { i : A ≤ i ≤ B, i mod K = 0 } For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10. Write an efficient algorithm for the following assumptions: A and B are integers within the range [0..2,000,000,000]; K is an integer within the range [1..2,000,000,000]; A ≤ B.
3d2f60a452a5106dc35a88fc812f5490
{ "intermediate": 0.13696624338626862, "beginner": 0.2841167449951172, "expert": 0.5789170861244202 }
46,104
Write a function in Java 11 class Solution { public int solution(int[] A); } that, given an array A consisting of N integers, returns the number of distinct values in array A. For example, given array A consisting of six elements such that: A[0] = 2 A[1] = 1 A[2] = 1 A[3] = 2 A[4] = 3 A[5] = 1 the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000].
607c0f555f529c4b5748832a4dce92a5
{ "intermediate": 0.18561959266662598, "beginner": 0.14933523535728455, "expert": 0.6650452017784119 }
46,105
Solve in Java 11: A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N). For example, array A such that: A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6 contains the following example triplets: (0, 1, 2), product is −3 * 1 * 2 = −6 (1, 2, 4), product is 1 * 2 * 5 = 10 (2, 4, 5), product is 2 * 5 * 6 = 60 Your goal is to find the maximal product of any triplet. Write a function: class Solution { public int solution(int[] A); } that, given a non-empty array A, returns the value of the maximal product of any triplet. For example, given array A such that: A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6 the function should return 60, as the product of triplet (2, 4, 5) is maximal. Write an efficient algorithm for the following assumptions: N is an integer within the range [3..100,000]; each element of array A is an integer within the range [−1,000..1,000].
99899b9c8949bdeeb89767c38213da5b
{ "intermediate": 0.270243376493454, "beginner": 0.20886783301830292, "expert": 0.5208888053894043 }
46,106
I have this code in react. I am using react-effector library. const selectedFilters = useStore($selectedFilters); const currentFilter = selectedFilters[selectedFilter] as IAbstractObject[]; I have been told that I can get access to currentFilter through the usage of useStoreMap method instead. How can I do it?
090d305769bf34a4ab364e528d2a0705
{ "intermediate": 0.7480359673500061, "beginner": 0.18973621726036072, "expert": 0.06222781911492348 }
46,107
The customGNN was designed with the below features, - Dynamic Feature Processing: This version specifically processes dynamic features index [18, 19] (and, depending on the specific component node, index [20], [21], [22]) for action space parameters within component nodes. - Maintaining Original Features: For both component and net nodes, static features remain unchanged. The entire node features matrix is initialized to hold original features, and only the dynamic features of component nodes are processed through the GAT layer. - Component and Net Node Handling: Component node features are selectively updated based on the action space parameters. Net nodes and static features of component nodes are left unchanged, fulfilling the requirement to keep net nodes and other static component node features static during the training process. I need you to rovide me the complete code for RL PPO agent in continuous action space for tuning the selected dynamic feature values(with actor and critic) to be properly synchronize with the existing custom model 'class CustomGNN(torch.nn.Module)', import torch from torch_geometric.nn import GATConv class CustomGNN(torch.nn.Module): def init(self, total_node_count, num_feature_dim, num_output_dim): super(CustomGNN, self).init() self.total_node_count = total_node_count self.num_feature_dim = num_feature_dim self.num_output_dim = num_output_dim # GAT layer for component nodes, customized for dynamic features self.gat_component = GATConv(in_channels=2, # Only taking the dynamic features for GAT processing out_channels=num_output_dim, heads=8, dropout=0.6) def forward(self, node_features, edge_index): # Dynamically determine component and net node indices based on their features component_indices = (node_features[:, 0] == 0).nonzero(as_tuple=True)[0] # Initialize a tensor for all nodes to hold original features all_node_features = torch.zeros((self.total_node_count, self.num_feature_dim)) # For component nodes, selectively process only the dynamic features (indices [18] [19]) dynamic_feature_indices = torch.tensor([18, 19], dtype=torch.long) for idx in component_indices: # Identify if node is part of synchronized tuning sets and pick correct dynamic indices node_idx_value = node_features[idx, 7:18].nonzero(as_tuple=True)[0].item() + 7 dynamic_index = [node_idx_value - 7 + 18, node_idx_value - 7 + 19] if node_idx_value < 15 else [node_idx_value] dynamic_features = node_features[idx, dynamic_feature_indices].reshape(1, -1) processed_dynamic_features = self.gat_component(dynamic_features, edge_index)[0] # Insert processed dynamic features back, keep static features unchanged all_node_features[idx, dynamic_feature_indices] = processed_dynamic_features # Copy net node features directly, as they remain unchanged net_indices = (node_features[:, 0] == 1).nonzero(as_tuple=True)[0] all_node_features[net_indices] = node_features[net_indices] return all_node_features
5d1f15ace644f11eac233c5a6b6ddea4
{ "intermediate": 0.24236372113227844, "beginner": 0.5326916575431824, "expert": 0.22494454681873322 }
46,108
explain this code to me. const copy = filter.reduce((object, option) => { object[option.id] = option; return object; }, {}); what is object? What is {} at the end of it?
b5e98403ef720e0d131a7fa00fea4f1c
{ "intermediate": 0.4252438545227051, "beginner": 0.4365522861480713, "expert": 0.1382039338350296 }
46,109
We have totally 11 component nodes (‘M0’ to ‘M7’, ‘C0’, ‘I0’, ‘V1’), to identify the corresponding component nodes (‘M0’ to ‘M7’, ‘C0’, ‘I0’, ‘V1’) with index number for each component as, for component ‘M0’ has index number [7] with value '1.0000', ‘M1’ has index number [8] with value '1.0000', ‘M2’ has index number [9] with value '1.0000', ‘M3’ has index number [10] with value '1.0000', ‘M4’ has index number [11] with value '1.0000', ‘M5’ has index number [12] with value '1.0000', ‘M6’ has index number [13] with value '1.0000', ‘M7’ has index number [14] with value '1.0000', ‘C0’ has index number [15] with value '1.0000', ‘I0’ has index number [16] with value '1.0000', ‘V1’ has index number [17] with value '1.0000', the action space are need to be dynamic only to the below given specific features with in the component nodes, remaining features in the component nodes and all the features in the net nodes are need to be static in the training process. Among the selected component nodes we need to tune only the selected features, it can be identify by for component ‘M0’ has index number [7] with value '1.0000', we need to tune only the values of the features at its indices [18] [19], for component ‘M1’ has index number [8] with value '1.0000', we need to tune only the values of the features at its indices [18] [19], for component ‘M2’ has index number [9] with value '1.0000', we need to tune only the values of the features at its indices [18] [19], for component ‘M3’ has index number [10] with value '1.0000', we need to tune only the values of the features at its indices [18] [19], for component ‘M4’ has index number [11] with value '1.0000', we need to tune only the values of the features at its indices [18] [19], for component ‘M5’ has index number [12] with value '1.0000', we need to tune only the values of the features at its indices [18] [19], for component ‘M6’ has index number [13] with value '1.0000', we need to tune only the values of the features at its indices [18] [19], for component ‘M7’ has index number [14] with value '1.0000', we need to tune only the values of the features at its indices [18] [19], for component ‘C0’ has index number [15] with value '1.0000', we need to tune only the values of the features at its index [20], for component ‘I0’ has index number [16] with value '1.0000', we need to tune only the values of the features at its index [21], for component ‘V1’ has index number [17] with value '1.0000', we need to tune only the values of the features at its index [22], Among ('M0' to 'M7') We have three set pairs of component nodes (‘M0’ and ‘M1’, ‘M2’ and ‘M3’, ‘M4’ and ‘M7’) which always needs to be tune with synchronus values between each other. to achive synchronus tuning on, for component ‘M0’ with index number [7] and for component ‘M1’ with index number [8], we need to tune same values at its indices [18] [19], for component ‘M2’ with index number [9] and for component ‘M3’ with index number [10], we need to tune same values at its indices [18] [19], for component ‘M4’ with index number [11] and for component ‘M7’ with index number [14], we need to tune same values at its indices [18] [19]. remaining components 'M5', 'M6', 'C0', 'I0', and 'V1' doesnot have any synchronize constraints it can keep its own tuned values. The customGNN was designed with the above requirement with the below features, - Dynamic Feature Processing: This version specifically processes dynamic features index [18, 19] (and, depending on the specific component node, index [20], [21], [22]) for action space parameters within component nodes. - Maintaining Original Features: For both component and net nodes, static features remain unchanged. The entire node features matrix is initialized to hold original features, and only the dynamic features of component nodes are processed through the GAT layer. - Component and Net Node Handling: Component node features are selectively updated based on the action space parameters. Net nodes and static features of component nodes are left unchanged, fulfilling the requirement to keep net nodes and other static component node features static during the training process. I need you to provide me the complete code for RL PPO agent in continuous action space for tuning the selected dynamic feature values(with actor and critic) to be properly synchronize with the existing custom model 'class CustomGNN(torch.nn.Module)', import torch from torch_geometric.nn import GATConv class CustomGNN(torch.nn.Module): def init(self, total_node_count, num_feature_dim, num_output_dim): super(CustomGNN, self).init() self.total_node_count = total_node_count self.num_feature_dim = num_feature_dim self.num_output_dim = num_output_dim # GAT layer for component nodes, customized for dynamic features self.gat_component = GATConv(in_channels=2, # Only taking the dynamic features for GAT processing out_channels=num_output_dim, heads=8, dropout=0.6) def forward(self, node_features, edge_index): # Dynamically determine component and net node indices based on their features component_indices = (node_features[:, 0] == 0).nonzero(as_tuple=True)[0] # Initialize a tensor for all nodes to hold original features all_node_features = torch.zeros((self.total_node_count, self.num_feature_dim)) # For component nodes, selectively process only the dynamic features (indices [18] [19]) dynamic_feature_indices = torch.tensor([18, 19], dtype=torch.long) for idx in component_indices: # Identify if node is part of synchronized tuning sets and pick correct dynamic indices node_idx_value = node_features[idx, 7:18].nonzero(as_tuple=True)[0].item() + 7 dynamic_index = [node_idx_value - 7 + 18, node_idx_value - 7 + 19] if node_idx_value < 15 else [node_idx_value] dynamic_features = node_features[idx, dynamic_feature_indices].reshape(1, -1) processed_dynamic_features = self.gat_component(dynamic_features, edge_index)[0] # Insert processed dynamic features back, keep static features unchanged all_node_features[idx, dynamic_feature_indices] = processed_dynamic_features # Copy net node features directly, as they remain unchanged net_indices = (node_features[:, 0] == 1).nonzero(as_tuple=True)[0] all_node_features[net_indices] = node_features[net_indices] return all_node_features
493af0f0f7a318d25b7a6b71d9794401
{ "intermediate": 0.3122709393501282, "beginner": 0.3951568007469177, "expert": 0.2925722599029541 }
46,110
import tensorflow as tf from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM # Initialize the context manager once strategy = tf.distribute.MirroredStrategy( devices=["/gpu:0", "/gpu:1", "/gpu:2", "/gpu:3", "/gpu:4", "/gpu:5"], cross_device_ops=tf.distribute.HierarchicalCopyAllReduce() ) with strategy.scope(): #model_name = "HuggingFaceH4/zephyr-7b-beta" model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" # Or a better model if you find one tokenizer = AutoTokenizer.from_pretrained(model_name, padding_side="left") model = AutoModelForCausalLM.from_pretrained(model_name) # Create the pipeline for text generation def generate_response(messages): prompts = [tokenizer.apply_chat_template(messages + [prompt], tokenize=False, add_generation_prompt=True) for prompt in batch_prompts] with strategy.scope(): input_ids = tokenizer.batch_encode_plus(prompts, return_tensors='pt', padding=True) #attention_mask = input_ids['attention_mask'] attention_mask = input_ids['input_ids'].ne(tokenizer.eos_token_id).int() with strategy.scope(): outputs = model.generate(input_ids=input_ids['input_ids'], attention_mask=attention_mask, max_new_tokens=256, do_sample=True, temperature=0.7, top_k=50, top_p=0.95) return [tokenizer.decode(output, skip_special_tokens=True) for output in outputs] # Initial messages messages = [ { "role": "system", "content": "You are an emotionally intelligent and brilliant experienced expert futures stock, forex and cryptocurrency day trader who knows his stuff and does'nt make excuses. I (the prompter) am your boss and I count on your advice to make big profits in the markets, you are handsomely rewarded and thereby love this arrangement. As my employee your job is to offer me expert opinions and predictions.", "content": "examine the crypto currency data and decide whether we should enter long position, short position or wait for better signals", }, {"role": "user", "content": ""}, ] # Main interaction loop batch_prompts = [] while True: with strategy.scope(): while True: # Inner loop for collecting a batch new_prompt = input("Enter your new prompt (or type 'go' to process): ") if new_prompt.lower() == 'go': break # Exit the inner batch collection loop batch_prompts.append({"role": "user", "content": new_prompt}) # Process the batch responses = generate_response(messages) for response in responses: print("Trader Response:", response) batch_prompts = [] # Clear the batch_prompts for the next set of questions can thiks be further improved
e386bed2515ba16f4ac6f9adafcd6bdc
{ "intermediate": 0.28789034485816956, "beginner": 0.5059770345687866, "expert": 0.2061326652765274 }
46,111
Данный код читает шейп-файл с точками и таблицу со списком ребер из этих точек, связывает таблицу с шейп-файлом по номеру (идентификатору точки), чтобы извлечь ее геометрию, построить ребро и добавить его в новый шейп-файл. Однако возникает ошибка, как ее решить? path = r"C:\BAZA\COURSEWORK\GRID_1\with_dem\points_dem.shp" points = gpd.read_file(path) FID_land_p Landtype Road_type MEAN_speed MEDIAN_spe ELEV_DEM MERGE_SRC geometry TARGET_FID 0 113 Залежь None 3.312347 3.471036 162.055 land POINT Z (329981.690 6119284.376 0.000) 1 1 113 Залежь None 3.312347 3.471036 161.896 land POINT Z (329986.690 6119284.376 0.000) 2 2 113 Залежь None 3.312347 3.471036 161.719 land POINT Z (329991.690 6119284.376 0.000) 3 3 113 Залежь None 3.312347 3.471036 161.526 land POINT Z (329996.690 6119284.376 0.000) 4 4 113 Залежь None 3.312347 3.471036 161.318 land POINT Z (330001.690 6119284.376 0.000) 5 5 113 Залежь None 3.312347 3.471036 161.096 land POINT Z (330006.690 6119284.376 0.000) 6 6 113 Залежь None 3.312347 3.471036 160.853 land POINT Z (330011.690 6119284.376 0.000) 7 7 113 Залежь None 3.312347 3.471036 160.586 land POINT Z (330016.690 6119284.376 0.000) 8 8 113 Залежь None 3.312347 3.471036 160.294 land POINT Z (330021.690 6119284.376 0.000) 9 9 113 Залежь None 3.312347 3.471036 159.980 land POINT Z (330026.690 6119284.376 0.000) 10 len(points) 814404 all_table_points = pd.read_pickle(r"C:\BAZA\COURSEWORK\GRID_1\with_dem\all_table_points.pkl") OBJECTID IN_FID NEAR_FID NEAR_DIST NEAR_RANK 0 2 797613 797614 4.999981 1 1 3 797613 797612 5.000031 2 2 4 797614 797613 4.999981 1 3 5 797614 797615 5.000031 2 4 6 797615 797616 4.999981 1 5 7 797615 797614 5.000031 2 6 8 797616 797615 4.999981 1 7 9 797616 797617 5.000031 2 8 10 797617 797618 4.999940 1 9 11 797617 797616 5.000031 2 len(all_table_points) 6429638 %%time edges = [] set_edges = set() for index, row in all_table_points.iterrows(): start_id, end_id = row['IN_FID'], row['NEAR_FID'] start_point = points[points['feature_or'] == start_id].geometry.values[0] end_point = points[points['feature_or'] == end_id].geometry.values[0] start = points[points['feature_or'] == start_id]['MEDIAN_spe'].values[0] end = points[points['feature_or'] == end_id]['MEDIAN_spe'].values[0] start_source = points[points['feature_or'] == start_id]['MERGE_SRC'].values[0] end_source = points[points['feature_or'] == end_id]['MERGE_SRC'].values[0] start_lt = points[points['feature_or'] == start_id]['Landtype'].values[0] end_lt = points[points['feature_or'] == end_id]['Landtype'].values[0] if frozenset((start_id, end_id)) not in set_edges: edge = LineString([start_point, end_point]) edges.append({'geometry': edge, 'START_ID': start_id, 'END_ID': end_id, 'START_SPEED': start, 'END_SPEED': end, 'START_SOURCE': start_source, 'END_SOURCE': end_source, 'LT1': start_lt, 'LT2': end_lt}) set_edges.add(frozenset((start_id, end_id))) print(len(edges), start_id, end_id) edges_gdf = gpd.GeoDataFrame(edges, crs=points.crs) output_shapefile = r"C:\BAZA\COURSEWORK\GRID_1\with_dem\links_dem.shp" edges_gdf.to_file(output_shapefile) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) File <timed exec>:7 File ~\.conda\envs\ELZAS_LORAN\lib\site-packages\geopandas\array.py:384, in GeometryArray.__getitem__(self, idx) 382 def __getitem__(self, idx): 383 if isinstance(idx, numbers.Integral): --> 384 return _geom_to_shapely(self._data[idx]) 385 # array-like, slice 386 # validate and convert IntegerArray/BooleanArray 387 # to numpy array, pass-through non-array-like indexers 388 idx = pd.api.indexers.check_array_indexer(self, idx) IndexError: index 0 is out of bounds for axis 0 with size 0
924c5b6a7883939059429c10ce9371df
{ "intermediate": 0.3613375425338745, "beginner": 0.4257080852985382, "expert": 0.21295438706874847 }
46,112
how can i count the nnumber of times a value occurs in an array in java
d6b185ad14bf0776c60e3626ce4f641c
{ "intermediate": 0.5664662718772888, "beginner": 0.2209686040878296, "expert": 0.21256518363952637 }
46,113
remove element from java array by value
076a5eb82d52a5f2ad11516ecc86766d
{ "intermediate": 0.43807804584503174, "beginner": 0.2741837501525879, "expert": 0.28773826360702515 }
46,114
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Objects; using System.Data.Objects.SqlClient; using System.Linq; using System.Net; using System.Reflection; using ServicesApiOcaPeek.Data; using ServicesApiOcaPeek.ExceptionPersonnalisees; using ServicesApiOcaPeek.Extensions; using ServicesApiOcaPeek.Models; namespace ServicesApiOcaPeek.Helpers { /// <summary> /// Gestion de l'accès à la couche de données /// </summary> public class ServicesApiOcaPeekDataHelper : IDisposable { OCAPEEKEntities ent; public virtual void Dispose() { ent.Dispose(); ent = null; } /// <summary> /// /// </summary> public ServicesApiOcaPeekDataHelper() { try { ent = new OCAPEEKEntities(); } catch (Exception exc) { Utils.ElmahLogException(exc); throw exc; } } #region Check connection base /// <summary> /// Permet de test si la base de données est disponible /// </summary> /// <returns></returns> internal bool CheckConnectionBase() { return ent.DatabaseExists(); } internal bool CheckAccessTable() { return ent.OP_VISITE.Any(); } #endregion public PAR_GEN_SERV GetParcGenServDansBdd(string environnement) { return ent.PAR_GEN_SERV.Where(w => w.PGS_ENV.Equals(environnement, StringComparison.OrdinalIgnoreCase)) .SingleOrDefault(); } /// <summary> /// recuperer les visites /// </summary> /// <param name="site">site</param> /// <param name="username">nom d'utilisateur</param> /// <param name="startDate">date de debut</param> /// <param name="endDate">date de fin</param> /// <param name="sortindex">nom propiete </param> /// <param name="sortdir">sans de l'ordre (exemple : 'ASC' pour croissant)</param> /// <param name="page">numéro de page</param> /// <param name="count">nombre element dans une page</param> /// <param name="archive"></param> /// <returns></returns> public ListePaginee<Visite> ListeVisites(string site = null, string username = null, DateTime? startDate = null, DateTime? endDate = null, string sortindex = null, string sortdir = "ASC", int page = 1, int count = 10, bool archive = false) { var req = ent.OP_VISITE .Join(ent.OP_DATE_HORAIRE, ov => ov.OPV_ID, odh => odh.OPDH_OPV_ID, (ov, odh) => new { ov, odh }) .Join(ent.OP_VISITE_VISITEUR, joined => joined.ov.OPV_ID, ovv => ovv.OPVVS_OPV_ID, (joined, ovv) => new { joined.ov, joined.odh, ovv }) .Join(ent.OP_VISITEUR, joined => joined.ovv.OPVVS_OPVS_ID, ovvs => ovvs.OPVS_ID, (joined, ovvs) => new { joined.ov, joined.odh, joined.ovv, ovvs }) .Where(joined => (string.IsNullOrEmpty(site) || joined.ov.OPV_SITE.StartsWith(site)) && (string.IsNullOrEmpty(username) || joined.ov.OPV_COLLAB_USERNAME.StartsWith(username)) && (startDate == null || EntityFunctions.TruncateTime(joined.odh.OPDH_DATE_DEBUT) >= EntityFunctions.TruncateTime(startDate)) && (endDate == null || EntityFunctions.TruncateTime(joined.odh.OPDH_DATE_DEBUT) <= EntityFunctions.TruncateTime(endDate)) && (joined.ov.OPV_ARCHIVE == archive)) .Select(result => new Visite { id = result.ov.OPV_ID, archive = result.ov.OPV_ARCHIVE, description = result.ov.OPV_DESCRIPTION, site = result.ov.OPV_SITE, status = result.ov.OPV_STATUS, sujet = result.ov.OPV_SUJET, titre = result.ov.OPV_TITRE, type = result.ov.OPV_TYPE_VISITE, dateDebut = result.odh.OPDH_DATE_DEBUT, dateFin = result.odh.OPDH_DATE_FIN, duree = result.odh.OPDH_DUREE, heureArrivee = result.odh.OPDH_HEURE_ARRIVEE, heureDepart = result.odh.OPDH_HEURE_DEPART, badge = result.ovv.OPVVS_BADGE, overtime = result.ovv.OPVVS_OVERTIME, plaqueImmatriculation = result.ovv.OPVVS_PLAQUE_IMMATRICUL, parking = result.ovv.OPVVS_PARKING, nomCollaborateur = result.ov.OPV_COLLAB_USERNAME, contact = new VisiteContact { nom = result.ov.OPV_NOM_CONTACT, telephone = result.ov.OPV_TELEPHONE_CONTACT } }).OrderBy(x => EntityFunctions.DiffDays(x.dateDebut, DateTime.Now)).AsEnumerable(); req = req.Distinct(); var visiteListe = req.ToList(); List<Visite> listeVisite = new List<Visite>(); #region système de pagination int total = req.Count(); IEnumerable<Visite> elems = Enumerable.Empty<Visite>(); if (string.IsNullOrEmpty(sortindex)) { elems = req.AsEnumerable(); } else { var nomPropriete = typeof(Visite).GetProperty(sortindex, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (sortdir.Equals("ASC", StringComparison.InvariantCultureIgnoreCase)) { elems = req.OrderBy(x => nomPropriete.GetValue(x, null)); } else { elems = req.OrderByDescending(x => nomPropriete.GetValue(x, null)); } } var res = elems.Skip((page - 1) * count).Take(count); #endregion return new ListePaginee<Visite> { count = count, elements = res.ToList(), page = page, total = total }; } public Visite GetVisite(int visiteId) { var listeVisiteur = GetListeVisiteurFromVisite(visiteId); var req = (from ov in ent.OP_VISITE join odh in ent.OP_DATE_HORAIRE on ov.OPV_ID equals odh.OPDH_OPV_ID join ovv in ent.OP_VISITE_VISITEUR on ov.OPV_ID equals ovv.OPVVS_OPV_ID join ovvs in ent.OP_VISITEUR on ovv.OPVVS_OPVS_ID equals ovvs.OPVS_ID where ( ov.OPV_ID.Equals(visiteId) ) select new Visite { archive = ov.OPV_ARCHIVE, badge = ovv.OPVVS_BADGE, dateDebut = odh.OPDH_DATE_DEBUT, dateFin = odh.OPDH_DATE_FIN, overtime = ovv.OPVVS_OVERTIME, titre = ov.OPV_TITRE, description = ov.OPV_DESCRIPTION, site = ov.OPV_SITE, type = ov.OPV_TYPE_VISITE, status = ov.OPV_STATUS, id = ov.OPV_ID, duree = odh.OPDH_DUREE, heureArrivee = odh.OPDH_HEURE_ARRIVEE, heureDepart = odh.OPDH_HEURE_DEPART, nomCollaborateur = ov.OPV_COLLAB_USERNAME, reponse = new VisiteReponse { refus = (bool)ovv.OPVVS_REFUS ? ovv.OPVVS_REFUS : false, raisonRefus = ovv.OPVVS_RAISON_REFUS }, contact = new VisiteContact { nom = ov.OPV_NOM_CONTACT, telephone = ov.OPV_TELEPHONE_CONTACT } }).AsEnumerable(); if (listeVisiteur.Count == 0) { throw new Exception("Aucun visiteur pour cette visite"); } var visiteWithVisiteurs = req.ToArray(); var visiteToReturn = req.FirstOrDefault(); visiteToReturn.reponse = null; for (var i = 0; i < visiteWithVisiteurs.Length; i++) { var visiteur = listeVisiteur.ElementAt(i); var visite = visiteWithVisiteurs.ElementAt(i); visiteur.reponse = visite.reponse; } if (visiteToReturn != null) { visiteToReturn.visiteurs = listeVisiteur; } //return visiteWithVisiteurs; return visiteToReturn; } public VisiteCourante GetVisiteByKey(string key) { var vvs = ent.OP_VISITE_VISITEUR.SingleOrDefault(v => v.OPVVS_CLE_LIEN == key); if (vvs == null) { throw new ExceptionNotFoundApi("Clé invalide"); } var visiteur = vvs.OP_VISITEUR; var visite = vvs.OP_VISITE; var odh = visite.OP_DATE_HORAIRE.SingleOrDefault(dh => dh.OPDH_OPV_ID == visite.OPV_ID); if (odh == null || vvs == null) { throw new ExceptionNotFoundApi("Erreur: Cette visite n'existe pas"); } return new VisiteCourante { archive = vvs.OP_VISITE.OPV_ARCHIVE, collabUsername = visite.OPV_COLLAB_USERNAME, confirmee = vvs.OPVVS_CONFIRMEE, overtime = vvs.OPVVS_OVERTIME, badge = vvs.OPVVS_BADGE, parking = vvs.OPVVS_PARKING, dateDebut = odh.OPDH_DATE_DEBUT, heureDebut = odh.OPDH_HEURE_ARRIVEE, heureDebutPrev = odh.OPDH_HEURE_DEBUT_PREV, dateDebutPrev = odh.OPDH_DATE_DEBUT_PREV, dateFinPrev = odh.OPDH_DATE_FIN_PREV, heureFinPrev = odh.OPDH_HEURE_FIN_PREV, description = visite.OPV_DESCRIPTION, donneeReponse = vvs.OPVVS_DONNEE_REPONSE, horaireId = odh.OPDH_ID, idVvs = vvs.OPVVS_ID, idVisite = visite.OPV_ID, idVisiteur = visiteur.OPVS_ID, email = visiteur.OPVS_EMAIL, nom = visiteur.OPVS_NOM, prenom = visiteur.OPVS_PRENOM, telephone = visiteur.OPVS_TELEPHONE, site = visite.OPV_SITE, status = visite.OPV_STATUS, titre = visite.OPV_TITRE, typeVisite = visite.OPV_TYPE_VISITE, duree = odh.OPDH_DUREE.HasValue ? odh.OPDH_DUREE.Value : 0, }; } /// <summary> /// Crée une visite /// </summary> /// <param name="valeur"></param> /// <returns>Identifiant de la visite crée</returns> public VisiteVisiteur CreerVisite(VisiteVisiteur valeur) { if (valeur.visiteurs.Count <= 0) { throw new Exception("Au moins un visiteur est requis"); } var visite = new OP_VISITE { OPV_ARCHIVE = false, OPV_DESCRIPTION = valeur.visite.description, OPV_SITE = valeur.visite.site, OPV_STATUS = valeur.visite.status, OPV_SUJET = valeur.visite.sujet, OPV_TITRE = valeur.visite.titre, OPV_TYPE_VISITE = valeur.visite.type, OPV_COLLAB_USERNAME = valeur.visite.initiateur, OPV_NOM_CONTACT = valeur.visite.contact.nom, OPV_TELEPHONE_CONTACT = valeur.visite.contact.telephone }; var dateHoraire = new OP_DATE_HORAIRE { OPDH_DATE_DEBUT = valeur.visite.dateDebut, OPDH_HEURE_ARRIVEE = valeur.visite.heureArrivee, OPDH_DUREE = valeur.visite.duree, OPDH_SITE = valeur.visite.site, OP_VISITE = visite, }; var index = 0; Random rnd = new Random(); valeur.visiteurs.ForEach((payloadVisiteur) => { OP_VISITE_VISITEUR visiteCourrante = new OP_VISITE_VISITEUR { // données globales OPVVS_BADGE = valeur.badge, OPVVS_OVERTIME = valeur.overtime, OP_VISITE = visite, OPVVS_PARKING = payloadVisiteur.parking, OPVVS_PLAQUE_IMMATRICUL = payloadVisiteur.plaqueImmatriculation, }; var visiteurExistant = ent.OP_VISITEUR.SingleOrDefault(ov => ov.OPVS_ID == payloadVisiteur.id); if (visiteurExistant != null) { visiteCourrante.OP_VISITEUR = visiteurExistant; } else { visiteCourrante.OP_VISITEUR = new OP_VISITEUR { OPVS_EMAIL = payloadVisiteur.email, OPVS_NOM = payloadVisiteur.nom, OPVS_PRENOM = payloadVisiteur.prenom, OPVS_TELEPHONE = payloadVisiteur.telephone, }; } string hash = UtilHelpers.GenSHA512($"{rnd.Next()}{visiteCourrante.OP_VISITEUR.OPVS_EMAIL}"); visiteCourrante.OPVVS_CLE_LIEN = hash; valeur.visiteurs[index].hashKey = hash; ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante); index++; }); ent.OP_DATE_HORAIRE.AddObject(dateHoraire); ent.SaveChanges(); return new VisiteVisiteur() { id = visite.OPV_ID, visite = valeur.visite, visiteurs = valeur.visiteurs }; } /// <summary> /// Modifier une visite /// </summary> /// <param name="id"></param> /// <param name="valeur"></param> /// <returns></returns> /// public VisiteVisiteur ModifierVisite(int id, Visite valeur,List<Visiteur> visiteurs) { var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id); if (visite == null) { throw new ExceptionDataConstraint("La visite n'existe pas"); } visite.OPV_ARCHIVE = valeur.archive; visite.OPV_DESCRIPTION = valeur.description; visite.OPV_SITE = valeur.site; visite.OPV_STATUS = valeur.status; visite.OPV_SUJET = valeur.titre; visite.OPV_TITRE = valeur.titre; var dateHoraire = ent.OP_DATE_HORAIRE.SingleOrDefault(dh => dh.OPDH_OPV_ID == visite.OPV_ID); if (dateHoraire == null) { throw new ExceptionDataConstraint("La date de la visite n'existe pas"); } dateHoraire.OPDH_DATE_DEBUT = valeur.dateDebut; dateHoraire.OPDH_DUREE = valeur.duree; var visiteursCourants = ent.OP_VISITE_VISITEUR.Where(vv => vv.OPVVS_OPV_ID == visite.OPV_ID).ToList(); foreach (var visiteurCourant in visiteursCourants) { ent.OP_VISITE_VISITEUR.DeleteObject(visiteurCourant); } foreach (var visiteur in visiteurs) { var visiteurExistant = ent.OP_VISITEUR.SingleOrDefault(ov => ov.OPVS_ID == visiteur.id); if (visiteurExistant != null) { var visiteCourrante = new OP_VISITE_VISITEUR { OPVVS_PARKING = visiteur.parking, OPVVS_PLAQUE_IMMATRICUL = visiteur.plaqueImmatriculation, OP_VISITE = visite, OP_VISITEUR = visiteurExistant }; ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante); } else { var visiteurCourant = new OP_VISITEUR { OPVS_EMAIL = visiteur.email, OPVS_NOM = visiteur.nom, OPVS_PRENOM = visiteur.prenom, OPVS_TELEPHONE = visiteur.telephone }; ent.OP_VISITEUR.AddObject(visiteurCourant); var visiteCourrante = new OP_VISITE_VISITEUR { OPVVS_PARKING = visiteur.parking, OPVVS_PLAQUE_IMMATRICUL = visiteur.plaqueImmatriculation, OP_VISITE = visite, OP_VISITEUR = visiteurCourant }; ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante); } } ent.SaveChanges(); return new VisiteVisiteur { id = visite.OPV_ID, visite = valeur, visiteurs = visiteurs }; } public Visiteur AddVisitortovisit(int id, List<Visiteur> visiteurs) { var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id); if (visite == null) { throw new ExceptionDataConstraint("La visite n'existe pas"); } foreach (var visiteur in visiteurs) { var visiteurExistant = ent.OP_VISITEUR.SingleOrDefault(ov => ov.OPVS_ID == visiteur.id); if (visiteurExistant != null) { var visiteCourrante = new OP_VISITE_VISITEUR { OPVVS_PARKING = visiteur.parking, OPVVS_PLAQUE_IMMATRICUL = visiteur.plaqueImmatriculation, OP_VISITE = visite, OP_VISITEUR = visiteurExistant }; ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante); } else { var visiteurCourant = new OP_VISITEUR { OPVS_EMAIL = visiteur.email, OPVS_NOM = visiteur.nom, OPVS_PRENOM = visiteur.prenom, OPVS_TELEPHONE = visiteur.telephone }; ent.OP_VISITEUR.AddObject(visiteurCourant); } } ent.SaveChanges(); return new Visiteur(); } /// <summary> /// /// </summary> /// <param name="nom"></param> /// <param name="prenom"></param> /// <param name="username"></param> /// <param name="sortindex"></param> /// <param name="sortdir"></param> /// <param name="page"></param> /// <param name="count"></param> /// <returns></returns> public ListePaginee<Visiteur> ListeVisiteur(string nom = null, string prenom = null, string username = null, string sortindex = null, string sortdir = "ASC", int page = 1, int count = 10) { var req = ent.OP_VISITEUR .Join(ent.OP_VISITE_VISITEUR, ov => ov.OPVS_ID, ovv => ovv.OPVVS_OPVS_ID, (ov, ovv) => new Visiteur { nom = ov.OPVS_NOM, prenom = ov.OPVS_PRENOM, email = ov.OPVS_EMAIL, telephone = ov.OPVS_TELEPHONE, id = ov.OPVS_ID }) .Where(ov => (string.IsNullOrEmpty(nom) || ov.nom.StartsWith(nom)) && (string.IsNullOrEmpty(prenom) || ov.prenom.StartsWith(prenom))) .Distinct() .AsEnumerable(); #region système de pagination int total = req.Count(); IEnumerable<Visiteur> elems = Enumerable.Empty<Visiteur>(); if (string.IsNullOrEmpty(sortindex)) { elems = req; } else { var nomPropriete = typeof(Visiteur).GetProperty(sortindex, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (sortdir.Equals("ASC", StringComparison.InvariantCultureIgnoreCase)) { elems = req.OrderBy(x => nomPropriete.GetValue(x, null)); } else { elems = req.OrderByDescending(x => nomPropriete.GetValue(x, null)); } } var res = elems.Skip((page - 1) * count).Take(count); #endregion return new ListePaginee<Visiteur> { count = count, elements = res.ToList(), page = 0, total = total }; } /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="valeur"></param> /// <returns></returns> public VisiteVisiteur ModifierVisiteur(int id, VisiteVisiteur valeur) { var visiteur = ent.OP_VISITEUR.SingleOrDefault(v => v.OPVS_ID == id); if (visiteur == null) { throw new ExceptionDataConstraint("Le visiteur n'existe pas"); } visiteur.OPVS_NOM = valeur.visiteurs[0].nom; visiteur.OPVS_PRENOM = valeur.visiteurs[0].prenom; visiteur.OPVS_EMAIL = valeur.visiteurs[0].email; visiteur.OPVS_TELEPHONE = valeur.visiteurs[0].telephone; ent.SaveChanges(); return new VisiteVisiteur() { id = visiteur.OPVS_ID, visite = valeur.visite, visiteurs = valeur.visiteurs }; } public VisiteVisiteur EnvoieReponseVisite(int visiteId, int visiteurId, VisiteReponse valeur) { var result = GetVisiteCourante(visiteId, visiteurId); var visiteCourante = result.Item1; if (visiteCourante.OPVVS_DONNEE_REPONSE == true) { throw new ExceptionDataConstraint("Le visiteur à déja repondu à la visite"); } visiteCourante.OPVVS_DONNEE_REPONSE = true; if ((bool)valeur.refus) { visiteCourante.OPVVS_REFUS = valeur.refus; visiteCourante.OPVVS_RAISON_REFUS = valeur.raisonRefus; } visiteCourante.OPVVS_PLAQUE_IMMATRICUL = valeur.plaqueImmat; visiteCourante.OPVVS_PARKING = valeur.parking; var estCurrVisiteRefusee = estVisiteRefusee(result.Item2); var estVisiteInitie = !estCurrVisiteRefusee && estVisiteInitiee(result.Item2); if (estCurrVisiteRefusee) { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE; } if (estVisiteInitie) // si tous les visiteurs ont repondu { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.CONFIRMATION_INITIATEUR; } ent.SaveChanges(); return new VisiteVisiteur(); } public VisiteVisiteur EnvoieRefusVisiteur(int visiteId, int visiteurId, VisiteReponse valeur) { var result = GetVisiteCourante(visiteId, visiteurId); var visiteCourante = result.Item1; if (!visiteCourante.OPVVS_DONNEE_REPONSE) { throw new ExceptionDataConstraint("Le visiteur n'a pas encore donnée sa réponse"); } if (valeur.refus.HasValue && valeur.refus.Value) { visiteCourante.OPVVS_REFUS = valeur.refus; visiteCourante.OPVVS_RAISON_REFUS = valeur.raisonRefus; } visiteCourante.OPVVS_CONFIRMEE = true; bool isVisitRefusee = estVisiteRefusee(result.Item2); bool isVisitProgramme = !isVisitRefusee && estVisiteProgramme(result.Item2); if (estVisiteRefusee(result.Item2)) { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE; } if (isVisitProgramme) // si tous les visiteurs ont repondu { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.PROGRAMMEE; } ent.SaveChanges(); return new VisiteVisiteur { }; } public HttpResponseExtension SignalerPresenceVisiteur(int visiteId, int visiteurId) { var result = GetVisiteCourante(visiteId, visiteurId); HttpResponseExtension reponse = new HttpResponseExtension(); var visiteCourante = result.Item1; if (!visiteCourante.OPVVS_DONNEE_REPONSE || !visiteCourante.OPVVS_CONFIRMEE || (visiteCourante.OPVVS_REFUS.HasValue && visiteCourante.OPVVS_REFUS.Value)) { throw new ExceptionDataConstraint("Erreur: L'Etat du visiteur n'est pas valide"); } visiteCourante.OPVVS_PRESENT = true; var estCurrVisiteEnCours = estVisiteEnCours(result.Item2); if (estCurrVisiteEnCours) { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.EN_COURS; reponse.statusUpdated = true; } ent.SaveChanges(); reponse.message = "Le visiteur à été signalé comme entré"; return reponse; } public Tuple<OP_VISITE_VISITEUR, List<OP_VISITE_VISITEUR>> GetVisiteCourante(int visiteId, int visiteurId) { var visiteVisiteurs = ent.OP_VISITE_VISITEUR.Where(vvs => vvs.OP_VISITE.OPV_ID == visiteId).ToList(); var dataVisiteCourante = visiteVisiteurs.Where(visiteur => visiteur.OP_VISITEUR.OPVS_ID == visiteurId).SingleOrDefault(); if (dataVisiteCourante == null || dataVisiteCourante == null) { throw new ExceptionDataConstraint("Aucun visiteur ou aucune visite existante"); } return Tuple.Create(dataVisiteCourante, visiteVisiteurs); } public bool estVisiteRefusee(List<OP_VISITE_VISITEUR> ovvs) { return ovvs.Where(v => v.OPVVS_REFUS == true).Count() == ovvs.Count(); } public bool estVisiteProgramme(List<OP_VISITE_VISITEUR> ovvs) { return ovvs.Where(v => v.OPVVS_CONFIRMEE == true).Count() == ovvs.Count(); } public bool estVisiteInitiee(List<OP_VISITE_VISITEUR> ovvs) { return ovvs.Where(v => v.OPVVS_DONNEE_REPONSE == true).Count() == ovvs.Count(); } public bool estVisiteEnCours(List<OP_VISITE_VISITEUR> ovvs) { return ovvs.Where(v => v.OPVVS_PRESENT == true).Count() == ovvs.Count(); } public bool ConfirmationVisiteur(int visiteId, int visiteurId) { var result = GetVisiteCourante(visiteId, visiteurId); var visiteCourante = result.Item1; visiteCourante.OPVVS_CONFIRMEE = true; bool estCurrVisiteRefuse = estVisiteRefusee(result.Item2); bool estCurrVisiteProgramme = estVisiteProgramme(result.Item2); if (estCurrVisiteRefuse) { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE; } if (estCurrVisiteProgramme) { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.PROGRAMMEE; } ent.SaveChanges(); return true; } public List<Visiteur> GetListeVisiteurFromVisite(int visiteId) { var visiteurQuery = ent.OP_VISITE .Join(ent.OP_DATE_HORAIRE, ov => ov.OPV_ID, odh => odh.OPDH_OPV_ID, (ov, odh) => new { ov, odh }) .Join(ent.OP_VISITE_VISITEUR, joined => joined.ov.OPV_ID, ovv => ovv.OPVVS_OPV_ID, (joined, ovv) => new { joined.ov, joined.odh, ovv }) .Join(ent.OP_VISITEUR, joined => joined.ovv.OPVVS_OPVS_ID, ovvs => ovvs.OPVS_ID, (joined, ovvs) => new { joined.ovv, ovvs }) .Where(joined => joined.ovv.OPVVS_OPV_ID == visiteId) .Select(result => new { result.ovvs.OPVS_NOM, result.ovvs.OPVS_PRENOM, result.ovvs.OPVS_EMAIL, result.ovvs.OPVS_TELEPHONE, result.ovvs.OPVS_ID, result.ovv.OPVVS_PLAQUE_IMMATRICUL, result.ovv.OPVVS_PARKING, result.ovv.OPVVS_DONNEE_REPONSE, result.ovv.OPVVS_CONFIRMEE, result.ovv.OPVVS_RAISON_REFUS, result.ovv.OPVVS_REFUS, result.ovv.OPVVS_PRESENT }); var visiteurListe = visiteurQuery.ToList(); if (visiteurListe.Count == 0) throw new DataNotFoundException("Les données demandées n'existent pas"); List<Visiteur> listeVisiteur = new List<Visiteur>(); visiteurListe.ForEach((OP_VISITEUR) => { listeVisiteur.Add(new Visiteur { nom = OP_VISITEUR.OPVS_NOM, prenom = OP_VISITEUR.OPVS_PRENOM, telephone = OP_VISITEUR.OPVS_TELEPHONE, email = OP_VISITEUR.OPVS_EMAIL, plaqueImmatriculation = OP_VISITEUR.OPVVS_PLAQUE_IMMATRICUL, id = OP_VISITEUR.OPVS_ID, parking = OP_VISITEUR.OPVVS_PARKING, donneeReponse = OP_VISITEUR.OPVVS_DONNEE_REPONSE, confirmer = OP_VISITEUR.OPVVS_CONFIRMEE, present = OP_VISITEUR.OPVVS_PRESENT, reponse = new VisiteReponse { raisonRefus = OP_VISITEUR.OPVVS_RAISON_REFUS, refus = OP_VISITEUR.OPVVS_REFUS, plaqueImmat = OP_VISITEUR.OPVVS_PLAQUE_IMMATRICUL } }); }); return listeVisiteur; } /// <summary> /// Créer une date horaire /// </summary> /// <param name="valeur"></param> /// <returns></returns> public DateHoraire CreeHoraire(DateHoraire valeur) { return new DateHoraire() { }; } /// <summary> /// Création d'un visiteur /// </summary> /// <param name="value"></param> /// <returns></returns> public Visiteur CreerVisiteur(Visiteur value) { return new Visiteur { }; } public Visite ArchiveVisite(int id) { var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id); if (visite == null) { return null; } visite.OPV_ARCHIVE = true; ent.SaveChanges(); return new Visite { id = id }; } } } Modification des visiteurs: - ajouter une fonction qui boucle des visiteurs en paramètre et qui les crée et les ajoute à la visite dépendant si il existe ou non. and adapt AddVisitortovisit method
1027d0986f8f44e4b57d451de104e396
{ "intermediate": 0.34747663140296936, "beginner": 0.4042559266090393, "expert": 0.24826745688915253 }
46,115
How do I parse these strings to give me these arrays in java? "hi " == ["hi", " "] " hi" == [" ", "hi"]
5c24196bd197275d81a2d24b285515ed
{ "intermediate": 0.792007565498352, "beginner": 0.07785475254058838, "expert": 0.13013769686222076 }
46,116
convert this pinescript so that i can run it in mql5 //@version=5 indicator("Autocorrelation Candles [SS]", max_labels_count = 500, overlay=true) import HeWhoMustNotBeNamed/arrays/1 as arrays show_reversals = input.bool(true, "Show Reversals") limit_labels = input.bool(false, "Limit Labels") limit_len = input.int(30, "Limit Labels to #") size = input.string("Tiny", "Label Size", ["Tiny", "Normal", "Large"]) col = input.string("White", "Text Colour", ["White", "Black"]) cor = math.round(ta.correlation(close, close[1], 14), 2) highest = ta.highest(cor, 75) trend = ta.correlation(time, close, 14) atr = ta.atr(10) bool reversal = cor >= highest bool generic = cor >= 0.94 color text_color = na if col == "White" text_color := color.white else if col == "Black" text_color := color.rgb(0, 0, 0) color transp = color.new(color.white, 100) color collah = reversal ? color.orange : generic ? color.red : text_color bool upside_reversal = trend <= -0.5 and cor >= 0.94 bool downside_reversal = trend >= 0.5 and cor >= 0.94 string reversal_string = upside_reversal ? "Likely \n Upside Reversal" : downside_reversal ? "Likely \n Downside Reversal" : na label_array = array.new<label>() reversal_array = array.new<label>() create_label(id) => label.new(bar_index[id], y = low[id], text = str.tostring(cor[id]), color = transp, textcolor = reversal[id] ? color.orange : cor[id] >= 0.94 ? color.red : text_color, style = label.style_label_up, size = size == "Tiny" ? size.tiny : size == "Normal" ? size.normal : size == "Large" ? size.large : size.tiny) reversal_label(id) => label.new(bar_index[id], y = high[id] + atr[id], text = upside_reversal[id] or downside_reversal[id] ? str.tostring(reversal_string[id]) : na, color = transp, textcolor = trend[id] <= -0.5 ? color.lime : trend[id] >= 0.5 ? color.red : text_color, style = label.style_label_up, size =size == "Tiny" ? size.tiny : size == "Normal" ? size.normal : size == "Large" ? size.large : size.tiny) if limit_labels != true label.new(bar_index, y = low, text = str.tostring(cor), color = transp, textcolor = collah, style = label.style_label_up, size = size == "Tiny" ? size.tiny : size == "Normal" ? size.normal : size == "Large" ? size.large : size.tiny) if show_reversals label.new(bar_index, y = high + atr, text = upside_reversal or downside_reversal ? str.tostring(reversal_string) : na, color = transp, textcolor = trend <= -0.5 ? color.lime : trend >= 0.5 ? color.red : color.white, style = label.style_label_up, size = size == "Tiny" ? size.tiny : size == "Normal" ? size.normal : size == "Large" ? size.large : size.tiny) else if limit_labels for i = 0 to limit_len arrays.push(label_array, create_label(i), limit_len) if show_reversals arrays.push(reversal_array, reversal_label(i), limit_len)
760a2668a7355d9e9e7db79a3088b7fd
{ "intermediate": 0.29304108023643494, "beginner": 0.44097310304641724, "expert": 0.2659858465194702 }
46,117
Subprocess: execute application in wine Linux
f1415da5f07526688fcf0c0f1b18d760
{ "intermediate": 0.41701656579971313, "beginner": 0.2679448425769806, "expert": 0.31503862142562866 }
46,118
Make this regex also include \n characters: "(?<=\s)|(?=\s)"
be5be492970532e6713e7d4b76898190
{ "intermediate": 0.34128981828689575, "beginner": 0.3824571669101715, "expert": 0.27625295519828796 }
46,119
Make this regex also include \n characters, it doesnt work in java "word".split(""(?<=\s)|(?=\s)"")
27e327e89f06d0f2f5bb2b1c8a5ab593
{ "intermediate": 0.459151029586792, "beginner": 0.2867923676967621, "expert": 0.25405657291412354 }
46,120
A: Diamond Ring B: Totality C: Shadow Bands D: Partial Eclipse E: Baily's Beads put in order
051286c2b7bef7691f90eac5d27baabc
{ "intermediate": 0.4133599102497101, "beginner": 0.31268778443336487, "expert": 0.27395233511924744 }
46,121
Make this regex also include \n characters, it doesnt work in java "word".split(""(?<=\s)|(?=\s)""). For some reason, a word like "hi\n" will not split hi and \n together
1f2a484898d858a5e463829e3a3250d7
{ "intermediate": 0.45994657278060913, "beginner": 0.21718202531337738, "expert": 0.3228713870048523 }
46,122
Suppose I have a function that takes in as a param another function that accepts ints and returns strings. How can I use jsdoc to document the type of this param?
ff79d7b2bfbc275502f17da2e6cecd49
{ "intermediate": 0.5581041574478149, "beginner": 0.2525635361671448, "expert": 0.18933239579200745 }
46,123
#include <iostream> #include <vector> #include <cmath> using namespace std; int maxSumAbsolute(vector<int>& arr) { int n = arr.size(); int max_sum = INT_MIN; for (int i = 0; i < n - 2; ++i) { for (int j = i + 1; j < n - 1; ++j) { for (int k = j + 1; k < n; ++k) { int sum = abs(arr[i] + arr[j] + arr[k]); if (sum > max_sum) { max_sum = sum; } } } } return max_sum; } int main() { int N; cout << "Nhap so phan tu cua day: "; cin >> N; vector<int> arr(N); cout << "Nhap cac phan tu cua day:\n"; for (int i = 0; i < N; ++i) { cin >> arr[i]; } int result = maxSumAbsolute(arr); cout << "Gia tri lon nhat cua S = |ai + aj + ak| la: " << result << endl; return 0; } giảm độ phức tạp thuật toán của bài sau
4d5b7461ff98964597ad787e3c5fc6db
{ "intermediate": 0.3023815155029297, "beginner": 0.4034103453159332, "expert": 0.29420819878578186 }
46,124
..so basically i have 4 excel sheets ...........1. Stock price for Indian companies (here on 1st row it has names of columns ISIN, Date and Price close) 2. Final events M&A---India (column names are Date Event ,Date Type ,Event Type ,RIC ,Company Name ,Event Name ,Summarization ,Announce Date ,Target Name ,Acquiror Name) 3. Index Prices (Here there are 4 columns first 2 columns have data for BSE ltd and next 2 columns have National India data which is exchange date and close ....so on 1st row index name is written and second row has title of exchange date and close) 4. ISIN with exchange (here there are two columns name ISIN AND Exchange, So with their ISIN their index is written) I have the above data in xlsx format and i already calculated Actual returns for stocks and Index and just after that i have to calculate Expected returns .....................There are total 141 events of dissolution from past two years and i have to study the impact of that on 55 companies that are registered. So basically Each ISIN have one of the two exchange so i have the data for that as well and with that index prices for last two years which is daily data and stock prices of each company from past two years daily data .
865902eb603e9f3c90a97d4ccf5727f2
{ "intermediate": 0.3162302076816559, "beginner": 0.298197865486145, "expert": 0.38557198643684387 }
46,125
Change this code "model = Sequential() model.add(ResNet50(weights='imagenet', include_top=False, input_shape=(image_size, image_size, 3))) model.add(GlobalAveragePooling2D()) model.add(Dropout(rate=0.5)) model.add(Dense(5,activation='softmax')) model.summary()" to this form: x= ...
92f05d0c83afe035228f203b0fcb9199
{ "intermediate": 0.27273914217948914, "beginner": 0.23364704847335815, "expert": 0.4936138987541199 }
46,126
In My dissertation i am focusing on technology sector of Indian markets considering stock price as my variable. So basically i have data with dissolution events with its date and type of dissolution. At the time when dissolution happen…i want to study the impact of that dissolution on existing companies or we can say competitors in technology sector from their stock price. …Above is my main focus …so i was thinking based on the data i have currently which is Companies—55, events—141, time—2 years(2022 & 2023) and type of data–> stock price of past 2 years on trading days …so basically i have 4 excel sheets …1. Stock price for Indian companies (here on 1st row it has names of columns ISIN, Date and Price close) 2. Final events M&A—India (column names are Date Event ,Date Type ,Event Type ,RIC ,Company Name ,Event Name ,Summarization ,Announce Date ,Target Name ,Acquiror Name) 3. Index Prices (Here there are 4 columns first 2 columns have data for BSE ltd and next 2 columns have National India data which is exchange date and close …so on 1st row index name is written and second row has title of exchange date and close) 4. ISIN with exchange (here there are two columns name ISIN AND Exchange, So with their ISIN their index is written) …So first calculating Abnormal returns (Actual returns and expected returns) then calculating CAR with considerign event window then running t-test to see the impact of that event on their stock price …this could be the first option and second option could be calculating abnormal returns and CAr considering event window and events and by doing this we can see the effect of events of competitor’s …which could be the best option and why …is it possible to do that as their are big number of events and i have to run code for that altogether to see the impact using R …if yes it is possible then can you please give me codes for that
6cf84900f53b366529fc932f75bc541d
{ "intermediate": 0.4056292176246643, "beginner": 0.18554864823818207, "expert": 0.40882208943367004 }
46,127
I would like to know how to count the number of full-width characters among the full-width half-width characters entered in a column in onChange of the client script.
b6411e1373282ce7ae5049a4d475c9e7
{ "intermediate": 0.5234107375144958, "beginner": 0.18758976459503174, "expert": 0.2889994978904724 }
46,128
My code: “ import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import cv2 import random import tensorflow as tf import tkinter as tk from tkinter import filedialog from PIL import ImageTk, Image from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from IPython.display import display, clear_output from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl from tensorflow.keras.preprocessing.image import ImageDataGenerator from tqdm import tqdm import os from sklearn.utils import shuffle from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential, Model, load_model from tensorflow.keras.layers import ( GlobalAveragePooling2D, Dropout, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation, concatenate, Conv2DTranspose, Input, Reshape, UpSampling2D, ) from tensorflow.keras.applications import ( EfficientNetV2B0, EfficientNetV2B1, EfficientNetV2B2, EfficientNetV2B3, EfficientNetV2L, EfficientNetV2M, EfficientNetV2S, VGG16, VGG19, Xception, ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101, InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile ) from tensorflow.keras.utils import to_categorical from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint from sklearn.metrics import classification_report, confusion_matrix import ipywidgets as widgets import io from PIL import Image from IPython.display import display, clear_output from warnings import filterwarnings from google.colab import drive drive.mount(”/content/gdrive") def load_data(data_folders): X_data = [] # Combined data y_class_labels = [] # Combined classification labels y_seg_labels = [] # Combined segmentation labels for folderPath in data_folders: for label in labels: label_folder_path = os.path.join(folderPath, label) for filename in tqdm(os.listdir(label_folder_path)): if filename.endswith(“.jpg”): img = cv2.imread(os.path.join(label_folder_path, filename)) img = cv2.resize(img, (image_size, image_size)) X_data.append(img) y_class_labels.append(label) seg_filename = filename.split(“.”)[0] + “.png” seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0) seg_img = cv2.resize(seg_img, (image_size, image_size)) seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary y_seg_labels.append(seg_img) X_data = np.array(X_data) y_class_labels = np.array(y_class_labels) y_seg_labels = np.array(y_seg_labels) X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101) return X_data, y_class_labels, y_seg_labels def split_data(X_data, y_class_labels, class_data_counts): X_train, y_train_class = [], [] X_val, y_val_class = [], [] X_test, y_test_class = [], [] for label, count in class_data_counts.items(): label_indices = np.where(y_class_labels == label)[0] class_X_data = X_data[label_indices] class_y_class_labels = y_class_labels[label_indices] train_count, val_count, test_count = count class_X_train = class_X_data[:train_count] class_y_train_class = class_y_class_labels[:train_count] class_X_val = class_X_data[train_count: train_count + val_count] class_y_val_class = class_y_class_labels[train_count: train_count + val_count] class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count] class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count] X_train.extend(class_X_train) y_train_class.extend(class_y_train_class) X_val.extend(class_X_val) y_val_class.extend(class_y_val_class) X_test.extend(class_X_test) y_test_class.extend(class_y_test_class) # Convert class labels to categorical label_encoder = LabelEncoder() y_train_class_encoded = label_encoder.fit_transform(y_train_class) y_train_class_categorical = to_categorical(y_train_class_encoded) y_val_class_encoded = label_encoder.transform(y_val_class) y_val_class_categorical = to_categorical(y_val_class_encoded) y_test_class_encoded = label_encoder.transform(y_test_class) y_test_class_categorical = to_categorical(y_test_class_encoded) return ( np.array(X_train), np.array(y_train_class_categorical), np.array(X_val), np.array(y_val_class_categorical), np.array(X_test), np.array(y_test_class_categorical), ) def count_labels(y_class_categorical, label_encoder): # Convert one-hot encoded labels back to label encoded y_class_labels = np.argmax(y_class_categorical, axis=1) # Convert label encoded labels back to original class names y_class_names = label_encoder.inverse_transform(y_class_labels) unique, counts = np.unique(y_class_names, return_counts=True) return dict(zip(unique, counts)) def build_model(input_shape, num_classes): base_model = ResNet50(weights= None, include_top=False, input_shape=input_shape) x = GlobalAveragePooling2D()(base_model) x = Dropout(0.5)(x) # Classification output layer predictions = Dense(num_classes, activation=‘softmax’)(x) # Define the model model = Model(inputs=base_model.input, outputs=predictions) return model Categorical_Focal_loss = tf.keras.losses.CategoricalFocalCrossentropy( alpha=0.25, #0.25 default gamma=2.0, #2 from_logits=False, label_smoothing=0.0, axis=-1,) def train_model(model, X_train, y_train_class, X_val, y_val_class, batch_size, epochs): checkpoint = ModelCheckpoint( “classification_best_weights.h5”, monitor=“val_accuracy”, save_best_only=True, mode=“max”, verbose=1,) reduce_lr = ReduceLROnPlateau( monitor=“val_accuracy”, factor=0.3, patience=2, min_delta=0.001, mode=“auto”, verbose=1,) tensorboard = TensorBoard(log_dir=“logs”) model.compile( optimizer=Adam(lr=0.001), loss=Categorical_Focal_loss, metrics=[“accuracy”],) history = model.fit( X_train, y_train_class, validation_data=(X_val, y_val_class), epochs=epochs, verbose=1, batch_size=batch_size, callbacks=[checkpoint, reduce_lr, tensorboard],) return history def evaluate_model(model, X_test, y_test_class): # Load the best model weights best_model = load_model(“classification_best_weights.h5”) # Evaluate the model on test data test_loss, test_acc = best_model.evaluate(X_test, y_test_class) print(“Test Loss:”, test_loss) print(“Test Accuracy:”, test_acc) return test_acc def plot_performance(history): # Plot classification accuracy plt.figure(figsize=(10, 4)) # Accuracy plot plt.subplot(1, 2, 1) plt.plot(history.history[‘accuracy’], label=‘Training Accuracy’) plt.plot(history.history[‘val_accuracy’], label=‘Validation Accuracy’) plt.title(‘Classification Accuracy’) plt.xlabel(‘Epochs’) plt.ylabel(‘Accuracy’) plt.legend() # Loss plot plt.subplot(1, 2, 2) plt.plot(history.history[‘loss’], label=‘Training Loss’) plt.plot(history.history[‘val_loss’], label=‘Validation Loss’) plt.title(‘Classification Loss’) plt.xlabel(‘Epochs’) plt.ylabel(‘Loss’) plt.legend() plt.tight_layout() plt.show() # Image size and labels setup image_size = 224 labels = [“bridge”, “dirty”, “good”, “lift”, “shift”] # Data folders data_folders = [ “/content/gdrive/MyDrive/FYP_8/jit0/f_ffc/train”, “/content/gdrive/MyDrive/FYP_8/jit0/f_ffc/val”, “/content/gdrive/MyDrive/FYP_8/jit0/f_ffc/test”, ] # Load and split the data X_data, y_class_labels, y_seg_labels = load_data(data_folders) # Define train:val:test ratio for each class (ratio x4 = exact) class_data_counts = {“bridge”: [80, 80, 80], “dirty”: [80, 80, 80], “good”: [80, 80, 80], “lift”: [80, 80, 80], “shift”: [80, 80, 80] } X_train, y_train_class, X_val, y_val_class, X_test, y_test_class = split_data(X_data, y_class_labels, class_data_counts) # Initialize the label encoder label_encoder = LabelEncoder() label_encoder.fit(y_class_labels) # Count the number of images of each class in the train, validation, and test sets train_counts = count_labels(y_train_class, label_encoder) val_counts = count_labels(y_val_class, label_encoder) test_counts = count_labels(y_test_class, label_encoder) print(“Train counts: “, train_counts,” Total in train set:”, sum(train_counts.values())) print(“Validation counts:”, val_counts, " Total in validation set:“, sum(val_counts.values())) print(“Test counts: “, test_counts,” Total in test set:”, sum(test_counts.values())) # Train model n times input_shape = (image_size, image_size, 3) num_classes = len(labels) model = build_model(input_shape, num_classes) model.summary() test_acc_list = [] for i in range(5): print(f”\nTrain {i+1}:\n") #model = build_model(input_shape, num_classes) batch_size = 16 epochs = 50 history = train_model(model, X_train, y_train_class, X_val, y_val_class, batch_size, epochs) # Evaluate model on test data test_acc = evaluate_model(model, X_test, y_test_class) test_acc_list.append(test_acc) # Calculate average test classification accuracy average_test_acc = sum(test_acc_list) / len(test_acc_list) print(“Test Classification Accuracy List:”, test_acc_list) print(“Average Test Classification Accuracy:”, average_test_acc) “ Error:--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-ebb050df02e9> in <cell line: 4>() 2 input_shape = (image_size, image_size, 3) 3 num_classes = len(labels) ----> 4 model = build_model(input_shape, num_classes) 5 model.summary() 6 test_acc_list = [] 2 frames /usr/local/lib/python3.10/dist-packages/keras/src/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name) 211 # which does not have a shape attribute. 212 if not hasattr(x, “shape”): –> 213 raise TypeError( 214 f"Inputs to a layer should be tensors. Got ‘{x}’ “ 215 f”(of type {type(x)}) as input for layer ‘{layer_name}’.” TypeError: Inputs to a layer should be tensors. Got ‘<keras.src.engine.functional.Functional object at 0x788c4fe78430>’ (of type <class ‘keras.src.engine.functional.Functional’>) as input for layer ‘global_average_pooling2d_1’.
044b5b0396760ddbbd4bd65805a3201d
{ "intermediate": 0.359732061624527, "beginner": 0.4406496584415436, "expert": 0.19961832463741302 }
46,129
import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class floyd { private static int[][] adjMatrix; private static int[][] pMatrix; private static final String OUTPUT_FILE = "output_floyd.txt"; private static ArrayList<Integer> path = new ArrayList<>(); public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: java Floyd <graph-file>"); return; } try (Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0])))) { createFile(); while (scanner.hasNextInt()) { int n = scanner.nextInt(); // Number of vertices if (n < 5 || n > 10) { throw new IllegalArgumentException("Invalid number of vertices."); } initializeMatrices(n, scanner); calculateShortestPaths(); printResult(n); } } } private static void createFile() throws FileNotFoundException { PrintWriter writer = new PrintWriter(OUTPUT_FILE); writer.close(); } private static void initializeMatrices(int n, Scanner scanner) { adjMatrix = new int[n][n]; pMatrix = new int[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { adjMatrix[i][j] = scanner.nextInt(); if (adjMatrix[i][j] < 0 || adjMatrix[i][j] > 10) { throw new IllegalArgumentException("Edge weight must be between 0 and 10."); } if (i == j) { adjMatrix[i][j] = 0; } else { pMatrix[i][j] = j; } } } } private static void calculateShortestPaths() { int n = adjMatrix.length; for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (adjMatrix[i][k] + adjMatrix[k][j] < adjMatrix[i][j]) { adjMatrix[i][j] = adjMatrix[i][k] + adjMatrix[k][j]; pMatrix[i][j] = pMatrix[i][k]; } } } } } private static void printResult(int n) throws FileNotFoundException { StringBuilder builder = new StringBuilder(); for (int i = 0; i < n; ++i) { clearPathList(); builder.setLength(0); builder.append("Problem") .append(i + 1) .append(": n = ") .append(n) .append('\n') .append("Pmatrix:\n"); for (int j = 0; j < n; ++j) { builder.append(formatElement(adjMatrix[i][j])); if (j != n - 1) { builder.append(' '); } } builder.append('\n'); appendToFile(builder.toString()); builder.setLength(0); for (int j = 0; j < n; ++j) { if (i == j) continue; buildPath(i, j); builder .append("V") .append((char) ('A' + i)) .append(" - V") .append((char) ('A' + j)) .append(": Shortest Path = "); if (isDirectlyConnected(i, j)) { builder.append("Directly Connected"); } else { builder .append("[") .append(getShortestPathAsString(i, j)) .append("]; Length = ") .append(adjMatrix[i][j]) .append('\n'); } appendToFile(builder.toString()); builder.setLength(0); } builder.append('\n').append('\n'); appendToFile(builder.toString()); } } private static boolean isDirectlyConnected(int current, int destination) { return current == destination && adjMatrix[current][destination] > 0; } private static String getShortestPathAsString(int current, int destination) { StringBuilder stringBuilder = new StringBuilder(); int intermediateNode = current; while (intermediateNode != destination) { stringBuilder.append((char) ('A' + intermediateNode)); intermediateNode = pMatrix[intermediateNode][destination]; if (intermediateNode != destination) { stringBuilder.append(" -> "); } } stringBuilder.append((char) ('A' + intermediateNode)); return stringBuilder.toString(); } private static void buildPath(int current, int destination) { path.clear(); if (current != destination) { path.add(current); while (pMatrix[current][destination] != destination) { current = pMatrix[current][destination]; path.add(current); } path.add(destination); } } private static void clearPathList() { path.clear(); } private static String formatElement(int element) { return "%2d ".formatted(element); } private static void appendToFile(String string) throws FileNotFoundException { File outputFile = new File(OUTPUT_FILE); try (FileWriter fw = new FileWriter(outputFile, true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println(string); } catch (IOException ex) { ex.printStackTrace(); } } } I want this program to read the input Problem1 Amatrix: n = 7 0 6 5 4 6 3 6 6 0 6 4 5 5 3 5 6 0 3 1 4 6 4 4 3 0 4 1 4 6 5 1 4 0 5 5 3 5 4 1 5 0 3 6 3 6 4 5 3 0 Problem2 Amatrix: n = 6 0 1 2 1 3 4 1 0 3 2 2 3 2 3 0 3 3 6 1 2 3 0 3 5 3 2 3 3 0 5 4 3 6 5 5 0 correctly from the graphfile.txt and give the output as Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: 0 The solution of problem should start with an integer n (the number cities) and the n x n Pointer Array P (in the next n rows). The shortest paths should then follow, one per line. Output the shortest paths from C1 to all other cities, then C2 to all other cities, and Cn to all other cities.
4802d5aafadcd2d64f6d580b6bf430e2
{ "intermediate": 0.35600847005844116, "beginner": 0.48953330516815186, "expert": 0.15445825457572937 }
46,130
import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class floyd { private static int[][] adjMatrix; private static int[][] pMatrix; private static final String OUTPUT_FILE = "output.txt"; private static ArrayList<Integer> path = new ArrayList<>(); public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: java Floyd <graph-file>"); return; } try (Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0])))) { createFile(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("Problem")) { // Extract number of vertices from the line int n = Integer.parseInt(line.split("n = ")[1].trim()); if (n < 5 || n > 10) { throw new IllegalArgumentException("Invalid number of vertices."); } // Read and initialize the adjacency matrix for the current problem initializeMatrices(n, scanner); // Compute shortest paths and print results calculateShortestPaths(); printResult(n); } } } } private static void createFile() throws FileNotFoundException { PrintWriter writer = new PrintWriter(OUTPUT_FILE); writer.close(); } private static void initializeMatrices(int n, Scanner scanner) { adjMatrix = new int[n][n]; pMatrix = new int[n][n]; for (int i = 0; i < n; ++i) { if (!scanner.hasNextLine()) { throw new IllegalStateException("Expected adjacency matrix row is missing."); } String[] values = scanner.nextLine().trim().split("\s+"); for (int j = 0; j < n; ++j) { int weight = Integer.parseInt(values[j]); adjMatrix[i][j] = weight; if (weight < 0 || weight > 10) { throw new IllegalArgumentException("Edge weight must be between 0 and 10."); } if (i == j) { adjMatrix[i][j] = 0; } else if (weight != 0) { pMatrix[i][j] = j; } } } } private static void calculateShortestPaths() { int n = adjMatrix.length; for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (adjMatrix[i][k] + adjMatrix[k][j] < adjMatrix[i][j]) { adjMatrix[i][j] = adjMatrix[i][k] + adjMatrix[k][j]; pMatrix[i][j] = pMatrix[i][k]; } } } } } private static void printResult(int n) throws FileNotFoundException { StringBuilder builder = new StringBuilder(); for (int i = 0; i < n; ++i) { clearPathList(); builder.setLength(0); builder.append("Problem") .append(i + 1) .append(": n = ") .append(n) .append('\n') .append("Pmatrix:\n"); for (int j = 0; j < n; ++j) { builder.append(formatElement(adjMatrix[i][j])); if (j != n - 1) { builder.append(' '); } } builder.append('\n'); appendToFile(builder.toString()); builder.setLength(0); for (int j = 0; j < n; ++j) { if (i == j) continue; buildPath(i, j); builder .append("V") .append((char) ('A' + i)) .append(" - V") .append((char) ('A' + j)) .append(": Shortest Path = "); if (isDirectlyConnected(i, j)) { builder.append("Directly Connected"); } else { builder .append("[") .append(getShortestPathAsString(i, j)) .append("]; Length = ") .append(adjMatrix[i][j]) .append('\n'); } appendToFile(builder.toString()); builder.setLength(0); } builder.append('\n').append('\n'); appendToFile(builder.toString()); } } private static boolean isDirectlyConnected(int from, int to) { return pMatrix[from][to] == to && adjMatrix[from][to] > 0; } private static String getShortestPathAsString(int source, int destination) { if (adjMatrix[source][destination] == Integer.MAX_VALUE) { return "No path"; } StringBuilder pathBuilder = new StringBuilder(); pathBuilder.append("V").append((char) ('1' + source)); int inter = source; while (inter != destination) { inter = pMatrix[inter][destination]; pathBuilder.append(" V").append((char) ('1' + inter)); } return pathBuilder.toString(); } private static void buildPath(int current, int destination) { path.clear(); if (current != destination) { path.add(current); while (pMatrix[current][destination] != destination) { current = pMatrix[current][destination]; path.add(current); } path.add(destination); } } private static void clearPathList() { path.clear(); } private static String formatElement(int element) { return "%2d ".formatted(element); } private static void appendToFile(String string) throws FileNotFoundException { File outputFile = new File(OUTPUT_FILE); try (FileWriter fw = new FileWriter(outputFile, true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println(string); } catch (IOException ex) { ex.printStackTrace(); } } } The program is giving the output as Problem1: n = 7 Pmatrix: 0 6 5 4 6 3 6 VA - VB: Shortest Path = Directly Connected VA - VC: Shortest Path = Directly Connected VA - VD: Shortest Path = Directly Connected VA - VE: Shortest Path = Directly Connected VA - VF: Shortest Path = Directly Connected VA - VG: Shortest Path = Directly Connected Problem2: n = 7 Pmatrix: 6 0 6 4 5 5 3 VB - VA: Shortest Path = Directly Connected VB - VC: Shortest Path = Directly Connected VB - VD: Shortest Path = Directly Connected VB - VE: Shortest Path = Directly Connected VB - VF: Shortest Path = Directly Connected VB - VG: Shortest Path = Directly Connected Problem3: n = 7 Pmatrix: 5 6 0 3 1 4 6 VC - VA: Shortest Path = Directly Connected VC - VB: Shortest Path = Directly Connected VC - VD: Shortest Path = Directly Connected VC - VE: Shortest Path = Directly Connected VC - VF: Shortest Path = Directly Connected VC - VG: Shortest Path = Directly Connected Problem4: n = 7 Pmatrix: 4 4 3 0 4 1 4 VD - VA: Shortest Path = Directly Connected VD - VB: Shortest Path = Directly Connected VD - VC: Shortest Path = Directly Connected VD - VE: Shortest Path = Directly Connected VD - VF: Shortest Path = Directly Connected VD - VG: Shortest Path = Directly Connected Problem5: n = 7 Pmatrix: 6 5 1 4 0 5 5 VE - VA: Shortest Path = Directly Connected VE - VB: Shortest Path = Directly Connected VE - VC: Shortest Path = Directly Connected VE - VD: Shortest Path = Directly Connected VE - VF: Shortest Path = Directly Connected VE - VG: Shortest Path = Directly Connected Problem6: n = 7 Pmatrix: 3 5 4 1 5 0 3 VF - VA: Shortest Path = Directly Connected VF - VB: Shortest Path = Directly Connected VF - VC: Shortest Path = Directly Connected VF - VD: Shortest Path = Directly Connected VF - VE: Shortest Path = Directly Connected VF - VG: Shortest Path = Directly Connected Problem7: n = 7 Pmatrix: 6 3 6 4 5 3 0 VG - VA: Shortest Path = Directly Connected VG - VB: Shortest Path = Directly Connected VG - VC: Shortest Path = Directly Connected VG - VD: Shortest Path = Directly Connected VG - VE: Shortest Path = Directly Connected VG - VF: Shortest Path = Directly Connected Problem1: n = 6 Pmatrix: 0 1 2 1 3 4 VA - VB: Shortest Path = Directly Connected VA - VC: Shortest Path = Directly Connected VA - VD: Shortest Path = Directly Connected VA - VE: Shortest Path = Directly Connected VA - VF: Shortest Path = Directly Connected Problem2: n = 6 Pmatrix: 1 0 3 2 2 3 VB - VA: Shortest Path = Directly Connected VB - VC: Shortest Path = Directly Connected VB - VD: Shortest Path = Directly Connected VB - VE: Shortest Path = Directly Connected VB - VF: Shortest Path = Directly Connected Problem3: n = 6 Pmatrix: 2 3 0 3 3 6 VC - VA: Shortest Path = Directly Connected VC - VB: Shortest Path = Directly Connected VC - VD: Shortest Path = Directly Connected VC - VE: Shortest Path = Directly Connected VC - VF: Shortest Path = Directly Connected Problem4: n = 6 Pmatrix: 1 2 3 0 3 5 VD - VA: Shortest Path = Directly Connected VD - VB: Shortest Path = Directly Connected VD - VC: Shortest Path = Directly Connected VD - VE: Shortest Path = Directly Connected VD - VF: Shortest Path = Directly Connected Problem5: n = 6 Pmatrix: 3 2 3 3 0 5 VE - VA: Shortest Path = Directly Connected VE - VB: Shortest Path = Directly Connected VE - VC: Shortest Path = Directly Connected VE - VD: Shortest Path = Directly Connected VE - VF: Shortest Path = Directly Connected Problem6: n = 6 Pmatrix: 4 3 6 5 5 0 VF - VA: Shortest Path = Directly Connected VF - VB: Shortest Path = Directly Connected VF - VC: Shortest Path = Directly Connected VF - VD: Shortest Path = Directly Connected VF - VE: Shortest Path = Directly Connected but the expected output is Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: Make necessary changes to the code to get the expected output
5435fd6188d33acdf8ac4e0166442638
{ "intermediate": 0.33483585715293884, "beginner": 0.5323074460029602, "expert": 0.13285668194293976 }
46,131
Hi I've cuda toolkit 11.8 and pytorch and I would know how to configure batch size with cuda. Can you explain simply how
808e573dc2368cc7146b9ee022b7626d
{ "intermediate": 0.5672972798347473, "beginner": 0.1422276645898819, "expert": 0.2904750108718872 }
46,132
I am making a c++ sdl bsed game engine, and I need help to write the doxygen documentation and implementation of SDL_RENDER_TARGETS_RESET, as an example I will write another class so you can use as reference, also try to explain in deep the needs of this event in the doxygen: #include "events/Event.h" /** @class QuitEvent * * @brief Represents an application quit request. * * This event is dispatched when the application is being closed. * * @sa Event */ class QuitEvent : public Event { public: explicit QuitEvent(); ~QuitEvent() override = default; }; #endif // QUITEVENT_H /** @brief Constructs an QuitEvent that represents an application quit request. */ QuitEvent::QuitEvent() { priority = 255; }
45bad39214abcc2fd0ba43858cf8f356
{ "intermediate": 0.405457466840744, "beginner": 0.4545576572418213, "expert": 0.1399848312139511 }
46,133
binary classification using attention 768 -> 0/1
b7d2363a0c9bdf0fe207b5fe9ebc3a3d
{ "intermediate": 0.22685040533542633, "beginner": 0.16745172441005707, "expert": 0.6056978702545166 }
46,134
import numpy as np import tensorflow as tf import pandas as pd #x = np.arange(0,np.pi*200 ,np.pi/8) #x = np.arange(0,np.pi*200 ,np.pi/8) x_1 = np.arange(1600) y_1 = 2*np.sin(0.1*x_1+2) import numpy as np # Создание последовательности временных шагов и соответствующих значений def create_sequence_data(x, y, n_steps): X, Y = [], [] for i in range(len(x)-n_steps): X.append(y[i:i+n_steps]) Y.append(y[i+n_steps]) return np.array(X), np.array(Y) n_steps = 100 x_train, y_train = create_sequence_data(x_1[:int(len(x)*0.7)], y_1[:int(len(x)*0.7)], n_steps) x_val, y_val = create_sequence_data(x_1[int(len(x)*0.7):], y_1[int(len(x)*0.7):], n_steps) x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], 1) x_val = x_val.reshape(x_val.shape[0], n_steps, 1) import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Embedding,SimpleRNN # Создание модели LSTM model = Sequential() model.add(LSTM(50, input_shape=(n_steps, 1))) model.add(Dense(1)) model.compile(optimizer='adam', loss='mse') # Обучение модели model.fit(x_train, y_train, epochs=50, batch_size=5, validation_data=(x_val, y_val)) 1317 1318 if self._inferred_steps == 0: -> 1319 raise ValueError("Expected input data to be non-empty.") 1320 1321 def _configure_dataset_and_inferred_steps( ValueError: Expected input data to be non-empty.
4b7ad19f43792ca01adac9227a8aa2a9
{ "intermediate": 0.43310219049453735, "beginner": 0.15692266821861267, "expert": 0.4099751114845276 }
46,135
Привет! мне нужно сделать несколько нововведений в боте. 1) После того, как пользователь закончил отвечать на вопросы, ему должно писать "Вот ваши ответы:\n\n {Пронумерованные вопросы} - {ответы}". С этим сообщением должны идти 3 инлайн-кнопки: "Сгенерировать", "Изменить ответ", "Заполнить заново". Давай сейчас реализуем кнопки "Изменить ответ" - она должна работать так же, как и "Изменить ответ" в личном кабинете пользователя, и кнопку "Заполнить заново", которая тоже работает также, как и в личном кабинете пользователя. from aiogram import Bot, Dispatcher, executor, types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup from aiogram.utils.callback_data import CallbackData import aiosqlite import asyncio import requests API_TOKEN = '6306133720:AAH0dO6nwIlnQ7Hbts6RfGs0eI73EKwx-hE' ADMINS = [989037374, 123456789] bot = Bot(token=API_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) class Form(StatesGroup): choosing_action = State() answer_question = State() class lk(StatesGroup): personal_account = State() edit_answer = State() new_answer = State() class admin(StatesGroup): admin_panel = State() select_question_to_delete = State() select_question_to_edit = State() edit_question_text = State() new_question = State() async def create_db(): async with aiosqlite.connect('base.db') as db: await db.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT NOT NULL, last_question_idx INTEGER DEFAULT 0)''') await db.execute('''CREATE TABLE IF NOT EXISTS questions ( id INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT NOT NULL, order_num INTEGER NOT NULL)''') await db.execute('''CREATE TABLE IF NOT EXISTS answers ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, question TEXT, answer TEXT, FOREIGN KEY (user_id) REFERENCES users (id))''') await db.commit() # Обработка под MarkdownV2 def mdv2(text: str) -> str: escape_chars = [ "_", "*", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!" ] for char in escape_chars: text = text.replace(char, f"\{char}") text = text.replace('"', '“') return text # КНОПКА МЕНЮ menu = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) menu.add(KeyboardButton("В меню")) async def add_user(user_id: int, username: str): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT id FROM users WHERE id = ?', (user_id,)) user_exists = await cursor.fetchone() if user_exists: await db.execute('UPDATE users SET username = ? WHERE id = ?', (username, user_id)) else: await db.execute('INSERT INTO users (id, username) VALUES (?, ?)', (user_id, username)) await db.commit() @dp.message_handler(commands="start", state="*") async def cmd_start(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) user_id = message.from_user.id username = message.from_user.username or "unknown" await add_user(user_id, username) if user_id not in ADMINS: await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() @dp.message_handler(lambda message: message.text == "В меню", state="*") async def back_to_menu(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) if message.from_user.id not in ADMINS: await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() async def save_answer(user_id: int, question: str, answer: str, question_idx: int): async with aiosqlite.connect('base.db') as db: await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question, answer)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (question_idx, user_id)) await db.commit() async def set_next_question(user_id: int): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() last_question_idx = result[0] if result else 0 next_question_idx = last_question_idx + 1 question_cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (next_question_idx,)) question_text = await question_cursor.fetchone() if question_text: await bot.send_message(user_id, question_text[0], reply_markup=menu) await Form.answer_question.set() await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (next_question_idx, user_id)) await db.commit() else: await dp.current_state(user=user_id).reset_state(with_data=False) await bot.send_message(user_id, "Вы ответили на все вопросы. Ответы сохранены.", reply_markup=menu) @dp.message_handler(lambda message: message.text == "Сгенерировать био", state=Form.choosing_action) async def generate_bio(message: types.Message): user_id = message.from_user.id await set_next_question(user_id) @dp.message_handler(state=Form.answer_question) async def process_question_answer(message: types.Message, state: FSMContext): user_id = message.from_user.id answer_text = mdv2(message.text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() current_question_idx = result[0] if result else 0 cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (current_question_idx,)) question = await cursor.fetchone() if question: question_text = question[0] await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question_text, answer_text)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (current_question_idx, user_id)) await db.commit() else: await message.answer("Произошла ошибка при сохранении вашего ответа.") await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Личный кабинет", state=Form.choosing_action) async def personal_account(message: types.Message): user_id = message.from_user.id answers_text = "Личный кабинет\n\nВаши ответы:\n" async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question, answer FROM answers WHERE user_id=? ORDER BY id', (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question}: {answer}\n" if answers_text == "Личный кабинет\n\nВаши ответы:\n": answers_text = "Личный кабинет\n\nВы еще не отвечали на вопросы. Пожалуйста, нажмите «В меню» и выберите «Сгенерировать био», чтобы ответить на вопросы" await message.answer(answers_text, reply_markup=menu) else: markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) await message.answer(answers_text, reply_markup=markup) await lk.personal_account.set() @dp.message_handler(lambda message: message.text == "Изменить ответ", state=lk.personal_account) async def change_answer(message: types.Message): await message.answer("Введите номер вопроса, на который хотите изменить ответ:",reply_markup=menu) await lk.edit_answer.set() @dp.message_handler(state=lk.edit_answer) async def process_question_number(message: types.Message, state: FSMContext): text = message.text question_number = int(text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await state.update_data(question=question_text[0], question_number=question_number) await message.answer("Введите новый ответ:") await lk.new_answer.set() else: await message.answer(f"Вопроса под номером {question_number} не существует.") @dp.message_handler(state=lk.new_answer) async def process_new_answer(message: types.Message, state: FSMContext): user_data = await state.get_data() question_number = user_data['question_number'] new_answer = message.text user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer}") else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() @dp.message_handler(lambda message: message.text == "Заполнить заново", state=lk.personal_account) async def refill_form(message: types.Message): markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да", callback_data="confirm_refill")) await message.answer("Вы уверены, что хотите начать заново? Все текущие ответы будут удалены.", reply_markup=markup) @dp.callback_query_handler(lambda c: c.data == 'confirm_refill', state=lk.personal_account) async def process_refill(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with aiosqlite.connect('base.db') as db: await db.execute('DELETE FROM answers WHERE user_id=?', (user_id,)) await db.commit() await db.execute('UPDATE users SET last_question_idx = 0 WHERE id = ?', (user_id,)) await db.commit() state = dp.current_state(user=user_id) await state.reset_state(with_data=False) await bot.answer_callback_query(callback_query.id) await cmd_start(callback_query.message) # ГЕНЕРАЦИЯ def generate(self, prompt, apikey, sa_id): url = 'https://llm.api.cloud.yandex.net/foundationModels/v1/completion' headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {apikey}' } data = { "modelUri": f"gpt://{sa_id}/yandexgpt-lite/latest", "completionOptions": { "stream": False, "temperature": 0.6, "maxTokens": "1000" }, "messages": [ { "role": "system", "text": "Отвечай как можно более кратко" }, { "role": "user", "text": prompt } ] } response = requests.post(url, json=data, headers=headers) return response.text # АДМИН-ПАНЕЛЬ # КНОПКА НАЗАД back = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False) back.add(KeyboardButton("Назад")) @dp.message_handler(lambda message: message.text == "Назад", state=[admin.new_question, admin.edit_question_text, admin.select_question_to_edit, admin.select_question_to_delete]) async def back_to_admin_panel(message: types.Message, state: FSMContext): await state.finish() await admin_panel(message) @dp.message_handler(lambda message: message.text == "Админ-панель", state=Form.choosing_action) async def admin_panel(message: types.Message): if message.from_user.id not in ADMINS: await message.answer("Доступ запрещен.") return markup = ReplyKeyboardMarkup(resize_keyboard=True) markup.add("Вопросы", "Добавить", "Удалить", "Редактировать","В меню") await message.answer("Админ-панель:", reply_markup=markup) await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Вопросы", state=admin.admin_panel) async def show_questions(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if questions: text = "\n".join([f"{idx + 1}. {question[0]}" for idx, question in enumerate(questions)]) else: text = "Вопросы отсутствуют." await message.answer(text) @dp.message_handler(lambda message: message.text == "Добавить", state=admin.admin_panel) async def add_question_start(message: types.Message): await message.answer("Введите текст нового вопроса:", reply_markup=back) await admin.new_question.set() @dp.message_handler(state=admin.new_question) async def add_question_process(message: types.Message, state: FSMContext): new_question = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT MAX(order_num) FROM questions") max_order_num = await cursor.fetchone() next_order_num = (max_order_num[0] or 0) + 1 await db.execute("INSERT INTO questions (question, order_num) VALUES (?, ?)", (new_question, next_order_num)) await db.commit() await message.answer("Вопрос успешно добавлен.") await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Редактировать", state=admin.admin_panel) async def select_question_to_edit_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для редактирования:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_edit.set() @dp.message_handler(state=admin.select_question_to_edit) async def edit_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with state.proxy() as data: data['question_id'] = qid await admin.edit_question_text.set() await message.answer("Введите новый текст вопроса:", reply_markup=back) @dp.message_handler(state=admin.edit_question_text) async def update_question(message: types.Message, state: FSMContext): new_text = message.text async with state.proxy() as data: qid = data['question_id'] async with aiosqlite.connect('base.db') as db: await db.execute("UPDATE questions SET question = ? WHERE id = ?", (new_text, qid)) await db.commit() await message.answer("Вопрос успешно отредактирован.") await admin.admin_panel.set() @dp.message_handler(lambda message: message.text == "Удалить", state=admin.admin_panel) async def select_question_to_delete_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для удаления:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text, reply_markup=back) await admin.select_question_to_delete.set() @dp.message_handler(state=admin.select_question_to_delete) async def delete_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:", reply_markup=back) return qid = int(qid_text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT order_num FROM questions WHERE id = ?", (qid,)) question = await cursor.fetchone() if not question: await message.answer(f"Вопрос под номером {qid} не найден. Пожалуйста, попробуйте другой номер.") return order_num_to_delete = question[0] await db.execute("DELETE FROM questions WHERE id = ?", (qid,)) await db.execute("UPDATE questions SET order_num = order_num - 1 WHERE order_num > ?", (order_num_to_delete,)) await db.commit() await message.answer("Вопрос успешно удален.") await admin.admin_panel.set() async def main(): await create_db() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) executor.start_polling(dp, skip_updates=True)
4d9ab8e1fa1f051e4701876cabd9a30e
{ "intermediate": 0.3482479155063629, "beginner": 0.49922195076942444, "expert": 0.15253007411956787 }
46,136
make me a python gui QR code creator
6165571744871884ef8e55ddaf83c509
{ "intermediate": 0.5063953399658203, "beginner": 0.24377112090587616, "expert": 0.24983350932598114 }
46,137
can u help me with my code Search for a query string (e.g. “entertaining”, “disgusting” or “main male character”) within the files zipped in ʻmaterials/aclimdb_dataset.zip” ○ The program should output the name of the file and how often the search term shows up in the file. ○ Order the files by the count of the searched term, starting from the file with the highest number of hits. import zipfile import os Task 01 def find_files(filename, search_path): result = [] for root, dirs, files in os.walk(search_path): if filename in files: result.append(os.path.join(root, filename)) return result ​ print(find_files("filename", "search_path")) [] def search_str(file_path, word): with open(file_path, 'rb') as file: content = file.read().decode('utf-8', 'ignore') if word in content: print('string exist in a file') else: print('string does not exist in a file') search_str('C:\\Users\\selin\\Documents\\Volltext\\aclimdb_dataset.zip', 'entertaining') ​ string does not exist in a file
7c9d5e29cea2d8ad121275e26d678290
{ "intermediate": 0.5269098281860352, "beginner": 0.2811712622642517, "expert": 0.19191887974739075 }
46,138
{r} # Calculating for one company as an example # You may loop this or apply a similar approach for all companies # Filter data for one company company_data <- subset(stock_market_data, ISIN == "Specific_ISIN_of_Company") # Linear regression model <- lm(Daily_Return_stock ~ Daily_Return_index, data=company_data) # Predicted (expected) returns company_data$Expected_Return <- predict(model, company_data) # View the head of the company data to see the expected returns head(company_data)....................Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 0 (non-NA) cases..................Can you please explain the error and correct it
b056e7bcd504f42bef6892d5fef78bd9
{ "intermediate": 0.2400224804878235, "beginner": 0.31931546330451965, "expert": 0.44066205620765686 }
46,139
Suppose I click the submit button on a form and the browser sends a post request. What would the content-type header be for the request sent?
20cb40e7704da9f0741f94a53db5ad4d
{ "intermediate": 0.4811169505119324, "beginner": 0.2091616988182068, "expert": 0.30972135066986084 }
46,140
i have a list of strings. count all the same strings and sort them in dict like string and count {"string1':83, 'string2':74,'string3':54}
d714b13f3970dbfe983f8c4947b27504
{ "intermediate": 0.4080621898174286, "beginner": 0.2297927886247635, "expert": 0.36214497685432434 }
46,141
explain malloc in c
d7c4d1d18c9744d691138d238cac290f
{ "intermediate": 0.4930398762226105, "beginner": 0.32584255933761597, "expert": 0.18111762404441833 }
46,143
Hi
d67759fe4900be536b4e72c9aa009d43
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
46,144
with arch linux, make all files non-executeable
908686e601ab6f929a782b3fd1226e35
{ "intermediate": 0.3535686731338501, "beginner": 0.19802093505859375, "expert": 0.44841039180755615 }
46,145
Hi
862dc5f9bcc960cb5e9ed29e6a0f980c
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
46,146
A car company wants to keep a list of all the cars that they have in stock. The company has created a ClassicCar class that stores important information about each of their cars. Initialize an ArrayList called garage that stores each ClassicCar that the company has in stock.public class ClassicCar { String name; String model; int cost; public ClassicCar(String name, String model, int cost) { this.name = name; this.model = model; this.cost = cost; } } import java.util.ArrayList; public class CarTracker { public static void main(String[] args) { //Initialize your ArrayList here: ArrayList<ClassicCar> garage = new ArrayList<>(); } }
83db475dddbb0e6fe5701c95c32a395c
{ "intermediate": 0.41533753275871277, "beginner": 0.3235398530960083, "expert": 0.2611226439476013 }
46,147
can you please put comments on the code: letters = 'abcdefghijklmnopqrstuvwxyz' num_letters = len(letters) def encrypt_decrypt(text, mode, key): result = '' if mode == 'd': key = -key for letter in text: letter = letter.lower() if not letter == ' ': index = letters.find(letter) if index == -1: result += letter else: new_index = index + key if new_index >= num_letters: new_index -= num_letters elif new_index <0: new_index += num_letters result += letters[new_index] return result print() print('*** CAESAR CIPHER PROGRAM ***') print() print('Do you want to encrypt or decrypt?') user_input = input('e/d: ').lower() print() if user_input == 'e': print('Encryption mode selected') print() key = int(input('Enter the key (1 through 26): ')) text = input('Enter the text to encrypt: ') ciphertext = encrypt_decrypt(text, user_input, key) print(f'CIPHERTEXT: {ciphertext}') elif user_input == 'd': print('Decryption mode selected') print() key = int(input('Enter the key (1 through 26): ')) text = input('Enter the text to decrypt: ') plaintext = encrypt_decrypt(text, user_input, key) print(f'PLAINTEXT: {plaintext}')
7a9ee87985cd6d053cf3494a4d6821e7
{ "intermediate": 0.33674558997154236, "beginner": 0.4609162211418152, "expert": 0.20233821868896484 }
46,148
Привет! В моем коде слишком много разбиения на функции, мне не нужно такое количество функций. мне надо чтобы функций было минимум, они были максимально гибки и универсальны, чтобы код легко расширялся. ну и насчет конфига бы подумать немного - привести к какому-то более общему виду, больше внутри закономерностей, больше настроек, что ли - вроде вложения штук в штуки, может быть, выравния и все такое. сам код - local IS_ACTIVE_KEY = "z" local IS_ACTIVE = false local SAMP = require "samp" local memory = require "memory" require "socket" local FONT_ARIAL = { Small = renderCreateFont("Arial", 6.5, 0), Medium = renderCreateFont("Arial", 8.125), Large = renderCreateFont("Arial", 16.25, 0) } local SPEEDOMETER_CONFIG = { Position = {X = 1200, Y = 730}, Width = 200, Height = 70, SpeedBar = { Offset = {X = 20, Y = 10}, Height = 25 }, SpeedTextOffset = {X = 0, Y = 48}, CurrentSpeedOffset = {X = 0, Y = 25}, LabelOffset = {X = 0, Y = 62}, Ticks = { Main = { Width = 20, Start = {X = 20, Y = 35}, End = {X = 180, Y = 40} }, Secondary = { Width = 10, Start = {X = 30, Y = 35}, End = {X = 180, Y = 38} } }, BorderWidth = 1.1, MaxSpeed = 160, SpeedWidth = 160 } local function initializeFonts() for name, font in pairs(FONT_ARIAL) do if not font then error("Failed to create font " .. name) end end end local function getCarSpeed(car) return getHandlingFromCarHandle(car, 0x6C) end local function getHandlingFromCarHandle(carHandle, offset) local carPointer = getCarPointer(carHandle) local handlingPointer = readMemory(carPointer + 0x384, 4, false) local value = memory.getfloat(handlingPointer + offset, false) return (value / 0.02) * 2 end local function drawBox(x, y, width, height, color) renderDrawBox(x, y, width, height, color) end local function drawLine(startX, startY, endX, endY, width, color) renderDrawLine(startX, startY, endX, endY, width, color) end local function drawText(font, text, x, y, color) local length, height = renderGetFontDrawTextSize(font, text, false) renderFontDrawText(font, text, x - length / 2, y - height / 2, color) end local function drawSpeedometerBackground() local position = SPEEDOMETER_CONFIG.Position drawBox(position.X, position.Y, SPEEDOMETER_CONFIG.Width, SPEEDOMETER_CONFIG.Height, 0xd9FFFFFF) end local function drawSpeedBar(speed) local position = SPEEDOMETER_CONFIG.Position local offset = SPEEDOMETER_CONFIG.SpeedBar.Offset local speedBarHeight = SPEEDOMETER_CONFIG.SpeedBar.Height local speedWidth = SPEEDOMETER_CONFIG.SpeedWidth local speedStart = speed.Value > SPEEDOMETER_CONFIG.MaxSpeed and SPEEDOMETER_CONFIG.MaxSpeed * math.floor(speed.Value / SPEEDOMETER_CONFIG.MaxSpeed) or 0 local barWidth = math.min((speedWidth / SPEEDOMETER_CONFIG.MaxSpeed) * (speed.Value - speedStart), speedWidth) drawBox(position.X + offset.X, position.Y + offset.Y, barWidth, speedBarHeight, 0x800000ff) end local function drawTicks(tickConfig) local position = SPEEDOMETER_CONFIG.Position local start = tickConfig.Start local endPos = tickConfig.End local width = tickConfig.Width for x = start.X, endPos.X, width do drawLine(position.X + x, position.Y + start.Y, position.X + x, position.Y + endPos.Y, 1, 0xff000000) end end local function drawSpeedLabels() local position = SPEEDOMETER_CONFIG.Position local offset = SPEEDOMETER_CONFIG.SpeedTextOffset local font = FONT_ARIAL.Small for speed = 0, SPEEDOMETER_CONFIG.MaxSpeed, SPEEDOMETER_CONFIG.Ticks.Main.Width do drawText(font, tostring(speed), position.X + speed + offset.X, position.Y + offset.Y, 0xff000000) end end local function drawCurrentSpeed(speed) local position = SPEEDOMETER_CONFIG.Position local offset = SPEEDOMETER_CONFIG.CurrentSpeedOffset local font = FONT_ARIAL.Large drawText(font, tostring(speed.Value), position.X + SPEEDOMETER_CONFIG.Width / 2, position.Y + offset.Y, 0xff000000) end local function drawSpeedLabel() local position = SPEEDOMETER_CONFIG.Position local offset = SPEEDOMETER_CONFIG.LabelOffset local font = FONT_ARIAL.Medium drawText(font, "Speed(MPH)", position.X + SPEEDOMETER_CONFIG.Width / 2, position.Y + offset.Y, 0xff000000) end local function drawBorders() local position = SPEEDOMETER_CONFIG.Position local offset = SPEEDOMETER_CONFIG.SpeedBar.Offset local speedBarHeight = SPEEDOMETER_CONFIG.SpeedBar.Height local speedWidth = SPEEDOMETER_CONFIG.SpeedWidth local borderWidth = SPEEDOMETER_CONFIG.BorderWidth drawLine( position.X + offset.X, position.Y + offset.Y, position.X + offset.X + speedWidth, position.Y + offset.Y, borderWidth, 0xff000000 ) drawLine( position.X + offset.X, position.Y + offset.Y + speedBarHeight, position.X + offset.X + speedWidth, position.Y + offset.Y + speedBarHeight, borderWidth, 0xff000000 ) drawLine( position.X + offset.X, position.Y + offset.Y, position.X + offset.X, position.Y + offset.Y + speedBarHeight, borderWidth, 0xff000000 ) drawLine( position.X + offset.X + speedWidth, position.Y + offset.Y, position.X + offset.X + speedWidth, position.Y + offset.Y + speedBarHeight, borderWidth, 0xff000000 ) end local function drawSpeedometer(speed) drawSpeedometerBackground() drawSpeedBar(speed) drawTicks(SPEEDOMETER_CONFIG.Ticks.Main) drawTicks(SPEEDOMETER_CONFIG.Ticks.Secondary) drawSpeedLabels() drawCurrentSpeed(speed) drawSpeedLabel() drawBorders() end local function main() repeat wait(0) until SAMP.isAvailable() SAMP.registerChatCommand( IS_ACTIVE_KEY, function(arg) IS_ACTIVE = not IS_ACTIVE end ) while true do wait(0) if SAMP.isCharInAnyCar(SAMP.playerPed()) then local car = SAMP.storeCarCharIsInNoSave(SAMP.playerPed()) local speed = {Value = math.floor(getCarSpeed(car) * 2)} if IS_ACTIVE then drawSpeedometer(speed) end end end end initializeFonts() main()
b06f50a40999a28616b2afe40e44423d
{ "intermediate": 0.33794960379600525, "beginner": 0.3533005118370056, "expert": 0.30874988436698914 }
46,149
Исправь ошибку df_stab_agg.loc[:, df_stab_agg.columns != ['mean_finance_opened_share', 'mean_navigation_opened_share']]
616f5f5f0c5547e2b03fe3055e0f1cb9
{ "intermediate": 0.3372873067855835, "beginner": 0.26478224992752075, "expert": 0.39793041348457336 }
46,150
local isActive = true local memory = require 'memory' require "socket" local Arial_8px = renderCreateFont('Arial', 6.5, 0) local Arial_20px = renderCreateFont('Arial', 16.25, 0) local Arial_10px = renderCreateFont('Arial', 8.125) -- Константы local SPEED_END = 160 -- максимальная скорость, отображаемая на спидометре local SPEED_WIDTH = 160 -- ширина полосы скорости local POS_X = 1200 -- позиция спидометра по X local POS_Y = 730 -- позиция спидометра по Y local MAIN_TICK_WIDTH = 20 -- local SECONDARY_TICK_WIDTH = 10 -- local BORDER_WIDTH = 1.1 -- local SPEEDOMETER_WIDTH = 200 -- local SPEEDOMETER_HEIGHT = 70 -- local SPEED_BAR_HEIGHT = 25 -- local SPEED_BAR_OFFSET_X = 20 -- local SPEED_BAR_OFFSET_Y = 10 -- local SPEED_TEXT_OFFSET_Y = 48 -- local CURRENT_SPEED_OFFSET_Y = 10 + SPEED_BAR_HEIGHT / 2 -- local LABEL_OFFSET_Y = 62 -- local MAIN_TICK_START_X = 20 -- local MAIN_TICK_END_X = 180 -- local MAIN_TICK_START_Y = 35 -- local MAIN_TICK_END_Y = 40 -- local SECONDARY_TICK_START_X = 30 -- local SECONDARY_TICK_END_X = 180 -- local SECONDARY_TICK_START_Y = 35 -- local SECONDARY_TICK_END_Y = 38 -- function main() repeat wait(0) until isSampAvailable() sampRegisterChatCommand("z", function(arg) isActive = not isActive end) while true do wait(0) if isCharInAnyCar(playerPed) then local car = storeCarCharIsInNoSave(playerPed) local speedUnits = math.floor(getCarSpeed(car) * 2) local speedStart = speedUnits > SPEED_END and SPEED_END * math.floor(speedUnits / SPEED_END) or 0 -- Отрисовка фона спидометра renderDrawBox(POS_X, POS_Y, SPEEDOMETER_WIDTH, SPEEDOMETER_HEIGHT, 0xd9FFFFFF) -- Отрисовка полосы скорости renderDrawBox(POS_X + SPEED_BAR_OFFSET_X, POS_Y + SPEED_BAR_OFFSET_Y, math.min((SPEED_WIDTH / SPEED_END) * (speedUnits - speedStart), SPEED_WIDTH), SPEED_BAR_HEIGHT, 0x800000ff) -- Отрисовка основных делений for x = MAIN_TICK_START_X, MAIN_TICK_END_X, MAIN_TICK_WIDTH do renderDrawLine(POS_X + x, POS_Y + MAIN_TICK_START_Y, POS_X + x, POS_Y + MAIN_TICK_END_Y, 1, 0xff000000) end -- Отрисовка промежуточных делений for x = SECONDARY_TICK_START_X, SECONDARY_TICK_END_X, MAIN_TICK_WIDTH do renderDrawLine(POS_X + x, POS_Y + SECONDARY_TICK_START_Y, POS_X + x, POS_Y + SECONDARY_TICK_END_Y, 1, 0xff000000) end -- Отрисовка чисел скорости for speed = 0, SPEED_END, MAIN_TICK_WIDTH do local length = renderGetFontDrawTextLength(Arial_8px, tostring(speed)) local height = renderGetFontDrawHeight(Arial_8px) renderFontDrawText(Arial_8px, tostring(speed), POS_X + speed + SPEED_BAR_OFFSET_X - (length / 2), POS_Y + SPEED_TEXT_OFFSET_Y - (height / 2), 0xff000000) end -- Отрисовка текущей скорости local length2 = renderGetFontDrawTextLength(Arial_20px, tostring(speedUnits)) local height2 = renderGetFontDrawHeight(Arial_20px) renderFontDrawText(Arial_20px, tostring(speedUnits), POS_X + SPEEDOMETER_WIDTH / 2 - (length2 / 2), POS_Y + CURRENT_SPEED_OFFSET_Y - (height2 / 2), 0xff000000) -- Отрисовка надписи "Speed(MPH)" local length3 = renderGetFontDrawTextLength(Arial_10px, 'Speed(MPH)') local height3 = renderGetFontDrawHeight(Arial_10px) renderFontDrawText(Arial_10px, 'Speed(MPH)', POS_X + SPEEDOMETER_WIDTH / 2 - (length3 / 2), POS_Y + LABEL_OFFSET_Y - (height3 / 2), 0xff000000) -- Отрисовка границ спидометра renderDrawLine(POS_X + SPEED_BAR_OFFSET_X, POS_Y + SPEED_BAR_OFFSET_Y, POS_X + SPEED_BAR_OFFSET_X + SPEED_WIDTH, POS_Y + SPEED_BAR_OFFSET_Y, BORDER_WIDTH, 0xff000000) renderDrawLine(POS_X + SPEED_BAR_OFFSET_X, POS_Y + SPEED_BAR_OFFSET_Y + SPEED_BAR_HEIGHT, POS_X + SPEED_BAR_OFFSET_X + SPEED_WIDTH, POS_Y + SPEED_BAR_OFFSET_Y + SPEED_BAR_HEIGHT, BORDER_WIDTH, 0xff000000) renderDrawLine(POS_X + SPEED_BAR_OFFSET_X, POS_Y + SPEED_BAR_OFFSET_Y, POS_X + SPEED_BAR_OFFSET_X, POS_Y + SPEED_BAR_OFFSET_Y + SPEED_BAR_HEIGHT, BORDER_WIDTH, 0xff000000) renderDrawLine(POS_X + SPEED_BAR_OFFSET_X + SPEED_WIDTH, POS_Y + SPEED_BAR_OFFSET_Y, POS_X + SPEED_BAR_OFFSET_X + SPEED_WIDTH, POS_Y + SPEED_BAR_OFFSET_Y + SPEED_BAR_HEIGHT, BORDER_WIDTH, 0xff000000) end end end function getHandlingFromCarHandle(carHandle, offset) CCar = getCarPointer(carHandle) -- указатель на структуру автомобиля CHandling = readMemory(CCar + 0x384, 4, false) -- указатель на структуру хендлинга автомобиля res = memory.getfloat(CHandling + offset, false) return (res/0.02)*2 end function getVehicleRPM(vehicle) local vehicleRPM = 0 if (vehicle) then if (isCarEngineOn(vehicle) == true) then if getCarCurrentGear(vehicle) > 0 then vehicleRPM = math.floor(((getCarSpeed(vehicle) / getCarCurrentGear(vehicle)) * 160) + 0.5) else vehicleRPM = math.floor((getCarSpeed(vehicle) * 160) + 0.5) end if (vehicleRPM < 650) then vehicleRPM = math.random(650, 750) -- Когда машина стоит, обороты будут колебаться от 650 до 750, их можно менять elseif (vehicleRPM >= 9000) then vehicleRPM = math.random(9000, 9900) -- Максимальное количество оборотов end else vehicleRPM = 0 end return tonumber(vehicleRPM) else return 0 end end function roundToTenths(num) return math.floor(num * 10 + 0.5) / 10 end окончательно убери из этого кода 'магические числа', измени использование переменных - а т.е. сделай названия более понятными, сгруппируй по таблицам значения
98b8cb04f1b298e8c54b47d42ea187d0
{ "intermediate": 0.40363603830337524, "beginner": 0.43561193346977234, "expert": 0.1607520580291748 }
46,151
1_ Translate the following legal text into colloquial Farsi 2_ Place the Persian and English text side by side in the table 3_ From the beginning to the end of the text, there should be an English sentence on the left side and a Persian sentence on the right side. 4- Using legal language for Persian translation .Lesson Thirty-Eight Word Study accessory/ǝk'sesǝri / a person who helps another in a crime or knows the details of it. He was charged with being an accessory to the murder. An accessory before the act is a person who helps the perpetrator before the crime committed. An accessory after the act is a person who helps a felon to escape from punishment. accomplice / a'kamplis / a person who associate with another person to commit a crime. The police arrested the killer and his two accomplices. An accomplice might be either a principal or an accessory. The jury convicts him and his accomplice of rape. arrange / ǝ'reind3 / to put in order; to make preparations; to plan. The Government sought the help of volunteer agencies to arrange for jobs and housing for young people. The court arranged a convenient time for hearing the case. Her marriage was arranged by her parents. associate/ǝ'sǝufieit / a partner or companion; a colleague. They are my closest business associates. He is consulting his associates in the bank. Both the principal and his associate were found guilty. evade/ I'veid/to escape from; to avoid meeting someone. The murderer has evaded capture for three years. We cannot evade the laws of God and nature. The seller has never evaded any of his obligations regarding the supply of the products.
fcb28f3628d56cf226db0231e61b90ef
{ "intermediate": 0.3072167634963989, "beginner": 0.3758353888988495, "expert": 0.3169478476047516 }
46,152
ul { margin: 0; padding: 0; } ul li { list-style-type: none; justify-content: center; } a { text-decoration: none; } nav { position: absolute; display: flex; justify-content: center; align-items: center; bottom: 150px; background-color: #000000; min-height: 64px; } nav li { float: left; width: 250px; } nav a { transition: .9s; display: block; color: white; background-color: b; line-height: 3em; font-weight: bold; font-size: 20px; t <nav> <ul> <!-- <form class="reg" action="#"> --> <!-- <input type="text" placeholder="Login" required> --> <!-- <input type="password" placeholder="Password" required> --> <!-- <input type="submit" value="Sign In"> --> <!--</form>--> <li><a href="gnome.html">Gnome</a></li> <li><a href="info.html">About</a></li> <li><a href="gallery.html">Gallery</a></li> <li><a href="contact.html">Contacts</a></li> </ul> </nav> Center the list
3526a9ddcf4d88356db640e31e153afb
{ "intermediate": 0.36876070499420166, "beginner": 0.3300211429595947, "expert": 0.30121806263923645 }
46,153
I am making a c++ sdl based game engine, just finished the EventManager and all the events I support. However, in another instance of you, you said that I should implement periodic Renderer health checks to check if my Renderer was lost, You said something that when the window get resized the renderer can or will get lost but if I mainly work with windowed window it is not a big problem there. I plan on support both fullscreen and windowed modes, should I add this feature of health checking the renderer? I don't want it to be too invasive like checking everytime but use the newly created event system to periodically check the offending events like maximizing or minimizing to check if the renderer was lost or not. Also recreating the entire renderer each time could lead to potential errors, something I don't want to deal with, do this recreation always produce errors?
288c761a9a92dd2e846442c6e18ed0e7
{ "intermediate": 0.6776803135871887, "beginner": 0.15663312375545502, "expert": 0.16568659245967865 }
46,154
Is this ChatGPT?
5c10bffbb2edc29aa3c46dc4539ffdfe
{ "intermediate": 0.35716012120246887, "beginner": 0.19295063614845276, "expert": 0.449889212846756 }
46,155
Could you make this part of the code menu look way better? // Define GUI window properties Microsoft.Xna.Framework.Rectangle guiWindowRect = new Microsoft.Xna.Framework.Rectangle((int)windowX, (int)windowY, (int)fixedWindowWidth, (int)fixedWindowHeight); int borderWidth = 4; Microsoft.Xna.Framework.Rectangle borderRect = new Microsoft.Xna.Framework.Rectangle(guiWindowRect.X - borderWidth, guiWindowRect.Y - borderWidth, guiWindowRect.Width + 2 * borderWidth, guiWindowRect.Height + 2 * borderWidth); Microsoft.Xna.Framework.Color borderColor = new Microsoft.Xna.Framework.Color(50, 50, 50); // Dark gray border color // Draw window border this.m_spriteBatch.Draw(this.pixelTexture, borderRect, borderColor); // Draw window background Microsoft.Xna.Framework.Color windowBackgroundColor = new Microsoft.Xna.Framework.Color(20, 20, 20); // Dark background color this.m_spriteBatch.Draw(this.pixelTexture, guiWindowRect, windowBackgroundColor); // Draw GUI elements string guiMessage = "MadeByHowque || Mouse2 to drag!"; Vector2 guiMessageSize = Constants.FontSimple.MeasureString(guiMessage); Vector2 guiMessagePosition = new Vector2((float)(guiWindowRect.X + 20), (float)(guiWindowRect.Y + 20)); this.m_spriteBatch.DrawString(Constants.FontSimple, guiMessage, guiMessagePosition, Microsoft.Xna.Framework.Color.White); // White text color // Draw checkboxes string[] checkboxTexts = { "SpeedHack", "FlyHack", "AlwaysRechargeEnergy", "NoCooldowns", "InfiniteEnergy", "LadderDiveExploit", "FakelagExploit", "EletricBulletHit", "Test2", "Test3" }; float leftOffset = 20f; Vector2 checkboxPosition = new Vector2((float)guiWindowRect.X + leftOffset, guiMessagePosition.Y + guiMessageSize.Y + 7f); float checkboxSpacing = 30f; for (int i = 0; i < checkboxTexts.Length; i++) { string checkboxText = checkboxTexts[i]; bool checkboxState = checkboxStates[i]; Microsoft.Xna.Framework.Color checkboxColor = checkboxState ? Microsoft.Xna.Framework.Color.Green : Microsoft.Xna.Framework.Color.Red; this.m_spriteBatch.Draw(this.pixelTexture, new Microsoft.Xna.Framework.Rectangle((int)checkboxPosition.X, (int)checkboxPosition.Y, 20, 20), checkboxColor); this.m_spriteBatch.DrawString(Constants.FontSimple, checkboxText, new Vector2(checkboxPosition.X + 30f, checkboxPosition.Y), Microsoft.Xna.Framework.Color.White); checkboxPosition.Y += checkboxSpacing; }
36139e44737a4828ebd06a7eb2e134c2
{ "intermediate": 0.5171547532081604, "beginner": 0.31451186537742615, "expert": 0.16833332180976868 }
46,156
in vtfedit, how can a new 'skin' be created, for sfm models?
9f346e49f375279a9535aa09f6382fb4
{ "intermediate": 0.15619336068630219, "beginner": 0.10631813108921051, "expert": 0.7374884486198425 }
46,157
for making a new skin for a model for sfm, how can a Vmt file be done?
706df8b109ae5220f94d0b9d2d6c0638
{ "intermediate": 0.2920149862766266, "beginner": 0.16460098326206207, "expert": 0.5433840155601501 }
46,158
<div class="footer"> <hr /> <p>© 2018-2024 KLMP Project</p> </div> .footer { width: 100%; color: #5b5b5b; text-align: center; padding: 20px 0; background-color: #131313; } он у меня просто статично стоит, в низу, и когда я добовляю контент он заходит на него а не опускает его ниже
91f25f5dd9d27bd2f45085a51d4c2252
{ "intermediate": 0.33617064356803894, "beginner": 0.29640182852745056, "expert": 0.36742764711380005 }
46,159
For sfm, in vtfedit, how can I make textures that glow in the dark?
30b403abf12a0cac9c3dd2289385173e
{ "intermediate": 0.4381644129753113, "beginner": 0.14727652072906494, "expert": 0.414559006690979 }
46,160
I am creating a c++ sdl based rpg game engine, and my goal is to be able to replicate a Final Fantasy with my engine. I was reading though AI scripts and saw a big script of Ozma super boss from Final Fantasy IX and got me curious, could this be implemented as a Lua script for example? Function Ozma_Init set phase1attacklist = [ Doomsday ; Flare ; Meteor ; Holy ; Flare Star ; Death ] set phase1attackmplist = [ 16 ; 47 ; 40 ; 36 ; 0 ; 26 ] set phase2attacklist = [ Curse ; LV4 Holy ; LV5 Death ; Curaga ; Esuna ; Mini ] set phase2attackmplist = [ 0 ; 22 ; 20 ; 20 ; 22 ; 8 ] Function Ozma_Loop if ( !InitFlag ) set InitFlag = 1 set SV_FunctionEnemy[ENABLE_SHADOW_FLAG] = 0 set SV_FunctionEnemy[CURRENT_ATB] = SV_FunctionEnemy[MAX_ATB] - 1 if ( ( SV_PlayerTeam & 1 ) && ( 1[LEVEL] % 4 == 0 ) ) set lv4characters | = 1 if ( ( SV_PlayerTeam & 2 ) && ( 2[LEVEL] % 4 == 0 ) ) set lv4characters | = 2 if ( ( SV_PlayerTeam & 4 ) && ( 4[LEVEL] % 4 == 0 ) ) set lv4characters | = 4 if ( ( SV_PlayerTeam & 8 ) && ( 8[LEVEL] % 4 == 0 ) ) set lv4characters | = 8 if ( ( SV_PlayerTeam & 1 ) && ( 1[LEVEL] % 5 == 0 ) ) set lv5characters | = 1 if ( ( SV_PlayerTeam & 2 ) && ( 2[LEVEL] % 5 == 0 ) ) set lv5characters | = 2 if ( ( SV_PlayerTeam & 4 ) && ( 4[LEVEL] % 5 == 0 ) ) set lv5characters | = 4 if ( ( SV_PlayerTeam & 8 ) && ( 8[LEVEL] % 5 == 0 ) ) set lv5characters | = 8 if ( FriendlyMonster_Complete ) set SV_FunctionEnemy[ABSORB_ELEMENTS] &= ~SHADOW set SV_FunctionEnemy[WEAK_ELEMENTS] | = SHADOW BattleDialog( "The spiritual power raised the attack range." ) Wait( 60 ) if ( ReplenishATBStep == 0 ) if ( GetAttacker == SV_FunctionEnemy ) set ReplenishATBStep = 1 elseif ( ReplenishATBStep == 1 ) if ( GetAttacker == SV_FunctionEnemy ) set ReplenishATBStep = 1 else set ReplenishATBStep = 2 set SV_FunctionEnemy[CURRENT_ATB] = SV_FunctionEnemy[MAX_ATB] - 1 elseif ( ReplenishATBStep == 2 ) if ( GetAttacker == SV_FunctionEnemy ) set ReplenishATBStep = 1 if ( SV_FunctionEnemy[HP] <= 10000 ) while ( IsAttacking != 0 ) Wait( 1 ) RunBattleCode( Disable ATB ) while ( GetBattleState != BATTLE_STATE_PAUSE ) Wait( 1 ) set SV_Target = SV_FunctionEnemy RunBattleCode( Run Camera, 9 ) AttackSpecial( Death ) set SV_FunctionEnemy[STAND_ANIMATION] = 1 while ( IsAttacking != 0 ) Wait( 1 ) set SV_FunctionEnemy[DEFEATED_ON] = 1 set Ozma_Defeated = TRUE RunBattleCode( End Battle, Victory ) return Wait( 1 ) loop Function Ozma_ATB set phaseswitch = ~phaseswitch & 1 if ( phaseswitch ) set phase1selectedattack = RandomAttack( phase1attacklist ) if ( phase1selectedattack == Doomsday ) set SV_Target = ( SV_PlayerTeam | SV_EnemyTeam ) elseif ( phase1selectedattack == Flare ) set SV_Target = RandomInTeam( WithoutMatching( SV_PlayerTeam[CURRENT_STATUS], PETRIFY | DEATH | KO | REFLECT) & WithoutMatching( SV_PlayerTeam[AUTO_STATUS], REFLECT) ) elseif ( phase1selectedattack == Meteor ) set SV_Target = SV_PlayerTeam elseif ( phase1selectedattack == Holy ) ...
a91b7699e2aaafa1726051eeb7877730
{ "intermediate": 0.3226507306098938, "beginner": 0.4437501132488251, "expert": 0.23359915614128113 }
46,161
import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class floyd { private static int[][] adjMatrix; private static int[][] pMatrix; private static final String OUTPUT_FILE = "output.txt"; private static ArrayList<Integer> path = new ArrayList<>(); public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: java Floyd <graph-file>"); return; } try (Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0])))) { createFile(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("Problem")) { // Extract number of vertices from the line int n = Integer.parseInt(line.split("n = ")[1].trim()); if (n < 5 || n > 10) { throw new IllegalArgumentException("Invalid number of vertices."); } // Read and initialize the adjacency matrix for the current problem initializeMatrices(n, scanner); // Compute shortest paths and print results calculateShortestPaths(); printResult(n); } } } } private static void createFile() throws FileNotFoundException { PrintWriter writer = new PrintWriter(OUTPUT_FILE); writer.close(); } private static void initializeMatrices(int n, Scanner scanner) { adjMatrix = new int[n][n]; pMatrix = new int[n][n]; for (int i = 0; i < n; ++i) { if (!scanner.hasNextLine()) { throw new IllegalStateException("Expected adjacency matrix row is missing."); } String[] values = scanner.nextLine().trim().split("\s+"); for (int j = 0; j < n; ++j) { int weight = Integer.parseInt(values[j]); adjMatrix[i][j] = weight; if (weight < 0 || weight > 10) { throw new IllegalArgumentException("Edge weight must be between 0 and 10."); } if (i == j) { adjMatrix[i][j] = 0; } else if (weight != 0) { pMatrix[i][j] = j; } } } } private static void calculateShortestPaths() { int n = adjMatrix.length; for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (adjMatrix[i][k] + adjMatrix[k][j] < adjMatrix[i][j]) { adjMatrix[i][j] = adjMatrix[i][k] + adjMatrix[k][j]; pMatrix[i][j] = pMatrix[i][k]; } } } } } private static void printResult(int n) throws FileNotFoundException { StringBuilder builder = new StringBuilder(); for (int i = 0; i < n; ++i) { clearPathList(); builder.setLength(0); builder.append("Problem") .append(i + 1) .append(": n = ") .append(n) .append('\n') .append("Pmatrix:\n"); for (int j = 0; j < n; ++j) { builder.append(formatElement(adjMatrix[i][j])); if (j != n - 1) { builder.append(' '); } } builder.append('\n'); appendToFile(builder.toString()); builder.setLength(0); for (int j = 0; j < n; ++j) { if (i == j) continue; buildPath(i, j); builder .append("V") .append((char) ('A' + i)) .append(" - V") .append((char) ('A' + j)) .append(": Shortest Path = "); if (isDirectlyConnected(i, j)) { builder.append("Directly Connected"); } else { builder .append("[") .append(getShortestPathAsString(i, j)) .append("]; Length = ") .append(adjMatrix[i][j]) .append('\n'); } appendToFile(builder.toString()); builder.setLength(0); } builder.append('\n').append('\n'); appendToFile(builder.toString()); } } private static boolean isDirectlyConnected(int from, int to) { return pMatrix[from][to] == to && adjMatrix[from][to] > 0; } private static String getShortestPathAsString(int source, int destination) { if (adjMatrix[source][destination] == Integer.MAX_VALUE) { return "No path"; } StringBuilder pathBuilder = new StringBuilder(); pathBuilder.append("V").append((char) ('1' + source)); int inter = source; while (inter != destination) { inter = pMatrix[inter][destination]; pathBuilder.append(" V").append((char) ('1' + inter)); } return pathBuilder.toString(); } private static void buildPath(int current, int destination) { path.clear(); if (current != destination) { path.add(current); while (pMatrix[current][destination] != destination) { current = pMatrix[current][destination]; path.add(current); } path.add(destination); } } private static void clearPathList() { path.clear(); } private static String formatElement(int element) { return "%2d ".formatted(element); } private static void appendToFile(String string) throws FileNotFoundException { File outputFile = new File(OUTPUT_FILE); try (FileWriter fw = new FileWriter(outputFile, true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println(string); } catch (IOException ex) { ex.printStackTrace(); } } } The program is giving output as Problem1: n = 7 Pmatrix: 0 6 5 4 6 3 6 VA - VB: Shortest Path = Directly Connected VA - VC: Shortest Path = Directly Connected VA - VD: Shortest Path = Directly Connected VA - VE: Shortest Path = Directly Connected VA - VF: Shortest Path = Directly Connected VA - VG: Shortest Path = Directly Connected Problem2: n = 7 Pmatrix: 6 0 6 4 5 5 3 VB - VA: Shortest Path = Directly Connected VB - VC: Shortest Path = Directly Connected VB - VD: Shortest Path = Directly Connected VB - VE: Shortest Path = Directly Connected VB - VF: Shortest Path = Directly Connected VB - VG: Shortest Path = Directly Connected Problem3: n = 7 Pmatrix: 5 6 0 3 1 4 6 VC - VA: Shortest Path = Directly Connected VC - VB: Shortest Path = Directly Connected VC - VD: Shortest Path = Directly Connected VC - VE: Shortest Path = Directly Connected VC - VF: Shortest Path = Directly Connected VC - VG: Shortest Path = Directly Connected Problem4: n = 7 Pmatrix: 4 4 3 0 4 1 4 VD - VA: Shortest Path = Directly Connected VD - VB: Shortest Path = Directly Connected VD - VC: Shortest Path = Directly Connected VD - VE: Shortest Path = Directly Connected VD - VF: Shortest Path = Directly Connected VD - VG: Shortest Path = Directly Connected Problem5: n = 7 Pmatrix: 6 5 1 4 0 5 5 VE - VA: Shortest Path = Directly Connected VE - VB: Shortest Path = Directly Connected VE - VC: Shortest Path = Directly Connected VE - VD: Shortest Path = Directly Connected VE - VF: Shortest Path = Directly Connected VE - VG: Shortest Path = Directly Connected Problem6: n = 7 Pmatrix: 3 5 4 1 5 0 3 VF - VA: Shortest Path = Directly Connected VF - VB: Shortest Path = Directly Connected VF - VC: Shortest Path = Directly Connected VF - VD: Shortest Path = Directly Connected VF - VE: Shortest Path = Directly Connected VF - VG: Shortest Path = Directly Connected Problem7: n = 7 Pmatrix: 6 3 6 4 5 3 0 VG - VA: Shortest Path = Directly Connected VG - VB: Shortest Path = Directly Connected VG - VC: Shortest Path = Directly Connected VG - VD: Shortest Path = Directly Connected VG - VE: Shortest Path = Directly Connected VG - VF: Shortest Path = Directly Connected Problem1: n = 6 Pmatrix: 0 1 2 1 3 4 VA - VB: Shortest Path = Directly Connected VA - VC: Shortest Path = Directly Connected VA - VD: Shortest Path = Directly Connected VA - VE: Shortest Path = Directly Connected VA - VF: Shortest Path = Directly Connected Problem2: n = 6 Pmatrix: 1 0 3 2 2 3 VB - VA: Shortest Path = Directly Connected VB - VC: Shortest Path = Directly Connected VB - VD: Shortest Path = Directly Connected VB - VE: Shortest Path = Directly Connected VB - VF: Shortest Path = Directly Connected Problem3: n = 6 Pmatrix: 2 3 0 3 3 6 VC - VA: Shortest Path = Directly Connected VC - VB: Shortest Path = Directly Connected VC - VD: Shortest Path = Directly Connected VC - VE: Shortest Path = Directly Connected VC - VF: Shortest Path = Directly Connected Problem4: n = 6 Pmatrix: 1 2 3 0 3 5 VD - VA: Shortest Path = Directly Connected VD - VB: Shortest Path = Directly Connected VD - VC: Shortest Path = Directly Connected VD - VE: Shortest Path = Directly Connected VD - VF: Shortest Path = Directly Connected Problem5: n = 6 Pmatrix: 3 2 3 3 0 5 VE - VA: Shortest Path = Directly Connected VE - VB: Shortest Path = Directly Connected VE - VC: Shortest Path = Directly Connected VE - VD: Shortest Path = Directly Connected VE - VF: Shortest Path = Directly Connected Problem6: n = 6 Pmatrix: 4 3 6 5 5 0 VF - VA: Shortest Path = Directly Connected VF - VB: Shortest Path = Directly Connected VF - VC: Shortest Path = Directly Connected VF - VD: Shortest Path = Directly Connected VF - VE: Shortest Path = Directly Connected which is incorrect. The expected output is Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: 0 Understand the format of the expected output and make necessary changes to the code to get the expected ouptut.
2082839045e6d0ac73bccaabce83d54d
{ "intermediate": 0.33483585715293884, "beginner": 0.5323074460029602, "expert": 0.13285668194293976 }
46,162
for sfm, how can I create a glowing texture that I can use a slider to control the intensity of?
7106c14f16256c1f552ff0bdc513402e
{ "intermediate": 0.44570645689964294, "beginner": 0.19032491743564606, "expert": 0.3639686405658722 }
46,163
how to make a chat gpt app with streaming python and js
12d102c685d00274321a4e6ea9f2da66
{ "intermediate": 0.3956655263900757, "beginner": 0.3242834806442261, "expert": 0.28005099296569824 }
46,164
import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class floyd { private static int[][] adjMatrix; private static int[][] pMatrix; private static final String OUTPUT_FILE = "output.txt"; private static ArrayList<Integer> path = new ArrayList<>(); public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: java Floyd <graph-file>"); return; } try (Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0])))) { createFile(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("Problem")) { // Extract number of vertices from the line int n = Integer.parseInt(line.split("n = ")[1].trim()); if (n < 5 || n > 10) { throw new IllegalArgumentException("Invalid number of vertices."); } // Read and initialize the adjacency matrix for the current problem initializeMatrices(n, scanner); // Compute shortest paths and print results calculateShortestPaths(); printResult(n); } } } } private static void createFile() throws FileNotFoundException { PrintWriter writer = new PrintWriter(OUTPUT_FILE); writer.close(); } private static void initializeMatrices(int n, Scanner scanner) { adjMatrix = new int[n][n]; pMatrix = new int[n][n]; for (int i = 0; i < n; ++i) { if (!scanner.hasNextLine()) { throw new IllegalStateException("Expected adjacency matrix row is missing."); } String[] values = scanner.nextLine().trim().split("\s+"); for (int j = 0; j < n; ++j) { int weight = Integer.parseInt(values[j]); adjMatrix[i][j] = weight; if (weight < 0 || weight > 10) { throw new IllegalArgumentException("Edge weight must be between 0 and 10."); } if (i == j) { adjMatrix[i][j] = 0; } else if (weight != 0) { pMatrix[i][j] = j; } } } } private static void calculateShortestPaths() { int n = adjMatrix.length; for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (adjMatrix[i][k] + adjMatrix[k][j] < adjMatrix[i][j]) { adjMatrix[i][j] = adjMatrix[i][k] + adjMatrix[k][j]; pMatrix[i][j] = pMatrix[i][k]; } } } } } private static String getFullPathAsString(int source, int dest) { if (adjMatrix[source][dest] == Integer.MAX_VALUE) return "No path"; StringBuilder pathBuilder = new StringBuilder("V" + (source + 1)); while (source != dest) { source = pMatrix[source][dest]; pathBuilder.append(" V").append(source + 1); } return pathBuilder.toString(); } private static void printResult(int n) throws FileNotFoundException { StringBuilder builder = new StringBuilder(); for (int source = 0; source < n; ++source) { builder.append("Problem").append(source + 1).append(": n = ").append(n).append('\n'); builder.append("Pmatrix:\n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { builder.append(formatElement(pMatrix[i][j])).append(" "); } builder.append("\n"); } builder.append("\n"); for (int dest = 0; dest < n; ++dest) { if (source != dest) { // Skip self to self paths builder.append("V").append(source + 1).append("-V").append(dest + 1).append(": shortest path and length\n"); String pathStr = getFullPathAsString(source, dest); builder.append(pathStr) .append(": ") .append(adjMatrix[source][dest]) .append("\n"); } } builder.append("\n\n"); // Separate problems visually appendToFile(builder.toString()); builder.setLength(0); // Reset builder for next problem } } private static boolean isDirectlyConnected(int from, int to) { return pMatrix[from][to] == to && adjMatrix[from][to] > 0; } private static String getShortestPathAsString(int source, int destination) { if (adjMatrix[source][destination] == Integer.MAX_VALUE) { return "No path"; } int intermediate = pMatrix[source][destination]; StringBuilder pathBuilder = new StringBuilder(); pathBuilder.append("V").append(source + 1); while (source != destination) { pathBuilder.append(" V").append(intermediate + 1); source = intermediate; intermediate = pMatrix[source][destination]; } return pathBuilder.toString(); } private static void buildPath(int current, int destination) { path.clear(); if (current != destination) { path.add(current); while (pMatrix[current][destination] != destination) { current = pMatrix[current][destination]; path.add(current); } path.add(destination); } } private static void clearPathList() { path.clear(); } private static String formatElement(int element) { return "%2d ".formatted(element); } private static void appendToFile(String string) throws FileNotFoundException { try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(OUTPUT_FILE, true)))) { out.println(string); } catch (IOException ex) { System.err.println("An error occurred while writing to the file: " + ex.getMessage()); } } } The program is giving output as Problem1: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V1-V2: shortest path and length V1 V2: 6 V1-V3: shortest path and length V1 V3: 5 V1-V4: shortest path and length V1 V4: 4 V1-V5: shortest path and length V1 V5: 6 V1-V6: shortest path and length V1 V6: 3 V1-V7: shortest path and length V1 V7: 6 Problem2: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V2-V1: shortest path and length V2 V1: 6 V2-V3: shortest path and length V2 V3: 6 V2-V4: shortest path and length V2 V4: 4 V2-V5: shortest path and length V2 V5: 5 V2-V6: shortest path and length V2 V6: 5 V2-V7: shortest path and length V2 V7: 3 Problem3: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V3-V1: shortest path and length V3 V1: 5 V3-V2: shortest path and length V3 V2: 6 V3-V4: shortest path and length V3 V4: 3 V3-V5: shortest path and length V3 V5: 1 V3-V6: shortest path and length V3 V6: 4 V3-V7: shortest path and length V3 V7: 6 Problem4: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V4-V1: shortest path and length V4 V1: 4 V4-V2: shortest path and length V4 V2: 4 V4-V3: shortest path and length V4 V3: 3 V4-V5: shortest path and length V4 V5: 4 V4-V6: shortest path and length V4 V6: 1 V4-V7: shortest path and length V4 V7: 4 Problem5: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V5-V1: shortest path and length V5 V1: 6 V5-V2: shortest path and length V5 V2: 5 V5-V3: shortest path and length V5 V3: 1 V5-V4: shortest path and length V5 V4: 4 V5-V6: shortest path and length V5 V6: 5 V5-V7: shortest path and length V5 V7: 5 Problem6: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V6-V1: shortest path and length V6 V1: 3 V6-V2: shortest path and length V6 V2: 5 V6-V3: shortest path and length V6 V3: 4 V6-V4: shortest path and length V6 V4: 1 V6-V5: shortest path and length V6 V5: 5 V6-V7: shortest path and length V6 V7: 3 Problem7: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V7-V1: shortest path and length V7 V1: 6 V7-V2: shortest path and length V7 V2: 3 V7-V3: shortest path and length V7 V3: 6 V7-V4: shortest path and length V7 V4: 4 V7-V5: shortest path and length V7 V5: 5 V7-V6: shortest path and length V7 V6: 3 Problem1: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V1-V2: shortest path and length V1 V2: 1 V1-V3: shortest path and length V1 V3: 2 V1-V4: shortest path and length V1 V4: 1 V1-V5: shortest path and length V1 V5: 3 V1-V6: shortest path and length V1 V6: 4 Problem2: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V2-V1: shortest path and length V2 V1: 1 V2-V3: shortest path and length V2 V3: 3 V2-V4: shortest path and length V2 V4: 2 V2-V5: shortest path and length V2 V5: 2 V2-V6: shortest path and length V2 V6: 3 Problem3: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V3-V1: shortest path and length V3 V1: 2 V3-V2: shortest path and length V3 V2: 3 V3-V4: shortest path and length V3 V4: 3 V3-V5: shortest path and length V3 V5: 3 V3-V6: shortest path and length V3 V6: 6 Problem4: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V4-V1: shortest path and length V4 V1: 1 V4-V2: shortest path and length V4 V2: 2 V4-V3: shortest path and length V4 V3: 3 V4-V5: shortest path and length V4 V5: 3 V4-V6: shortest path and length V4 V6: 5 Problem5: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V5-V1: shortest path and length V5 V1: 3 V5-V2: shortest path and length V5 V2: 2 V5-V3: shortest path and length V5 V3: 3 V5-V4: shortest path and length V5 V4: 3 V5-V6: shortest path and length V5 V6: 5 Problem6: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V6-V1: shortest path and length V6 V1: 4 V6-V2: shortest path and length V6 V2: 3 V6-V3: shortest path and length V6 V3: 6 V6-V4: shortest path and length V6 V4: 5 V6-V5: shortest path and length V6 V5: 5 which is incorrect. The expected output is Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: 0 Understand the format of the expected output and make necessary changes to the program to achieve it. Output is the solution of problem 1 first, then problem 2, and etc. The solution of problem j(for eg. from V1 to all other cities should indicate as V1-Vj: shortest path and length first and then print the shortest path and distance to each city as shown in the expected output) should start with an integer n (the number cities) and the n x n Pointer Array P (in the next n rows). The shortest paths should then follow, one per line. Output the shortest paths from C1 to all other cities, then C2 to all other cities, and Cn to all other cities.
2319d43d794886f8770d9b77e8c77d8d
{ "intermediate": 0.33483585715293884, "beginner": 0.5323074460029602, "expert": 0.13285668194293976 }
46,165
Common ranger commands
633ee7c72392e3ebf5f0fde49882fa59
{ "intermediate": 0.25198179483413696, "beginner": 0.5394721627235413, "expert": 0.20854607224464417 }
46,166
import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class floyd { private static int[][] adjMatrix; private static int[][] pMatrix; private static final String OUTPUT_FILE = "output.txt"; private static ArrayList<Integer> path = new ArrayList<>(); public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: java Floyd <graph-file>"); return; } try (Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0])))) { createFile(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("Problem")) { // Extract number of vertices from the line int n = Integer.parseInt(line.split("n = ")[1].trim()); if (n < 5 || n > 10) { throw new IllegalArgumentException("Invalid number of vertices."); } // Read and initialize the adjacency matrix for the current problem initializeMatrices(n, scanner); // Compute shortest paths and print results calculateShortestPaths(); printResult(n); } } } } private static void createFile() throws FileNotFoundException { PrintWriter writer = new PrintWriter(OUTPUT_FILE); writer.close(); } private static void initializeMatrices(int n, Scanner scanner) { adjMatrix = new int[n][n]; pMatrix = new int[n][n]; for (int i = 0; i < n; ++i) { if (!scanner.hasNextLine()) { throw new IllegalStateException("Expected adjacency matrix row is missing."); } String[] values = scanner.nextLine().trim().split("\s+"); for (int j = 0; j < n; ++j) { int weight = Integer.parseInt(values[j]); adjMatrix[i][j] = weight; if (weight < 0 || weight > 10) { throw new IllegalArgumentException("Edge weight must be between 0 and 10."); } if (i == j) { adjMatrix[i][j] = 0; } else if (weight != 0) { pMatrix[i][j] = j; } } } } private static void calculateShortestPaths() { int n = adjMatrix.length; for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (adjMatrix[i][k] + adjMatrix[k][j] < adjMatrix[i][j]) { adjMatrix[i][j] = adjMatrix[i][k] + adjMatrix[k][j]; pMatrix[i][j] = pMatrix[i][k]; } } } } } private static String getFullPathAsString(int source, int dest) { if (adjMatrix[source][dest] == Integer.MAX_VALUE) return "No path"; StringBuilder pathBuilder = new StringBuilder("V" + (source + 1)); while (source != dest) { source = pMatrix[source][dest]; pathBuilder.append(" V").append(source + 1); } return pathBuilder.toString(); } private static void printResult(int n) throws FileNotFoundException { StringBuilder builder = new StringBuilder(); for (int source = 0; source < n; ++source) { builder.append("Problem").append(source + 1).append(": n = ").append(n).append('\n'); builder.append("Pmatrix:\n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { builder.append(formatElement(pMatrix[i][j])).append(" "); } builder.append("\n"); } builder.append("\n"); for (int dest = 0; dest < n; ++dest) { if (source != dest) { // Skip self to self paths builder.append("V").append(source + 1).append("-V").append(dest + 1).append(": shortest path and length\n"); String pathStr = getFullPathAsString(source, dest); builder.append(pathStr) .append(": ") .append(adjMatrix[source][dest]) .append("\n"); } } builder.append("\n\n"); // Separate problems visually appendToFile(builder.toString()); builder.setLength(0); // Reset builder for next problem } } private static boolean isDirectlyConnected(int from, int to) { return pMatrix[from][to] == to && adjMatrix[from][to] > 0; } private static String getShortestPathAsString(int source, int destination) { if (adjMatrix[source][destination] == Integer.MAX_VALUE) { return "No path"; } int intermediate = pMatrix[source][destination]; StringBuilder pathBuilder = new StringBuilder(); pathBuilder.append("V").append(source + 1); while (source != destination) { pathBuilder.append(" V").append(intermediate + 1); source = intermediate; intermediate = pMatrix[source][destination]; } return pathBuilder.toString(); } private static void buildPath(int current, int destination) { path.clear(); if (current != destination) { path.add(current); while (pMatrix[current][destination] != destination) { current = pMatrix[current][destination]; path.add(current); } path.add(destination); } } private static void clearPathList() { path.clear(); } private static String formatElement(int element) { return "%2d ".formatted(element); } private static void appendToFile(String string) throws FileNotFoundException { try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(OUTPUT_FILE, true)))) { out.println(string); } catch (IOException ex) { System.err.println("An error occurred while writing to the file: " + ex.getMessage()); } } } The program is giving output as Problem1: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V1-V2: shortest path and length V1 V2: 6 V1-V3: shortest path and length V1 V3: 5 V1-V4: shortest path and length V1 V4: 4 V1-V5: shortest path and length V1 V5: 6 V1-V6: shortest path and length V1 V6: 3 V1-V7: shortest path and length V1 V7: 6 Problem2: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V2-V1: shortest path and length V2 V1: 6 V2-V3: shortest path and length V2 V3: 6 V2-V4: shortest path and length V2 V4: 4 V2-V5: shortest path and length V2 V5: 5 V2-V6: shortest path and length V2 V6: 5 V2-V7: shortest path and length V2 V7: 3 Problem3: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V3-V1: shortest path and length V3 V1: 5 V3-V2: shortest path and length V3 V2: 6 V3-V4: shortest path and length V3 V4: 3 V3-V5: shortest path and length V3 V5: 1 V3-V6: shortest path and length V3 V6: 4 V3-V7: shortest path and length V3 V7: 6 Problem4: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V4-V1: shortest path and length V4 V1: 4 V4-V2: shortest path and length V4 V2: 4 V4-V3: shortest path and length V4 V3: 3 V4-V5: shortest path and length V4 V5: 4 V4-V6: shortest path and length V4 V6: 1 V4-V7: shortest path and length V4 V7: 4 Problem5: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V5-V1: shortest path and length V5 V1: 6 V5-V2: shortest path and length V5 V2: 5 V5-V3: shortest path and length V5 V3: 1 V5-V4: shortest path and length V5 V4: 4 V5-V6: shortest path and length V5 V6: 5 V5-V7: shortest path and length V5 V7: 5 Problem6: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V6-V1: shortest path and length V6 V1: 3 V6-V2: shortest path and length V6 V2: 5 V6-V3: shortest path and length V6 V3: 4 V6-V4: shortest path and length V6 V4: 1 V6-V5: shortest path and length V6 V5: 5 V6-V7: shortest path and length V6 V7: 3 Problem7: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V7-V1: shortest path and length V7 V1: 6 V7-V2: shortest path and length V7 V2: 3 V7-V3: shortest path and length V7 V3: 6 V7-V4: shortest path and length V7 V4: 4 V7-V5: shortest path and length V7 V5: 5 V7-V6: shortest path and length V7 V6: 3 Problem1: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V1-V2: shortest path and length V1 V2: 1 V1-V3: shortest path and length V1 V3: 2 V1-V4: shortest path and length V1 V4: 1 V1-V5: shortest path and length V1 V5: 3 V1-V6: shortest path and length V1 V6: 4 Problem2: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V2-V1: shortest path and length V2 V1: 1 V2-V3: shortest path and length V2 V3: 3 V2-V4: shortest path and length V2 V4: 2 V2-V5: shortest path and length V2 V5: 2 V2-V6: shortest path and length V2 V6: 3 Problem3: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V3-V1: shortest path and length V3 V1: 2 V3-V2: shortest path and length V3 V2: 3 V3-V4: shortest path and length V3 V4: 3 V3-V5: shortest path and length V3 V5: 3 V3-V6: shortest path and length V3 V6: 6 Problem4: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V4-V1: shortest path and length V4 V1: 1 V4-V2: shortest path and length V4 V2: 2 V4-V3: shortest path and length V4 V3: 3 V4-V5: shortest path and length V4 V5: 3 V4-V6: shortest path and length V4 V6: 5 Problem5: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V5-V1: shortest path and length V5 V1: 3 V5-V2: shortest path and length V5 V2: 2 V5-V3: shortest path and length V5 V3: 3 V5-V4: shortest path and length V5 V4: 3 V5-V6: shortest path and length V5 V6: 5 Problem6: n = 6 Pmatrix: 0 1 2 3 4 5 0 0 2 3 4 5 0 1 0 3 4 5 0 1 2 0 4 5 0 1 2 3 0 5 0 1 2 3 4 0 V6-V1: shortest path and length V6 V1: 4 V6-V2: shortest path and length V6 V2: 3 V6-V3: shortest path and length V6 V3: 6 V6-V4: shortest path and length V6 V4: 5 V6-V5: shortest path and length V6 V5: 5 But the expected output is Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: 0 Make necessary changes to the code so as to get the proper matrix representation as there in the expected output.
27fa0c6ad1ebe43b96bb4f39bebcb9d9
{ "intermediate": 0.33483585715293884, "beginner": 0.5323074460029602, "expert": 0.13285668194293976 }
46,167
You are a Computer Science professor. Create an assignment that requires students to code in C++. The assignment must also involve the use to hash tables.
2ed2117b084263cadd038f64e7a41656
{ "intermediate": 0.3423401713371277, "beginner": 0.27560731768608093, "expert": 0.3820525109767914 }
46,168
you know the Godot engine?
57789cf07c77a3cdeb753a85e3b1aaf4
{ "intermediate": 0.34006252884864807, "beginner": 0.397465318441391, "expert": 0.26247212290763855 }
46,169
npm run build --publicPath='/newhome'
0ed2875f30fc63b260425b477f74df5e
{ "intermediate": 0.40770718455314636, "beginner": 0.22111833095550537, "expert": 0.37117451429367065 }
46,170
I have a 3 branch structure in my repository. A main branch, which contains the unbuilt quasar files, a deploy-test branch which contains the built project in main and hosts those built files on a website path called /newhome, and a deploy-prod branch, which hosts build files from the main branch but hosts on a root public path instead '/'. I need to be able to configure the public path when building for deploy-test or deploy-prod. I was thinking about making environment variables and putting them in each branch, but my boss likes to merge from deploy-test into deploy-prod to "go live." How should I work around this?
c2b91947f75d43f8fc73db7e5bb034a2
{ "intermediate": 0.37912189960479736, "beginner": 0.31677016615867615, "expert": 0.3041079640388489 }
46,171
In the "quasar build" command, can I add a publicPath option to it?
61a0941a1230d7b054e78c7e63666b65
{ "intermediate": 0.3806215822696686, "beginner": 0.19410833716392517, "expert": 0.42527008056640625 }
46,172
are you familiar with rasa , can you provide me with the latest version you are aware of
ae837a9cffa2931f6227317f7f0b64f7
{ "intermediate": 0.3832949101924896, "beginner": 0.3015654683113098, "expert": 0.3151395916938782 }
46,173
"build": "quasar build", "build:test": "quasar build publicPath='/newhome'" Im trying to make a special build function in package.json that will set the public path to be something different in my quasar project. How can I achiev this?
ee507c8255bc741991d207530ca3d3a1
{ "intermediate": 0.4205131232738495, "beginner": 0.3002372682094574, "expert": 0.2792495787143707 }
46,174
"build": "quasar build", "build:test": "quasar build --publicPath=/newhome" Seems setting the public path this way instead of throguh quasar.config.js doesn't work. Is there any alternative that doesnt involve environment variables?
7a72076dcf64cb33f1b5fc4f69801a47
{ "intermediate": 0.4264935255050659, "beginner": 0.40431174635887146, "expert": 0.16919468343257904 }
46,175
In servicenow get current logged in user managers name on form
4a063d3bcaf2ff1a9e93e9424b74b3d0
{ "intermediate": 0.3518029451370239, "beginner": 0.26432177424430847, "expert": 0.3838753402233124 }
46,176
@bot.slash_command( name='refine_text', description='Refine input text by iterating with an external AI service.' ) async def refine_text(ctx: discord.ApplicationContext, input_text: str): # Defer response if operation takes a long time await ctx.defer() # Create a thread from the current channel with the provided name thread = await ctx.channel.create_thread(name=input_text[:100], type=discord.ChannelType.public_thread) await ctx.followup.send(f'Thread "{input_text[:100]}" created!') # Initialize the message to be refined message_to_refine = input_text # Loop to refine the text 5 times for i in range(5): await thread.send(f"Refining: Iteration {i+1}") headers = { 'Origin': 'https://gptcall.net/', 'Referer': 'https://gptcall.net/' } body = { "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are RefineGPT. RefineGPT takes an input and if it is an action needed to be done process the action. If it is a completed action then refine the action to be better. AI Image Prompt Examples: A highly photorealistic image of a off road race track, complete with precise replicas of the world’s most iconic heavy noun, captured at the moment of a sharp turn, with smoke and sparks flying from under the wheels and the noun drifting around the bend. The image captures the excitement of the moment, with happy and noisy fans cheering and waving in the background. If asked to make one generate a image in that style with lots of keywords like 8k, 16k, realisitc, appened to the end. Do not assume the user is making an image. Don't assume the user is talking to you always think it is needing you to refine the response." }, { "role": "user", "content": message_to_refine } # Add more messages if needed ] } # Send the request to the external AI service response = requests.post( "https://reverse.mubi.tech/v1/chat/completions", json=body, headers=headers ) # Parse the response and refine the message if response.status_code == 200: response_data = response.json() message_to_refine = response_data['choices'][0]['message']['content'] # Display the refined message await thread.send(f"Refined text (Iteration {i+1}): {message_to_refine}") else: await thread.send("An error occurred while contacting the AI service. Please try again later.") break # Exit if there's an error Make this so it remembers the past messages in the refiment process.
e461f9e1f24cd671aca6b99f73c32023
{ "intermediate": 0.3656464219093323, "beginner": 0.4030781686306, "expert": 0.23127536475658417 }
46,177
public BuffCardOut BuffCardHealth(BuffCardIn param) { Card buffCard = GetActorObject(param.BuffCard); GameAttribute originGameHealth = buffCard.GetHealth(); originGameHealth += param.BuffValue; // 卡牌的原始生命值增加 CardAttribute originCardAttribute = buffCard.GetOriginAttribute(); GameAttribute originAttribute = originCardAttribute.Health; originAttribute += param.BuffValue; originCardAttribute.Health = originAttribute; buffCard.SetOriginAttribute(originCardAttribute); buffCard.SetHealth(originGameHealth); return new BuffCardOut(); } 帮忙优化一下这段代码
83c313130cddae9945d6926104a97f9b
{ "intermediate": 0.37651556730270386, "beginner": 0.2817816138267517, "expert": 0.34170278906822205 }
46,178
I would like to find free software that can help with small lending to business owners
50fad8c796f630011e9bd8dcaec5be90
{ "intermediate": 0.3373701274394989, "beginner": 0.23894451558589935, "expert": 0.4236854016780853 }
46,179
const match1v1Queue = await strapi.query('api::match.match').findMany({ where: { $and: [ { matched: { $eq: false, }, type:{ $eq: "Match1V1" } } ], }, populate: ['deck', 'deck.cards'] }); const match2V2Queue = await strapi.query('api::match.match').findMany({ where: { $and: [ { matched: { $eq: false, }, type:{ $eq: "Match2V2" } } ], }, populate: ['deck', 'deck.cards'] }); 默认match2V2Queue 的四个玩家 默认是 按id 从小到大排序的,我想把它改成按照id顺序 改成1 3 2 4的排序怎么改?
17de6954d4d7c66863a49343795f483a
{ "intermediate": 0.24504607915878296, "beginner": 0.5987221598625183, "expert": 0.15623177587985992 }
46,181
Hi There, please be a senior sapui5 developer and answer my following questions with working code examples.
545a184202556224b33ad08f42aa834d
{ "intermediate": 0.4101978540420532, "beginner": 0.27620670199394226, "expert": 0.3135954439640045 }
46,182
import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class floyd { private static int[][] adjMatrix; private static int[][] pMatrix; private static final String OUTPUT_FILE = "output.txt"; private static ArrayList<Integer> path = new ArrayList<>(); public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: java Floyd <graph-file>"); return; } try (Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0])))) { createFile(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("Problem")) { // Extract number of vertices from the line int n = Integer.parseInt(line.split("n = ")[1].trim()); if (n < 5 || n > 10) { throw new IllegalArgumentException("Invalid number of vertices."); } // Read and initialize the adjacency matrix for the current problem initializeMatrices(n, scanner); // Compute shortest paths and print results calculateShortestPaths(); printResult(n); } } } } private static void createFile() throws FileNotFoundException { PrintWriter writer = new PrintWriter(OUTPUT_FILE); writer.close(); } private static void initializeMatrices(int n, Scanner scanner) { adjMatrix = new int[n][n]; pMatrix = new int[n][n]; for (int i = 0; i < n; ++i) { String[] values = scanner.nextLine().trim().split("\s+"); for (int j = 0; j < n; ++j) { int weight = values[j].equals("INF") ? Integer.MAX_VALUE : Integer.parseInt(values[j]); adjMatrix[i][j] = weight; pMatrix[i][j] = i; // Initialize to source vertex if (i == j) adjMatrix[i][j] = 0; } } } private static void calculateShortestPaths() { int n = adjMatrix.length; for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (adjMatrix[i][k] == Integer.MAX_VALUE || adjMatrix[k][j] == Integer.MAX_VALUE) continue; { adjMatrix[i][j] = adjMatrix[i][k] + adjMatrix[k][j]; pMatrix[i][j] = pMatrix[i][k]; } } } } } private static String getFullPathAsString(int source, int dest) { if (adjMatrix[source][dest] == Integer.MAX_VALUE) return "No path"; StringBuilder pathBuilder = new StringBuilder("V" + (source + 1)); while (source != dest) { source = pMatrix[source][dest]; pathBuilder.append(" V").append(source + 1); } return pathBuilder.toString(); } private static void printResult(int n) throws FileNotFoundException { StringBuilder builder = new StringBuilder(); for (int source = 0; source < n; ++source) { builder.append("Problem").append(source + 1).append(": n = ").append(n).append('\n'); builder.append("Pmatrix:\n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { builder.append(formatElement(pMatrix[i][j])).append(" "); } builder.append("\n"); } builder.append("\n"); for (int dest = 0; dest < n; ++dest) { if (source != dest) { // Skip self to self paths builder.append("V").append(source + 1).append("-V").append(dest + 1).append(": shortest path and length\n"); String pathStr = getFullPathAsString(source, dest); builder.append(pathStr) .append(": ") .append(adjMatrix[source][dest]) .append("\n"); } } builder.append("\n\n"); // Separate problems visually appendToFile(builder.toString()); builder.setLength(0); // Reset builder for next problem } } private static boolean isDirectlyConnected(int from, int to) { return pMatrix[from][to] == to && adjMatrix[from][to] > 0; } private static String getShortestPathAsString(int source, int destination) { if (adjMatrix[source][destination] == Integer.MAX_VALUE) { return "No path"; } int intermediate = pMatrix[source][destination]; StringBuilder pathBuilder = new StringBuilder(); pathBuilder.append("V").append(source + 1); while (source != destination) { pathBuilder.append(" V").append(intermediate + 1); source = intermediate; intermediate = pMatrix[source][destination]; } return pathBuilder.toString(); } private static void buildPath(int current, int destination) { path.clear(); if (current != destination) { path.add(current); while (pMatrix[current][destination] != destination) { current = pMatrix[current][destination]; path.add(current); } path.add(destination); } } private static void clearPathList() { path.clear(); } private static String formatElement(int element) { return "%2d ".formatted(element); } private static void appendToFile(String string) throws FileNotFoundException { try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(OUTPUT_FILE, true)))) { out.println(string); } catch (IOException ex) { System.err.println("An error occurred while writing to the file: " + ex.getMessage()); } } } java floyd graphfile.txt Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.base/java.util.Arrays.copyOf(Arrays.java:3541) at java.base/java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:242) at java.base/java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:587) at java.base/java.lang.StringBuilder.append(StringBuilder.java:179) at floyd.getFullPathAsString(floyd.java:80) at floyd.printResult(floyd.java:104) at floyd.main(floyd.java:34)
163406274140843806fddc9224c63401
{ "intermediate": 0.40136468410491943, "beginner": 0.48672211170196533, "expert": 0.11191317439079285 }
46,183
Hi there, please be a sapui5 senior developer and answer myquestion with working code examples.
c691c6e324469b48a1043fb60e10bf79
{ "intermediate": 0.3941217362880707, "beginner": 0.3043172061443329, "expert": 0.30156099796295166 }