content
stringlengths
3
806k
option
stringclasses
3 values
score
float64
0.01
1
__index_level_0__
int64
0
100k
/** *Submitted for verification at Etherscan.io on 2021-09-14 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } contract KARMA is ERC721Enumerable, Ownable { using Strings for uint256; string _baseTokenURI; uint256 public _reserved = 555; uint256 private _price = 0.0555 ether; bool public _paused = true; // withdraw addresses address t1 = 0xeed0f861c97a181Cb1f91e39C500652e08e87955; constructor(string memory baseURI) ERC721("Karma Collective", "KARMA") { setBaseURI(baseURI); } function mint(uint256 num) public payable { uint256 supply = totalSupply(); require( !_paused, "Sale paused" ); require( num < 21, "You can mint a maximum of 20" ); require(balanceOf(msg.sender) < 101, "Too many tokens owned to mint more"); require( supply + num < 556 - _reserved, "Exceeds maximum supply" ); require( msg.value >= _price * num, "Ether sent is not correct" ); for(uint256 i; i < num; i++){ _safeMint( msg.sender, supply + i ); } } function walletOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } // Just in case Eth does some crazy stuff function setPrice(uint256 _newPrice) public onlyOwner() { _price = _newPrice; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function getPrice() public view returns (uint256){ return _price; } function giveAway(address _to, uint256 _amount) external onlyOwner() { require( _amount <= _reserved, "Exceeds reserved supply" ); uint256 supply = totalSupply(); for(uint256 i; i < _amount; i++){ _safeMint( _to, supply + i ); } _reserved -= _amount; } function pause(bool val) public onlyOwner { _paused = val; } function setReserved(uint256 _newReserved) public onlyOwner { _reserved = _newReserved; } function withdrawAll() public payable onlyOwner { uint256 _each = address(this).balance; require(payable(t1).send(_each)); } }
high
0.84314
99,810
# SPDX-License-Identifier: Apache-2.0 # Licensed to the Ed-Fi Alliance under one or more agreements. # The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. # See the LICENSE and NOTICES files in the project root for more information. function Install-NuGetCli { <# .SYNOPSIS Installs the latest version of the NuGet command line executable .DESCRIPTION Installs the latest version of the NuGet command line executable .PARAMETER toolsPath The path to store nuget.exe to .PARAMETER sourceNuGetExe Web location to the nuget file. Defaulted to the version 5.3.1.0 of nuget.exe. #> [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [string] $ToolsPath, [string] $sourceNuGetExe = "https://dist.nuget.org/win-x86-commandline/v5.3.1/nuget.exe" ) if (-not $(Test-Path $ToolsPath)) { mkdir $ToolsPath | Out-Null } $nuget = (Join-Path $ToolsPath "nuget.exe") if (-not $(Test-Path $nuget)) { Write-Host "Downloading nuget.exe official distribution from " $sourceNuGetExe Invoke-WebRequest $sourceNuGetExe -OutFile $nuget } else { $info = Get-Command $nuget if ("5.3.1.0" -ne $info.Version.ToString()) { Write-Host "Updating nuget.exe official distribution from " $sourceNuGetExe Invoke-WebRequest $sourceNuGetExe -OutFile $nuget } } # Add the tools directory to the path if not already there if (-not ($env:PATH.Contains($ToolsPath))) { $env:PATH = "$ToolsPath;$env:PATH" } return $nuget } function Get-NuGetPackage { <# .SYNOPSIS Download and unzip a NuGet package for the purpose of bundling into another package. .DESCRIPTION Uses nuget command line to download a NuGet package and unzip it into an output directory. Uses the Ed-Fi Azure Artifacts package feed by default. Default output directory is .\downloads. .PARAMETER packageName Alias "applicationId". Name of the package to download. .PARAMETER packageVersion Package version number. Can include pre-release information. Optional. If not specified, installs the most recent full release version. .PARAMETER toolsPath The path in which to find the NuGet command line client. .PARAMETER outputDirectory The path into which the package is unzipped. Defaults to ".\downloads". .PARAMETER packageSource The NuGet package source. Defaults to "https://pkgs.dev.azure.com/ed-fi-alliance/Ed-Fi-Alliance-OSS/_packaging/EdFi/nuget/v3/index.json". .EXAMPLE $parameters = @{ packageName = "EdFi.Suite3.Ods.WebApi" packageVersion = "5.0.0-b11661" toolsPath = ".\tools" } Get-NuGetPackage @parameters #> [CmdletBinding()] param ( [string] [Parameter(Mandatory = $true)] [Alias("applicationId")] $PackageName, [string] $PackageVersion, [string] [Parameter(Mandatory = $true)] $ToolsPath, [string] $OutputDirectory = '.\downloads', [string] $PackageSource = "https://pkgs.dev.azure.com/ed-fi-alliance/Ed-Fi-Alliance-OSS/_packaging/EdFi/nuget/v3/index.json" ) $nuget = Install-NuGetCli $ToolsPath if (-not $PackageVersion) { # Lookup current "latest" version $latestVersion = & "$ToolsPath\nuget" list -source $PackageSource $PackageName if ($latestVersion) { # output is like "packageName packageVersion", split to get second part $parts = $latestVersion.split(' ') if ($parts.length -eq 2) { $PackageVersion = $parts[1] } } } $downloadedPackagePath = Join-Path $OutputDirectory "$PackageName.$PackageVersion" if (Test-Path $downloadedPackagePath) { Write-Debug "Reusing already downloaded package for: $PackageName" return $downloadedPackagePath } $parameters = @( "install", $PackageName, "-source", $PackageSource, "-version", $PackageVersion, "-outputDirectory", $OutputDirectory ) Write-Host -ForegroundColor Magenta "$ToolsPath\nuget $parameters" & "$ToolsPath\nuget" $parameters | Out-Null return Resolve-Path $downloadedPackagePath } $exports = @( "Install-NuGetCli" "Get-NuGetPackage" ) Export-ModuleMember -Function $exports
high
0.540154
99,811
-- This query uses a temporary table named "year_pubcounts". Its creation script and insertion scripts are given in task_3_temp.sql file. select concat(cast(ypc1.year as varchar), '-' , cast(ypc10.year + 1 as varchar)) as decade, (ypc1.pubCount + ypc2.pubCount + ypc3.pubCount + ypc4.pubCount + ypc5.pubCount + ypc6.pubCount + ypc7.pubCount + ypc8.pubCount + ypc9.pubCount + ypc10.pubCount) as total from year_pubcounts ypc1, year_pubcounts ypc2, year_pubcounts ypc3, year_pubcounts ypc4, year_pubcounts ypc5, year_pubcounts ypc6, year_pubcounts ypc7, year_pubcounts ypc8, year_pubcounts ypc9, year_pubcounts ypc10 where ypc2.year - ypc1.year = 1 and ypc3.year - ypc1.year = 2 and ypc4.year - ypc1.year = 3 and ypc5.year - ypc1.year = 4 and ypc6.year - ypc1.year = 5 and ypc7.year - ypc1.year = 6 and ypc8.year - ypc1.year = 7 and ypc9.year - ypc1.year = 8 and ypc10.year - ypc1.year = 9 order by decade;
medium
0.455849
99,812
SUBROUTINE iau_ATICQN ( RI, DI, ASTROM, N, B, RC, DC ) *+ * - - - - - - - - - - - * i a u _ A T I C Q N * - - - - - - - - - - - * * Quick CIRS to ICRS astrometric place transformation, given the * star-independent astrometry parameters plus a list of light- * deflecting bodies. * * Use of this routine is appropriate when efficiency is important and * where many star positions are all to be transformed for one date. * The star-independent astrometry parameters can be obtained by * calling one of the routines iau_APCI[13], iau_APCG[13], iau_APCO[13] * or iau_APCS[13]. * * If the only light-deflecting body to be taken into account is the * Sun, the iau_ATICQ routine can be used instead. * * This routine is part of the International Astronomical Union's * SOFA (Standards of Fundamental Astronomy) software collection. * * Status: support routine. * * Given: * RI,DI d CIRS RA,Dec (radians) * ASTROM d(30) star-independent astrometry parameters: * (1) PM time interval (SSB, Julian years) * (2-4) SSB to observer (vector, au) * (5-7) Sun to observer (unit vector) * (8) distance from Sun to observer (au) * (9-11) v: barycentric observer velocity (vector, c) * (12) sqrt(1-|v|^2): reciprocal of Lorenz factor * (13-21) bias-precession-nutation matrix * (22) longitude + s' (radians) * (23) polar motion xp wrt local meridian (radians) * (24) polar motion yp wrt local meridian (radians) * (25) sine of geodetic latitude * (26) cosine of geodetic latitude * (27) magnitude of diurnal aberration vector * (28) "local" Earth rotation angle (radians) * (29) refraction constant A (radians) * (30) refraction constant B (radians) * N i number of bodies (Note 3) * B d(8,N) data for each of the NB bodies (Notes 3,4): * (1,I) mass of the body (solar masses, Note 5) * (2,I) deflection limiter (Note 6) * (3-5,I) barycentric position of the body (au) * (6-8,I) barycentric velocity of the body (au/day) * * Returned: * RC,DC d ICRS astrometric RA,Dec (radians) * * Notes: * * 1) Iterative techniques are used for the aberration and light * deflection corrections so that the routines iau_ATICQN and * iau_ATCIQN are accurate inverses; even at the edge of the Sun's * disk the discrepancy is only about 1 nanoarcsecond. * * 2) If the only light-deflecting body to be taken into account is the * Sun, the iau_ATICQ routine can be used instead. * * 3) The array B contains N entries, one for each body to be * considered. If N = 0, no gravitational light deflection will be * applied, not even for the Sun. * * 4) The array B should include an entry for the Sun as well as for any * planet or other body to be taken into account. The entries should * be in the order in which the light passes the body. * * 5) In the entry in the B array for body I, the mass parameter B(1,I) * can, as required, be adjusted in order to allow for such effects * as quadrupole field. * * 6) The deflection limiter parameter B(2,I) is phi^2/2, where phi is * the angular separation (in radians) between star and body at which * limiting is applied. As phi shrinks below the chosen threshold, * the deflection is artificially reduced, reaching zero for phi = 0. * Example values suitable for a terrestrial observer, together with * masses, are as follows: * * body I B(1,I) B(2,I) * * Sun 1D0 6D-6 * Jupiter 0.00095435D0 3D-9 * Saturn 0.00028574D0 3D-10 * * 7) For efficiency, validation of the contents of the B array is * omitted. The supplied masses must be greater than zero, the * position and velocity vectors must be right, and the deflection * limiter greater than zero. * * Called: * iau_S2C spherical coordinates to unit vector * iau_TRXP product of transpose of r-matrix and p-vector * iau_ZP zero p-vector * iau_AB stellar aberration * iau_LDN light deflection by n bodies * iau_C2S p-vector to spherical * iau_ANP normalize angle into range +/- pi * * This revision: 2013 September 30 * * SOFA release 2017-04-20 * * Copyright (C) 2017 IAU SOFA Board. See notes at end. * *----------------------------------------------------------------------- IMPLICIT NONE DOUBLE PRECISION RI, DI, ASTROM(30) INTEGER N DOUBLE PRECISION B(8,N), RC, DC INTEGER J, I DOUBLE PRECISION PI(3), PPR(3), PNAT(3), PCO(3), W, D(3), : BEFORE(3), R2, R, AFTER(3) DOUBLE PRECISION iau_ANP * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * CIRS RA,Dec to Cartesian. CALL iau_S2C ( RI, DI, PI ) * Bias-precession-nutation, giving GCRS proper direction. CALL iau_TRXP ( ASTROM(13), PI, PPR ) * Aberration, giving GCRS natural direction. CALL iau_ZP ( D ) DO 50 J=1,2 R2 = 0D0 DO 10 I=1,3 W = PPR(I) - D(I) BEFORE(I) = W R2 = R2 + W*W 10 CONTINUE R = SQRT ( R2 ) DO 20 I=1,3 BEFORE(I) = BEFORE(I) / R 20 CONTINUE CALL iau_AB ( BEFORE, ASTROM(9), ASTROM(8), ASTROM(12), AFTER ) R2 = 0D0 DO 30 I=1,3 D(I) = AFTER(I) - BEFORE(I) W = PPR(I) - D(I) PNAT(I) = W R2 = R2 + W*W 30 CONTINUE R = SQRT ( R2 ) DO 40 I=1,3 PNAT(I) = PNAT(I) / R 40 CONTINUE 50 CONTINUE * Light deflection, giving BCRS coordinate direction. CALL iau_ZP ( D ) DO 100 J=1,5 R2 = 0D0 DO 60 I=1,3 W = PNAT(I) - D(I) BEFORE(I) = W R2 = R2 + W*W 60 CONTINUE R = SQRT ( R2 ) DO 70 I=1,3 BEFORE(I) = BEFORE(I) / R 70 CONTINUE CALL iau_LDN ( N, B, ASTROM(2), BEFORE, AFTER ) R2 = 0D0 DO 80 I=1,3 D(I) = AFTER(I) - BEFORE(I) W = PNAT(I) - D(I) PCO(I) = W R2 = R2 + W*W 80 CONTINUE R = SQRT ( R2 ) DO 90 I=1,3 PCO(I) = PCO(I) / R 90 CONTINUE 100 CONTINUE * ICRS astrometric RA,Dec. CALL iau_C2S ( PCO, W, DC ) RC = iau_ANP ( W ) * Finished. *+---------------------------------------------------------------------- * * Copyright (C) 2017 * Standards Of Fundamental Astronomy Board * of the International Astronomical Union. * * ===================== * SOFA Software License * ===================== * * NOTICE TO USER: * * BY USING THIS SOFTWARE YOU ACCEPT THE FOLLOWING SIX TERMS AND * CONDITIONS WHICH APPLY TO ITS USE. * * 1. The Software is owned by the IAU SOFA Board ("SOFA"). * * 2. Permission is granted to anyone to use the SOFA software for any * purpose, including commercial applications, free of charge and * without payment of royalties, subject to the conditions and * restrictions listed below. * * 3. You (the user) may copy and distribute SOFA source code to others, * and use and adapt its code and algorithms in your own software, * on a world-wide, royalty-free basis. That portion of your * distribution that does not consist of intact and unchanged copies * of SOFA source code files is a "derived work" that must comply * with the following requirements: * * a) Your work shall be marked or carry a statement that it * (i) uses routines and computations derived by you from * software provided by SOFA under license to you; and * (ii) does not itself constitute software provided by and/or * endorsed by SOFA. * * b) The source code of your derived work must contain descriptions * of how the derived work is based upon, contains and/or differs * from the original SOFA software. * * c) The names of all routines in your derived work shall not * include the prefix "iau" or "sofa" or trivial modifications * thereof such as changes of case. * * d) The origin of the SOFA components of your derived work must * not be misrepresented; you must not claim that you wrote the * original software, nor file a patent application for SOFA * software or algorithms embedded in the SOFA software. * * e) These requirements must be reproduced intact in any source * distribution and shall apply to anyone to whom you have * granted a further right to modify the source code of your * derived work. * * Note that, as originally distributed, the SOFA software is * intended to be a definitive implementation of the IAU standards, * and consequently third-party modifications are discouraged. All * variations, no matter how minor, must be explicitly marked as * such, as explained above. * * 4. You shall not cause the SOFA software to be brought into * disrepute, either by misuse, or use for inappropriate tasks, or * by inappropriate modification. * * 5. The SOFA software is provided "as is" and SOFA makes no warranty * as to its use or performance. SOFA does not and cannot warrant * the performance or results which the user may obtain by using the * SOFA software. SOFA makes no warranties, express or implied, as * to non-infringement of third party rights, merchantability, or * fitness for any particular purpose. In no event will SOFA be * liable to the user for any consequential, incidental, or special * damages, including any lost profits or lost savings, even if a * SOFA representative has been advised of such damages, or for any * claim by any third party. * * 6. The provision of any version of the SOFA software under the terms * and conditions specified herein does not imply that future * versions will also be made available under the same terms and * conditions. * * In any published work or commercial product which uses the SOFA * software directly, acknowledgement (see www.iausofa.org) is * appreciated. * * Correspondence concerning SOFA software should be addressed as * follows: * * By email: sofa@ukho.gov.uk * By post: IAU SOFA Center * HM Nautical Almanac Office * UK Hydrographic Office * Admiralty Way, Taunton * Somerset, TA1 2DN * United Kingdom * *----------------------------------------------------------------------- END
high
0.864349
99,813
#' Get a random vector of species names. #' #' Family and order names come from the APG plant names list. Genus and #' species names come from Theplantlist.org. #' #' @export #' @param rank Taxonomic rank, one of species, genus (default), family, order #' @param size Number of names to get. Maximum depends on the rank #' @return Vector of taxonomic names. #' @author Scott Chamberlain \email{myrmecocystus@@gmail.com} #' @examples #' names_list() #' names_list('species') #' names_list('genus') #' names_list('family') #' names_list('order') #' names_list('order', '2') #' names_list('order', '15') #' #' # You can get a lot of genus or species names if you want #' nrow(theplantlist) #' names_list('genus', 500) names_list <- function(rank='genus', size=10) { getsp <- function(size){ tmp <- apply(taxize_ds$theplantlist[ sample(1:nrow(taxize_ds$theplantlist), size), c('genus','species')], 1, function(y) paste(y, collapse = " ")) names(tmp) <- NULL tmp } switch(rank, family = as.character(sample(taxize_ds$apg_families$this, size)), order = as.character(sample(taxize_ds$apg_orders$this, size)), genus = sample(unique(taxize_ds$theplantlist$genus), size), species = getsp(size) ) }
high
0.200488
99,814
// (c) Copyright 1995-2019 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. // IP VLNV: xilinx.com:ip:c_addsub:12.0 // IP Revision: 11 // The following must be inserted into your Verilog file for this // core to be instantiated. Change the instance name and port connections // (in parentheses) to your own signal names. //----------- Begin Cut here for INSTANTIATION Template ---// INST_TAG c_addsub_2 your_instance_name ( .A(A), // input wire [16 : 0] A .B(B), // input wire [16 : 0] B .CLK(CLK), // input wire CLK .CE(CE), // input wire CE .S(S) // output wire [17 : 0] S ); // INST_TAG_END ------ End INSTANTIATION Template --------- // You must compile the wrapper file c_addsub_2.v when simulating // the core, c_addsub_2. When compiling the wrapper file, be sure to // reference the Verilog simulation library.
low
0.322229
99,815
/* * Copyright 2015 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.linkedin.gradle.validator.pig import com.linkedin.gradle.hadoopdsl.NamedScope import com.linkedin.gradle.hadoopdsl.job.PigJob import org.apache.pig.Main import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.tasks.TaskAction /** * The PigSyntaxValidator class provides a task for validating the syntax of Apache Pig Scripts. */ class PigSyntaxValidator extends DefaultTask implements PigValidator { public enum PigArgs { //Execution mode Local EXEC_MODE('local', 'This arg sets the pig execution mode to local'), //command line option to set exec mode CL_OPTION_EXECTYPE('-x', 'command line option to set execution mode'), //Command line option for parameter substitution CL_OPTION_PARAMETERS('-p', 'Command line option for specifying parameters'), //Command line option to perform parameter substitution CL_OPTION_DRYRUN('-dryrun', 'Command line option to perform parameter substitution'), //Command line parameter to initiate syntax checking CL_OPTS_C('-c', 'Command line parameter to initiate syntax checking') private String value; private String description; private PigArgs(String value, String description) { this.value = value; this.description = description; } } Map<PigJob, NamedScope> jobMap; Properties properties; /** * Task that validates the syntax the Apache Pig Scripts in the project. */ @TaskAction void validate() { ArrayList<String> _args = new ArrayList<String>(); File script; InputStream krbInputStream = this.getClass().getClassLoader().getResourceAsStream("krb5.conf"); File krb5 = new File(System.getProperty("java.io.tmpdir"), "krb5.conf"); OutputStream krbOutputStream = new FileOutputStream(krb5); int read; byte[] bytes = new byte[1024]; while ((read = krbInputStream.read(bytes)) != -1) { krbOutputStream.write(bytes, 0, read); } System.setProperty("java.security.krb5.conf", krb5.getAbsolutePath()); jobMap.each { PigJob pigJob, NamedScope parentScope -> script = new File(pigJob.script); if (script.name.endsWith(".pig")) { _args.addAll(pigJob.parameters.collect { key, value -> "${PigArgs.CL_OPTION_PARAMETERS.value} $key=$value" }. join(" "). split()) _args.add(PigArgs.CL_OPTION_DRYRUN.value); project.logger.lifecycle("Checking file: \t $script"); _args.add("$script"); File subst_file = new File("${script}.substituted"); subst_file.deleteOnExit(); String[] args = _args.toArray(); int returnValue = Main.run(args, null); if (returnValue) { throw new GradleException('Syntax checker found errors'); } _args.clear(); } } } }
high
0.658534
99,816
(* user interface to HolCheck *) structure holCheck :> holCheck = struct local open Globals HolKernel Parse open bddTools ksTools ctlCheck cearTools modelTools internalCacheTools val dpfx = "hc_" fun init model = let val _ = dbgTools.DEN dpfx "i"(*DBG*) val _ = if bdd.isRunning() then () else bdd.init 1000000 10000 (* FIXME: allow user to supply the nums here *) val (I1,T1,Ric,ksname,bvm,state,fl,_,ic) = dest_model model val state = if isSome state then valOf state else mk_state I1 T1 val (apl,apsubs) = if get_flag_abs model then holCheckTools.mk_abs_APs fl state else (NONE,[]) val vm = mk_varmap state bvm val _ = dbgTools.DEX dpfx "i"(*DBG*) in (I1,T1,Ric,ksname,bvm,state,fl,ic,vm,apl,apsubs) end in fun holCheck model = let val _ = dbgTools.DEN dpfx "hc"(*DBG*) val _ = profTools.bgt (dpfx^"hc")(*PRF*) val (I1,T1,Ric,ksname,bvm,state,fl,ic,vm,apl,apsubs) = init model val (results,ic) = List.foldl (fn ((nf,f),(results,ic)) => let val _ = dbgTools.DST (dpfx^"hc_nf: "^nf) (*DBG*) val is_mu = ((String.compare(fst(dest_type(type_of f)),"mu"))=EQUAL) val (res,ic) = if is_mu then let val (r,(i,c)) = absCheck I1 T1 state Ric vm ksname (get_abs ic,get_common ic) (nf,f) (apl,apsubs) in (r,((set_common c) o (set_abs i)) ic) end else let val (r,(i,c)) = ctlCheck I1 T1 state Ric vm ksname (get_ctl ic,get_common ic) (nf,f) (apl,apsubs) in (r,((set_common c) o (set_ctl i)) ic) end in (results@[res],ic) end) ([],if isSome ic then valOf ic else set_vm vm empty_ic) fl val _ = profTools.ent (dpfx^"hc")(*PRF*) val _ = dbgTools.DEX dpfx "hc"(*DBG*) in (((set_ic ic) o (set_results results)) model) end end end
high
0.427537
99,817
import CodeMirror from 'codemirror'; import { initializeSpectral, isLintError } from '../../../../common/spectral'; const spectral = initializeSpectral(); CodeMirror.registerHelper('lint', 'openapi', async function(text: string) { const results = (await spectral.run(text)).filter(isLintError); return results.map(result => ({ from: CodeMirror.Pos(result.range.start.line, result.range.start.character), to: CodeMirror.Pos(result.range.end.line, result.range.end.character), message: result.message, })); });
high
0.450093
99,818
-- Shamelessly stolen from Edwin Brady module Main pythagoras : Int -> List (Int, Int, Int) pythagoras max = [ (x, y, z) | z <- [1..max] , y <- [1..z] , x <- [1..y] , x * x + y *y == z * z ] main : IO () main = do arg <- getLine printLn $ pythagoras (cast arg)
high
0.209363
99,819
syntax = "proto3"; package gorums; import "google/protobuf/descriptor.proto"; option go_package = "github.com/relab/gorums"; extend google.protobuf.MethodOptions { bool qc = 50000; bool correctable = 50001; bool correctable_stream = 50002; bool multicast = 50003; bool qc_future = 50004; bool qf_with_req = 50005; bool per_node_arg = 50006; string custom_return_type = 51000; }
low
0.725307
99,820
# See the file LICENSE for redistribution information. # # Copyright (c) 1999, 2017 Oracle and/or its affiliates. All rights reserved. # # $Id$ # # TEST env003 # TEST Test DB_TMP_DIR and env name resolution # TEST With an environment path specified using -home, and then again # TEST with it specified by the environment variable DB_HOME: # TEST 1) Make sure that the DB_TMP_DIR config file option is respected # TEST a) as a relative pathname. # TEST b) as an absolute pathname. # TEST 2) Make sure that the -tmp_dir config option is respected, # TEST again as relative and absolute pathnames. # TEST 3) Make sure that if -both- -tmp_dir and a file are present, # TEST only the file is respected (see doc/env/naming.html). proc env003 { } { # env003 is essentially just a small driver that runs # env003_body twice. First, it supplies a "home" argument # to use with environment opens, and the second time it sets # DB_HOME instead. # Note that env003_body itself calls env003_run_test to run # the body of the actual test. global env source ./include.tcl puts "Env003: DB_TMP_DIR test." puts "\tEnv003: Running with -home argument to berkdb_env." env003_body "-home $testdir" puts "\tEnv003: Running with environment variable DB_HOME set." set env(DB_HOME) $testdir env003_body "-use_environ" unset env(DB_HOME) puts "\tEnv003: Running with both DB_HOME and -home set." # Should respect -only- -home, so we give it a bogus # environment variable setting. set env(DB_HOME) $testdir/bogus_home env003_body "-use_environ -home $testdir" unset env(DB_HOME) } proc env003_body { home_arg } { source ./include.tcl env_cleanup $testdir set tmpdir "tmpfiles_in_here" file mkdir $testdir/$tmpdir # Set up full path to $tmpdir for when we test absolute paths. set curdir [pwd] cd $testdir/$tmpdir set fulltmpdir [pwd] cd $curdir # Create DB_CONFIG env003_make_config $tmpdir # Run the meat of the test. env003_run_test a 1 "relative path, config file" $home_arg \ $testdir/$tmpdir env003_make_config $fulltmpdir # Run the test again env003_run_test a 2 "absolute path, config file" $home_arg \ $fulltmpdir # Now we try without a config file, but instead with db_config # relative paths env003_run_test b 1 "relative path, db_config" "$home_arg \ -tmp_dir $tmpdir -data_dir ." \ $testdir/$tmpdir # absolute paths env003_run_test b 2 "absolute path, db_config" "$home_arg \ -tmp_dir $fulltmpdir -data_dir ." \ $fulltmpdir # Now, set db_config -and- have a # DB_CONFIG file, and make # sure only the latter is honored. file mkdir $testdir/bogus env003_make_config $tmpdir env003_run_test c 1 "relative path, both db_config and file" \ "$home_arg -tmp_dir $testdir/bogus -data_dir ." \ $testdir/$tmpdir file mkdir $fulltmpdir/bogus env003_make_config $fulltmpdir env003_run_test c 2 "absolute path, both db_config and file" \ "$home_arg -tmp_dir $fulltmpdir/bogus -data_dir ." \ $fulltmpdir } proc env003_run_test { major minor msg env_args tmp_path} { global testdir global alphabet global errorCode puts "\t\tEnv003.$major.$minor: $msg" # Create an environment and small-cached in-memory database to # use. set dbenv [eval {berkdb_env -create -home $testdir} $env_args \ {-cachesize {0 50000 1}}] error_check_good env_open [is_valid_env $dbenv] TRUE set db [berkdb_open -env $dbenv -create -btree] error_check_good db_open [is_valid_db $db] TRUE # Fill the database with more than its cache can fit. # # When CONFIG_TEST is defined, the tempfile is left linked so # we can check for its existence. Size the data to overfill # the cache--the temp file is created lazily, so it is created # when the cache overflows. # set key "key" set data [repeat $alphabet 2000] error_check_good db_put [$db put $key $data] 0 # Check for exactly one temp file. set ret [glob -nocomplain $tmp_path/BDB*] error_check_good temp_file_exists [llength $ret] 1 # Can't remove temp file until db is closed on Windows. error_check_good db_close [$db close] 0 fileremove -f $ret error_check_good env_close [$dbenv close] 0 } proc env003_make_config { tmpdir } { global testdir set cid [open $testdir/DB_CONFIG w] puts $cid "set_data_dir ." puts $cid "set_tmp_dir $tmpdir" close $cid }
high
0.506823
99,821
/* "Chapter 6 Splitting Sorted Data via Hash.sas" from the SAS Press book Data Management Solutions Using SAS Hash Table Operations: A Business Intelligence Case Study */ data _null_ ; if _n_ = 1 then do ; dcl hash h (multidata:"Y") ; h.defineKey ("_n_") ; h.defineData ("League", "Team_SK", "Team_Name") ; h.defineDone () ; end ; do until (last.League) ; set bizarro.Teams ; by League ; h.add() ; end ; h.output (dataset: catx ("_", "work.League", League)) ; h.clear() ; run ;
high
0.334701
99,822
from django.conf import settings from django import forms from seymour.accounts.models import Account __all__ = ( 'LoginForm', 'SignupForm', 'ResetPasswordForm', 'ConfirmResetPasswordForm', 'EditOpenIDProfileForm', 'EditEmailProfileForm' ) class LoginForm(forms.Form): method = forms.ChoiceField(label='Login using', required=True, choices=(('email', 'Email & Password'), ('openid', 'OpenID')), widget=forms.RadioSelect()) openid = forms.CharField(label='Your OpenID', max_length=255, required=False, widget=forms.TextInput(attrs={'class': 'text'})) email = forms.EmailField(label='Email address', max_length=75, required=False, widget=forms.TextInput(attrs={'class': 'text'})) password = forms.CharField(label='Password', max_length=30, required=False, widget=forms.PasswordInput(attrs={'class': 'text'})) def clean(self): if self.cleaned_data['method'] == 'email': email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') # must I use a forms.ValidationError()? must this be a sequence? # the documentation isn't clear.. if not email: self.errors['email'] = "This field is required." if not password: self.errors['password'] = "This field is required." if email and password: try: account = Account.objects.get(email=email) except Account.DoesNotExist: self.data['password'] = '' raise forms.ValidationError("Please enter a correct email address and password. Note that both fields are case-sensitive.") if not account.check_password(password): self.data['password'] = '' raise forms.ValidationError("Please enter a correct email address and password. Note that both fields are case-sensitive.") if not account.is_active: raise forms.ValidationError("This account is inactive.") self._account = account return self.cleaned_data else: # TODO: do some basic checks to make sure this is actually a URL.. return self.cleaned_data def get_openid(self): # for now handle it all inside the view return self.cleaned_data['openid'] def get_account(self): if hasattr(self, '_account'): return self._account else: return None email_help = """Please use a valid email address as you will use this to log-in. We will never sell your email address to anyone.""" password_help = """Password should be at least 6 characters.""" confirmation_help = """We sent you this in an email. If you clicked the link we sent it should automatically be filled in.""" class SignupForm(forms.Form): method = forms.ChoiceField(label='Signup using', required=True, choices=(('email', 'Email & Password'), ('openid', 'OpenID')), widget=forms.RadioSelect()) openid = forms.CharField(label='Your OpenID', max_length=255, required=False, widget=forms.TextInput(attrs={'class': 'text'})) firstname = forms.CharField(label='First name', max_length=100, required=False, widget=forms.TextInput(attrs={'class': 'text'})) lastname = forms.CharField(label='Last name', max_length=100, required=False, widget=forms.TextInput(attrs={'class': 'text'})) email = forms.EmailField(label='Email address', help_text=email_help, max_length=75, required=False, widget=forms.TextInput(attrs={'class': 'text'})) password = forms.CharField(label='Password', help_text=password_help, initial='', max_length=30, required=False, widget=forms.PasswordInput(attrs={'class': 'text'})) confirm_password = forms.CharField(label='Re-type password', initial='', max_length=30, required=False, widget=forms.PasswordInput(attrs={'class': 'text'})) captcha = forms.CharField(label='Please type the word you see in the image', initial='', max_length=128, required=True, widget=forms.TextInput(attrs={'class': 'vTextField'})) def __init__(self, *args, **kwargs): self.word = kwargs['word'] del kwargs['word'] super(SignupForm, self).__init__(*args, **kwargs) def clean_email(self): value = self.cleaned_data['email'] try: account = Account.objects.get(email=value) except Account.DoesNotExist: pass else: raise forms.ValidationError("The email address is already used.") return value def clean_captcha(self): value = self.cleaned_data['captcha'] if value != self.word: self.data['captcha'] = '' raise forms.ValidationError("Please fill in this code.") return value def clean(self): if self.cleaned_data['method'] == 'email': email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') confirm_password = self.cleaned_data.get('confirm_password') # must I use a forms.ValidationError()? must this be a sequence? # the documentation isn't clear.. if not email: self.errors['email'] = "This field is required." if not password: self.errors['password'] = "This field is required." if not confirm_password: self.errors['confirm_password'] = "This field is required." if password or confirm_password: if password != confirm_password: self.data['password'] = '' self.data['confirm_password'] = '' raise forms.ValidationError("The Passwords don't match.") else: if len(password) < 6: self._errors['password'] = "Passwords must be at least 6 characters long." self.data['password'] = '' self.data['confirm_password'] = '' return self.cleaned_data else: # TODO: do some basic checks to make sure this is actually a URL.. return self.cleaned_data def save(self): data = self.cleaned_data account = Account( firstname=data['firstname'], lastname=data['lastname'], email=data['email'], is_active=True, ) account.set_password(data['password']) account.save() # email the password to the user from django.core.mail import send_mail from django.template import Template, Context, loader context = Context({ 'account': account, 'password': data['password'], 'sitename': settings.SITENAME, 'seymour_domain': settings.SEYMOUR_DOMAIN }) subject = u"Welcome to %s" % (settings.SITENAME) t = loader.get_template('emails/account_added.email') email_body = t.render(context) if settings.DEBUG: print "Subject: " + subject.encode('utf8') print "-"*80 print email_body.encode('utf8') else: send_mail(subject, email_body, settings.EMAIL_FROM, [account.email], fail_silently=True) return account def get_openid(self): # for now handle it all inside the view return self.cleaned_data['openid'] class ResetPasswordForm(forms.Form): email = forms.EmailField(label='Email address', max_length=75, required=True, widget=forms.TextInput(attrs={'class': 'vTextField'})) def clean_email(self): email = self.cleaned_data.get('email') if email: try: account = Account.objects.get(email=email) except Account.DoesNotExist: raise forms.ValidationError("This email address is not on our system.") return email def save(self): import sha import random confirmation_code = sha.new(str(random.random())).hexdigest()[:5].upper() email = self.cleaned_data['email'] account = Account.objects.get(email=email) account.confirmation_code = confirmation_code account.save() # send email from django.core.mail import send_mail from django.template import Template, Context, loader context = Context({ 'account': account, 'sitename': settings.SITENAME, 'seymour_domain': settings.SEYMOUR_DOMAIN }) subject = u"[%s] Reset Password Confirmation" % (settings.SITENAME) t = loader.get_template('emails/reset_password_confirm.email') email_body = t.render(context) if settings.DEBUG: print "Subject: " + subject.encode('utf8') print "-"*80 print email_body.encode('utf8') else: send_mail(subject, email_body, settings.EMAIL_FROM, [account.email], fail_silently=True) class ConfirmResetPasswordForm(forms.Form): email = forms.EmailField(label='Email address', max_length=75, required=True, widget=forms.TextInput(attrs={'class': 'vTextField'})) confirmation_code = forms.CharField(label='Confirmation code', max_length=75, help_text=confirmation_help, required=True, widget=forms.TextInput(attrs={'class': 'vTextField'})) def clean_email(self): email = self.cleaned_data.get('email') if email: try: account = Account.objects.get(email=email) except Account.DoesNotExist: raise forms.ValidationError("This email address is not on our system.") return email def clean(self): email = self.cleaned_data.get('email') confirmation_code = self.cleaned_data.get('confirmation_code') if email: try: account = Account.objects.get(email=email) if account.confirmation_code != confirmation_code: self._errors['confirmation_code'] = "Invalid confirmation code. Please try again. If you keep having problems, please contact support." return self.cleaned_data except Account.DoesNotExist: self._errors['email'] = "This email address is not on our system." def save(self): import sha import random email = self.cleaned_data['email'] account = Account.objects.get(email=email) new_password = sha.new(str(random.random())).hexdigest()[:5].upper() account.confirmation_code = None account.set_password(new_password) account.save() # send email from django.core.mail import send_mail from django.template import Template, Context, loader context = Context({ 'account': account, 'password': new_password, 'sitename': settings.SITENAME, 'seymour_domain': settings.SEYMOUR_DOMAIN }) subject = u"[%s] Password Changed" % (settings.SITENAME) t = loader.get_template('emails/changed_password.email') email_body = t.render(context) if settings.DEBUG: print "Subject: " + subject.encode('utf8') print "-"*80 print email_body.encode('utf8') else: send_mail(subject, email_body, settings.EMAIL_FROM, [account.email], fail_silently=True) class EditOpenIDProfileForm(forms.Form): firstname = forms.CharField(label='First name', max_length=100, required=False, widget=forms.TextInput(attrs={'class': 'text'})) lastname = forms.CharField(label='Last name', max_length=100, required=False, widget=forms.TextInput(attrs={'class': 'text'})) # TODO: allow changing OpenID (will probably require re-authentication, # because otherwise you can't log back in..) def __init__(self, *args, **kwargs): self.update = kwargs['update'] del kwargs['update'] super(EditOpenIDProfileForm, self).__init__(*args, **kwargs) def save(self): data = self.cleaned_data account = self.update account.firstname = data['firstname'] account.lastname = data['lastname'] account.save() class EditEmailProfileForm(forms.Form): firstname = forms.CharField(label='First name', max_length=100, required=False, widget=forms.TextInput(attrs={'class': 'text'})) lastname = forms.CharField(label='Last name', max_length=100, required=False, widget=forms.TextInput(attrs={'class': 'text'})) email = forms.EmailField(label='Email address', max_length=75, required=True, widget=forms.TextInput(attrs={'class': 'text'})) password = forms.CharField(label='Password', initial='', max_length=30, required=False, widget=forms.PasswordInput(attrs={'class': 'text'})) confirm_password = forms.CharField(label='Re-type password', initial='', max_length=30, required=False, widget=forms.PasswordInput(attrs={'class': 'text'})) def __init__(self, *args, **kwargs): self.update = kwargs['update'] del kwargs['update'] super(EditEmailProfileForm, self).__init__(*args, **kwargs) def clean_email(self): value = self.cleaned_data['email'] if value == self.update.email: return value try: account = Account.objects.get(email=value) except Account.DoesNotExist: pass else: raise forms.ValidationError("The email address is already used.") return value def clean(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') confirm_password = self.cleaned_data.get('confirm_password') if password or confirm_password: if password != confirm_password: self.data['password'] = '' self.data['confirm_password'] = '' raise forms.ValidationError("The Passwords don't match.") else: if len(password) < 6: self._errors['password'] = "Passwords must be at least 6 characters long." self.data['password'] = '' self.data['confirm_password'] = '' return self.cleaned_data def save(self): data = self.cleaned_data account = self.update account.email = data['email'] account.firstname = data['firstname'] account.lastname = data['lastname'] if data['password']: account.set_password(data['password']) account.save()
high
0.268139
99,823
/*- * Copyright (c) 2003-2007 Tim Kientzle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "archive_platform.h" __FBSDID("$FreeBSD$"); #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_IO_H #include <io.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include "archive.h" struct read_FILE_data { FILE *f; size_t block_size; void *buffer; char can_skip; }; static int file_close(struct archive *, void *); static ssize_t file_read(struct archive *, void *, const void **buff); static int64_t file_skip(struct archive *, void *, int64_t request); int archive_read_open_FILE(struct archive *a, FILE *f) { struct stat st; struct read_FILE_data *mine; size_t block_size = 128 * 1024; void *b; archive_clear_error(a); mine = (struct read_FILE_data *)malloc(sizeof(*mine)); b = malloc(block_size); if (mine == NULL || b == NULL) { archive_set_error(a, ENOMEM, "No memory"); free(mine); free(b); return (ARCHIVE_FATAL); } mine->block_size = block_size; mine->buffer = b; mine->f = f; /* * If we can't fstat() the file, it may just be that it's not * a file. (On some platforms, FILE * objects can wrap I/O * streams that don't support fileno()). As a result, fileno() * should be used cautiously.) */ if (fstat(fileno(mine->f), &st) == 0 && S_ISREG(st.st_mode)) { archive_read_extract_set_skip_file(a, st.st_dev, st.st_ino); /* Enable the seek optimization only for regular files. */ mine->can_skip = 1; } else mine->can_skip = 0; #if defined(__CYGWIN__) || defined(_WIN32) setmode(fileno(mine->f), O_BINARY); #endif archive_read_set_read_callback(a, file_read); archive_read_set_skip_callback(a, file_skip); archive_read_set_close_callback(a, file_close); archive_read_set_callback_data(a, mine); return (archive_read_open1(a)); } static ssize_t file_read(struct archive *a, void *client_data, const void **buff) { struct read_FILE_data *mine = (struct read_FILE_data *)client_data; size_t bytes_read; *buff = mine->buffer; bytes_read = fread(mine->buffer, 1, mine->block_size, mine->f); if (bytes_read < mine->block_size && ferror(mine->f)) { archive_set_error(a, errno, "Error reading file"); } return (bytes_read); } static int64_t file_skip(struct archive *a, void *client_data, int64_t request) { struct read_FILE_data *mine = (struct read_FILE_data *)client_data; #if HAVE_FSEEKO off_t skip = (off_t)request; #elif HAVE__FSEEKI64 int64_t skip = request; #else long skip = (long)request; #endif int skip_bits = sizeof(skip) * 8 - 1; (void)a; /* UNUSED */ /* * If we can't skip, return 0 as the amount we did step and * the caller will work around by reading and discarding. */ if (!mine->can_skip) return (0); if (request == 0) return (0); /* If request is too big for a long or an off_t, reduce it. */ if (sizeof(request) > sizeof(skip)) { int64_t max_skip = (((int64_t)1 << (skip_bits - 1)) - 1) * 2 + 1; if (request > max_skip) skip = max_skip; } #ifdef __ANDROID__ /* fileno() isn't safe on all platforms ... see above. */ if (lseek(fileno(mine->f), skip, SEEK_CUR) < 0) #elif HAVE_FSEEKO if (fseeko(mine->f, skip, SEEK_CUR) != 0) #elif HAVE__FSEEKI64 if (_fseeki64(mine->f, skip, SEEK_CUR) != 0) #else if (fseek(mine->f, skip, SEEK_CUR) != 0) #endif { mine->can_skip = 0; return (0); } return (request); } static int file_close(struct archive *a, void *client_data) { struct read_FILE_data *mine = (struct read_FILE_data *)client_data; (void)a; /* UNUSED */ free(mine->buffer); free(mine); return (ARCHIVE_OK); }
high
0.8284
99,824
----------------------------------------------------------------------- -- package body e_Jacobi_Eigen, extended precision Jacobi eigen-decomposition -- Copyright (C) 2008-2018 Jonathan S. Parker -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --------------------------------------------------------------------------- package body e_Jacobi_Eigen is Reciprocal_Epsilon : constant Real := One / e_Real_Model_Epsilon; --------------------------------- -- Get_Jacobi_Rotation_Factors -- --------------------------------- -- all underflows are OK here. -- no overflows are OK here. -- so we test for Q / P overflows by calculating P / Q procedure Get_Jacobi_Rotation_Factors (P, Q : in Real; s : out Real; tau : out Real; Delta_D : out Real) is t, Gamma : Real; -- function "/" (x, y : Real) return Real renames Divide; -- faster than stnd "/", but scarcely matters. begin s := Zero; tau := Zero; Delta_D := Zero; if Abs (Q) > e_Real_Safe_Min and then Abs (P) > e_Real_Safe_Min and then Abs (Q) < e_Real_Safe_Max and then Abs (P) < e_Real_Safe_Max then -- Following Gamma is usually the more accurate. Gamma := P / (Abs (Q) + Sqrt (P*P + Q*Q)); if Q < Zero then Gamma := -Gamma; end if; -- usual case overwhelmingly. If you scale matrix to unit Norm, -- then no overflows because Matrix norm is preserved, preventing -- large P, Q if they are not large to begin with. (So the above -- tests for < e_Real_Safe_Max would be unnecessary.) -- (Requires scaling of matrix prior to decomposition to be -- absolutely sure.) -- Should be able to do the following w/o any tests of p,q if don't care -- about quality of answer in P < e_Safe_Small, Q < e_Safe_Small limit. -- --Gamma := P / (Abs(Q) + Sqrt (P*P + Q*Q) + e_Safe_Small); --if Q < Zero then Gamma := -Gamma; end if; elsif Abs (Q) > Abs (P) then -- Abs (P) > 0 was a tested before arrival, which implies Abs (Q) > 0. t := P / Q; Gamma := t / (One + Sqrt (One + t*t)); -- Underflow OK; overflow not allowed. elsif Abs (P) >= Abs (Q) then t := Q / P; Gamma := One / (Abs (t) + Sqrt (One + t*t)); -- Underflow OK; overflow not allowed. if t < Zero then Gamma := -Gamma; end if; else return; -- must have hit some inf's. Use stnd rotation init'd above. end if; declare c : Real; begin c := Reciprocal_Sqrt (One + Gamma*Gamma); -- Cosine (ok) --c := Sqrt (One / (One + Gamma*Gamma)); -- Cosine s := c * Gamma; -- Sine tau := s / (One + c); -- -cos_minus_1_over_sin Delta_D := P * Gamma; end; end Get_Jacobi_Rotation_Factors; --------------------- -- Eigen_Decompose -- --------------------- procedure Eigen_Decompose (A : in out Matrix; Q_tr : out Matrix; Eigenvals : out Col_Vector; No_of_Sweeps_Performed : out Natural; Total_No_of_Rotations : out Natural; Start_Col : in Index := Index'First; Final_Col : in Index := Index'Last; Eigenvectors_Desired : in Boolean := False) is D : Col_Vector renames Eigenvals; Z, B : Col_Vector; Max_Allowed_No_of_Sweeps : constant Positive := 256; -- badly scaled need lots No_of_Preliminary_Sweeps : constant Positive := 14; --Reciprocal_Epsilon : constant Real := One / e_Real_Model_Epsilon; -- Good stnd setting for the effective eps is: Real'Epsilon * Two**(-2). -- Usually, Real'Epsilon := 2.0**(-50) for 15 digit Reals. Matrix_Size : constant Real_8 := Real_8(Final_Col) - Real_8(Start_Col) + 1.0; No_of_Off_Diag_Elements : constant Real_8 := 0.5*Matrix_Size*(Matrix_Size-1.0); Mean_Off_Diagonal_Element_Size : Real; s, g, h, tau : Real; -- Rutishauser variable names. Q, Delta_D : Real; Sum, Pivot, Threshold : Real; begin -- Initialize all out parameters. D renames Eigenvals. -- Q_tr starts as Identity; is rotated into set of Eigenvectors of A. Q_tr := (others => (others => Zero)); for j in Index loop Q_tr(j,j) := One; end loop; Z := (others => Zero); B := (others => Zero); D := (others => Zero); for j in Start_Col .. Final_Col loop -- assume A not all init D(j) := A(j,j); B(j) := A(j,j); end loop; No_of_Sweeps_Performed := 0; Total_No_of_Rotations := 0; if Matrix_Size <= 1.0 then return; end if; -- right answer for Size=1. Sweep: for Sweep_id in 1 .. Max_Allowed_No_of_Sweeps loop Sum := Zero; for N in Start_Col .. Final_Col-1 loop --sum off-diagonal elements for I in N+1 .. Final_Col loop Sum := Sum + Abs (A(N,I)); end loop; end loop; Mean_Off_Diagonal_Element_Size := Sum / (+No_of_Off_Diag_Elements); exit Sweep when Mean_Off_Diagonal_Element_Size < Min_Allowed_Real; if Sweep_id > No_of_Preliminary_Sweeps then Threshold := Zero; else Threshold := One * Mean_Off_Diagonal_Element_Size; end if; for N in Start_Col .. Final_Col-1 loop for I in N+1 .. Final_Col loop Pivot := A(N,I); -- Have to zero out sufficiently small A(I,N) to get convergence, -- ie, to get Off_Diag_Sum -> 0.0. -- After 4 sweeps all A(I,N) are small so that -- A(I,N) / Epsilon will never overflow. The test is -- A(I,N) / Epsilon <= Abs D(I) and A(I,N) / Epsilon <= Abs D(N). if (Sweep_id > No_of_Preliminary_Sweeps) and then (Reciprocal_Epsilon * Abs (Pivot) <= Abs D(N)) and then (Reciprocal_Epsilon * Abs (Pivot) <= Abs D(I)) then A(N,I) := Zero; elsif Abs (Pivot) > Threshold then Q := Half * (D(I) - D(N)); Get_Jacobi_Rotation_Factors (Pivot, Q, s, tau, Delta_D); -- Pivot=A(N,I) D(N) := D(N) - Delta_D; -- Locally D is only used for threshold test. D(I) := D(I) + Delta_D; Z(N) := Z(N) - Delta_D; -- Z is reinitialized to 0 each sweep, so Z Z(I) := Z(I) + Delta_D; -- sums the small d's 1st. Helps a tad. A(N,I) := Zero; for j in Start_Col .. N-1 loop g := A(j,N); h := A(j,I); A(j,N) := g-s*(h+g*tau); A(j,I) := h+s*(g-h*tau); end loop; for j in N+1 .. I-1 loop g := A(N,j); h := A(j,I); A(N,j) := g-s*(h+g*tau); A(j,I) := h+s*(g-h*tau); end loop; for j in I+1 .. Final_Col loop g := A(N,j); h := A(I,j); A(N,j) := g-s*(h+g*tau); A(I,j) := h+s*(g-h*tau); end loop; if Eigenvectors_Desired then for j in Start_Col .. Final_Col loop g := Q_tr(N,j); h := Q_tr(I,j); Q_tr(N,j) := g-s*(h+g*tau); Q_tr(I,j) := h+s*(g-h*tau); end loop; end if; Total_No_of_Rotations := Total_No_of_Rotations + 1; end if; -- if (Sweep_id > No_of_Preliminary_Sweeps) end loop; --I loop (Col) end loop; --N loop (Row) for j in Start_Col .. Final_Col loop -- assume A not all initialized B(j) := B(j) + Z(j); D(j) := B(j); Z(j) := Zero; end loop; end loop Sweep; --Sweep_id loop end Eigen_Decompose; --------------- -- Sort_Eigs -- --------------- procedure Sort_Eigs (Eigenvals : in out Col_Vector; Q_tr : in out Matrix; -- rows are the eigvectors Start_Col : in Index := Index'First; Final_Col : in Index := Index'Last; Sort_Eigvecs_Also : in Boolean := False) is Max_Eig, tmp : Real; Max_id : Index; begin if Start_Col < Final_Col then for i in Start_Col .. Final_Col-1 loop Max_Eig := Eigenvals(i); Max_id := i; for j in i+1 .. Final_Col loop if Eigenvals(j) > Max_Eig then Max_Eig := Eigenvals(j); Max_id := j; end if; end loop; tmp := Eigenvals(i); Eigenvals(i) := Max_Eig; Eigenvals(Max_id) := tmp; -- swap rows of Q_tr: if Sort_Eigvecs_Also then for k in Start_Col .. Final_Col loop tmp := Q_tr(i,k); Q_tr(i,k) := Q_tr(Max_id,k); Q_tr(Max_id,k) := tmp; end loop; end if; end loop; end if; end Sort_Eigs; end e_Jacobi_Eigen;
high
0.639715
99,825
-- Used for all testcases for MySQL driver with AdaBase.Driver.Base.MySQL; with AdaBase.Statement.Base.MySQL; package Connect is -- All specific drivers renamed to "Database_Driver" subtype Database_Driver is AdaBase.Driver.Base.MySQL.MySQL_Driver; subtype Stmt_Type is AdaBase.Statement.Base.MySQL.MySQL_statement; subtype Stmt_Type_access is AdaBase.Statement.Base.MySQL.MySQL_statement_access; DR : Database_Driver; procedure connect_database; end Connect;
medium
0.330997
99,826
prefix fibo-fnd-rel-rel: <https://spec.edmcouncil.org/fibo/ontology/FND/Relations/Relations/> prefix fibo-der-rtd-irswp: <https://spec.edmcouncil.org/fibo/DER/RateDerivatives/IRSwaps/> prefix fibo-der-drc-swp: <https://spec.edmcouncil.org/fibo/DER/DerivativesContracts/Swaps/> prefix fibo-ind-ir-ir: <https://spec.edmcouncil.org/fibo/IND/InterestRates/InterestRates/> prefix ex: <http://www.example.org/time#> prefix owl: <http://www.w3.org/2002/07/owl#> prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> prefix spin: <http://spinrdf.org/spin#> prefix xsd: <http://www.w3.org/2001/XMLSchema#> prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> prefix sp: <http://spinrdf.org/sp#> prefix fibo-test-lattice: <http://www.omg.org/spec/fibo/etc/testing/patterns/lattice#> prefix fibo-fnd-aap-agt: <https://spec.edmcouncil.org/fibo/FND/AgentsAndPeople/Agents/> prefix fibo-fnd-pty-rl: <https://spec.edmcouncil.org/fibo/FND/Parties/Roles/> prefix afn: <http://jena.apache.org/ARQ/function#> prefix fibo-fnd-utl-av: <https://spec.edmcouncil.org/fibo/ontology/FND/Utilities/AnnotationVocabulary/> prefix sm: <http://www.omg.org/techprocess/ab/SpecificationMetadata/> prefix dct: <http://purl.org/dc/terms/> ## # banner We should not make explicit references to owl:Thing SELECT DISTINCT ?error WHERE { { {?s ?p owl:Thing .} UNION {?s rdfs:subClassOf|owl:equivalentClass [?p owl:Thing]} } FILTER (REGEX (xsd:string (?s), "edmcouncil")) FILTER (?p != owl:someValuesFrom) BIND (afn:localname (?p) AS ?prop) BIND (concat ("PRODERROR:", xsd:string (?s), " has an explicit reference to owl:Thing (", ?prop, ").") AS ?error) }
high
0.50766
99,827
body { font-family: Arial, 'PT Sans', Ubuntu, Helvetica, sans-serif; color: #585858; } h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 { font-family: Arial, 'PT Sans', Ubuntu, Helvetica, sans-serif; font-weight: normal; } hr { border-color: #ccc; } a, a:hover { color: #d64513; } p { margin-bottom: 15px; } h1 { font-family: "Century Gothic", Arial, 'PT Sans', Ubuntu, Helvetica, sans-serif; font-size: 28px; } h1 small { font-size: 22px; } h2 { font-family: "Century Gothic", Arial, 'PT Sans', Ubuntu, Helvetica, sans-serif; font-size: 26px; margin: 30px 0 20px; } h2 small { font-size: 18px; } h3 { margin-top: 25px; font-size: 18px; font-weight: bold; } h3 small { font-size: 16px; } h4 { font-size: 18px; } h4 small { font-size: 14px; } h5 { font-size: 16px; } h5 small { font-size: 12px; } h6 { font-size: 14px; } h6 small { font-size: 10px; } .panel { border-radius: 10px; background: #f5f5f5; box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.2); -webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.2); } .panel-heading { border-bottom: 1px solid #ddd; color: #4d4d4d; font-size: 14px; margin: 0; } .panel-heading a { color: #4d4d4d; } .panel-body { border-top: 1px solid #fff; } .abstract { min-height: 60px; } .btn-info { border: none; background: #d64513; color: #fff; box-shadow: none; text-shadow: none; } .btn-info:hover, .btn-info:focus, .btn-info:active, .btn-info.active, .btn-info.disabled, .btn-info[disabled] { background: #a5360f; } /* woodpaul on board */ .hero-unit { text-align: center; margin: 0 0 50px; } .hero-unit h1 { font-size: 48px; text-align: center; text-shadow: 1px 1px 0px rgba(255,255,255,1); } .hero-unit h1 small { display: block; } .hero-unit .btn { margin: 0; } hr{ background-color: transparent; border-top: 1px solid #ddd; border-bottom: 1px solid #fff; } .controls-row { margin: 0 0 10px; } /* table */ .table thead th { font-family: "Century Gothic", Arial, sans-serif; text-transform: uppercase; font-weight: normal; background-color: #bc451b; color: #fff; vertical-align: middle!important; } code { padding: 1px 4px; }
high
0.91118
99,828
SqVBpYsUbtVG2zdZOL9UlzCBiAJCAWJZVuR+HCILw1+Tv1vLSLF9QS0BixSSmhhvvOw+SO0Rx1TuINAUfCxGvoNhg2dJD+lPyQQJQdXWe61arMvpLa6ZAkIBh/UdYxan5k53SSKUHidqO6hGku6XNwyU5xgigPOERD1Fwpo/jaqGD99025vSwHetuVOwrhy3ofupVFH8R01JiFE=
low
0.359431
99,829
import baseSet from './.internal/baseSet.js' /** * This method is like `set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * const object = {} * * setWith(object, '[0][1]', 'a', Object) * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer === 'function' ? customizer : undefined return object == null ? object : baseSet(object, path, value, customizer) } export default setWith
high
0.630025
99,830
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 include("${CMAKE_CURRENT_LIST_DIR}/hexl-fpgaTargets.cmake")
low
0.822762
99,831
module Facebooker class FacebookAdapter < AdapterBase def canvas_server_base "apps.facebook.com" end def api_server_base "api.facebook.com" end def www_server_base_url "www.facebook.com" end def api_rest_path "/restserver.php" end def api_key ENV['FACEBOOK_API_KEY'] || super end def secret_key ENV['FACEBOOK_SECRET_KEY'] || super end def is_for?(application_context) application_context == :facebook end def login_url_base "http://#{www_server_base_url}/login.php?api_key=#{api_key}&v=1.0" end def install_url_base "http://#{www_server_base_url}/install.php?api_key=#{api_key}&v=1.0" end end end
medium
0.71554
99,832
/****************************************************************************** * Copyright (c) 2011, Duane Merrill. All rights reserved. * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ /****************************************************************************** * Test of WarpReduce utilities ******************************************************************************/ // Ensure printing of CUDA runtime errors to console #define CUB_STDERR #include <stdio.h> #include <typeinfo> #include <cub/warp/warp_reduce.cuh> #include <cub/util_allocator.cuh> #include "test_util.h" using namespace cub; //--------------------------------------------------------------------- // Globals, constants and typedefs //--------------------------------------------------------------------- bool g_verbose = false; CachingDeviceAllocator g_allocator(true); /** * \brief WrapperFunctor (for precluding test-specialized dispatch to *Sum variants) */ template< typename OpT, int LOGICAL_WARP_THREADS> struct WrapperFunctor { OpT op; int num_valid; inline __host__ __device__ WrapperFunctor(OpT op, int num_valid) : op(op), num_valid(num_valid) {} template <typename T> inline __host__ __device__ T operator()(const T &a, const T &b) const { if (CUB_IS_DEVICE_CODE) { #if CUB_INCLUDE_DEVICE_CODE != 0 if ((cub::LaneId() % LOGICAL_WARP_THREADS) >= num_valid) { _CubLog("%s\n", "Invalid lane ID in cub::WrapperFunctor::operator()"); cub::ThreadTrap(); } #endif } return op(a, b); } }; //--------------------------------------------------------------------- // Test kernels //--------------------------------------------------------------------- /** * Generic reduction */ template < typename T, typename ReductionOp, typename WarpReduce, bool PRIMITIVE = Traits<T>::PRIMITIVE> struct DeviceTest { static __device__ __forceinline__ T Reduce( typename WarpReduce::TempStorage &temp_storage, T &data, ReductionOp &reduction_op) { return WarpReduce(temp_storage).Reduce(data, reduction_op); } static __device__ __forceinline__ T Reduce( typename WarpReduce::TempStorage &temp_storage, T &data, ReductionOp &reduction_op, const int &valid_warp_threads) { return WarpReduce(temp_storage).Reduce(data, reduction_op, valid_warp_threads); } template <typename FlagT> static __device__ __forceinline__ T HeadSegmentedReduce( typename WarpReduce::TempStorage &temp_storage, T &data, FlagT &flag, ReductionOp &reduction_op) { return WarpReduce(temp_storage).HeadSegmentedReduce(data, flag, reduction_op); } template <typename FlagT> static __device__ __forceinline__ T TailSegmentedReduce( typename WarpReduce::TempStorage &temp_storage, T &data, FlagT &flag, ReductionOp &reduction_op) { return WarpReduce(temp_storage).TailSegmentedReduce(data, flag, reduction_op); } }; /** * Summation */ template < typename T, typename WarpReduce> struct DeviceTest<T, Sum, WarpReduce, true> { static __device__ __forceinline__ T Reduce( typename WarpReduce::TempStorage &temp_storage, T &data, Sum &reduction_op) { return WarpReduce(temp_storage).Sum(data); } static __device__ __forceinline__ T Reduce( typename WarpReduce::TempStorage &temp_storage, T &data, Sum &reduction_op, const int &valid_warp_threads) { return WarpReduce(temp_storage).Sum(data, valid_warp_threads); } template <typename FlagT> static __device__ __forceinline__ T HeadSegmentedReduce( typename WarpReduce::TempStorage &temp_storage, T &data, FlagT &flag, Sum &reduction_op) { return WarpReduce(temp_storage).HeadSegmentedSum(data, flag); } template <typename FlagT> static __device__ __forceinline__ T TailSegmentedReduce( typename WarpReduce::TempStorage &temp_storage, T &data, FlagT &flag, Sum &reduction_op) { return WarpReduce(temp_storage).TailSegmentedSum(data, flag); } }; /** * Full-tile warp reduction kernel */ template < int WARPS, int LOGICAL_WARP_THREADS, typename T, typename ReductionOp> __global__ void FullWarpReduceKernel( T *d_in, T *d_out, ReductionOp reduction_op, clock_t *d_elapsed) { // Cooperative warp-reduce utility type (1 warp) typedef WarpReduce<T, LOGICAL_WARP_THREADS> WarpReduce; // Allocate temp storage in shared memory __shared__ typename WarpReduce::TempStorage temp_storage[WARPS]; // Per-thread tile data T input = d_in[threadIdx.x]; // Record elapsed clocks __threadfence_block(); // workaround to prevent clock hoisting clock_t start = clock(); __threadfence_block(); // workaround to prevent clock hoisting // Test warp reduce int warp_id = threadIdx.x / LOGICAL_WARP_THREADS; T output = DeviceTest<T, ReductionOp, WarpReduce>::Reduce( temp_storage[warp_id], input, reduction_op); // Record elapsed clocks __threadfence_block(); // workaround to prevent clock hoisting clock_t stop = clock(); __threadfence_block(); // workaround to prevent clock hoisting *d_elapsed = stop - start; // Store aggregate d_out[threadIdx.x] = (threadIdx.x % LOGICAL_WARP_THREADS == 0) ? output : input; } /** * Partially-full warp reduction kernel */ template < int WARPS, int LOGICAL_WARP_THREADS, typename T, typename ReductionOp> __global__ void PartialWarpReduceKernel( T *d_in, T *d_out, ReductionOp reduction_op, clock_t *d_elapsed, int valid_warp_threads) { // Cooperative warp-reduce utility type typedef WarpReduce<T, LOGICAL_WARP_THREADS> WarpReduce; // Allocate temp storage in shared memory __shared__ typename WarpReduce::TempStorage temp_storage[WARPS]; // Per-thread tile data T input = d_in[threadIdx.x]; // Record elapsed clocks __threadfence_block(); // workaround to prevent clock hoisting clock_t start = clock(); __threadfence_block(); // workaround to prevent clock hoisting // Test partial-warp reduce int warp_id = threadIdx.x / LOGICAL_WARP_THREADS; T output = DeviceTest<T, ReductionOp, WarpReduce>::Reduce( temp_storage[warp_id], input, reduction_op, valid_warp_threads); // Record elapsed clocks __threadfence_block(); // workaround to prevent clock hoisting clock_t stop = clock(); __threadfence_block(); // workaround to prevent clock hoisting *d_elapsed = stop - start; // Store aggregate d_out[threadIdx.x] = (threadIdx.x % LOGICAL_WARP_THREADS == 0) ? output : input; } /** * Head-based segmented warp reduction test kernel */ template < int WARPS, int LOGICAL_WARP_THREADS, typename T, typename FlagT, typename ReductionOp> __global__ void WarpHeadSegmentedReduceKernel( T *d_in, FlagT *d_head_flags, T *d_out, ReductionOp reduction_op, clock_t *d_elapsed) { // Cooperative warp-reduce utility type typedef WarpReduce<T, LOGICAL_WARP_THREADS> WarpReduce; // Allocate temp storage in shared memory __shared__ typename WarpReduce::TempStorage temp_storage[WARPS]; // Per-thread tile data T input = d_in[threadIdx.x]; FlagT head_flag = d_head_flags[threadIdx.x]; // Record elapsed clocks __threadfence_block(); // workaround to prevent clock hoisting clock_t start = clock(); __threadfence_block(); // workaround to prevent clock hoisting // Test segmented warp reduce int warp_id = threadIdx.x / LOGICAL_WARP_THREADS; T output = DeviceTest<T, ReductionOp, WarpReduce>::HeadSegmentedReduce( temp_storage[warp_id], input, head_flag, reduction_op); // Record elapsed clocks __threadfence_block(); // workaround to prevent clock hoisting clock_t stop = clock(); __threadfence_block(); // workaround to prevent clock hoisting *d_elapsed = stop - start; // Store aggregate d_out[threadIdx.x] = ((threadIdx.x % LOGICAL_WARP_THREADS == 0) || head_flag) ? output : input; } /** * Tail-based segmented warp reduction test kernel */ template < int WARPS, int LOGICAL_WARP_THREADS, typename T, typename FlagT, typename ReductionOp> __global__ void WarpTailSegmentedReduceKernel( T *d_in, FlagT *d_tail_flags, T *d_out, ReductionOp reduction_op, clock_t *d_elapsed) { // Cooperative warp-reduce utility type typedef WarpReduce<T, LOGICAL_WARP_THREADS> WarpReduce; // Allocate temp storage in shared memory __shared__ typename WarpReduce::TempStorage temp_storage[WARPS]; // Per-thread tile data T input = d_in[threadIdx.x]; FlagT tail_flag = d_tail_flags[threadIdx.x]; FlagT head_flag = (threadIdx.x == 0) ? 0 : d_tail_flags[threadIdx.x - 1]; // Record elapsed clocks __threadfence_block(); // workaround to prevent clock hoisting clock_t start = clock(); __threadfence_block(); // workaround to prevent clock hoisting // Test segmented warp reduce int warp_id = threadIdx.x / LOGICAL_WARP_THREADS; T output = DeviceTest<T, ReductionOp, WarpReduce>::TailSegmentedReduce( temp_storage[warp_id], input, tail_flag, reduction_op); // Record elapsed clocks __threadfence_block(); // workaround to prevent clock hoisting clock_t stop = clock(); __threadfence_block(); // workaround to prevent clock hoisting *d_elapsed = stop - start; // Store aggregate d_out[threadIdx.x] = ((threadIdx.x % LOGICAL_WARP_THREADS == 0) || head_flag) ? output : input; } //--------------------------------------------------------------------- // Host utility subroutines //--------------------------------------------------------------------- /** * Initialize reduction problem (and solution) */ template < typename T, typename ReductionOp> void Initialize( GenMode gen_mode, int flag_entropy, T *h_in, int *h_flags, int warps, int warp_threads, int valid_warp_threads, ReductionOp reduction_op, T *h_head_out, T *h_tail_out) { for (int i = 0; i < warps * warp_threads; ++i) { // Sample a value for this item InitValue(gen_mode, h_in[i], i); h_head_out[i] = h_in[i]; h_tail_out[i] = h_in[i]; // Sample whether or not this item will be a segment head char bits; RandomBits(bits, flag_entropy); h_flags[i] = bits & 0x1; } // Accumulate segments (lane 0 of each warp is implicitly a segment head) for (int warp = 0; warp < warps; ++warp) { int warp_offset = warp * warp_threads; int item_offset = warp_offset + valid_warp_threads - 1; // Last item in warp T head_aggregate = h_in[item_offset]; T tail_aggregate = h_in[item_offset]; if (h_flags[item_offset]) h_head_out[item_offset] = head_aggregate; item_offset--; // Work backwards while (item_offset >= warp_offset) { if (h_flags[item_offset + 1]) { head_aggregate = h_in[item_offset]; } else { head_aggregate = reduction_op(head_aggregate, h_in[item_offset]); } if (h_flags[item_offset]) { h_head_out[item_offset] = head_aggregate; h_tail_out[item_offset + 1] = tail_aggregate; tail_aggregate = h_in[item_offset]; } else { tail_aggregate = reduction_op(tail_aggregate, h_in[item_offset]); } item_offset--; } // Record last segment head_aggregate to head offset h_head_out[warp_offset] = head_aggregate; h_tail_out[warp_offset] = tail_aggregate; } } /** * Test warp reduction */ template < int WARPS, int LOGICAL_WARP_THREADS, typename T, typename ReductionOp> void TestReduce( GenMode gen_mode, ReductionOp reduction_op, int valid_warp_threads = LOGICAL_WARP_THREADS) { const int BLOCK_THREADS = LOGICAL_WARP_THREADS * WARPS; // Allocate host arrays T *h_in = new T[BLOCK_THREADS]; int *h_flags = new int[BLOCK_THREADS]; T *h_out = new T[BLOCK_THREADS]; T *h_tail_out = new T[BLOCK_THREADS]; // Initialize problem Initialize(gen_mode, -1, h_in, h_flags, WARPS, LOGICAL_WARP_THREADS, valid_warp_threads, reduction_op, h_out, h_tail_out); // Initialize/clear device arrays T *d_in = NULL; T *d_out = NULL; clock_t *d_elapsed = NULL; CubDebugExit(g_allocator.DeviceAllocate((void**)&d_in, sizeof(T) * BLOCK_THREADS)); CubDebugExit(g_allocator.DeviceAllocate((void**)&d_out, sizeof(T) * BLOCK_THREADS)); CubDebugExit(g_allocator.DeviceAllocate((void**)&d_elapsed, sizeof(clock_t))); CubDebugExit(cudaMemcpy(d_in, h_in, sizeof(T) * BLOCK_THREADS, cudaMemcpyHostToDevice)); CubDebugExit(cudaMemset(d_out, 0, sizeof(T) * BLOCK_THREADS)); if (g_verbose) { printf("Data:\n"); for (int i = 0; i < WARPS; ++i) DisplayResults(h_in + (i * LOGICAL_WARP_THREADS), valid_warp_threads); } // Run kernel printf("\nGen-mode %d, %d warps, %d warp threads, %d valid lanes, %s (%d bytes) elements:\n", gen_mode, WARPS, LOGICAL_WARP_THREADS, valid_warp_threads, typeid(T).name(), (int) sizeof(T)); fflush(stdout); if (valid_warp_threads == LOGICAL_WARP_THREADS) { // Run full-warp kernel FullWarpReduceKernel<WARPS, LOGICAL_WARP_THREADS><<<1, BLOCK_THREADS>>>( d_in, d_out, reduction_op, d_elapsed); } else { // Run partial-warp kernel PartialWarpReduceKernel<WARPS, LOGICAL_WARP_THREADS><<<1, BLOCK_THREADS>>>( d_in, d_out, reduction_op, d_elapsed, valid_warp_threads); } CubDebugExit(cudaPeekAtLastError()); CubDebugExit(cudaDeviceSynchronize()); // Copy out and display results printf("\tReduction results: "); int compare = CompareDeviceResults(h_out, d_out, BLOCK_THREADS, g_verbose, g_verbose); printf("%s\n", compare ? "FAIL" : "PASS"); AssertEquals(0, compare); printf("\tElapsed clocks: "); DisplayDeviceResults(d_elapsed, 1); // Cleanup if (h_in) delete[] h_in; if (h_flags) delete[] h_flags; if (h_out) delete[] h_out; if (h_tail_out) delete[] h_tail_out; if (d_in) CubDebugExit(g_allocator.DeviceFree(d_in)); if (d_out) CubDebugExit(g_allocator.DeviceFree(d_out)); if (d_elapsed) CubDebugExit(g_allocator.DeviceFree(d_elapsed)); } /** * Test warp segmented reduction */ template < int WARPS, int LOGICAL_WARP_THREADS, typename T, typename ReductionOp> void TestSegmentedReduce( GenMode gen_mode, int flag_entropy, ReductionOp reduction_op) { const int BLOCK_THREADS = LOGICAL_WARP_THREADS * WARPS; // Allocate host arrays int compare; T *h_in = new T[BLOCK_THREADS]; int *h_flags = new int[BLOCK_THREADS]; T *h_head_out = new T[BLOCK_THREADS]; T *h_tail_out = new T[BLOCK_THREADS]; // Initialize problem Initialize(gen_mode, flag_entropy, h_in, h_flags, WARPS, LOGICAL_WARP_THREADS, LOGICAL_WARP_THREADS, reduction_op, h_head_out, h_tail_out); // Initialize/clear device arrays T *d_in = NULL; int *d_flags = NULL; T *d_head_out = NULL; T *d_tail_out = NULL; clock_t *d_elapsed = NULL; CubDebugExit(g_allocator.DeviceAllocate((void**)&d_in, sizeof(T) * BLOCK_THREADS)); CubDebugExit(g_allocator.DeviceAllocate((void**)&d_flags, sizeof(int) * BLOCK_THREADS)); CubDebugExit(g_allocator.DeviceAllocate((void**)&d_head_out, sizeof(T) * BLOCK_THREADS)); CubDebugExit(g_allocator.DeviceAllocate((void**)&d_tail_out, sizeof(T) * BLOCK_THREADS)); CubDebugExit(g_allocator.DeviceAllocate((void**)&d_elapsed, sizeof(clock_t))); CubDebugExit(cudaMemcpy(d_in, h_in, sizeof(T) * BLOCK_THREADS, cudaMemcpyHostToDevice)); CubDebugExit(cudaMemcpy(d_flags, h_flags, sizeof(int) * BLOCK_THREADS, cudaMemcpyHostToDevice)); CubDebugExit(cudaMemset(d_head_out, 0, sizeof(T) * BLOCK_THREADS)); CubDebugExit(cudaMemset(d_tail_out, 0, sizeof(T) * BLOCK_THREADS)); if (g_verbose) { printf("Data:\n"); for (int i = 0; i < WARPS; ++i) DisplayResults(h_in + (i * LOGICAL_WARP_THREADS), LOGICAL_WARP_THREADS); printf("\nFlags:\n"); for (int i = 0; i < WARPS; ++i) DisplayResults(h_flags + (i * LOGICAL_WARP_THREADS), LOGICAL_WARP_THREADS); } printf("\nGen-mode %d, head flag entropy reduction %d, %d warps, %d warp threads, %s (%d bytes) elements:\n", gen_mode, flag_entropy, WARPS, LOGICAL_WARP_THREADS, typeid(T).name(), (int) sizeof(T)); fflush(stdout); // Run head-based kernel WarpHeadSegmentedReduceKernel<WARPS, LOGICAL_WARP_THREADS><<<1, BLOCK_THREADS>>>( d_in, d_flags, d_head_out, reduction_op, d_elapsed); CubDebugExit(cudaPeekAtLastError()); CubDebugExit(cudaDeviceSynchronize()); // Copy out and display results printf("\tHead-based segmented reduction results: "); compare = CompareDeviceResults(h_head_out, d_head_out, BLOCK_THREADS, g_verbose, g_verbose); printf("%s\n", compare ? "FAIL" : "PASS"); AssertEquals(0, compare); printf("\tElapsed clocks: "); DisplayDeviceResults(d_elapsed, 1); // Run tail-based kernel WarpTailSegmentedReduceKernel<WARPS, LOGICAL_WARP_THREADS><<<1, BLOCK_THREADS>>>( d_in, d_flags, d_tail_out, reduction_op, d_elapsed); CubDebugExit(cudaPeekAtLastError()); CubDebugExit(cudaDeviceSynchronize()); // Copy out and display results printf("\tTail-based segmented reduction results: "); compare = CompareDeviceResults(h_tail_out, d_tail_out, BLOCK_THREADS, g_verbose, g_verbose); printf("%s\n", compare ? "FAIL" : "PASS"); AssertEquals(0, compare); printf("\tElapsed clocks: "); DisplayDeviceResults(d_elapsed, 1); // Cleanup if (h_in) delete[] h_in; if (h_flags) delete[] h_flags; if (h_head_out) delete[] h_head_out; if (h_tail_out) delete[] h_tail_out; if (d_in) CubDebugExit(g_allocator.DeviceFree(d_in)); if (d_flags) CubDebugExit(g_allocator.DeviceFree(d_flags)); if (d_head_out) CubDebugExit(g_allocator.DeviceFree(d_head_out)); if (d_tail_out) CubDebugExit(g_allocator.DeviceFree(d_tail_out)); if (d_elapsed) CubDebugExit(g_allocator.DeviceFree(d_elapsed)); } /** * Run battery of tests for different full and partial tile sizes */ template < int WARPS, int LOGICAL_WARP_THREADS, typename T, typename ReductionOp> void Test( GenMode gen_mode, ReductionOp reduction_op) { // Partial tiles for ( int valid_warp_threads = 1; valid_warp_threads < LOGICAL_WARP_THREADS; valid_warp_threads += CUB_MAX(1, LOGICAL_WARP_THREADS / 5)) { // Without wrapper (to test non-excepting PTX POD-op specializations) TestReduce<WARPS, LOGICAL_WARP_THREADS, T>(gen_mode, reduction_op, valid_warp_threads); // With wrapper to ensure no ops called on OOB lanes WrapperFunctor<ReductionOp, LOGICAL_WARP_THREADS> wrapped_op(reduction_op, valid_warp_threads); TestReduce<WARPS, LOGICAL_WARP_THREADS, T>(gen_mode, wrapped_op, valid_warp_threads); } // Full tile TestReduce<WARPS, LOGICAL_WARP_THREADS, T>(gen_mode, reduction_op, LOGICAL_WARP_THREADS); // Segmented reduction with different head flags for (int flag_entropy = 0; flag_entropy < 10; ++flag_entropy) { TestSegmentedReduce<WARPS, LOGICAL_WARP_THREADS, T>(gen_mode, flag_entropy, reduction_op); } } /** * Run battery of tests for different data types and reduce ops */ template < int WARPS, int LOGICAL_WARP_THREADS> void Test(GenMode gen_mode) { // primitive Test<WARPS, LOGICAL_WARP_THREADS, char>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, short>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, int>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, long long>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, unsigned char>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, unsigned short>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, unsigned int>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, unsigned long long>( gen_mode, Sum()); if (gen_mode != RANDOM) { Test<WARPS, LOGICAL_WARP_THREADS, float>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, double>( gen_mode, Sum()); } // primitive (alternative reduce op) Test<WARPS, LOGICAL_WARP_THREADS, unsigned char>( gen_mode, Max()); Test<WARPS, LOGICAL_WARP_THREADS, unsigned short>( gen_mode, Max()); Test<WARPS, LOGICAL_WARP_THREADS, unsigned int>( gen_mode, Max()); Test<WARPS, LOGICAL_WARP_THREADS, unsigned long long>( gen_mode, Max()); // vec-1 Test<WARPS, LOGICAL_WARP_THREADS, uchar1>( gen_mode, Sum()); // vec-2 Test<WARPS, LOGICAL_WARP_THREADS, uchar2>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, ushort2>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, uint2>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, ulonglong2>( gen_mode, Sum()); // vec-4 Test<WARPS, LOGICAL_WARP_THREADS, uchar4>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, ushort4>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, uint4>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, ulonglong4>( gen_mode, Sum()); // complex Test<WARPS, LOGICAL_WARP_THREADS, TestFoo>( gen_mode, Sum()); Test<WARPS, LOGICAL_WARP_THREADS, TestBar>( gen_mode, Sum()); } /** * Run battery of tests for different problem generation options */ template < int WARPS, int LOGICAL_WARP_THREADS> void Test() { Test<WARPS, LOGICAL_WARP_THREADS>(UNIFORM); Test<WARPS, LOGICAL_WARP_THREADS>(INTEGER_SEED); Test<WARPS, LOGICAL_WARP_THREADS>(RANDOM); } /** * Run battery of tests for different number of active warps */ template <int LOGICAL_WARP_THREADS> void Test() { Test<1, LOGICAL_WARP_THREADS>(); // Only power-of-two subwarps can be tiled if ((LOGICAL_WARP_THREADS == 32) || PowerOfTwo<LOGICAL_WARP_THREADS>::VALUE) Test<2, LOGICAL_WARP_THREADS>(); } /** * Main */ int main(int argc, char** argv) { // Initialize command line CommandLineArgs args(argc, argv); g_verbose = args.CheckCmdLineFlag("v"); // Print usage if (args.CheckCmdLineFlag("help")) { printf("%s " "[--device=<device-id>] " "[--v] " "\n", argv[0]); exit(0); } // Initialize device CubDebugExit(args.DeviceInit()); // Test logical warp sizes Test<32>(); Test<16>(); Test<9>(); Test<7>(); return 0; }
high
0.791881
99,833
<!DOCTYPE html> <html lang="ru" itemscope itemtype="http://schema.org/WebPage" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# book: http://ogp.me/ns/book# video: http://ogp.me/ns/video# ya: http://webmaster.yandex.ru/vocabularies/"> <head> <title>Анатолий Рыбаков повесть &laquo;Выстрел&raquo; страница 140</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="Анатолий Рыбаков читать повесть &laquo;Выстрел&raquo; страница 140"> <meta name="keywords" content="электронные книги, электронная библиотека, книги онлайн, читать книги онлайн, библиотека, онлайн библиотека, книги онлайн бесплатно, online книги, чтение онлайн, почитать книгу онлайн, чтение книг онлайн, скачать книгу, скачать книгу бесплатно, слушать книгу онлайн, выстрел Рыбаков, выстрел Рыбакова, Анатолия Рыбакова выстрел, выстрел Рыбакова читать, выстрел Рыбаков читать, страница 140"> <meta name="robots" content="ALL"> <meta name="revisit-after" content="14 days"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> <link media="screen" rel="stylesheet" type="text/css" href="../../CSS/cmn.css"> <link media="print" rel="stylesheet" type="text/css" href="/CSS/printfmd.css"> <link rel="shortcut icon" type="image/x-icon" href="/img/rybakov/kortik3/favicon.ico"> <link rel="apple-touch-icon" sizes="57x57" href="/img/rybakov/kortik3/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/img/rybakov/kortik3/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/img/rybakov/kortik3/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/img/rybakov/kortik3/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/img/rybakov/kortik3/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/img/rybakov/kortik3/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/img/rybakov/kortik3/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/img/rybakov/kortik3/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/img/rybakov/kortik3/apple-icon-180x180.png"> <link rel="apple-touch-icon" sizes="57x57" href="/img/rybakov/kortik3/apple-touch-icon-57x57-precomposed.png"> <link rel="apple-touch-icon" sizes="60x60" href="/img/rybakov/kortik3/apple-touch-icon-60x60-precomposed.png"> <link rel="apple-touch-icon" sizes="72x72" href="/img/rybakov/kortik3/apple-touch-icon-72x72-precomposed.png"> <link rel="apple-touch-icon" sizes="76x76" href="/img/rybakov/kortik3/apple-touch-icon-76x76-precomposed.png"> <link rel="apple-touch-icon" sizes="114x114" href="/img/rybakov/kortik3/apple-touch-icon-114x114-precomposed.png"> <link rel="apple-touch-icon" sizes="120x120" href="/img/rybakov/kortik3/apple-touch-icon-120x120-precomposed.png"> <link rel="apple-touch-icon" sizes="144x144" href="/img/rybakov/kortik3/apple-touch-icon-144x144-precomposed.png"> <link rel="apple-touch-icon" sizes="152x152" href="/img/rybakov/kortik3/apple-touch-icon-152x152-precomposed.png"> <link rel="apple-touch-icon" sizes="180x180" href="/img/rybakov/kortik3/apple-touch-icon-180x180-precomposed.png"> <link rel="mask-icon" href="/img/rybakov/kortik3/safari-pinned-tab.svg" color="#f0011e"> <meta name="msapplication-config" content="/browserconfigs/vystrel.xml"> <meta name="application-name" content="повесть &laquo;Выстрел&raquo;"> <meta name="msapplication-tooltip" content="повесть Анатолия Рыбакова повесть &laquo;Выстрел&raquo;"> <meta name="msapplication-TileImage" content="/img/rybakov/kortik3/ms-icon-144x144.png"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="theme-color" content="#1e9c6e"> <meta property="fb:admins" content="100000899468660"> <meta property="fb:app_id" content="100342733820902"> <meta property="og:locale" content="ru_RU"> <meta property="og:site_name" content="Сайт посвященный Сергею Шевкуненко"> <meta property="og:url" content="https://shevkunenko.ru/rybakov/kortik-3/glava140.htm"> <meta property="og:type" content="book"> <meta property="book:author" content="https://shevkunenko.ru/rybakov/index.htm"> <meta property="og:title" content="Выстрел"> <meta property="og:description" content="Третья часть популярной детской трилогии &laquo;Кортик&raquo;, &laquo;Бронзовая птица&raquo;, &laquo;Выстрел&raquo; Анатолия Рыбакова, в которой арбатский парень Миша Поляков и его друзья помогают раскрыть таинственное убийство инженера."> <meta property="book:isbn" content="978-5-08-005471-6"> <meta property="book:tag" content="выстрел"> <meta property="book:tag" content="Рыбаков"> <meta property="og:image" content="https://shevkunenko.ru/img/rybakov/kortik3/vystrel-big.png"> <meta name="twitter:card" content="summary"> <meta name="twitter:description" content="Третья часть популярной детской трилогии &laquo;Кортик&raquo;, &laquo;Бронзовая птица&raquo;, &laquo;Выстрел&raquo; Анатолия Рыбакова, в которой арбатский парень Миша Поляков и его друзья помогают раскрыть таинственное убийство инженера."> <meta name="twitter:title" content="повесть Анатолия Рыбакова &laquo;Выстрел&raquo;"> <meta name="twitter:image" content="https://shevkunenko.ru/img/rybakov/kortik3/vystrel-big.png"> <link rel="canonical" href="https://shevkunenko.ru/rybakov/kortik-3/glava140.htm"> <link rel="manifest" href="/manifests/vystrel.json"> <script src="/JS/jquery-3.1.1.js"></script> <script src="/JS/print.js"></script> <!--[if lt IE 9]> <script> var e = ("abbr,article,aside,audio,canvas,datalist,details," + "figure,footer,header,hgroup,mark,menu,meter,nav,output," + "progress,section,time,video,summary").split(','); for (var i = 0; i < e.length; i++) { document.createElement(e[i]); } </script> <![endif]--> </head> <body id="bd"> <script src="http://ma-static.ru/sticker/27949.js"></script> <meta itemprop="description" content="Третья часть популярной детской трилогии &laquo;Кортик&raquo;, &laquo;Бронзовая птица&raquo;, &laquo;Выстрел&raquo; Анатолия Рыбакова, в которой арбатский парень Миша Поляков и его друзья помогают раскрыть таинственное убийство инженера."> <meta itemprop="image" content="https://shevkunenko.ru/img/rybakov/kortik3/vystrel.png"> <meta itemprop="lastReviewed" content="2017-03-10"> <header> <div id="tsnt"> <script async src="https://rkkvq.com/jzdek8/291/92197i129b7j79i2tq/live8k7i9f9xvqu/kpyu1ih96ldd2dcf86179f4efaa623429d5cc52d36"></script> </div> <!-- <div id="lx_511977"></div> --> <nav itemprop="breadcrumb" itemscope itemtype="http://schema.org/BreadcrumbList"> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="https://shevkunenko.site/Main2"> <span itemprop="name">ШЕВКУНЕНКО&nbsp;&rarr;</span> </a> <meta itemprop="position" content="1"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/biografy.htm"> <span itemprop="name">БИОГРАФИЯ&nbsp;&rarr;</span> </a> <meta itemprop="position" content="2"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/krfilm/index.htm"> <span itemprop="name">&laquo;КОРТИК&raquo;&nbsp;&rarr;</span> </a> <meta itemprop="position" content="3"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/krfilm/kortik.htm"> <span itemprop="name">О ФИЛЬМЕ&nbsp;&rarr;</span> </a> <meta itemprop="position" content="4"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/rybakov/index.htm"> <span itemprop="name">АНАТОЛИЙ РЫБАКОВ&nbsp;&rarr;</span> </a> <meta itemprop="position" content="5"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/rybakov/books.htm"> <span itemprop="name">КНИГИ А. РЫБАКОВА</span> </a> <meta itemprop="position" content="6"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/rybakov/kortik-3/content.htm"> <span itemprop="name">&laquo;Выстрел&raquo;</span> </a> <meta itemprop="position" content="7"> </span> </nav> </header> <div id="mnbd"> <div class="top_of_page"> <div class="pig"> <div class="pod"> <a href="/1.htm">ПОДДЕРЖАТЬ&nbsp;САЙТ</a> </div> </div> <div class="mypoisk"> <div class="ya-site-form ya-site-form_inited_no" data-bem="{&quot;action&quot;:&quot;https://yandex.ru/search/site/&quot;,&quot;arrow&quot;:false,&quot;bg&quot;:&quot;transparent&quot;,&quot;fontsize&quot;:14,&quot;fg&quot;:&quot;#000000&quot;,&quot;language&quot;:&quot;ru&quot;,&quot;logo&quot;:&quot;rb&quot;,&quot;publicname&quot;:&quot;Поиск по shevkunenko.ru&quot;,&quot;suggest&quot;:true,&quot;target&quot;:&quot;_blank&quot;,&quot;tld&quot;:&quot;ru&quot;,&quot;type&quot;:2,&quot;usebigdictionary&quot;:true,&quot;searchid&quot;:2352678,&quot;input_fg&quot;:&quot;#000000&quot;,&quot;input_bg&quot;:&quot;#ffffff&quot;,&quot;input_fontStyle&quot;:&quot;normal&quot;,&quot;input_fontWeight&quot;:&quot;normal&quot;,&quot;input_placeholder&quot;:&quot;поиск по сайту&quot;,&quot;input_placeholderColor&quot;:&quot;#333333&quot;,&quot;input_borderColor&quot;:&quot;#cc0000&quot;}"> <form action="https://yandex.ru/search/site/" method="get" target="_blank" accept-charset="utf-8"> <input type="hidden" name="searchid" value="2352678"/> <input type="hidden" name="l10n" value="ru"/> <input type="hidden" name="reqenc" value="utf-8"/> <input type="search" name="text" value=""/> <input type="submit" value="Найти"/> </form> </div> </div> <div class="sb-dn"> <div class="ya-share2" data-services="vkontakte,facebook,odnoklassniki,moimir,twitter,telegram" data-counter="ig" data-lang="ru"></div> </div> </div> <article itemscope itemtype="http://schema.org/Book"> <meta itemprop="author" content="Анатолий Рыбаков"> <meta itemprop="name" content="Выстрел"> <meta itemprop="genre" content="приключения"> <meta itemprop="publisher" content="Издательство Детской литературы"> <meta itemprop="isbn" content="978-5-08-005471-6"> <meta itemprop="datePublished" content="1975-01-01"> <meta itemprop="numberOfPages" content="240"> <meta itemprop="description" content="Третья часть популярной детской трилогии &laquo;Кортик&raquo;, &laquo;Бронзовая птица&raquo;, &laquo;Выстрел&raquo; Анатолия Рыбакова, в которой арбатский парень Миша Поляков и его друзья помогают раскрыть таинственное убийство инженера."> <header> <h1 class="nameofbook1"> <span itemprop="author" itemscope itemtype="http://schema.org/Person"> <span itemprop="givenName">Анатолий</span>&nbsp;<span itemprop="familyName">Рыбаков</span> </span> &laquo;Выстрел&raquo; </h1> </header> <section class="bookpage" itemprop="text"> <div class="text-of-book"> <p>- А кто украл портфель?</p> <p>- Я спал, когда его украли.</p> <p>- И не слыхал, как кто-то забрался в квартиру и унес портфель?</p> <p>- Не слыхал.</p> <p>- А как портфель очутился на чердаке?</p> <p>Вместо ответа Фургон пожал плечами, губы у него задрожали.</p> <p>&quot;Мучаю ребенка&quot;, - подумал Миша.</p> <p>- Слушай, Андрей, - сказал Миша, - твоего отца убил негодяй, мерзавец. Неужели ты будешь его защищать?</p> <p>- Но ведь я ничего не знаю! Меня и следователь вызывал, и мама спрашивала. А что я знаю? Я спал. Я не видел, кто стрелял.</p> <p>- Но сам ты как думаешь: Витька виноват?</p> <p>Андрей молчал.</p> <p>- Что же ты молчишь? Ты его боишься? Кого ты боишься?</p> <p>- Никого я не боюсь, - ответил Андрей, потупившись.</p> <p>- Ну, так говори!</p> <p>- Ничего я не знаю. И про Витьку не знаю: он украл или нет - не знаю.</p> <p>- А зачем ты с ним водился?</p> <p>- Я не с ним, а со Шнырой, а уж потом вместе&hellip;</p> <p>- Что вместе?</p> <p>- Ну, были вместе.</p> <p>- А револьвер ты видел у Витьки?</p> <p>- Нет.</p> <p>- Честное слово?</p> <p>- Честное слово!</p> <p>Миша смотрел на Фургона. Не может быть, чтобы врал, не похож на лгуна, неуклюжий, добродушный мальчишка, ничего в нем нет воровского, блатного, ничего хитрого, лукавого.</p> <footer class="bookfooter"> <a id="pechat" href="javascript:window.print(); void 0;" title="распечатать страницу"></a> <a id="audioon" href="audio029.htm" title="слушать online"></a> <p id="nomstr">140</p> </footer> </div> </section> <div class="nv-bk"> <a href="glava139.htm" title="переход к предыдущей странице" itemprop="url">НАЗАД</a> <a href="content.htm" title="переход к содержанию книги" itemprop="url">СОДЕРЖАНИЕ</a> <a href="glava141.htm" title="переход к следующей странице" itemprop="url">ВПЕРЕД</a> </div> </article> </div> <footer> <nav itemprop="breadcrumb" itemscope itemtype="http://schema.org/BreadcrumbList"> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="https://shevkunenko.site/Main2"> <span itemprop="name">ШЕВКУНЕНКО&nbsp;&rarr;</span> </a> <meta itemprop="position" content="1"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/biografy.htm"> <span itemprop="name">БИОГРАФИЯ&nbsp;&rarr;</span> </a> <meta itemprop="position" content="2"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/krfilm/index.htm"> <span itemprop="name">&laquo;КОРТИК&raquo;&nbsp;&rarr;</span> </a> <meta itemprop="position" content="3"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/krfilm/kortik.htm"> <span itemprop="name">О ФИЛЬМЕ&nbsp;&rarr;</span> </a> <meta itemprop="position" content="4"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/rybakov/index.htm"> <span itemprop="name">АНАТОЛИЙ РЫБАКОВ&nbsp;&rarr;</span> </a> <meta itemprop="position" content="5"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/rybakov/books.htm"> <span itemprop="name">КНИГИ А. РЫБАКОВА</span> </a> <meta itemprop="position" content="6"> </span> <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"> <a itemprop="item" href="/rybakov/kortik-3/content.htm"> <span itemprop="name">&laquo;Выстрел&raquo;</span> </a> <meta itemprop="position" content="7"> </span> </nav> <div id="teasernet"> <script>var ea7859d1be = 234661; var f750b0807311 = 500533;</script> <script async src="https://rkkvq.com/jzdek8/291/92197i129b7j79i2tq/live8k7i9f9xvqu/kpyu1ih96ldd2dcf86179f4efaa623429d5cc52d36"></script> <script src="/JS/common.js"></script> <script> let tnSubscribeOptions = { serviceWorkerRelativePath: '/tnServiceWorker.js', block: '911916'}; </script> <script async src="https://motbw.com/webpush/pushSubscribe.js"></script> </div> </footer> <script type="text/javascript">var b4c089e0f95 = 234661; var c0c1bb66d2295f = 911449;</script> <script type="text/javascript" src="/JS/4ca466.js"></script> </body> </html> <!-- 5 mrY mrG -->
low
0.858078
99,834
{-# OPTIONS --without-K --safe #-} module Algebra.Structures.Bundles.Field where open import Algebra open import Level using (suc; _⊔_) open import Relation.Binary using (Rel) open import Algebra.Structures.Field record Field c ℓ : Set (suc (c ⊔ ℓ)) where field Carrier : Set c _≈_ : Rel Carrier ℓ _+_ : Carrier -> Carrier -> Carrier _*_ : Carrier -> Carrier -> Carrier 0# : Carrier 1# : Carrier -_ : Carrier -> Carrier _⁻¹ : MultiplicativeInverse _≈_ 0# isField : IsField _≈_ _+_ _*_ 0# 1# -_ _⁻¹ open IsField isField public
high
0.557676
99,835
# This file must be used with "source bin/activate.csh" *from csh*. # You cannot run it directly. # Created by Davide Di Blasi <davidedb@gmail.com>. alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate && unalias pydoc' # Unset irrelevant variables. deactivate nondestructive setenv VIRTUAL_ENV "/home/hinkeu/hincode/matchmaker" set _OLD_VIRTUAL_PATH="$PATH" setenv PATH "$VIRTUAL_ENV/bin:$PATH" if ("" != "") then set env_name = "" else set env_name = `basename "$VIRTUAL_ENV"` endif # Could be in a non-interactive environment, # in which case, $prompt is undefined and we wouldn't # care about the prompt anyway. if ( $?prompt ) then set _OLD_VIRTUAL_PROMPT="$prompt" set prompt = "[$env_name] $prompt" endif unset env_name alias pydoc python -m pydoc rehash
low
1
99,836
// ---------------------------------------------------------------- // Small, directed tests for the various functions in PAClib // // Please comment out all except one test in mkTb_PAClib // ---------------------------------------------------------------- // Import standard BSV libs import LFSR::*; import Vector::*; import FIFO::*; import FIFOF::*; import SpecialFIFOs :: *; import GetPut::*; import ClientServer::*; import CompletionBuffer :: *; import PAClib::*; import Common::*; // ---------------------------------------------------------------- // ================================================================ // Test mkSource_from_fav, mkFn_to_Pipe_SynchBuffered, mkSynchBuffer, mkSink_to_fa (* synthesize *) module [Module] sysSynchPipe (Empty); Integer n_samples = 8; Reg #(int) x <- mkReg (2); function ActionValue #(int) next_int (); actionvalue x <= x + 1; return x; endactionvalue endfunction PipeOut #(int) po1 <- mkSource_from_fav (next_int); function int square (int y) = y * y; PipeOut #(int) po2 <- mkFn_to_Pipe_SynchBuffered (tagged Valid (1), square, tagged Valid (0), po1); Reg #(int) xx <- mkReg (0); function Action showint (int z); action $display ("%0t: sinking %0d", cyclenum(), z); if ((xx * xx) != z) begin $display ("Cycle %0d: Test fail: mkTestSynchPipe", cyclenum ()); $finish; end if (xx == fromInteger (n_samples - 1)) begin $display ("Cycle %0d: Test ok: mkTestSynchPipe: all %0d outputs ok", cyclenum (), n_samples); $finish; end xx <= xx + 1; endaction endfunction let emptyifc <- mkSink_to_fa (showint, po2); return emptyifc; endmodule
low
0.285885
99,838
# Graphs A simple implementation of some Graph algorithms :) A school work. ![Graphs](./screenshots/graphs.png) To run this project just type `./scripts/run.sh` ou just `make && ./graphs`.
medium
0.30036
99,839
module Minecraft.Base.PreClassic.Cobblestone.Item.Export import public Minecraft.Core.Entity.Pickup.Export import public Minecraft.Base.PreClassic.Cobblestone.Block import public Minecraft.Base.PreClassic.Cobblestone.Item import public Minecraft.Base.PreClassic.Cobblestone.ItemEntity %default total [cobblestoneItem'] Item Cobblestone.Item where id = "minecraft:cobblestone" stackable = Just 64 givenName = \x => x.base.givenName proj = \x => new Cobblestone.ItemEntity Cobblestone.MkItemEntity [putCobblestone'] Put Cobblestone.Item where putItem self = new Cobblestone.Block Cobblestone.MkBlock [cobblestoneVtbl'] Vtbl Cobblestone.Item where vtable (Item Cobblestone.Item) = Just cobblestoneItem vtable (Put Cobblestone.Item) = Just putCobblestone vtable _ = Nothing cobblestoneItem = cobblestoneItem' putCobblestone = putCobblestone' cobblestoneVtbl = cobblestoneVtbl'
high
0.48472
99,840
<?php namespace Google\AdsApi\AdWords\v201705\cm; /** * This file was generated from WSDL. DO NOT EDIT. */ class BiddingStrategyReturnValue extends \Google\AdsApi\AdWords\v201705\cm\ListReturnValue { /** * @var \Google\AdsApi\AdWords\v201705\cm\SharedBiddingStrategy[] $value */ protected $value = null; /** * @param string $ListReturnValueType * @param \Google\AdsApi\AdWords\v201705\cm\SharedBiddingStrategy[] $value */ public function __construct($ListReturnValueType = null, array $value = null) { parent::__construct($ListReturnValueType); $this->value = $value; } /** * @return \Google\AdsApi\AdWords\v201705\cm\SharedBiddingStrategy[] */ public function getValue() { return $this->value; } /** * @param \Google\AdsApi\AdWords\v201705\cm\SharedBiddingStrategy[] $value * @return \Google\AdsApi\AdWords\v201705\cm\BiddingStrategyReturnValue */ public function setValue(array $value) { $this->value = $value; return $this; } }
medium
0.476183
99,841
#include "common.vert" layout (triangles) in; layout (triangle_strip, max_vertices = 3) out; in VertexData { vec3 normal; int tex_offset; vec3 color; int instance_id; } VertexIn[]; uniform samplerBuffer tex_transforms; uniform usamplerBuffer tex_colorIDs; uniform usamplerBuffer tex_colors; out vert_color { vec3 diffuse; } OutColor; void main() { const mat4 m = mat4(texelFetch(tex_transforms, (VertexIn[0].tex_offset+VertexIn[0].instance_id)*3+0), texelFetch(tex_transforms, (VertexIn[0].tex_offset+VertexIn[0].instance_id)*3+1), texelFetch(tex_transforms, (VertexIn[0].tex_offset+VertexIn[0].instance_id)*3+2), vec4(0.0f, 0.0f, 0.0f, 1.0f)); // int color_id = int(texelFetch(tex_colorIDs, in_tex_offset+gl_InstanceID).r); // OutColor.diffuse = texelFetch(tex_colors, color_id).rgb * vec3(0.00392156862745f); OutColor.diffuse = VertexIn[0].color; for(int i = 0; i < 3; i++) { gl_Position = default_transform_t(gl_in[i].gl_Position.xyz, VertexIn[i].normal, m); EmitVertex(); } EndPrimitive(); }
high
0.263827
99,842
/* -- MAGMA (version 2.1.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date August 2016 @generated from sparse-iter/blas/ziteric.cu, normal z -> d, Tue Aug 30 09:38:46 2016 */ #include "magmasparse_internal.h" #define PRECISION_d __global__ void magma_diteric_csr_kernel( magma_int_t n, magma_int_t nnz, magma_index_t *Arowidx, magma_index_t *Acolidx, const double * __restrict__ A_val, magma_index_t *rowptr, magma_index_t *colidx, double *val ) { int i, j; int k = (blockDim.x * blockIdx.x + threadIdx.x); // % nnz; double zero = MAGMA_D_MAKE(0.0, 0.0); double s, sp; int il, iu, jl, ju; if ( k < nnz ) { i = Arowidx[k]; j = Acolidx[k]; #if (__CUDA_ARCH__ >= 350) && (defined(PRECISION_d) || defined(PRECISION_s)) s = __ldg( A_val+k ); #else s = A_val[k]; #endif il = rowptr[i]; iu = rowptr[j]; while (il < rowptr[i+1] && iu < rowptr[j+1]) { sp = zero; jl = colidx[il]; ju = colidx[iu]; if (jl < ju) il++; else if (ju < jl) iu++; else { // we are going to modify this u entry sp = val[il] * val[iu]; s -= sp; il++; iu++; } } // undo the last operation (it must be the last) s += sp; __syncthreads(); // modify entry if (i == j) val[il-1] = MAGMA_D_MAKE( sqrt( fabs( MAGMA_D_REAL(s) )), 0.0 ); else val[il-1] = s / val[iu-1]; } }// kernel /** Purpose ------- This routine iteratively computes an incomplete Cholesky factorization. The idea is according to Edmond Chow's presentation at SIAM 2014. This routine was used in the ISC 2015 paper: E. Chow et al.: 'Study of an Asynchronous Iterative Algorithm for Computing Incomplete Factorizations on GPUs' The input format of the initial guess matrix A is Magma_CSRCOO, A_CSR is CSR or CSRCOO format. Arguments --------- @param[in] A magma_d_matrix input matrix A - initial guess (lower triangular) @param[in,out] A_CSR magma_d_matrix input/output matrix containing the IC approximation @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_dgegpuk ********************************************************************/ extern "C" magma_int_t magma_diteric_csr( magma_d_matrix A, magma_d_matrix A_CSR, magma_queue_t queue ) { int blocksize1 = 128; int blocksize2 = 1; int dimgrid1 = magma_ceildiv( A.nnz, blocksize1 ); int dimgrid2 = 1; int dimgrid3 = 1; // Runtime API // cudaFuncCachePreferShared: shared memory is 48 KB // cudaFuncCachePreferEqual: shared memory is 32 KB // cudaFuncCachePreferL1: shared memory is 16 KB // cudaFuncCachePreferNone: no preference //cudaFuncSetCacheConfig(cudaFuncCachePreferShared); cudaDeviceSetCacheConfig( cudaFuncCachePreferL1 ); dim3 grid( dimgrid1, dimgrid2, dimgrid3 ); dim3 block( blocksize1, blocksize2, 1 ); magma_diteric_csr_kernel<<< grid, block, 0, queue->cuda_stream() >>> ( A.num_rows, A.nnz, A.rowidx, A.col, A.val, A_CSR.row, A_CSR.col, A_CSR.val ); return MAGMA_SUCCESS; }
high
0.724534
99,843
----------------------------------- -- Area: Mhaura -- NPC: Dieh Yamilsiah -- Reports the time remaining before boat arrival. -- !pos 7.057 -2.364 2.489 249 ----------------------------------- local ID = require("scripts/zones/Mhaura/IDs") require("scripts/globals/transport") ----------------------------------- local messages = { [tpz.transport.trigger.mhaura.FERRY_ARRIVING_FROM_ALZAHBI] = ID.text.FERRY_ARRIVING, [tpz.transport.trigger.mhaura.FERRY_DEPARTING_TO_ALZAHBI] = ID.text.FERRY_DEPARTING, [tpz.transport.trigger.mhaura.FERRY_ARRIVING_FROM_SELBINA] = ID.text.FERRY_ARRIVING, [tpz.transport.trigger.mhaura.FERRY_DEPARTING_TO_SELBINA] = ID.text.FERRY_DEPARTING } function onSpawn(npc) npc:initNpcAi() -- TODO: NPC needs to rotate after finishing walking. npc:addPeriodicTrigger(tpz.transport.trigger.mhaura.FERRY_ARRIVING_FROM_ALZAHBI, tpz.transport.interval.mhaura.FROM_TO_ALZAHBI, tpz.transport.offset.mhaura.FERRY_ARRIVING_FROM_ALZAHBI) npc:addPeriodicTrigger(tpz.transport.trigger.mhaura.FERRY_DEPARTING_TO_ALZAHBI, tpz.transport.interval.mhaura.FROM_TO_ALZAHBI, tpz.transport.offset.mhaura.FERRY_DEPARTING_TO_ALZAHBI) npc:addPeriodicTrigger(tpz.transport.trigger.mhaura.FERRY_ARRIVING_FROM_SELBINA, tpz.transport.interval.mhaura.FROM_TO_SELBINA, tpz.transport.offset.mhaura.FERRY_ARRIVING_FROM_SELBINA) npc:addPeriodicTrigger(tpz.transport.trigger.mhaura.FERRY_DEPARTING_TO_SELBINA, tpz.transport.interval.mhaura.FROM_TO_SELBINA, tpz.transport.offset.mhaura.FERRY_DEPARTING_TO_SELBINA) end function onTimeTrigger(npc, triggerID) tpz.transport.dockMessage(npc, triggerID, messages, 'mhaura') end function onTrade(player, npc, trade) end function onTrigger(player, npc) -- Each boat comes every 1152 seconds/8 game hours, 4 hour offset between Selbina and Aht Urghan -- Original timer: local timer = 1152 - ((os.time() - 1009810584)%1152) local timer = 1152 - ((os.time() - 1009810802)%1152) local destination = 0 -- Selbina, set to 1 for Al Zhabi local direction = 0 -- Arrive, 1 for depart local waiting = 216 -- Offset for Selbina -- Next ferry is Al Zhabi for higher values. if (timer >= 576) then destination = 1 timer = timer - 576 waiting = 193 end -- Logic to manipulate cutscene results. if (timer <= waiting) then direction = 1 -- Ship arrived, switch dialog from "arrive" to "depart" else timer = timer - waiting -- Ship hasn't arrived, subtract waiting time to get time to arrival end player:startEvent(231, timer, direction, 0, destination) -- timer arriving/departing ??? destination --[[Other cutscenes: 233 "This ship is headed for Selbina." 234 "The Selbina ferry will deparrrt soon! Passengers are to board the ship immediately!" Can't find a way to toggle the destination on 233 or 234, so they are not used. Users knowing which ferry is which > using all CSs.]] end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
medium
0.561514
99,844
/* * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ syntax = "proto2"; package goosci; option java_package = "com.google.android.apps.forscience.whistlepunk.data"; option java_outer_classname = "GoosciSensorSpec"; option objc_class_prefix = "GSJ"; option optimize_for = LITE_RUNTIME; import "basic_sensor_appearance.proto"; import "gadget_info.proto"; // Specification of an observable sensor. // Added in V2 message SensorSpec { // Provider, address, hostid, etc. optional GadgetInfo info = 1; // Opaque to Science Journal, but meaningful to each SensorDiscoverer. // Each SensorDiscoverer can place whatever proto it wants here that contains all the // information it needs, beyond the address, to connect to, configure, // and relay data from a particular sensor in a particular configuration. optional bytes config = 2; // contains all of the data necessary to display a sensor as part of a trial optional BasicSensorAppearance rememberedAppearance = 3; };
high
0.846897
99,845
pragma solidity ^0.5.0; import "../TokenCrowdsale.sol"; /** * @title TokenCrowdsaleTester is a crowdsale with time-travel features. * This is used to test the crowdsale contract. */ contract TokenCrowdsaleTester is TokenCrowdsale { constructor( TokenTemplate _tokenToGive, TokenTemplate _tokenToAccept, uint256 _start, uint256 _end, uint256 _acceptRatio, uint256 _giveRatio, uint256 _maxCap, address _owner ) TokenCrowdsale( _tokenToGive, _tokenToAccept, _start, _end, _acceptRatio, _giveRatio, _maxCap, _owner ) public { } /** * @dev Allows to go back and forth in time, this is used to test start and end * of a crowdsale. Actually moves start and end of the crowdsale, but * it's good for our purposes. * using int256 may have overflow / underflow errors. */ function timeTravel(int256 _timeSpan) public { uint256 span; if (_timeSpan > 0) { span = uint256(_timeSpan); start -= span; end -= span; } else { span = uint256(-_timeSpan); start += span; end += span; } } }
high
0.699391
99,846
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // RISC-V Platform-Level Interrupt Controller compliant INTC // // Current version doesn't support MSI interrupt but it is easy to add // the feature. Create one external register and connect qe signal to the // gateway module (as edge-triggered) // // Consider to set MAX_PRIO as small number as possible. It is main factor // of area increase if edge-triggered counter isn't implemented. // // verilog parameter // MAX_PRIO: Maximum value of interrupt priority module rv_plic import rv_plic_reg_pkg::*; #( parameter FIND_MAX = "SEQUENTIAL", // SEQUENTIAL | MATRIX // derived parameter localparam int SRCW = $clog2(NumSrc+1) ) ( input clk_i, input rst_ni, // Bus Interface (device) input tlul_pkg::tl_h2d_t tl_i, output tlul_pkg::tl_d2h_t tl_o, // Interrupt Sources input [NumSrc-1:0] intr_src_i, // Interrupt notification to targets output [NumTarget-1:0] irq_o, output [SRCW-1:0] irq_id_o [NumTarget], output logic [NumTarget-1:0] msip_o ); import rv_plic_reg_pkg::*; rv_plic_reg2hw_t reg2hw; rv_plic_hw2reg_t hw2reg; localparam int MAX_PRIO = 7; localparam int PRIOW = $clog2(MAX_PRIO+1); logic [NumSrc-1:0] le; // 0:level 1:edge logic [NumSrc-1:0] ip; logic [NumSrc-1:0] ie [NumTarget]; logic [NumTarget-1:0] claim_re; // Target read indicator logic [SRCW-1:0] claim_id [NumTarget]; logic [NumSrc-1:0] claim; // Converted from claim_re/claim_id logic [NumTarget-1:0] complete_we; // Target write indicator logic [SRCW-1:0] complete_id [NumTarget]; logic [NumSrc-1:0] complete; // Converted from complete_re/complete_id logic [SRCW-1:0] cc_id [NumTarget]; // Write ID logic [PRIOW-1:0] prio [NumSrc]; logic [PRIOW-1:0] threshold [NumTarget]; // Glue logic between rv_plic_reg_top and others assign cc_id = irq_id_o; always_comb begin claim = '0; for (int i = 0 ; i < NumTarget ; i++) begin if (claim_re[i]) claim[claim_id[i] -1] = 1'b1; end end always_comb begin complete = '0; for (int i = 0 ; i < NumTarget ; i++) begin if (complete_we[i]) complete[complete_id[i] -1] = 1'b1; end end //`ASSERT_PULSE(claimPulse, claim_re[i], clk_i, !rst_ni) //`ASSERT_PULSE(completePulse, complete_we[i], clk_i, !rst_ni) `ASSERT(onehot0Claim, $onehot0(claim_re), clk_i, !rst_ni) `ASSERT(onehot0Complete, $onehot0(complete_we), clk_i, !rst_ni) ////////////// // Priority // ////////////// assign prio[0] = reg2hw.prio0.q; assign prio[1] = reg2hw.prio1.q; assign prio[2] = reg2hw.prio2.q; assign prio[3] = reg2hw.prio3.q; assign prio[4] = reg2hw.prio4.q; assign prio[5] = reg2hw.prio5.q; assign prio[6] = reg2hw.prio6.q; assign prio[7] = reg2hw.prio7.q; assign prio[8] = reg2hw.prio8.q; assign prio[9] = reg2hw.prio9.q; assign prio[10] = reg2hw.prio10.q; assign prio[11] = reg2hw.prio11.q; assign prio[12] = reg2hw.prio12.q; assign prio[13] = reg2hw.prio13.q; assign prio[14] = reg2hw.prio14.q; assign prio[15] = reg2hw.prio15.q; assign prio[16] = reg2hw.prio16.q; assign prio[17] = reg2hw.prio17.q; assign prio[18] = reg2hw.prio18.q; assign prio[19] = reg2hw.prio19.q; assign prio[20] = reg2hw.prio20.q; assign prio[21] = reg2hw.prio21.q; assign prio[22] = reg2hw.prio22.q; assign prio[23] = reg2hw.prio23.q; assign prio[24] = reg2hw.prio24.q; assign prio[25] = reg2hw.prio25.q; assign prio[26] = reg2hw.prio26.q; assign prio[27] = reg2hw.prio27.q; assign prio[28] = reg2hw.prio28.q; assign prio[29] = reg2hw.prio29.q; assign prio[30] = reg2hw.prio30.q; assign prio[31] = reg2hw.prio31.q; assign prio[32] = reg2hw.prio32.q; assign prio[33] = reg2hw.prio33.q; assign prio[34] = reg2hw.prio34.q; assign prio[35] = reg2hw.prio35.q; assign prio[36] = reg2hw.prio36.q; assign prio[37] = reg2hw.prio37.q; assign prio[38] = reg2hw.prio38.q; assign prio[39] = reg2hw.prio39.q; assign prio[40] = reg2hw.prio40.q; assign prio[41] = reg2hw.prio41.q; assign prio[42] = reg2hw.prio42.q; assign prio[43] = reg2hw.prio43.q; assign prio[44] = reg2hw.prio44.q; assign prio[45] = reg2hw.prio45.q; assign prio[46] = reg2hw.prio46.q; assign prio[47] = reg2hw.prio47.q; assign prio[48] = reg2hw.prio48.q; assign prio[49] = reg2hw.prio49.q; assign prio[50] = reg2hw.prio50.q; assign prio[51] = reg2hw.prio51.q; assign prio[52] = reg2hw.prio52.q; assign prio[53] = reg2hw.prio53.q; assign prio[54] = reg2hw.prio54.q; ////////////////////// // Interrupt Enable // ////////////////////// for (genvar s = 0; s < 55; s++) begin : gen_ie0 assign ie[0][s] = reg2hw.ie0[s].q; end //////////////////////// // THRESHOLD register // //////////////////////// assign threshold[0] = reg2hw.threshold0.q; ///////////////// // CC register // ///////////////// assign claim_re[0] = reg2hw.cc0.re; assign claim_id[0] = irq_id_o[0]; assign complete_we[0] = reg2hw.cc0.qe; assign complete_id[0] = reg2hw.cc0.q; assign hw2reg.cc0.d = cc_id[0]; /////////////////// // MSIP register // /////////////////// assign msip_o[0] = reg2hw.msip0.q; //////// // IP // //////// for (genvar s = 0; s < 55; s++) begin : gen_ip assign hw2reg.ip[s].de = 1'b1; // Always write assign hw2reg.ip[s].d = ip[s]; end /////////////////////////////////// // Detection:: 0: Level, 1: Edge // /////////////////////////////////// for (genvar s = 0; s < 55; s++) begin : gen_le assign le[s] = reg2hw.le[s].q; end ////////////// // Gateways // ////////////// rv_plic_gateway #( .N_SOURCE (NumSrc) ) u_gateway ( .clk_i, .rst_ni, .src (intr_src_i), .le, .claim, .complete, .ip ); /////////////////////////////////// // Target interrupt notification // /////////////////////////////////// for (genvar i = 0 ; i < NumTarget ; i++) begin : gen_target rv_plic_target #( .N_SOURCE (NumSrc), .MAX_PRIO (MAX_PRIO), .ALGORITHM(FIND_MAX) ) u_target ( .clk_i, .rst_ni, .ip, .ie (ie[i]), .prio, .threshold (threshold[i]), .irq (irq_o[i]), .irq_id (irq_id_o[i]) ); end //////////////////////// // Register interface // //////////////////////// // Limitation of register tool prevents the module from having flexibility to parameters // So, signals are manually tied at the top. rv_plic_reg_top u_reg ( .clk_i, .rst_ni, .tl_i, .tl_o, .reg2hw, .hw2reg, .devmode_i (1'b1) ); // Assertions `ASSERT_KNOWN(TlDValidKnownO_A, tl_o.d_valid, clk_i, !rst_ni) `ASSERT_KNOWN(TlAReadyKnownO_A, tl_o.a_ready, clk_i, !rst_ni) `ASSERT_KNOWN(IrqKnownO_A, irq_o, clk_i, !rst_ni) `ASSERT_KNOWN(MsipKnownO_A, msip_o, clk_i, !rst_ni) for (genvar k = 0; k < NumTarget; k++) begin : gen_irq_id_known `ASSERT_KNOWN(IrqIdKnownO_A, irq_id_o[k], clk_i, !rst_ni) end endmodule
high
0.776815
99,847
data { real<lower=0> v; real<lower=0> alpha; int<lower=2> total_count; int y[4]; // multinomial observations } parameters { simplex[4] phi; simplex[4] theta; } model { phi ~ dirichlet(rep_vector(alpha, 4)); theta ~ dirichlet(1 + phi * v); y ~ multinomial(theta); } generated quantities { vector[4] theta_hat = dirichlet_rng(phi * v); int y_hat[4] = multinomial_rng(theta, total_count); }
high
0.576501
99,848
test-actionlib_tutorials/ testactionlib_tutorials_AveragingActionFeedback | definition | definition := browser type: 'actionlib_tutorials/AveragingActionFeedback'. self assert: definition typeName = 'actionlib_tutorials/AveragingActionFeedback'. self assert: definition md5Sum = '78a4a09241b1791069223ae7ebd5b16b'.
low
0.935706
99,849
#### Description: Normalize raw counts for density graph. Collect data in case input was parallelized. #### Written by: OD function abs(value) { return (value<0?-value:value); } BEGIN { PK = P0 + (P1 * log(K)) } # read in the cprops { if (FILENAME==ARGV[1]) { cname[$1]=$2 clength[$2]=$3 next } } # read in current assembly { if (FILENAME==ARGV[2]) { n=split($0,a) slength[FNR]=0 for (k=1; k<=n; k++) { slist[abs(a[k])]=FNR shift[abs(a[k])]=slength[FNR] slength[FNR]+=clength[abs(a[k])] } next } } # read in the sorted score stdin { if (($1!=prev1 || $2!=prev2 || $3!=prev3) && FNR!=1) { print prev1, prev2, prev3, score - (count * PK), count score = 0 count = 0 } prev1=$1; prev2=$2; prev3=$3 score += $4 count += $5 } END{ if (prev1) { print prev1, prev2, prev3, score - (count * PK), count } }
low
0.542431
99,850
import { MaybeArray } from './helpers'; export function isArray<T>(o: MaybeArray<T>): o is Array<T> { return Array.isArray(o); } export const isObject = (o: any) => !isArray(o) && typeof o === 'object' && o !== null && o !== undefined;
high
0.720808
99,851
setx DATABASE_URL "postgres://kskeem:test123@localhost:5432/helloworld" call mvn clean package java -jar target/dependency/jetty-runner.jar --port 8081 target/*.war
low
0.577171
99,852
-- Copyright 1986-2019 Xilinx, Inc. All Rights Reserved. -- -------------------------------------------------------------------------------- -- Tool Version: Vivado v.2019.1 (win64) Build 2552052 Fri May 24 14:49:42 MDT 2019 -- Date : Tue Aug 24 23:23:04 2021 -- Host : BrunoDev running 64-bit major release (build 9200) -- Command : write_vhdl -force -mode synth_stub -rename_top decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix -prefix -- decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix_ bd_0_hls_inst_0_stub.vhdl -- Design : bd_0_hls_inst_0 -- Purpose : Stub declaration of top-level module interface -- Device : xc7z010clg400-1 -- -------------------------------------------------------------------------------- library IEEE; use IEEE.STD_LOGIC_1164.ALL; entity decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix is Port ( ap_clk : in STD_LOGIC; ap_rst_n : in STD_LOGIC; src_TVALID : in STD_LOGIC; src_TREADY : out STD_LOGIC; src_TDATA : in STD_LOGIC_VECTOR ( 31 downto 0 ); src_TLAST : in STD_LOGIC_VECTOR ( 0 to 0 ); dst_TVALID : out STD_LOGIC; dst_TREADY : in STD_LOGIC; dst_TDATA : out STD_LOGIC_VECTOR ( 31 downto 0 ); dst_TLAST : out STD_LOGIC_VECTOR ( 0 to 0 ) ); end decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix; architecture stub of decalper_eb_ot_sdeen_pot_pi_dehcac_xnilix is attribute syn_black_box : boolean; attribute black_box_pad_pin : string; attribute syn_black_box of stub : architecture is true; attribute black_box_pad_pin of stub : architecture is "ap_clk,ap_rst_n,src_TVALID,src_TREADY,src_TDATA[31:0],src_TLAST[0:0],dst_TVALID,dst_TREADY,dst_TDATA[31:0],dst_TLAST[0:0]"; attribute X_CORE_INFO : string; attribute X_CORE_INFO of stub : architecture is "convolution_network,Vivado 2019.1"; begin end;
low
0.924084
99,853
namespace JetBrains.ReSharper.Plugins.FSharp.Psi.Features.Daemon.Analyzers open JetBrains.ReSharper.Feature.Services.Daemon open JetBrains.ReSharper.Plugins.FSharp.Psi.Features.Daemon.Highlightings.Errors open JetBrains.ReSharper.Plugins.FSharp.Psi.Tree // todo: add for nested patterns like `1 :: 2 :: []` // todo: add for expressions [<ElementProblemAnalyzer([| typeof<IListConsPat> |], HighlightingTypes = [| typeof<ConsWithEmptyListPatWarning> |])>] type ListConsPatAnalyzer() = inherit ElementProblemAnalyzer<IListConsPat>() override x.Run(consPat, _, consumer) = let listPat = consPat.TailPattern.As<IListPat>() if isNotNull listPat && listPat.Patterns.IsEmpty then consumer.AddHighlighting(ConsWithEmptyListPatWarning(consPat))
high
0.439184
99,854
module Page exposing (Msg(..), Page(..), current, subscriptions, update, view) import Data.Comment exposing (Comment) import Data.Post exposing (Post) import Data.Session exposing (Session) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Page.Home import Page.Login import Page.NewPost import Page.Register import Page.ShowPost import Ui.Page import Update.Deep exposing (..) type Msg = HomePageMsg Page.Home.Msg | NewPostPageMsg Page.NewPost.Msg | ShowPostPageMsg Page.ShowPost.Msg | LoginPageMsg Page.Login.Msg | RegisterPageMsg Page.Register.Msg type Page = HomePage Page.Home.State | NewPostPage Page.NewPost.State | ShowPostPage Page.ShowPost.State | LoginPage Page.Login.State | RegisterPage Page.Register.State | AboutPage | NotFoundPage current : Page -> { isHomePage : Bool, isNewPostPage : Bool, isShowPostPage : Bool, isLoginPage : Bool, isRegisterPage : Bool, isAboutPage : Bool, isNotFoundPage : Bool } current page = let none = { isHomePage = False, isNewPostPage = False, isShowPostPage = False, isLoginPage = False, isRegisterPage = False, isAboutPage = False, isNotFoundPage = False } in case page of HomePage _ -> { none | isHomePage = True } NewPostPage _ -> { none | isNewPostPage = True } ShowPostPage _ -> { none | isShowPostPage = True } LoginPage _ -> { none | isLoginPage = True } RegisterPage _ -> { none | isRegisterPage = True } AboutPage -> { none | isAboutPage = True } NotFoundPage -> { none | isNotFoundPage = True } update : { onAuthResponse : Maybe Session -> a , onPostAdded : Post -> a , onCommentCreated : Comment -> a } -> Msg -> Page -> Update Page Msg a update { onAuthResponse, onPostAdded, onCommentCreated } msg page = case ( page, msg ) of ( HomePage homePageState, HomePageMsg homeMsg ) -> homePageState |> Page.Home.update homeMsg |> Update.Deep.map HomePage |> mapCmd HomePageMsg ( NewPostPage newPostPageState, NewPostPageMsg newPostMsg ) -> newPostPageState |> Page.NewPost.update { onPostAdded = onPostAdded } newPostMsg |> Update.Deep.map NewPostPage |> mapCmd NewPostPageMsg ( ShowPostPage showPostPageState, ShowPostPageMsg showPostMsg ) -> showPostPageState |> Page.ShowPost.update { onCommentCreated = onCommentCreated } showPostMsg |> Update.Deep.map ShowPostPage |> mapCmd ShowPostPageMsg ( LoginPage loginPageState, LoginPageMsg loginMsg ) -> loginPageState |> Page.Login.update { onAuthResponse = onAuthResponse } loginMsg |> Update.Deep.map LoginPage |> mapCmd LoginPageMsg ( RegisterPage registerPageState, RegisterPageMsg registerMsg ) -> registerPageState |> Page.Register.update registerMsg |> Update.Deep.map RegisterPage |> mapCmd RegisterPageMsg _ -> save page subscriptions : Page -> (Msg -> msg) -> Sub msg subscriptions page toMsg = case page of HomePage homePageState -> Page.Home.subscriptions homePageState (toMsg << HomePageMsg) NewPostPage newPostPageState -> Page.NewPost.subscriptions newPostPageState (toMsg << NewPostPageMsg) ShowPostPage showPostPageState -> Page.ShowPost.subscriptions showPostPageState (toMsg << ShowPostPageMsg) LoginPage loginPageState -> Page.Login.subscriptions loginPageState (toMsg << LoginPageMsg) RegisterPage registerPageState -> Page.Register.subscriptions registerPageState (toMsg << RegisterPageMsg) AboutPage -> Sub.none NotFoundPage -> Sub.none view : Page -> (Msg -> msg) -> Html msg view page toMsg = case page of HomePage homePageState -> Page.Home.view homePageState (toMsg << HomePageMsg) NewPostPage newPostPageState -> Page.NewPost.view newPostPageState (toMsg << NewPostPageMsg) ShowPostPage showPostPageState -> Page.ShowPost.view showPostPageState (toMsg << ShowPostPageMsg) LoginPage loginPageState -> Page.Login.view loginPageState (toMsg << LoginPageMsg) RegisterPage registerPageState -> Page.Register.view registerPageState (toMsg << RegisterPageMsg) AboutPage -> Ui.Page.container "About" [ text "Welcome to Facepalm. A place to meet weird people while keeping all your personal data safe." ] NotFoundPage -> Ui.Page.container "Error 404" [ text "That means we couldn’t find this page." ]
high
0.739582
99,855
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.roots.impl; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootModel; import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.roots.OrderEnumerationHandler; import com.intellij.util.PairProcessor; import com.intellij.util.Processor; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class ProjectOrderEnumerator extends OrderEnumeratorBase { private final Project myProject; public ProjectOrderEnumerator(@NotNull Project project, @Nullable OrderRootsCache rootsCache) { super(rootsCache); myProject = project; } @Override public void processRootModules(@NotNull Processor<? super Module> processor) { Module[] modules = myModulesProvider != null ? myModulesProvider.getModules() : ModuleManager.getInstance(myProject).getSortedModules(); for (Module each : modules) { processor.process(each); } } @Override protected void forEach(@NotNull final PairProcessor<? super OrderEntry, ? super List<? extends OrderEnumerationHandler>> processor) { myRecursively = false; myWithoutDepModules = true; final THashSet<Module> processed = new THashSet<>(); processRootModules(module -> { processEntries(getRootModel(module), processed, true, getCustomHandlers(module), processor); return true; }); } @Override public void forEachModule(@NotNull Processor<? super Module> processor) { processRootModules(processor); } @Override public boolean isRootModuleModel(@NotNull ModuleRootModel rootModel) { return true; } }
high
0.689469
99,856
/* Copyright 2019 EPAM Systems. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ package com.epam.edp.stages.impl.ci.impl.compile import com.epam.edp.stages.impl.ci.ProjectType import com.epam.edp.stages.impl.ci.Stage @Stage(name = "compile", buildTool = "maven", type = [ProjectType.APPLICATION, ProjectType.LIBRARY]) class CompileMavenApplicationLibrary { Script script void run(context) { script.dir("${context.workDir}") { script.withCredentials([script.usernamePassword(credentialsId: "${context.nexus.credentialsId}", passwordVariable: 'PASSWORD', usernameVariable: 'USERNAME')]) { script.sh "${context.buildTool.command} ${context.buildTool.properties} -Dartifactory.username=${script.USERNAME} -Dartifactory.password=${script.PASSWORD}" + " compile -B" } } } }
high
0.558068
99,857
# Copyright 2018 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function BuildGoFiles($folders, $recreate) { Get-Command -ErrorAction Ignore -Name go | Out-Null if (!$?) { Write-Verbose ("Go is not installed or not found. Skipping building " + "go files. This might result in some docker images " + "failing to build.") return } Write-Verbose "Building Go items..." foreach ($folder in $folders) { $items = Get-ChildItem -Recurse $folder | ? Name -Match ".*.go(lnk)?$" | ? Name -NotMatch "util" foreach ($item in $items) { $exePath = Join-Path $item.DirectoryName ($item.BaseName + ".exe") if (!$recreate -and (Test-Path $exePath)) { Write-Verbose "$exePath already exists. Skipping go build for it." continue } $sourceFilePath = Join-Path $item.DirectoryName $item.Name Write-Verbose "Building $sourceFilePath to $exePath" pushd $item.DirectoryName $source = "." if ($item.Extension -eq ".golnk") { $source = (cat $item).Trim() } go build -o $exePath $source popd } } } Function Build-DockerImages { Param ( [Parameter(Mandatory=$true)] [PSObject[]]$Images, [Parameter(Mandatory=$true)] [String]$BaseImage, [Parameter(Mandatory=$true)] [String]$Repository, [Parameter(Mandatory=$true)] [bool]$Recreate, [Parameter(mandatory=$false)] [String]$VersionSuffix = "" ) Write-Verbose "Building Docker images..." $failedImages = New-Object System.Collections.ArrayList $allDockerImages = docker images foreach ($image in $Images) { $imgName = $image.Name foreach ($version in $image.Versions) { $version = "$version$VersionSuffix" $fullImageName = "$Repository/$imgName`:$version" if (!$Recreate) { $imageFound = $allDockerImages | Select-String -Pattern "$Repository/$imgName" | Select-String -Pattern "\s$version\s" if ($imageFound) { Write-Verbose "Image ""$fullImageName"" already exists. Skipping." continue } } # if the image has no ImageBase, use $BaseImage instead. # if it has, check if the image is based on another already built # image, like busybox. if ($image.ImageBase -eq "") { $imgBase = $BaseImage } else { $imgBase = $image.ImageBase $imgBaseObj = $Images | ? Name -eq $image.ImageBase if ($imgBaseObj) { $imgBaseObjVersion = $imgBaseObj[0].Versions[0] $imgBase = "$Repository/$imgBase`:$imgBaseObjVersion$VersionSuffix" } } pushd $imgName Write-Verbose "Building $fullImageName, using as base image: $imgBase." docker build -t "$fullImageName" --build-arg BASE_IMAGE="$imgBase" . | Write-Verbose $result = $? popd if (!$result) { $failedImages.Add($fullImageName) } } } return $failedImages } Function Push-DockerImages { Param ( [Parameter(Mandatory=$true)] [PSObject]$Images, [Parameter(Mandatory=$true)] [String]$Repository, [Parameter(mandatory=$false)] [String]$VersionSuffix = "" ) Write-Verbose "Pushing Docker images..." $failedImages = $myArray = New-Object System.Collections.ArrayList foreach ($image in $images) { $imgName = $image.Name foreach ($version in $image.Versions) { $version = "$version$VersionSuffix" $fullImageName = "$Repository/$imgName`:$version" docker push "$fullImageName" | Write-Verbose if (!$?) { $failedImages.Add($fullImageName) } } } return $failedImages } Function Build-DockerManifestLists { Param ( [Parameter(Mandatory=$true)] [PSObject]$Images, [Parameter(Mandatory=$true)] [PSObject]$BaseImages, [Parameter(Mandatory=$true)] [String]$Repository ) Write-Verbose "Creating Docker manifest lists..." $failedManifests = $myArray = New-Object System.Collections.ArrayList foreach ($image in $images) { $manifestName = $image.Name foreach ($version in $image.Versions) { $fullManifestName = "$Repository/$manifestName`:$version" $manifestImages = $BaseImages.Suffix | % {$fullManifestName + $_} docker manifest create --amend "$fullManifestName" $manifestImages | Write-Verbose if (!$?) { $failedManifests.Add($fullManifestName) } } } return $failedManifests } Function Push-DockerManifestLists { Param ( [Parameter(Mandatory=$true)] [PSObject]$Images, [Parameter(Mandatory=$true)] [String]$Repository ) Write-Verbose "Pushing Docker manifest lists..." $failedManifests = $myArray = New-Object System.Collections.ArrayList foreach ($image in $images) { $imgName = $image.Name foreach ($version in $image.Versions) { $version = "$version$VersionSuffix" $fullManifestName = "$Repository/$imgName`:$version" docker manifest push --purge "$fullManifestName" | Write-Verbose if (!$?) { $failedManifests.Add($fullManifestName) } } } return $failedManifests } function PullDockerImages($images) { Write-Verbose "Pulling Docker images..." $failedImages = $myArray = New-Object System.Collections.ArrayList foreach ($image in $images) { $imgName = $image.Name foreach ($version in $image.Versions) { $fullImageName = "$repository/$imgName`:$version" docker pull "$fullImageName" | Write-Verbose if (!$?) { $failedImages.Add($fullImageName) } } } return $failedImages } function BaseImage { param ( $ImageName, $Suffix ) $psObj = New-Object -TypeName PSObject $psObj | Add-Member -MemberType NoteProperty -Name ImageName -Value $ImageName $psObj | Add-Member -MemberType NoteProperty -Name Suffix -Value "-$Suffix" # Calling "psObj" below outputs it, acting as a "return" value $psObj } $BaseImages = @( BaseImage -ImageName "mcr.microsoft.com/windows/servercore:ltsc2019" -Suffix "1809" BaseImage -ImageName "mcr.microsoft.com/windows/servercore:1909" -Suffix "1909" ) function DockerImage { param ( $Name, $Versions = "1.0", $ImageBase = "" ) if ($Versions -is [string]) { $Versions = @($Versions) } $image = New-Object -TypeName PSObject $image | Add-Member -MemberType NoteProperty -Name Name -Value $Name $image | Add-Member -MemberType NoteProperty -Name Versions -Value $Versions $image | Add-Member -MemberType NoteProperty -Name ImageBase -Value $ImageBase # Calling "image" below outputs it, acting as a "return" value $image } $Images = @( # base images used to build other images. DockerImage -Name "busybox" -Versions "1.29" DockerImage -Name "curl" -Versions "1803" DockerImage -Name "java" -Versions "openjdk-8-jre" -ImageBase "busybox" DockerImage -Name "test-webserver" DockerImage -Name "cassandra" -Versions "v13" -ImageBase "java" DockerImage -Name "dnsutils" -ImageBase "busybox" -Versions "1.2" DockerImage -Name "echoserver" -ImageBase "busybox" -Versions "2.2" DockerImage -Name "entrypoint-tester" DockerImage -Name "etcd" -Versions "v3.3.15", "3.3.15" DockerImage -Name "fakegitserver" DockerImage -Name "gb-frontend" -Versions "v6" DockerImage -Name "gb-redisslave" -Versions "v3" DockerImage -Name "hazelcast-kubernetes" -Versions "3.8_1" -ImageBase "java" DockerImage -Name "hostexec" -Versions "1.1" -ImageBase "busybox" DockerImage -Name "httpd" -Versions @("2.4.38-alpine", "2.4.39-alpine") -ImageBase "busybox" DockerImage -Name "iperf" -ImageBase "busybox" DockerImage -Name "jessie-dnsutils" -ImageBase "busybox" -Versions "1.1" DockerImage -Name "kitten" -ImageBase "test-webserver" DockerImage -Name "liveness" -Versions "1.1" DockerImage -Name "logs-generator" DockerImage -Name "mounttest" DockerImage -Name "nautilus" -ImageBase "test-webserver" DockerImage -Name "net" -ImageBase "busybox" DockerImage -Name "netexec" -ImageBase "busybox" -Versions "1.1" DockerImage -Name "nettest" DockerImage -Name "nginx" -Versions @("1.14-alpine","1.15-alpine") -ImageBase "busybox" DockerImage -Name "no-snat-test" DockerImage -Name "nonroot" -Versions "1.1" DockerImage -Name "pause" -Versions "3.1" DockerImage -Name "port-forward-tester" DockerImage -Name "porter" DockerImage -Name "redis" -ImageBase "busybox" -Versions "3.2.9-alpine" DockerImage -Name "resource-consumer" -Versions "1.5" DockerImage -Name "resource-consumer-controller" #DockerImage -Name "rethinkdb" -Version "1.16.0_1" -ImageBase "busybox" DockerImage -Name "sample-apiserver" -Versions "1.10" DockerImage -Name "serve-hostname" -Versions "1.1" DockerImage -Name "webhook" -Versions "1.15v1" DockerImage -Name "agnhost" -ImageBase "busybox" -Versions "2.6" )
high
0.424899
99,858
nqubits = 16; name = "16v2 1 1 3 6 2 1"; nstates = 4; amplitude[x_,y_] := (Exp[-15 I y] (1 (I Sin[x])^6 Cos[x]^10 + 1 (I Sin[x])^10 Cos[x]^6) + Exp[-13 I y] (6 (I Sin[x])^7 Cos[x]^9 + 6 (I Sin[x])^9 Cos[x]^7 + 4 (I Sin[x])^6 Cos[x]^10 + 4 (I Sin[x])^10 Cos[x]^6 + 6 (I Sin[x])^8 Cos[x]^8 + 2 (I Sin[x])^5 Cos[x]^11 + 2 (I Sin[x])^11 Cos[x]^5) + Exp[-11 I y] (19 (I Sin[x])^5 Cos[x]^11 + 19 (I Sin[x])^11 Cos[x]^5 + 35 (I Sin[x])^7 Cos[x]^9 + 35 (I Sin[x])^9 Cos[x]^7 + 9 (I Sin[x])^4 Cos[x]^12 + 9 (I Sin[x])^12 Cos[x]^4 + 22 (I Sin[x])^6 Cos[x]^10 + 22 (I Sin[x])^10 Cos[x]^6 + 36 (I Sin[x])^8 Cos[x]^8 + 2 (I Sin[x])^3 Cos[x]^13 + 2 (I Sin[x])^13 Cos[x]^3) + Exp[-9 I y] (115 (I Sin[x])^6 Cos[x]^10 + 115 (I Sin[x])^10 Cos[x]^6 + 152 (I Sin[x])^8 Cos[x]^8 + 140 (I Sin[x])^7 Cos[x]^9 + 140 (I Sin[x])^9 Cos[x]^7 + 72 (I Sin[x])^11 Cos[x]^5 + 72 (I Sin[x])^5 Cos[x]^11 + 38 (I Sin[x])^12 Cos[x]^4 + 38 (I Sin[x])^4 Cos[x]^12 + 12 (I Sin[x])^13 Cos[x]^3 + 12 (I Sin[x])^3 Cos[x]^13 + 2 (I Sin[x])^2 Cos[x]^14 + 2 (I Sin[x])^14 Cos[x]^2) + Exp[-7 I y] (341 (I Sin[x])^6 Cos[x]^10 + 341 (I Sin[x])^10 Cos[x]^6 + 472 (I Sin[x])^8 Cos[x]^8 + 102 (I Sin[x])^4 Cos[x]^12 + 102 (I Sin[x])^12 Cos[x]^4 + 202 (I Sin[x])^5 Cos[x]^11 + 202 (I Sin[x])^11 Cos[x]^5 + 424 (I Sin[x])^7 Cos[x]^9 + 424 (I Sin[x])^9 Cos[x]^7 + 44 (I Sin[x])^3 Cos[x]^13 + 44 (I Sin[x])^13 Cos[x]^3 + 14 (I Sin[x])^2 Cos[x]^14 + 14 (I Sin[x])^14 Cos[x]^2 + 2 (I Sin[x])^1 Cos[x]^15 + 2 (I Sin[x])^15 Cos[x]^1) + Exp[-5 I y] (1031 (I Sin[x])^7 Cos[x]^9 + 1031 (I Sin[x])^9 Cos[x]^7 + 428 (I Sin[x])^11 Cos[x]^5 + 428 (I Sin[x])^5 Cos[x]^11 + 1144 (I Sin[x])^8 Cos[x]^8 + 733 (I Sin[x])^10 Cos[x]^6 + 733 (I Sin[x])^6 Cos[x]^10 + 177 (I Sin[x])^12 Cos[x]^4 + 177 (I Sin[x])^4 Cos[x]^12 + 52 (I Sin[x])^13 Cos[x]^3 + 52 (I Sin[x])^3 Cos[x]^13 + 9 (I Sin[x])^2 Cos[x]^14 + 9 (I Sin[x])^14 Cos[x]^2 + 1 (I Sin[x])^1 Cos[x]^15 + 1 (I Sin[x])^15 Cos[x]^1) + Exp[-3 I y] (1644 (I Sin[x])^7 Cos[x]^9 + 1644 (I Sin[x])^9 Cos[x]^7 + 733 (I Sin[x])^5 Cos[x]^11 + 733 (I Sin[x])^11 Cos[x]^5 + 136 (I Sin[x])^3 Cos[x]^13 + 136 (I Sin[x])^13 Cos[x]^3 + 1189 (I Sin[x])^6 Cos[x]^10 + 1189 (I Sin[x])^10 Cos[x]^6 + 364 (I Sin[x])^4 Cos[x]^12 + 364 (I Sin[x])^12 Cos[x]^4 + 1792 (I Sin[x])^8 Cos[x]^8 + 35 (I Sin[x])^2 Cos[x]^14 + 35 (I Sin[x])^14 Cos[x]^2 + 7 (I Sin[x])^1 Cos[x]^15 + 7 (I Sin[x])^15 Cos[x]^1 + 1 Cos[x]^16 + 1 (I Sin[x])^16) + Exp[-1 I y] (2656 (I Sin[x])^8 Cos[x]^8 + 284 (I Sin[x])^12 Cos[x]^4 + 284 (I Sin[x])^4 Cos[x]^12 + 1611 (I Sin[x])^10 Cos[x]^6 + 1611 (I Sin[x])^6 Cos[x]^10 + 2341 (I Sin[x])^9 Cos[x]^7 + 2341 (I Sin[x])^7 Cos[x]^9 + 790 (I Sin[x])^11 Cos[x]^5 + 790 (I Sin[x])^5 Cos[x]^11 + 68 (I Sin[x])^3 Cos[x]^13 + 68 (I Sin[x])^13 Cos[x]^3 + 12 (I Sin[x])^2 Cos[x]^14 + 12 (I Sin[x])^14 Cos[x]^2 + 1 (I Sin[x])^15 Cos[x]^1 + 1 (I Sin[x])^1 Cos[x]^15) + Exp[1 I y] (2352 (I Sin[x])^8 Cos[x]^8 + 1587 (I Sin[x])^6 Cos[x]^10 + 1587 (I Sin[x])^10 Cos[x]^6 + 436 (I Sin[x])^4 Cos[x]^12 + 436 (I Sin[x])^12 Cos[x]^4 + 2097 (I Sin[x])^7 Cos[x]^9 + 2097 (I Sin[x])^9 Cos[x]^7 + 952 (I Sin[x])^5 Cos[x]^11 + 952 (I Sin[x])^11 Cos[x]^5 + 146 (I Sin[x])^3 Cos[x]^13 + 146 (I Sin[x])^13 Cos[x]^3 + 36 (I Sin[x])^2 Cos[x]^14 + 36 (I Sin[x])^14 Cos[x]^2 + 5 (I Sin[x])^1 Cos[x]^15 + 5 (I Sin[x])^15 Cos[x]^1) + Exp[3 I y] (1936 (I Sin[x])^9 Cos[x]^7 + 1936 (I Sin[x])^7 Cos[x]^9 + 541 (I Sin[x])^11 Cos[x]^5 + 541 (I Sin[x])^5 Cos[x]^11 + 2266 (I Sin[x])^8 Cos[x]^8 + 1171 (I Sin[x])^6 Cos[x]^10 + 1171 (I Sin[x])^10 Cos[x]^6 + 176 (I Sin[x])^4 Cos[x]^12 + 176 (I Sin[x])^12 Cos[x]^4 + 43 (I Sin[x])^3 Cos[x]^13 + 43 (I Sin[x])^13 Cos[x]^3 + 5 (I Sin[x])^14 Cos[x]^2 + 5 (I Sin[x])^2 Cos[x]^14) + Exp[5 I y] (1055 (I Sin[x])^7 Cos[x]^9 + 1055 (I Sin[x])^9 Cos[x]^7 + 410 (I Sin[x])^5 Cos[x]^11 + 410 (I Sin[x])^11 Cos[x]^5 + 759 (I Sin[x])^6 Cos[x]^10 + 759 (I Sin[x])^10 Cos[x]^6 + 1124 (I Sin[x])^8 Cos[x]^8 + 163 (I Sin[x])^4 Cos[x]^12 + 163 (I Sin[x])^12 Cos[x]^4 + 47 (I Sin[x])^3 Cos[x]^13 + 47 (I Sin[x])^13 Cos[x]^3 + 7 (I Sin[x])^2 Cos[x]^14 + 7 (I Sin[x])^14 Cos[x]^2) + Exp[7 I y] (608 (I Sin[x])^8 Cos[x]^8 + 339 (I Sin[x])^10 Cos[x]^6 + 339 (I Sin[x])^6 Cos[x]^10 + 514 (I Sin[x])^7 Cos[x]^9 + 514 (I Sin[x])^9 Cos[x]^7 + 151 (I Sin[x])^5 Cos[x]^11 + 151 (I Sin[x])^11 Cos[x]^5 + 50 (I Sin[x])^4 Cos[x]^12 + 50 (I Sin[x])^12 Cos[x]^4 + 7 (I Sin[x])^13 Cos[x]^3 + 7 (I Sin[x])^3 Cos[x]^13) + Exp[9 I y] (101 (I Sin[x])^6 Cos[x]^10 + 101 (I Sin[x])^10 Cos[x]^6 + 224 (I Sin[x])^8 Cos[x]^8 + 172 (I Sin[x])^7 Cos[x]^9 + 172 (I Sin[x])^9 Cos[x]^7 + 49 (I Sin[x])^11 Cos[x]^5 + 49 (I Sin[x])^5 Cos[x]^11 + 18 (I Sin[x])^4 Cos[x]^12 + 18 (I Sin[x])^12 Cos[x]^4 + 3 (I Sin[x])^3 Cos[x]^13 + 3 (I Sin[x])^13 Cos[x]^3) + Exp[11 I y] (38 (I Sin[x])^9 Cos[x]^7 + 38 (I Sin[x])^7 Cos[x]^9 + 18 (I Sin[x])^11 Cos[x]^5 + 18 (I Sin[x])^5 Cos[x]^11 + 30 (I Sin[x])^6 Cos[x]^10 + 30 (I Sin[x])^10 Cos[x]^6 + 32 (I Sin[x])^8 Cos[x]^8 + 3 (I Sin[x])^12 Cos[x]^4 + 3 (I Sin[x])^4 Cos[x]^12) + Exp[13 I y] (1 (I Sin[x])^5 Cos[x]^11 + 1 (I Sin[x])^11 Cos[x]^5 + 7 (I Sin[x])^9 Cos[x]^7 + 7 (I Sin[x])^7 Cos[x]^9 + 6 (I Sin[x])^8 Cos[x]^8 + 4 (I Sin[x])^6 Cos[x]^10 + 4 (I Sin[x])^10 Cos[x]^6) + Exp[15 I y] (1 (I Sin[x])^10 Cos[x]^6 + 1 (I Sin[x])^6 Cos[x]^10))/Sqrt[2^nqubits]; amplitude2[x_,y_] := (Exp[-15 I y] (1 (I Sin[x])^6 Cos[x]^10 + 1 (I Sin[x])^10 Cos[x]^6) + Exp[-13 I y] (6 (I Sin[x])^7 Cos[x]^9 + 6 (I Sin[x])^9 Cos[x]^7 + 4 (I Sin[x])^6 Cos[x]^10 + 4 (I Sin[x])^10 Cos[x]^6 + 6 (I Sin[x])^8 Cos[x]^8 + 2 (I Sin[x])^5 Cos[x]^11 + 2 (I Sin[x])^11 Cos[x]^5) + Exp[-11 I y] (19 (I Sin[x])^5 Cos[x]^11 + 19 (I Sin[x])^11 Cos[x]^5 + 35 (I Sin[x])^7 Cos[x]^9 + 35 (I Sin[x])^9 Cos[x]^7 + 9 (I Sin[x])^4 Cos[x]^12 + 9 (I Sin[x])^12 Cos[x]^4 + 22 (I Sin[x])^6 Cos[x]^10 + 22 (I Sin[x])^10 Cos[x]^6 + 36 (I Sin[x])^8 Cos[x]^8 + 2 (I Sin[x])^3 Cos[x]^13 + 2 (I Sin[x])^13 Cos[x]^3) + Exp[-9 I y] (115 (I Sin[x])^6 Cos[x]^10 + 115 (I Sin[x])^10 Cos[x]^6 + 152 (I Sin[x])^8 Cos[x]^8 + 140 (I Sin[x])^7 Cos[x]^9 + 140 (I Sin[x])^9 Cos[x]^7 + 72 (I Sin[x])^11 Cos[x]^5 + 72 (I Sin[x])^5 Cos[x]^11 + 38 (I Sin[x])^12 Cos[x]^4 + 38 (I Sin[x])^4 Cos[x]^12 + 12 (I Sin[x])^13 Cos[x]^3 + 12 (I Sin[x])^3 Cos[x]^13 + 2 (I Sin[x])^2 Cos[x]^14 + 2 (I Sin[x])^14 Cos[x]^2) + Exp[-7 I y] (341 (I Sin[x])^6 Cos[x]^10 + 341 (I Sin[x])^10 Cos[x]^6 + 472 (I Sin[x])^8 Cos[x]^8 + 102 (I Sin[x])^4 Cos[x]^12 + 102 (I Sin[x])^12 Cos[x]^4 + 202 (I Sin[x])^5 Cos[x]^11 + 202 (I Sin[x])^11 Cos[x]^5 + 424 (I Sin[x])^7 Cos[x]^9 + 424 (I Sin[x])^9 Cos[x]^7 + 44 (I Sin[x])^3 Cos[x]^13 + 44 (I Sin[x])^13 Cos[x]^3 + 14 (I Sin[x])^2 Cos[x]^14 + 14 (I Sin[x])^14 Cos[x]^2 + 2 (I Sin[x])^1 Cos[x]^15 + 2 (I Sin[x])^15 Cos[x]^1) + Exp[-5 I y] (1031 (I Sin[x])^7 Cos[x]^9 + 1031 (I Sin[x])^9 Cos[x]^7 + 428 (I Sin[x])^11 Cos[x]^5 + 428 (I Sin[x])^5 Cos[x]^11 + 1144 (I Sin[x])^8 Cos[x]^8 + 733 (I Sin[x])^10 Cos[x]^6 + 733 (I Sin[x])^6 Cos[x]^10 + 177 (I Sin[x])^12 Cos[x]^4 + 177 (I Sin[x])^4 Cos[x]^12 + 52 (I Sin[x])^13 Cos[x]^3 + 52 (I Sin[x])^3 Cos[x]^13 + 9 (I Sin[x])^2 Cos[x]^14 + 9 (I Sin[x])^14 Cos[x]^2 + 1 (I Sin[x])^1 Cos[x]^15 + 1 (I Sin[x])^15 Cos[x]^1) + Exp[-3 I y] (1644 (I Sin[x])^7 Cos[x]^9 + 1644 (I Sin[x])^9 Cos[x]^7 + 733 (I Sin[x])^5 Cos[x]^11 + 733 (I Sin[x])^11 Cos[x]^5 + 136 (I Sin[x])^3 Cos[x]^13 + 136 (I Sin[x])^13 Cos[x]^3 + 1189 (I Sin[x])^6 Cos[x]^10 + 1189 (I Sin[x])^10 Cos[x]^6 + 364 (I Sin[x])^4 Cos[x]^12 + 364 (I Sin[x])^12 Cos[x]^4 + 1792 (I Sin[x])^8 Cos[x]^8 + 35 (I Sin[x])^2 Cos[x]^14 + 35 (I Sin[x])^14 Cos[x]^2 + 7 (I Sin[x])^1 Cos[x]^15 + 7 (I Sin[x])^15 Cos[x]^1 + 1 Cos[x]^16 + 1 (I Sin[x])^16) + Exp[-1 I y] (2656 (I Sin[x])^8 Cos[x]^8 + 284 (I Sin[x])^12 Cos[x]^4 + 284 (I Sin[x])^4 Cos[x]^12 + 1611 (I Sin[x])^10 Cos[x]^6 + 1611 (I Sin[x])^6 Cos[x]^10 + 2341 (I Sin[x])^9 Cos[x]^7 + 2341 (I Sin[x])^7 Cos[x]^9 + 790 (I Sin[x])^11 Cos[x]^5 + 790 (I Sin[x])^5 Cos[x]^11 + 68 (I Sin[x])^3 Cos[x]^13 + 68 (I Sin[x])^13 Cos[x]^3 + 12 (I Sin[x])^2 Cos[x]^14 + 12 (I Sin[x])^14 Cos[x]^2 + 1 (I Sin[x])^15 Cos[x]^1 + 1 (I Sin[x])^1 Cos[x]^15) + Exp[1 I y] (2352 (I Sin[x])^8 Cos[x]^8 + 1587 (I Sin[x])^6 Cos[x]^10 + 1587 (I Sin[x])^10 Cos[x]^6 + 436 (I Sin[x])^4 Cos[x]^12 + 436 (I Sin[x])^12 Cos[x]^4 + 2097 (I Sin[x])^7 Cos[x]^9 + 2097 (I Sin[x])^9 Cos[x]^7 + 952 (I Sin[x])^5 Cos[x]^11 + 952 (I Sin[x])^11 Cos[x]^5 + 146 (I Sin[x])^3 Cos[x]^13 + 146 (I Sin[x])^13 Cos[x]^3 + 36 (I Sin[x])^2 Cos[x]^14 + 36 (I Sin[x])^14 Cos[x]^2 + 5 (I Sin[x])^1 Cos[x]^15 + 5 (I Sin[x])^15 Cos[x]^1) + Exp[3 I y] (1936 (I Sin[x])^9 Cos[x]^7 + 1936 (I Sin[x])^7 Cos[x]^9 + 541 (I Sin[x])^11 Cos[x]^5 + 541 (I Sin[x])^5 Cos[x]^11 + 2266 (I Sin[x])^8 Cos[x]^8 + 1171 (I Sin[x])^6 Cos[x]^10 + 1171 (I Sin[x])^10 Cos[x]^6 + 176 (I Sin[x])^4 Cos[x]^12 + 176 (I Sin[x])^12 Cos[x]^4 + 43 (I Sin[x])^3 Cos[x]^13 + 43 (I Sin[x])^13 Cos[x]^3 + 5 (I Sin[x])^14 Cos[x]^2 + 5 (I Sin[x])^2 Cos[x]^14) + Exp[5 I y] (1055 (I Sin[x])^7 Cos[x]^9 + 1055 (I Sin[x])^9 Cos[x]^7 + 410 (I Sin[x])^5 Cos[x]^11 + 410 (I Sin[x])^11 Cos[x]^5 + 759 (I Sin[x])^6 Cos[x]^10 + 759 (I Sin[x])^10 Cos[x]^6 + 1124 (I Sin[x])^8 Cos[x]^8 + 163 (I Sin[x])^4 Cos[x]^12 + 163 (I Sin[x])^12 Cos[x]^4 + 47 (I Sin[x])^3 Cos[x]^13 + 47 (I Sin[x])^13 Cos[x]^3 + 7 (I Sin[x])^2 Cos[x]^14 + 7 (I Sin[x])^14 Cos[x]^2) + Exp[7 I y] (608 (I Sin[x])^8 Cos[x]^8 + 339 (I Sin[x])^10 Cos[x]^6 + 339 (I Sin[x])^6 Cos[x]^10 + 514 (I Sin[x])^7 Cos[x]^9 + 514 (I Sin[x])^9 Cos[x]^7 + 151 (I Sin[x])^5 Cos[x]^11 + 151 (I Sin[x])^11 Cos[x]^5 + 50 (I Sin[x])^4 Cos[x]^12 + 50 (I Sin[x])^12 Cos[x]^4 + 7 (I Sin[x])^13 Cos[x]^3 + 7 (I Sin[x])^3 Cos[x]^13) + Exp[9 I y] (101 (I Sin[x])^6 Cos[x]^10 + 101 (I Sin[x])^10 Cos[x]^6 + 224 (I Sin[x])^8 Cos[x]^8 + 172 (I Sin[x])^7 Cos[x]^9 + 172 (I Sin[x])^9 Cos[x]^7 + 49 (I Sin[x])^11 Cos[x]^5 + 49 (I Sin[x])^5 Cos[x]^11 + 18 (I Sin[x])^4 Cos[x]^12 + 18 (I Sin[x])^12 Cos[x]^4 + 3 (I Sin[x])^3 Cos[x]^13 + 3 (I Sin[x])^13 Cos[x]^3) + Exp[11 I y] (38 (I Sin[x])^9 Cos[x]^7 + 38 (I Sin[x])^7 Cos[x]^9 + 18 (I Sin[x])^11 Cos[x]^5 + 18 (I Sin[x])^5 Cos[x]^11 + 30 (I Sin[x])^6 Cos[x]^10 + 30 (I Sin[x])^10 Cos[x]^6 + 32 (I Sin[x])^8 Cos[x]^8 + 3 (I Sin[x])^12 Cos[x]^4 + 3 (I Sin[x])^4 Cos[x]^12) + Exp[13 I y] (1 (I Sin[x])^5 Cos[x]^11 + 1 (I Sin[x])^11 Cos[x]^5 + 7 (I Sin[x])^9 Cos[x]^7 + 7 (I Sin[x])^7 Cos[x]^9 + 6 (I Sin[x])^8 Cos[x]^8 + 4 (I Sin[x])^6 Cos[x]^10 + 4 (I Sin[x])^10 Cos[x]^6) + Exp[15 I y] (1 (I Sin[x])^10 Cos[x]^6 + 1 (I Sin[x])^6 Cos[x]^10)); probability[x_, y_] := Abs[amplitude[x, y]]^2; result = NMaximize[{nstates*probability[a, b], 0 < a < Pi/2, 0 < b < Pi}, {a, b}, Method -> {"SimulatedAnnealing", "PerturbationScale" -> 15}]; Print[name, ": ", result] f = probability[c, d]; n = Pi; Plot3D[f, {c, 0, n/2}, {d, -n, n}, PlotRange -> All] ContourPlot[probability[x, y], {x, 0, n/2}, {y, 0, n}, PlotLegends -> Automatic, Contours -> 30]
high
0.310773
99,859
const std = @import("std"); const gravity = @import("gravity.zig"); const Delegate = gravity.Delegate; const c = gravity.c; pub const Vm = struct { inner: *c.gravity_vm, pub fn init(delegate: *Delegate) !Vm { const vm: ?*c.gravity_vm = c.gravity_vm_new(&delegate.inner); if (vm) |v| { return Vm{ .inner = v }; } return error.FailedToInitVm; } pub fn deinit(self: *Vm) void { c.gravity_vm_free(self.inner); c.gravity_core_free(); self.inner = undefined; } pub fn runmain(self: *Vm, closure: *c.gravity_closure_t) bool { return c.gravity_vm_runmain(self.inner, closure); } pub fn result(self: *Vm) c.gravity_value_t { return c.gravity_vm_result(self.inner); } pub fn valueDump(self: *Vm, val: c.gravity_value_t, buf: []u8) void { c.gravity_value_dump(self.inner, val, buf.ptr, @intCast(u16, buf.len)); } };
high
0.695257
99,860
get("phrase") { # todo: allow joining rest of multiline input label("translate"); menu(websearch("https://translate.google.com/#auto/en/", get("phrase"))) label("google.com"); menu(websearch("https://encrypted.google.com/search?q=", get("phrase"))) menu(websearch("https://en.wikipedia.org/wiki/", get("phrase"))) } # series episode calculator # http://...season-1-episode-2#... match(get("http"), /^(.*season-)([0-9]+)(-episode-)([0-9]+)(#.*)$/, m) { label("next episode"); menu(websearch(m[1] m[2] m[3] (m[4]+1))) label("next season"); menu(websearch(m[1] (m[2]+1) m[3] "1")) } # http://...s01e01 match(get("http"), /^(.*[Ss])([0-9]+)([eE])([0-9]+)$/, m) { label("next episode"); menu(websearch(m[1] m[2] m[3] lpad(m[4]+1, 2, "0"))) label("next season"); menu(websearch(m[1] lpad(m[2]+1, 2, "0") m[3] "01")) } get("identifier") { label("google.com"); menu(websearch("https://encrypted.google.com/search?q=", get("identifier"))) # gawk label("info gawk"); let("auto", ctx("file_name") ~ /\.awk$/) menu(info("gawk --index-search=" Q(get("identifier")))) } get("word") || get("identifier") { label("info apropos"); menu(pager("info -k " Q(get("word")))) label("man apropos"); menu(pager("man -k " Q(get("word")))) } # man page match($0, /^([A-Za-z0-9._-]+) ?(\[[^\]]+\] )?\(([0-9]+)\)/, m) { auto(1); menu(man(Q(m[3]) " " Q(m[1]))) } # info page match($0, /^"?(\([a-zA-Z0-9._-]+\))(([^"]*)")?/, m) { auto(1); menu(info(Q(m[1]m[3]))) }
high
0.276027
99,861
package model import ( "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/utils" "errors" "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/converter" "strings" ) // Request Object type ShowRepositoryRequest struct { // 消息体的类型(格式),下方类型可任选其一使用: application/json;charset=utf-8 application/json ContentType ShowRepositoryRequestContentType `json:"Content-Type"` // 组织名称。小写字母开头,后面跟小写字母、数字、小数点、下划线或中划线(其中下划线最多允许连续两个,小数点、下划线、中划线不能直接相连),小写字母或数字结尾,1-64个字符。 Namespace string `json:"namespace"` // 镜像仓库名称 Repository string `json:"repository"` } func (o ShowRepositoryRequest) String() string { data, err := utils.Marshal(o) if err != nil { return "ShowRepositoryRequest struct{}" } return strings.Join([]string{"ShowRepositoryRequest", string(data)}, " ") } type ShowRepositoryRequestContentType struct { value string } type ShowRepositoryRequestContentTypeEnum struct { APPLICATION_JSONCHARSETUTF_8 ShowRepositoryRequestContentType APPLICATION_JSON ShowRepositoryRequestContentType } func GetShowRepositoryRequestContentTypeEnum() ShowRepositoryRequestContentTypeEnum { return ShowRepositoryRequestContentTypeEnum{ APPLICATION_JSONCHARSETUTF_8: ShowRepositoryRequestContentType{ value: "application/json;charset=utf-8", }, APPLICATION_JSON: ShowRepositoryRequestContentType{ value: "application/json", }, } } func (c ShowRepositoryRequestContentType) MarshalJSON() ([]byte, error) { return utils.Marshal(c.value) } func (c *ShowRepositoryRequestContentType) UnmarshalJSON(b []byte) error { myConverter := converter.StringConverterFactory("string") if myConverter != nil { val, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), "\"")) if err == nil { c.value = val.(string) return nil } return err } else { return errors.New("convert enum data to string error") } }
high
0.74294
99,862
(define-package "magit" "20160305.2218" "A Git porcelain inside Emacs" '((emacs "24.4") (async "20150909.2257") (dash "20151021.113") (with-editor "20160128.1201") (git-commit "20160119.1409") (magit-popup "20160119.1409")) :url "https://github.com/magit/magit" :keywords '("git" "tools" "vc")) ;; Local Variables: ;; no-byte-compile: t ;; End:
low
0.631512
99,863
#! usr/bin/perl use strict; use warnings; use File::Spec; use Time::HiRes qw(time); use POSIX qw(strftime); my ($verbose, $configfile, %config, %segs, %coord, $setting, $recur, $p3begin, $ret, $optP, %optima); my (@solved, @frags, $fCt, $fLen, $seg, %seen, %ass, %p3s, $tntcall, %tnts, %tntbads, %stats, %windows); my %subopt = qw/pen maxpen maxpen pen uni maxuni maxuni uni/; my $t0 = time; my $invoke = "Called \"$0 @ARGV\" on " . localtime; #my %paths = (bin => File::Spec->rel2abs($0)); $paths{bin} =~ s/\/([^\/]+)$//; my $scriptname = $1; my %paths = (install => File::Spec->rel2abs($0)); $paths{install} =~ s/\/[^\/]+\/([^\/]+)$//; my $scriptname = $1; Options(); # See bottom of script; help and other messages, Getopt chdir $paths{out}; open LOG, ">bigdna.log"; Log("$invoke\nConfig file: $paths{in}/$configfile\n") if $verbose; ReadDefault(); my $set = $config{SETTING}; ReadConfig(); LoadTreats(); SetCheck(); CollectSeqs(); for (qw/REGION SEGMENT/) {$config{$_} = ()} # Free some memory, all reqd info now in %segs Rebuilds(); Splice(); #SUBROUTINES sub Recurse { # Full backdown for 1st-solution triggered by return value 1 at Solution() $recur ++; for my $i (1 .. $fCt) { next if $frags[$i]; # Find first untreated fragment my ($r, $s) = ($recur, scalar(@solved)); Log("Begin recursion R$r F$i\n") if $verbose; my $pcrs = Primer3($i); # List of candidate PCRs for fragment for my $pcr (@{$pcrs}) { # Try them all next if $seen{$$pcr{R}[0]}; # Skip right end already found to fail $frags[$i] = $pcr; # Test valid PCR if ($i == $fCt and $ret = Solution()) { # SOLUTION! Primer3 filled last PCR (Test with Tnt) if ($ret) { Log("Start $ret drops from R$r\n") if $verbose; pop @frags; return $ret-1; } } $ret = Recurse(); # RECURSE forward if ($ret) { # Continuing to drop back pop @frags; return $ret-1; } } $frags[$i] = ''; # All pcrs have failed; empty this fragment $s = @solved-$s; Log("End R$r, $s new-solved, lastR=$frags[$i-1]{R}[0]\n") if $verbose; unless ($s) { # No new solutions came from this recursion; ie it failed $seen{$frags[$i-1]{R}[0]} ++; # Mark failed right end to prevent retesting Log("Mark $frags[$i-1]{R}[0] failed\n") if $verbose; } return 0; # Backtrack one level } } sub Stats { my @cats = qw/flen frag rend done back tryfrst frst trylast last tryint int pen maxpen uni maxuni tnt_test tnt_fail tnt_nohit tnt_multi time solved reject/; @stats{qw/tnt_test tnt_fail/} = (scalar(keys %tnts), scalar(keys %tntbads)); for (@cats) {$stats{$_} = 0 unless $stats{$_}} $stats{back} = 1 if $stats{done} and $stats{tryint} + $stats{trylast} > $stats{int} + $stats{last}; Log("$stats{tnt_test} tntblasted pcrs; $stats{tnt_fail} rejected\n") if $verbose and $$set{TNT_USE} ne 'off'; Log(join ("\t", 'Segment', @cats) . "\n"); my $log = $seg; for (@cats) {$log .= "\t$stats{$_}"} $log .= "\n"; Log($log); } sub Rebuilds { # Rebuild each segment of assembly (including single-PCR segments) for (sort {$segs{$a}{order} <=> $segs{$b}{order}} keys %segs) { ($seg, $recur) = ($_, 0); my $s = $segs{$seg}; %seen = (); %p3s = (); %tnts = (); %tntbads = (); @solved = (); %windows = (Lin => 1, Lout => 1, Rin => $$s{len}, Rout => $$s{len}); # Tolerance for rebuild termini, default is forcing to extreme termini my (@L, @R); if ($$s{DELTA_INT} && $$s{annots}) { # Find int gene closest to an end for (qw/L_GENE R_GENE L_TOLERANCE R_TOLERANCE/) {delete $$s{$_}} for (@{$$s{annots}}) { if ($$_[8] =~ /annot=[PRSY]/) { # Int gene my ($diff, $side) = ($$s{len}-$$_[3]+1, 'R'); ($diff, $side) = ($$_[4], 'L') if $diff > $$_[4]; @windows{qw/diff Iend IL IR/} = ($diff, $side, $$_[3]-1, $$_[4]+1) unless $windows{Iend} and $windows{diff} < $diff; } push @L, $$_[3]; unshift @R, $$_[4]; if ($windows{Iend} and $windows{Iend} eq 'L' and not $windows{InL} and $$_[3] >= $windows{IR}) {$windows{InL} = $$_[3]} } @R = sort {$b <=> $a} @R; if ($windows{Iend} and $windows{Iend} eq 'L') { @windows{qw/Lout Lin/} = @windows{qw/IR InL/}; for (@R) {next if $_ > $$s{len} -99; @windows{qw/Rout Rin/} = ($$s{len} -99, $_); last} } elsif ($windows{Iend} and $windows{Iend} eq 'R') { for (@R) {next if $_ > $windows{IL}; @windows{qw/Rout Rin/} = ($windows{IL}, $_); last} for (@L) {next if $_ < 100; @windows{qw/Lout Lin/} = (100, $_); last} } } if ($$s{L_GENE} && $$s{annots}) {$windows{Lin} = $$s{annots}[0][3]} elsif ($$s{L_TOLERANCE}) {$windows{Lin} = $$s{L_TOLERANCE}} if ($$s{R_GENE} && $$s{annots}) { # Find rightmost gene right end (R_GENE) and shortest terminal integrase gene deletion (DELTA_INT) for (@{$$s{annots}}) {push @R, $$_[4]}; @R = sort {$b <=> $a} @R; $windows{Rin} = $R[0]; } elsif ($$s{R_TOLERANCE}) {$windows{Rin} = $$s{len}-$$s{R_TOLERANCE}+1} $fCt = ($windows{Rout}-$windows{Lout}+1)/$$set{PCR_MAX_SIZE}; $fCt ++ unless $fCt == int $fCt; $fCt = int $fCt; $fLen = int(($windows{Rout}-$windows{Lout}+1)/$fCt); %stats = (len => $$s{len}, frag => $fCt, flen => $fLen); my $max = $fLen + 2* $$set{REBUILD_WINDOW}; my $opt = $$set{optmax}.$$set{opt}; $p3begin =~ s/(PRIMER_PRODUCT_SIZE_RANGE=\d+-)\S*/$1$max/; $$set{PRIMER_PRODUCT_SIZE_RANGE} = '200-' . ($fLen + 2* $$set{REBUILD_WINDOW}); Log("$segs{$seg}{len}-bp Segment $seg rebuilding with $fCt PCRs of ~$fLen: end windows L:$windows{Lout}-$windows{Lin}, R:$windows{Rin}-$windows{Rout}\n"); if ($fCt > 2) {unless (RightTest()) {$stats{rend} = 1; Log(Timer() . "FATAL: RightTest failed for Segment $seg\n"); Stats(); exit}} @frags = (); $frags[0]{R}[0] = 0; # $frags[0] is never used (but "preceding" right end should be defined for %seen) Recurse(); # Start recursion unless (@solved) {Log(Timer() . "FATAL: $segs{$seg}{len}-bp Segment $seg $fCt-PCR rebuilding failed\n"); Stats(); exit} if ($$set{SOLUTION} eq 'exhaustive') { for my $opt (qw/pen uni maxpen maxuni/) { my %sco; for my $stat (qw/pen uni maxpen maxuni/) {$sco{$stat} = $optima{$opt}{$stat}} $stats{$opt} = $sco{$opt}; Log("$opt-optimizing: penalty=$sco{pen}, nonuniformity=$sco{uni}, maxpenalty=$sco{maxpen}, maxnonuni=$sco{maxuni}:$optima{$opt}{sum}\n"); } @solved = sort {$$a{$opt} <=> $$b{$opt} || $$a{$subopt{$opt}} <=> $$b{$subopt{$opt}}} @solved; # solved[0] best by OPTIMIZE if ($$set{TNT_USE} eq 'post-exhaustive') { Log("Tnt launched, post-exhaustive\n") if $verbose; while (@solved) { my ($sol, @tnt) = ($solved[0]{sol}); for (@{$sol}) {my @s = @{$_}; my $sum = "$s[0]-$s[3],$s[1],$s[4]"; push @tnt, [$s[0], $s[2], $s[3], $s[5], $sum];} if (Tnt(\@tnt)) { # Misprime, requires backtracking $stats{reject} ++; Log("Rejected for mispriming: $solved[0]{sum}\n") if $verbose; shift @solved; next; } last; # Stop at first tnt-acceptable of ranked solutions } } } unless (@solved) {Log(Timer() . "FATAL: $segs{$seg}{len}-bp Segment $seg $fCt-PCR rebuilding failed after post-exhaustive tntBlast\n"); Stats(); exit} my %sco; for my $stat (qw/pen uni maxpen maxuni/) {$sco{$stat} = $solved[0]{$stat}; $stats{$stat} = $sco{$stat} unless $stats{$stat}} Log("Final $opt-optimizing: penalty=$sco{pen}, nonuniformity=$sco{uni}, maxpenalty=$sco{maxpen}, maxnonuni=$sco{uni}:$solved[0]{sum}\n"); Log("$stats{reject} rejects of $stats{solved} solutions\n") if $verbose and $stats{reject}; @stats{qw/time done/} = (sprintf("%.6f", time-$t0), 1); Stats(); $segs{$seg}{pcr} = $solved[0]{sum}; } } sub Solution { # Return value is number of backtracks to perform immediately my ($sum, @uni, @pen, %t); $stats{solved} ++; for my $i (1..$#frags) { $t{pen} += $frags[$i]{pen}; $t{uni} += $frags[$i]{uni}; $t{maxpen} = $frags[$i]{pen} unless $t{maxpen} and $t{maxpen} >= $frags[$i]{pen}; $t{maxuni} = $frags[$i]{uni} unless $t{maxuni} and $t{maxuni} >= $frags[$i]{uni}; push @{$t{sol}}, [@{$frags[$i]{L}}[0,1,2], @{$frags[$i]{R}}[0,1,2]]; $sum .= " F$i:$frags[$i]{L}[0]-$frags[$i]{R}[0] $frags[$i]{L}[1],$frags[$i]{R}[1];"; } for (qw/pen uni/) {$t{$_} = sprintf "%.3f", $t{$_}/$fCt} $t{maxpen} = sprintf "%.3f", $t{maxpen}; if ($$set{TNT_USE} eq 'per-solution') { Log("Tnt per-solution launched for " . scalar(@frags) . " fragments, per-solution\n") if $verbose; for my $i (1..$#frags) {push @{$t{tnt}}, [@{$frags[$i]{L}}[0,2], @{$frags[$i]{R}}[0,2], $frags[$i]{sum}]} # [0] Lcoord [1] Lseq [2] Rcoord [3] Rseq [4] pcrSummary $ret = Tnt($t{tnt}); if ($ret) { # Misprime, requires backtracking Log("Rejected for mispriming: $sum\n") if $verbose; $stats{reject}++; return $ret; } } Log("$seg SOLVED: Penalty=$t{pen}; Nonuni=$t{uni}; MaxPenalty=$t{maxpen}; MaxNonuni=$t{maxuni};$sum\n") if $verbose; for my $opt (qw/pen uni maxpen maxuni/) { next if $optima{$opt} and ($optima{$opt}{$opt} < $t{$opt} or ($optima{$opt}{$opt} == $t{$opt} and $optima{$opt}{$subopt{$opt}} <= $t{$subopt{$opt}})); # Avg and Max optimize each other? %{$optima{$opt}} = (pen => $t{pen}, uni => $t{uni}, maxpen => $t{maxpen}, maxuni => $t{maxuni}, sol => $t{sol}, sum => $sum); } push @solved, {pen => $t{pen}, uni => $t{uni}, maxpen => $t{maxpen}, maxuni => $t{maxuni}, sol => $t{sol}, sum => $sum}; if ($$set{SOLUTION} eq 'exhaustive') {return 0} else {return $#frags} # Full backdown for 1st } sub Tnt { # Tests all PCRs of a rebuild solution OR (per-recursion) all PCRs from a Primer3 run return if $$set{TNT_USE} eq 'off'; # XXX? my ($call, $pcrs, %expected, %found, $expect, @in, $hit) = ("$tntcall -d $segs{$seg}{FASTA} -l " . (2*$fLen) . " > /dev/null", @_); my $backtracks = 0; # How many recursion levels to drop to correct mispriming PCR for (my $i=$#{$pcrs}; $i >= 0; $i--) { # Contents of each PCR are: [0] Lend, [1] Lseq, [2] Rend, [3] Rseq, [4] ExpectLabel $expect = ${$pcrs}[$i][4]; # Each $expect should be a label like this: 'Lend-Rend,lenL,lenR' $backtracks = $#{$pcrs} -$i if $tntbads{$expect}; # Backtracks to fix leftmost bad PCR next if $tnts{$expect}; # Previously found to fail $expect =~ /(,.*)/; %{$expected{$expect}} = (ct => 0, lens => $1); push @in, join(' ', $expect, @{$$pcrs[$i]}[1,3]) . "\n"; # @in are tnt inputs; empty if all previously tested } return 1 if $backtracks and $$set{TNT_USE} eq 'post-exhaustive'; # Post-exhaustive: return 0=OK, 1=bad unless (@in) { # All Pcrs have previously been tested return $backtracks; # Per-solution: backtrack or not; Per-recursion: return value unimportant but saves a Tnt run } open INPUT, ">tntIn"; print INPUT join('', @in); close INPUT; unlink "tntOut"; system $call; unless (-f "tntOut") {Log("WARNING: " . scalar(@in) . " tntblast inputs, no output for $call\n"); return} for (`cat tntOut`) { if (/^name = (\S+)/) {($expect, $hit) = ($1, '')} elsif (/^amplicon range = (\d+) \.\. (\d+)/) { # Tntblast output is zero-based my ($L, $R) = ($1+1 -$segs{$seg}{FA_L}+1, $2+1 -$segs{$seg}{FA_L}+1); ($L, $R) = ($segs{$seg}{FA_R} -($2+1) + 1, $segs{$seg}{FA_R} -$1) if $segs{$seg}{FA_ORIENT} eq '-'; for ($L, $R) {$_ = $_ % $segs{$seg}{entrylen}} $hit = "$L-$R" . $expected{$expect}{lens}; } elsif (/^>(\S+)/) { # $1 is the ENTRY hit next if $tnts{$expect}; unless ($hit) {Log("Entry but no hit for $expect\n") if $verbose; next} my $entryhit = $1; if ($entryhit eq $segs{$seg}{ENTRY} and $expected{$hit}) { Log("expected $expect hits other expected $hit\n") if $verbose and $hit ne $expect; $expected{$hit}{ct} ++; } else {$tnts{$expect} =1; $tntbads{$expect} =1; Log("$expect misprimes at $hit on $entryhit\n") if $verbose} } } unlink "tntOut", 'tntIn'; for (keys %expected) { next if $tnts{$_}; $tnts{$_} = 1; if ($expected{$_}{ct} == 0) {$stats{tnt_nohit} ++; Log("No expected PCR $_ for segment $seg found by tntblast\n") if $verbose} elsif ($expected{$_}{ct} > 1) {$stats{tnt_multi} ++; $tntbads{$_} = 1; Log("Expected PCR $_ for segment $seg found multiply by tntblast\n") if $verbose} } $backtracks = 0; for (my $i=$#{$pcrs}; $i >= 0; $i--) { # $backtracks = $#{$pcrs} -$i if $tntbads{$$pcrs[$i][4]}; # Backtracks to fix leftmost bad PCR } return $backtracks; } sub SetCheck { for (sort keys %{$set}) {$p3begin .= "$_=$$set{$_}\n" if /^PRIMER_/} $p3begin .= "PRIMER_PRODUCT_SIZE_RANGE=200-x\n"; return if $$set{TNT_USE} eq 'off'; if ($$set{TNT_USE} eq 'post-exhaustive' and $$set{SOLUTION} eq 'first') { $$set{TNT_USE} = 'pre-solution'; Log("TNT_USE post-exhaustive not allowed with SOLUTION=first, resetting to 'pre-solution'\n"); } my %tnt_args = (qw/TNT_MIN_TM -e TNT_CLAMP --primer-clamp TNT_MAX_GAP --max-gap TNT_MAX_MISMATCH --max-mismatch/); $tntcall = 'tntblast -i tntIn -o tntOut'; for (keys %tnt_args) {if (defined $$set{$_}) {$tntcall .= " $tnt_args{$_} $$set{$_}"}} Log("Tntblast basic call (database and max length customized for each segment): $tntcall\n") if $verbose; } sub Splice { my (@primers, $last); for (sort {$segs{$a}{order} <=> $segs{$b}{order}} keys %segs) { $seg = $_; my $e = $segs{$seg}{ENTRY}; while ($segs{$seg}{pcr} =~ s/ F(\d+):(\d+)-(\d+) (\d+),(\d+);//) { my ($frag, $L, $R, $sL, $sR) = ($1, $2, $3, $4, $5); my @seqs = (substr($segs{$seg}{seq}, $2-1, $4), Revcomp(substr($segs{$seg}{seq}, $3-$5, $5))); if ($last and $1 == 1) {($primers[-1][0], $seqs[0]) = Frankenstein (@{$primers[-1]}[0,5], $seqs[0], $L, $sL)} push @primers, [$seqs[0], $seg, $frag, 'F', $L, $sL, "$2-" . ($2+$4-1)]; # [0] primerSeq [1] seg [2] frag [3] dir [4] 5'end [5] len [6] span push @primers, [$seqs[1], $seg, $frag, 'R', $R, $sR, "$3-" . ($3-$5+1)]; } $last = $primers[-1][0] if @primers; unless ($$set{LINEAR}) { # Circularize ($primers[-1][0], $primers[0][0]) = Frankenstein(@{$primers[-1]}[0,5], @{$primers[0]}[0,4,5]); } } open OUT, ">primers.txt"; for my $p (@primers) {print OUT "$$p[0]\t$segs{$$p[1]}{order}_$$p[2]$$p[3]\t$$p[1]:$$p[6]\n"} close OUT; } sub Frankenstein { my ($seqL, $lenL, $seqR, $startR, $lenR) = @_; my @franks = (lc(Revcomp($seqR)) . $seqL, lc(Revcomp($seqL)) . $seqR); my $diff = $$set{OVERLAP_MIN_SIZE} - $lenL - $lenR; # Length from L segment to make up to OVERLAP_MIN if ($diff > 0) {$franks[0] = lc(Revcomp(substr($segs{$seg}{seq}, $startR+$lenR-1, $diff))) . $franks[0]} return (@franks); } sub Log {print LOG $_[0]} #warn $_[0] if $verbose sub RightTest { # Feasibility test for rightmost PCR during rebuilding; avoids slow discovery that the last PCR is impossible; no tntBlast testing my ($len, $in, @pcrs, @tntin) = ($windows{Rout}); my @ok = ($len - $fLen - int($$set{REBUILD_WINDOW}/2) +2); $ok[1] = $ok[0] + $$set{REBUILD_WINDOW} -1; $ok[0] = $windows{Lout} if $ok[0] < $windows{Lout}; push @ok, @windows{qw/Rin Rout/}; if ($ok[2] == $ok[3]) {$in .= "SEQUENCE_FORCE_RIGHT_START=$ok[2]\n"; $ok[2] -= $$set{PRIMER_MAX_SIZE} - $optP} $in .= "SEQUENCE_PRIMER_PAIR_OK_REGION_LIST=" . join(',', $ok[0], $ok[1]-$ok[0]+$optP, $ok[2]-$optP+1, $len-$ok[2]+$optP) . "\n"; Log($in) if $verbose; open P3, ">p3in"; print P3 "$p3begin${in}SEQUENCE_TEMPLATE=$segs{$seg}{seq}\n=\n"; close P3; system "primer3_core p3in > p3out"; unless (-f 'p3out') {Log("WARNING: No Primer3 output for seg $seg RightTest\n"); unlink 'p3in'; return 0;} for (`cat p3out`) { push (@{$pcrs[$2]{$1}}, $3 ) if /^PRIMER_(R|L)[^_]+_(\d+)_SEQUENCE=(\S+)/; unshift (@{$pcrs[$2]{$1}}, $3, $4) if /^PRIMER_(R|L)[^_]+_(\d+)=(\d+),(\d+)/; } unlink 'p3in', 'p3out'; for (my $j=$#pcrs; $j >= 0; $j--) {splice(@pcrs, $j, 1) if $pcrs[$j]{L}[0] > $ok[1] or $pcrs[$j]{R}[0] < $ok[2]} # Primer3 5' control Log("RightTest on segment $seg: " . scalar(@pcrs) . " pairs\n") if $verbose; return scalar(@pcrs); } sub Primer3 { my ($i) = @_; my ($target, $len, $in, @pcrs, @tntin, @ok) = ($i * $fLen, $segs{$seg}{len}); # @ok holds ranges for acceptable 5' primer ends if ($i == 1) { # Special L end instructions for leftmost @ok = @windows{qw/Lout Lin/}; if ($ok[0] == $ok[1]) {$ok[1] += $$set{PRIMER_MAX_SIZE} - $optP; $in .= "SEQUENCE_FORCE_LEFT_START=$ok[0]\n"} } else { # All other fragments of rebuilding @ok = (${$frags[$i-1]}{R}[0] - $$set{OVERLAP_MAX_SIZE} + 1, ${$frags[$i-1]}{R}[0] - $$set{OVERLAP_MIN_SIZE} + 1); } if ($i == $fCt) { # Special R end instructions for rightmost push @ok, @windows{qw/Rin Rout/}; if ($ok[2] == $ok[3]) {$ok[2] -= $$set{PRIMER_MAX_SIZE} - $optP; $in .= "SEQUENCE_FORCE_RIGHT_START=$ok[3]\n"} $ok[3] = $len; } else { # All other fragments of rebuilding push @ok, $target - int($$set{REBUILD_WINDOW}/2), $target + int($$set{REBUILD_WINDOW}/2 - 1); } my $p3 = "$ok[0],$ok[3]"; return $p3s{$p3} if $p3s{$p3}; $in .= "SEQUENCE_PRIMER_PAIR_OK_REGION_LIST=" . join(',', $ok[0], $ok[1]-$ok[0]+$optP, $ok[2]-$optP+1, $ok[3]-$ok[2]+$optP) . "\n"; Log($in) if $verbose; open P3, ">p3in"; print P3 "$p3begin${in}SEQUENCE_TEMPLATE=$segs{$seg}{seq}\n=\n"; close P3; system "primer3_core p3in > p3out"; unless (-f 'p3out') {P3stats($i, 0, "WARNING: No Primer3 output for seg $seg $p3\n"); $p3s{$p3} = \@pcrs; return \@pcrs;} for (`cat p3out`) { $pcrs[$1]{pen} = $2 if /^PRIMER_PAIR_(\d+)_PENALTY=(\S+)/; push (@{$pcrs[$2]{$1}}, $3 ) if /^PRIMER_(R|L)[^_]+_(\d+)_SEQUENCE=(\S+)/; unshift (@{$pcrs[$2]{$1}}, $3, $4) if /^PRIMER_(R|L)[^_]+_(\d+)=(\d+),(\d+)/; } for my $j (0..$#pcrs) { $pcrs[$j]{uni} = abs($target - $pcrs[$j]{R}[0]); $pcrs[$j]{sum} = "$pcrs[$j]{L}[0]-$pcrs[$j]{R}[0],$pcrs[$j]{L}[1],$pcrs[$j]{R}[1]"; } if ($$set{OPTIMIZE} eq 'uniform' and $i != $fCt) { # Sort by closest to center of internal right window @pcrs = sort {$$a{uni} <=> $$b{uni}} @pcrs; } for (my $j=$#pcrs; $j >= 0; $j--) {splice(@pcrs, $j, 1) if $pcrs[$j]{L}[0] > $ok[1] or $pcrs[$j]{R}[0] < $ok[2] or $seen{$pcrs[$j]{R}[0]} or $tnts{$pcrs[$j]{sum}}} if ($$set{TNT_USE} eq 'per-recursion') { Log("Tnt launched for " . scalar(@pcrs) . " pcrs, per-recursion\n") if $verbose; for (@pcrs) {push @tntin, [@{$$_{L}}[0,2], @{$$_{R}}[0,2], $$_{sum}]} Tnt(\@tntin) if @tntin; for (my $j=$#pcrs; $j >= 0; $j--) {splice(@pcrs, $j, 1) if $tntbads{$pcrs[$j]{sum}}} } my $ct = scalar(@pcrs); P3stats($i, $ct, "Primer3 search on segment $seg: fragment $i left $ok[0]-$ok[1], right $ok[2]-$ok[3]: $ct pairs\n"); unlink 'p3in', 'p3out' unless $seg eq 'Ape1.38.V'; # CHANGE IN FINAL XXX $p3s{$p3} = \@pcrs; return \@pcrs; # Keys: pen uni L(pos,len) R(pos,len) } sub P3stats { my ($i, $ct, $log) = @_; if ($i == 1) {$stats{tryfrst} ++; $stats{frst} ++ if $ct} elsif ($i == $fCt) {$stats{trylast} ++; $stats{last} ++ if $ct} else {$stats{tryint} ++; $stats{int} ++ if $ct} Log($log) if $verbose; } sub ReadConfig { # L=0 > 1; R=0 > full-length my ($order, $type, $name) = (1); for (`cat $paths{in}/$configfile`) { next if /^#/; my ($key, $value) = ('', ''); chomp; if (/^(TYPE)=(\S+)/) { # Top record lines ($key, $value) = ($1, $2); $type = $value; Log("Undefined type $type\n"), exit unless $type =~ /^SETTING|REGION|SEGMENT$/; $setting .= "=\n" unless $type eq 'SETTING'; } elsif (/^(NAME)=(.+)/) { ($key, $value, $name) = ($1, $2, $2); Log("No type specified in configfile $configfile line $_\n"), exit unless $type; Log("Type $type name $value duplicated\n"), exit if $config{$type}{$value}; if ($type eq 'SEGMENT') {$segs{$value}{order} = $order; $order ++;} @{$config{$type}{$value}}{qw/FASTA ENTRY ANNOT L R ORIENT/} = ('', '', '', 1, 0, '+'); # R=0 changes to full length once known } elsif (/^\s*=\s*$/) { # Record end ($type, $name) = ('', ''); next } elsif (/^([^=#]+)=(.+)/) { # Tag, stopping early if SETTING ($key, $value) = ($1, $2); Log("No type specified in configfile $configfile line $_\n"), exit unless $type; if ($type eq 'SETTING') {$config{$type}{$key} = $value; next} Log("No name specified in configfile $configfile line $_\n"), exit unless $name; for (qw/FASTA ANNOT/) { # Convert relative path (from config file dir) into absolute path; check file existence next unless $key eq $_; $value =~ s/INSTALL/$paths{install}/; $value = File::Spec->rel2abs($value); unless (-f $value) {Log("No $_ $value\n"); exit} } $config{$type}{$name}{$key} = $value; if ($value =~ /[^\d]/ and ($key eq 'L' or $key eq 'R')) {Log("L and R values must be zero or positive integer\n"); exit} if ($key eq 'ORIENT' and $value !~ /^[\+\-]$/) {Log("ORIENT must be + or -\n"); exit} $config{$type}{$name}{L} = 1 unless $config{$type}{$name}{L}; } $setting .= "$key=$value\n" unless $type eq 'SETTING'; } for (qw/PRIMER_OPT_SIZE PCR_MAX_SIZE REBUILD_WINDOW OVERLAP_MAX_SIZE OVERLAP_MIN_SIZE OPTIMIZE/) {Log("FATAL: $_ not set\n"), exit unless defined $config{SETTING}{$_}} $config{SETTING}{optmax} = ''; $config{SETTING}{optmax} = $1 if $config{SETTING}{OPTIMIZE} =~ s/^(max)//; $config{SETTING}{opt} = $config{SETTING}{OPTIMIZE}; $config{SETTING}{opt} =~ s/^(...).*/$1/; # Short form often useful $optP = $$set{PRIMER_OPT_SIZE}; Log("No TYPE=SEGMENT line(s) in configfile $configfile\n"), exit unless %segs; } sub LoadTreats { my %treats = qw/hiL PRIMER_MAX_SIZE loT PRIMER_MIN_TM hiT PRIMER_MAX_TM hiH PRIMER_MAX_HAIRPIN_TH hiM PRIMER_MAX_POLY_X loG PRIMER_MIN_GC/; if ($$set{QUICK_P3}) { for my $t (split ',', $$set{QUICK_P3}) { $t =~ s/(\d+)$//; my $value = $1; next unless $treats{$t}; # Unrecognized abbreviation $$set{$treats{$t}} = $value; Log("Key Primer3 setting $treats{$t} ($t) = $value\n") if $verbose; } } if (%{$set}) { $setting .= "=\nTYPE=SETTING\n"; for (sort keys %{$set}) {$setting .= "$_=$$set{$_}\n"} } Log($setting . "=\n") if $verbose; } sub CollectSeqs { # Progresses to REGION if necessary to find FASTA for my $s (sort {$segs{$a}{order} <=> $segs{$b}{order}} keys %segs) { $seg = $config{SEGMENT}{$s}; if ($$seg{REFERENCE}) { # In case via REGION, first get REGION then SEGMENT my $name = $$seg{REFERENCE}; my $reg = $config{REGION}{$name}; unless ($$reg{seq}) { # Get REGION's seq etc. my @params = @{$reg}{qw/FASTA ENTRY L R ORIENT/}; @{$reg}{qw/seq ENTRY entrylen len source/} = GetSeq(@params); $$reg{annots} = GetAnnot($$reg{ANNOT}, @params) if $$reg{ANNOT}; } $$seg{FASTA} = $$reg{FASTA}; my @params = ($name, '', @{$seg}{qw/L R ORIENT/}); @{$seg}{qw/seq ENTRY entrylen len source/} = GetSeq(@params, $$reg{seq}, $$reg{entrylen}); $$seg{R} = $$seg{len} unless $$seg{R}; if ($$seg{ORIENT} eq $$reg{ORIENT}) {$$seg{FA_ORIENT} = '+'} else {$$seg{FA_ORIENT} = '-'} if ($$reg{ORIENT} eq '+') {@{$seg}{qw/FA_L FA_R/} = ($$reg{L}+$$seg{L}-1, $$reg{L}+$$seg{R}-1)} else {@{$seg}{qw/FA_L FA_R/} = ($$reg{R}-$$seg{R}+1, $$reg{R}-$$seg{L}+1)} $$seg{annots} = GetAnnot('', '', @params, $$reg{annots}) if @{$$reg{annots}}; $$seg{source} .= "=$$reg{source}"; } else { # Fasta specified directly for segment Log("No FASTA nor REFERENCE for segment $s\n"), exit unless $$seg{FASTA}; my @params = @{$seg}{qw/FASTA ENTRY L R ORIENT/}; @{$seg}{qw/seq ENTRY entrylen len source/} = GetSeq(@params); $$seg{R} = $$seg{len} unless $$seg{R}; @{$seg}{qw/FA_L FA_R FA_ORIENT/} = @{$seg}{qw/L R ORIENT/}; $$seg{annots} = GetAnnot($$seg{ANNOT}, @params) if $$seg{ANNOT}; } for (keys %{$seg}) {$segs{$s}{$_} = $$seg{$_}} } } sub GetSeq { my ($fa, $entry, $L, $R, $ori, $full, $entrylen, $collect, $seq) = @_; unless ($full) { for (`cat $fa`) { if (/^>(\S+)/) { last if $collect; $entry = $1 unless $entry; $collect ++ if $entry eq $1; } elsif ($collect) {chomp; $full .= $_} } } Log("No seq for entry $entry in fasta $fa\n"), exit unless $full; my $len = length($full); $entrylen = $len unless $entrylen; $R = $len unless $R; while ($R > $len) {$R -= $len} Log("R coord $R must be from 1 to length(=$len) of entry $entry in fasta $fa\n"), exit if $R > $len or $R < 1; if ($L <= $R) { Log("R coord $R must be greater than L coord $L < length $len\n"), exit unless $R > $L; $seq = uc substr($full, $L-1, $R-$L+1); } else { # Wrap around circle $seq = uc(substr($full, $L-1) . substr($full, 0, $R)); } if ($ori eq '-') {$seq = Revcomp($seq)} return ($seq, $entry, $entrylen, length($seq), "$fa/$entry:${L}_${R}_$ori"); } sub GetAnnot { my ($file, $fa, $entry, $L, $R, $ori, $ann, @annots) = @_; @annots = @{$ann} if $ann; if ($file) { for (`cat $file`) { my @f = split "\t"; if ($f[0] eq $entry and $f[3] > $L and $f[4] < $R) {push @annots, [@f]} } } for my $ann (@annots) { if ($ori eq '-') { ($$ann[3], $$ann[4]) = ($R-$$ann[4]+1, $R-$$ann[3]+1); $$ann[6] =~ tr/\+\-/-+/; } else { ($$ann[3], $$ann[4]) = ($$ann[3]-$L+1, $$ann[4]-$L+1); } } @annots = reverse @annots if $ori eq '-'; return \@annots; } sub Revcomp {my $seq = $_[0]; $seq =~ tr/ACGT/TGCA/; $seq = reverse $seq; return $seq} sub ReadDefault { $paths{lib} = $paths{install}; $paths{lib} .= '/lib'; for (`cat $paths{lib}/default.txt`) {chomp; $config{SETTING}{$1} = $2 if /^([^#]\S*)=(.+)/} $config{SETTING}{PRIMER_FIRST_BASE_INDEX} = 1; # Insist on 1-based indexing my $path = `which primer3_core`; chomp $path; Log("FATAL: No primer3_core in paths: $path\n"), exit unless $path =~ /\//; $path =~ s/primer3_core$/primer3_config\//; $config{SETTING}{PRIMER_THERMODYNAMIC_PARAMETERS_PATH} = $path; } sub Timer{my $t = sprintf("%.6f", time-$t0); return "[t=$t] "} sub Options { my $version = '1.1 (Oct 2021)'; # ' | ' | ' | ' | ' | ' | ' | ' | my $help = <<END; $scriptname version $version Usage: perl $scriptname [options] CONFIG_FILE -out <output directory> (default uses same directory as CONFIG_FILE) -verbose Print log messages to screen also Additional options: -help, -version, -authors, -license See README.txt for further details and CONFIG_FILE instructions. END die $help if @ARGV == 0; use Getopt::Long; my $options_okay = GetOptions( 'help' => sub {print $help; exit}, 'version' => sub {print "$scriptname version $version\n"; exit}, 'authors' => sub {print "AUTHORS: Ivan Vuong, Catherine Mageeney, Kelly Williams (kpwilli\@sandia.gov)\n"; exit}, 'license' => sub {print `cat $paths{install}/LICENSE`; exit}, 'verbose' => \$verbose, 'out=s' => \$paths{out}, ); die $help if !$options_okay; $configfile = $ARGV[-1]; die "No configuration file $configfile\n" unless -f $configfile; $paths{in} = File::Spec->rel2abs($configfile); $paths{in} =~ s/\/[^\/]*$//; $configfile =~ s/.*\///; $paths{out} = $paths{in} unless $paths{out}; mkdir $paths{out}; die "Output directory $paths{out} unavailable\n" unless -e $paths{out} and -d $paths{out}; }
high
0.135684
99,864
syntax = "proto3"; package maskDetection; message Alert { string event_time = 1; message Device { string type = 1; string guid = 2; string enrolled_on = 3; } Device created_by = 2; message Location { float longitude = 1; float latitude = 2; } Location location = 3; message Model { string name = 1; string guid = 2; float threshold = 3; } Model face_detection_model = 4; Model mask_classifier_model = 5; float probability = 6; message Image { message Size { int32 width = 1; int32 height = 2; } string format = 1; Size size = 2; bytes data = 3; } Image image = 7; }
low
0.451608
99,865
open main pred id2KwGSuj5M7q5CJe47_prop9 { all t:Train | some tk:Entry | eventually (t->tk in pos and before no t.pos) } pred __repair { id2KwGSuj5M7q5CJe47_prop9 } check __repair { id2KwGSuj5M7q5CJe47_prop9 <=> prop9o }
low
0.847513
99,866
\setcounter{section}{1} \section{Домашнє завдання за 9/12} \begin{problem}[Владимиров 5.18] Знайти всі характеристичні числа і відповідні власні функції наступних інтегральних рівнянь: \begin{enumerate} \item $\phi(x) = \lambda \Int_0^{2\pi} \left(\sin(x+y)+\dfrac12\right)\phi(y)dy$. \item[4.] $\phi(x) = \lambda \Int_0^1 \left(\left(\dfrac xy\right)^{2/5}+\bigg(\dfrac yx\bigg)^{2/5}\right)\phi(y)dy$ \end{enumerate} \end{problem} \begin{solution} \begin{enumerate} \item Це рівняння з виродженим ядром. Справді: \begin{equation*}\begin{split} \phi(x) &= \lambda \Int_0^{2\pi} \left(\sin(x+y)+\dfrac12\right)\phi(y)dy = \lambda \Int_0^{2\pi} \left(\sin x\cos y+\cos x\sin y+\dfrac12\right)\phi(y)dy = \\ &= \lambda \sin(x)\Int_0^{2\pi} \cos(y)\phi(y)dy + \lambda \cos(x)\Int_0^{2\pi} \sin(y)\phi(y)dy + \lambda \Int_0^{2\pi} \dfrac{\phi(y) dy}{2}. \end{split}\end{equation*} Позначаємо \[ c_1 = \Int_0^{2\pi} \cos(y)\phi(y)dy \qquad c_2 = \Int_0^{2\pi} \sin(y)\phi(y)dy \qquad c_3 = \Int_0^{2\pi} \dfrac{\phi(y) dy}{2},\] тоді \[ \phi(x) = \lambda \sin(x) c_1 + \lambda \cos(x) c_2 + \lambda c_3.\] Підставляємо це замість $\phi(y)$ в $c_1$, $c_2$, $c_3$: \begin{equation*}\left\{\begin{aligned} c_1 &= \Int_0^{2\pi} \cos(y)(\lambda \sin(y) c_1 + \lambda \cos(y) c_2 + \lambda c_3) dy &= 0 + \lambda\pi c_2 + 0 \\ c_2 &= \Int_0^{2\pi} \sin(y)(\lambda \sin(y) c_1 + \lambda \cos(y) c_2 + \lambda c_3) dy &= \lambda\pi c_1 + 0 + 0 \\ c_3 &= \Int_0^{2\pi} \dfrac{(\lambda \sin(y) c_1 + \lambda \cos(y) c_2 + \lambda c_3) dy}{2} &= 0 + 0 + \lambda \pi c_3 \end{aligned}\right.\end{equation*} Нескладно бачити, що $\lambda=\pm1/\pi$, а відповідними власними функціями будуть $\cos x\pm \sin x$. \item[4.] Це рівняння з виродженим ядром. Справді: \[ \phi(x) = \lambda \Int_0^1 \left(\left(\dfrac xy\right)^{2/5}+\bigg(\dfrac yx\bigg)^{2/5}\right)\phi(y)dy = \lambda x^{2/5}\Int_0^1 y^{-2/5}\phi(y) dy + \lambda x^{-2/5}\Int_0^1 y^{2/5}\phi(y)dy. \] Позначаємо \[c_1 = \Int_0^1 y^{-2/5}\phi(y) dy \qquad c_2 = \Int_0^1 y^{2/5}\phi(y) dy,\] тоді \[\phi(x) = \lambda x^{2/5} c_1 + \lambda x^{-2/5} c_2.\] Підставляємо це замість $\phi(y)$ в $c_1$, $c_2$: \begin{equation*}\left\{\begin{aligned} c_1 &= \Int_0^1 y^{-2/5}\left(\lambda y^{2/5} c_1 + \lambda y^{-2/5} c_2\right) dy &= \lambda c_1 + 5\lambda c_2 \\ c_2 &= \Int_0^1 y^{2/5}\left(\lambda y^{2/5} c_1 + \lambda y^{-2/5} c_2\right) dy &= \dfrac59\lambda c_1 + \lambda c_2 \end{aligned}\right.\end{equation*} Звідси маємо \[\begin{vmatrix} 1 - \lambda & - 5\lambda \\ - 5\lambda/9 & 1 - \lambda \end{vmatrix} = \lambda^2 - 2\lambda + 1 - 25\lambda^2/9 = \left(\lambda + \dfrac32\right) \left(\lambda - \dfrac38\right) = 0. \] При $\lambda = -3/2$ власною функцією буде $\phi(x) = 3x^{2/5} + x^{-2/5}$, а при $\lambda = 3/8$ -- $\phi(x) = 3x^{2/5} - x^{-2/5}$. \end{enumerate} \end{solution} \begin{problem}[Владимиров, 5.22] Знайти розв'язок наступних інтегральних рівнянь для всі $\lambda$ і для всіх значень параметрів $a$, $b$, $c$ що входять у вільний член цих рівнянь: \begin{enumerate} \item[3.] $\phi(x) = \lambda\Int_{-1}^1 (1 + xy) \phi(y) dy + ax^2 + bx + c$. \item[6.] $\phi(x) = \lambda\Int_{-1}^1 \left(5(xy)^{1/3} + 7(xy)^{2/3}\right) \phi(y) dy + a + bx^{1/3}$. \end{enumerate} \end{problem} \begin{solution} \begin{enumerate} \item[3.] Це рівняння з виродженим ядром. Справді: \[ \phi(x) = \lambda\Int_{-1}^1 (1 + xy) \phi(y) dy + ax^2 + bx + c = \lambda \Int_{-1}^1 \phi(y) dy + \lambda x \Int_{-1}^1 y \phi(y) dy + ax^2 + bx + c. \] Позначаємо \[ c_1 = \Int_{-1}^1 \phi(y) dy \qquad c_2 = \Int_{-1}^1 y \phi(y) dy, \] тоді \[ \phi(x) = \lambda c_1 + \lambda x c_2 + ax^2 + bx + c. \] Підставляємо це замість $\phi(y)$ в $c_1$, $c_2$: \begin{equation*}\left\{\begin{aligned} c_1 &= \Int_{-1}^1 \left(\lambda c_1 + \lambda y c_2 + ay^2 + by + c\right) dy &=& \,\, 2\lambda c_1 + \dfrac{2a}{3} + 2c \\ c_2 &= \Int_{-1}^1 y \left(\lambda c_1 + \lambda y c_2 + ay^2 + by + c\right) dy &=& \,\, \dfrac{2\lambda c_2}{3} + \dfrac{2b}{3} \end{aligned}\right.\end{equation*} Окремо розглянемо $\lambda = 1/2$ і $\lambda = 3/2$ як корені характеристичного поліному.\\ При $\lambda = 1/2$ маємо, що для існування розв'язку необхідно $2a/3 + 2c = 0$, а сам розв'язок набуває вигляду \[\phi(x) = c_1/2 + bx/2 + ax^2 + bx - a/3 = ax^2 + 3bx/2 + C_1.\] При $\lambda = 3/2$ маємо, що для існування розв'язку необхідно $2b/3 = 0$, а сам розв'язок набуває вигляду \[\phi(x) = (3/2)(2a/3 + 2c)/(-2) + (3/2)c_2 x + ax^2 + c = ax^2 + C_2x - (a + c)/2.\] Інакше ж маємо $c_1 = \dfrac{2(a + 3c)}{3(1 - 2\lambda)}$, $c_2 = \dfrac{2b}{3 - 2 \lambda}$, без жодних обмежень на $a$, $b$, $c$, тому розв'язок набуває вигляду \[\phi(x) = \dfrac{2\lambda(a + 3c)}{3(1 - 2\lambda)} + \dfrac{2\lambda b}{3 - 2 \lambda}x + ax^2 + bx + c = \dfrac{2\lambda a + 3c}{3(1 - 2\lambda)} + \dfrac{3b}{3 - 2 \lambda}x + ax^2.\] \item[6.] Це рівняння з виродженим ядром. Справді: \begin{equation*} \begin{aligned} \phi(x) &= \lambda\Int_{-1}^1 \left(5(xy)^{1/3} + 7(xy)^{2/3}\right) \phi(y) dy + a + bx^{1/3} = \\ &= \lambda x^{1/3}\Int_{-1}^1 5y^{1/3}\phi(y) dy + \lambda x^{2/3}\Int_{-1}^1 7y^{2/3} \phi(y) dy + ax + bx^{1/3}. \end{aligned} \end{equation*} Позначаємо \[ c_1 = \Int_{-1}^1 5y^{1/3} \phi(y) dy \qquad c_2 = \Int_{-1}^1 7y^{2/3} \phi(y) dy, \] тоді \[ \phi(x) = \lambda x^{1/3} c_1 + \lambda x^{2/3} c_2 + ax + bx^{1/3}. \] Підставляємо це замість $\phi(y)$ в $c_1$, $c_2$: \begin{equation*}\left\{\begin{aligned} c_1 &= \Int_{-1}^1 5y^{1/3} \left(\lambda y^{1/3} c_1 + \lambda y^{2/3} c_2 + ay + by^{1/3}\right) dy &=& \,\, 6\lambda c_1 + 30a/7 + 6b \\ c_2 &= \Int_{-1}^1 7y^{2/3} \left(\lambda y^{1/3} c_1 + \lambda y^{2/3} c_2 + ay + by^{1/3}\right) dy &=& \,\, 6\lambda c_2 \end{aligned}\right.\end{equation*} Окремо розглянемо $\lambda = 1/6$ як корінь характеристичного поліному. Маємо, що для існування розв'язку необхідно $30a/7 + 6b = 0$, а сам розв'язок набуває вигляду \[\phi(x) = ax + C_1 x^{1/3} + C_2 x^{2/3}. \] Інакше ж маємо $c_1 = \dfrac{30a + 42b}{7(1 - 6\lambda)}$, $c_2 = 0$, без жодних обмежень на $a$, $b$ тому розв'язок набуває вигляду \[\phi(x) = \dfrac{\lambda(30a + 42b)}{7(1 - 6\lambda)}x^{1/3} + ax + bx^{1/3} = \dfrac{30\lambda a + 7b}{7(1 - 6\lambda)}x^{1/3} + ax. \] \end{enumerate} \end{solution}
high
0.353826
99,867
local function AddedMe(msg) local text = msg.content_.text_ if ChatType == 'sp' or ChatType == 'gp' then if text and text:match("منو ضافني") then if not DevAbs:get(ANTIQUES..'Abs:Added:Me'..msg.chat_id_) then tdcli_function ({ID = "GetChatMember",chat_id_ = msg.chat_id_,user_id_ = msg.sender_user_id_},function(arg,da) if da and da.status_.ID == "ChatMemberStatusCreator" then Dev_Abs(msg.chat_id_, msg.id_, 1, '⌁︙انت منشئ المجموعه', 1, 'md') return false end local Added_Me = DevAbs:get(ANTIQUES.."Who:Added:Me"..msg.chat_id_..':'..msg.sender_user_id_) if Added_Me then tdcli_function ({ID = "GetUser",user_id_ = Added_Me},function(extra,result,success) local Name = '['..result.first_name_..'](tg://user?id='..result.id_..')' Text = '⌁︙*الشخص الذي قام باضافتك هو* ↫ '..Name SendText(msg.chat_id_,Text,msg.id_/2097152/0.5,'md') end,nil) else Dev_Abs(msg.chat_id_, msg.id_, 1, '⌁︙انت دخلت عبر الرابط', 1, 'md') end end,nil) else Dev_Abs(msg.chat_id_, msg.id_, 1, '⌁︙امر منو ضافني تم تعطيله من قبل المدراء', 1, 'md') end end if text == 'تفعيل ضافني' and Manager(msg) then DevAbs:del(ANTIQUES..'Abs:Added:Me'..msg.chat_id_) Dev_Abs(msg.chat_id_, msg.id_, 1, '⌁︙تم تفعيل امر منو ضافني', 1, 'md') end if text == 'تعطيل ضافني' and Manager(msg) then DevAbs:set(ANTIQUES..'Abs:Added:Me'..msg.chat_id_,true) Dev_Abs(msg.chat_id_, msg.id_, 1, '⌁︙تم تعطيل امر منو ضافني', 1, 'md') end end end return { ANTIQUES = AddedMe }
low
0.354833
99,868
#|------------------------------------------------------------*-Scheme-*--| | File: compiler/target.scm | | Copyright (C)1997 Donovan Kolbly <d.kolbly@rscheme.org> | as part of the RScheme project, licensed for free use. | See <http://www.rscheme.org/> for the latest information. | | File version: 1.13 | File mod date: 2003-10-13 13:01:45 | System build: v0.7.3.4-b7u, 2007-05-30 | Owned by module: (rsc) | `------------------------------------------------------------------------|# ;;; must be in sync with <<class>> and <<standard-class>> (define-class <<target-class>> (<object>) class-name heap-type image-mode superclasses (class-category type: <fixnum> init-value: 0) (class-hash type: <fixnum> init-value: 0) (properties type: <vector> init-value: '#()) ;; direct-slots all-slots instance-size corresponding-primtype class-precedence-list (spare-0 init-keyword: #f getter: #f setter: #f init-value: #f)) (add-mifio-class "<<standard-class>>" <<target-class>>) ;; the variable <<target-class>> is defined as a regular variable in ;; modules/compiler/classes.scm; we need to make it a constant... (set-write-prot! (& <<target-class>>) #t) ;;; (define-class <target-function> (<object>) template) (define-class <target-closure> (<target-function>) environment) (define-class <target-method> (<target-closure>) function-specializers (sync-method init-value: #f)) (define-class <target-gf1> (<target-function>) generic-function-methods function-specializers generic-function-name (gf-cache-0-k init-value: #f) (gf-cache-0-v init-value: #f) ;; [4 5] (gf-cache-1-k init-value: #f) (gf-cache-1-v init-value: #f) ;; [6 7] (gf-cache-2-k init-value: #f) (gf-cache-2-v init-value: #f) ;; [8 9] (gf-cache-3-k init-value: #f) (gf-cache-3-v init-value: #f) ;; [10 11] (gf-cache-V-k init-value: #f) (gf-cache-V-v init-value: #f) ;; [12 13] (gf-cache-overflow init-value: #f) (miss-count type: <fixnum> init-value: 0) (properties type: <vector> init-value: '#())) (add-mifio-class "<function>" <target-function>) (add-mifio-class "<closure>" <target-closure>) (add-mifio-class "<method>" <target-method>) (add-mifio-class "<single-dispatch-gf>" <target-gf1>) ;;; (define-class <target-slot-method> (<target-method>) (index type: <fixnum>) type-restriction ;; a <<target-class>> or a <patch> (slot-descriptor type: <slot-descriptor>)) (define-class <target-getter> (<target-slot-method>)) (define-class <target-setter> (<target-slot-method>)) (add-mifio-class "<getter>" <target-getter>) (add-mifio-class "<setter>" <target-setter>) #| (define $target-classes (list <<target-class>> <target-getter> <target-setter>)) |# ;;; (define-syntax (target-class? o) (instance? o <<target-class>>)) ;;; ;; class introspection ;; return a list of all the class's <slot-descriptor>'s (including inherited) (define (tclass-slots c) (if (null? (tclass-supers c)) (tclass-direct-slots c) (append (tclass-slots (car (tclass-supers c))) (tclass-direct-slots c)))) (define (tclass-supers c) (superclasses (actual-value c))) (define (tclass-direct-slots c) (direct-slots (actual-value c))) (define (tclass-precedence-list (c <<target-class>>)) (if (null? (superclasses c)) (list c) (cons c (tclass-precedence-list (car (superclasses c)))))) (define (target-expr-value expr lex-envt dyn-envt) (let ((ic (compile expr lex-envt dyn-envt 'value))) (if (compile-time-const? ic) (compile-time-const-value ic) (error "~s: not a constant expression" expr)))) (define (method-dispatch-class (m <target-method>)) (car (function-specializers m))) (define (find-method-by-class (gf <target-gf1>) class) (let loop ((i (generic-function-methods gf))) (if (pair? i) (if (target-subclass? class (method-dispatch-class (car i))) (car i) (loop (cdr i))) #f))) (define-method write-object ((self <<target-class>>) port) (format port "#[<<target-class>> ~s]" (class-name self))) ;;; ;;; standard ones ;;; (mifio-class "<symbol>" <symbol>) (mifio-class "<vector>" <vector>) (mifio-class "<string>" <string>) (mifio-class "<pair>" <pair>) (mifio-class "<double-float>" <double-float>) (mifio-class "<table>" <table>) (mifio-class "<string-table>" <string-table>) (mifio-class "<string-ci-table>" <string-ci-table>) (mifio-class "<object-table>" <object-table>) (mifio-class "<eq-table>" <eq-table>) (mifio-class "<table-bucket>" <table-bucket>) (mifio-class "<long-int>" <long-int>) ;; ;; these are built in to 0.6, but not 0.5 (mifio-class "<top-level-var>" <top-level-var>) (mifio-class "<top-level-contour>" <top-level-contour>) ;; note that a <lexical-contour> can occur in a module image if ;; a <macro> captures a contour containing macros. This may be ;; a good reason right here to distinguish variable-type contours ;; from syntactic contours, since the latter preserve top-levelness ;; and can be in an image, wheras the former do not. (mifio-class "<lexical-contour>" <lexical-contour>) (mifio-class "<binding-envt>" <binding-envt>) (mifio-class "<slot-descriptor>" <slot-descriptor>) (mifio-class "<rewriter>" <rewriter>) (mifio-class "<macro>" <macro>) (mifio-class "<macro-form>" <macro-form>) (mifio-class "<substitution>" <substitution>) (mifio-class "<primop>" <primop>) (mifio-class "<template>" <template>) ;;; (mifio-class "<bignum>" <bignum>) (mifio-class "<mp-rational>" <mp-rational>) (mifio-class "<mp-data>" <mp-data>)
high
0.333318
99,869
module Foursquare class Venue attr_reader :json def initialize(foursquare, json) @foursquare, @json = foursquare, json end def fetch @json = @foursquare.get("venues/#{id}")["venue"] self end def id @json["id"] end def name @json["name"] end def contact @json["contact"] end def twitter contact['twitter'] end def location Foursquare::Location.new(@json["location"]) end def categories @categories ||= @json["categories"].map { |hash| Foursquare::Category.new(hash) } end def verified? @json["verified"] end def checkins_count @json["stats"]["checkinsCount"] end def users_count @json["stats"]["usersCount"] end def todos_count @json["todos"]["count"] end def stats @json["stats"] end def primary_category return nil if categories.blank? @primary_category ||= categories.select { |category| category.primary? }.first end # return the url to the icon of the primary category # if no primary is available, then return a default icon def icon primary_category ? Foursquare::Icon.new(primary_category["icon"]) : Foursquare::Icon.venue end def short_url @json["shortUrl"] end def url @json["url"] end def photos_count @json["photos"]["count"] end # not all photos may be present here (but we try to avoid one extra API call) # if you want to get all the photos, try all_photos def photos return all_photos if @json["photos"].blank? @json["photos"]["groups"].select { |g| g["type"] == "venue" }.first["items"].map do |item| Foursquare::Photo.new(@foursquare, item) end end # https://developer.foursquare.com/docs/venues/photos.html def all_photos(options={:group => "venue"}) @foursquare.get("venues/#{id}/photos", options)["photos"]["items"].map do |item| Foursquare::Photo.new(@foursquare, item) end end # count the people who have checked-in at the venue in the last two hours def here_now_count fetch unless @json.has_key?("hereNow") @json["hereNow"]["count"] end # returns a list of checkins (only if a valid oauth token from a user is provided) # https://developer.foursquare.com/docs/venues/herenow.html # options: limit, offset, aftertimestamp def here_now_checkins(options={:limit => "50"}) @foursquare.get("venues/#{id}/herenow", options)["hereNow"]["items"].map do |item| Foursquare::Checkin.new(@foursquare, item) end end # Returns a list of stats for a managed venue. Will return an error if the user # is not managing that venue def managed_stats(options={}) response = @foursquare.get("venues/#{id}/stats", options)["stats"] Foursquare::VenueStats.new(response) end end end
high
0.660788
99,870
\relax \@writefile{toc}{\boolfalse {citerequest}\boolfalse {citetracker}\boolfalse {pagetracker}\boolfalse {backtracker}\relax } \@writefile{lof}{\boolfalse {citerequest}\boolfalse {citetracker}\boolfalse {pagetracker}\boolfalse {backtracker}\relax } \@writefile{lot}{\boolfalse {citerequest}\boolfalse {citetracker}\boolfalse {pagetracker}\boolfalse {backtracker}\relax } \abx@aux@refcontext{ydnt/global//global/global} \providecommand\babel@aux[2]{} \@nameuse{bbl@beforestart} \abx@aux@read@bbl@mdfivesum{nobblfile} \babel@aux{english}{} \@writefile{toc}{\defcounter {refsection}{0}\relax }\@writefile{toc}{\contentsline {section}{\numberline {1}Education}{1}{}\protected@file@percent } \@writefile{toc}{\defcounter {refsection}{0}\relax }\@writefile{toc}{\contentsline {section}{\numberline {2}Skills}{1}{}\protected@file@percent } \@writefile{toc}{\defcounter {refsection}{0}\relax }\@writefile{toc}{\contentsline {section}{\numberline {3}Projects}{1}{}\protected@file@percent } \@writefile{toc}{\defcounter {refsection}{0}\relax }\@writefile{toc}{\contentsline {section}{\numberline {4}Experience}{1}{}\protected@file@percent } \@writefile{toc}{\defcounter {refsection}{0}\relax }\@writefile{toc}{\contentsline {section}{\numberline {5}Scholarships and Awards}{1}{}\protected@file@percent } \newlabel{LastPage}{{}{1}} \xdef\lastpage@lastpage{1} \gdef\lastpage@lastpageHy{} \gdef \@abspage@last{1}
high
0.437253
99,871
#!/usr/bin/env bash SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" source "${SCRIPT_DIR}/utils.sh" set -eo pipefail main_srcdir="$1" [[ -n "${main_srcdir}" ]] || die "Usage: $0 <directory with main file>" x_defs=() x_def_errors=() while read -r line || [[ -n "$line" ]]; do if [[ "$line" =~ ^[[:space:]]*$ ]]; then continue elif [[ "$line" =~ ^([^[:space:]]+)[[:space:]]+(.*)[[:space:]]*$ ]]; then var="${BASH_REMATCH[1]}" def="${BASH_REMATCH[2]}" eval "stamp_${var}=$(printf '%q' "$def")" else die "Malformed variable_stamps.sh output line ${line}" fi done < <("${SCRIPT_DIR}/variable_stamps.sh") while read -r line || [[ -n "$line" ]]; do if [[ "$line" =~ ^[[:space:]]*$ ]]; then continue elif [[ "$line" =~ ^([^:]+):([[:digit:]]+):[[:space:]]*(var[[:space:]]+)?([^[:space:]]+)[[:space:]].*//XDef:([^[:space:]]+)[[:space:]]*$ ]]; then go_file="${BASH_REMATCH[1]}" go_line="${BASH_REMATCH[2]}" go_var="${BASH_REMATCH[4]}" stamp_var="${BASH_REMATCH[5]}" varname="stamp_${stamp_var}" [[ -n "${!varname}" ]] || x_def_errors+=( "Variable ${go_var} defined in ${go_file}:${go_line} references status var ${stamp_var} that is not part of the variable_stamps.sh output" ) go_package="$(cd "${SCRIPT_DIR}/.."; go list -e "./$(dirname "$go_file")")" x_defs+=(-X "\"${go_package}.${go_var}=${!varname}\"") fi done < <(git -C "${SCRIPT_DIR}/.." grep -n '//XDef:' -- '*.go') if [[ "${#x_def_errors[@]}" -gt 0 ]]; then printf >&2 "%s\n" "${x_def_errors[@]}" exit 1 fi ldflags=(-s -w "${x_defs[@]}") [[ -n "${GOOS}" ]] || die "GOOS must be set" bin_name="$(basename "$main_srcdir")" output_file="bin/${GOOS}/${bin_name}" if [[ "$GOOS" == "windows" ]]; then output_file="${output_file}.exe" fi mkdir -p "$(dirname "$output_file")" echo >&2 "Compiling Go source in ${main_srcdir} to ${output_file}" go build -ldflags="${ldflags[*]}" -o "${output_file}" "${main_srcdir}"
low
0.203077
99,872
--- title: 開始使用 R 教學課程 description: 在 Visual Studio 中使用 R 的逐步解說,包括專案建立、互動式視窗、程式碼編輯和偵錯。 ms.date: 06/29/2017 ms.topic: tutorial author: kraigb ms.author: kraigb manager: jillfra ms.workload: - data-science ms.openlocfilehash: df46a2731f9923d85a16082f96c44947099db592 ms.sourcegitcommit: 94b3a052fb1229c7e7f8804b09c1d403385c7630 ms.translationtype: HT ms.contentlocale: zh-TW ms.lasthandoff: 04/23/2019 ms.locfileid: "63000424" --- # <a name="get-started-with-r-tools-for-visual-studio"></a>Visual Studio R 工具使用者入門 一旦安裝了 Visual Studio R 工具 (RTVS) (請參閱[安裝](installing-r-tools-for-visual-studio.md)),便可以快速體驗一下這些工具提供的體驗。 ## <a name="create-an-r-project"></a>建立 R 專案 1. 開啟 Visual Studio。 1. 選擇 檔案 > 新增 > 專案 (**Ctrl**+**Shift**+**N**) 1. 從 [範本] > [R] 下選取 [R 專案]、提供專案名稱和位置,然後選取 [確定]: ![Visual Studio R (在 VS2017 中為 RTVS) 的 [新增專案] 對話方塊](media/getting-started-01-new-project.png) 1. 建立專案之後,您會看到下列視窗︰ - 右邊為 Visual Studio 方案總管,您會在此看到專案,位於包含的「解決方案」內。 (解決方案可以包含任意數目且不同類型的專案,如需詳細資料,請參閱[專案](r-projects-in-visual-studio.md)。 - 左上方是新的 R 檔案 (`script.R`),您可以在其中使用 Visual Studio 所有的編輯功能來編輯原始程式碼。 - 左下方是 [R 互動] 視窗,您可以在其中以互動方式開發及測試程式碼。 > [!Note] > 您可以使用 [R 互動] 視窗而不開啟任何專案,甚至是在載入不同的專案類型時。 只要隨時選取 [R 工具] > [視窗] > [R 互動]。 ## <a name="explore-the-interactive-window-and-intellisense"></a>瀏覽 Interactive 視窗和 IntelliSense 1. 藉由鍵入 `3 + 4` 然後按 **Enter** 鍵查看結果,測試互動式視窗是否在運作中︰ ![Visual Studio 2017 (VS2017) 中的 R 互動視窗](media/getting-started-02-interactive1.png) 1. 輸入稍微複雜的內容 `ds <- c(1.5, 6.7, 8.9) * 1:12`,然後輸入 `ds` 查看結果︰ ![Visual Studio R 的其他互動式範例](media/getting-started-03-interactive2.png) 1. 輸入 `mean(ds)`,但請注意,只要您輸入 `m` 或 `me`,Visual Studio IntelliSense 就會提供自動完成的選項。 在清單中選取您想要的完成時,按 **Tab** 鍵插入。您可以使用方向鍵或滑鼠變更選取範圍。 ![您輸入程式碼時會顯示 IntelliSense](media/getting-started-04-intellisense1.png) 1. 完成 `mean` 之後,輸入左括弧 `(`,並注意 IntelliSense 如何提供您函式的內嵌說明︰ ![IntelliSense 顯示函式的說明](media/getting-started-05-intellisense2.png) 1. 完成 `mean(ds)` 一行並按 Enter 查看結果 (`[1] 39.51667`)。 1. Interactive 視窗已和說明整合,因此輸入 `?mean` 會在 Visual Studio 的 [R 說明] 視窗中顯示該函式的說明。 如需詳細資訊,請參閱 [Visual Studio R 工具中的說明](getting-started-help.md)。 ![Visual Studio 的 [R 說明] 視窗](media/getting-started-06-help.png) 1. 一些命令,例如 `plot(1:100)`,會在無法直接於 Interactive 視窗中顯示輸出時,在 Visual Studio 中開啟新視窗: ![在 Visual Studio 中顯示繪圖](media/getting-started-07-plot-window.png) 互動式視窗也可讓您檢閱您的歷程記錄、載入和儲存工作區、附加至偵錯工具,並與原始程式碼檔案互動,而不使用複製貼上。 如需詳細資料,請參閱[使用 R 互動視窗](interactive-repl-for-r-in-visual-studio.md)。 ## <a name="experience-code-editing-features"></a>體驗程式碼編輯功能 簡短地使用互動式視窗,示範了也適用於程式碼編輯器的基本編輯功能,例如 IntelliSense。 如果您如同之前一樣輸入相同的程式碼,您會看到相同的自動完成和 IntelliSense 提示,但輸出不會相同。 在 *.R* 檔案中撰寫程式碼可讓您一次看到所有程式碼,並且能較輕鬆地進行細微變更,然後快速在互動式視窗中執行程式碼,以查看結果。 您也可以在專案中有任意數目的檔案。 當程式碼在檔案中時,您也可以在偵錯工具中逐步執行程式碼 (在本文中稍後討論)。 當您開發計算演算法並撰寫程式碼來管理一或多個資料集時,尤其是當您想要檢查所有中繼結果時,這些功能很有幫助。 舉例來說,下列步驟會建立一些程式碼來探索 [Central Limit Theorem](https://en.wikipedia.org/wiki/Central_limit_theorem) (中央限制理論) (Wikipedia)。 (這個範例取自於 Paul Teetor 的 *R Cookbook*。) 1. 在 `script.R` 編輯器中,輸入下列程式碼: ```R mu <- 50 stddev <- 1 N <- 10000 pop <- rnorm(N, mean = mu, sd = stddev) plot(density(pop), main = "Population Density", xlab = "X", ylab = "") ``` 1. 若要快速查看結果,請選取所有程式碼 (**Ctrl**+**A**),然後按 **Ctrl**+**Enter** 鍵或以滑鼠右鍵按一下並選取 [以互動方式執行]。 所有選取的程式碼會在互動式視窗中執行,就彷彿您直接鍵入一樣,並在繪圖視窗中顯示結果︰ ![在 Visual Studio 中顯示繪圖](media/getting-started-08-plot1.png) 1. 針對某一行,隨時按 **Ctrl**+**Enter**,在互動式視窗中執行這一行。 > [!Tip] > 了解進行編輯並按 **Ctrl**+**Enter** 鍵 (或用 **Ctrl**+**A** 選取所有項目,然後按 **Ctrl**+**Enter** 鍵) 以快速執行程式碼的模式。 這樣做會比使用滑鼠進行相同的作業更有效率。 > > 此外,您可以將繪圖視窗從 Visual Studio 框架拖曳出來,放在顯示畫面上您想要的其他任何地方。 您可以輕鬆地將繪圖視窗調整成您想要的尺寸,然後將它儲存成影像或 PDF 檔案。 1. 新增幾行程式碼,包含第二個繪圖︰ ```R n <- 30 samp.means <- rnorm(N, mean = mu, sd = stddev / sqrt(n)) lines(density(samp.means)) ``` 1. 再次按 **Ctrl**+**A** 和 **Ctrl**+**Enter**,執行程式碼以產生下列結果︰ ![Visual Studio 中的更新雙重繪圖](media/getting-started-09-plot2.png) 1. 問題是,第一個繪圖決定了垂直的比例,因此第二個繪圖 (與 `lines`) 不符。 若要修正此問題,我們必須在 `plot` 呼叫上設定 `ylim` 參數,但要正確地這麼做,我們需要新增程式碼來計算垂直的最大值。 在互動式視窗中逐行這麼做不太方便,因為我們需要重新排列程式碼,在呼叫 `plot` 之前先使用 `samp.means`。 不過在程式碼檔案中,我們可以輕鬆地進行適當的編輯︰ ```R mu <- 50 stddev <- 1 N <- 10000 pop <- rnorm(N, mean = mu, sd = stddev) n <- 30 samp.means <- rnorm(N, mean = mu, sd = stddev / sqrt(n)) max.samp.means <- max(density(samp.means)$y) plot(density(pop), main = "Population Density", ylim = c(0, max.samp.means), xlab = "X", ylab = "") lines(density(samp.means)) ``` 1. 再次按 **Ctrl**+**A** 和 **Ctrl**+**Enter** 鍵,查看結果︰ ![Visual Studio 中的更新雙重繪圖,比例正確](media/getting-started-10-plot3.png) 您在編輯器中還可以做其他事。 如需詳細資料,請參閱[編輯 R 程式碼](editing-r-code-in-visual-studio.md)、[IntelliSense](r-intellisense.md) 和[程式碼片段](code-snippets-for-r.md)。 ## <a name="debug-your-code"></a>偵錯程式碼 Visual Studio 的其中一項主要優點是其偵錯 UI。 RTVS 建置在這項強固的基礎上,並新增創新的 UI,例如[變數總管](variable-explorer.md)。 在這裡,我們只是初探一下偵錯。 1. 若要開始,請重設目前的工作區,清除到目前為止已經進行的一切,方法是使用 [R 工具] > [工作階段] > [重設] 功能表命令。 根據預設,您在互動式視窗中所做的一切都會累算到目前工作階段,然後也會由偵錯工具使用。 藉由重設工作階段,您可以確保偵錯工作階段開始時沒有任何預先存在的資料。 不過 [重設] 並不會影響您的 *script.R* 來源檔案,因為它是在工作區之外管理和儲存。 1. 使用上一節中所建立的 *script.R* 檔案,在開頭為 `pop <-` 的行上設定中斷點,方法是將插入號放在該行上然後按 **F9** 鍵,或選取 [偵錯] > [切換中斷點] 功能表命令。 或者,只要按一下出現紅色中斷點的那一行的左邊界 (或裝訂邊)︰ ![在編輯器中設定中斷點](media/getting-started-11-debug1.png) 1. 使用 *script.R* 中的程式碼啟動偵錯工具,方法是選取工具列上的 [執行啟動檔案] 按鈕、選取 [偵錯] > [執行啟動檔案] 功能表項目,或按 **F5** 鍵。 Visual Studio 會進入偵錯模式,並開始執行程式碼。 不過,它會停在您設定中斷點的行上︰ ![在 Visual Studio 偵錯工具的中斷點上停止](media/getting-started-12-debug2.png) 1. 在偵錯期間,Visual Studio 提供逐步執行逐行程式碼行的能力。 您也可以逐步執行函式、不進入函式,或跳離函式到呼叫的內容。 這些功能,以及其他功能,可以在 [偵錯] 功能表、編輯器的快顯內容功能表,和 [偵錯] 工具列中找到︰ ![Visual Studio 中的 [偵錯] 工具列](media/getting-started-13-debug3.png) 1. 在中斷點停止時,您可以檢查變數的值。 在 Visual Studio 中找到 [自動變數] 視窗,在底部選取名為 [區域變數] 的索引標籤。 [區域變數] 視窗會顯示程式目前位置的區域變數。 如果您停在稍早設定的中斷點上,則會看到尚未定義 `pop` 變數。 現在,使用 [偵錯] > [不進入函式] 命令 (**F10**),您會看到出現 `pop` 的值︰ ![Visual Studio 中的 [區域變數] 視窗](media/getting-started-14-debug4.png) 1. 若要檢查不同範圍中的變數,包括全域範圍和套件範圍,則是使用[變數總管](variable-explorer.md)。 變數總管也讓您能夠切換到具有可排序資料行的表格式檢視,以及將資料匯出至 CSV 檔案。 ![變數總管的展開檢視](media/variable-explorer-expanded-results.png) 1. 您可以繼續逐步執行程式行,或選取 [繼續] (**F5**) 來執行到完成 (或下一個中斷點)。 若要深入資訊,請參閱[偵錯](debugging-r-in-visual-studio.md)和[變數總管](variable-explorer.md)。 ## <a name="next-steps"></a>後續步驟 在此逐步解說中,您已了解 R 專案的基本概念、使用互動式視窗、程式碼編輯,以及在 Visual Studio 中偵錯。 若要繼續探索更多的功能,請參閱下列文章,以及目錄中所示的文章︰ - [範例專案](getting-started-samples.md) - [編輯程式碼](editing-r-code-in-visual-studio.md) - [偵錯](debugging-r-in-visual-studio.md) - [工作區](r-workspaces-in-visual-studio.md) - [視覺化資料](visualizing-data-with-r-in-visual-studio.md)
high
0.39386
99,873
(* adapted from Peter Lammich and René Neumann *) theory DFS_Phase imports Specification DFS_Framework.DFS_Framework CAVA_Automata.Digraph_Impl \<comment> \<open>maybe \<open>Digraph\<close> is enough?\<close> DFS_Framework.Impl_Rev_Array_Stack begin locale node_and_MST_in_graph = complete_finite_weighted_graph G weight + T: tree T for G::\<open>('v,'w::weight) graph\<close> and weight and T::\<open>('v,'w) graph\<close> + fixes v::\<open>'v\<close> assumes v_in_V: \<open>v \<in> V\<close> and mst: \<open>minimum_spanning_tree T G\<close> begin lemma n_in_TV_iff: \<open>n \<in> T.V \<longleftrightarrow> n \<in> V\<close> using mst[unfolded minimum_spanning_tree_def spanning_tree_def] by (meson subgraph_node) lemma v_in_TV: \<open>v \<in> T.V\<close> using n_in_TV_iff v_in_V by blast definition T' where \<open>T' asdf = \<lparr>g_V = V, g_E = {(v,v'). (\<exists>w.(v,w,v')\<in>T.E) \<or> (\<exists>w.(v',w,v)\<in>T.E)}, g_V0 = {v},\<dots>=asdf\<rparr>\<close> sublocale dTgraph: graph "(T' ())" apply standard apply (auto simp: T'_def E_validD v_in_TV v_in_V) using T.E_validD n_in_TV_iff by blast+ lemma finite_dTgraph_reachable: \<open>finite dTgraph.reachable\<close> unfolding T'_def using dTgraph.finite_E by (simp add: T'_def) lemma finite_dTgraph_V0: \<open>finite dTgraph.V0\<close> by (simp add: dTgraph.finite_V0 finite_dTgraph_reachable) lemma reachable_finite: \<open>\<And>v. v \<in> dTgraph.reachable \<Longrightarrow> finite (dTgraph.E `` {v})\<close> by (simp add: dTgraph.fb_graphI_fr fb_graph.finitely_branching finite_dTgraph_reachable) end lemma (in complete_finite_weighted_graph) node_and_MST_in_graphI: assumes \<open>minimum_spanning_tree T G\<close> and \<open>v \<in> nodes G\<close> shows \<open>node_and_MST_in_graph G weight T v\<close> using assms by (simp add: complete_finite_weighted_graph_axioms minimum_spanning_tree_def node_and_MST_in_graph.intro node_and_MST_in_graph_axioms_def spanning_tree_def) txt \<open>more robust variant in case of additional type constraints in \<^locale>\<open>node_and_MST_in_graph\<close>'s def:\<close> lemma node_and_MST_in_graphI: assumes \<open>complete_finite_weighted_graph G weight\<close> and \<open>minimum_spanning_tree T G\<close> and \<open>v \<in> nodes G\<close> shows \<open>node_and_MST_in_graph G weight T v\<close> using assms by (simp add: minimum_spanning_tree_def node_and_MST_in_graph_axioms_def node_and_MST_in_graph_def spanning_tree_def) subsection \<open>Framework Instantiation\<close> text \<open> Define a state, based on the DFS-state.\<close> record 'v cycc_state = "'v state" + break :: \<open>'v list\<close> text \<open>Some utility lemmas for the simplifier, to handle idiosyncrasies of the record package. \<close> lemma break_more_cong: "state.more s = state.more s' \<Longrightarrow> break s = break s'" by (cases s, cases s', simp) lemma [simp]: "s\<lparr> state.more := \<lparr> break = foo \<rparr> \<rparr> = s \<lparr> break := foo \<rparr>" by (cases s) simp text \<open> Define the parameterization. We start at a default parameterization, where all operations default to skip, and just add the operations we are interested in: Initially, the break flag is false, it is set if we encounter a back-edge, and once set, the algorithm shall terminate immediately. \<close> definition cycc_params :: "('v,('v,unit) cycc_state_ext) parameterization" where "cycc_params \<equiv> dflt_parametrization state.more (RETURN \<lparr> break = [] \<rparr>) \<lparr> on_discover := \<lambda>_ n s. RETURN \<lparr>break = break s @ [n]\<rparr> \<^cancel>\<open>,on_back_edge := \<lambda>_ _ . RETURN o state.more,\<close> \<^cancel>\<open>is_break := \<lambda>s. break s = []\<close> \<rparr>" lemmas cycc_params_simp[simp] = gen_parameterization.simps[mk_record_simp, OF cycc_params_def[simplified]] interpretation cycc: param_DFS_defs where param=cycc_params for G . text \<open>The total correct variant asserts finitely many reachable nodes.\<close> definition "cyc_checkerT G weight T v \<equiv> do { ASSERT (node_and_MST_in_graph G weight T v); s \<leftarrow> cycc.it_dfsT TYPE('a) (node_and_MST_in_graph.T' G T v (undefined::'a)); RETURN (break s) }" \<^cancel>\<open>text \<open> Next, we define a locale for the cyclicity checker's precondition and invariant, by specializing the \<open>param_DFS\<close> locale.\<close> locale cycc = param_DFS G cycc_params for G :: "('v, 'more) graph_rec_scheme" begin text \<open>We can easily show that our parametrization does not fail, thus we also get the DFS-locale, which gives us the correctness theorem for the DFS-scheme \<close> sublocale DFS G cycc_params apply unfold_locales apply simp_all done thm it_dfs_correct \<comment> \<open>Partial correctness\<close> thm it_dfsT_correct \<comment> \<open>Total correctness if set of reachable states is finite\<close> end\<close> context node_and_MST_in_graph begin sublocale DFS "T' ()" cycc_params apply unfold_locales apply simp_all apply (fact finite_dTgraph_V0) by (fact reachable_finite) thm it_dfs_correct \<comment> \<open>Partial correctness\<close> thm it_dfsT_correct \<comment> \<open>Total correctness if set of reachable states is finite\<close> end text \<open>Next, we specialize the @{term DFS_invar} locale to our parameterization. This locale contains all proven invariants. When proving new invariants, this locale is available as assumption, thus allowing us to re-use already proven invariants. \<close> locale cycc_invar = dTgraph: DFS_invar where param = cycc_params and G = \<open>node_and_MST_in_graph.T' G T v ()\<close> + node_and_MST_in_graph text \<open> The lemmas to establish invariants only provide the \<open>DFS_invar\<close> locale. This lemma is used to convert it into the \<open>cycc_invar\<close> locale. \<close> lemma (in node_and_MST_in_graph) cycc_invar_eq[simp]: assumes \<open>DFS_invar (node_and_MST_in_graph.T' G T v ()) cycc_params s\<close> shows "cycc_invar s G weight T v" proof assume "DFS_invar (node_and_MST_in_graph.T' G T v) cycc_params s" interpret DFS_invar "(node_and_MST_in_graph.T' G T v)" cycc_params s by fact show "cycc_invar s G weight T v" by unfold_locales next assume "cycc_invar G s" then interpret cycc_invar G s . show "DFS_invar G cycc_params s" by unfold_locales qed*) subsection \<open>Correctness Proof\<close> text \<open> We now enter the \<open>cycc_invar\<close> locale, and show correctness of our cyclicity checker. \<close> context cycc_invar begin text \<open>We show that we break if and only if there are back edges. This is straightforward from our parameterization, and we can use the @{thm [source] dTgraph.establish_invarI} rule provided by the DFS framework. We use this example to illustrate the general proof scheme: \<close> lemma (in node_and_MST_in_graph) \<open>is_invar (\<lambda>s. tour (break s))\<close> proof (induct rule: establish_invarI) case init then show ?case sorry next case (new_root s s' v0) then show ?case by (simp_all cong: break_more_cong) next case (finish s s' u) then show ?case by (simp_all cong: break_more_cong) next case (cross_edge s s' u v) then show ?case by (simp_all cong: break_more_cong) next case (back_edge s s' u v) then show ?case by (simp_all cong: break_more_cong) next case (discover s s' u v) then show ?case sorry qed (* lemma (in cycc) i_brk_eq_back: "is_invar (\<lambda>s. break s = [] \<longleftrightarrow> back_edges s \<noteq> {})" proof (induct rule: establish_invarI) txt \<open>The @{thm establish_invarI} rule is used with the induction method, and yields cases\<close> print_cases txt \<open>Our parameterization has only hooked into initialization and back-edges, so only these two cases are non-trivial\<close> case init thus ?case try by (simp add: empty_state_def) next case (back_edge s s' u v) txt \<open>For proving invariant preservation, we may assume that the invariant holds on the previous state. Interpreting the invariant locale makes available all invariants ever proved into this locale (i.e., the invariants from all loaded libraries, and the ones you proved yourself.). \<close> then interpret cycc_invar G s by simp txt \<open>However, here we do not need them:\<close> from back_edge show ?case by simp qed (simp_all cong: break_more_cong) text \<open>For technical reasons, invariants are proved in the basic locale, and then transferred to the invariant locale:\<close> lemmas brk_eq_back = i_brk_eq_back[THEN make_invar_thm] text \<open>The above lemma is simple enough to have a short apply-style proof:\<close> lemma (in cycc) i_brk_eq_back_short_proof: "is_invar (\<lambda>s. break s \<longleftrightarrow> back_edges s \<noteq> {})" apply (induct rule: establish_invarI) apply (simp_all add: cond_def cong: break_more_cong) apply (simp add: empty_state_def) done text \<open>Now, when we know that the break flag indicates back-edges, we can easily prove correctness, using a lemma from the invariant library:\<close> thm cycle_iff_back_edges lemma cycc_correct_aux: assumes NC: "\<not>cond s" shows "break s \<longleftrightarrow> \<not>acyclic (E \<inter> reachable \<times> UNIV)" proof (cases "break s", simp_all) assume "break s" with brk_eq_back have "back_edges s \<noteq> {}" by simp with cycle_iff_back_edges have "\<not>acyclic (edges s)" by simp with acyclic_subset[OF _ edges_ss_reachable_edges] show "\<not>acyclic (E \<inter> reachable \<times> UNIV)" by blast next assume A: "\<not>break s" from A brk_eq_back have "back_edges s = {}" by simp with cycle_iff_back_edges have "acyclic (edges s)" by simp also from A nc_edges_covered[OF NC] have "edges s = E \<inter> reachable \<times> UNIV" by simp finally show "acyclic (E \<inter> reachable \<times> UNIV)" . qed text \<open>Again, we have a short two-line proof:\<close> lemma cycc_correct_aux_short_proof: assumes NC: "\<not>cond s" shows "break s \<longleftrightarrow> \<not>acyclic (E \<inter> reachable \<times> UNIV)" using nc_edges_covered[OF NC] brk_eq_back cycle_iff_back_edges by (auto dest: acyclic_subset[OF _ edges_ss_reachable_edges]) *) end (* definition \<open>circuit_finderT_spec T n \<equiv> do { ASSERT (node_in_graph w T n); SPEC (\<lambda>ns. is_hamiltonian_circuit)}\<close> text \<open>The same for the total correct variant:\<close> definition "cyc_checkerT_spec G \<equiv> do { ASSERT (graph G \<and> finite (graph_defs.reachable G)); SPEC (\<lambda>r. r \<longleftrightarrow> \<not>acyclic (g_E G \<inter> ((g_E G)\<^sup>* `` g_V0 G) \<times> UNIV))}" theorem cyc_checkerT_correct: "cyc_checkerT G \<le> cyc_checkerT_spec G" unfolding cyc_checkerT_def cyc_checkerT_spec_def proof (refine_vcg le_ASSERTI order_trans[OF DFS.it_dfsT_correct], clarsimp_all) assume "graph G" then interpret graph G . assume "finite (graph_defs.reachable G)" then interpret fb_graph G by (rule fb_graphI_fr) interpret cycc by unfold_locales show "DFS G cycc_params" by unfold_locales next fix s assume "cycc_invar G s" then interpret cycc_invar G s . assume "\<not>cycc.cond TYPE('b) G s" thus "break s = (\<not> acyclic (g_E G \<inter> cycc.reachable TYPE('b) G \<times> UNIV))" by (rule cycc_correct_aux) qed subsection \<open>Implementation\<close> text \<open> The implementation has two aspects: Structural implementation and data implementation. The framework provides recursive and tail-recursive implementations, as well as a variety of data structures for the state. We will choose the \<open>simple_state\<close> implementation, which provides a stack, an on-stack and a visited set, but no timing information. Note that it is common for state implementations to omit details from the very detailed abstract state. This means, that the algorithm's operations must not access these details (e.g. timing). However, the algorithm's correctness proofs may still use them. \<close> text \<open>We extend the state template to add a break flag\<close> record 'v cycc_state_impl = "'v simple_state" + break :: bool text \<open>Definition of refinement relation: The break-flag is refined by identity.\<close> definition "cycc_erel \<equiv> { (\<lparr> cycc_state_impl.break = b \<rparr>, \<lparr> cycc_state.break = b\<rparr>) | b. True }" abbreviation "cycc_rel \<equiv> \<langle>cycc_erel\<rangle>simple_state_rel" text \<open>Implementation of the parameters\<close> definition cycc_params_impl :: "('v,'v cycc_state_impl,unit cycc_state_impl_ext) gen_parameterization" where "cycc_params_impl \<equiv> dflt_parametrization simple_state.more (RETURN \<lparr> break = False \<rparr>) \<lparr> on_back_edge := \<lambda>u v s. RETURN \<lparr> break = True \<rparr>, is_break := break \<rparr>" lemmas cycc_params_impl_simp[simp,DFS_code_unfold] = gen_parameterization.simps[mk_record_simp, OF cycc_params_impl_def[simplified]] text \<open>Note: In this simple case, the reformulation of the extension state and parameterization is just redundant, However, in general the refinement will also affect the parameterization.\<close> lemma break_impl: "(si,s)\<in>cycc_rel \<Longrightarrow> cycc_state_impl.break si = cycc_state.break s" by (cases si, cases s, simp add: simple_state_rel_def cycc_erel_def) interpretation cycc_impl: simple_impl_defs G cycc_params_impl cycc_params for G . text \<open>The above interpretation creates an iterative and a recursive implementation \<close> term cycc_impl.tailrec_impl term cycc_impl.rec_impl term cycc_impl.tailrec_implT \<comment> \<open>Note, for total correctness we currently only support tail-recursive implementations.\<close> text \<open>We use both to derive a tail-recursive and a recursive cyclicity checker:\<close> definition [DFS_code_unfold]: "cyc_checker_impl G \<equiv> do { ASSERT (fb_graph G); s \<leftarrow> cycc_impl.tailrec_impl TYPE('a) G; RETURN (break s) }" definition [DFS_code_unfold]: "cyc_checker_rec_impl G \<equiv> do { ASSERT (fb_graph G); s \<leftarrow> cycc_impl.rec_impl TYPE('a) G; RETURN (break s) }" definition [DFS_code_unfold]: "cyc_checker_implT G \<equiv> do { ASSERT (graph G \<and> finite (graph_defs.reachable G)); s \<leftarrow> cycc_impl.tailrec_implT TYPE('a) G; RETURN (break s) }" text \<open>To show correctness of the implementation, we integrate the locale of the simple implementation into our cyclicity checker's locale:\<close> context cycc begin sublocale simple_impl G cycc_params cycc_params_impl cycc_erel apply unfold_locales apply (intro fun_relI, clarsimp simp: simple_state_rel_def, parametricity) [] apply (auto simp: cycc_erel_def break_impl simple_state_rel_def) done text \<open>We get that our implementation refines the abstrct DFS algorithm.\<close> lemmas impl_refine = simple_tailrec_refine simple_rec_refine simple_tailrecT_refine text \<open>Unfortunately, the combination of locales and abbreviations gets to its limits here, so we state the above lemma a bit more readable:\<close> lemma "cycc_impl.tailrec_impl TYPE('more) G \<le> \<Down> cycc_rel it_dfs" "cycc_impl.rec_impl TYPE('more) G \<le> \<Down> cycc_rel it_dfs" "cycc_impl.tailrec_implT TYPE('more) G \<le> \<Down> cycc_rel it_dfsT" using impl_refine . end text \<open>Finally, we get correctness of our cyclicity checker implementations\<close> lemma cyc_checker_impl_refine: "cyc_checker_impl G \<le> \<Down>Id (cyc_checker G)" unfolding cyc_checker_impl_def cyc_checker_def apply (refine_vcg cycc.impl_refine) apply (simp_all add: break_impl cyccI) done lemma cyc_checker_rec_impl_refine: "cyc_checker_rec_impl G \<le> \<Down>Id (cyc_checker G)" unfolding cyc_checker_rec_impl_def cyc_checker_def apply (refine_vcg cycc.impl_refine) apply (simp_all add: break_impl cyccI) done lemma cyc_checker_implT_refine: "cyc_checker_implT G \<le> \<Down>Id (cyc_checkerT G)" unfolding cyc_checker_implT_def cyc_checkerT_def apply (refine_vcg cycc.impl_refine) apply (simp_all add: break_impl cyccI') done subsection \<open>Synthesizing Executable Code\<close> text \<open> Our algorithm's implementation is still abstract, as it uses abstract data structures like sets and relations. In a last step, we use the Autoref tool to derive an implementation with efficient data structures. \<close> text \<open>Again, we derive our state implementation from the template provided by the framework. The break-flag is implemented by a Boolean flag. Note that, in general, the user-defined state extensions may be data-refined in this step.\<close> record ('si,'nsi,'psi)cycc_state_impl' = "('si,'nsi)simple_state_impl" + break_impl :: bool text \<open>We define the refinement relation for the state extension\<close> definition [to_relAPP]: "cycc_state_erel erel \<equiv> { (\<lparr>break_impl = bi, \<dots> = mi\<rparr>,\<lparr>break = b, \<dots> = m\<rparr>) | bi mi b m. (bi,b)\<in>bool_rel \<and> (mi,m)\<in>erel}" text \<open>And register it with the Autoref tool:\<close> consts i_cycc_state_ext :: "interface \<Rightarrow> interface" lemmas [autoref_rel_intf] = REL_INTFI[of cycc_state_erel i_cycc_state_ext] text \<open>We show that the record operations on our extended state are parametric, and declare these facts to Autoref: \<close> lemma [autoref_rules]: fixes ns_rel vis_rel erel defines "R \<equiv> \<langle>ns_rel,vis_rel,\<langle>erel\<rangle>cycc_state_erel\<rangle>ss_impl_rel" shows "(cycc_state_impl'_ext, cycc_state_impl_ext) \<in> bool_rel \<rightarrow> erel \<rightarrow> \<langle>erel\<rangle>cycc_state_erel" "(break_impl, cycc_state_impl.break) \<in> R \<rightarrow> bool_rel" unfolding cycc_state_erel_def ss_impl_rel_def R_def by auto (* for Digraph: *) type_synonym 'a slg = "'a \<Rightarrow> 'a list" definition slg_rel :: "('a\<times>'b) set \<Rightarrow> ('a slg \<times> 'b digraph) set" where slg_rel_def_internal: "slg_rel R \<equiv> (R \<rightarrow> \<langle>R\<rangle>list_set_rel) O br (\<lambda>succs. {(u,v). v\<in>succs u}) (\<lambda>_. True)" lemma slg_rel_def: "\<langle>R\<rangle>slg_rel = (R \<rightarrow> \<langle>R\<rangle>list_set_rel) O br (\<lambda>succs. {(u,v). v\<in>succs u}) (\<lambda>_. True)" unfolding slg_rel_def_internal relAPP_def by simp record ('vi,'ei,'v0i) gen_g_impl = gi_V :: 'vi gi_E :: 'ei gi_V0 :: 'v0i definition gen_f_impl_rel_ext_internal_def: "\<And> Rm Rv Re Rv0. gen_f_impl_rel_ext Rm Rv Re Rv0 \<equiv> { (gen_g_impl_ext Vi Ei V0i mi, graph_rec_ext V E V0 m) | Vi Ei V0i mi V E V0 m. (Vi,V)\<in>Rv \<and> (Ei,E)\<in>Re \<and> (V0i,V0)\<in>Rv0 \<and> (mi,m)\<in>Rm }" lemma gen_f_impl_rel_ext_def: "\<And>Rm Rv Re Rv0. \<langle>Rm,Rv,Re,Rv0\<rangle>gen_f_impl_rel_ext \<equiv> { (gen_g_impl_ext Vi Ei V0i mi, graph_rec_ext V E V0 m) | Vi Ei V0i mi V E V0 m. (Vi,V)\<in>Rv \<and> (Ei,E)\<in>Re \<and> (V0i,V0)\<in>Rv0 \<and> (mi,m)\<in>Rm }" unfolding gen_f_impl_rel_ext_internal_def relAPP_def by simp definition f_impl_rel_ext_internal_def: "f_impl_rel_ext Rm Rv \<equiv> \<langle>Rm,\<langle>Rv\<rangle>fun_set_rel,\<langle>Rv\<rangle>slg_rel,\<langle>Rv\<rangle>list_set_rel\<rangle>gen_g_impl_rel_ext" lemma g_impl_rel_ext_def: "\<langle>Rm,Rv\<rangle>g_impl_rel_ext \<equiv> \<langle>Rm,\<langle>Rv\<rangle>fun_set_rel,\<langle>Rv\<rangle>Digraph_Impl.slg_rel,\<langle>Rv\<rangle>list_set_rel\<rangle>gen_g_impl_rel_ext" unfolding g_impl_rel_ext_internal_def relAPP_def by simp (* end for Digraph *) text \<open>And, again, for the total correct version. Note that we generate a plain implementation, not inside a monad:\<close> schematic_goal cyc_checker_implT: defines "V \<equiv> Id :: ('v \<times> 'v::hashable) set" assumes [unfolded V_def,autoref_rules]: "(Gi, G) \<in> \<langle>Rm, V\<rangle>g_impl_rel_ext" notes [unfolded V_def,autoref_tyrel] = TYRELI[where R="\<langle>V\<rangle>dflt_ahs_rel"] TYRELI[where R="\<langle>V \<times>\<^sub>r \<langle>V\<rangle>list_set_rel\<rangle>ras_rel"] shows "RETURN (?c::?'c) \<le>\<Down>?R (cyc_checker_implT G)" unfolding DFS_code_unfold using [[autoref_trace_failed_id, goals_limit=1]] apply (autoref_monadic (trace,plain)) done concrete_definition cyc_checker_codeT uses cyc_checker_implT export_code cyc_checker_codeT checking SML theorem cyc_checker_codeT_correct: assumes 1: "graph G" "finite (graph_defs.reachable G)" assumes 2: "(Gi, G) \<in> \<langle>Rm, Id\<rangle>g_impl_rel_ext" shows "cyc_checker_codeT Gi \<longleftrightarrow> (\<not>acyclic (g_E G \<inter> ((g_E G)\<^sup>* `` g_V0 G) \<times> UNIV))" proof - note cyc_checker_codeT.refine[OF 2] also note cyc_checker_implT_refine also note cyc_checkerT_correct finally show ?thesis using 1 unfolding cyc_checkerT_spec_def by auto qed context node_in_graph begin thm cyc_checker_codeT_correct[OF dgraph.graph_axioms] end *) end
high
0.619891
99,874
/** * Copyright 2017 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace java org.apache.distributedlog.thrift.messaging struct TransformedRecord { 1: required binary payload 2: optional binary srcDlsn }
high
0.760213
99,875
import {ChatMessage} from '../../../../models/'; import {createChatMessageFromDiscriminatorValue} from '../../../../models/createChatMessageFromDiscriminatorValue'; import {AdditionalDataHolder, Parsable, ParseNode, SerializationWriter} from '@microsoft/kiota-abstractions'; /** Provides operations to call the delta method. */ export class DeltaResponse implements AdditionalDataHolder, Parsable { /** Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. */ private _additionalData: Record<string, unknown>; /** The value property */ private _value?: ChatMessage[] | undefined; /** * Gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. * @returns a Record<string, unknown> */ public get additionalData() { return this._additionalData; }; /** * Sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. * @param value Value to set for the AdditionalData property. */ public set additionalData(value: Record<string, unknown>) { this._additionalData = value; }; /** * Instantiates a new deltaResponse and sets the default values. */ public constructor() { this._additionalData = {}; }; /** * The deserialization information for the current model * @returns a Record<string, (node: ParseNode) => void> */ public getFieldDeserializers() : Record<string, (node: ParseNode) => void> { return { "value": n => { this.value = n.getCollectionOfObjectValues<ChatMessage>(createChatMessageFromDiscriminatorValue); }, }; }; /** * Serializes information the current object * @param writer Serialization writer to use to serialize this model */ public serialize(writer: SerializationWriter) : void { if(!writer) throw new Error("writer cannot be undefined"); writer.writeCollectionOfObjectValues<ChatMessage>("value", this.value); writer.writeAdditionalData(this.additionalData); }; /** * Gets the value property value. The value property * @returns a chatMessage */ public get value() { return this._value; }; /** * Sets the value property value. The value property * @param value Value to set for the value property. */ public set value(value: ChatMessage[] | undefined) { this._value = value; }; }
high
0.757107
99,876
// Copyright (c) 2016 Cornell University. // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import AcceptorTable::*; import BuildVector::*; import ClientServer::*; import Connectable::*; import ConnectalTypes::*; import DbgTypes::*; import DbgDefs::*; import DstMacTable::*; import DropTable::*; import Ethernet::*; import FIFO::*; import FIFOF::*; import GetPut::*; import MemTypes::*; import PaxosTypes::*; import Pipe::*; import RegFile::*; import Register::*; import RoleTable::*; import RoundTable::*; import SequenceTable::*; import Vector::*; `include "ConnectalProjectConfig.bsv" interface Ingress; interface MemWriteClient#(`DataBusWidth) writeClient; interface Client#(MetadataRequest, MetadataResponse) next; interface Get#(Role) role_reg_read_resp; method Action datapath_id_reg_write(Bit#(DatapathSize) datapath); method Action instance_reg_write(Bit#(InstanceSize) instance_); method Action role_reg_write(Role r); method Action role_reg_read(); method Action vround_reg_write(Bit#(TLog#(InstanceCount)) inst, Bit#(RoundSize) vround); method Action round_reg_write(Bit#(TLog#(InstanceCount)) inst, Bit#(RoundSize) round); method Action value_reg_write(Bit#(TLog#(InstanceCount)) inst, Vector#(8, Bit#(32)) value); method Action sequenceTable_add_entry(Bit#(16) msgtype, SequenceTblActionT action_); method Action acceptorTable_add_entry(Bit#(16) msgtype, AcceptorTblActionT action_); method Action dmacTable_add_entry(Bit#(48) mac, Bit#(9) port); // Debug method IngressDbgRec read_debug_info; method IngressPerfRec read_perf_info; endinterface module mkIngress#(Vector#(numClients, MetadataClient) mdc)(Ingress); let verbose = True; Reg#(LUInt) fwdCount <- mkReg(0); FIFOF#(MetadataRequest) currPacketFifo <- mkFIFOF; FIFOF#(MetadataRequest) inReqFifo <- mkFIFOF; FIFOF#(MetadataResponse) outRespFifo <- mkFIFOF; Vector#(numClients, MetadataServer) metadataServers = newVector; for (Integer i=0; i<valueOf(numClients); i=i+1) begin metadataServers[i] = (interface MetadataServer; interface Put request = toPut(inReqFifo); interface Get response = toGet(outRespFifo); endinterface); end mkConnection(mdc, metadataServers); // Request/Response Fifos FIFOF#(MetadataRequest) dmacReqFifo <- mkFIFOF; FIFOF#(MetadataRequest) roleReqFifo <- mkFIFOF; FIFOF#(MetadataRequest) roundReqFifo <- mkFIFOF; FIFOF#(MetadataRequest) sequenceReqFifo <- mkFIFOF; FIFOF#(MetadataRequest) acceptorReqFifo <- mkFIFOF; FIFOF#(MetadataResponse) dmacRespFifo <- mkFIFOF; FIFOF#(MetadataResponse) roleRespFifo <- mkFIFOF; FIFOF#(MetadataResponse) roundRespFifo <- mkFIFOF; FIFOF#(MetadataResponse) sequenceRespFifo <- mkFIFOF; FIFOF#(MetadataResponse) acceptorRespFifo <- mkFIFOF; FIFOF#(MetadataRequest) next_req_ff <- mkFIFOF; FIFOF#(MetadataResponse) next_rsp_ff <- mkFIFOF; Reg#(Bit#(32)) clk_cnt <- mkReg(0); Reg#(Bit#(32)) ingress_start_time <- mkReg(0); Reg#(Bit#(32)) ingress_end_time <- mkReg(0); Reg#(Bit#(32)) acceptor_start_time <- mkReg(0); Reg#(Bit#(32)) acceptor_end_time <- mkReg(0); Reg#(Bit#(32)) sequence_start_time <- mkReg(0); Reg#(Bit#(32)) sequence_end_time <- mkReg(0); rule clockrule; clk_cnt <= clk_cnt + 1; endrule // Tables DstMacTable dstMacTable <- mkDstMacTable(toGPClient(dmacReqFifo, dmacRespFifo)); RoleTable roleTable <- mkRoleTable(toGPClient(roleReqFifo, roleRespFifo)); RoundTable roundTable <- mkRoundTable(toGPClient(roundReqFifo, roundRespFifo)); SequenceTable sequenceTable <- mkSequenceTable(toGPClient(sequenceReqFifo, sequenceRespFifo)); AcceptorTable acceptorTable <- mkAcceptorTable(toGPClient(acceptorReqFifo, acceptorRespFifo)); //DropTable dropTable <- mkDropTable();//roundTable.next1); // BasicBlocks BasicBlockForward bb_fwd <- mkBasicBlockForward(); BasicBlockIncreaseInstance bb_increase_instance <- mkBasicBlockIncreaseInstance(); BasicBlockHandle1A bb_handle_1a <- mkBasicBlockHandle1A(); BasicBlockHandle2A bb_handle_2a <- mkBasicBlockHandle2A(); BasicBlockDrop bb_handle_drop <- mkBasicBlockDrop(); BasicBlockRound bb_read_round <- mkBasicBlockRound(); BasicBlockRole bb_read_role <- mkBasicBlockRole(); // Registers FIFO#(RoundRegRequest) roundRegReqFifo <- mkFIFO; FIFO#(RoleRegRequest) roleRegReqFifo <- mkFIFO; FIFO#(DatapathIdRegRequest) datapathIdRegReqFifo <- mkFIFO; FIFO#(InstanceRegRequest) instanceRegReqFifo <- mkFIFO; FIFO#(VRoundRegRequest) vroundRegReqFifo <- mkFIFO; FIFO#(ValueRegRequest) valueRegReqFifo <- mkFIFO; FIFO#(RoundRegResponse) roundRegRespFifo <- mkFIFO; FIFO#(RoleRegResponse) roleRegRespFifo <- mkFIFO; FIFO#(DatapathIdRegResponse) datapathIdRegRespFifo <- mkFIFO; FIFO#(InstanceRegResponse) instanceRegRespFifo <- mkFIFO; FIFO#(VRoundRegResponse) vroundRegRespFifo <- mkFIFO; FIFO#(ValueRegResponse) valueRegRespFifo <- mkFIFO; FIFO#(Role) roleRegReadFifo <- mkFIFO; rule readRole; let v <- toGet(roleRegRespFifo).get; roleRegReadFifo.enq(unpack(v.data)); endrule //Vector#(1, Client#(RoleRegRequest, RoleRegResponse)) role_clients = newVector(); //role_clients[0] = bb_read_role.regClient; //role_clients[1] = toGPClient(roleRegReqFifo, roleRegRespFifo); //RegisterIfc#(1, SizeOf#(Role)) roleReg <- mkP4Register(role_clients); // zipWithM_(mkConnection, role_clients, roleReg.servers); let roleReg <- mkP4Register(vec(bb_read_role.regClient, toGPClient(roleRegReqFifo, roleRegRespFifo))); let datapathIdReg <- mkP4Register(vec(bb_handle_2a.regClient_datapath_id, bb_handle_1a.regClient_datapath_id, toGPClient(datapathIdRegReqFifo, datapathIdRegRespFifo))); let instanceReg <- mkP4Register(vec(bb_increase_instance.regClient, toGPClient(instanceRegReqFifo, instanceRegRespFifo))); let roundReg <- mkP4Register(vec(bb_read_round.regClient, bb_handle_2a.regClient_round, bb_handle_1a.regClient_round, toGPClient(roundRegReqFifo, roundRegRespFifo))); let vroundReg <- mkP4Register(vec(bb_handle_1a.regClient_vround, bb_handle_2a.regClient_vround, toGPClient(vroundRegReqFifo, vroundRegRespFifo))); let valueReg <- mkP4Register(vec(bb_handle_1a.regClient_value, bb_handle_2a.regClient_value, toGPClient(valueRegReqFifo, valueRegRespFifo))); // Connect Table with BasicBlock mkConnection(dstMacTable.next_control_state_0, bb_fwd.prev_control_state); mkConnection(sequenceTable.next_control_state_0, bb_increase_instance.prev_control_state); mkConnection(acceptorTable.next_control_state_0, bb_handle_1a.prev_control_state); mkConnection(acceptorTable.next_control_state_1, bb_handle_2a.prev_control_state); mkConnection(acceptorTable.next_control_state_2, bb_handle_drop.prev_control_state); mkConnection(roundTable.next_control_state_0, bb_read_round.prev_control_state); mkConnection(roleTable.next_control_state_0, bb_read_role.prev_control_state); // Resolve rule conflicts (* descending_urgency ="sequence_tbl_next_control_state, acceptor_tbl_next_control_state" *) // Control Flow rule start_control_state if (inReqFifo.notEmpty); let _req = inReqFifo.first; let pkt = _req.pkt; let meta = _req.meta; inReqFifo.deq; ingress_start_time <= clk_cnt; // if (isValid(meta.valid_ipv4)) begin // MetadataRequest req = tagged DstMacLookupRequest {pkt: pkt, meta: meta}; // dmacReqFifo.enq(req); // end //endrule //rule dmac_tbl_next_control_state if (dmacRespFifo.first matches tagged DstMacResponse {pkt: .pkt, meta: .meta}); // dmacRespFifo.deq; if (isValid(meta.valid_paxos)) begin MetadataRequest req = MetadataRequest {pkt: pkt, meta: meta}; roleReqFifo.enq(req); end $display("(%0d) Ingress: dmac_tbl next control state", $time); endrule rule role_tbl_next_control_state if (roleRespFifo.notEmpty); let rsp = roleRespFifo.first; let meta = rsp.meta; let pkt = rsp.pkt; roleRespFifo.deq; if (meta.switch_metadata$role matches tagged Valid .role) begin case (role) matches ACCEPTOR: begin $display("(%0d) Role: Acceptor %h", $time, pkt.id); MetadataRequest req = MetadataRequest {pkt: pkt, meta: meta}; roundReqFifo.enq(req); acceptor_start_time <= clk_cnt; end COORDINATOR: begin $display("(%0d) Role: Coordinator %h", $time, pkt.id); MetadataRequest req = MetadataRequest {pkt: pkt, meta: meta}; sequenceReqFifo.enq(req); sequence_start_time <= clk_cnt; end FORWARDER: begin $display("(%0d) Role: Forwarder %h", $time, pkt.id); MetadataRequest req = MetadataRequest {pkt: pkt, meta: meta}; currPacketFifo.enq(req); end endcase end endrule rule sequence_tbl_next_control_state if (sequenceRespFifo.notEmpty); let rsp = sequenceRespFifo.first; let meta = rsp.meta; let pkt = rsp.pkt; sequenceRespFifo.deq; sequence_end_time <= clk_cnt; $display("(%0d) Sequence: fwd %h", $time, pkt.id); //FIXME: check action MetadataRequest req = MetadataRequest {pkt: pkt, meta: meta}; currPacketFifo.enq(req); endrule rule round_tbl_next_control_state if (roundRespFifo.notEmpty); let rsp = roundRespFifo.first; let meta = rsp.meta; let pkt = rsp.pkt; roundRespFifo.deq; $display("(%0d) round table response", $time); if (meta.paxos_packet_meta$round matches tagged Valid .round) begin if (round <= fromMaybe(?, meta.paxos$rnd)) begin $display("(%0d) Round: Acceptor %h, round=%h, rnd=%h", $time, pkt.id, round, fromMaybe(?, meta.paxos$rnd)); MetadataRequest req = MetadataRequest {pkt: pkt, meta: meta}; acceptorReqFifo.enq(req); end end endrule rule acceptor_tbl_next_control_state if (acceptorRespFifo.notEmpty); let rsp = acceptorRespFifo.first; acceptorRespFifo.deq; let meta = rsp.meta; let pkt = rsp.pkt; acceptor_end_time <= clk_cnt; $display("(%0d) Acceptor: fwd ", $time, fshow(meta)); MetadataRequest req = MetadataRequest {pkt: pkt, meta: meta}; next_req_ff.enq(req); endrule interface writeClient = dstMacTable.writeClient; interface next = (interface Client#(MetadataRequest, MetadataResponse); interface request = toGet(next_req_ff); interface response = toPut(next_rsp_ff); endinterface); method IngressDbgRec read_debug_info(); return IngressDbgRec { fwdCount: fwdCount, accTbl: acceptorTable.read_debug_info, seqTbl: sequenceTable.read_debug_info, dmacTbl: dstMacTable.read_debug_info }; endmethod method IngressPerfRec read_perf_info(); return IngressPerfRec { ingress_start_time: ingress_start_time, ingress_end_time: ingress_end_time, acceptor_start_time: acceptor_start_time, acceptor_end_time: acceptor_end_time, sequence_start_time: sequence_start_time, sequence_end_time: sequence_end_time }; endmethod method Action round_reg_write(Bit#(TLog#(InstanceCount)) inst, Bit#(RoundSize) round); RoundRegRequest req = RoundRegRequest {addr: inst, data: round, write: True}; roundRegReqFifo.enq(req); endmethod method Action vround_reg_write(Bit#(TLog#(InstanceCount)) inst, Bit#(RoundSize) round); VRoundRegRequest req = VRoundRegRequest {addr: inst, data: round, write: True}; vroundRegReqFifo.enq(req); endmethod method Action role_reg_write(Role role); RoleRegRequest req = RoleRegRequest {addr: 0, data: pack(role), write: True}; roleRegReqFifo.enq(req); endmethod method Action datapath_id_reg_write(Bit#(DatapathSize) datapath); DatapathIdRegRequest req = DatapathIdRegRequest {addr: 0, data: datapath, write: True}; datapathIdRegReqFifo.enq(req); endmethod method Action instance_reg_write(Bit#(InstanceSize) instance_); InstanceRegRequest req = InstanceRegRequest {addr: 0, data: instance_, write: True}; instanceRegReqFifo.enq(req); endmethod method Action value_reg_write(Bit#(TLog#(InstanceCount)) inst, Vector#(8, Bit#(32)) value); ValueRegRequest req = ValueRegRequest {addr: inst, data: pack(value), write: True}; valueRegReqFifo.enq(req); endmethod method Action role_reg_read(); RoleRegRequest req = RoleRegRequest {addr: 0, data: ?, write: False}; roleRegReqFifo.enq(req); endmethod interface role_reg_read_resp = toGet(roleRegReadFifo); method sequenceTable_add_entry = sequenceTable.add_entry; method acceptorTable_add_entry = acceptorTable.add_entry; method dmacTable_add_entry = dstMacTable.add_entry; endmodule
high
0.691978
99,877
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Styles --> <link href="{{ asset('css/admin.css') }}" rel="stylesheet"> <!-- Scripts --> <script> window.Laravel = <?php echo json_encode([ 'csrfToken' => csrf_token(), ]); ?> </script> </head> <body> <div id="app"> <header> @if (Auth::check()) <?php $menuConfig = [ 'name' => Auth::user()->name, 'menus' => [ ['name' => 'Banco', 'url' => route('admin.banks.index'), 'active' => isRouteActive('admin.banks.index')], ['name' => 'Contas a pagar', 'dropdownId' => 'teste'] ], 'menusDropdown' => [ [ 'id' => 'teste', 'items' => [ ['name' => 'Banco', 'url' => route('admin.banks.index'), 'active' => isRouteActive('admin.banks.index')], ['name' => 'Banco Edit', 'url' => route('admin.banks.index'), 'active' => isRouteActive('admin.banks.edit')], ] ] ], 'urlLogout' => '/admin/logout', 'csrfToken' => csrf_token() ]; ?> <admin-menu :config="{{ json_encode($menuConfig) }}"></admin-menu> @endif </header> <main>@yield('content')</main> <footer class="page-footer"> <div class="footer-copyfight"> <div class="container"> {{date('Y')}} <a class="grey-text text-lighten-4" href="http://localhost:3001/admin/home">Laravel Vue Admin</a> </div> </div> </footer> </div> <!-- Scripts --> <script src="{{ asset('build/admin.bundle.js') }}"></script> </body> </html>
low
0.699774
99,878
structure updateSyntax :> updateSyntax = struct open Abbrev HolKernel updateTheory val monop = HolKernel.syntax_fns "update" 1 HolKernel.dest_monop (Lib.curry boolSyntax.mk_icomb) val monop3 = HolKernel.syntax_fns "update" 3 HolKernel.dest_monop (Lib.curry boolSyntax.mk_icomb) val binop = HolKernel.syntax_fns "update" 2 HolKernel.dest_binop HolKernel.mk_binop val (find_tm, mk_find, dest_find, is_find) = binop "FIND" val (override_tm, mk_override, dest_override, is_override) = monop "OVERRIDE" val (list_update_tm, mk_list_update, dest_list_update, is_list_update) = monop3 "LIST_UPDATE" val strip_list_update = List.map pairSyntax.dest_pair o fst o listSyntax.dest_list o dest_list_update end
high
0.348739
99,879
# Copyright 2016 Facebook. All Rights Reserved. # #!/usr/local/bin/thrift -cpp -py -java # # Whenever you change this file please run the following command to refresh the java source code: # $ thrift --gen java -out src-gen/ src/com/facebook/buck/query/thrift/dag.thrift namespace java com.facebook.buck.query.thrift //Node of the graph struct DirectedAcyclicGraphNode { //Node name 1: string name; //Node attributes : key-value pairs 2: optional map<string, string> nodeAttributes; } // Graph's edge struct DirectedAcyclicGraphEdge { //From node 1: DirectedAcyclicGraphNode fromNode; //To node 2: DirectedAcyclicGraphNode toNode; } // Graph struct DirectedAcyclicGraph{ // list of nodes 1: list<DirectedAcyclicGraphNode> nodes; // list of edges 2: list<DirectedAcyclicGraphEdge> edges; }
high
0.809131
99,880
function like(id) { $.post('/site/likes?id='+id, {loadMore:true}).done(function(data){ $('#likeButton_'+id).toggleClass('liked'); var count = parseInt($('#count_'+id).html()); if ( $('#likeButton_'+id).hasClass("liked") ) { $('#count_'+id).html(count+1); } else { $('#count_'+id).html(count-1); } }).fail(function () { console.log('Server error'); }); }
high
0.230716
99,881
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 class lc_ctrl_scoreboard extends cip_base_scoreboard #( .CFG_T(lc_ctrl_env_cfg), .RAL_T(lc_ctrl_reg_block), .COV_T(lc_ctrl_env_cov) ); `uvm_component_utils(lc_ctrl_scoreboard) // local variables bit is_personalized = 0; // Data to program OTP protected otp_ctrl_pkg::lc_otp_program_req_t m_otp_prog_data; // First OTP program instruction count cleared by reset protected uint m_otp_prog_cnt; event check_lc_output_ev; // TLM agent fifos uvm_tlm_analysis_fifo #(push_pull_item #( .HostDataWidth (OTP_PROG_HDATA_WIDTH), .DeviceDataWidth(OTP_PROG_DDATA_WIDTH) )) otp_prog_fifo; uvm_tlm_analysis_fifo #(push_pull_item #( .HostDataWidth(lc_ctrl_state_pkg::LcTokenWidth) )) otp_token_fifo; uvm_tlm_analysis_fifo #(alert_esc_seq_item) esc_wipe_secrets_fifo; uvm_tlm_analysis_fifo #(alert_esc_seq_item) esc_scrap_state_fifo; uvm_tlm_analysis_fifo #(jtag_riscv_item) jtag_riscv_fifo; // local queues to hold incoming packets pending comparison `uvm_component_new function void build_phase(uvm_phase phase); super.build_phase(phase); otp_prog_fifo = new("otp_prog_fifo", this); otp_token_fifo = new("otp_token_fifo", this); esc_wipe_secrets_fifo = new("esc_wipe_secrets_fifo", this); esc_scrap_state_fifo = new("esc_scrap_state_fifo", this); jtag_riscv_fifo = new("jtag_riscv_fifo", this); endfunction function void connect_phase(uvm_phase phase); super.connect_phase(phase); endfunction task run_phase(uvm_phase phase); super.run_phase(phase); fork check_lc_output(); process_otp_prog_rsp(); process_otp_token_rsp(); process_jtag_riscv(); join_none endtask virtual task check_lc_output(); forever begin @(posedge cfg.pwr_lc_vif.pins[LcPwrDoneRsp] && cfg.en_scb) begin // TODO: add coverage dec_lc_state_e lc_state = dec_lc_state(cfg.lc_ctrl_vif.otp_i.state); lc_outputs_t exp_lc_o = EXP_LC_OUTPUTS[int'(lc_state)]; string err_msg = $sformatf("LC_St %0s", lc_state.name); cfg.clk_rst_vif.wait_n_clks(1); // lc_creator_seed_sw_rw_en_o is ON only when device has NOT been personalized or RMA state if (is_personalized && lc_state != DecLcStRma) begin exp_lc_o.lc_creator_seed_sw_rw_en_o = lc_ctrl_pkg::Off; end // lc_seed_hw_rd_en_o is ON only when device has been personalized or RMA state if (!is_personalized && lc_state != DecLcStRma) begin exp_lc_o.lc_seed_hw_rd_en_o = lc_ctrl_pkg::Off; end ->check_lc_output_ev; check_lc_outputs(exp_lc_o, err_msg); if (cfg.err_inj.state_err || cfg.err_inj.count_err || cfg.err_inj.state_backdoor_err || cfg.err_inj.count_backdoor_err ) begin // State/count error expected set_exp_alert(.alert_name("fatal_state_error"), .is_fatal(1), .max_delay(cfg.alert_max_delay)); end end end endtask virtual task process_otp_prog_rsp(); otp_ctrl_pkg::lc_otp_program_req_t otp_prog_data_exp; lc_state_e otp_prog_state_act, otp_prog_state_exp; lc_cnt_e otp_prog_count_act, otp_prog_count_exp; const string MsgFmt = "Check failed %s == %s %s [%h] vs %s [%h]"; forever begin push_pull_item #( .HostDataWidth (OTP_PROG_HDATA_WIDTH), .DeviceDataWidth(OTP_PROG_DDATA_WIDTH) ) item_rcv; otp_prog_fifo.get(item_rcv); if (item_rcv.d_data == 1 && cfg.en_scb) begin set_exp_alert(.alert_name("fatal_prog_error"), .is_fatal(1)); end // Decode and store to use for prediction m_otp_prog_data = otp_ctrl_pkg::lc_otp_program_req_t'(item_rcv.h_data); // Increment otp program count m_otp_prog_cnt++; // Get expected from model otp_prog_data_exp = predict_otp_prog_req(); otp_prog_state_act = lc_state_e'(m_otp_prog_data.state); otp_prog_state_exp = lc_state_e'(otp_prog_data_exp.state); otp_prog_count_exp = lc_cnt_e'(otp_prog_data_exp.count); otp_prog_count_act = lc_cnt_e'(m_otp_prog_data.count); `DV_CHECK_EQ(otp_prog_state_act, otp_prog_state_exp, $sformatf( " - %s vs %s", otp_prog_state_act.name, otp_prog_state_exp.name)) `DV_CHECK_EQ(otp_prog_count_act, otp_prog_count_exp, $sformatf( " - %s vs %s", otp_prog_count_act.name, otp_prog_count_exp.name)) end endtask // verilog_format: off - avoid bad formatting virtual task process_otp_token_rsp(); forever begin push_pull_item#(.HostDataWidth(lc_ctrl_state_pkg::LcTokenWidth)) item_rcv; otp_token_fifo.get(item_rcv); if (cfg.en_scb) begin `DV_CHECK_EQ(item_rcv.h_data, {`gmv(ral.transition_token[3]), `gmv(ral.transition_token[2]), `gmv(ral.transition_token[1]), `gmv(ral.transition_token[0])}) end end endtask // verilog_format: on virtual task process_jtag_riscv(); jtag_riscv_item jt_item; tl_seq_item tl_item; const uvm_reg_addr_t jtag_risc_address_mask = ~(2 ** (DMI_ADDRW + 2) - 1); const uvm_reg_addr_t base_address = cfg.jtag_riscv_map.get_base_addr(); const uvm_reg_addr_t base_address_masked = base_address & jtag_risc_address_mask; forever begin jtag_riscv_fifo.get(jt_item); `uvm_info(`gfn, {"process_jtag_risc: ", jt_item.sprint(uvm_default_line_printer)}, UVM_MEDIUM) if ((jt_item.op === DmiRead || jt_item.op === DmiWrite) && jt_item.status === DmiNoErr) begin `uvm_create_obj(tl_seq_item, tl_item) tl_item.a_addr = base_address_masked | (jt_item.addr << 2); tl_item.a_data = jt_item.data; tl_item.a_opcode = (jt_item.op === DmiRead) ? tlul_pkg::Get : tlul_pkg::PutFullData; tl_item.a_mask = '1; tl_item.d_data = jt_item.data; tl_item.d_opcode = (jt_item.op === DmiRead) ? tlul_pkg::Get : tlul_pkg::PutFullData; process_tl_access(tl_item, AddrChannel, "lc_ctrl_reg_block"); process_tl_access(tl_item, DataChannel, "lc_ctrl_reg_block"); end end endtask // check lc outputs, default all off virtual function void check_lc_outputs(lc_outputs_t exp_o = '{default: lc_ctrl_pkg::Off}, string msg = "expect all output OFF"); `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_dft_en_o, exp_o.lc_dft_en_o, msg) `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_nvm_debug_en_o, exp_o.lc_nvm_debug_en_o, msg) `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_hw_debug_en_o, exp_o.lc_hw_debug_en_o, msg) `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_cpu_en_o, exp_o.lc_cpu_en_o, msg) `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_keymgr_en_o, exp_o.lc_keymgr_en_o, msg) `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_escalate_en_o, exp_o.lc_escalate_en_o, msg) `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_owner_seed_sw_rw_en_o, exp_o.lc_owner_seed_sw_rw_en_o, msg) `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_iso_part_sw_rd_en_o, exp_o.lc_iso_part_sw_rd_en_o, msg) `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_iso_part_sw_wr_en_o, exp_o.lc_iso_part_sw_wr_en_o, msg) `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_seed_hw_rd_en_o, exp_o.lc_seed_hw_rd_en_o, msg) `DV_CHECK_EQ(cfg.lc_ctrl_vif.lc_creator_seed_sw_rw_en_o, exp_o.lc_creator_seed_sw_rw_en_o, msg) endfunction virtual task process_tl_access(tl_seq_item item, tl_channels_e channel, string ral_name); uvm_reg csr; bit do_read_check = 1'b0; bit write = item.is_write(); uvm_reg_addr_t csr_addr = cfg.ral_models[ral_name].get_word_aligned_addr(item.a_addr); lc_outputs_t exp = '{default: lc_ctrl_pkg::Off}; bit addr_phase_read = (!write && channel == AddrChannel); bit addr_phase_write = (write && channel == AddrChannel); bit data_phase_read = (!write && channel == DataChannel); bit data_phase_write = (write && channel == DataChannel); // if access was to a valid csr, get the csr handle if (csr_addr inside {cfg.ral_models[ral_name].csr_addrs}) begin csr = cfg.ral_models[ral_name].default_map.get_reg_by_offset(csr_addr); `DV_CHECK_NE_FATAL(csr, null) end else begin `uvm_fatal(`gfn, $sformatf("Access unexpected addr 0x%0h", csr_addr)) end // if incoming access is a write to a valid csr, then make updates right away if (addr_phase_write) begin `uvm_info(`gfn, { "process_tl_access: write predict ", csr.get_name(), " ", item.sprint(uvm_default_line_printer) }, UVM_MEDIUM) void'(csr.predict(.value(item.a_data), .kind(UVM_PREDICT_WRITE), .be(item.a_mask))); end if (addr_phase_read) begin case (csr.get_name()) "lc_state": begin // if (cfg.err_inj.state_err) begin // State error expected // case(cfg.test_phase) // LcCtrlReadState1: `DV_CHECK_FATAL( // ral.lc_state.predict(.value(DecLcStInvalid), .kind(UVM_PREDICT_READ))) // LcCtrlReadState2: `DV_CHECK_FATAL( // ral.lc_state.predict(.value(DecLcStEscalate), .kind(UVM_PREDICT_READ))) // endcase `DV_CHECK_FATAL(ral.lc_state.state.predict( .value(predict_lc_state()), .kind(UVM_PREDICT_READ))) end "lc_transition_cnt": begin // If we have a state error no transition will take place so // the tarnsition count will be 31 if(!cfg.err_inj.count_err && !cfg.err_inj.state_err && !cfg.err_inj.count_backdoor_err && !cfg.err_inj.state_backdoor_err ) begin `DV_CHECK_FATAL((ral.lc_transition_cnt.predict( .value(dec_lc_cnt(cfg.lc_ctrl_vif.otp_i.count)), .kind(UVM_PREDICT_READ) ))) end else begin // State or count error expected `DV_CHECK_FATAL(ral.lc_transition_cnt.predict(.value(31), .kind(UVM_PREDICT_READ))) end end default: begin // `uvm_fatal(`gfn, $sformatf("invalid csr: %0s", csr.get_full_name())) end endcase end // On reads, if do_read_check, is set, then check mirrored_value against item.d_data if (data_phase_read) begin if (csr.get_name() inside {"lc_state", "lc_transition_cnt"}) do_read_check = 1; if (do_read_check) begin `DV_CHECK_EQ(csr.get_mirrored_value(), item.d_data, $sformatf( "reg name: %0s", csr.get_full_name())) end void'(csr.predict(.value(item.d_data), .kind(UVM_PREDICT_READ))); `uvm_info(`gfn, { "process_tl_access: read predict ", csr.get_name(), " ", item.sprint(uvm_default_line_printer) }, UVM_MEDIUM) // when lc successfully req a transition, all outputs are turned off. if (cfg.err_inj.state_backdoor_err || cfg.err_inj.count_backdoor_err) begin // Expect escalate exp.lc_escalate_en_o = lc_ctrl_pkg::On; end if (ral.status.transition_successful.get()) check_lc_outputs(exp); end endtask // Predict the value of lc_state register virtual function bit [31:0] predict_lc_state(); // Unrepeated lc_state expected - default state from otp_i dec_lc_state_e lc_state_single_exp = dec_lc_state(cfg.lc_ctrl_vif.otp_i.state); bit [31:0] lc_state_exp; // Exceptions to default if (cfg.err_inj.state_err || cfg.err_inj.count_err || cfg.err_inj.count_backdoor_err || cfg.err_inj.state_backdoor_err) begin // State error expected case (cfg.test_phase) LcCtrlReadState1: lc_state_single_exp = DecLcStInvalid; LcCtrlReadState2: lc_state_single_exp = DecLcStEscalate; default: lc_state_single_exp = DecLcStInvalid; endcase end // repeat state to fill the word for hardness lc_state_exp = {DecLcStateNumRep{lc_state_single_exp}}; `uvm_info(`gfn, $sformatf( "predict_lc_state: lc_state_single_exp=%s(%x) lc_state_exp=%h", lc_state_single_exp.name, lc_state_single_exp, lc_state_exp ), UVM_MEDIUM) return lc_state_exp; endfunction virtual function otp_ctrl_pkg::lc_otp_program_req_t predict_otp_prog_req(); // Convert state and count back to enums const lc_state_e LcStateIn = cfg.lc_ctrl_vif.otp_i.state; const lc_cnt_e LcCntIn = cfg.lc_ctrl_vif.otp_i.count; // Incremented LcCntIn - next() works because of encoding method const lc_cnt_e LcCntInInc = LcCntIn.next(); // TODO needs expanding for JTAG registers const lc_state_e LcTargetState = encode_lc_state( cfg.ral.transition_target.get_mirrored_value() ); lc_state_e lc_state_exp; lc_cnt_e lc_cnt_exp; if (m_otp_prog_cnt == 1) begin // First program transaction just programs the incremented count so state // is the same as input lc_cnt_exp = LcCntInInc; lc_state_exp = LcStateIn; end else if (m_otp_prog_cnt == 2) begin // Second program transaction programs both the incremented count and // the transition target state in (TRANSITION_TARGET register) lc_cnt_exp = LcCntInInc; lc_state_exp = LcTargetState; end // Transition to SCRAP state always programs LcCnt24 if (LcTargetState == LcStScrap) lc_cnt_exp = LcCnt24; `uvm_info(`gfn, $sformatf( "predict_otp_prog_req: state=%s count=%s", lc_state_exp.name(), lc_cnt_exp.name), UVM_MEDIUM) return ('{state: lc_state_t'(lc_state_exp), count: lc_cnt_t'(lc_cnt_exp), req: 0}); endfunction // this function check if the triggered alert is expected // to turn off this check, user can set `do_alert_check` to 0 // We overload this to trigger events in the config object when an alert is triggered virtual function void process_alert(string alert_name, alert_esc_seq_item item); if (item.alert_handshake_sta == AlertReceived) begin case (alert_name) "fatal_prog_error": begin ->cfg.fatal_prog_error_ev; end "fatal_state_error": begin ->cfg.fatal_state_error_ev; end "fatal_bus_integ_error": begin ->cfg.fatal_bus_integ_error_ev; end default: begin `uvm_fatal(`gfn, {"Unexpected alert received: ", alert_name}) end endcase end super.process_alert(alert_name, item); endfunction virtual function void reset(string kind = "HARD"); super.reset(kind); // reset local fifos queues and variables // Clear OTP program count m_otp_prog_cnt = 0; endfunction function void check_phase(uvm_phase phase); super.check_phase(phase); // post test checks - ensure that all local fifos and queues are empty endfunction endclass
high
0.667395
99,882
-- (c) Copyright 1995-2020 Xilinx, Inc. All rights reserved. -- -- This file contains confidential and proprietary information -- of Xilinx, Inc. and is protected under U.S. and -- international copyright and other intellectual property -- laws. -- -- DISCLAIMER -- This disclaimer is not a license and does not grant any -- rights to the materials distributed herewith. Except as -- otherwise provided in a valid license issued to you by -- Xilinx, and to the maximum extent permitted by applicable -- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND -- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES -- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING -- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- -- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and -- (2) Xilinx shall not be liable (whether in contract or tort, -- including negligence, or under any other theory of -- liability) for any loss or damage of any kind or nature -- related to, arising under or in connection with these -- materials, including for any direct, or any indirect, -- special, incidental, or consequential loss or damage -- (including loss of data, profits, goodwill, or any type of -- loss or damage suffered as a result of any action brought -- by a third party) even if such damage or loss was -- reasonably foreseeable or Xilinx had been advised of the -- possibility of the same. -- -- CRITICAL APPLICATIONS -- Xilinx products are not designed or intended to be fail- -- safe, or for use in any application requiring fail-safe -- performance, such as life-support or safety devices or -- systems, Class III medical devices, nuclear facilities, -- applications related to the deployment of airbags, or any -- other applications that could lead to death, personal -- injury, or severe property or environmental damage -- (individually and collectively, "Critical -- Applications"). Customer assumes the sole risk and -- liability of any use of Xilinx products in Critical -- Applications, subject only to applicable laws and -- regulations governing limitations on product liability. -- -- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS -- PART OF THIS FILE AT ALL TIMES. -- -- DO NOT MODIFY THIS FILE. -- IP VLNV: xilinx.com:module_ref:OS_ISERDES:1.0 -- IP Revision: 1 LIBRARY ieee; USE ieee.std_logic_1164.ALL; USE ieee.numeric_std.ALL; ENTITY REAL_OS_OS_ISERDES_0_1 IS PORT ( CLK0 : IN STD_LOGIC; CLK1 : IN STD_LOGIC; DATA_IN : IN STD_LOGIC; DATA_OUT : OUT STD_LOGIC_VECTOR(7 DOWNTO 0); RESETN : IN STD_LOGIC ); END REAL_OS_OS_ISERDES_0_1; ARCHITECTURE REAL_OS_OS_ISERDES_0_1_arch OF REAL_OS_OS_ISERDES_0_1 IS ATTRIBUTE DowngradeIPIdentifiedWarnings : STRING; ATTRIBUTE DowngradeIPIdentifiedWarnings OF REAL_OS_OS_ISERDES_0_1_arch: ARCHITECTURE IS "yes"; COMPONENT OS_ISERDES IS GENERIC ( mode : STRING; o_width : INTEGER ); PORT ( CLK0 : IN STD_LOGIC; CLK1 : IN STD_LOGIC; DATA_IN : IN STD_LOGIC; DATA_OUT : OUT STD_LOGIC_VECTOR(7 DOWNTO 0); RESETN : IN STD_LOGIC ); END COMPONENT OS_ISERDES; ATTRIBUTE IP_DEFINITION_SOURCE : STRING; ATTRIBUTE IP_DEFINITION_SOURCE OF REAL_OS_OS_ISERDES_0_1_arch: ARCHITECTURE IS "module_ref"; ATTRIBUTE X_INTERFACE_INFO : STRING; ATTRIBUTE X_INTERFACE_PARAMETER : STRING; ATTRIBUTE X_INTERFACE_PARAMETER OF RESETN: SIGNAL IS "XIL_INTERFACENAME RESETN, POLARITY ACTIVE_LOW, INSERT_VIP 0"; ATTRIBUTE X_INTERFACE_INFO OF RESETN: SIGNAL IS "xilinx.com:signal:reset:1.0 RESETN RST"; BEGIN U0 : OS_ISERDES GENERIC MAP ( mode => "SDR", o_width => 4 ) PORT MAP ( CLK0 => CLK0, CLK1 => CLK1, DATA_IN => DATA_IN, DATA_OUT => DATA_OUT, RESETN => RESETN ); END REAL_OS_OS_ISERDES_0_1_arch;
high
0.642924
99,883
/* * This source file is part of ArkGameFrame * For the latest info, see https://github.com/ArkGame * * Copyright (c) 2013-2018 ArkGame authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #pragma once #include "SDK/Core/AFPlatform.hpp" #include "SDK/Core/AFNoncopyable.hpp" namespace ark { class AFLock : public AFNoncopyable { public: explicit AFLock() { flag.clear(); } ~AFLock() { } void lock() { while (flag.test_and_set(std::memory_order_acquire)); } void unlock() { flag.clear(std::memory_order_release); } private: mutable std::atomic_flag flag; }; template<typename T> class AFQueue : public AFLock { public: AFQueue() { } virtual ~AFQueue() { } bool Push(const T& object) { lock(); mList.push_back(object); unlock(); return true; } bool Pop(T& object) { lock(); if (mList.empty()) { unlock(); return false; } object = mList.front(); mList.pop_front(); unlock(); return true; } int Count() { return mList.size(); } private: std::list<T> mList; }; }
high
0.85174
99,884
1 1;JGT 1;JEQ 1;JGE 1;JLT 1;JNE 1;JLE 1;JMP -1 -1;JGT -1;JEQ -1;JGE -1;JLT -1;JNE -1;JLE -1;JMP D D;JGT D;JEQ D;JGE D;JLT D;JNE D;JLE D;JMP A A;JGT A;JEQ A;JGE A;JLT A;JNE A;JLE A;JMP !D !D;JGT !D;JEQ !D;JGE !D;JLT !D;JNE !D;JLE !D;JMP !A !A;JGT !A;JEQ !A;JGE !A;JLT !A;JNE !A;JLE !A;JMP -D -D;JGT -D;JEQ -D;JGE -D;JLT -D;JNE -D;JLE -D;JMP -A -A;JGT -A;JEQ -A;JGE -A;JLT -A;JNE -A;JLE -A;JMP D+1 D+1;JGT D+1;JEQ D+1;JGE D+1;JLT D+1;JNE D+1;JLE D+1;JMP A+1 A+1;JGT A+1;JEQ A+1;JGE A+1;JLT A+1;JNE A+1;JLE A+1;JMP D-1 D-1;JGT D-1;JEQ D-1;JGE D-1;JLT D-1;JNE D-1;JLE D-1;JMP A-1 A-1;JGT A-1;JEQ A-1;JGE A-1;JLT A-1;JNE A-1;JLE A-1;JMP D+A D+A;JGT D+A;JEQ D+A;JGE D+A;JLT D+A;JNE D+A;JLE D+A;JMP D-A D-A;JGT D-A;JEQ D-A;JGE D-A;JLT D-A;JNE D-A;JLE D-A;JMP A-D A-D;JGT A-D;JEQ A-D;JGE A-D;JLT A-D;JNE A-D;JLE A-D;JMP D&A D&A;JGT D&A;JEQ D&A;JGE D&A;JLT D&A;JNE D&A;JLE D&A;JMP D|A D|A;JGT D|A;JEQ D|A;JGE D|A;JLT D|A;JNE D|A;JLE D|A;JMP M M;JGT M;JEQ M;JGE M;JLT M;JNE M;JLE M;JMP !M !M;JGT !M;JEQ !M;JGE !M;JLT !M;JNE !M;JLE !M;JMP -M -M;JGT -M;JEQ -M;JGE -M;JLT -M;JNE -M;JLE -M;JMP M+1 M+1;JGT M+1;JEQ M+1;JGE M+1;JLT M+1;JNE M+1;JLE M+1;JMP M-1 M-1;JGT M-1;JEQ M-1;JGE M-1;JLT M-1;JNE M-1;JLE M-1;JMP D+M D+M;JGT D+M;JEQ D+M;JGE D+M;JLT D+M;JNE D+M;JLE D+M;JMP D-M D-M;JGT D-M;JEQ D-M;JGE D-M;JLT D-M;JNE D-M;JLE D-M;JMP M-D M-D;JGT M-D;JEQ M-D;JGE M-D;JLT M-D;JNE M-D;JLE M-D;JMP D&M D&M;JGT D&M;JEQ D&M;JGE D&M;JLT D&M;JNE D&M;JLE D&M;JMP D|M D|M;JGT D|M;JEQ D|M;JGE D|M;JLT D|M;JNE D|M;JLE D|M;JMP M=1 M=1;JGT M=1;JEQ M=1;JGE M=1;JLT M=1;JNE M=1;JLE M=1;JMP M=-1 M=-1;JGT M=-1;JEQ M=-1;JGE M=-1;JLT M=-1;JNE M=-1;JLE M=-1;JMP M=D M=D;JGT M=D;JEQ M=D;JGE M=D;JLT M=D;JNE M=D;JLE M=D;JMP M=A M=A;JGT M=A;JEQ M=A;JGE M=A;JLT M=A;JNE M=A;JLE M=A;JMP M=!D M=!D;JGT M=!D;JEQ M=!D;JGE M=!D;JLT M=!D;JNE M=!D;JLE M=!D;JMP M=!A M=!A;JGT M=!A;JEQ M=!A;JGE M=!A;JLT M=!A;JNE M=!A;JLE M=!A;JMP M=-D M=-D;JGT M=-D;JEQ M=-D;JGE M=-D;JLT M=-D;JNE M=-D;JLE M=-D;JMP M=-A M=-A;JGT M=-A;JEQ M=-A;JGE M=-A;JLT M=-A;JNE M=-A;JLE M=-A;JMP M=D+1 M=D+1;JGT M=D+1;JEQ M=D+1;JGE M=D+1;JLT M=D+1;JNE M=D+1;JLE M=D+1;JMP M=A+1 M=A+1;JGT M=A+1;JEQ M=A+1;JGE M=A+1;JLT M=A+1;JNE M=A+1;JLE M=A+1;JMP M=D-1 M=D-1;JGT M=D-1;JEQ M=D-1;JGE M=D-1;JLT M=D-1;JNE M=D-1;JLE M=D-1;JMP M=A-1 M=A-1;JGT M=A-1;JEQ M=A-1;JGE M=A-1;JLT M=A-1;JNE M=A-1;JLE M=A-1;JMP M=D+A M=D+A;JGT M=D+A;JEQ M=D+A;JGE M=D+A;JLT M=D+A;JNE M=D+A;JLE M=D+A;JMP M=D-A M=D-A;JGT M=D-A;JEQ M=D-A;JGE M=D-A;JLT M=D-A;JNE M=D-A;JLE M=D-A;JMP M=A-D M=A-D;JGT M=A-D;JEQ M=A-D;JGE M=A-D;JLT M=A-D;JNE M=A-D;JLE M=A-D;JMP M=D&A M=D&A;JGT M=D&A;JEQ M=D&A;JGE M=D&A;JLT M=D&A;JNE M=D&A;JLE M=D&A;JMP M=D|A M=D|A;JGT M=D|A;JEQ M=D|A;JGE M=D|A;JLT M=D|A;JNE M=D|A;JLE M=D|A;JMP M=M M=M;JGT M=M;JEQ M=M;JGE M=M;JLT M=M;JNE M=M;JLE M=M;JMP M=!M M=!M;JGT M=!M;JEQ M=!M;JGE M=!M;JLT M=!M;JNE M=!M;JLE M=!M;JMP M=-M M=-M;JGT M=-M;JEQ M=-M;JGE M=-M;JLT M=-M;JNE M=-M;JLE M=-M;JMP M=M+1 M=M+1;JGT M=M+1;JEQ M=M+1;JGE M=M+1;JLT M=M+1;JNE M=M+1;JLE M=M+1;JMP M=M-1 M=M-1;JGT M=M-1;JEQ M=M-1;JGE M=M-1;JLT M=M-1;JNE M=M-1;JLE M=M-1;JMP M=D+M M=D+M;JGT M=D+M;JEQ M=D+M;JGE M=D+M;JLT M=D+M;JNE M=D+M;JLE M=D+M;JMP M=D-M M=D-M;JGT M=D-M;JEQ M=D-M;JGE M=D-M;JLT M=D-M;JNE M=D-M;JLE M=D-M;JMP M=M-D M=M-D;JGT M=M-D;JEQ M=M-D;JGE M=M-D;JLT M=M-D;JNE M=M-D;JLE M=M-D;JMP M=D&M M=D&M;JGT M=D&M;JEQ M=D&M;JGE M=D&M;JLT M=D&M;JNE M=D&M;JLE M=D&M;JMP M=D|M M=D|M;JGT M=D|M;JEQ M=D|M;JGE M=D|M;JLT M=D|M;JNE M=D|M;JLE M=D|M;JMP D=1 D=1;JGT D=1;JEQ D=1;JGE D=1;JLT D=1;JNE D=1;JLE D=1;JMP D=-1 D=-1;JGT D=-1;JEQ D=-1;JGE D=-1;JLT D=-1;JNE D=-1;JLE D=-1;JMP D=D D=D;JGT D=D;JEQ D=D;JGE D=D;JLT D=D;JNE D=D;JLE D=D;JMP D=A D=A;JGT D=A;JEQ D=A;JGE D=A;JLT D=A;JNE D=A;JLE D=A;JMP D=!D D=!D;JGT D=!D;JEQ D=!D;JGE D=!D;JLT D=!D;JNE D=!D;JLE D=!D;JMP D=!A D=!A;JGT D=!A;JEQ D=!A;JGE D=!A;JLT D=!A;JNE D=!A;JLE D=!A;JMP D=-D D=-D;JGT D=-D;JEQ D=-D;JGE D=-D;JLT D=-D;JNE D=-D;JLE D=-D;JMP D=-A D=-A;JGT D=-A;JEQ D=-A;JGE D=-A;JLT D=-A;JNE D=-A;JLE D=-A;JMP D=D+1 D=D+1;JGT D=D+1;JEQ D=D+1;JGE D=D+1;JLT D=D+1;JNE D=D+1;JLE D=D+1;JMP D=A+1 D=A+1;JGT D=A+1;JEQ D=A+1;JGE D=A+1;JLT D=A+1;JNE D=A+1;JLE D=A+1;JMP D=D-1 D=D-1;JGT D=D-1;JEQ D=D-1;JGE D=D-1;JLT D=D-1;JNE D=D-1;JLE D=D-1;JMP D=A-1 D=A-1;JGT D=A-1;JEQ D=A-1;JGE D=A-1;JLT D=A-1;JNE D=A-1;JLE D=A-1;JMP D=D+A D=D+A;JGT D=D+A;JEQ D=D+A;JGE D=D+A;JLT D=D+A;JNE D=D+A;JLE D=D+A;JMP D=D-A D=D-A;JGT D=D-A;JEQ D=D-A;JGE D=D-A;JLT D=D-A;JNE D=D-A;JLE D=D-A;JMP D=A-D D=A-D;JGT D=A-D;JEQ D=A-D;JGE D=A-D;JLT D=A-D;JNE D=A-D;JLE D=A-D;JMP D=D&A D=D&A;JGT D=D&A;JEQ D=D&A;JGE D=D&A;JLT D=D&A;JNE D=D&A;JLE D=D&A;JMP D=D|A D=D|A;JGT D=D|A;JEQ D=D|A;JGE D=D|A;JLT D=D|A;JNE D=D|A;JLE D=D|A;JMP D=M D=M;JGT D=M;JEQ D=M;JGE D=M;JLT D=M;JNE D=M;JLE D=M;JMP D=!M D=!M;JGT D=!M;JEQ D=!M;JGE D=!M;JLT D=!M;JNE D=!M;JLE D=!M;JMP D=-M D=-M;JGT D=-M;JEQ D=-M;JGE D=-M;JLT D=-M;JNE D=-M;JLE D=-M;JMP D=M+1 D=M+1;JGT D=M+1;JEQ D=M+1;JGE D=M+1;JLT D=M+1;JNE D=M+1;JLE D=M+1;JMP D=M-1 D=M-1;JGT D=M-1;JEQ D=M-1;JGE D=M-1;JLT D=M-1;JNE D=M-1;JLE D=M-1;JMP D=D+M D=D+M;JGT D=D+M;JEQ D=D+M;JGE D=D+M;JLT D=D+M;JNE D=D+M;JLE D=D+M;JMP D=D-M D=D-M;JGT D=D-M;JEQ D=D-M;JGE D=D-M;JLT D=D-M;JNE D=D-M;JLE D=D-M;JMP D=M-D D=M-D;JGT D=M-D;JEQ D=M-D;JGE D=M-D;JLT D=M-D;JNE D=M-D;JLE D=M-D;JMP D=D&M D=D&M;JGT D=D&M;JEQ D=D&M;JGE D=D&M;JLT D=D&M;JNE D=D&M;JLE D=D&M;JMP D=D|M D=D|M;JGT D=D|M;JEQ D=D|M;JGE D=D|M;JLT D=D|M;JNE D=D|M;JLE D=D|M;JMP MD=1 MD=1;JGT MD=1;JEQ MD=1;JGE MD=1;JLT MD=1;JNE MD=1;JLE MD=1;JMP MD=-1 MD=-1;JGT MD=-1;JEQ MD=-1;JGE MD=-1;JLT MD=-1;JNE MD=-1;JLE MD=-1;JMP MD=D MD=D;JGT MD=D;JEQ MD=D;JGE MD=D;JLT MD=D;JNE MD=D;JLE MD=D;JMP MD=A MD=A;JGT MD=A;JEQ MD=A;JGE MD=A;JLT MD=A;JNE MD=A;JLE MD=A;JMP MD=!D MD=!D;JGT MD=!D;JEQ MD=!D;JGE MD=!D;JLT MD=!D;JNE MD=!D;JLE MD=!D;JMP MD=!A MD=!A;JGT MD=!A;JEQ MD=!A;JGE MD=!A;JLT MD=!A;JNE MD=!A;JLE MD=!A;JMP MD=-D MD=-D;JGT MD=-D;JEQ MD=-D;JGE MD=-D;JLT MD=-D;JNE MD=-D;JLE MD=-D;JMP MD=-A MD=-A;JGT MD=-A;JEQ MD=-A;JGE MD=-A;JLT MD=-A;JNE MD=-A;JLE MD=-A;JMP MD=D+1 MD=D+1;JGT MD=D+1;JEQ MD=D+1;JGE MD=D+1;JLT MD=D+1;JNE MD=D+1;JLE MD=D+1;JMP MD=A+1 MD=A+1;JGT MD=A+1;JEQ MD=A+1;JGE MD=A+1;JLT MD=A+1;JNE MD=A+1;JLE MD=A+1;JMP MD=D-1 MD=D-1;JGT MD=D-1;JEQ MD=D-1;JGE MD=D-1;JLT MD=D-1;JNE MD=D-1;JLE MD=D-1;JMP MD=A-1 MD=A-1;JGT MD=A-1;JEQ MD=A-1;JGE MD=A-1;JLT MD=A-1;JNE MD=A-1;JLE MD=A-1;JMP MD=D+A MD=D+A;JGT MD=D+A;JEQ MD=D+A;JGE MD=D+A;JLT MD=D+A;JNE MD=D+A;JLE MD=D+A;JMP MD=D-A MD=D-A;JGT MD=D-A;JEQ MD=D-A;JGE MD=D-A;JLT MD=D-A;JNE MD=D-A;JLE MD=D-A;JMP MD=A-D MD=A-D;JGT MD=A-D;JEQ MD=A-D;JGE MD=A-D;JLT MD=A-D;JNE MD=A-D;JLE MD=A-D;JMP MD=D&A MD=D&A;JGT MD=D&A;JEQ MD=D&A;JGE MD=D&A;JLT MD=D&A;JNE MD=D&A;JLE MD=D&A;JMP MD=D|A MD=D|A;JGT MD=D|A;JEQ MD=D|A;JGE MD=D|A;JLT MD=D|A;JNE MD=D|A;JLE MD=D|A;JMP MD=M MD=M;JGT MD=M;JEQ MD=M;JGE MD=M;JLT MD=M;JNE MD=M;JLE MD=M;JMP MD=!M MD=!M;JGT MD=!M;JEQ MD=!M;JGE MD=!M;JLT MD=!M;JNE MD=!M;JLE MD=!M;JMP MD=-M MD=-M;JGT MD=-M;JEQ MD=-M;JGE MD=-M;JLT MD=-M;JNE MD=-M;JLE MD=-M;JMP MD=M+1 MD=M+1;JGT MD=M+1;JEQ MD=M+1;JGE MD=M+1;JLT MD=M+1;JNE MD=M+1;JLE MD=M+1;JMP MD=M-1 MD=M-1;JGT MD=M-1;JEQ MD=M-1;JGE MD=M-1;JLT MD=M-1;JNE MD=M-1;JLE MD=M-1;JMP MD=D+M MD=D+M;JGT MD=D+M;JEQ MD=D+M;JGE MD=D+M;JLT MD=D+M;JNE MD=D+M;JLE MD=D+M;JMP MD=D-M MD=D-M;JGT MD=D-M;JEQ MD=D-M;JGE MD=D-M;JLT MD=D-M;JNE MD=D-M;JLE MD=D-M;JMP MD=M-D MD=M-D;JGT MD=M-D;JEQ MD=M-D;JGE MD=M-D;JLT MD=M-D;JNE MD=M-D;JLE MD=M-D;JMP MD=D&M MD=D&M;JGT MD=D&M;JEQ MD=D&M;JGE MD=D&M;JLT MD=D&M;JNE MD=D&M;JLE MD=D&M;JMP MD=D|M MD=D|M;JGT MD=D|M;JEQ MD=D|M;JGE MD=D|M;JLT MD=D|M;JNE MD=D|M;JLE MD=D|M;JMP A=1 A=1;JGT A=1;JEQ A=1;JGE A=1;JLT A=1;JNE A=1;JLE A=1;JMP A=-1 A=-1;JGT A=-1;JEQ A=-1;JGE A=-1;JLT A=-1;JNE A=-1;JLE A=-1;JMP A=D A=D;JGT A=D;JEQ A=D;JGE A=D;JLT A=D;JNE A=D;JLE A=D;JMP A=A A=A;JGT A=A;JEQ A=A;JGE A=A;JLT A=A;JNE A=A;JLE A=A;JMP A=!D A=!D;JGT A=!D;JEQ A=!D;JGE A=!D;JLT A=!D;JNE A=!D;JLE A=!D;JMP A=!A A=!A;JGT A=!A;JEQ A=!A;JGE A=!A;JLT A=!A;JNE A=!A;JLE A=!A;JMP A=-D A=-D;JGT A=-D;JEQ A=-D;JGE A=-D;JLT A=-D;JNE A=-D;JLE A=-D;JMP A=-A A=-A;JGT A=-A;JEQ A=-A;JGE A=-A;JLT A=-A;JNE A=-A;JLE A=-A;JMP A=D+1 A=D+1;JGT A=D+1;JEQ A=D+1;JGE A=D+1;JLT A=D+1;JNE A=D+1;JLE A=D+1;JMP A=A+1 A=A+1;JGT A=A+1;JEQ A=A+1;JGE A=A+1;JLT A=A+1;JNE A=A+1;JLE A=A+1;JMP A=D-1 A=D-1;JGT A=D-1;JEQ A=D-1;JGE A=D-1;JLT A=D-1;JNE A=D-1;JLE A=D-1;JMP A=A-1 A=A-1;JGT A=A-1;JEQ A=A-1;JGE A=A-1;JLT A=A-1;JNE A=A-1;JLE A=A-1;JMP A=D+A A=D+A;JGT A=D+A;JEQ A=D+A;JGE A=D+A;JLT A=D+A;JNE A=D+A;JLE A=D+A;JMP A=D-A A=D-A;JGT A=D-A;JEQ A=D-A;JGE A=D-A;JLT A=D-A;JNE A=D-A;JLE A=D-A;JMP A=A-D A=A-D;JGT A=A-D;JEQ A=A-D;JGE A=A-D;JLT A=A-D;JNE A=A-D;JLE A=A-D;JMP A=D&A A=D&A;JGT A=D&A;JEQ A=D&A;JGE A=D&A;JLT A=D&A;JNE A=D&A;JLE A=D&A;JMP A=D|A A=D|A;JGT A=D|A;JEQ A=D|A;JGE A=D|A;JLT A=D|A;JNE A=D|A;JLE A=D|A;JMP A=M A=M;JGT A=M;JEQ A=M;JGE A=M;JLT A=M;JNE A=M;JLE A=M;JMP A=!M A=!M;JGT A=!M;JEQ A=!M;JGE A=!M;JLT A=!M;JNE A=!M;JLE A=!M;JMP A=-M A=-M;JGT A=-M;JEQ A=-M;JGE A=-M;JLT A=-M;JNE A=-M;JLE A=-M;JMP A=M+1 A=M+1;JGT A=M+1;JEQ A=M+1;JGE A=M+1;JLT A=M+1;JNE A=M+1;JLE A=M+1;JMP A=M-1 A=M-1;JGT A=M-1;JEQ A=M-1;JGE A=M-1;JLT A=M-1;JNE A=M-1;JLE A=M-1;JMP A=D+M A=D+M;JGT A=D+M;JEQ A=D+M;JGE A=D+M;JLT A=D+M;JNE A=D+M;JLE A=D+M;JMP A=D-M A=D-M;JGT A=D-M;JEQ A=D-M;JGE A=D-M;JLT A=D-M;JNE A=D-M;JLE A=D-M;JMP A=M-D A=M-D;JGT A=M-D;JEQ A=M-D;JGE A=M-D;JLT A=M-D;JNE A=M-D;JLE A=M-D;JMP A=D&M A=D&M;JGT A=D&M;JEQ A=D&M;JGE A=D&M;JLT A=D&M;JNE A=D&M;JLE A=D&M;JMP A=D|M A=D|M;JGT A=D|M;JEQ A=D|M;JGE A=D|M;JLT A=D|M;JNE A=D|M;JLE A=D|M;JMP AM=1 AM=1;JGT AM=1;JEQ AM=1;JGE AM=1;JLT AM=1;JNE AM=1;JLE AM=1;JMP AM=-1 AM=-1;JGT AM=-1;JEQ AM=-1;JGE AM=-1;JLT AM=-1;JNE AM=-1;JLE AM=-1;JMP AM=D AM=D;JGT AM=D;JEQ AM=D;JGE AM=D;JLT AM=D;JNE AM=D;JLE AM=D;JMP AM=A AM=A;JGT AM=A;JEQ AM=A;JGE AM=A;JLT AM=A;JNE AM=A;JLE AM=A;JMP AM=!D AM=!D;JGT AM=!D;JEQ AM=!D;JGE AM=!D;JLT AM=!D;JNE AM=!D;JLE AM=!D;JMP AM=!A AM=!A;JGT AM=!A;JEQ AM=!A;JGE AM=!A;JLT AM=!A;JNE AM=!A;JLE AM=!A;JMP AM=-D AM=-D;JGT AM=-D;JEQ AM=-D;JGE AM=-D;JLT AM=-D;JNE AM=-D;JLE AM=-D;JMP AM=-A AM=-A;JGT AM=-A;JEQ AM=-A;JGE AM=-A;JLT AM=-A;JNE AM=-A;JLE AM=-A;JMP AM=D+1 AM=D+1;JGT AM=D+1;JEQ AM=D+1;JGE AM=D+1;JLT AM=D+1;JNE AM=D+1;JLE AM=D+1;JMP AM=A+1 AM=A+1;JGT AM=A+1;JEQ AM=A+1;JGE AM=A+1;JLT AM=A+1;JNE AM=A+1;JLE AM=A+1;JMP AM=D-1 AM=D-1;JGT AM=D-1;JEQ AM=D-1;JGE AM=D-1;JLT AM=D-1;JNE AM=D-1;JLE AM=D-1;JMP AM=A-1 AM=A-1;JGT AM=A-1;JEQ AM=A-1;JGE AM=A-1;JLT AM=A-1;JNE AM=A-1;JLE AM=A-1;JMP AM=D+A AM=D+A;JGT AM=D+A;JEQ AM=D+A;JGE AM=D+A;JLT AM=D+A;JNE AM=D+A;JLE AM=D+A;JMP AM=D-A AM=D-A;JGT AM=D-A;JEQ AM=D-A;JGE AM=D-A;JLT AM=D-A;JNE AM=D-A;JLE AM=D-A;JMP AM=A-D AM=A-D;JGT AM=A-D;JEQ AM=A-D;JGE AM=A-D;JLT AM=A-D;JNE AM=A-D;JLE AM=A-D;JMP AM=D&A AM=D&A;JGT AM=D&A;JEQ AM=D&A;JGE AM=D&A;JLT AM=D&A;JNE AM=D&A;JLE AM=D&A;JMP AM=D|A AM=D|A;JGT AM=D|A;JEQ AM=D|A;JGE AM=D|A;JLT AM=D|A;JNE AM=D|A;JLE AM=D|A;JMP AM=M AM=M;JGT AM=M;JEQ AM=M;JGE AM=M;JLT AM=M;JNE AM=M;JLE AM=M;JMP AM=!M AM=!M;JGT AM=!M;JEQ AM=!M;JGE AM=!M;JLT AM=!M;JNE AM=!M;JLE AM=!M;JMP AM=-M AM=-M;JGT AM=-M;JEQ AM=-M;JGE AM=-M;JLT AM=-M;JNE AM=-M;JLE AM=-M;JMP AM=M+1 AM=M+1;JGT AM=M+1;JEQ AM=M+1;JGE AM=M+1;JLT AM=M+1;JNE AM=M+1;JLE AM=M+1;JMP AM=M-1 AM=M-1;JGT AM=M-1;JEQ AM=M-1;JGE AM=M-1;JLT AM=M-1;JNE AM=M-1;JLE AM=M-1;JMP AM=D+M AM=D+M;JGT AM=D+M;JEQ AM=D+M;JGE AM=D+M;JLT AM=D+M;JNE AM=D+M;JLE AM=D+M;JMP AM=D-M AM=D-M;JGT AM=D-M;JEQ AM=D-M;JGE AM=D-M;JLT AM=D-M;JNE AM=D-M;JLE AM=D-M;JMP AM=M-D AM=M-D;JGT AM=M-D;JEQ AM=M-D;JGE AM=M-D;JLT AM=M-D;JNE AM=M-D;JLE AM=M-D;JMP AM=D&M AM=D&M;JGT AM=D&M;JEQ AM=D&M;JGE AM=D&M;JLT AM=D&M;JNE AM=D&M;JLE AM=D&M;JMP AM=D|M AM=D|M;JGT AM=D|M;JEQ AM=D|M;JGE AM=D|M;JLT AM=D|M;JNE AM=D|M;JLE AM=D|M;JMP AD=1 AD=1;JGT AD=1;JEQ AD=1;JGE AD=1;JLT AD=1;JNE AD=1;JLE AD=1;JMP AD=-1 AD=-1;JGT AD=-1;JEQ AD=-1;JGE AD=-1;JLT AD=-1;JNE AD=-1;JLE AD=-1;JMP AD=D AD=D;JGT AD=D;JEQ AD=D;JGE AD=D;JLT AD=D;JNE AD=D;JLE AD=D;JMP AD=A AD=A;JGT AD=A;JEQ AD=A;JGE AD=A;JLT AD=A;JNE AD=A;JLE AD=A;JMP AD=!D AD=!D;JGT AD=!D;JEQ AD=!D;JGE AD=!D;JLT AD=!D;JNE AD=!D;JLE AD=!D;JMP AD=!A AD=!A;JGT AD=!A;JEQ AD=!A;JGE AD=!A;JLT AD=!A;JNE AD=!A;JLE AD=!A;JMP AD=-D AD=-D;JGT AD=-D;JEQ AD=-D;JGE AD=-D;JLT AD=-D;JNE AD=-D;JLE AD=-D;JMP AD=-A AD=-A;JGT AD=-A;JEQ AD=-A;JGE AD=-A;JLT AD=-A;JNE AD=-A;JLE AD=-A;JMP AD=D+1 AD=D+1;JGT AD=D+1;JEQ AD=D+1;JGE AD=D+1;JLT AD=D+1;JNE AD=D+1;JLE AD=D+1;JMP AD=A+1 AD=A+1;JGT AD=A+1;JEQ AD=A+1;JGE AD=A+1;JLT AD=A+1;JNE AD=A+1;JLE AD=A+1;JMP AD=D-1 AD=D-1;JGT AD=D-1;JEQ AD=D-1;JGE AD=D-1;JLT AD=D-1;JNE AD=D-1;JLE AD=D-1;JMP AD=A-1 AD=A-1;JGT AD=A-1;JEQ AD=A-1;JGE AD=A-1;JLT AD=A-1;JNE AD=A-1;JLE AD=A-1;JMP AD=D+A AD=D+A;JGT AD=D+A;JEQ AD=D+A;JGE AD=D+A;JLT AD=D+A;JNE AD=D+A;JLE AD=D+A;JMP AD=D-A AD=D-A;JGT AD=D-A;JEQ AD=D-A;JGE AD=D-A;JLT AD=D-A;JNE AD=D-A;JLE AD=D-A;JMP AD=A-D AD=A-D;JGT AD=A-D;JEQ AD=A-D;JGE AD=A-D;JLT AD=A-D;JNE AD=A-D;JLE AD=A-D;JMP AD=D&A AD=D&A;JGT AD=D&A;JEQ AD=D&A;JGE AD=D&A;JLT AD=D&A;JNE AD=D&A;JLE AD=D&A;JMP AD=D|A AD=D|A;JGT AD=D|A;JEQ AD=D|A;JGE AD=D|A;JLT AD=D|A;JNE AD=D|A;JLE AD=D|A;JMP AD=M AD=M;JGT AD=M;JEQ AD=M;JGE AD=M;JLT AD=M;JNE AD=M;JLE AD=M;JMP AD=!M AD=!M;JGT AD=!M;JEQ AD=!M;JGE AD=!M;JLT AD=!M;JNE AD=!M;JLE AD=!M;JMP AD=-M AD=-M;JGT AD=-M;JEQ AD=-M;JGE AD=-M;JLT AD=-M;JNE AD=-M;JLE AD=-M;JMP AD=M+1 AD=M+1;JGT AD=M+1;JEQ AD=M+1;JGE AD=M+1;JLT AD=M+1;JNE AD=M+1;JLE AD=M+1;JMP AD=M-1 AD=M-1;JGT AD=M-1;JEQ AD=M-1;JGE AD=M-1;JLT AD=M-1;JNE AD=M-1;JLE AD=M-1;JMP AD=D+M AD=D+M;JGT AD=D+M;JEQ AD=D+M;JGE AD=D+M;JLT AD=D+M;JNE AD=D+M;JLE AD=D+M;JMP AD=D-M AD=D-M;JGT AD=D-M;JEQ AD=D-M;JGE AD=D-M;JLT AD=D-M;JNE AD=D-M;JLE AD=D-M;JMP AD=M-D AD=M-D;JGT AD=M-D;JEQ AD=M-D;JGE AD=M-D;JLT AD=M-D;JNE AD=M-D;JLE AD=M-D;JMP AD=D&M AD=D&M;JGT AD=D&M;JEQ AD=D&M;JGE AD=D&M;JLT AD=D&M;JNE AD=D&M;JLE AD=D&M;JMP AD=D|M AD=D|M;JGT AD=D|M;JEQ AD=D|M;JGE AD=D|M;JLT AD=D|M;JNE AD=D|M;JLE AD=D|M;JMP AMD=1 AMD=1;JGT AMD=1;JEQ AMD=1;JGE AMD=1;JLT AMD=1;JNE AMD=1;JLE AMD=1;JMP AMD=-1 AMD=-1;JGT AMD=-1;JEQ AMD=-1;JGE AMD=-1;JLT AMD=-1;JNE AMD=-1;JLE AMD=-1;JMP AMD=D AMD=D;JGT AMD=D;JEQ AMD=D;JGE AMD=D;JLT AMD=D;JNE AMD=D;JLE AMD=D;JMP AMD=A AMD=A;JGT AMD=A;JEQ AMD=A;JGE AMD=A;JLT AMD=A;JNE AMD=A;JLE AMD=A;JMP AMD=!D AMD=!D;JGT AMD=!D;JEQ AMD=!D;JGE AMD=!D;JLT AMD=!D;JNE AMD=!D;JLE AMD=!D;JMP AMD=!A AMD=!A;JGT AMD=!A;JEQ AMD=!A;JGE AMD=!A;JLT AMD=!A;JNE AMD=!A;JLE AMD=!A;JMP AMD=-D AMD=-D;JGT AMD=-D;JEQ AMD=-D;JGE AMD=-D;JLT AMD=-D;JNE AMD=-D;JLE AMD=-D;JMP AMD=-A AMD=-A;JGT AMD=-A;JEQ AMD=-A;JGE AMD=-A;JLT AMD=-A;JNE AMD=-A;JLE AMD=-A;JMP AMD=D+1 AMD=D+1;JGT AMD=D+1;JEQ AMD=D+1;JGE AMD=D+1;JLT AMD=D+1;JNE AMD=D+1;JLE AMD=D+1;JMP AMD=A+1 AMD=A+1;JGT AMD=A+1;JEQ AMD=A+1;JGE AMD=A+1;JLT AMD=A+1;JNE AMD=A+1;JLE AMD=A+1;JMP AMD=D-1 AMD=D-1;JGT AMD=D-1;JEQ AMD=D-1;JGE AMD=D-1;JLT AMD=D-1;JNE AMD=D-1;JLE AMD=D-1;JMP AMD=A-1 AMD=A-1;JGT AMD=A-1;JEQ AMD=A-1;JGE AMD=A-1;JLT AMD=A-1;JNE AMD=A-1;JLE AMD=A-1;JMP AMD=D+A AMD=D+A;JGT AMD=D+A;JEQ AMD=D+A;JGE AMD=D+A;JLT AMD=D+A;JNE AMD=D+A;JLE AMD=D+A;JMP AMD=D-A AMD=D-A;JGT AMD=D-A;JEQ AMD=D-A;JGE AMD=D-A;JLT AMD=D-A;JNE AMD=D-A;JLE AMD=D-A;JMP AMD=A-D AMD=A-D;JGT AMD=A-D;JEQ AMD=A-D;JGE AMD=A-D;JLT AMD=A-D;JNE AMD=A-D;JLE AMD=A-D;JMP AMD=D&A AMD=D&A;JGT AMD=D&A;JEQ AMD=D&A;JGE AMD=D&A;JLT AMD=D&A;JNE AMD=D&A;JLE AMD=D&A;JMP AMD=D|A AMD=D|A;JGT AMD=D|A;JEQ AMD=D|A;JGE AMD=D|A;JLT AMD=D|A;JNE AMD=D|A;JLE AMD=D|A;JMP AMD=M AMD=M;JGT AMD=M;JEQ AMD=M;JGE AMD=M;JLT AMD=M;JNE AMD=M;JLE AMD=M;JMP AMD=!M AMD=!M;JGT AMD=!M;JEQ AMD=!M;JGE AMD=!M;JLT AMD=!M;JNE AMD=!M;JLE AMD=!M;JMP AMD=-M AMD=-M;JGT AMD=-M;JEQ AMD=-M;JGE AMD=-M;JLT AMD=-M;JNE AMD=-M;JLE AMD=-M;JMP AMD=M+1 AMD=M+1;JGT AMD=M+1;JEQ AMD=M+1;JGE AMD=M+1;JLT AMD=M+1;JNE AMD=M+1;JLE AMD=M+1;JMP AMD=M-1 AMD=M-1;JGT AMD=M-1;JEQ AMD=M-1;JGE AMD=M-1;JLT AMD=M-1;JNE AMD=M-1;JLE AMD=M-1;JMP AMD=D+M AMD=D+M;JGT AMD=D+M;JEQ AMD=D+M;JGE AMD=D+M;JLT AMD=D+M;JNE AMD=D+M;JLE AMD=D+M;JMP AMD=D-M AMD=D-M;JGT AMD=D-M;JEQ AMD=D-M;JGE AMD=D-M;JLT AMD=D-M;JNE AMD=D-M;JLE AMD=D-M;JMP AMD=M-D AMD=M-D;JGT AMD=M-D;JEQ AMD=M-D;JGE AMD=M-D;JLT AMD=M-D;JNE AMD=M-D;JLE AMD=M-D;JMP AMD=D&M AMD=D&M;JGT AMD=D&M;JEQ AMD=D&M;JGE AMD=D&M;JLT AMD=D&M;JNE AMD=D&M;JLE AMD=D&M;JMP AMD=D|M AMD=D|M;JGT AMD=D|M;JEQ AMD=D|M;JGE AMD=D|M;JLT AMD=D|M;JNE AMD=D|M;JLE AMD=D|M;JMP
low
0.259802
99,885
module app_if_door_panel_is_opened_turn_on_wemo open IoTBottomUp as base open cap_doorControl open cap_switch lone sig app_if_door_panel_is_opened_turn_on_wemo extends IoTApp { trigObj : one cap_doorControl, switch : one cap_switch, } { rules = r } // application rules base class abstract sig r extends Rule {} one sig r1 extends r {}{ triggers = r1_trig no conditions commands = r1_comm } abstract sig r1_trig extends Trigger {} one sig r1_trig0 extends r1_trig {} { capabilities = app_if_door_panel_is_opened_turn_on_wemo.trigObj attribute = cap_doorControl_attr_door value = cap_doorControl_attr_door_val_open } abstract sig r1_comm extends Command {} one sig r1_comm0 extends r1_comm {} { capability = app_if_door_panel_is_opened_turn_on_wemo.switch attribute = cap_switch_attr_switch value = cap_switch_attr_switch_val_on }
high
0.363241
99,886
-- Abstract : -- -- Procedural packrat parser, supporting only direct left recursion. -- -- Coding style, algorithm is the same as generated by -- wisi-generate_packrat, but in procedural form. -- -- References: -- -- See parent. -- -- Copyright (C) 2018 - 2019 Free Software Foundation, Inc. -- -- This library is free software; you can redistribute it and/or modify it -- under terms of the GNU General Public License as published by the Free -- Software Foundation; either version 3, or (at your option) any later -- version. This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- As a special exception under Section 7 of GPL version 3, you are granted -- additional permissions described in the GCC Runtime Library Exception, -- version 3.1, as published by the Free Software Foundation. pragma License (Modified_GPL); with WisiToken.Productions; package WisiToken.Parse.Packrat.Procedural is -- These types duplicate Packrat.Generated. We keep them separate so -- we can experiment with ways of implementing indirect left -- recursion. type Memo_State is (No_Result, Failure, Success); subtype Result_States is Memo_State range Failure .. Success; type Memo_Entry (State : Memo_State := No_Result) is record case State is when No_Result => null; when Failure => null; when Success => Result : WisiToken.Syntax_Trees.Valid_Node_Index; Last_Pos : Base_Token_Index; end case; end record; package Memos is new SAL.Gen_Unbounded_Definite_Vectors (Token_Index, Memo_Entry, Default_Element => (others => <>)); type Derivs is array (Token_ID range <>) of Memos.Vector; type Parser (First_Nonterminal, Last_Nonterminal : Token_ID) is new Packrat.Parser with record Grammar : WisiToken.Productions.Prod_Arrays.Vector; Start_ID : Token_ID; Direct_Left_Recursive : Token_ID_Set (First_Nonterminal .. Last_Nonterminal); Derivs : Procedural.Derivs (First_Nonterminal .. Last_Nonterminal); end record; function Create (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Direct_Left_Recursive : in Token_ID_Set; Start_ID : in Token_ID; Trace : access WisiToken.Trace'Class; Lexer : WisiToken.Lexer.Handle; User_Data : WisiToken.Syntax_Trees.User_Data_Access) return Procedural.Parser; overriding procedure Parse (Parser : aliased in out Procedural.Parser); overriding function Tree (Parser : in Procedural.Parser) return Syntax_Trees.Tree; overriding function Any_Errors (Parser : in Procedural.Parser) return Boolean is (False); -- All errors are reported by Parse raising Syntax_Error. overriding procedure Put_Errors (Parser : in Procedural.Parser) is null; end WisiToken.Parse.Packrat.Procedural;
high
0.706731
99,887
module Rationals import ZZ %access public export Pair : Type Pair = (Integer, Integer) ZZPair : Type ZZPair = (ZZ, ZZ) ZZtoDb : ZZ -> Double ZZtoDb x = cast{from=Integer}{to=Double} (cast{from=ZZ}{to=Integer} x) DbtoZZ : Double -> ZZ DbtoZZ x = cast{from=Integer}{to=ZZ} (cast{from=Double}{to=Integer} x) isNotZero : Nat -> Bool isNotZero Z = False isNotZero (S k) = True divides : (m: Integer) -> (n: Integer) -> (k: Integer ** (m * k = n)) -> Integer divides m n k = (fst k) --Integer implemetation of gcd CalcGCD : (Integer, Integer) -> Integer CalcGCD (a, b) = if (isNotZero (toNat b)) then next else a where next = CalcGCD (b, toIntegerNat (modNat (toNat a) (toNat b))) OnlyPositive : (x: Pair) -> Pair OnlyPositive x = (if (fst x)>0 then fst x else (-1)*(fst x), if(snd x)>0 then (snd x) else (-1)*(snd x)) --Integer implemetation of gcd gccd : (Integer, Integer) -> Integer gccd x = CalcGCD (OnlyPositive x) data NotZero : Integer -> Type where --Proof that a number is not zero, needed to construct Q OneNotZero : NotZero 1 NegativeNotZero : ( n: Integer ) -> NotZero n -> NotZero (-n) PositiveNotZero : ( m: Integer ) -> LTE 1 (fromIntegerNat m) -> NotZero m data ZZNotZero : ZZ -> Type where ZZOneNotZero : ZZNotZero 1 ZZNegativeNotZero : ( n: ZZ ) -> ZZNotZero n -> ZZNotZero (-n) ZZPositiveNotZero : ( m: ZZ ) -> LTE 1 (fromIntegerNat (cast(m))) -> ZZNotZero m --Type for equality of two Rationals data EqRat : Pair -> Pair -> Type where IdEq : (m : Pair) -> EqRat m m MulEq : (c : Integer) -> EqRat n m -> EqRat ((fst n)*c,(snd n)*c) m make_rational : (p: Nat) -> (q: Integer) -> NotZero q -> Pair make_rational p q x = (toIntegerNat(p), q) InclusionMap : (n : Nat) -> Pair --Includes the naturals in Q InclusionMap n = make_rational n 1 OneNotZero AddRationals : (x: ZZPair) -> ZZNotZero (snd x) -> (y: ZZPair) -> ZZNotZero (snd y) -> ZZPair AddRationals x a y b = ((fst x)*(snd y) + (snd x)*(fst y), (snd x)*(snd y)) MultiplyRationals : (x: ZZPair) -> ZZNotZero (snd x) -> (y: ZZPair) -> ZZNotZero (snd y) -> ZZPair MultiplyRationals x a y b =((fst x)*(fst y), (snd x)*(snd y)) MultInverse : (x: ZZPair) -> ZZNotZero (fst x) -> ZZNotZero (snd x) -> ZZPair MultInverse x y z = ((snd x), (fst x)) AddInverse : (x: ZZPair) -> ZZNotZero (snd x) -> ZZPair AddInverse x a = (-(fst x), (snd x)) Subtraction : (x: ZZPair) -> ZZNotZero (snd x) -> (y: ZZPair) -> ZZNotZero (snd y) -> ZZPair Subtraction x a y b = AddRationals x a (AddInverse y b) b Division : (x: ZZPair) -> ZZNotZero (snd x) -> (y: ZZPair) -> ZZNotZero (fst y) -> ZZNotZero (snd y) -> ZZPair Division x a y b c = MultiplyRationals x a (MultInverse y b c) b --SimplifyRational : (x: Pair) -> NotZero (snd x) -> Pair --SimplifyRational x a = (divides (gcdab fromIntegerNat((fst x)) fromIntegerNat((snd x))) ___ (fst x), divides (gcdab fromIntegerNat((fst x)) fromIntegerNat((snd x)) __ (snd x)) --To prove that the SimplifyRational works, we can just check if the output is equal to the input -- To be done simplifyRational : (x : ZZPair) -> ZZPair simplifyRational (a, b) = (sa, sb) where sa = DbtoZZ (da / g) where da = ZZtoDb a g = cast {from=Integer} {to=Double} (gccd (cast {from=ZZ} {to=Integer}a,cast {from=ZZ} {to=Integer}b)) sb = DbtoZZ (db / g) where db = ZZtoDb b g = cast {from=Integer} {to=Double} (gccd (cast {from=ZZ} {to=Integer}a,cast {from=ZZ} {to=Integer}b)) --Above, I will need to supply a proof that the GCD divides the two numbers. Then, the function defined above will produce the rational in simplified form. xAndInverseNotZero : (x: ZZPair) -> (k: ZZNotZero (snd x)) -> ZZNotZero (snd (AddInverse x k)) xAndInverseNotZero x (ZZPositiveNotZero (snd x) y) = (ZZPositiveNotZero (snd x) y) FirstIsInverted : (x: ZZPair) -> (k: ZZNotZero (snd x)) -> (a: ZZ) -> (a = (fst x)) -> ((-a) = fst (AddInverse x k)) FirstIsInverted x k a prf = (apZZ (\x => -x) a (fst x) prf) SecondStaysSame : (x: ZZPair) -> (k: ZZNotZero (snd x)) -> (b: ZZ) -> (b = (snd x)) -> (b = (snd (AddInverse x k))) SecondStaysSame x k b prf = (apZZ (\x => x) b (snd x) prf) xplusinverse: (x: ZZPair) -> (k: ZZNotZero (snd x)) -> ZZPair xplusinverse x k = AddRationals x k (AddInverse x k) (xAndInverseNotZero x k) addinverselemma: (a: ZZ) -> (b: ZZ) -> ((-a)=b) -> (a + b = ((-a) + a)) -> ((-a)+a =0 ) -> (a + b = 0) addinverselemma a b prf prf1 prf2 = trans prf1 prf2 addinverseFST: (x: ZZPair) -> (k: ZZNotZero (snd x)) -> (a: ZZ) -> (a = (fst x)) -> (fst (AddInverse x k) = b) -> ((-a) = b) addinverseFST x k a prf prf1 = trans (FirstIsInverted x k a prf) (prf1) addinverseSND: (x: ZZPair) -> (k: ZZNotZero (snd x)) -> (c: ZZ) -> (c = (snd x)) -> (snd (AddInverse x k) = b) -> (c = b) addinverseSND x k c prf prf1 = trans (SecondStaysSame x k c prf) (prf1)
high
0.484424
99,888
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2021 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include "fragment.glsl" in vec4 vs_color; in float vs_depth; uniform bool usingAdditiveBlending; Fragment getFragment() { if (vs_color.a == 0) { discard; } vec4 fragColor = vs_color; Fragment frag; frag.depth = vs_depth; frag.color = fragColor; // G-Buffer frag.gPosition = vec4(0.0);//vs_gPosition; // There is no normal here // TODO: Add the correct normal if necessary (JCC) frag.gNormal = vec4(0.0, 0.0, -1.0, 1.0); if (usingAdditiveBlending) { frag.blend = BLEND_MODE_ADDITIVE; } return frag; }
high
0.679268
99,889
; Auto-generated. Do not edit! (cl:in-package ros_tcp_endpoint-msg) ;//! \htmlinclude RosUnityError.msg.html (cl:defclass <RosUnityError> (roslisp-msg-protocol:ros-message) ((message :reader message :initarg :message :type cl:string :initform "")) ) (cl:defclass RosUnityError (<RosUnityError>) ()) (cl:defmethod cl:initialize-instance :after ((m <RosUnityError>) cl:&rest args) (cl:declare (cl:ignorable args)) (cl:unless (cl:typep m 'RosUnityError) (roslisp-msg-protocol:msg-deprecation-warning "using old message class name ros_tcp_endpoint-msg:<RosUnityError> is deprecated: use ros_tcp_endpoint-msg:RosUnityError instead."))) (cl:ensure-generic-function 'message-val :lambda-list '(m)) (cl:defmethod message-val ((m <RosUnityError>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ros_tcp_endpoint-msg:message-val is deprecated. Use ros_tcp_endpoint-msg:message instead.") (message m)) (cl:defmethod roslisp-msg-protocol:serialize ((msg <RosUnityError>) ostream) "Serializes a message object of type '<RosUnityError>" (cl:let ((__ros_str_len (cl:length (cl:slot-value msg 'message)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_str_len) ostream)) (cl:map cl:nil #'(cl:lambda (c) (cl:write-byte (cl:char-code c) ostream)) (cl:slot-value msg 'message)) ) (cl:defmethod roslisp-msg-protocol:deserialize ((msg <RosUnityError>) istream) "Deserializes a message object of type '<RosUnityError>" (cl:let ((__ros_str_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'message) (cl:make-string __ros_str_len)) (cl:dotimes (__ros_str_idx __ros_str_len msg) (cl:setf (cl:char (cl:slot-value msg 'message) __ros_str_idx) (cl:code-char (cl:read-byte istream))))) msg ) (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<RosUnityError>))) "Returns string type for a message object of type '<RosUnityError>" "ros_tcp_endpoint/RosUnityError") (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'RosUnityError))) "Returns string type for a message object of type 'RosUnityError" "ros_tcp_endpoint/RosUnityError") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<RosUnityError>))) "Returns md5sum for a message object of type '<RosUnityError>" "5f003d6bcc824cbd51361d66d8e4f76c") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'RosUnityError))) "Returns md5sum for a message object of type 'RosUnityError" "5f003d6bcc824cbd51361d66d8e4f76c") (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<RosUnityError>))) "Returns full string definition for message of type '<RosUnityError>" (cl:format cl:nil "string message~%~%")) (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'RosUnityError))) "Returns full string definition for message of type 'RosUnityError" (cl:format cl:nil "string message~%~%")) (cl:defmethod roslisp-msg-protocol:serialization-length ((msg <RosUnityError>)) (cl:+ 0 4 (cl:length (cl:slot-value msg 'message)) )) (cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <RosUnityError>)) "Converts a ROS message object to a list" (cl:list 'RosUnityError (cl:cons ':message (message msg)) ))
high
0.586357
99,890
// macros to just make things compile `define rv64 True `define m True `define a True `define f True `define d True `define sizeSup 1 `define NUM_CORES 1 `define NUM_EPOCHS 1 `define ROB_SIZE 1 `define LDQ_SIZE 1 `define STQ_SIZE 1 `define SB_SIZE 1 `define DRAM_MAX_READS 1 `define DRAM_MAX_WRITES 1 `define DRAM_MAX_REQS 1 `define DRAM_LATENCY 1 `define LOG_DEADLOCK_CYCLES 26 `define LOG_BOOT_ROM_BYTES 12 // useful macros `define NUM_SPEC_TAGS 16 `define TLB_SIZE 32 `define DTLB_REQ_NUM 4
low
0.392851
99,891
function New-InsightHeaders { <# .SYNOPSIS Generate Insight headers. .EXAMPLE $Headers = New-InsightHeaders -ApiKey $InsightApiKey .OUTPUTS Generic dictionary. #> param ( [Parameter(Mandatory = $true)] [string]$InsightApiKey ) Write-Verbose 'Generating Headers' $Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $Headers.Add('content-type' , 'application/json') $Headers.Add('authorization', 'bearer ' + $InsightApiKey) Write-Output $Headers }
high
0.287403
99,892
(cl:in-package #:asdf-user) (defsystem #:sicl-boot-phase-0 :depends-on (#:sicl-boot-base #:sicl-hir-interpreter #:sicl-source-tracking #:sicl-data-and-control-flow-support #:sicl-package-support #:sicl-sequence-support #:sicl-arithmetic #:sicl-printer-support #:eclector #:eclector-concrete-syntax-tree #:cleavir-io) :serial t :components ((:file "packages") (:file "eval") (:file "host-load") (:file "import-from-host") (:file "define-defmacro") (:file "define-backquote-macro") (:file "define-setf-macro-function") (:file "fill-environment") (:file "environment") (:file "load-file") (:file "boot")))
high
0.485143
99,893
library ieee; use ieee.std_logic_1164.all; use IEEE.NUMERIC_STD.ALL; entity bootrom is port (CLK : in std_logic; EN : in std_logic; ADDR : in std_logic_vector(4 downto 0); DATA : out std_logic_vector(15 downto 0)); end bootrom; architecture syn of bootrom is constant ROMSIZE: integer := 64; type ROM_TYPE is array(0 to ROMSIZE/2-1) of std_logic_vector(15 downto 0); signal ROM: ROM_TYPE := (x"0801", x"0afd", x"5853", x"0600", x"1600", x"0402", x"5032", x"4020", x"3007", x"1701", x"3006", x"1700", x"0e0c", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000", x"0000"); signal rdata : std_logic_vector(15 downto 0); begin rdata <= ROM(to_integer(unsigned(ADDR))); process (CLK) begin if (CLK'event and CLK = '1') then if (EN = '1') then DATA <= rdata; end if; end if; end process; end syn;
high
0.538367
99,894
/** *Submitted for verification at Etherscan.io on 2021-07-11 */ /** *Submitted for verification at Etherscan.io on 2021-07-08 */ /** *Submitted for verification at Etherscan.io on 2021-04-30 */ /** *Submitted for verification at Etherscan.io on 2020-05-04 */ pragma solidity =0.5.16; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function getPair(address tokenA, address tokenB) external view returns (address pair); function permissions(address user) external view returns (bool status); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB, address feeOwner) external returns (address pair); } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address, address) external; function setFeeOwner(address _feeOwner) external; } interface IUniswapV2ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } contract Context { constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract UniswapV2ERC20 is IUniswapV2ERC20 { using SafeMath for uint; string public constant name = 'Crypto Mine'; string public constant symbol = 'CM'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'Crypto Mine: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'Crypto Mine: INVALID_SIGNATURE'); _approve(owner, spender, value); } } contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 { using SafeMath for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; address public feeOwner; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint public price0CumulativeLast; uint public price1CumulativeLast; uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'Crypto Mine: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'Crypto Mine: TRANSFER_FAILED'); } event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1, address _feeOwner) external { require(msg.sender == factory, 'Crypto Mine: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; feeOwner = _feeOwner; } // update reserves and, on the first call per block, price accumulators function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'Crypto Mine: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint liquidity) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings uint balance0 = IERC20(token0).balanceOf(address(this)); uint balance1 = IERC20(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); //bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'Crypto Mine: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint amount0, uint amount1) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint balance0 = IERC20(_token0).balanceOf(address(this)); uint balance1 = IERC20(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'Crypto Mine: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'Crypto Mine:INSUFFICIENT_OUTPUT_AMOUNT'); require(amount0Out == 0 || amount1Out == 0, 'Crypto Mine:INSUFFICIENT_OUTPUT_AMOUNT 0'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'Crypto Mine: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'Crypto Mine: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); { uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(100)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(100)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K'); uint256 kresidue = balance0.mul(balance1).sub(uint(_reserve0).mul(_reserve1)); (address token,uint256 fee) = amount0Out==0?(token0,kresidue/balance1):(token1,kresidue/balance0); if(fee>0) _safeTransfer(token, feeOwner, fee); balance0 = IERC20(token0).balanceOf(address(this)); balance1 = IERC20(token1).balanceOf(address(this)); } require(balance0.mul(balance1) >= uint(_reserve0).mul(_reserve1), 'Crypto Mine: invalid_FEE'); _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); } function setFeeOwner(address _feeOwner) external { if(feeOwner!=address(0)){ require(msg.sender == feeOwner, 'Crypto Mine: FORBIDDEN'); } feeOwner = _feeOwner; } } contract UniswapV2Factory is IUniswapV2Factory,Ownable { mapping(address => mapping(address => address)) public getPair; address[] public allPairs; mapping(address => bool) public permissions; bytes32 public initCodeHash; event PairCreated(address indexed token0, address indexed token1, address pair, uint); event SetPermission(address indexed,bool); constructor() public { initCodeHash = keccak256(abi.encodePacked(type(UniswapV2Pair).creationCode)); } modifier authority(){ require(permissions[_msgSender()],"Crypto Mine: access denied"); _; } function allPairsLength() external view returns (uint) { return allPairs.length; } function setPermission(address userAddress,bool status) public onlyOwner { permissions[userAddress] = status; emit SetPermission(userAddress,status); } function createPair(address tokenA, address tokenB, address feeOwner) external authority returns (address pair) { require(tokenA != tokenB, 'Crypto Mine: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'Crypto Mine: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'Crypto Mine: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } IUniswapV2Pair(pair).initialize(token0, token1, feeOwner); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } }
high
0.509586
99,895
(ns book.html-converter (:require [com.fulcrologic.fulcro.dom :as dom] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]] [hickory.core :as hc] [clojure.set :as set] [clojure.pprint :refer [pprint]] [clojure.string :as str])) (def attr-renames { :class :className :for :htmlFor :tabindex :tabIndex :viewbox :viewBox :spellcheck :spellcheck :autocorrect :autoCorrect :autocomplete :autoComplete}) (defn elem-to-cljs [elem] (cond (and (string? elem) (let [elem (str/trim elem)] (or (= "" elem) (and (str/starts-with? elem "<!--") (str/ends-with? elem "-->")) (re-matches #"^[ \n]*$" elem)))) nil (string? elem) (str/trim elem) (vector? elem) (let [tag (name (first elem)) attrs (set/rename-keys (second elem) attr-renames) children (keep elem-to-cljs (drop 2 elem))] (concat (list (symbol "dom" tag) attrs) children)) :otherwise "UNKNOWN")) (defn to-cljs "Convert an HTML fragment (containing just one tag) into a corresponding Dom cljs" [html-fragment] (let [hiccup-list (map hc/as-hiccup (hc/parse-fragment html-fragment))] (first (map elem-to-cljs hiccup-list)))) (defmutation convert [p] (action [{:keys [state]}] (let [html (get-in @state [:top :conv :html]) cljs (to-cljs html)] (swap! state assoc-in [:top :conv :cljs] {:code cljs})))) (defsc HTMLConverter [this {:keys [html cljs]}] {:initial-state (fn [params] {:html "<div id=\"3\" class=\"b\"><p>Paragraph</p></div>" :cljs {:code (list)}}) :query [:cljs :html] :ident (fn [] [:top :conv])} (dom/div {:className ""} (dom/textarea {:cols 80 :rows 10 :onChange (fn [evt] (m/set-string! this :html :event evt)) :value html}) (dom/pre {} (with-out-str (pprint (:code cljs)))) (dom/button :.c-button {:onClick (fn [evt] (comp/transact! this `[(convert {})]))} "Convert"))) (def ui-html-convert (comp/factory HTMLConverter)) (defsc Root [this {:keys [converter]}] {:initial-state {:converter {}} :query [{:converter (comp/get-query HTMLConverter)}]} (ui-html-convert converter))
high
0.553343
99,896
-- -------------------------------------------------------- -- Title: Retrieves a glucose histogram of adult patients -- 检索成年患者的血糖直方图 -- Notes: this query does not specify a schema. To run it on your local -- MIMIC schema, run the following command: -- SET SEARCH_PATH TO mimiciii; -- Where "mimiciii" is the name of your schema, and may be different. -- -------------------------------------------------------- WITH agetbl AS ( SELECT ad.subject_id FROM admissions ad INNER JOIN patients p ON ad.subject_id = p.subject_id WHERE -- filter to only adults EXTRACT(EPOCH FROM (ad.admittime - p.dob))/60.0/60.0/24.0/365.242 > 15 -- group by subject_id to ensure there is only 1 subject_id per row group by ad.subject_id ) , glc as ( SELECT width_bucket(valuenum, 0.5, 1000, 1000) AS bucket FROM labevents le INNER JOIN agetbl ON le.subject_id = agetbl.subject_id WHERE itemid IN (50809,50931) AND valuenum IS NOT NULL ) SELECT bucket as glucose, count(*) FROM glc GROUP BY bucket ORDER BY bucket;
high
0.436019
99,897
module Libraries.Text.PrettyPrint.Prettyprinter.Render.Terminal import Data.Maybe import Data.String import public Libraries.Control.ANSI import Control.Monad.ST import Libraries.Text.PrettyPrint.Prettyprinter.Doc %default covering public export AnsiStyle : Type AnsiStyle = List SGR export color : Color -> AnsiStyle color c = pure $ SetForeground c export bgColor : Color -> AnsiStyle bgColor c = pure $ SetBackground c export bold : AnsiStyle bold = pure $ SetStyle Bold export italic : AnsiStyle italic = pure $ SetStyle Italic export underline : AnsiStyle underline = pure $ SetStyle SingleUnderline export strike : AnsiStyle strike = pure $ SetStyle Striked export renderString : SimpleDocStream AnsiStyle -> String renderString sdoc = fromMaybe "<internal pretty printing error>" $ runST $ do styleStackRef <- newSTRef {a = List AnsiStyle} [neutral] outputRef <- newSTRef {a = String} neutral go styleStackRef outputRef sdoc readSTRef styleStackRef >>= \case [] => pure Nothing [_] => Just <$> readSTRef outputRef _ => pure Nothing where push : STRef s (List AnsiStyle) -> List SGR -> ST s () push stack x = modifySTRef stack (x ::) peek : STRef s (List AnsiStyle) -> ST s (Maybe AnsiStyle) peek stack = do (x :: _) <- readSTRef stack | [] => pure Nothing pure (Just x) pop : STRef s (List AnsiStyle) -> ST s (Maybe AnsiStyle) pop stack = do (x :: xs) <- readSTRef stack | [] => pure Nothing writeSTRef stack xs pure (Just x) writeOutput : STRef s String -> String -> ST s () writeOutput out x = modifySTRef out (<+> x) go : STRef s (List AnsiStyle) -> STRef s String -> SimpleDocStream AnsiStyle -> ST s () go stack out SEmpty = pure () go stack out (SChar c rest) = do writeOutput out (singleton c) go stack out rest go stack out (SText l t rest) = do writeOutput out t go stack out rest go stack out (SLine l rest) = do writeOutput out (singleton '\n' <+> textSpaces l) go stack out rest go stack out (SAnnPush style rest) = do Just currentStyle <- peek stack | Nothing => writeSTRef stack [] let newStyle = style <+> currentStyle push stack newStyle writeOutput out (escapeSGR newStyle) go stack out rest go stack out (SAnnPop rest) = do _ <- pop stack Just newStyle <- peek stack | Nothing => writeSTRef stack [] writeOutput out (escapeSGR (Reset :: newStyle)) go stack out rest export renderIO : SimpleDocStream AnsiStyle -> IO () renderIO = putStrLn . renderString export putDoc : Doc AnsiStyle -> IO () putDoc = renderIO . layoutPretty defaultLayoutOptions
high
0.793775
99,898
------------------------------------------------------------------------------ -- Test the consistency of FOTC.Program.ABP.ABP ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} -- In the module FOTC.Program.ABP.ABP we declare Agda postulates as -- first-order logic axioms. We test if it is possible to prove an -- unprovable theorem from these axioms. module FOTC.Program.ABP.ABP.Consistency.Axioms where open import FOTC.Base open import FOTC.Program.ABP.ABP ------------------------------------------------------------------------------ postulate impossible : ∀ d e → d ≡ e {-# ATP prove impossible #-}
high
0.432482
99,899
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- package body Program.Nodes.Formal_Interface_Types is function Create (Limited_Token : Program.Lexical_Elements.Lexical_Element_Access; Task_Token : Program.Lexical_Elements.Lexical_Element_Access; Protected_Token : Program.Lexical_Elements.Lexical_Element_Access; Synchronized_Token : Program.Lexical_Elements.Lexical_Element_Access; Interface_Token : Program.Lexical_Elements.Lexical_Element_Access; And_Token : Program.Lexical_Elements.Lexical_Element_Access; Progenitors : Program.Elements.Expressions .Expression_Vector_Access) return Formal_Interface_Type is begin return Result : Formal_Interface_Type := (Limited_Token => Limited_Token, Task_Token => Task_Token, Protected_Token => Protected_Token, Synchronized_Token => Synchronized_Token, Interface_Token => Interface_Token, And_Token => And_Token, Progenitors => Progenitors, Enclosing_Element => null) do Initialize (Result); end return; end Create; function Create (Progenitors : Program.Elements.Expressions .Expression_Vector_Access; Is_Part_Of_Implicit : Boolean := False; Is_Part_Of_Inherited : Boolean := False; Is_Part_Of_Instance : Boolean := False; Has_Limited : Boolean := False; Has_Task : Boolean := False; Has_Protected : Boolean := False; Has_Synchronized : Boolean := False) return Implicit_Formal_Interface_Type is begin return Result : Implicit_Formal_Interface_Type := (Progenitors => Progenitors, Is_Part_Of_Implicit => Is_Part_Of_Implicit, Is_Part_Of_Inherited => Is_Part_Of_Inherited, Is_Part_Of_Instance => Is_Part_Of_Instance, Has_Limited => Has_Limited, Has_Task => Has_Task, Has_Protected => Has_Protected, Has_Synchronized => Has_Synchronized, Enclosing_Element => null) do Initialize (Result); end return; end Create; overriding function Progenitors (Self : Base_Formal_Interface_Type) return Program.Elements.Expressions.Expression_Vector_Access is begin return Self.Progenitors; end Progenitors; overriding function Limited_Token (Self : Formal_Interface_Type) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Limited_Token; end Limited_Token; overriding function Task_Token (Self : Formal_Interface_Type) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Task_Token; end Task_Token; overriding function Protected_Token (Self : Formal_Interface_Type) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Protected_Token; end Protected_Token; overriding function Synchronized_Token (Self : Formal_Interface_Type) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Synchronized_Token; end Synchronized_Token; overriding function Interface_Token (Self : Formal_Interface_Type) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Interface_Token; end Interface_Token; overriding function And_Token (Self : Formal_Interface_Type) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.And_Token; end And_Token; overriding function Has_Limited (Self : Formal_Interface_Type) return Boolean is begin return Self.Limited_Token.Assigned; end Has_Limited; overriding function Has_Task (Self : Formal_Interface_Type) return Boolean is begin return Self.Task_Token.Assigned; end Has_Task; overriding function Has_Protected (Self : Formal_Interface_Type) return Boolean is begin return Self.Protected_Token.Assigned; end Has_Protected; overriding function Has_Synchronized (Self : Formal_Interface_Type) return Boolean is begin return Self.Synchronized_Token.Assigned; end Has_Synchronized; overriding function Is_Part_Of_Implicit (Self : Implicit_Formal_Interface_Type) return Boolean is begin return Self.Is_Part_Of_Implicit; end Is_Part_Of_Implicit; overriding function Is_Part_Of_Inherited (Self : Implicit_Formal_Interface_Type) return Boolean is begin return Self.Is_Part_Of_Inherited; end Is_Part_Of_Inherited; overriding function Is_Part_Of_Instance (Self : Implicit_Formal_Interface_Type) return Boolean is begin return Self.Is_Part_Of_Instance; end Is_Part_Of_Instance; overriding function Has_Limited (Self : Implicit_Formal_Interface_Type) return Boolean is begin return Self.Has_Limited; end Has_Limited; overriding function Has_Task (Self : Implicit_Formal_Interface_Type) return Boolean is begin return Self.Has_Task; end Has_Task; overriding function Has_Protected (Self : Implicit_Formal_Interface_Type) return Boolean is begin return Self.Has_Protected; end Has_Protected; overriding function Has_Synchronized (Self : Implicit_Formal_Interface_Type) return Boolean is begin return Self.Has_Synchronized; end Has_Synchronized; procedure Initialize (Self : in out Base_Formal_Interface_Type'Class) is begin for Item in Self.Progenitors.Each_Element loop Set_Enclosing_Element (Item.Element, Self'Unchecked_Access); end loop; null; end Initialize; overriding function Is_Formal_Interface_Type (Self : Base_Formal_Interface_Type) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Formal_Interface_Type; overriding function Is_Formal_Type_Definition (Self : Base_Formal_Interface_Type) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Formal_Type_Definition; overriding function Is_Definition (Self : Base_Formal_Interface_Type) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Definition; overriding procedure Visit (Self : not null access Base_Formal_Interface_Type; Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is begin Visitor.Formal_Interface_Type (Self); end Visit; overriding function To_Formal_Interface_Type_Text (Self : in out Formal_Interface_Type) return Program.Elements.Formal_Interface_Types .Formal_Interface_Type_Text_Access is begin return Self'Unchecked_Access; end To_Formal_Interface_Type_Text; overriding function To_Formal_Interface_Type_Text (Self : in out Implicit_Formal_Interface_Type) return Program.Elements.Formal_Interface_Types .Formal_Interface_Type_Text_Access is pragma Unreferenced (Self); begin return null; end To_Formal_Interface_Type_Text; end Program.Nodes.Formal_Interface_Types;
high
0.839372
99,900
module ANF where open import Data.Nat open import Data.Vec open import Data.Fin open import Data.String open import Data.Rational open import Data.Sum open import Data.Unit open import Binders.Var record DataConApp (universe a : Set) : Set where constructor _#_◂_ -- theres probably room for a better notation :))) field -- universe : Set arity : ℕ schema : Vec universe arity app : Vec a arity mutual data term (a : Set ) : Set where v : a -> term a -- variables return only appears in "tail" position app : ∀ (n : ℕ ) -> Callish a n -> term a letCall : ∀ (n : ℕ ) -> Callish a n -> term (Var (Fin n) a) -> term a letAlloc : Allocish a 1 -> term (Var (Fin 1) a) -> term a -- for now we only model direct allocations have having a single return value ... data Allocish (a : Set) : ℕ -> Set where lam : ∀ (n : ℕ ) -> term (Var (Fin n) (term a)) -> Allocish a 1 delay : term a -> Allocish a 1 dataConstr : DataConApp ⊤ {- for now using unit as the universe -} a -> Allocish a 1 data Callish (a : Set) : ℕ -> Set where force : a -> Callish a 0 call : ∀ {n } -> a -> Vec a n -> Callish a n primCall : ∀ {n } -> String -> Vec a n -> Callish a n
high
0.42489
99,901
less = Npm.require('less') autoprefixer = Npm.require('less-plugin-autoprefix') crypto = Npm.require('crypto') calculateClientHash = WebAppHashing.calculateClientHash WebAppHashing.calculateClientHash = (manifest, includeFilter, runtimeConfigOverride) -> css = RocketChat.theme.getCss() WebAppInternals.staticFiles['/__cordova/theme.css'] = WebAppInternals.staticFiles['/theme.css'] = cacheable: true sourceMapUrl: undefined type: 'css' content: css hash = crypto.createHash('sha1').update(css).digest('hex') themeManifestItem = _.find manifest, (item) -> return item.path is 'app/theme.css' if not themeManifestItem? themeManifestItem = {} manifest.push themeManifestItem themeManifestItem.path = 'app/theme.css' themeManifestItem.type = 'css' themeManifestItem.cacheable = true themeManifestItem.where = 'client' themeManifestItem.url = "/theme.css?#{hash}" themeManifestItem.size = css.length themeManifestItem.hash = hash calculateClientHash.call this, manifest, includeFilter, runtimeConfigOverride RocketChat.theme = new class variables: {} files: [ 'assets/stylesheets/global/_variables.less' 'assets/stylesheets/utils/_emojione.import.less' 'assets/stylesheets/utils/_keyframes.import.less' 'assets/stylesheets/utils/_lesshat.import.less' 'assets/stylesheets/utils/_preloader.import.less' 'assets/stylesheets/utils/_reset.import.less' 'assets/stylesheets/utils/_octicons.less' 'assets/stylesheets/utils/_chatops.less' 'assets/stylesheets/animation.css' 'assets/stylesheets/base.less' 'assets/stylesheets/fontello.css' 'assets/stylesheets/rtl.less' 'assets/stylesheets/swipebox.min.css' 'assets/stylesheets/utils/_colors.import.less' ] constructor: -> RocketChat.settings.add 'css', '' RocketChat.settings.addGroup 'Theme' compile = _.debounce Meteor.bindEnvironment(@compile.bind(@)), 200 RocketChat.settings.onload '*', Meteor.bindEnvironment (key, value, initialLoad) => if /^theme-.+/.test(key) is false then return name = key.replace /^theme-[a-z]+-/, '' if @variables[name]? @variables[name].value = value compile() compile: -> content = [ @getVariablesAsLess() ] content.push Assets.getText file for file in @files content = content.join '\n' options = compress: true plugins: [ new autoprefixer() ] start = Date.now() less.render content, options, (err, data) -> console.log 'stop rendering', Date.now() - start if err? return console.log err RocketChat.settings.updateById 'css', data.css process.emit('message', {refresh: 'client'}) addVariable: (type, name, value, persist=true) -> @variables[name] = type: type value: value if persist is true config = group: 'Theme' type: type section: type public: false RocketChat.settings.add "theme-#{type}-#{name}", value, config addPublicColor: (name, value) -> @addVariable 'color', name, value, true getVariablesAsObject: -> obj = {} for name, variable of @variables obj[name] = variable.value return obj getVariablesAsLess: -> items = [] for name, variable of @variables items.push "@#{name}: #{variable.value};" return items.join '\n' getCss: -> return RocketChat.settings.get 'css'
high
0.481626
99,902
## # vcpkg_configure_meson ## ## Configure Meson for Debug and Release builds of a project. ## ## ## Usage ## ```cmake ## vcpkg_configure_meson( ## SOURCE_PATH <${SOURCE_PATH}> ## [OPTIONS <-DUSE_THIS_IN_ALL_BUILDS=1>...] ## [OPTIONS_RELEASE <-DOPTIMIZE=1>...] ## [OPTIONS_DEBUG <-DDEBUGGABLE=1>...] ## ) ## ``` ## ## ## Parameters ## ### SOURCE_PATH ## Specifies the directory containing the `meson.build`. ## By convention, this is usually set in the portfile as the variable `SOURCE_PATH`. ## ## ### OPTIONS ## Additional options passed to Meson during the configuration. ## ## ### OPTIONS_RELEASE ## Additional options passed to Meson during the Release configuration. These are in addition to `OPTIONS`. ## ## ### OPTIONS_DEBUG ## Additional options passed to Meson during the Debug configuration. These are in addition to `OPTIONS`. ## ## ## Notes ## This command supplies many common arguments to Meson. To see the full list, examine the source. ## ## ## Examples ## ## * [fribidi](https://github.com/Microsoft/vcpkg/blob/master/ports/fribidi/portfile.cmake) ## * [libepoxy](https://github.com/Microsoft/vcpkg/blob/master/ports/libepoxy/portfile.cmake) function(vcpkg_configure_meson) # parse parameters such that semicolons in options arguments to COMMAND don't get erased cmake_parse_arguments(PARSE_ARGV 0 _vcm "" "SOURCE_PATH" "OPTIONS;OPTIONS_DEBUG;OPTIONS_RELEASE") file(REMOVE_RECURSE ${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel) file(REMOVE_RECURSE ${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg) #Extract compiler flags if(NOT VCPKG_CHAINLOAD_TOOLCHAIN_FILE) set(MESON_CMAKE_FLAG_SUFFIX "_INIT") if(VCPKG_TARGET_IS_WINDOWS AND NOT VCPKG_TARGET_IS_MINGW) set(VCPKG_CHAINLOAD_TOOLCHAIN_FILE "${SCRIPTS}/toolchains/windows.cmake") set(MESON_CMAKE_FLAG_SUFFIX "") elseif(VCPKG_TARGET_IS_LINUX) set(VCPKG_CHAINLOAD_TOOLCHAIN_FILE "${SCRIPTS}/toolchains/linux.cmake") elseif(VCPKG_TARGET_IS_ANDROID) set(VCPKG_CHAINLOAD_TOOLCHAIN_FILE "${SCRIPTS}/toolchains/android.cmake") elseif(VCPKG_TARGET_IS_OSX) set(VCPKG_CHAINLOAD_TOOLCHAIN_FILE "${SCRIPTS}/toolchains/osx.cmake") elseif(VVCPKG_TARGET_IS_FREEBSD) set(VCPKG_CHAINLOAD_TOOLCHAIN_FILE "${SCRIPTS}/toolchains/freebsd.cmake") elseif(VCPKG_TARGET_IS_MINGW) set(VCPKG_CHAINLOAD_TOOLCHAIN_FILE "${SCRIPTS}/toolchains/mingw.cmake") endif() endif() include("${VCPKG_CHAINLOAD_TOOLCHAIN_FILE}") string(APPEND MESON_COMMON_CFLAGS " ${CMAKE_C_FLAGS${MESON_CMAKE_FLAG_SUFFIX}}") string(APPEND MESON_COMMON_CXXFLAGS " ${CMAKE_CXX_FLAGS${MESON_CMAKE_FLAG_SUFFIX}}") string(APPEND MESON_DEBUG_CFLAGS " ${CMAKE_C_FLAGS_DEBUG${MESON_CMAKE_FLAG_SUFFIX}}") string(APPEND MESON_DEBUG_CXXFLAGS " ${CMAKE_CXX_FLAGS_DEBUG${MESON_CMAKE_FLAG_SUFFIX}}") string(APPEND MESON_RELEASE_CFLAGS " ${CMAKE_C_FLAGS_RELEASE${MESON_CMAKE_FLAG_SUFFIX}}") string(APPEND MESON_RELEASE_CXXFLAGS " ${CMAKE_CXX_FLAGS_RELEASE${MESON_CMAKE_FLAG_SUFFIX}}") string(APPEND MESON_COMMON_LDFLAGS " ${CMAKE_SHARED_LINKER_FLAGS${MESON_CMAKE_FLAG_SUFFIX}}") string(APPEND MESON_DEBUG_LDFLAGS " ${CMAKE_SHARED_LINKER_FLAGS_DEBUG${MESON_CMAKE_FLAG_SUFFIX}}") string(APPEND MESON_RELEASE_LDFLAGS " ${CMAKE_SHARED_LINKER_FLAGS_RELEASE${MESON_CMAKE_FLAG_SUFFIX}}") # select meson cmd-line options if(VCPKG_TARGET_IS_WINDOWS) list(APPEND _vcm_OPTIONS "-Dcmake_prefix_path=['${CURRENT_INSTALLED_DIR}','${CURRENT_INSTALLED_DIR}/share']") else() list(APPEND _vcm_OPTIONS "-Dcmake_prefix_path=['${CURRENT_INSTALLED_DIR}']") endif() list(APPEND _vcm_OPTIONS --buildtype plain --backend ninja --wrap-mode nodownload) if(VCPKG_LIBRARY_LINKAGE STREQUAL "dynamic") list(APPEND _vcm_OPTIONS --default-library shared) else() list(APPEND _vcm_OPTIONS --default-library static) endif() list(APPEND _vcm_OPTIONS --libdir lib) # else meson install into an architecture describing folder list(APPEND _vcm_OPTIONS_DEBUG --prefix ${CURRENT_PACKAGES_DIR}/debug --includedir ../include) list(APPEND _vcm_OPTIONS_RELEASE --prefix ${CURRENT_PACKAGES_DIR}) vcpkg_find_acquire_program(MESON) get_filename_component(CMAKE_PATH ${CMAKE_COMMAND} DIRECTORY) vcpkg_add_to_path("${CMAKE_PATH}") # Make CMake invokeable for Meson vcpkg_find_acquire_program(NINJA) get_filename_component(NINJA_PATH ${NINJA} DIRECTORY) vcpkg_add_to_path("${NINJA_PATH}") vcpkg_find_acquire_program(PKGCONFIG) get_filename_component(PKGCONFIG_PATH ${PKGCONFIG} DIRECTORY) vcpkg_add_to_path("${PKGCONFIG_PATH}") set(PKGCONFIG_SHARE_DIR "${CURRENT_INSTALLED_DIR}/share/pkgconfig/") # configure debug if(NOT DEFINED VCPKG_BUILD_TYPE OR VCPKG_BUILD_TYPE STREQUAL "debug") message(STATUS "Configuring ${TARGET_TRIPLET}-dbg") file(MAKE_DIRECTORY ${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg) #setting up PKGCONFIG if(NOT PKGCONFIG MATCHES "--define-variable=prefix") set(PKGCONFIG_PREFIX "${CURRENT_INSTALLED_DIR}/debug") set(ENV{PKG_CONFIG} "${PKGCONFIG} --define-variable=prefix=${PKGCONFIG_PREFIX}") endif() set(PKGCONFIG_INSTALLED_DIR "${CURRENT_INSTALLED_DIR}/debug/lib/pkgconfig/") if(ENV{PKG_CONFIG_PATH}) set(BACKUP_ENV_PKG_CONFIG_PATH_DEBUG $ENV{PKG_CONFIG_PATH}) set(ENV{PKG_CONFIG_PATH} "${PKGCONFIG_INSTALLED_DIR}${VCPKG_HOST_PATH_SEPARATOR}${PKGCONFIG_SHARE_DIR}${VCPKG_HOST_PATH_SEPARATOR}$ENV{PKG_CONFIG_PATH}") else() set(ENV{PKG_CONFIG_PATH} "${PKGCONFIG_INSTALLED_DIR}${VCPKG_HOST_PATH_SEPARATOR}${PKGCONFIG_SHARE_DIR}") endif() set(CFLAGS "-Dc_args=[${MESON_COMMON_CFLAGS} ${MESON_DEBUG_CFLAGS}]") string(REGEX REPLACE " +(/|-)" "','\\1" CFLAGS ${CFLAGS}) # Seperate compiler arguments with comma and enclose in ' string(REGEX REPLACE " *\\\]" "']" CFLAGS ${CFLAGS}) # Add trailing ' at end string(REGEX REPLACE "\\\['," "[" CFLAGS ${CFLAGS}) # Remove prepended ', introduced in #1 string(REGEX REPLACE "\\\['\\\]" "[]" CFLAGS ${CFLAGS}) # Remove trailing ' introduced in #2 if no elements set(CXXFLAGS "-Dcpp_args=[${MESON_COMMON_CXXFLAGS} ${MESON_DEBUG_CXXFLAGS}]") string(REGEX REPLACE " +(/|-)" "','\\1" CXXFLAGS ${CXXFLAGS}) string(REGEX REPLACE " *\\\]" "']" CXXFLAGS ${CXXFLAGS}) string(REGEX REPLACE "\\\['," "[" CXXFLAGS ${CXXFLAGS}) string(REGEX REPLACE "\\\['\\\]" "[]" CXXFLAGS ${CXXFLAGS}) set(LDFLAGS "[${MESON_COMMON_LDFLAGS} ${MESON_DEBUG_LDFLAGS}]") string(REGEX REPLACE " +(/|-)" "','\\1" LDFLAGS ${LDFLAGS}) string(REGEX REPLACE " *\\\]" "']" LDFLAGS ${LDFLAGS}) string(REGEX REPLACE "\\\['," "[" LDFLAGS ${LDFLAGS}) string(REGEX REPLACE "\\\['\\\]" "[]" LDFLAGS ${LDFLAGS}) set(CLDFLAGS "-Dc_link_args=${LDFLAGS}") set(CXXLDFLAGS "-Dcpp_link_args=${LDFLAGS}") vcpkg_execute_required_process( COMMAND ${MESON} ${_vcm_OPTIONS} ${_vcm_OPTIONS_DEBUG} ${_vcm_SOURCE_PATH} ${CFLAGS} ${CXXFLAGS} ${CLDFLAGS} ${CXXLDFLAGS} WORKING_DIRECTORY ${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg LOGNAME config-${TARGET_TRIPLET}-dbg ) #Copy meson log files into buildtree for CI if(EXISTS "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg/meson-logs/meson-log.txt") file(COPY "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg/meson-logs/meson-log.txt" DESTINATION "${CURRENT_BUILDTREES_DIR}") file(RENAME "${CURRENT_BUILDTREES_DIR}/meson-log.txt" "${CURRENT_BUILDTREES_DIR}/meson-log-dbg.txt") endif() if(EXISTS "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg/meson-logs/install-log.txt") file(COPY "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg/meson-logs/install-log.txt" DESTINATION "${CURRENT_BUILDTREES_DIR}") file(RENAME "${CURRENT_BUILDTREES_DIR}/install-log.txt" "${CURRENT_BUILDTREES_DIR}/install-log-dbg.txt") endif() message(STATUS "Configuring ${TARGET_TRIPLET}-dbg done") #Restore PKG_CONFIG_PATH if(BACKUP_ENV_PKG_CONFIG_PATH_DEBUG) set(ENV{PKG_CONFIG_PATH} "${BACKUP_ENV_PKG_CONFIG_PATH_DEBUG}") unset(BACKUP_ENV_PKG_CONFIG_PATH_DEBUG) else() unset(ENV{PKG_CONFIG_PATH}) endif() endif() # configure release if(NOT DEFINED VCPKG_BUILD_TYPE OR VCPKG_BUILD_TYPE STREQUAL "release") message(STATUS "Configuring ${TARGET_TRIPLET}-rel") file(MAKE_DIRECTORY ${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel) #setting up PKGCONFIG if(NOT PKGCONFIG MATCHES "--define-variable=prefix") set(PKGCONFIG_PREFIX "${CURRENT_INSTALLED_DIR}") set(ENV{PKG_CONFIG} "${PKGCONFIG} --define-variable=prefix=${PKGCONFIG_PREFIX}") endif() set(PKGCONFIG_INSTALLED_DIR "${CURRENT_INSTALLED_DIR}/lib/pkgconfig/") if(ENV{PKG_CONFIG_PATH}) set(BACKUP_ENV_PKG_CONFIG_PATH_RELEASE $ENV{PKG_CONFIG_PATH}) set(ENV{PKG_CONFIG_PATH} "${PKGCONFIG_INSTALLED_DIR}${VCPKG_HOST_PATH_SEPARATOR}${PKGCONFIG_SHARE_DIR}${VCPKG_HOST_PATH_SEPARATOR}$ENV{PKG_CONFIG_PATH}") else() set(ENV{PKG_CONFIG_PATH} "${PKGCONFIG_INSTALLED_DIR}${VCPKG_HOST_PATH_SEPARATOR}${PKGCONFIG_SHARE_DIR}") endif() # Normalize flags for meson (i.e. " /string /with /flags " -> ['/string', '/with', '/flags']) set(CFLAGS "-Dc_args=[${MESON_COMMON_CFLAGS} ${MESON_RELEASE_CFLAGS}]") string(REGEX REPLACE " +(/|-)" "','\\1" CFLAGS ${CFLAGS}) # Seperate compiler arguments with comma and enclose in ' string(REGEX REPLACE " *\\\]" "']" CFLAGS ${CFLAGS}) # Add trailing ' at end string(REGEX REPLACE "\\\['," "[" CFLAGS ${CFLAGS}) # Remove prepended ', introduced in #1 string(REGEX REPLACE "\\\['\\\]" "[]" CFLAGS ${CFLAGS}) # Remove trailing ' introduced in #2 if no elements set(CXXFLAGS "-Dcpp_args=[${MESON_COMMON_CXXFLAGS} ${MESON_RELEASE_CXXFLAGS}]") string(REGEX REPLACE " +(/|-)" "','\\1" CXXFLAGS ${CXXFLAGS}) string(REGEX REPLACE " *\\\]" "']" CXXFLAGS ${CXXFLAGS}) string(REGEX REPLACE "\\\['," "[" CXXFLAGS ${CXXFLAGS}) string(REGEX REPLACE "\\\['\\\]" "[]" CXXFLAGS ${CXXFLAGS}) set(LDFLAGS "[${MESON_COMMON_LDFLAGS} ${MESON_RELEASE_LDFLAGS}]") string(REGEX REPLACE " +(/|-)" "','\\1" LDFLAGS ${LDFLAGS}) string(REGEX REPLACE " *\\\]" "']" LDFLAGS ${LDFLAGS}) string(REGEX REPLACE "\\\['," "[" LDFLAGS ${LDFLAGS}) string(REGEX REPLACE "\\\['\\\]" "[]" LDFLAGS ${LDFLAGS}) set(CLDFLAGS "-Dc_link_args=${LDFLAGS}") set(CXXLDFLAGS "-Dcpp_link_args=${LDFLAGS}") vcpkg_execute_required_process( COMMAND ${MESON} ${_vcm_OPTIONS} ${_vcm_OPTIONS_RELEASE} ${_vcm_SOURCE_PATH} ${CFLAGS} ${CXXFLAGS} ${CLDFLAGS} ${CXXLDFLAGS} WORKING_DIRECTORY ${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel LOGNAME config-${TARGET_TRIPLET}-rel ) #Copy meson log files into buildtree for CI if(EXISTS "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel/meson-logs/meson-log.txt") file(COPY "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel/meson-logs/meson-log.txt" DESTINATION "${CURRENT_BUILDTREES_DIR}") file(RENAME "${CURRENT_BUILDTREES_DIR}/meson-log.txt" "${CURRENT_BUILDTREES_DIR}/meson-log-rel.txt") endif() if(EXISTS "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel/meson-logs/install-log.txt") file(COPY "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel/meson-logs/install-log.txt" DESTINATION "${CURRENT_BUILDTREES_DIR}") file(RENAME "${CURRENT_BUILDTREES_DIR}/install-log.txt" "${CURRENT_BUILDTREES_DIR}/install-log-rel.txt") endif() message(STATUS "Configuring ${TARGET_TRIPLET}-rel done") #Restore PKG_CONFIG_PATH if(BACKUP_ENV_PKG_CONFIG_PATH_RELEASE) set(ENV{PKG_CONFIG_PATH} "${BACKUP_ENV_PKG_CONFIG_PATH_RELEASE}") unset(BACKUP_ENV_PKG_CONFIG_PATH_RELEASE) else() unset(ENV{PKG_CONFIG_PATH}) endif() endif() endfunction()
high
0.643468
99,903
require ['core/event-emitter','core/colour-literals','core/livecodelab-core'], (EventEmitter, ColourLiterals, LiveCodeLabCore) -> describe "ImageTest", -> beforeEach -> @addMatchers imagediff.jasmine it "A simple ball", -> a = new Image() b = new Image() Bowser = createBowser() if Bowser.firefox b.src = "test-page-files/images/ballCanvasFirefox.png" else if Bowser.safari b.src = "test-page-files/images/ballCanvasSafari.png" else if Bowser.chrome b.src = "test-page-files/images/ballCanvasChrome.png" console.log b.src testCanvas = document.createElement("canvas") testCanvas.width = 300 testCanvas.height = 300 eventRouter = new EventEmitter() colourNames = new ColourLiterals() liveCodeLabCoreInstance = new LiveCodeLabCore( blendedThreeJsSceneCanvas: testCanvas canvasForBackground: null forceCanvasRenderer: true eventRouter: eventRouter statsWidget: null testMode: true ) waits 10 runs -> liveCodeLabCoreInstance.updateCode "ball" liveCodeLabCoreInstance.startAnimationLoop() waits 1500 runs -> a = liveCodeLabCoreInstance.getForeground3DSceneImage("#FFFFFF") waits 200 runs -> expect(a).toImageDiffEqual b, 0 it "A simple box", -> a = new Image() b = new Image() Bowser = createBowser() if Bowser.firefox b.src = "test-page-files/images/ballCanvasFirefox.png" else if Bowser.safari b.src = "test-page-files/images/ballCanvasSafari.png" else if Bowser.chrome b.src = "test-page-files/images/ballCanvasChrome.png" console.log b.src testCanvas = document.createElement("canvas") testCanvas.width = 300 testCanvas.height = 300 eventRouter = new EventEmitter() colourNames = new ColourLiterals() liveCodeLabCoreInstance = new LiveCodeLabCore( blendedThreeJsSceneCanvas: testCanvas canvasForBackground: null forceCanvasRenderer: true eventRouter: eventRouter statsWidget: null testMode: true ) waits 10 runs -> liveCodeLabCoreInstance.updateCode "box ball rect line peg" liveCodeLabCoreInstance.startAnimationLoop() waits 1500 runs -> a = liveCodeLabCoreInstance.getForeground3DSceneImage("#FFFFFF") waits 200 runs -> expect(a).toImageDiffEqual b, 0
low
0.272837
99,904
proc import datafile="C:\Users\lanxin\Documents\GitHub\Chronic_Kidney_Disease\HW5\CKDCC.csv" out=CKDCC dbms=csv replace; getnames=yes; run; proc glm data=CKDCC; class sg rbc; model bgr sc=sg rbc sg*rbc / solution; manova h=sg rbc sg*rbc; run; proc glm data=CKDCC; class sg rbc; model bgr sc hemo=sg rbc sg*rbc / solution; manova h=sg rbc sg*rbc; run; data CKDCC; set CKDCC; trtcombine=trim(trim(sg) || trim(rbc)); run; proc sort data=CKDCC; by trtcombine; ods rtf file="C:\Users\lanxin\Documents\GitHub\Chronic_Kidney_Disease\HW5\contrast.rtf"; proc glm data=CKDCC; class trtcombine; model bgr sc=trtcombine; *contrast 'Red blood cell: abnormal vs normal' trtcombine 1 -1 1 -1 1 -1 1 -1 0; *contrast 'Specific Gravity: 1.005 vs 1.010' trtcombine 1 1 -1 -1 0 0 0 0 0; *contrast 'Specific Gravity: 1.005 vs 1.015' trtcombine 1 1 0 0 -1 -1 0 0 0; *contrast 'Specific Gravity: 1.005 vs 1.020' trtcombine 1 1 0 0 0 0 -1 -1 0; *contrast 'Specific Gravity: 1.005 vs 1.025' trtcombine 1 1 0 0 0 0 0 0 -2; *contrast 'Specific Gravity: 1.010 vs 1.015' trtcombine 0 0 1 1 -1 -1 0 0 0; *contrast 'Specific Gravity: 1.010 vs 1.020' trtcombine 0 0 1 1 0 0 -1 -1 0; *contrast 'Specific Gravity: 1.010 vs 1.025' trtcombine 0 0 1 1 0 0 0 0 -2; *contrast 'Specific Gravity: 1.015 vs 1.020' trtcombine 0 0 0 0 1 1 -1 -1 0; *contrast 'Specific Gravity: 1.015 vs 1.025' trtcombine 0 0 0 0 1 1 0 0 -2; *contrast 'Specific Gravity: 1.020 vs 1.025' trtcombine 0 0 0 0 0 0 1 1 -2; contrast 'Specific Gravity linear effect' trtcombine 1 1 0.5 0.5 0 0 -0.5 -0.5 -2; contrast 'Specific Gravity: 1.010 vs the other ' trtcombine -1 -1 3.5 3.5 -1 -1 -1 -1 -1; *manova h=trtcombine; run; ods rtf close;
low
0.795014
99,905
# # Copyright 03/05/04 Sun Microsystems, Inc. All Rights Reserved. # # libmcr -- libm correctly rounded # # Correctly Rounded elementary functions(wrap up routines) # double __libmcr_exp(double x) # double __libmcr_log(double x) # double __libmcr_pow(double x) # double __libmcr_atan(double x) # double __libmcr_sin(double x) # double __libmcr_cos(double x) # double __libmcr_tan(double x) # # Elementary functions with correction term(~20 bit extra precision) # double __libmcr_mx_exp(double x, double *err) # double __libmcr_mx_log(double x, double *err) # double __libmcr_mx_pow(double x, double y, double *err) # double __libmcr_mx_atan(double x, double *err) # double __libmcr_mx_sin(double x, double *err) # double __libmcr_mx_cos(double x, double *err) # double __libmcr_mx_tan(double x, double *err) # # Auxilary and kernel functions # double __libmcr_k_mx_exp(double x, double *err, int *expn) # double __libmcr_k_mx_pow(double *x, double *y, double *err, int *expn) # double __libmcr_k_mx_tan(double x, double t, double *err) # double __libmcr_k_mx_cos(double x, double t, double *err) # double __libmcr_k_mx_sin(double x, double t, double *err) # int __libmcr_k_mx_rem_pio2(double x, double *y) # int __libmcr_mx_check(int hz, int lz, int hr, int rnd) # void __libmcr_mx_poly(double *z, double *a, double *e, int n) # # Multi-precision kernel functions with test flag # double __libmcr_mi_atan(double, int, int *, int); # double __libmcr_mi_exp(double, int, int *, int); # double __libmcr_mi_log(double, int, int *, int); # double __libmcr_mi_pow(double, double, int, int *, int); # double __libmcr_mi_sin(double, int, int *, int); # double __libmcr_mi_cos(double, int, int *, int); # double __libmcr_mi_tan(double, int, int *, int); # # void __libmcr_mm_sub(int *, int *, int *, int); # void __libmcr_mm_add(int *, int *, int *, int); # void __libmcr_mm_div(int *, int *, int *, int); # void __libmcr_mm_divi(int *, int, int *, int); # void __libmcr_mm_mul(int *, int *, int *, int); # void __libmcr_mm_muli(int *, int, int *, int); # void __libmcr_mm_scalbn(int *, int, int); # void __libmcr_mm_sqrt(int *, int *, int); # void __libmcr_mm_atan(int *, int *, int); # Auxilary and kernel functions # void __libmcr_mi_dtomi(double, int *, int); # void __libmcr_mi_itomi(int, int *, int); # void __libmcr_mi_format(int *, int); # double __libmcr_mi_mitod(int *, int, int *); # double __libmcr_mi_final(int *, int, int *, int); # int __libmcr_mi_ilogb(int *); # void __libmcr_mm_pio2(int *, int); # void __libmcr_mm_pio4(int *, int); # void __libmcr_mm_ln2(int *, int); # void __libmcr_k_mm_exp(int *, int *, int); # void __libmcr_k_mm_sin(int *, int *, int); # void __libmcr_k_mm_cos(int *, int *, int); # int __libmcr_k_mi_rem_pio2(double, int *, int); # int __libmcr_k_rem_pio2m(double *, double *, int, int, int); # void __libmcr_k_mi_log(double, int *, int); # double __libmcr_k_exactsqrt(double, int *); # # Data # const int __libmcr_TBL_atan_hi[]; # const int __libmcr_TBL_atan_lo[]; # const int __libmcr_TBL_pio2[]; # const int __libmcr_TBL_pio4[]; # const int __libmcr_TBL_ipio2[]; # CC = cc CFLAGS = INCDIR = ../include HSRC = ${INCDIR}/libmcr.h ${INCDIR}/mcr.h LIBDIR = ../lib LIB = ${LIBDIR}/libmcr.a COMPLINEOPTS = -I${INCDIR} ${OPT} ${CFLAGS} OBJS = \ __libmcr_exp.o \ __libmcr_log.o \ __libmcr_pow.o \ __libmcr_atan.o \ __libmcr_sin.o \ __libmcr_cos.o \ __libmcr_tan.o \ __libmcr_mx_exp.o \ __libmcr_mx_log.o \ __libmcr_mx_pow.o \ __libmcr_mx_atan.o \ __libmcr_mx_sin.o \ __libmcr_mx_cos.o \ __libmcr_mx_tan.o \ __libmcr_k_mx_exp.o \ __libmcr_k_mx_pow.o \ __libmcr_k_mx_tan.o \ __libmcr_k_mx_cos.o \ __libmcr_k_mx_sin.o \ __libmcr_k_mx_rem_pio2.o \ __libmcr_k_exactsqrt.o \ __libmcr_mx_check.o \ __libmcr_mx_poly.o \ __libmcr_mi_atan.o \ __libmcr_mi_exp.o \ __libmcr_mi_log.o \ __libmcr_mi_pow.o \ __libmcr_mi_sin.o \ __libmcr_mi_cos.o \ __libmcr_mi_tan.o \ __libmcr_mm_sub.o \ __libmcr_mm_add.o \ __libmcr_mm_div.o \ __libmcr_mm_divi.o \ __libmcr_mm_mul.o \ __libmcr_mm_muli.o \ __libmcr_mm_scalbn.o \ __libmcr_mm_sqrt.o \ __libmcr_mm_atan.o \ __libmcr_mi_dtomi.o \ __libmcr_mi_itomi.o \ __libmcr_mi_format.o \ __libmcr_mi_mitod.o \ __libmcr_mi_final.o \ __libmcr_mi_ilogb.o \ __libmcr_mm_pio2.o \ __libmcr_mm_ln2.o \ __libmcr_k_mm_exp.o \ __libmcr_k_mm_sin.o \ __libmcr_k_mm_cos.o \ __libmcr_k_mi_rem_pio2.o \ __libmcr_k_rem_pio2m.o \ __libmcr_k_mi_log.o \ __libmcr_TBL_atan.o \ __libmcr_TBL_pio2.o all: $(LIB) $(LIB): $(HSRC) $(OBJS) ar cru $(LIB) $(OBJS) $(OBJS): Makefile .c.o: $*.c $(CC) ${COMPLINEOPTS} -c -o $*.o $*.c clean: /bin/rm -f $(OBJS) clobber: clean rm -f ${LIB}
high
0.532436
99,906
;; Compiled from #P"/home/frank/quicklisp/local-projects/climbe/schema/CIM2.42.0/CIM_PolicyGroupInPolicyGroup.xml" (in-package #:climbe) (DEFCIM-CLASS CIM_POLICYGROUPINPOLICYGROUP (CIM_POLICYCOMPONENT) ((GROUPCOMPONENT NIL :CIM-NAME "GroupComponent" :QUALIFIERS ((:DEPRECATED ("CIM_PolicySetComponent.GroupComponent")) :AGGREGATE (:OVERRIDE "GroupComponent") (:DESCRIPTION "A PolicyGroup that aggregates other Groups.") :KEY) :INITFORM "CIM_PolicyGroup") (PARTCOMPONENT NIL :CIM-NAME "PartComponent" :QUALIFIERS ((:DEPRECATED ("CIM_PolicySetComponent.PartComponent")) (:OVERRIDE "PartComponent") (:DESCRIPTION "A PolicyGroup aggregated by another Group.") :KEY) :INITFORM "CIM_PolicyGroup")) (:CIM-NAME "CIM_PolicyGroupInPolicyGroup") (:QUALIFIERS :ASSOCIATION (:DEPRECATED ("CIM_PolicySetComponent")) (NIL "true") (:VERSION "2.7.0") (:UML-PACKAGE-PATH "CIM::Policy") (:DESCRIPTION "PolicySetComponent provides a more general mechanism for aggregating both PolicyGroups and PolicyRules and doing so with the priority value applying only to the aggregated set rather than policy wide. A relationship that aggregates one or more lower-level PolicyGroups into a higher-level Group. A Policy Group may aggregate PolicyRules and/or other Policy Groups.")))
high
0.81083
99,907
defmodule OpenTelemetry.Tracer do @moduledoc """ This module contains macros for Tracer operations around the lifecycle of the Spans within a Trace. The Tracer is able to start a new Span as a child of the active Span of the current process, set a different Span to be the current Span by passing the Span's context, end a Span or run a code block within the context of a newly started span that is ended when the code block completes. The macros use the Tracer registered to the Application the module using the macro is included in, assuming `OpenTelemetry.register_application_tracer/1` has been called for the Application. If not then the default Tracer is used. require OpenTelemetry.Tracer OpenTelemetry.Tracer.with_span \"span-1\" do ... do something ... end """ @type start_opts() :: %{optional(:parent) => OpenTelemetry.span() | OpenTelemetry.span_ctx(), optional(:attributes) => OpenTelemetry.attributes(), optional(:sampler) => :ot_sampler.sampler(), optional(:links) => OpenTelemetry.links(), optional(:is_recording) => boolean(), optional(:start_time) => :opentelemetry.timestamp(), optional(:kind) => OpenTelemetry.span_kind()} @doc """ Starts a new span and makes it the current active span of the current process. The current active Span is used as the parent of the created Span unless a `parent` is given in the `t:start_opts/0` argument or there is no active Span. If there is neither a current Span or a `parent` option given then the Tracer checks for an extracted SpanContext to use as the parent. If there is also no extracted context then the created Span is a root Span. """ defmacro start_span(name, opts \\ quote(do: %{})) do quote bind_quoted: [name: name, start_opts: opts] do :ot_tracer.start_span(:opentelemetry.get_tracer(__MODULE__), name, start_opts) end end @doc """ Starts a new span but does not make it the current active span of the current process. This is particularly useful when creating a child Span that is for a new process. Before spawning the new process start an inactive Span, which uses the current context as the parent, then pass this new SpanContext as an argument to the spawned function and in that function use `set_span/1`. The current active Span is used as the parent of the created Span unless a `parent` is given in the `t:start_opts/0` argument or there is no active Span. If there is neither a current Span or a `parent` option given then the Tracer checks for an extracted SpanContext to use as the parent. If there is also no extracted context then the created Span is a root Span. """ defmacro start_inactive_span(name, opts \\ quote(do: %{})) do quote bind_quoted: [name: name, start_opts: opts] do :ot_tracer.start_inactive_span(:opentelemetry.get_tracer(__MODULE__), name, start_opts) end end @doc """ Takes a `t:OpenTelemetry.span_ctx/0` and the Tracer sets it to the currently active Span. """ defmacro set_span(span_ctx) do quote bind_quoted: [span_ctx: span_ctx] do :ot_tracer.set_span(:opentelemetry.get_tracer(__MODULE__), span_ctx) end end @doc """ End the Span. Sets the end timestamp for the currently active Span. This has no effect on any child Spans that may exist of this Span. The default Tracer in the OpenTelemetry Erlang/Elixir SDK will then set the parent, if there is a local parent of the current Span, to the current active Span. """ defmacro end_span() do quote do :ot_tracer.end_span(:opentelemetry.get_tracer(__MODULE__)) end end @doc """ Creates a new span which is ended automatically when the `block` completes. See `start_span/2` and `end_span/0`. """ defmacro with_span(name, start_opts \\ quote(do: %{}), do: block) do quote do :ot_tracer.with_span(:opentelemetry.get_tracer(__MODULE__), unquote(name), unquote(start_opts), fn _ -> unquote(block) end) end end @doc """ Returns the currently active `t:OpenTelemetry.tracer_ctx/0`. """ defmacro current_ctx() do quote do :ot_tracer.current_ctx(:opentelemetry.get_tracer(__MODULE__)) end end @doc """ Returns the currently active `t:OpenTelemetry.span_ctx/0`. """ defmacro current_span_ctx() do quote do :ot_tracer.current_span_ctx(:opentelemetry.get_tracer(__MODULE__)) end end end
high
0.770555
99,908
# This file must be used with "source bin/activate.csh" *from csh*. # You cannot run it directly. # Created by Davide Di Blasi <davidedb@gmail.com>. # Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com> alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate' # Unset irrelevant variables. deactivate nondestructive setenv VIRTUAL_ENV "/mnt/c/Users/vtabbott/Documents/_Projects/wgan/generative-models/.venv" set _OLD_VIRTUAL_PATH="$PATH" setenv PATH "$VIRTUAL_ENV/bin:$PATH" set _OLD_VIRTUAL_PROMPT="$prompt" if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then if (".venv" != "") then set env_name = ".venv" else if (`basename "VIRTUAL_ENV"` == "__") then # special case for Aspen magic directories # see https://aspen.io/ set env_name = `basename \`dirname "$VIRTUAL_ENV"\`` else set env_name = `basename "$VIRTUAL_ENV"` endif endif set prompt = "[$env_name] $prompt" unset env_name endif alias pydoc python -m pydoc rehash
low
1
99,909
> module Chapters.Ch24 where > import Euterpea Chapter 24 - Sound Effects
low
0.666609
99,910