text
stringlengths 184
4.48M
|
|---|
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{common/sidebar}"
>
<head>
<meta charset="utf-8">
<link th:href="@{/css/sb-admin-2.min.css}" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.10/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.10/dist/sweetalert2.min.js"></script>
<script th:inline="javascript">
$(document).ready(function(){
var errorMessage = [[${errorMessage}]];
if(errorMessage != null){
alert(errorMessage);
}
bindDomEvent();
});
function bindDomEvent() {
$(".memberImage").on("change", function() {
var fileName = $(this).val().split("\\").pop(); // 이미지 파일명
var fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); // 확장자 추출
if (fileExt != "jpg" && fileExt != "jpeg" && fileExt != "gif" && fileExt != "png" && fileExt != "bmp") {
Swal.fire({
icon: 'error',
title: 'ERROR',
text: '이미지 파일만 등록이 가능합니다.'
});
return;
}
$(this).siblings(".memberImage").html(fileName);
});
}
function readImage(input) {
if(input.files && input.files[0]) {
const reader = new FileReader()
reader.onload = e => {
const previewImage = document.getElementById("preview-image")
previewImage.src = e.target.result }
reader.readAsDataURL(input.files[0])
}
}
window.onload = function() {
const inputImage = document.getElementById("memberImage")
inputImage.addEventListener("change", e => {
readImage(e.target)
})
};
</script>
<script>
function sweetAlert(event) {
event.preventDefault(); // 폼 제출 기본 동작 중지
return new Promise((resolve) => {
Swal.fire({
title: '등록 하시겠습니까?',
icon: 'question',
showCancelButton: true,
confirmButtonColor: '#73685d',
cancelButtonColor: '#6e7881',
confirmButtonText: 'OK',
cancelButtonText: 'Cancel'
}).then((result) => {
if (result.isConfirmed) {
// MyDTO 객체 생성
const myDTO = {
password: document.getElementById('password').value,
name: document.getElementById('name').value,
birth: document.getElementById('birth').value,
email: document.getElementById('email').value,
phone: document.getElementById('phone').value,
address: document.getElementById('address').value,
date: document.getElementById('date').value,
department: document.getElementById('department').value,
position: document.getElementById('position').value,
hobong: document.getElementById('hobong').value,
bank: document.getElementById('bank').value,
status: document.getElementById('status').value,
role: document.getElementById('role').value,
memberImage: document.getElementById('memberImage').value
};
// 유효성 검사
const errors = validateMyDTO(myDTO);
if (errors.length > 0) {
// 오류 메시지 출력
Swal.fire({
title: 'Error',
icon: 'error',
html: errors[0],
confirmButtonColor: '#73685d'
});
} else {
Swal.fire({
title: 'Completed!',
icon: 'success',
confirmButtonColor: '#73685d'
}).then(() => {
// 폼을 수동으로 제출
event.target.form.submit();
});
}
}
});
});
}
// MyDTO 객체의 유효성 검사 함수
function validateMyDTO(myDTO) {
const errors = [];
// 각 필드에 대한 유효성 검사
if (!myDTO.memberImage) {
errors.push('이미지를 등록 해 주세요.');
}
if (!myDTO.department) {
errors.push('부서를 선택 해 주세요.');
}
if (!myDTO.position) {
errors.push('직위를 선택 해 주세요.');
}
if (!myDTO.hobong) {
errors.push('직급을 선택 해 주세요.');
}
if (!myDTO.role) {
errors.push('구분은 필수 입력 값입니다.');
}
if (!myDTO.status) {
errors.push('재직현황을 선택 해 주세요.');
}
if (!myDTO.name) {
errors.push('이름은 필수 입력 값입니다.');
}
if (!myDTO.password) {
errors.push('비밀번호는 8~16자 영문 대 소문자, 숫자, 특수문자를 사용해야 합니다.');
} else if (!myDTO.password.match(/^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*\W)(?=\S+$).{8,16}$/)) {
errors.push('비밀번호는 8~16자 영문 대 소문자, 숫자, 특수문자를 사용해야 합니다.');
}
if (!myDTO.birth) {
errors.push('생년월일은 필수 입력 값입니다.');
} else if (!myDTO.birth.match(/^\d{8}$/)) {
errors.push('생년월일을 알맞게 입력해 주세요.');
}
if (!myDTO.address) {
errors.push('주소는 필수 입력 값입니다.');
}
if (!myDTO.email) {
errors.push('이메일은 필수 입력 값입니다.');
} else if (!isValidEmail(myDTO.email)) {
errors.push('이메일 형식으로 입력해 주세요.');
}
if (!myDTO.phone) {
errors.push('핸드폰 번호는 필수 입력 값입니다.');
} else if (!myDTO.phone.match(/^010\d{8}$/)) {
errors.push('휴대폰 번호를 알맞게 입력해 주세요.');
}
if (!myDTO.bank) {
errors.push('계좌번호는 필수 입력 값입니다.');
}
if (!myDTO.date) {
errors.push('입사년월은 필수 입력 값입니다.');
}
return errors;
}
// 이메일 유효성 검사 함수
function isValidEmail(email) {
// 간단한 이메일 유효성 검사를 수행하는 정규식
const emailRegex = /^[^\s@]+@[^\s@]+.[^\s@]+$/;
return emailRegex.test(email);
}
</script>
<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>
function searchAddress() {
event.preventDefault(); // 폼 제출 기본 동작 중지
new daum.Postcode({
oncomplete: function(data) {
document.getElementById('address').value = data.address;
}
}).open({
popupTitle: '주소 검색',
popupKey: 'popup1',
autoClose: true
});
}
</script>
</head>
<div class="content" layout:fragment="content">
<body class="background-color-white">
<div class="container">
<div class="card o-hidden border-0 shadow-lg my-3">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-brown">Employee Registration</h6>
</div>
<div class="card-body p-50">
<form action="" role="form" method="post" th:object="${memberInsertDto}" enctype="multipart/form-data">
<div class="card shadow mb-4">
<div class="card-body3">
<div class="row gx-3 mb-3">
<div class="col-md-5" style="text-align: center; margin-top:40px; margin-bottom:-40px;">
<div class="image-container">
<label for="memberImage">
<img style="width: 250px;height: 280px;margin-top:-18px; border: 1px solid #d1d3e2;border-radius: 0.35rem;" id="preview-image"
src="https://dummyimage.com/500x500/ffffff/000000.png&text=preview+image">
<input style="display:block;" type="file" class="memberImage" id="memberImage" name="memberImage">
</label>
</div>
</div>
<div class="col-md-7">
<label class="small mb-1" th:for="name">Name</label>
<input type="text" class="form-control form-control-user" th:field="*{name}"
placeholder="이름">
<div class="tooltip">
<label class="small mb-1" th:for="password">Password</label>
<input type="password" class="form-control form-control-user" th:field="*{password}"
placeholder="패스워드">
<span class="tooltiptext tooltip-bottom">비밀번호는 8~16자 영문 대 소문자, 숫자, 특수문자를 사용해야 합니다.</span>
</div>
<div class="tooltip">
<label class="small mb-1" th:for="birth">Birth</label>
<input type="text" class="form-control form-control-user" th:field="*{birth}"
placeholder="생년월일">
<span class="tooltiptext tooltip-bottom">8자리 형식으로 입력해 주세요. (ex:19910101)</span>
</div>
<div class="tooltip">
<label class="small mb-1" th:for="phone">Phone number</label>
<input type="text" class="form-control form-control-user" th:field="*{phone}"
placeholder="핸드폰 번호">
<span class="tooltiptext tooltip-bottom">'-'은 제외하고 입력해 주세요. (ex:01012345678)</span>
</div>
<div class="tooltip">
<label class="small mb-1" th:for="email">Email</label>
<input type="text" class="form-control form-control-user" th:field="*{email}"
placeholder="이메일">
<span class="tooltiptext tooltip-bottom">이메일 형식으로 입력해 주세요. (ex:abcd@gmail.com)</span>
</div>
</div>
</div>
<div class="row gx-3 mb-3">
<div class="col-md-6">
<label class="small mb-1" th:for="address">address</label>
<div style="display: flex;">
<input type="text" class="form-control form-control-user" id="address" name="address" th:field="*{address}" placeholder="주소" style="flex: 1;">
<button onclick="searchAddress()" id="addressSearch" style="margin-right: 20px;">주소 찾기</button>
</div>
</div>
<div class="col-md-6">
<label class="small mb-1" th:for="bank">Bank account</label>
<input type="text" class="form-control form-control-user" th:field="*{bank}"
placeholder="계좌번호">
</div>
</div>
<div class="row gx-3 mb-3">
<div class="col-md-4">
<label class="small mb-1" th:for="department">Department</label>
<select class="custom-select" name="department" th:field="*{department}">
<option value="" selected="selected">부서</option>
<option value="생산직">생산팀</option>
<option value="구매팀">구매팀</option>
<option value="물류팀">물류팀</option>
<option value="EA팀">EA팀</option>
<option value="재무팀">재무팀</option>
<option value="임원">임원</option>
</select>
</div>
<div class="col-md-4">
<label class="small mb-1" th:for="position">Spot</label>
<select class="custom-select" name="position" th:field="*{position}">
<option value="" selected="selected">직위</option>
<option value="사원">사원</option>
<option value="대리">대리</option>
<option value="과장">과장</option>
<option value="차장">차장</option>
<option value="부장" >부장</option>
<option value="이사">이사</option>
<option value="부사장">부사장</option>
<option value="사장">사장</option>
</select>
</div>
<div class="col-md-4">
<label class="small mb-1" th:for="hobong">Rank</label>
<select class="custom-select" name="hobong" th:field="*{hobong}">
<option value="" selected="selected">직급</option>
<option value="1호봉">1호봉</option>
<option value="2호봉">2호봉</option>
<option value="3호봉">3호봉</option>
<option value="4호봉">4호봉</option>
<option value="5호봉">5호봉</option>
</select>
</div>
</div>
<div class="row gx-3 mb-3">
<div class="col-md-4">
<div class="tooltip">
<label class="small mb-1" th:for="date">Joining date</label>
<input type="date" class="form-control form-control-user" id="date" name="date" th:field="*{date}">
<span class="tooltiptext tooltip-bottom">입사날짜를 선택해 주세요.</span>
</div>
</div>
<div class="col-md-4">
<label class="small mb-1" th:for="status">Employment status</label>
<select class="custom-select" name="status" th:field="*{status}">
<option value="" selected="selected">재직현황</option>
<option value="WORKING">재직</option>
<option value="LEAVE">퇴사</option>
</select>
</div>
<div class="col-md-4">
<label class="small mb-1" th:for="role">Role</label>
<select class="custom-select" name="role" th:field="*{role}">
<option value="" selected="selected">구분</option>
<option value="USER">사용자</option>
<option value="ADMIN">관리자</option>
</select>
</div>
</div>
<!-- Save changes button-->
<div class="button-container">
<button type="submit" style="width:150px;" class="btn btn-background-brown btn-user btn-block" onclick="return sweetAlert(event);">
Confirm
</button>
</div>
<!-- 보안 관련 인증 토큰을 히든 파라미터로 보내줍니다-->
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
</div>
</div>
</form>
</div>
</div>
</div>
<script th:utext="${sweetAlertScript}"></script>
</body>
</div>
</html>
|
import { styled } from "@mui/system";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useTheme } from '@mui/material/styles';
const SearchInputEl = styled("div")<{isMobile?:boolean,isTablet?:boolean}>(({isMobile,isTablet})=>`
display:flex;
flex-direction:column;
padding:10px;
justify-content:center;
border-right: ${(isMobile || isTablet)?"0rem":'0.05rem solid #cecece' } ;;
`)
const LabelEl = styled("label")(()=>`
color:#898989;
font-size:0.85rem;
`)
const InputEl = styled("input")(()=>`
color:#565656;
margin-top:0.5rem;
border:0.05rem solid #cecece;
border-radius:0.15rem;
padding:0.1rem 0.5rem;
height:40px;
`)
const SearchInput = (props:{label:string,holder:string,name:string})=>{
const {label, holder,name} = props;
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
const isTablet = useMediaQuery(theme.breakpoints.down('md'));
const isLaptop = useMediaQuery(theme.breakpoints.down('lg'));
const isDesktop = useMediaQuery(theme.breakpoints.down('xl'));
return(<SearchInputEl isMobile={isMobile} isTablet={isTablet}>
<LabelEl>{label}</LabelEl>
<InputEl type="text" name={name} placeholder={holder} />
</SearchInputEl>);
}
export default SearchInput ;
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./NFTCollection.sol";
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function withdraw(uint) external;
}
interface INFTCollection {
function MintNFT(string memory _tokenURI, address _to) external returns(uint256);
}
interface IRegistration {
function isRegistered(address _user) external view returns(bool);
function getReferrerAddresses(address _userAddress) external view returns(address[] memory referrerAddresses);
}
contract CentherMarketplace is OwnableUpgradeable, ReentrancyGuardUpgradeable {
struct SaleInfo {
address seller;
uint256 price;
}
struct BidItemInfo {
uint256 bidPrice;
address bidAddress;
}
struct BidInfo {
BidItemInfo[] bids;
uint256 highestBidPrice;
}
struct CollectionInfo {
address creatorAddress;
}
uint8 constant referralDeep = 6;
struct DistributionFee {
uint32 marketplaceFee; //1.5%
uint32 creatorFee; //1.5%
uint32[referralDeep] referralFee; //0.7, 1.4, 2.1, 1.4, 0.7, 0.7%
uint32 sellerPercentage; //90%
}
enum AuctionState {
NONE,
OPEN,
CANCELED,
ENDED
}
struct AuctionInfo {
AuctionState state;
uint256 endAt;
uint256 startPrice;
uint256 highestBidPrice;
address highestBidAddress;
address seller;
}
mapping (address => mapping (uint256 => SaleInfo)) public _nftInfoForSale;
mapping (address => mapping (uint256 => BidInfo)) public _bidInfo;
mapping (address => mapping (uint256 => AuctionInfo)) public _nftInfoForAuction;
mapping (address => CollectionInfo) public _addedCollections;
DistributionFee public distributionFee;
uint256 public createItemFeeForTeam;
uint256 public createItemFeeForCreator;
uint256 public createCollectionFee;
uint32 private denominator;
IWETH public _WETH;
IRegistration public register;
address[] public _allCollections;
event NewItemListed(address indexed _collection, uint256 indexed _tokenID, uint256 _price, address _seller);
event EditItemPrice(address indexed _collection, uint256 indexed _tokenID, uint256 _newPrice, address _seller);
event CancelItemPrice(address indexed _collection, uint256 indexed _tokenID, address _seller);
event BuyItem(address indexed _collection, uint256 indexed _tokenID, uint256 _price, address _seller, address _buyer);
event CreateItem(address indexed _collection, uint256 indexed _tokenID, string _tokenURI, bool _isAuction, uint256 _price, uint256 _endAt, address _creator);
event BidOnNonAuctionItem(address indexed _collection, uint256 indexed _tokenID, uint256 _newPrice, address _newBidder);
event AcceptBid(address indexed _collection, uint256 indexed _tokenID, uint256 _price, address _seller, address _buyer);
event CreateCollection(address indexed _collection, string _collectionName, string _collectionSymbol, string _category, uint256 _maxSupply, string _uri, address _creator);
event CreateAuction(address indexed _collection, uint256 indexed _tokenID, uint256 _startPrice, uint256 _endAt, address _creator);
event BidOnAuction(address indexed _collection, uint256 indexed _tokenID, uint256 _newPrice, address _newBidder);
event EndAuction(address indexed _collection, uint256 indexed _tokenID, uint256 _lastPrice, address _seller, address _lastBidder);
event CancelAuction(address indexed _collection, uint256 indexed _tokenID, address _seller);
event ChangeCreateFee(uint256 _createItemFeeForTeam, uint256 _createItemFeeForCreator, uint256 _createCollectionFee);
event ChangeDistributionFee(uint32 _marketplaceFee, uint32 _creatorFee, uint32 _level1Fee, uint32 _level2Fee,
uint32 _level3Fee, uint32 _level4Fee, uint32 _level5Fee, uint32 _level6Fee, uint32 _sellerPercentage);
modifier onlyRegisterUser {
require(register.isRegistered(msg.sender), "No registered.");
_;
}
function initialize(address _register, address _weth) public initializer {
__Ownable_init();
__ReentrancyGuard_init();
denominator = 1000;
register = IRegistration(_register);
_WETH = IWETH(_weth);
changeDistributionFee(15, 15, 7, 14, 21, 14, 7, 7);
changeCreateFee(.0072 ether, 0 ether, .0026 ether);
}
function changeCreateFee(uint256 _createItemFeeForTeam, uint256 _createItemFeeForCreator, uint256 _createCollectionFee) public onlyOwner() {
createItemFeeForTeam = _createItemFeeForTeam;
createItemFeeForCreator = _createItemFeeForCreator;
createCollectionFee = _createCollectionFee;
emit ChangeCreateFee(createItemFeeForTeam, createItemFeeForCreator, createCollectionFee);
}
function changeDistributionFee(
uint32 _marketplaceFee,
uint32 _creatorFee,
uint32 _level1Fee,
uint32 _level2Fee,
uint32 _level3Fee,
uint32 _level4Fee,
uint32 _level5Fee,
uint32 _level6Fee
) public onlyOwner()
{
distributionFee.marketplaceFee = _marketplaceFee;
distributionFee.creatorFee = _creatorFee;
distributionFee.referralFee[0] = _level1Fee;
distributionFee.referralFee[1] = _level2Fee;
distributionFee.referralFee[2] = _level3Fee;
distributionFee.referralFee[3] = _level4Fee;
distributionFee.referralFee[4] = _level5Fee;
distributionFee.referralFee[5] = _level6Fee;
distributionFee.sellerPercentage =
denominator - distributionFee.marketplaceFee - distributionFee.creatorFee -
distributionFee.referralFee[0] - distributionFee.referralFee[1] - distributionFee.referralFee[2] -
distributionFee.referralFee[3] - distributionFee.referralFee[4] - distributionFee.referralFee[5];
emit ChangeDistributionFee(_marketplaceFee, _creatorFee, _level1Fee, _level2Fee, _level3Fee,
_level4Fee, _level5Fee, _level6Fee, distributionFee.sellerPercentage);
}
function createCollection(string memory name, string memory symbol, string memory category, string memory uri, uint256 maxSupply) public payable onlyRegisterUser returns(address) {
require(msg.value == createCollectionFee, "Insufficient_Funds");
require(maxSupply > 0, "MAX_SUPPLY must be greater than 0");
NFTCollection collection = new NFTCollection(name, symbol, maxSupply);
_addedCollections[address(collection)] = CollectionInfo({creatorAddress: msg.sender});
_allCollections.push(address(collection));
emit CreateCollection(address(collection), name, symbol, category, maxSupply, uri, msg.sender);
return address(collection);
}
function createItems(address collection, string memory tokenURI, uint32 supply, bool isAuction, uint256 price, uint256 period) public payable onlyRegisterUser {
require(msg.value == (createItemFeeForTeam + createItemFeeForCreator) * supply, "Insufficient Funds");
require(price > 0, "Incorrect Price");
require(supply > 0, "Incorrect Supply");
if(isAuction)
require(period > 0, "Incorrect Auction Period");
if(createItemFeeForCreator > 0)
payable(_addedCollections[collection].creatorAddress).transfer(createItemFeeForCreator * supply);
for(uint32 i = 0; i < supply; i++) {
uint256 tokenID = INFTCollection(collection).MintNFT(tokenURI, address(this));
if(isAuction) {
_nftInfoForAuction[collection][tokenID] = AuctionInfo({
state: AuctionState.OPEN,
endAt: block.timestamp + period,
startPrice: price,
highestBidPrice: price,
highestBidAddress: address(0x0),
seller: msg.sender
});
} else {
_nftInfoForSale[collection][tokenID] = SaleInfo({seller: msg.sender, price: price});
}
emit CreateItem(address(collection), tokenID, tokenURI, isAuction, price, block.timestamp + period, msg.sender);
}
}
function bidOnNonAuctionItem(address collection, uint256 tokenID, uint256 newPrice) public onlyRegisterUser {
require(_nftInfoForAuction[collection][tokenID].state != AuctionState.OPEN, "This is Auction Item");
BidInfo storage bidInfo = _bidInfo[collection][tokenID];
require(bidInfo.highestBidPrice < newPrice, "Incorrect Price");
bidInfo.highestBidPrice = newPrice;
bidInfo.bids.push(BidItemInfo({bidPrice: newPrice, bidAddress: msg.sender}));
emit BidOnNonAuctionItem(collection, tokenID, newPrice, msg.sender);
}
function acceptBid(address collection, uint256 tokenID, uint256 index) public onlyRegisterUser nonReentrant {
require(_nftInfoForAuction[collection][tokenID].state != AuctionState.OPEN, "This is Auction Item");
BidInfo storage bidInfo = _bidInfo[collection][tokenID];
bool isListed = IERC721(collection).ownerOf(tokenID) == address(this) && _nftInfoForSale[collection][tokenID].seller == msg.sender;
require(IERC721(collection).ownerOf(tokenID) == msg.sender || isListed, "Not your NFT");
BidItemInfo memory bid = bidInfo.bids[index];
_WETH.transferFrom(bid.bidAddress, address(this), bid.bidPrice);
if(isListed) {
IERC721(collection).transferFrom(address(this), bid.bidAddress, tokenID);
} else {
IERC721(collection).transferFrom(msg.sender, bid.bidAddress, tokenID);
}
_nftInfoForSale[collection][tokenID] = SaleInfo({seller: address(0), price: 0});
//Transfer money by distribution
_distributeFundsWETH(
msg.sender, bid.bidAddress,
_addedCollections[collection].creatorAddress, bid.bidPrice);
emit AcceptBid(collection, tokenID, bid.bidPrice, msg.sender, bid.bidAddress);
delete bidInfo.bids;
bidInfo.highestBidPrice = 0;
}
function listItemForSale(address collection, uint256 tokenID, uint256 price) public onlyRegisterUser {
require(_nftInfoForAuction[collection][tokenID].state != AuctionState.OPEN, "This is Auction Item");
require(IERC721(collection).ownerOf(tokenID) == msg.sender, "Not Your NFT");
require(IERC721(collection).isApprovedForAll(msg.sender, address(this)), "Not Approved");
require(price > 0, "Incorrect Price");
_nftInfoForSale[collection][tokenID] = SaleInfo({seller: msg.sender, price: price});
IERC721(collection).transferFrom(msg.sender, address(this), tokenID);
emit NewItemListed(collection, tokenID, price, msg.sender);
}
function editItemForSale(address collection, uint256 tokenID, uint256 newPrice) public onlyRegisterUser {
require(_nftInfoForAuction[collection][tokenID].state != AuctionState.OPEN, "This is Auction Item");
require(_nftInfoForSale[collection][tokenID].seller == msg.sender, "Not Your NFT");
require(IERC721(collection).ownerOf(tokenID) == address(this), "Not listed Item");
require(newPrice > 0, "Incorrect Price");
_nftInfoForSale[collection][tokenID] = SaleInfo({seller: msg.sender, price: newPrice});
emit EditItemPrice(collection, tokenID, newPrice, msg.sender);
}
function cancelItemForSale(address collection, uint256 tokenID) public onlyRegisterUser {
require(_nftInfoForAuction[collection][tokenID].state != AuctionState.OPEN, "This is Auction Item");
require(_nftInfoForSale[collection][tokenID].seller == msg.sender, "Not Your NFT");
_nftInfoForSale[collection][tokenID] = SaleInfo({seller: address(0), price: 0});
IERC721(collection).transferFrom(address(this), msg.sender, tokenID);
emit CancelItemPrice(collection, tokenID, msg.sender);
}
function buyForListedItem(address collection, uint256 tokenID) public payable onlyRegisterUser nonReentrant {
require(_nftInfoForAuction[collection][tokenID].state != AuctionState.OPEN, "This is Auction Item");
SaleInfo memory saleInfo = _nftInfoForSale[collection][tokenID];
// Verify that the item is for sale
require(saleInfo.seller != address(0x0) || saleInfo.price != 0, "This item is not for sale");
// Ensure buyer can't be seller
require(saleInfo.seller != msg.sender, "Sellers cannot buy from themselves");
// Ensure price
require(saleInfo.price == msg.value, "Insufficient price");
//Transfer NFT to buyer
IERC721(collection).transferFrom(address(this), msg.sender, tokenID);
_nftInfoForSale[collection][tokenID] = SaleInfo({seller: address(0), price: 0});
//Transfer money by distribution
_distributeFunds(saleInfo.seller, msg.sender, _addedCollections[collection].creatorAddress, msg.value);
emit BuyItem(collection, tokenID, saleInfo.price, saleInfo.seller, msg.sender);
}
function createAuction(address collection, uint256 tokenID, uint256 startPrice, uint256 auctionPeriod) public onlyRegisterUser{
require(IERC721(collection).ownerOf(tokenID) == msg.sender, "Not Your NFT");
require(_nftInfoForAuction[collection][tokenID].state != AuctionState.OPEN, "Already Opened");
require(startPrice > 0, "Incorrect Price");
require(auctionPeriod > 0, "Incorrect Auction Period");
_nftInfoForAuction[collection][tokenID] = AuctionInfo({
state: AuctionState.OPEN,
endAt: block.timestamp + auctionPeriod,
startPrice: startPrice,
highestBidPrice: startPrice,
highestBidAddress: address(0x0),
seller: msg.sender
});
IERC721(collection).transferFrom(msg.sender, address(this), tokenID);
emit CreateAuction(collection, tokenID, _nftInfoForAuction[collection][tokenID].startPrice, _nftInfoForAuction[collection][tokenID].endAt, _nftInfoForAuction[collection][tokenID].seller);
}
function bidOnAuction(address collection, uint256 tokenID) public payable onlyRegisterUser {
AuctionInfo storage auctionInfo = _nftInfoForAuction[collection][tokenID];
require(auctionInfo.state == AuctionState.OPEN, "This is non exist Auction");
require(auctionInfo.endAt > block.timestamp, "Time over for bid");
require(auctionInfo.highestBidPrice < msg.value, "Incorrect Price");
if (auctionInfo.highestBidAddress != address(0x0)) {
payable(auctionInfo.highestBidAddress).transfer(auctionInfo.highestBidPrice);
}
auctionInfo.highestBidPrice = msg.value;
auctionInfo.highestBidAddress = msg.sender;
emit BidOnAuction(collection, tokenID, auctionInfo.highestBidPrice, auctionInfo.highestBidAddress);
}
function endAuction(address collection, uint256 tokenID) public onlyRegisterUser nonReentrant {
AuctionInfo storage auctionInfo = _nftInfoForAuction[collection][tokenID];
require(auctionInfo.state == AuctionState.OPEN, "This is non exist Auction");
require(auctionInfo.endAt < block.timestamp, "It's not time yet");
require(auctionInfo.highestBidAddress == msg.sender || auctionInfo.seller == msg.sender, "Not allowed for you");
IERC721(collection).transferFrom(address(this), msg.sender, tokenID);
//Transfer money by distribution
_distributeFunds(
auctionInfo.seller, auctionInfo.highestBidAddress,
_addedCollections[collection].creatorAddress, auctionInfo.highestBidPrice);
auctionInfo.state = AuctionState.ENDED;
emit EndAuction(collection, tokenID, auctionInfo.highestBidPrice, auctionInfo.seller, auctionInfo.highestBidAddress);
}
function cancelAuction(address collection, uint256 tokenID) public onlyRegisterUser {
AuctionInfo storage auctionInfo = _nftInfoForAuction[collection][tokenID];
require(auctionInfo.state == AuctionState.OPEN, "This is non exist Auction");
require(auctionInfo.seller == msg.sender, "Not allowed for you");
auctionInfo.state = AuctionState.CANCELED;
if (auctionInfo.highestBidAddress != address(0x0)) {
payable(auctionInfo.highestBidAddress).transfer(auctionInfo.highestBidPrice);
}
emit CancelAuction(collection, tokenID, auctionInfo.seller);
}
function _distributeFunds(address _seller, address _buyer, address _creator, uint256 _price) private {
payable(_creator).transfer(_price * distributionFee.creatorFee / denominator);
address[] memory referrerAddresses = register.getReferrerAddresses(_buyer);
for(uint8 i = 0; i < referralDeep; i++) {
if(referrerAddresses[i] == address(0)) {
break;
}
payable(referrerAddresses[i]).transfer(_price * distributionFee.referralFee[i] / denominator);
}
payable(_seller).transfer(_price * distributionFee.sellerPercentage / denominator);
}
function _distributeFundsWETH(address _seller, address _buyer, address _creator, uint256 _price) private {
_WETH.transfer(_creator, _price * distributionFee.creatorFee / denominator);
address[] memory referrerAddresses = register.getReferrerAddresses(_buyer);
for(uint8 i = 0; i < referralDeep; i++) {
if(referrerAddresses[i] == address(0)) {
break;
}
_WETH.transfer(referrerAddresses[i], _price * distributionFee.referralFee[i] / denominator);
}
_WETH.transfer(_seller, _price * distributionFee.sellerPercentage / denominator);
}
function getSaleInfo(address _collection, uint256 _id) public view returns(SaleInfo memory){
return _nftInfoForSale[_collection][_id];
}
function getAuctionInfo(address _collection, uint256 _id) public view returns(AuctionInfo memory){
return _nftInfoForAuction[_collection][_id];
}
function getCollectionInfo(address _collection) public view returns(CollectionInfo memory){
return _addedCollections[_collection];
}
function withdrawBalance() public onlyOwner {
require(address(this).balance > 0, "No funds");
payable(owner()).transfer(address(this).balance);
}
}
|
'''
https://github.com/princeton-vl/pytorch_stacked_hourglass
'''
import torch
import torch.nn as nn
from typing import Optional
class Conv(nn.Module):
def __init__(
self,
inp_dim: int,
out_dim: int,
kernel_size: int = 3,
stride: int = 1,
bn: bool = False,
relu: bool = True
):
super().__init__()
self.inp_dim = inp_dim
self.conv = nn.Conv2d(
inp_dim, out_dim, kernel_size, stride, padding=(kernel_size-1)//2, bias=True)
self.relu = None
self.bn = None
if relu:
self.relu = nn.ReLU()
if bn:
self.bn = nn.BatchNorm2d(out_dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
assert x.size()[1] == self.inp_dim, "{} {}".format(x.size()[1], self.inp_dim)
x = self.conv(x)
if self.bn is not None:
x = self.bn(x)
if self.relu is not None:
x = self.relu(x)
return x
class Residual(nn.Module):
def __init__(self, inp_dim: int, out_dim: int):
super().__init__()
self.relu = nn.ReLU()
self.bn1 = nn.BatchNorm2d(inp_dim)
self.conv1 = Conv(inp_dim, int(out_dim/2), 1, relu=False)
self.bn2 = nn.BatchNorm2d(int(out_dim/2))
self.conv2 = Conv(int(out_dim/2), int(out_dim/2), 3, relu=False)
self.bn3 = nn.BatchNorm2d(int(out_dim/2))
self.conv3 = Conv(int(out_dim/2), out_dim, 1, relu=False)
self.skip_layer = Conv(inp_dim, out_dim, 1, relu=False)
if inp_dim == out_dim:
self.need_skip = False
else:
self.need_skip = True
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.need_skip:
residual = self.skip_layer(x)
else:
residual = x
out = self.bn1(x)
out = self.relu(out)
out = self.conv1(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn3(out)
out = self.relu(out)
out = self.conv3(out)
out += residual
return out
class HourglassModule(nn.Module):
def __init__(self, n: int, f: int, bn: Optional[bool] = None, increase: int = 0):
super().__init__()
nf = f + increase
self.up1 = Residual(f, f)
# Lower branch
self.pool1 = nn.MaxPool2d(2, 2)
self.low1 = Residual(f, nf)
self.n = n
# Recursive hourglass
if self.n > 1:
self.low2 = HourglassModule(n-1, nf, bn=bn)
else:
self.low2 = Residual(nf, nf)
self.low3 = Residual(nf, f)
self.up2 = nn.Upsample(scale_factor=2, mode='nearest')
def forward(self, x: torch.Tensor) -> torch.Tensor:
up1 = self.up1(x)
pool1 = self.pool1(x)
low1 = self.low1(pool1)
low2 = self.low2(low1)
low3 = self.low3(low2)
up2 = self.up2(low3)
return up1 + up2
class Merge(nn.Module):
def __init__(self, x_dim: int, y_dim: int):
super().__init__()
self.conv = Conv(x_dim, y_dim, 1, relu=False, bn=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.conv(x)
class Hourglass(nn.Module):
def __init__(
self,
nstack: int,
inp_dim: int,
oup_dim: int,
bn: bool = False,
increase: int = 0,
**kwargs
):
super().__init__()
self.nstack = nstack
self.pre = nn.Sequential(
Conv(3, 64, 7, 2, bn=True, relu=True),
Residual(64, 128),
nn.MaxPool2d(2, 2),
Residual(128, 128),
Residual(128, inp_dim)
)
self.hgs = nn.ModuleList([
nn.Sequential(
HourglassModule(4, inp_dim, bn, increase),
) for i in range(nstack)])
self.features = nn.ModuleList([
nn.Sequential(
Residual(inp_dim, inp_dim),
Conv(inp_dim, inp_dim, 1, bn=True, relu=True)
) for i in range(nstack)])
self.outs = nn.ModuleList([Conv(inp_dim, oup_dim, 1, relu=False, bn=False) for i in range(nstack)])
self.merge_features = nn.ModuleList([Merge(inp_dim, inp_dim) for i in range(nstack-1)])
self.merge_preds = nn.ModuleList([Merge(oup_dim, inp_dim) for i in range(nstack-1)])
self.nstack = nstack
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.pre(x)
combined_hm_preds = []
for i in range(self.nstack):
hg = self.hgs[i](x)
feature = self.features[i](hg)
preds = self.outs[i](feature)
combined_hm_preds.append(preds)
if i < self.nstack - 1:
x = x + self.merge_preds[i](preds) + self.merge_features[i](feature)
# TODO : how to set the channel of HG
# return torch.stack(combined_hm_preds, 1)
return combined_hm_preds[-1]
if __name__ == "__main__":
import numpy as np
model = Hourglass(8, 256, 16)
inputs = np.zeros((1, 3, 256, 256))
outputs = model(torch.Tensor(inputs))
# print(model)
print(outputs.shape)
|
import { useState } from "react";
import { useSession } from "next-auth/react";
import SuccessFlashMessage from "@/components/general/flash/SuccessFlashMessage.jsx";
import DangerFlashMessage from "@/components/general/flash/DangerFlashMessage.jsx";
import { useRouter } from "next/router.js";
import { useCategory } from "@/swr/category/useCategory.js";
import SectionHeaderNoButton from "@/components/general/section/SectionHeaderNoButton.jsx";
import SectionLayout from "@/components/general/section/SectionLayout.jsx";
import FormCategory from "@/components/general/form/FormCategory.jsx";
export default function EditCategory() {
const router = useRouter();
const {category} = useCategory(router.query.id)
const [flash, setFlash] = useState([]);
const { data: session, status } = useSession()
if(!category) return <div>Loading...!</div>
const addFlash = (message) => {
setFlash([message]);
};
const handleSubmit = async (event) => {
event.preventDefault();
const data = {
label: event.target.label.value,
};
const JSONdata = JSON.stringify(data);
const endpoint = process.env.NEXT_PUBLIC_URL_API + "/category/" + category.id;
const options = {
method: "PUT",
body: JSONdata,
headers: {
Authorization : `Bearer ${session.user.token} `
}
};
const response = await fetch(endpoint, options);
if (response.ok) {
addFlash(
<SuccessFlashMessage key="i">
La categorie a été mise à jour avec succes !
</SuccessFlashMessage>
);
} else {
addFlash(
<DangerFlashMessage key="i">
Il y a un probleme pour la mise à jour de la catégorie
</DangerFlashMessage>
);
}
};
return (
<SectionLayout>
<SectionHeaderNoButton title={'Modifier une categorie'}/>
{flash}
<FormCategory onSubmit={handleSubmit} category={category.label}/>
</SectionLayout>
);
}
|
import React, { FC, useState } from 'react';
import useToggleSelection from '../../hooks/useToggleSelection';
import ShoppingTemplate from '../../templates/shoppingTemplate/ShoppingTemplate';
import useProducts from '../../models/useProducts/useProducts';
import { useQueryClient } from 'react-query';
import IProduct from '../../api/interfaces/IProduct';
import NewInventoryModal from '../../organisms/newInventoryModal/NewInventoryModal';
interface CartItem {
id: string;
title: string;
count: number;
}
const Products: FC = () => {
const { data } = useProducts();
const [cart, setCart] = useState<CartItem[]>([]);
const [isModalOpen, setModalOpen] = useState<boolean>(false);
const [selectedItems, toggleSelection, clearSelection] = useToggleSelection();
const [selectedCartItems, toggleCartSelection, clearCartSelection] =
useToggleSelection();
const queryClient = useQueryClient();
const handleNewInventoryItem = (product: IProduct) => {
const newData = [...(data || []), product];
queryClient.setQueryData(['ListProductsQuery'], newData);
};
const addToCart = () => {
const newCart = [...cart];
for (const id of selectedItems) {
const existingCartItem = newCart.find((item) => item.id === id);
if (existingCartItem) {
existingCartItem.count += 1;
} else {
const product = data?.find((product) => product.id === id);
if (product) {
newCart.push({
id: product.id,
title: product.title,
count: 1,
});
}
}
}
setCart(newCart);
clearSelection();
};
const removeFromCart = () => {
setCart((prevCart) =>
prevCart.filter((item) => !selectedCartItems.includes(item.id))
);
clearCartSelection();
};
const totalCount = cart.reduce((sum, item) => sum + item.count, 0);
return (
<>
<ShoppingTemplate
inventoryItems={data || []}
selectedInventoryItems={selectedItems}
onInventoryItemToggleSelect={toggleSelection}
onAddToCart={addToCart}
onNewInventoryItem={() => setModalOpen(true)}
cartItems={cart}
selectedCartItems={selectedCartItems}
onCartItemToggleSelect={toggleCartSelection}
onRemoveFromCart={removeFromCart}
totalItemsCount={totalCount}
/>
<NewInventoryModal
isOpen={isModalOpen}
onClose={() => setModalOpen(false)}
onAdd={handleNewInventoryItem}
/>
</>
);
};
export default Products;
|
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpk g.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<title>Addition</title>
<style>
#app {
text-align:center;
font-family: sans-serif;
}
#problem {
font-size: 72px;
}
#winner {
font-size: 72px;
color: green;
}
</style>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
num1: 2,
num2: 9,
response:"",
score: 0
};
}
render() {
if (this.state.score === 10) {
return (
<div id="winner">
You Won !
</div>
);
}
return (
<div><p></p>
<div id="problem"> {this.state.num1} + {this.state.num2} </div><p></p>
<input onKeyPress={this.inputKeyPress} onChange={this.updateResponse} value={this.state.response}/><p></p>
<div>Score is : {this.state.score}</div>
{/*<div> You have typed : {this.state.response}</div>*/}
</div>
);
}
inputKeyPress = (event) => {
if (event.key === 'Enter') {
const answer = parseInt(this.state.response);
if (answer === this.state.num1 + this.state.num2) {
// User got question right
this.setState(state => ({
score: state.score + 1,
num1: Math.ceil(Math.random() * 10),
num2: Math.ceil(Math.random() * 10),
response: ""
}));
} else {
// User got question wrong
this.setState(state => ({
score: state.score - 1,
response: ""
}))
}
}
}
updateResponse = (event) => {
this.setState({
response: event.target.value
});
}
}
ReactDOM.render(<App />, document.querySelector('#app'));
</script>
</body>
</html>
|
import styled from 'styled-components'
import { darken } from 'polished'
interface IButtonProps {
buttonSize?: string
buttonType?: string
hesPage?: boolean
}
function converteTamanho(tamanho: string | undefined) {
if (tamanho === 'large') {
return '56px'
}
if (tamanho === 'small') {
return '30px'
} else {
return '40px'
}
}
function converteCorFundo(corEscolhida: string | undefined) {
if (corEscolhida === 'secondary') {
return 'var(--green-100)'
}
if (corEscolhida === 'warning') {
return 'var(--yellow-600)'
} else {
return 'var(--green-600)'
}
}
function converteCorEscrita(corEscolhida: string | undefined) {
if (corEscolhida === 'secondary') {
return 'var(--brown-600)'
}
if (corEscolhida === 'warning') {
return 'var(--brown-800)'
} else {
return 'var(--white)'
}
}
export const Botao = styled.button<IButtonProps>`
transition: background-color 0.2s;
width: 100%;
height: ${({ buttonSize }) => converteTamanho(buttonSize)};
padding: 12px 16px 12px 16px;
background: ${({ buttonType }) => converteCorFundo(buttonType)};
${({hesPage})=> hesPage && 'background-color: var(--green-300);'}
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
user-select: none;
border-radius: 10px;
&:hover {
${(props) => {
switch (props.buttonType) {
case 'primary':
return `background-color: ${darken(0.1, '#004F22')} ;`
case 'secondary':
return `background-color: ${darken(0.1, '#E2FFC4')} ;`
case 'warning':
return `background-color: ${darken(0.1, '#FFAE11')} ;`
}
}}
}
`
export const Span = styled.span<IButtonProps>`
margin: ${({ buttonType }) =>
buttonType === 'warning' ? '0px 8px' : '0px 12px;'};
font-size: ${({ buttonType }) =>
buttonType === 'warning' ? '20px' : '16px'};
font-weight: 700;
color: ${({ buttonType }) => converteCorEscrita(buttonType)};
`
|
<script lang="ts">
import { assert } from '../../../assert.ts';
import { Document as Api } from '../../../api/document.ts';
import { IconSize, ContainerType } from '../../../components/types.ts';
import { dashboardState } from '../../../stores/DashboardState.ts';
import { topToastMessage } from '../../../stores/ToastStore.ts';
import Container from '../../../components/ui/Container.svelte';
import PageUnavailable from '../../../components/ui/PageUnavailable.svelte';
import RegisterRow from '../../../components/ui/itemrow/RegisterRow.svelte';
$: ({ currentOffice } = $dashboardState);
function loadDossier(office: number) {
return Api.getDossier(office).catch(err => {
assert(err instanceof Error);
topToastMessage.enqueue({ title: err.name, body: err.message });
throw err;
});
}
</script>
{#if currentOffice === null}
<p>You must select an office before accessing the Dossier page.</p>
{:else}
<h1>Dossier</h1>
{#await loadDossier(currentOffice)}
<p>Loading registered documents.</p>
{:then reg}
<Container ty={ContainerType.Enumeration}>
{#each reg as entry (entry.doc)}
<RegisterRow
{...entry}
showOverflowIcon={false}
iconSize={IconSize.Large}
/>
{:else}
<p>No documents were created in this office yet.</p>
{/each}
</Container>
{:catch err}
<PageUnavailable {err} />
{/await}
{/if}
|
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
'users',
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
validate: { isEmail: true },
},
url: {
type: DataTypes.STRING,
allowNull: true,
},
introduction: {
type: DataTypes.STRING(200),
allowNull: false,
},
},
{ timestamps: true }
);
return User;
};
|
import React from 'react';
import { useParams, Link } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { Spinner } from 'react-bootstrap';
const Details = () => {
const { slug } = useParams();
const { postItems } = useSelector((state) => state.posts);
const { categoryItems } = useSelector((state) => state.categories);
const postIndex = postItems.findIndex((p) => p.slug === slug);
const post = postIndex >= 0 ? postItems[postIndex] : null;
const nextPost = postIndex > 0 ? postItems[postIndex - 1] : null;
const prevPost =
postIndex < postItems.length - 1 ? postItems[postIndex + 1] : null;
return (
<>
<section className="blog-details-page pt-130 pb-90">
<div className="container">
<div className="row">
<div className="col-lg-1"></div>
<div className="col-lg-10">
<div className="blog-details-wrapper mb-40">
{post ? (
<div className="blog-post mb-60 wow fadeInUp">
<div className="post-meta">
<ul>
{post.categories && post.categories.length > 0 ? (
post.categories.map((categoryId) => (
<li key={categoryId}>
{categoryItems.find((cat) => cat.id === categoryId)
? categoryItems.find((cat) => cat.id === categoryId)
.name
: 'Category Not Found'}
</li>
))
) : (
<li>No Categories</li>
)}
</ul>
</div>
<div className="main-post">
<div className="entry-content">
<h3 className="title">{post.title.rendered}</h3>
<div
dangerouslySetInnerHTML={{
__html: post.content.rendered,
}}
/>
</div>
</div>
</div>
) : (
<div className='my-5 text-center'>
<Spinner animation='grow' role='status'>
<span className='visually-hidden'></span>
</Spinner>
</div>
)}
<div className="post-navigation">
{prevPost && (
<Link
to={`/posts/${prevPost.slug}`}
className="btn me-4"
style={{ backgroundColor: '#8eb850', color: 'white' }}
>
< Previous Post
</Link>
)}
{nextPost && (
<Link
to={`/posts/${nextPost.slug}`}
className="btn"
style={{
backgroundColor: '#8eb850',
color: 'white',
float: 'right',
}}
>
Next Post >
</Link>
)}
</div>
</div>
</div>
<div className="col-lg-1"></div>
</div>
</div>
</section>
</>
);
};
export default Details;
|
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
@st.cache_data
def load_data():
df = pd.read_csv("Final_Patient_Scores.csv")
return df
data = load_data() # Load the cached data
# Define color mapping for BMI categories
bmi_colors = {"Normal": "green", "Overweight": "yellow", "Obese": "red"}
# Patient selection
selected_id = st.selectbox("Choose a patient ID", data["Patient_ID"].unique())
patient_data = data[data["Patient_ID"] == selected_id]
# Basic patient information
st.header(f"Patient ID: {selected_id}")
st.write(f"BMI: {patient_data['BMI'].values[0]}",
safe_html=f"<span style='color:{bmi_colors[patient_data['BMI'].values[0]]}'>{patient_data['BMI'].values[0]}</span>")
# Compliance scores
st.subheader("Compliance Scores")
cols = ["History_Score", "Alcohol_Score", "Diabetes_Signs_Score", "Diet_Score", "Exercise_Score", "Medication_Score"]
table_data = [["Compliance Category", "Patient", "Population Average"]]
for col in cols:
score = patient_data[col].values[0]
normalized = patient_data[f"{col}_Normalized"].values[0]
avg_normalized = data[data["BMI"] == patient_data["BMI"].values[0]][f"{col}_Normalized"].mean()
table_data.append([col, f"{score:.2f}", f"{normalized:.2f}"])
st.table(table_data)
# Normalized scores comparison
st.subheader("Normalized Score Comparison")
fig, ax = plt.subplots()
bar_width = 0.35
bar_positions_patient = range(len(cols))
bar_positions_average = [pos + bar_width for pos in bar_positions_patient]
# Plotting patient scores
ax.bar(bar_positions_patient, patient_data[cols].values[0], width=bar_width, label="Patient")
# Plotting average scores
avg_normalized = data[cols].mean().values
ax.bar(bar_positions_average, avg_normalized, width=bar_width, label="Average", alpha=0.5)
ax.set_xticks([pos + bar_width / 2 for pos in bar_positions_patient])
ax.set_xticklabels(cols, rotation=45, ha="right") # Adjust rotation angle as needed
ax.set_xlabel("Compliance Category")
ax.set_ylabel("Normalized Score")
ax.legend()
st.pyplot(fig)
# Overall compliance radar chart
st.subheader("Overall Compliance")
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
theta = range(len(cols))
radius = patient_data[cols].values[0]
ax.fill(theta, radius, color="blue", alpha=0.25)
# Calculate the overall average without filtering by BMI
avg_radius = data[cols].mean().values
ax.fill(theta, avg_radius, color="orange", alpha=0.25)
ax.set_xticks(theta)
ax.set_xticklabels(cols)
ax.set_ylabel("Score")
ax.set_title("Patient vs. Average")
st.pyplot(fig)
import streamlit as st
import pandas as pd
# Load the CSV file containing patient summaries
df = pd.read_csv("patient_summaries.csv")
# Streamlit app
def main():
st.title("Patient Summary Viewer")
# Create a dropdown to select a Patient_ID
selected_patient_id = st.selectbox("Select Patient_ID:", df["Patient_ID"].unique())
# Create a button to trigger the selected functionality
if st.button("View Summary"):
if selected_patient_id:
# Retrieve and display the summary for the selected Patient_ID
selected_summary = df[df["Patient_ID"] == selected_patient_id]["Summaries"].values[0]
st.subheader("Patient Summary:")
st.write(selected_summary)
else:
st.warning("Please select a Patient_ID.")
if __name__ == "__main__":
main()
|
package com.nartan.ba.post.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public enum SupportedException {
TAG_NOT_FOUND_EXCEPTION(TagNotFoundException.class, HttpStatus.NOT_FOUND),
POST_NOT_FOUND_EXCEPTION(PostNotFoundException.class, HttpStatus.NOT_FOUND),
USERNAME_NOT_FOUND(UsernameNotFoundException.class, HttpStatus.NOT_FOUND),
BAD_CREDENTIALS(BadCredentialsException.class, HttpStatus.BAD_REQUEST),
COUNTER_EXCEPTION(CounterException.class, HttpStatus.INTERNAL_SERVER_ERROR);
private Class<? extends Throwable> exceptionClass;
private HttpStatus status;
SupportedException(
final Class<? extends Throwable> exceptionClass,
final HttpStatus status
) {
this.exceptionClass = exceptionClass;
this.status = status;
}
public Class<? extends Throwable> getExceptionClass() {
return exceptionClass;
}
public HttpStatus getStatus() {
return status;
}
}
|
import React from 'react';
import { graphql } from 'gatsby';
import { GatsbyImage as Image, getImage } from 'gatsby-plugin-image';
import { AngleLeftIcon, GitHubIcon, Link, LinkedInIcon, TwitterIcon } from 'website-components';
import CustomMDXProvider from '../components/CustomMDXProvider';
import EventCard from '../components/EventCard';
import Seo from '../components/Seo';
const SpeakerPage = ({ data, path }) => {
const { speaker } = data;
const speakerLocation = path.includes('boston') ? 'boston' : 'barcelona';
let backProps = { to: `/${speakerLocation}/speakers/` };
if (typeof window !== 'undefined' && window.location.search.includes('goBack'))
backProps = { onClick: () => window.history.back() };
return (
<>
<Seo title={speaker.meta.title} description={speaker.meta.description} image={speaker.meta.image.publicURL} />
<div className="text-white container-sm py-10 md:py-20">
<div className="inline-flex items-center hover:text-green-300 mb-4">
<AngleLeftIcon className="h-6 w-6 inline-block mr-1" />
<Link {...backProps} noBorder>
Back
</Link>
</div>
<div className="flex flex-col md:flex-row">
<div className="w-full md:w-1/3 overflow-hidden" style={{ borderRadius: 100 }}>
<Image image={getImage(speaker.image)} className="w-full" imgClassName="rounded-md" alt={speaker.name} />
</div>
<div className="w-full md:w-2/3 mt-6 md:mt-0 md:px-6 inline-flex flex-col">
<h1 className="typo-h2 text-green-300 mb-4">{speaker.name}</h1>
<p className="typo-h5 mb-4">{speaker.position}</p>
{speaker.email && (
<div className="mb-4">
<Link to={`mailto:${speaker.email}`} className="typo-body" noBorder>
{speaker.email}
</Link>
</div>
)}
<div className="flex mb-4">
{speaker.github && (
<Link to={speaker.github} noBorder className="text-white hover:text-green-300 mr-4">
<GitHubIcon />
</Link>
)}
{speaker.twitter && (
<Link to={speaker.twitter} noBorder className="text-white hover:text-green-300 mr-4">
<TwitterIcon />
</Link>
)}
{speaker.linkedin && (
<Link to={speaker.linkedin} noBorder className="text-white hover:text-green-300">
<LinkedInIcon />
</Link>
)}
</div>
</div>
</div>
<div className="mt-5 md:mt-10 typo-body whitespace-pre-line">
<CustomMDXProvider>{speaker.content.body}</CustomMDXProvider>
</div>
<div className="mt-5 md:mt-10">
{data.events.nodes.map((event, i) => {
if (!event.path?.includes(speakerLocation)) return null;
return (
<div className="mt-8 first:mt-0" key={i}>
<EventCard event={event} disableTimeline />
</div>
);
})}
</div>
</div>
</>
);
};
export default SpeakerPage;
export const pageQuery = graphql`
query ($slug: String!) {
speaker: people(slug: { eq: $slug }) {
slug
name
position
email
tags
github
linkedin
twitter
image {
childImageSharp {
gatsbyImageData(placeholder: NONE)
}
}
content {
body
}
meta {
title
description
image {
publicURL
}
}
}
events: allEvent(filter: { speakers: { elemMatch: { slug: { eq: $slug } } } }, sort: { datetime: ASC }) {
nodes {
slug
id
timeframe
title
description
date
time
tags
location
locationUrl
youtube
youtubeUrl
hasPage
path
fullPath
speakers {
name
image {
childImageSharp {
gatsbyImageData(height: 32, placeholder: NONE, width: 32)
}
}
}
}
}
}
`;
|
# -1Chan Message Board
----------------------------------
## 1. Problem Description
----------------------------------
We will be designing a message board. The message board will organize community Threads under Topics. Users will be able to register using a unique user_name and password. Users can create threads under existing topics, add posts to existing threads, and add comments to existing posts.
The front end will display pages to help users navigate through the topics, threads, and posts. Users will have their own home page, where they can personalize a profile. A user’s profile will be linked to all of their existing posts. Likewise, any post will be linked to a user’s profile page.
----------------------------------
## 2. Proposed system
----------------------------------
Here are the necessary Entities within this system:
• Topic – (topic_id (PK), topic_title, topic_image)
• Thread – (thread_id (PK), topic_id (FK), user_name (FK), thread_title, thread_image, thread_creation_time)
• Post – (post_id (PK), user_name (FK), post_title, post_text, post_creation_time, posts_likes, posts_dislikes)
• Comment - (comment_id (PK), user_name (FK), post_id(FK), comment_text, comment_creation_time, comment_likes, comment_dislikes)
• User – (user_name (PK), password, profile_text, user_image, roles, vote_ratio)
----------------------------------
## 3. System Specification (proposed)
----------------------------------
Hardware Requirements:
Computer - to be able to run and access the site
Server - Hosting the website and database server
Database Server - Storing all relevant information from the users and other entities above
Software Requirements:
Python, we chose this language because it is compatible with our chosen backend and frontend languages and we all have experience with it.
PostgreSQL as one of us has experience and it is an established, detailed database system that allows for the scalability and security that we need.
Django can handle routing and frontend design that would be fairly easy to implement and learn shorthand.
SQLAlchemy and Psycopg2 library because we are using Python to code and interacting with PostgreSQL databases. Essentially our accessor to databases.
----------------------------------
## 4. Requirements
----------------------------------
• python = "^3.10"
• jupyter = "^1.0.0"
• sqlalchemy = "^2.0.19"
• pyscopg2 = "^66.0.2"
• flask = "^2.3.2"
• pandas = "^2.0.3"
• flask-login = "^0.6.2"
• flask-sqlalchemy = "^3.0.5"
----------------------------------
## 5. External Deps
----------------------------------
- Git - Download latest version at https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
- GitHub Desktop (Not needed, but HELPFUL) at https://desktop.github.com/
----------------------------------
## 6. Installation
----------------------------------
Download this code repository by using git:
'git clone git@github.com:Summer23-CSCE-310-Database-Systems/github-setup-minus1chan-group.git'
----------------------------------
## 7. Run the app
----------------------------------
You can run the app by running the command (make sure you are inside the repository before you run the command):
'python main.py'
|
import { Injectable } from '@nestjs/common';
import { CreateAssetDto } from './dto/create-asset.dto';
import { UpdateAssetDto } from './dto/update-asset.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { PrismaClient, Prisma } from '@prisma/client';
@Injectable()
export class AssetService {
constructor(private prisma: PrismaService) {}
async create(createAssetDto: CreateAssetDto, res) {
console.log(createAssetDto);
try {
const newAsset = await this.prisma.asset.create({
data: {
Employee: {
connect: {
id: createAssetDto.Employee,
},
},
Model: {
connect: {
Model: createAssetDto.ModelName,
},
},
},
});
return res.status(200).json({
message: 'Successfully created Asset',
data: newAsset,
});
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
console.log(error);
// Handle specific known request error
if (error.code === 'P2002')
return res.status(400).json({
error: 'Type already exists',
prismaCode: error.code,
});
return res.status(400).json({ prismaCode: error.code });
} else if (error instanceof Prisma.PrismaClientUnknownRequestError) {
console.log(error);
// Handle unknown request error
return res.status(500).json(error);
} else {
// Handle other errors
console.log(error);
return res.status(500).json({ message: 'Unknwon Reason' });
}
}
}
async findAll(res) {
try {
const assets = await this.prisma.asset.findMany();
return res
.status(200)
.json({ message: 'Succesfully queried assets', data: assets });
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
// Handle specific known request error
return res.status(400).json({ prismaCode: error.code });
} else if (error instanceof Prisma.PrismaClientUnknownRequestError) {
// Handle unknown request error
return res.status(500).json(error);
} else {
// Handle other errors
return res.status(500).json({ message: 'Unknwon Reason' });
}
}
}
async findOne(id: number, res) {
try {
const asset = await this.prisma.asset.findUnique({
where: { id: id },
});
if (asset === null)
return res
.status(400)
.json({ message: 'No asset was found!', data: asset });
return res
.status(200)
.json({ message: 'Succesfully queried asset', data: asset });
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
// Handle specific known request error
return res.status(400).json({ prismaCode: error.code });
} else if (error instanceof Prisma.PrismaClientUnknownRequestError) {
// Handle unknown request error
return res.status(500).json(error);
} else {
// Handle other errors
return res.status(500).json({ message: 'Unknwon Reason' });
}
}
}
update(id: number, updateAssetDto: UpdateAssetDto, res) {
return `This action updates a #${id} asset`;
}
async remove(id: number, res) {
try {
const asset = await this.prisma.asset.delete({
where: { id: id },
});
return res
.status(200)
.json({ message: 'Succesfully removed asset', data: asset });
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
// Handle specific known request error
if (error.code === 'P2025')
return res.status(400).json({
error: 'The employee could not be found!',
prismaCode: error.code,
});
return res.status(400).json({ prismaCode: error.code });
} else if (error instanceof Prisma.PrismaClientUnknownRequestError) {
// Handle unknown request error
return res.status(500).json(error);
} else {
// Handle other errors
return res.status(500).json({ message: 'Unknwon Reason' });
}
}
}
}
|
class Admin::CategoriesController < AdminController
before_action :load_category, only: %i(edit update destroy)
def index
@categories = Category.alphabet.paginate page: params[:page],
per_page: Settings.per_page.categories
end
def new
@category = Category.new
end
def create
@category = Category.new category_params
if @category.save
flash[:success] = t "controller.category.create.success"
redirect_to admin_categories_path
else
flash[:danger] = t "controller.category.create.failed"
render :new
end
end
def edit; end
def update
if @category.update_attributes category_params
flash[:success] = t "controller.category.update.success"
redirect_to admin_categories_path
else
render :edit
end
end
def destroy
if @category.destroy
flash[:success] = t "controller.category.destroy.success"
else
flash[:danger] = t "controller.category.destroy.failed"
end
redirect_to admin_categories_path
end
private
def category_params
params.require(:category).permit :name
end
def load_category
@category = Category.find_by id: params[:id]
return if @category
redirect_to admin_categories_path
end
end
|
namespace Users.Api.Contracts.Responses;
/// <summary>
/// The returned response when querying for a user
/// </summary>
public class UserResponse
{
/// <summary>
/// The id of the user
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// The username of the user
/// </summary>
public required string Username { get; init; }
/// <summary>
/// The name of the user
/// </summary>
public required string Name { get; init; }
/// <summary>
/// The email of the user
/// </summary>
public required string Email { get; init; }
/// <summary>
/// The phone number of the user
/// </summary>
public required string Phone { get; init; }
/// <summary>
/// The joined date of the user
/// </summary>
public required DateTime DateJoined { get; set; }
}
|
import pandas as pd
print("Script Start")
df = pd.read_csv("./bank_enriched_addresses.csv")
# a. Remove all rows where pdays is -1
df = df.query('pdays != -1')
# b. Split name into first name and second name columns (drop name)
names = df["name"].str.split(" ", n=1, expand=True)
df["first_name"] = names[0]
df["second_name"] = names[1]
df.drop(columns=["name"], inplace=True)
# Replace the values in the age column with bucketed values, such that
df["age"] = df["age"] // 10
# d. Replace yes/no values with booleans
df["default"] = df["default"].replace({'yes': True, 'no': False})
df["housing"] = df["housing"].replace({'yes': True, 'no': False})
df["loan"] = df["loan"].replace({'yes': True, 'no': False})
df["y"] = df["y"].replace({'yes': True, 'no': False})
# e. Replace day and month with a single date column, of the form dd/MM
month_mapping = {
"jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6,
"jul": 7, "aug": 8, "sep": 9, "oct": 10, "nov": 11, "dec": 12
}
# Convert the "month" column to numerical values using the mapping
df["month_numeric"] = df["month"].str.lower().map(month_mapping)
# Create a new datetime column using "day" and "month_numeric" columns
df["date"] = pd.to_datetime(df['day'].astype(str) + '/' + df['month_numeric'].astype(str), format='%d/%m')
# Format the "date" column as "dd/MM" and store it in a new column "date"
df["date"] = df["date"].dt.strftime('%d/%m')
# Drop temp and old columns
df.drop(["month_numeric", "day", "month"], axis=1, inplace=True)
# f. Rename the y column to “outcome"
df = df.rename(columns={"y": "outcome"})
# Add a column which categorizes geographical features in the address, where present. Note the dirtiness of the
# address data and that the exact categories:
# a. “water”, where the address contains e.g. lake, creek
# b. “relief”, where the address contains e.g. hill, canyon
# c. “flat”, where the address contains e.g. plain
def categorize_geographical_feature(address):
address = address.lower()
if any(keyword in address for keyword in ["lake", "creek", "river"]):
return "water"
elif any(keyword in address for keyword in ["hill", "canyon"]):
return "relief"
elif any(keyword in address for keyword in ["plain"]):
return "flat"
else:
return "unknown"
df["geographical_feature"] = df["address"].apply(categorize_geographical_feature)
# Group by the feature (if you created it, or by some other field if not) and filter out any empty values, sort by
# the age bucket (or age if you didn’t do the bucketing), and return a row count.
agg_df = df.dropna()
agg_df = agg_df.query('geographical_feature != "unknown"')
agg_df = agg_df.groupby(["geographical_feature", "age"]).size().reset_index(name='counts').sort_values("age")
# Write the row level data from step 2, and aggregated data from step 3 to both CSV and parquet formats.
df.to_csv('step_2.csv', index=False)
df.to_parquet('step_2.parquet.gzip', compression='gzip', index=False)
agg_df.to_csv('step_4.csv', index=False)
agg_df.to_parquet('step_4.parquet.gzip', compression='gzip', index=False)
print("Script End - Successfuly")
|
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { supabase } from "../client";
const UpdatePost = () => {
let params = useParams();
const [post, setPost] = useState(null);
const [input, setInput] = useState({
title: "",
description: "",
});
useEffect(() => {
const getPost = async () => {
await supabase
.from("Posts")
.select()
.eq("id", params.postID)
.then((response) => {
console.log(response.data[0]);
setPost(response.data[0]);
setInput({
title: response.data[0].title,
description: response.data[0].description,
});
});
};
getPost();
}, []);
const updatePost = async () => {
await supabase
.from("Posts")
.update({ title: input.title, description: input.description })
.eq("id", params.postID);
window.location = `/${params.postID}`;
window.alert("Post Successfully Updated.");
};
const deleteConfirmation = () => {
if (
confirm("Are you sure you want to delete your post? You can't undo this.")
) {
console.log("POST HAS BEEN DELETED.");
const deletePost = async () => {
await supabase
.from("Posts")
.delete()
.eq("id", params.postID)
.then((response) => (window.location = "/"));
};
deletePost();
window.alert("Post Successfully Deleted.");
}
};
const handleChange = (event) => {
console.log(event.target.value);
setInput((prev) => {
return {
...prev,
[event.target.name]: event.target.value,
};
});
};
return (
<div>
{post ? (
<div className="update-container">
<h2>Update Post</h2>
<div>
<input
name="title"
className="title"
placeholder="Title"
type="text"
value={input.title}
onChange={handleChange}
/>
</div>
<div>
<textarea
name="description"
placeholder="Text (Optional)"
className="description"
value={input.description}
onChange={handleChange}
></textarea>
</div>
{post.image_ids ? (
<div className="images-container">
{post.image_ids.map((image, index) => {
return (
<div key={index} className="image-upload">
<img
className="image"
src={`https://jansememwvnogkysxstd.supabase.co/storage/v1/object/public/images/${post.user_id}/${post.id}/${image}`}
/>
</div>
);
})}
</div>
) : null}
<div className="update-buttons">
<button className="button delete" onClick={deleteConfirmation}>
Delete
</button>
<button
disabled={input.title.length < 1}
className="button"
onClick={updatePost}
>
Update
</button>
</div>
</div>
) : null}
</div>
);
};
export default UpdatePost;
|
import type { RenderResult, fireEvent } from '@testing-library/svelte';
import type { SvelteComponentDev } from "svelte/internal";
import { Extension, ExtensionBlocks, ExtensionMenuDisplayDetails, NonEmptyArray, InternalButtonKey, } from "$common";
import Runtime from "$root/packages/scratch-vm/src/engine/runtime";
import { expect } from '@jest/globals';
import { BlockRunner } from './BlockRunner';
export type AnyExtension = Extension<ExtensionMenuDisplayDetails, ExtensionBlocks>;
export type BlockKey<T extends AnyExtension> = keyof T["BlockFunctions"] & string;
export type KeyToBlockIndexMap = Map<string, number>;
export interface ExtensionConstructor<T extends AnyExtension> {
new(...args: ConstructorParameters<typeof Extension>): T;
}
export type TestHelper = {
expect: typeof expect,
fireEvent: typeof fireEvent,
updateInputValue: (input: HTMLInputElement, value: string) => Promise<boolean>,
}
type ReturnsValue<T extends AnyExtension, Key extends BlockKey<T>> =
ReturnType<T["BlockFunctions"][Key]> extends void | Promise<void> | InternalButtonKey
? false
: true;
type ReportedValue<T extends AnyExtension, Key extends BlockKey<T>> = ReturnType<T["BlockFunctions"][Key]>;
export type Hooks<T extends AnyExtension, Key extends BlockKey<T>> = {
/**
* Ran before the begining of a test
* @param this
* @param extension
* @returns Nothing (but can be implemented as an async function)
*/
before?: (this: TestHelper, extension: T) => void | Promise<void>,
/**
* Ran after the conclusion of a test, and thus is the best place to put test cases.
* @param this `this` refers to a TestHelper object
* @param extension The instance of the extension under test that the block function was called on
* @param result (If the block function under test returns a value) the returned value of the block function under test
* @param ui
* @returns Nothing (but can be implemented as an async function)
*/
after?: ReturnsValue<T, Key> extends false
? (this: TestHelper, extension: T, ui?: RenderedUI) => void | Promise<void>
: (this: TestHelper, extension: T, result: ReportedValue<T, Key>, ui?: RenderedUI) => void | Promise<void>
};
export type InputArray<T extends AnyExtension, Key extends BlockKey<T>> =
Parameters<T["BlockFunctions"][Key]> extends NonEmptyArray<any>
? readonly [...Parameters<T["BlockFunctions"][Key]>]
: [];
export type Input<T extends AnyExtension, Key extends BlockKey<T>> =
Parameters<T["BlockFunctions"][Key]> extends NonEmptyArray<any>
? {
/**
* The input(s) that the block function (or "operation") under test should be given.
* If the block function takes one argument, then this will be a single value.
* If the block function takes multiple arguments, then this field will be an array of values.
*/
input: Parameters<T["BlockFunctions"][Key]> extends { length: 1 }
? Parameters<T["BlockFunctions"][Key]>[0]
: readonly [...Parameters<T["BlockFunctions"][Key]>]
}
: {};
export type Expected<T extends AnyExtension, Key extends BlockKey<T>> =
ReturnsValue<T, Key> extends true
? {
/**
* The expected value returned by the block function (or "operation") under test.
* At the conclusion of the test, this value will be compared to the actual value returned (or "reported") by the function under test.
*/
expected: ReportedValue<T, Key>
}
: {};
export type EnsureReady<T extends AnyExtension> = {
/**
* Function invoked periodically before a test begins.
* Once this function returns true (if defined), the test will begin.
* @param extension
* @returns
*/
isReady?: (extension: T) => boolean;
/**
* How often (in ms) to invoke the isReady function.
* If not defined, a rate of 100ms will be used.
*/
checkIsReadyRate?: number;
};
export type BlockTestCase<T extends AnyExtension, Key extends BlockKey<T>> =
Hooks<T, Key> &
EnsureReady<T> &
Input<T, Key> &
Expected<T, Key>;
export type SingleOrArray<T> = T | T[];
export type ObjectOrFunc<T, Args extends any[]> = T | ((...args: Args) => T);
export type GetTestCase<T extends AnyExtension, K extends BlockKey<T>> = (helper: TestHelper) => BlockTestCase<T, K>;
export type TestCaseEntry<T extends AnyExtension, K extends BlockKey<T>> = ObjectOrFunc<BlockTestCase<T, K>, Parameters<GetTestCase<T, K>>>;
export type UnitTests<T extends AnyExtension> = { [k in BlockKey<T>]?: SingleOrArray<ObjectOrFunc<BlockTestCase<T, k>, Parameters<GetTestCase<T, k>>>> };
export type RenderedUI = RenderResult<SvelteComponentDev, typeof import("/Users/parkermalachowsky/MIT/prg-extension-boilerplate/extensions/testing/node_modules/@testing-library/dom/types/queries")>;
export type RuntimeForTest<T extends AnyExtension> = Runtime & {
forTest: {
extension: T,
UIPromise: Promise<RenderedUI>;
}
}
export type IntegrationTest<T extends AnyExtension> = (blockrunner: BlockRunner<T>, helper: TestHelper) => void | Promise<void>;
|
<?php
namespace App\Controller;
use App\Entity\Productoscarrito;
use App\Repository\CarritoRepository;
use App\Repository\ProductoRepository;
use App\Repository\ProductoscarritoRepository;
use App\Repository\UsuarioRepository;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\SerializerInterface;
class CarritoController extends AbstractController
{
#[Route("/carrito/usuario/{idUsuario<\d+>}", methods: ["GET"])]
public function getCarritoUsuario(int $idUsuario, ProductoscarritoRepository $productoscarritoRepository, SerializerInterface $serializer, CarritoRepository $carritoRepository)
{
$idCarrito = $carritoRepository->findByUsuario($idUsuario)->getId();
$carrito = $productoscarritoRepository->findByCarrito($idCarrito);
$carritoJson = $serializer->serialize($carrito, 'json');
return new Response($carritoJson, Response::HTTP_OK, [
'Content-Type' => 'application/json'
]);
}
#[Route("/productocarrito/crear/{idUsuario<\d+>}/{idProducto<\d+>}", methods: ["PUT", "PATCH"])]
public function addProductoCarrito(int $idUsuario, int $idProducto, CarritoRepository $carritoRepository, ProductoRepository $productoRepository, ProductoscarritoRepository $productoscarritoRepository, Request $request)
{
$data = json_decode($request->getContent(), true);
$carrito = $carritoRepository->findByUsuario($idUsuario);
$producto = $productoRepository->find($idProducto);
$cantidad = intval($data["cantidad"]);
if ($producto->getStock() < $cantidad) {
return new JsonResponse([
"error" => "No se ha podido añadir el producto al carrito: El artículo " . $producto->getNombre() . " no está disponible"
], Response::HTTP_CONFLICT);
}
$productosCarrito = $productoscarritoRepository->findOneBy([
'carrito' => $carrito,
'producto' => $producto
]);
if ($productosCarrito) {
$nuevaCantidad = $productosCarrito->getCantidad() + $cantidad;
if ($producto->getStock() < $nuevaCantidad) {
return new JsonResponse([
"error" => "No se ha podido añadir el producto al carrito: No hay suficiente stock del artículo " . $producto->getNombre()
], Response::HTTP_CONFLICT);
}
$productosCarrito->setCantidad($nuevaCantidad);
} else {
$productosCarrito = new Productoscarrito();
$productosCarrito->setCarrito($carrito);
$productosCarrito->setProducto($producto);
$productosCarrito->setCantidad($cantidad);
}
$productoscarritoRepository->add($productosCarrito, true);
return new JsonResponse(["status" => "Producto añadido al carrito"], Response::HTTP_OK);
}
#[Route("/productocarrito/modificar/{idUsuario<\d+>}/{idProducto<\d+>}", methods: ["PUT", "PATCH"])]
public function updateProductoCarrito(int $idUsuario, int $idProducto, CarritoRepository $carritoRepository, ProductoRepository $productoRepository, ProductoscarritoRepository $productoscarritoRepository, Request $request)
{
$data = json_decode($request->getContent(), true);
$carrito = $carritoRepository->findByUsuario($idUsuario);
$producto = $productoRepository->find($idProducto);
$cantidad = intval($data["cantidad"]);
if ($producto->getStock() < $cantidad) {
return new JsonResponse([
"error" => "No se ha podido añadir el producto al carrito: El artículo " . $producto->getNombre() . " no está disponible"
], Response::HTTP_CONFLICT);
}
$productosCarrito = $productoscarritoRepository->findOneBy([
'carrito' => $carrito,
'producto' => $producto
]);
if ($producto->getStock() < $cantidad) {
return new JsonResponse([
"error" => "No se ha podido modificar el producto al carrito: No hay suficiente stock del artículo " . $producto->getNombre()
], Response::HTTP_CONFLICT);
}
$productosCarrito->setCantidad( $cantidad);
$productoscarritoRepository->add($productosCarrito, true);
return new JsonResponse(["status" => "Producto modificado"], Response::HTTP_OK);
}
#[Route("/productocarrito/eliminar/{idUsuario<\d+>}/{idProducto<\d+>}", methods: ["DELETE"])]
public function removeProductoPedido(int $idUsuario, int $idProducto, CarritoRepository $carritoRepository, ProductoRepository $productoRepository, ProductoscarritoRepository $productoscarritoRepository)
{
$carrito = $carritoRepository->findByUsuario($idUsuario);
$producto = $productoRepository->find($idProducto);
$productosCarrito = $productoscarritoRepository->find([
'producto' => $producto,
'carrito' => $carrito
]);
;
$productoscarritoRepository->removeProductosCarrito($productosCarrito, true);
return new JsonResponse(["status" => "Producto eliminado del carrito"], Response::HTTP_OK);
}
#[Route("/carrito/eliminar/usuario", methods: ["DELETE"])]
public function eliminarCarritoUsuario(Request $request, CarritoRepository $carritoRepository, ProductoscarritoRepository $productoscarritoRepository, UsuarioRepository $usuarioRepository)
{
$data = json_decode($request->getContent(), true);
$carrito = $carritoRepository->findByUsuario($data["idUsuario"]);
$productos = $productoscarritoRepository->findByCarrito($carrito->getId());
foreach ($productos as $producto) {
$productoscarritoRepository->removeProductosCarrito($producto, true);
}
return new Response(Response::HTTP_OK);
}
}
|
package main
import (
"crypto/sha1"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"sort"
"strings"
"time"
)
func main() {
var domain, port, sni string
flag.StringVar(&domain, "domain", "", "Domain to connect to")
flag.StringVar(&port, "port", "443", "Override port to connect to")
flag.StringVar(&sni, "sni", "", "Override SNI domain (default matches -domain)")
var printJSON bool
flag.BoolVar(&printJSON, "json", false, "Print all cert information as JSON")
flag.Parse()
if sni == "" {
sni = domain
}
var conf = tls.Config{
InsecureSkipVerify: true,
ServerName: sni,
}
conn, err := tls.Dial("tcp", domain+":"+port, &conf)
if err != nil {
log.Fatal(err.Error())
}
defer conn.Close()
var certs = conn.ConnectionState().PeerCertificates
for _, cert := range certs {
if printJSON {
json.NewEncoder(os.Stdout).Encode(cert)
os.Exit(0)
}
var sans = cert.DNSNames
sort.Strings(sans)
fmt.Printf("Fingerprint:\t%s\n", strings.ReplaceAll(fmt.Sprintf("SHA1=% X", sha1.Sum(cert.Raw)), " ", ":"))
fmt.Printf("Issuer:\t\t%s\n", cert.Issuer.String())
fmt.Printf("Subject:\t%s\n", cert.Subject.String())
fmt.Printf("Subject Alternative Names:\n")
for _, san := range sans {
fmt.Printf("\t%s\n", san)
}
fmt.Printf("Start Date:\t%s\n", cert.NotBefore.Format("2006-01-02"))
fmt.Printf("End Date:\t%s\n", cert.NotAfter.Format("2006-01-02"))
fmt.Printf("Remaining Days:\t%d\n", int(time.Until(cert.NotAfter).Hours()/24))
// Stop after first cert. Subsequent certs are intermediate or root CAs.
os.Exit(0)
}
}
|
#! /usr/bin/env python3
import collections
import http.client
import json
import os
import re
import socket
import sys
import time
def map_task(
input_file: str | list[str],
map_task_id: int,
num_reduce_tasks: int,
output_dir: str = "intermediate",
):
# Open the input file
if type(input_file) == str:
input_file = [input_file]
for file in input_file:
with open(file, "r") as f:
data = f.read()
# Split the text into words
words = re.findall(r"\w+", data)
print(f"map task processing file {file} with {len(words)} words")
# Create a bucket for each reduce task
buckets = [[] for _ in range(num_reduce_tasks)]
# Assign each word to a bucket
for word in words:
bucket_id = ord(word[0].lower()) % num_reduce_tasks
buckets[bucket_id].append(word)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Write each bucket to an intermediate file
for bucket_id, bucket in enumerate(buckets):
with open(f"{output_dir}/mr-{map_task_id}-{bucket_id}", "a") as f:
for word in bucket:
f.write(word + "\n")
def reduce_task(
bucket_id: int,
map_task_ids: list[int],
input_dir: str = "intermediate",
output_dir: str = "out",
):
# Initialize a counter for word frequencies
word_counts = collections.Counter()
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Process each intermediate file for this bucket
for map_task_id in map_task_ids:
with open(f"{input_dir}/mr-{map_task_id}-{bucket_id}", "r") as f:
words = f.read().splitlines()
print(
f"reduce task processing file mr-{map_task_id}-{bucket_id} with {len(words)} words"
)
word_counts.update(words)
# Write the word counts to the output file
with open(f"{output_dir}/out-{bucket_id}", "w") as f:
for word, count in word_counts.items():
f.write(f"{word} {count}\n")
def parse_args() -> tuple[str, int, int]:
if len(sys.argv) == 1:
print("driver host and port not specified, use default localhost:8080")
return "localhost", 8080, 0
if len(sys.argv) != 4:
print("Usage: python3 worker.py <driver_host> <driver_port> <delay_seconds>")
sys.exit(0)
return (sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
def run(host: str, port: int, delay_seconds: int):
while True:
try:
conn = http.client.HTTPConnection(host=host, port=port)
conn.request("GET", "/get_task")
response = conn.getresponse()
data = response.read()
resp = json.loads(data)
if resp["task_type"] == "map":
map_task(resp["input_files"], resp["task_id"], resp["num_reduce_tasks"])
elif resp["task_type"] == "reduce":
reduce_task(resp["bucket_id"], resp["map_task_ids"])
else:
print(f"unknown task type {resp['task_type']}, skip")
time.sleep(delay_seconds)
except Exception as e:
print("driver closed")
break
def wait_driver_start():
while True:
try:
print("check driver start")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as ss:
ss.connect(("localhost", 8080))
ss.close()
print("driver started")
break
except Exception as e:
print("driver not started, wait 1 second")
time.sleep(1)
pass
def wait_driver_exit():
# wait for dirver exit
while True:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as ss:
ss.connect(("localhost", 8080))
ss.close()
print("dirver not exit, wait 1 second")
time.sleep(1)
except Exception as e:
print("driver closed, worker exit")
break
if __name__ == "__main__":
driver_addr, driver_port, delay_seconds = parse_args()
wait_driver_start()
run(driver_addr, driver_port, delay_seconds)
wait_driver_exit()
|
//
// passwordStrengthService.swift
// password strength meter
//
// Created by Omar Diab on on 9/17/21.
//
import Foundation
let REGEX_PASSWORD_ONE_UPPERCASE = "^(?=.*[A-Z]).*$"
let REGEX_PASSWORD_ONE_LOWERCASE = "^(?=.*[a-z]).*$"
let REGEX_PASSWORD_ONE_NUMBER = "^(?=.*[0-9]).*$"
let REGEX_PASSWORD_ONE_SYMBOL = "^(?=.*[-_]).*$"
public enum PasswordStrengthType {
case weak, moderate, strong
}
@objc open class passwordStrengthService: NSObject{
static let singletonInstance = passwordStrengthService()
public func checkPasswordStrength(_ password: String?) -> PasswordStrengthType {
let len = password?.count ?? 0
var strength = 0
if len == 0 {
return PasswordStrengthType.weak
} else if len <= 5 {
strength += 1
} else if len <= 10 {
strength += 2
} else {
strength += 3
}
strength += validate(password, withPattern: REGEX_PASSWORD_ONE_UPPERCASE, caseSensitive: true)
strength += validate(password, withPattern: REGEX_PASSWORD_ONE_LOWERCASE, caseSensitive: true)
strength += validate(password, withPattern: REGEX_PASSWORD_ONE_NUMBER, caseSensitive: true)
strength += validate(password, withPattern: REGEX_PASSWORD_ONE_SYMBOL, caseSensitive: true)
if strength <= 3 {
return PasswordStrengthType.weak
} else if 3 < strength && strength < 6 {
return PasswordStrengthType.moderate
} else {
return PasswordStrengthType.strong
}
}
func validate(_ string: String?, withPattern pattern: String?, caseSensitive: Bool) -> Int {
var regex: NSRegularExpression? = nil
do {
regex = try NSRegularExpression(pattern: pattern!, options: NSRegularExpression.Options(rawValue: ((caseSensitive) ? 0 : NSRegularExpression.Options.caseInsensitive.rawValue)))
} catch {
return 0
}
let textRange = NSRange(location: 0, length: string?.count ?? 0)
let matchRange = regex?.rangeOfFirstMatch(in: string ?? "", options: .reportProgress, range: textRange)
var didValidate = 0
if matchRange?.location != NSNotFound {
didValidate = 1
}
return didValidate
}
}
|
import { existsSync, readFileSync } from "node:fs";
import { Worker } from "node:worker_threads";
import { execa } from "execa";
import { watch } from "chokidar";
import type { BuildOptions } from "esbuild";
import { context } from "esbuild";
import { join, resolve } from "pathe";
import { debounce } from "perfect-debounce";
import { colors as c } from "consola/utils";
import { log } from "src/core/utils";
import type { Config } from "./types";
const ignored = existsSync(join(".gitignore"))
? readFileSync(join(".gitignore"), { encoding: "utf8" }).split("\n").filter(Boolean)
: undefined;
const watcher = async (dir: string, reload: () => Promise<void>, dispose?: () => Promise<void>) => {
const w = watch(dir, {
cwd: process.cwd(),
ignoreInitial: true,
ignored: [
// Hidden directories like .git
"**/.*/**",
// Hidden files (e.g. logs or temp files)
"**/.*",
// Built files
"**/dist/**",
// 3rd party packages
"**/{node_modules,bower_components,vendor,target}/**",
// .gitignore
...ignored!,
],
})
.on("ready", async () => {
log.start(`Started server, listening for changes...`);
log.ready(`🦌 Press: ${c.green(c.bold("r"))} to reload • ${c.red(c.bold("q"))} to quit`);
await reload();
})
.on("change", async (path) => {
log.info(`[dev:watcher:change]: ${path}`);
await reload();
})
.on("error", (error) => log.error("[dev:watcher:error]", error));
process.stdin
.setRawMode(true)
.resume()
.setEncoding("utf-8")
.on("data", async (key: string) => {
switch (key) {
case "\u0071":
case "\u0003":
log.info("Exiting.");
await w.close();
dispose ? await dispose() : undefined;
process.exit(0);
case "\u0072":
log.info("Reloading.");
await reload();
break;
default:
break;
}
process.stdout.write(key);
});
};
interface BuildContext {
config: Config;
dir: string;
day: string;
}
export async function createBuildContext(ctx: BuildContext) {
if (ctx.config.days[Number(ctx.day)].runner !== null) {
const [cmd, ...cmdArgs] = ctx.config.days[Number(ctx.day)].runner!.split(" ");
const reload = debounce(async () => {
try {
const { stdout } = await execa(cmd, cmdArgs, { cwd: resolve(ctx.dir) });
console.log(stdout);
} catch (error) {
log.error(`The command failed. stderr: ${error.stderr} (${error.exitCode})`);
}
});
await watcher(ctx.dir, reload);
} else {
// Copied all from rose but removed references to it because I still haven't finished it lol
const buildConfig: BuildOptions = {
entryPoints: [join(ctx.dir, "index.ts")],
format: "esm",
platform: "node",
bundle: true,
outfile: join(ctx.dir, "dist", "index.js"),
};
const build = await context(buildConfig);
let worker: Worker | null = null;
function createWorker(): void {
if (worker) {
return;
}
worker = new Worker(resolve(buildConfig.outfile!), {
execArgv: ["--enable-source-maps"],
workerData: {},
stderr: true,
});
worker.on("error", (error) => {
// Handle errors in the worker
const newErr = new Error(`[dev:worker:error] ${error.message}`);
newErr.stack = error.stack;
log.error(newErr);
});
worker.stderr.on("error", (error) => {
// Handle errors in stderr
const newErr = new Error(`[dev:stderr:error] ${error.message}`);
newErr.stack = error.stack;
newErr.cause = error.cause;
log.error(newErr);
});
worker.once("exit", () => {
worker = null;
});
log.debug("Worker created.");
}
function deleteWorker(): void {
if (worker) {
worker.removeAllListeners();
worker.terminate();
worker = null;
} else null;
}
const reload = debounce(async () => {
deleteWorker();
await build
.rebuild()
.then(() => createWorker())
.catch((error) => log.error(error));
});
await watcher(ctx.dir, reload, build.dispose);
}
}
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../controllers/layout_cubit/layout_cubit.dart';
import '../../../core/network/local/sql_server.dart';
import '../../../core/network/remote/api_constant.dart';
import '../../../core/routes/app_routers.dart';
import '../../../core/style/icon_broken.dart';
import '../../../core/utils/app_size.dart';
import '../../../core/utils/screen_config.dart';
class RefCodeScreen extends StatelessWidget {
const RefCodeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
actions: [
IconButton(
onPressed: () => _buildExitDialog(context),
icon: const Icon(IconBroken.Logout, color: Colors.black),
),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'you can get ref code from here',
style: Theme.of(context).textTheme.titleLarge,
),
AppSize.sv_15,
Text(
'The ref code is:',
style: Theme.of(context).textTheme.displayLarge,
),
AppSize.sv_20,
Container(
padding: const EdgeInsets.all(20.0),
width: SizeConfig.screenWidth * .8,
decoration: BoxDecoration(
color: Colors.grey.shade200,
borderRadius: BorderRadius.circular(10.0),
),
child: Center(
child: Text(
ApiConstant.refCode,
style: Theme.of(context).textTheme.displayLarge!.copyWith(
fontSize: 23.0,
),
),
),
),
],
),
),
);
}
_buildExitDialog(BuildContext context) {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: const Text(
'Are you sure not completed the pay',
style: TextStyle(
fontSize: 14.0,
),
),
actions: [
TextButton(
onPressed: () {
SqliteServiceDatabase().deleteAllItems('cart').then((value) {
BlocProvider.of<LayoutCubit>(context).currentIndex = 0;
});
Navigator.pop(context);
Navigator.pushNamedAndRemoveUntil(
context,
Routers.LAYOUT_SCREEN,
(route) => false,
);
},
child: const Text('Yes'),
),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('No'),
),
],
);
},
);
}
}
|
import React from "react";
import { useState } from "react";
import { withRouter } from 'react-router-dom'
import { useDispatch } from "react-redux";
import { useHistory } from "react-router";
import { toast } from "react-toastify";
import { clearLoginData } from "../../redux/Actions/auth";
import "./navBar.css";
const NavBar = ({ showButton, location: { pathname }, history: { push } }) => {
const [showLogout, setShow] = useState(false);
const history = useHistory();
const dispatch = useDispatch();
const userData = JSON.parse(localStorage.getItem("userData"));
const handleClick = () => {
history.push("/login");
};
const handleLogout = () => {
localStorage.clear();
dispatch(clearLoginData());
toast.dark("Logged out successfully");
history.push("/login");
};
return (
<nav className="navContainer">
<span className="my">
My<span className="jobs">Jobs</span>
</span>
{showButton &&
(userData ? (
<div className="loggedInUserWrapper">
<button
className={`postJobLink ${pathname.includes('post-job') ? 'postJobLinkSeleted' : ''}`}
onClick={() => push('/console/post-job')}
>
Post a Job
</button>
<div className="loggedInUser">
{userData.name.charAt(0).toUpperCase()}
</div>
<i
className="fa fa-caret-down drop-icon"
aria-hidden="true"
onClick={() => setShow(!showLogout)}
></i>
{showLogout && (
<div className="logout" onClick={handleLogout}>
<div className="triangle-up"></div>
</div>
)}
</div>
) : (
<button onClick={handleClick} className="loginSignup">
Login/Signup
</button>
))}
</nav>
);
};
export default withRouter(NavBar);
|
<?php
use App\Http\Controllers\AuthController;
use App\Http\Controllers\TodoController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::controller(AuthController::class)->group(function () {
Route::post('register', 'register');
Route::post('login', 'login');
});
Route::controller(TodoController::class)->group(function () {
Route::get('todos', 'index');
Route::post('todo', 'store');
Route::get('todo/{id}', 'show');
Route::put('todo/{id}', 'update');
Route::delete('todo/{id}', 'destroy');
});
Route::get("need-authenticate", function(){
return response()->json([
'status' => 'error',
'message' => 'Unauthorized',
], 401);
})->name("need-authenticate");
|
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import Button from './components/Button.jsx'
const colors = [
{
name:'Red', hex:'#FF0000'
},
{
name:'Blue', hex:'#0000FF'
},
{
name:'Yellow', hex:'#FFFF00'
},
{
name:'Green', hex:'#00FF00'
},
{
name:'Purple', hex:'#800080'
},
{
name:'Orange', hex:'#FFA500'
},
{
name:'Cyan', hex:'#00FFFF'
},
{
name:'Pink', hex:'#FFC0CB'
},
{
name:'Brown', hex:'#A52121'
},
{
name:'Teal', hex:'#008080'
},
{
name:'Indigo', hex:'#4B00B2'
},
{
name:'Lavender', hex:'#E6E6FA'
},
{
name:'Maroon', hex:'#800000'
},
{
name:'Gold', hex:'#FFd700'
},
{
name:'Olive', hex:'#808000'
},
]
function App() {
const [selectedColor, setColor] = useState(colors[1].hex);
const changeBackground=(color)=>{
setColor(color)
}
return (
<div className='h-screen p-3'
style={{background: selectedColor}}>
<div className='bg-gray-100 p-2 round-md shadow'>
{
colors.map((color)=> <Button key={color.hex} title={color.name} color={color.hex} onClick={changeBackground}/>)
}
</div>
</div>
)
}
export default App
|
from sqlalchemy.orm import sessionmaker
from sqlalchemy.types import Integer, String
from sqlalchemy import Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
engine = create_engine("mysql://cf-python:password@localhost/my_database")
Base = declarative_base()
class Recipe(Base):
__tablename__ = 'final_recipes'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(50))
ingredients = Column(String(255))
cooking_time = Column(Integer)
difficulty = Column(String(20))
def __repr__(self):
return f"<Recipe(id={self.id}, name='{self.name}', difficulty='{self.difficulty}')>"
def __str__(self):
return f"\nRecipe ID: {self.id}\n{'-'*30}\nName: {self.name}\nDifficulty: {self.difficulty}\nCooking Time: {self.cooking_time} minutes\n{'-'*30}\nIngredients:\n{self.ingredients}\n{'-'*30}"
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
def calc_difficulty(cooking_time, recipe_ingredients):
print('Run the calc_difficulty with: ', cooking_time, recipe_ingredients)
if (cooking_time < 10) and (len(recipe_ingredients) < 4):
difficulty_level = 'Easy'
elif (cooking_time < 10) and (len(recipe_ingredients) >= 4):
difficulty_level = 'Medium'
elif (cooking_time >= 10) and (len(recipe_ingredients) < 4):
difficulty_level = 'Intermediate'
elif (cooking_time >= 10) and (len(recipe_ingredients) >= 4):
difficulty_level = 'Hard'
else:
print('Something bad happened, please try again')
print('Difficulty level: ', difficulty_level)
return difficulty_level
def return_ingredients_as_list():
recipes_list = session.query(Recipe).all()
for recipe in recipes_list:
print('Recipe: ', recipe)
print('recipe.ingredients: ', recipe.ingredients)
recipe_ingredients_list = recipe.ingredients.split(', ')
print(recipe_ingredients_list)
def create_recipe():
recipe_ingredients = []
correct_input_name = False
while correct_input_name == False:
name = input('\nEnter recipe name: ')
if len(name) < 50:
correct_input_name = True
correct_input_cooking_time = False
while correct_input_cooking_time == False:
cooking_time = input('\nEnter cooking time: ')
if cooking_time.isnumeric() == True:
correct_input_cooking_time = True
else: print('Please enter a number')
else:
print('Please enter a name that contains less than 50 characters')
correct_input_number = False
while correct_input_number == False:
ingredient_num = input('How many ingredients do you want to enter?: ')
if ingredient_num.isnumeric() == True:
correct_input_number = True
for _ in range(int(ingredient_num)):
ingredient = input('Enter an ingredient: ')
recipe_ingredients.append(ingredient)
else:
correct_input_number = False
print('Please enter a positive number')
recipe_ingredient_str = ', '.join(recipe_ingredients)
print(recipe_ingredient_str)
difficulty = calc_difficulty(int(cooking_time), recipe_ingredients)
recipe_entry = Recipe(
name = name,
cooking_time = int(cooking_time),
ingredients = recipe_ingredient_str,
difficulty = difficulty
)
print(recipe_entry)
session.add(recipe_entry)
session.commit()
print('Recipe saved!')
def view_all_recipes():
all_recipes = []
all_recipes = session.query(Recipe).all()
if len(all_recipes) == 0:
print('recipe not found')
return None
else:
print('\nShowing all Recipes')
for recipe in all_recipes:
print(recipe)
def search_by_ingredients():
if session.query(Recipe).count() == 0:
print('recipe does not exist')
return None
else:
results = session.query(Recipe.ingredients).all()
print('results: ', results)
all_ingredients = []
for recipe_ingredients_list in results:
for recipe_ingredients in recipe_ingredients_list:
recipe_ingredient_split = recipe_ingredients.split(', ')
all_ingredients.extend(recipe_ingredient_split)
print('all_ingredients after the loop: ', all_ingredients)
all_ingredients = list(dict.fromkeys(all_ingredients))
all_ingredients_list = list(enumerate(all_ingredients))
print('\nAll ingredients list')
for index, tup in enumerate(all_ingredients_list):
print(str(tup[0]+1) + '. ' + tup[1])
try:
ingredient_searched_num = input(
'\nEnter the number(or numbers with a space between) of the corresponding ingredient from the list'
)
ingredients_num_list_searched = ingredient_searched_num.split(' ')
ingredient_searched_list = []
for ingredient_searched_num in ingredients_num_list_searched:
ingredient_searched_index = int(ingredient_searched_num) -1
ingredient_searched = all_ingredients_list[ingredient_searched_index][1]
ingredient_searched_list.append(ingredient_searched)
print('\nYou selected these ingredients: ', ingredient_searched_list)
conditions = []
for ingredient in ingredient_searched_list:
like_term = '%' + ingredient + '%'
condition = Recipe.ingredients.like(like_term)
conditions.append(condition)
print('conditions: ', conditions)
searched_recipes = session.query(Recipe).filter(*conditions).all()
print(searched_recipes)
except:
print('Oops, something went wrong. Make sure to select a number from the list')
else:
print('searched_recipes: ')
for recipe in searched_recipes:
print(recipe)
def edit_recipe():
if session.query(Recipe).count() == 0:
print('There are no recipes to edit')
return None
else:
results = session.query(Recipe).with_entities(Recipe.id, Recipe.name).all()
print('results: ', results)
print('List of available recipes: ')
for recipe in results:
print('\nID: ', recipe[0])
print('Name: ', recipe[1])
recipe_id_for_edit = int(
input('\nEnter the ID of the recipe you want to edit: '))
print(session.query(Recipe).with_entities(Recipe.id).all())
recipes_id_tup_list = session.query(
Recipe).with_entities(Recipe.id).all()
recipes_id_list = []
for recipe_tup in recipes_id_tup_list:
print(recipe_tup[0])
recipes_id_list.append(recipe_tup[0])
print(recipes_id_list)
if recipe_id_for_edit not in recipes_id_list:
print('Not in the ID list, please try again later')
else:
print('continuing')
recipe_to_edit = session.query(Recipe).filter(
Recipe.id == recipe_id_for_edit).one()
print('\nWARNING: You are about to edit the following recipe: ')
print(recipe_to_edit)
column_for_update = int(input(
'\nEnter the corresponding number to the item you want to edit(1. name, 2. cooking_time, 3. ingredients): '
))
updated_value = input('\nEnter your edit here: ')
print('Choice: ', updated_value)
if column_for_update == 1:
print('Updating name')
session.query(Recipe).filter(Recipe.id == recipe_id_for_edit).update(
{Recipe.name: updated_value}
)
session.commit()
elif column_for_update == 2:
print('Updating cooking time')
session.query(Recipe).filter(Recipe.id == recipe_id_for_edit).update(
{Recipe.cooking_time: updated_value}
)
session.commit()
elif column_for_update == 3:
print('Updating ingredients')
session.query(Recipe).filter(Recipe.id == recipe_id_for_edit).update(
{Recipe.ingredients: updated_value}
)
session.commit()
else:
print("Wrong input, please try again.")
updated_difficulty = calc_difficulty(
recipe_to_edit.cooking_time, recipe_to_edit.ingredients)
print("updated_difficulty: ", updated_difficulty)
recipe_to_edit.difficulty = updated_difficulty
session.commit()
print('Update saved!')
def delete_recipe():
if session.query(Recipe).count() == 0:
print('There is nothing to delete')
return None
else:
results = session.query(Recipe).with_entities(
Recipe.id, Recipe.name).all()
print('results: ', results)
print('List of available recipes:')
for recipe in results:
print('\nID: ', recipe[0])
print('Name: ', recipe[1])
recipe_id_for_deletion = (
input('\nEnter the ID of the recipe you wish to delete: '))
recipe_to_be_deleted = session.query(Recipe).filter(
Recipe.id == recipe_id_for_deletion).one()
print('\nWARNING: you are about to delete this recipe: ')
print(recipe_to_be_deleted)
deletion_confirmed = input('\nTo confirm that you want to delete recipe enter (y/n): ')
if deletion_confirmed == 'y':
session.delete(recipe_to_be_deleted)
session.commit()
print('\nRecipe successfully deleted from the database.')
else:
return None
def main_menu():
choice = ''
while (choice != 'quit'):
print('Main Menu')
print('Pick a choice:')
print(' 1. Create a new recipe')
print(' 2. Search for a recipe by ingredient')
print(' 3. Update an existing recipe')
print(' 4. Delete a recipe')
print(' 5. view all recipes')
print("Type 'quit' to exit")
choice = input('\nYour choice: ')
if choice == '1':
create_recipe()
elif choice =='2':
search_by_ingredients()
elif choice == '3':
edit_recipe()
elif choice == '4':
delete_recipe()
elif choice == '5':
view_all_recipes()
else:
if choice == 'quit':
print('goodbye\n')
else:
print('Invalid entry, try again')
main_menu()
session.close()
|
<p id="notice">
<%= notice %>
</p>
<h1>Books</h1>
<table>
<thead>
<tr>
<th>Title</th>
<th>Body</th>
<th colspan="3"></th>
</tr>
</thead>
<% @books.each do |book| %>
<tbody>
<tr>
<td><%= book.title %></td>
<td><%= book.body %></td>
<td><%= link_to"Show",book_path(book.id) %></td>
<td><%= link_to"Edit",edit_book_path(book.id) %></td>
<td><%= link_to"Destroy", "/books/#{book.id}", method: :delete, "data-confirm" => "Are you sure?" %></td>
</tr>
</tbody>
<% end %>
</table>
<h1>New book</h1>
<% if @book.errors.any? %>
<%= @book.errors.count %>errors prohibited this book from being saved:
<% @book.errors.full_messages.each do |message| %>
<%= message %>
<% end %>
<% end %>
<!-- form_with部分 -->
<%= form_with model: @book, url:'/books', local:true do |f| %>
<div class="field">
<label for="book_title">Title</label>
<%= f.text_field :title %>
</div>
<div class="field">
<label for="book_body">Body</label>
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit 'Create Book' %>
</div>
<% end %>
|
Teorema di BOHM-JACOPINI :
---------------------
Qualunque algoritmo può essere realizzato utilizzando le sole tre strutture di controllo fondamentali:
-la sequenza(serie di istruzioni da eseguire in ordine)
-la selezione(scelta binaria)
-il ciclo(loop nel quale vengono ripetute istruzioni)
ARRAY:
----------------------
Sequenza di locazioni di memoria riservata ad una serie di dati dello stesso tipo. Gli elementi si numerano consecutivamente con espressioni intere che assumono valori da 0 a n-1 (con n=dimensione dell'array) e possiamo accedere all'i-esimo elemento di un vettore 'vet' con la sintassi vet[i-1];
Questi numeri si dicono indici dell’array, ed il loro ruolo è quello di localizzare la posizione di ogni
elemento dentro l’array, fornendo acceso diretto ad esso. Il nome del vettore è l'indirizzo in memoria del primo elemento(il suo puntatore) e si può usare l'aritmetica dei puntatori per accedere agli altri elementi sfruttando il nome del vettore e sommando un'espressione intera per ottenere il puntatore ad un altro elemento dell'array.
Il tipo di elementi immagazzinati nell'array può essere sia built-in che un tipo user-defined.
PUNTATORI E REFERENCE:
-----------------------
Sia i puntatori che i riferimenti possono essere usati per riferirsi agli oggetti indirettamente. Sostengono
essenzialmente gli indirizzi di memoria come valori. Il differenza fondamentale tra un puntatore e un
riferimento è quello un puntatore è una variabile che memorizza l'indirizzo della posizione di memoria di
un'altra variabile mentre un reference è una variabile che fa riferimento a un'altra variabile(alias).
I due meccanismi, il pointer e reference, hanno sintassi e utilizzo diversi.
-Sia puntatori che reference sono stati concepiti per limitare l'overhead (risorse accessorie, ma necessarie,
per ottenere un determinato scopo)
-Un puntatore può essere nullo, nel senso che non mantiene l'indirizzo di alcuna variabile o potrebbe non
essere inizializzato
-Un reference deve essere inizializzato contestualmente alla sua dichiarazione
-Un puntatore può puntare ad un altra variabile
-Un reference invece non può cambiare oggetto di riferimento
-La sintassi per un puntatore può essere tediosa
-La sintassi per un reference è molto più intuitiva
-Per la creazione di una collezione di oggetti vengono utilizzati i puntatori e non è possibile sostituirli
con i reference
-Passaggio di parametri per riferimento permette di passare l'indirizzo di una variabile e quindi ne modifica
lo stato
-Puntatori utilizzati per allocazioni dinamiche della memoria(heap o free store).
ALLOCAZIONE DELLA MEMORIA:
--------------------------
Scegliere come allocare la memoria per una variabile dipende dal tipo di problema che si deve risolvere.
Vi sono vari tipi di allocazione per collocare variabili in diversi segmenti di memoria:
https://www.youtube.com/watch?v=m9cm5MpP9nA&list=PL83Ordjpzm5oUl7tFEjc4iirkPBiv7FxR&index=14
-Allocazione STATICA:
----------------------
La quantità di memoria da allocare è determinata e fissata a tempo di compilazione(compile time). Una variabile allocata staticamente viene collocata nello stack. La memoria allocata staticamente viene liberata quando termina il ciclo di vita della variabile, ciò rende impossibile ad una funzione, per esempio, il ritorno di un vettore allocato staticamente al suo interno.
-Allocazione DINAMICA:
----------------------
Permette di definire variabili che possono essere create o accresciute in fase di esecuzione(run time).
Una variabile allocata dinamicamente viene collocata nello heap(free store). La memoria occupata allocando dinamicamente NON viene restituita quando termina il ciclo di vita delle variabili che invece permangono nella RAM. Si alza il rischio di memory leak (consumo non voluto di memoria dovuto alla mancata deallocazione dalla memoria), quindi è buona norma deallocare manualmente la memoria precedentemente occupata. Questo tipo di allocazione si rende necessaria per il ritorno di vettori da parte di una funzione.
NB. La deallocazione di una variabile indica al compilatore che quella porzione di memoria diventa
utilizzabile e che quindi può essere sovrascritta, ma il suo contenuto non viene immediatamente
cancellato.
-Variabili AUTOMATICHE:
Le variabili automatiche sono variabili locali in un blocco di istruzioni. Esse sono automaticamente allocate sullo stack quando si entra in quel blocco di codice e parallelamente, vengono distrutte quando si esce dal blocco stesso.
-Variabili GLOBALI:
Una variabile globale viene inizializzata contestualmente alla propria dichiarazione (a zero se non si specifica), ha uno scope esteso a tutto il programma dal punto in cui viene dichiarata.
Una variabile locale dichiarata "static" diventa a tutti gli effetti una variabile globale (per lo scope e perchè viene inizializzata una sola volta)
CONST
-------
Per rendere un riferimento di sola letture (renderlo read-only) si usa la keyword const. Nel caso di un
oggetto referenziato da un read-only reference, esso non potrà invocare metodi che ne modificano lo
stato interno, mentre per comunicare al compilatore che un metodo è di sola lettura si aggiunge "const" dopo
la lista di parametri. Utile l'utilizzo nei metodi getter(aumenta la sicurezza del codice).
STATIC
-------
Attributo:
La parola static può essere utilizzata per dichiarare delle variabili di classe. Queste sono diverse dalle
variabili (o attributi)di istanza. Ogni oggetto ha una sua copia delle variabili di istanza. Le variabili di
classe sono invece condivise tra tutte le istanze di una data classe.
Non è possibile inizializzare un attributo di classe ma l’inizializzazione è comunque obbligatoria e va
fatta “fuori” dalla definizione della classe.
Metodi Static
I metodi static sono dei metodi il cui funzionamento non dipende dallo stato dell’istanza. Se un metodo non
dipende dallo stato, ma solo da una variabile static, quindi può essere definito come static.
Dato che l’esecuzione di un metodo statico non dipende da una specifica istanza, posso anche richiamare un
metodo statico anche in maniera indipendente da una istanza (es. Classe::getCount(); )
FRIEND
-------
usata per dare accesso ad una classe "amica" a tutti i contenuti private della classe. La friendship non è
una proprietà simmetrica, infatti se una classe X è friend di Y, non è necessariamente vero anche il contrario.
OVERLOADING
--------------------
C++ consente di specificare più di una funzione con lo stesso nome (funzioni overload). Esse consentono di
specificare semantiche diverse per una stessa funzione, a seconda dei tipi e del numero di argomenti.
Quindi si hanno funzioni con lo stesso nome che cambiano semantica sulla base della loro firma.
OVERRIDING
--------------------
Nella programmazione ad oggetti assume notevole importanza la possibilità di creare classi a partire da classi
già esistenti (ereditarietà). Nella programmazione ad oggetti override è l'operazione di riscrittura di un
metodo ereditato.
Si hanno quindi metodi con la stessa firma che assumono una semantica diversa sulla base dell'oggetto che li
invoca.
Principio di LISKOV:
--------------------
Un tipo S è un sottotipo di T quando è possibile sostituire tutte le istanze di T con delle istanze di S
mantenendo intatto il funzionamento del programma.
TEMPLATE
-------------------
In C++, il template implementa il concetto di tipo parametrizzato: il tipo viene specificato come se fosse
un parametro. I templates permettono di implementare classi e funzioni indipendentemente dal tipo di oggetti
su cui operano(user-defined e primitivi)
Una funzione template è una sorta di modello dal quale il compilatore genera opportune specializzazioni in
corrispondenza di chiamate a funzione con parametri differenti(si riduce il lavoro del programmatore).
Una classe template specifica una famiglia di definizioni di classi. Il tipo generico è usato per dati interni
alla classe e per i parametri e i dati locali delle funzioni membro.
Conformità di tipo
---------------------
Possibilità di assegnare ad un reference/puntatore di classe madre un oggetto di classe figlia.
OOP [object oriented programming]
---------------------
PRINCIPI DELLA OOP :
1) Astrazione
2) Incapsulamento
3) Ereditarietà
4) Polimorfismo
Astrazione :
---------------------
Generalizzare i concetti da affrontare per avere un interfaccia comune per tutti gli oggetti di quel tipo.
Incapsulamento (information Hiding) :
---------------------
Utilizzo di "modificatori di accesso" in modo che alcune informazioni risultino publiche e che altre rimangano
nascoste all'esterno e accessibili solo ai membri della classe stessa.
Ereditarietà :
---------------------
Meccanismo che consente livelli di astrazione gerarchici che consentono di conservare le proprietà della classe base nelle classi derivate.
Polimorfismo
---------------------
Possibilità di presentarsi sotto diverse forme. In questo contesto il polimorfismo rappresenta uno dei 4 principi cardine della OOP e si manifesta quando in una gerarchia ereditaria vi sono ridefinizioni dello stesso metodo (stessa firma) che ha un comportamento diverso a seconda dell'oggetto chiamante(OVERRIDING). Questo favorisce il riutilizzo del codice
POLIMORFISMO STATICO
Quando un puntare/reference di tipo di classe base punta o diventa alias di un oggetto di classe
derivata(conformità di tipo).
Si verifica lo static binding, ovvero il riconoscimento di tipo anticipato rispetto al momento dell'esecuzione.
Il compilatore cerca il metodo invocato su un oggetto del tipo che si trova d'avanti.
POLIMORFISMO DINAMICO
Il "vero" polimorfismo, nella pienezza del suo significato "filosofico", deve essere associato al"late binding":
la differenziazione di comportamento degli oggetti in risposta allo stesso messaggio non deve essere statica e
predefinita, ma dinamica, cioè deve essere determinata dal contesto del programma in fase di esecuzione.
Vedremo che ciò é realizzabile solo nell'ambito di una stessa famiglia di classi, e quindi il "vero" polimorfismo NON può prescindere dall'eredità e si applica a funzioni-membro, con lo stesso nome e gli stessi argomenti, che appartengono sia alla classe base che alle sue derivate.
Per ottenere il polimorfismo dinamico si utilizza la keyword "virtual" per etichettare il metodo della classe madre che non verrà mai realmente invocato e si indica nei metodi delle classi figlie che sono "override".
L'applicazione della parola chiave virtual ai metodi di una classe consente di condizionare l'esecuzione del codice secondo il tipo dell'istanza oggetto cui si fa riferimento.
Se le funzioni della interfaccia sono dichiarate VIRTUAL, si ottiene il polimorfismo a run-time.
Il costruttore non è mai virtual mentre per favorire una riduzione del memory leak è utile spesso dichiarare il distruttore come virtual.
Overriding + virtual = Polimorfimo dinamico (a tempo di esecuzione).
• Il polimorfismo a tempo di esecuzione avviene mediante puntatori e/o reference, in presenza dei quali, al compilatore non sarà noto il tipo di oggetto referenziato.
FUNZIONE VIRTUALE PURA
---------------------
In certi casi non è possibile dare una definizione di base di un metodo nella classe madre, si parla allora di metodi virtuali puri, ovvero il significato di quel metodo deve essere necessariamente ridefinito nelle classi figlie affinchè possa essere istanziato correttamente l'oggetto.
• Una classe con una o più funzioni virtuali pure si dice classe astratta
• Non si possono creare istanze di una classe astratta.
• È comunque possibile dichiarare puntatori e reference a tipi astratti.
• Se una classe derivata non fornisce l’implementazione di una o più funzioni virtuali pure, allora anche essa diverrà
astratta;
INTERFACCIA
---------------------
Una classe base astratta che contiene solamente:
1) attributi costanti
2) funzioni virtuali pure si dice Interfaccia.
In un interfaccia nessun comportamento è definito, ma semplicemente dichiarato (solo specifiche senza implementazione).
RTTI
---------------------
La RTTI (RunTime Type Information o RunTime Type Identification) consente ai programmi che manipolano puntatori e riferimenti ad oggetti di una classe base, di determinare il tipo dell'oggetto durante l'esecuzione invece che solo al momento della compilazione. Per invocare un metodo su un'istanza il cui tipo verrà determinato a
run time si possono utilizzare due strategie:
1) DYNAMIC CAST + CONTROLLO dell'esistenza del puntatore per capire se il cast è avvenuto con successo
2) TYPEID() + STATIC CAST
|
import React, { useState, useEffect, useRef } from "react";
import { useStore } from "@nanostores/react";
import { isDarkMode } from "../store";
import type { SectionName } from "../types";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faArrowUp, faEnvelope, faMoon, faSun, faCircle } from "@fortawesome/free-solid-svg-icons";
import { faLinkedin, faGithub } from "@fortawesome/free-brands-svg-icons";
import '@fortawesome/fontawesome-svg-core/styles.css';
import "../styles/Header.scss";
const allSections = ["about", "experience", "projects", "skills"] as const;
interface RightSectionProps {
where: string;
}
function DarkModeSwitch({ where }: RightSectionProps) {
const enabled = useStore(isDarkMode);
if (typeof window === "undefined") {
return null;
}
return (
<span className={`darkmode-${where} darkmode-switch-container`}>
<span
style={{ justifyContent: enabled ? "flex-end" : "flex-start" }}
onClick={() => isDarkMode.set(!enabled)}
className="darkmode-switch"
>
<div className="darkmode-switch-circle">
{enabled
? <FontAwesomeIcon icon={faMoon} fixedWidth className="darkmode-moon" />
: <FontAwesomeIcon icon={faSun} fixedWidth className="darkmode-sun" />
}
</div>
</span>
</span>
);
}
export default function Header() {
const [atTop, setAtTop] = useState(false);
const [currentSection, setCurrentSection] = useState("about");
const titlebarRef = useRef<HTMLDivElement>(null);
const navbarRef = useRef<HTMLDivElement>(null);
function scrollToSection(id: SectionName | "top") {
const elem = id === "top"
? document.getElementById("header")!
: document.getElementById(`${id}-scroll-target`)!;
elem.scrollIntoView({ behavior: "smooth" });
}
useEffect(() => {
const sectionTops: { elementTop: number, sectionName: SectionName }[] = [];
for (const sectionName of allSections.slice().reverse()) {
const elementTop = document.getElementById(`${sectionName}-scroll-target`)!.offsetTop;
sectionTops.push({ elementTop, sectionName });
}
function nav() {
const y = window.scrollY;
const titlebarHeight = titlebarRef.current?.offsetHeight!;
const putNavbarToTop = y >= titlebarHeight;
if (atTop !== putNavbarToTop) {
setAtTop(putNavbarToTop);
}
const scrolledSection = sectionTops.find(({ elementTop }) => y >= elementTop - 5)?.sectionName || "about";
if (scrolledSection !== currentSection) {
setCurrentSection(scrolledSection);
}
}
window.addEventListener("scroll", nav);
nav();
return () => window.removeEventListener("scroll", nav);
})
return (
<header id="header">
{atTop && <div style={{ height: navbarRef.current?.offsetHeight }} />}
<div ref={titlebarRef} id="titlebar">
<h1 id="title">Alex Snezhko</h1>
<div className="contact-icons-container">
<span className="navbar-links">
{allSections.map(sectionName => (
<button
key={sectionName}
className={sectionName === currentSection ? "thispage" : ""}
onClick={() => scrollToSection(sectionName)}
>
{sectionName[0].toUpperCase() + sectionName.slice(1)}
</button>
))}
</span>
<DarkModeSwitch where="navbar" />
</div>
</div>
{atTop && <div ref={navbarRef} id="navbar" className={atTop ? "at-top" : ""}>
<div className="navbar-contents">
{atTop && (
<div>
<span onClick={() => scrollToSection("top")}>
<span className="navbar-initials">Alex Snezhko</span>
<span className="navbar-to-top"><FontAwesomeIcon icon={faArrowUp} /></span>
</span>
</div>
)}
{atTop && (
<div className="contact-icons-container">
<span className="navbar-links">
{allSections.map(sectionName => (
<button
key={sectionName}
className={sectionName === currentSection ? "thispage" : ""}
onClick={() => scrollToSection(sectionName)}
>
{sectionName[0].toUpperCase() + sectionName.slice(1)}
</button>
))}
</span>
<DarkModeSwitch where="navbar" />
</div>
)}
</div>
</div>}
</header>
);
}
|
const MembershipFeeSituationModel = require('../models/membershipFeeSituation');
const { updateSituationId } = require('./membershipFee');
const { DDBB_CONSTANTS } = require('../constants');
const { nextVal } = require('../helpers/nextVal');
const { sendRequestResponse } = require('../middlewares/sendRequestResponse');
// Método para crear una situación de cuota de socio
const create = async (req, res, next) => {
if (req.user) {
req.body.auditUser = req.user.username;
}
if (req.params.associationCode) {
req.body.associationCode = req.params.associationCode;
}
if (req.params.partnerId) {
req.body.partnerId = req.params.partnerId;
}
if (req.params.membershipId) {
const membershipId = req.params.membershipId;
req.body.membershipFeeId = membershipId;
req.body.situationNumber = await nextVal(
DDBB_CONSTANTS.membershipFeeSituationsCollection + '#' + membershipId
);
}
const membershipFeeSituationModel = new MembershipFeeSituationModel(req.body);
membershipFeeSituationModel
.save()
.then((membershipFeeSituationStored) => {
req.body.membershipFeeSituationId = membershipFeeSituationStored._id;
updateSituationId(req, res);
const response = {
status: 'success',
membershipFeeSituationStored,
};
return sendRequestResponse(req, res, next, '', response);
})
.catch((err) => {
const message = `Se ha producido un error al crear la situación de la cuota de socio ${membershipFeeSituationModel.situationNumber}: ${err}`;
const response = {
status: 'error',
message: message,
};
return sendRequestResponse(req, res, next, 404, response);
});
};
// Método para consultar una situación de cuota de socio
const read = async (req, res, next) => {
const situationId = req.params.situationId;
try {
const membershipFeeSituationFound =
await MembershipFeeSituationModel.findOne({
associationCode: req.params.associationCode,
partnerId: req.params.partnerId,
membershipFeeId: req.params.membershipId,
_id: situationId,
});
if (!membershipFeeSituationFound) {
const response = {
status: 'error',
message: `No se han encontrado la situación de la cuota de socio con número: ${situationId}`,
};
return sendRequestResponse(req, res, next, 404, response);
}
const response = {
status: 'success',
membershipSituation: membershipFeeSituationFound,
};
return sendRequestResponse(req, res, next, '', response);
} catch (error) {
const response = {
status: 'error',
message: `Error al consultar la situación de la cuota de socio ${situationId}: ${error}`,
};
return sendRequestResponse(req, res, next, 500, response);
}
};
// Método para actualizar una situación de cuota de socio
const update = async (req, res, next) => {
const associationCode = req.params.associationCode;
const situationId = req.params.situationId;
try {
req.body._id = situationId;
if (req.user) {
req.body.auditUser = req.user.username;
}
if (associationCode) {
req.body.associationCode = associationCode;
}
const membershipFeeSituationModel = new MembershipFeeSituationModel(
req.body
);
const membershipFeeSituationUpdated =
await MembershipFeeSituationModel.findOneAndUpdate(
{
associationCode: associationCode,
partnerId: req.params.partnerId,
membershipFeeId: req.params.membershipId,
_id: situationId,
},
membershipFeeSituationModel,
{
new: true,
}
);
if (!membershipFeeSituationUpdated) {
const response = {
status: 'error',
message: `No se han encontrado la situación de la cuota de socio a eliminar: ${situationId}`,
};
return sendRequestResponse(req, res, next, 404, response);
}
const response = {
status: 'success',
membershipSituation: membershipFeeSituationUpdated,
};
return sendRequestResponse(req, res, next, '', response);
} catch (error) {
const response = {
status: 'error',
message: `Error al actualizar la situación de la cuota de socio con número ${situationId}: ${error}`,
};
return sendRequestResponse(req, res, next, 500, response);
}
};
// Método para eliminar una situación de cuota de socio
const remove = async (req, res, next) => {
const situationId = req.params.situationId;
try {
const membershipFeeSituationRemoved =
await MembershipFeeSituationModel.findOneAndDelete({
associationCode: req.params.associationCode,
partnerId: req.params.partnerId,
membershipFeeId: req.params.membershipId,
_id: situationId,
});
if (!membershipFeeSituationRemoved) {
const response = {
status: 'error',
message: `No se han encontrado la situación de la cuota de socio a eliminar: ${situationId}`,
};
return sendRequestResponse(req, res, next, 404, response);
}
const response = {
status: 'success',
membershipSituation: membershipFeeSituationRemoved,
};
return sendRequestResponse(req, res, next, '', response);
} catch (error) {
const response = {
status: 'error',
message: `Error al eliminar la situación de la cuota de socio ${situationId}: ${error}`,
};
return sendRequestResponse(req, res, next, 500, response);
}
};
// Método para consultar las situaciones de una cuota de socio
const getSituations = async (req, res, next) => {
try {
const membershipFeeSituations = await MembershipFeeSituationModel.find({
associationCode: req.user.associationCode,
partnerId: req.params.partnerId,
membershipFeeId: req.params.membershipId,
}).sort('-situationNumber');
const response = {
status: 'success',
membershipSituations: membershipFeeSituations,
};
return sendRequestResponse(req, res, next, '', response);
} catch (error) {
const response = {
status: 'error',
message: `Error al consultar las situaciones de la cuota de socio: ${error}`,
};
return sendRequestResponse(req, res, next, 500, response);
}
};
module.exports = { create, read, update, remove, getSituations };
|
=begin
#Logistics API
## Getting Started Welcome to the API reference for the Logistics API. The Logistics API provide access to the logistics network that powers all of our e-commerce operations, such as order fulfillment, order returns, freight, and parcel. Build using our APIs to create custom applications and integrations, and retrieve data from your account. The Logistics API is based on the REST standard, and follows the OpenAPI 3 specification. You can access the Logistics API via one of the following following endpoints: | Tenant | Base URL for REST Endpoints | |-------------------------|-----------------------------------| | Production | https://logistics-api.flexport.com | | Sandbox | coming soon | To start using the Logistics API, you must have an active [Flexport Portal](https://portal.flexport.com) account. Sign up [here](https://login.deliverr.com/signup). To inbound physical inventory, ship orders, process returns or buy parcel labels, you'll also need to set up a billing account. ## Account Type We believe there are two primary account types that will use the Logistics API. | Account type | Meaning within the API reference | |--------------------------|-------------------------------------------------------------------------------| | You are a merchant if... | You will use the API to develop an integration for your own business or shop. | | You are a partner if... | You will use the API to develop an application to serve your own customers. | ## Account Creation Create a free [Flexport Portal](https://portal.flexport.com) account. Complete the questions to create your account, and don't forget to add your **business name**. When asked to create a catalog, you can select _\"I'm not selling online yet\"_. - You can access the <a href=\"#tag/Products\">Products</a>, <a href=\"#tag/Webhooks\">Webhooks</a> and <a href=\"#tag/Reports\">Reports</a> API immediately regardless of billing status. - To use the <a href=\"#tag/Parcels\">Parcels</a> or <a href=\"#tag/Returns\">Returns</a> API, your account must meet certain criteria. To inquire, submit a [ticket](https://support.portal.flexport.com/hc/en-us/requests/new). - All other APIs require setting up [billing](https://support.portal.flexport.com/hc/en-us/articles/115003185313-View-Billing-in-the-Seller-Portal) in the Flexport Seller Portal. ## Authentication and Authorization To use the API, you will need an access token. Each access token carries scopes with it. This allows you to create one access token to access products, and another one to access orders, for example. ### Creating Access Tokens There are two ways to request an access token: 1. Using the UI in [Seller Portal -> Settings -> API Tokens](https://sellerportal.deliverr.com/settings/api-tokens). 1. Using the API as described [here](#tag/OAuth/operation/AuthorizationRedirect) You must be an Administrator of your organization to manage access tokens. Once issued, access tokens do not expire unless revoked by the Administrator. ### Partner Access If you wish to develop an application that could be used by more than one merchant, reach out to us to request a unique client ID. Your application will receive callbacks with the authorization code whenever a merchant authorizes it using the [OAuth authorization_code flow](#tag/OAuth/operation/AuthorizationRedirect). Provide the following: - Detailed description of your application - Callback URI where your application will be running to receive authorization codes ### Migrating from Deliverr API You must request new access tokens as described above when migrating from Deliverr API. # Migration Guides The Logistics API is the future hub of all API development. All future services will be added to the Logistics API family, and use its authentication, common objects, and standards. We have prepared this guide to help our customers when migrating from the [Deliverr API V1](https://api.deliverr.com/documentation/v1/spec) to the [Logistics API](https://logistics-api.deliverr.com/logistics/api/unstable/documentation/spec). Here are the key differences between the two APIs at a high level: | Difference | Logistics API version 2023-04 | Deliverr API version 1.0.0 | |------------------------------|--------------------------------------|--------------------------------------| | OAuth 2.0, [RFC6749](https://www.rfc-editor.org/rfc/rfc6749) compliant | Yes | No | | Release schedule | Every 3 months | Ad-hoc | A handful of identifiers have been renamed or added in the Logistics API. Refer to the tables, like the one below, in each of the following guides. | Changes in | Deliverr API | Logistics API | |---------------|-------------------|--------------------| | All resources | productId (DSKU) | logisticsSku | ## Inbounds | Changes in | Deliverr API | Logistics API | |---------------|------------------------|--------------------| | All resources | productId | logisticsSku | | Inbounds | shippingPlan | shipment | | Inbounds | externalShippingPlanId | N/A | | Inbounds | destination | N/A | | Inbounds | caseQuantity | N/A | In the Logistics API, inventory inbounding has been simplified and a number of new endpoints have been added. Refer to the <a href=\"#tag/Inbounds\">Inbounds</a> reference for additional details. Key differences between the API are highlighted below: 1. Shipments can be read individually by the `id` of the shipment or as a list by specifying a list of ids via the `shipmentIds` query parameter 2. `logisticsSku` replaces `productId` as the identifier for the product being inbounded 3. When creating a shipment, the fields `externalShippingPlanId`, `destination` and `caseQuantity` are no longer supported 4. You cannot retrieve a shipment by an \"external\" `shippingId`. 5. Prep services such as box content labels can be required when creating a shipment 6. The GET labels endpoint in the Deliverr API has been replaced by an endpoint to request an expanded set of documents for the shipment (<a href=\"#tag/Inbounds/operation/GetTransferDocumentV2\">here</a>), which includes box content labels, shipping labels and bill of landing. ## Products | Changes in | Deliverr API | Logistics API | |---------------|-------------------|--------------------| | All resources | productId | logisticsSku | | Product | msku | merchantSku | | Product | externalProductId | N/A | | Inventory | availableUnits | available | | Inventory | N/A | onHand | | Inventory | N/A | unavailable | A few fundamental changes: - It is no longer necessary to link an alias to a product before use, as linking functionality is optional - For placing fulfillment orders, use `logisticsSku` instead of `externalProductId` in the list of **lineItems** - In the seller portal, your existing `externalProductId` mapping under the aliases section of a Product Detail page as \"Deliverr API\" will not be used in the Logistics API and will remain unchanged - You cannot update a product's dimensions (`height`, `length`, `width`, `weight`), units (lb/kg, in/cm), or category via the API The <a href=\"#tag/Products/operation/GetInventory\">retrieve inventory</a> endpoint response contains a few new fields. The <a href=\"#tag/Products/operation/GetWarehouseDetails\">retrieve warehouse details</a> endpoint is a POST request instead of a GET. Instead of passing a list of `productId` in the `productIds` query parameter, you will now send a body in the following JSON format: <!-- TODO: update all endpoints to use logisticsSku instead of logisticsSKU and update all fragments named SKU to sku per the codex. --> ```json { \"logisticsSKUs\": [ \"DSKU1\", \"DSKU2\", \"DSKU3\" ] } ``` ## Bundles The bundle endpoints remain semantically similar between the Deliverr API and the Logistics API. However, the bundle creation flow has changed between the APIs. The order endpoints in the Logistics API do not support fulfilling orders by `bundleId`. Merchants who wish to fulfill bundle orders in the logistics API have two options: - You manage the mapping of bundles to their definitions in your systems, which is an array of `{ logisticsSku, quantity }`. - You define bundles via the API or the Seller Portal. Use the GetBundle endpoint to retrieve the bundle definition. In both cases, you must use the `logisticsSku` and its total quantity when <a href=\"#tag/Orders/operation/CreateOrder\">creating an order</a>. The following operations no longer exist in the Logistics API. | Deprecated Endpoints | |---------------------------------| | PATCH [LinkAliasToBundle](https://api.deliverr.com/documentation/v1/spec#tag/Bundles/operation/LinkAliasToBundle) | | PATCH [UnlinkAliasFromBundles](https://api.deliverr.com/documentation/v1/spec#tag/Bundles/operation/UnlinkAliasFromBundles) | | GET [GetBundleByExternalBundleId](https://api.deliverr.com/documentation/v1/spec#tag/Bundles/operation/GetBundleByExternalBundleId) | ## Orders | Changes in endpoint | Deliverr API | Logistics API | |-------------------------------|-------------------|------------------------| | Create order | externalProductId | logisticsSku | | Create order | orderShipmentTime | promisedShipByTime | | Create order | orderDeliverTime | promisedDeliveryByTime | | Create order | shipToAddress | address | | Create order | deliverDays | deliveryDays | | Create order | N/A | packingSlipUrl | | Create order | N/A | duties | | Create order | createdAt | N/A | | Create order | updatedAt | N/A | | Create order | orderCreationTime | N/A | The response payload for getting an order’s information has now changed. See the <a href=\"#tag/Orders/operation/GetOrder\">retrieve order</a> response. ## Reports Beyond changes to the URIs, the report endpoints are a one-to-one mapping between the Deliverr API and the Logistics API. <!-- ## Parcels & Parcel Integration Placeholder: to be completed by the domain team --> <!-- ## Returns Placeholder: to be completed by the domain team --> ## Webhooks Your webhook subscriptions must be recreated using the <a href=\"#tag/Webhooks/operation/CreateWebhook\">create webhook</a> endpoint. # Common Resources Besides following the OpenAPI 3.0 specification, below is a list of common resources and standards shared across the APIs. ## Headers The Logistics API makes use of the following custom HTTP headers. <!-- TODO: the generated OpenAPI specs do not contain header info for any of the endpoints, which is a gap in the documentation. https://github.com/Shopify/deliverr-issues/issues/5825 --> | Header field name | in request | in response | description | |----------------------------------|------------|-------------|-------------| | `x-correlation-id` | no | yes | UUID v4 tied to a request | | `idempotency-key` | yes | no | Can be any string, use for making POST or PATCH requests fault tolerant | | `idempotent-replayed` | no | yes | If included in the response, indicates a stored value was used to replay the request | ## Versioning The Logistics API uses date based versioning for releases. Versions are declared explicitly in the Logistics API URI with a format of `/logistics/api/{api_version}/{endpoint}`. Stable releases follow the format of `yyyy-mm`. Experimental releases have an API version of `unstable`. For example: ``` /logistics/api/2023-04/orders /logistics/api/unstable/orders ``` # Change Log ## unstable The \"unstable\" version contains code experimental changes, developer previews, and new features. However, endpoints can always change and may update with breaking changes without notice. ## 2023-04 - Initial public beta release of the Logistics API # Errors When an API error occurs, the HTTP response includes a three-digit HTTP status code with additional information returned as a <a href=\"https://www.rfc-editor.org/rfc/rfc7807\">problem+json</a> object, for example: ``` HTTP/1.1 404 Not Found Content-Type: application/problem+json Content-Language: en { \"type\": \"https://logistics-api.flexport.com/logistics/api/2023-04/documentation/spec#section/Errors/404-Not-Found\", \"title\": \"Not Found\", \"detail\": \"Cannot find order 49201824029\", \"instance\": \"92e04577-c56b-47b9-b075-62096165a0ce\", } ``` In addition to the three-digit HTTP status code, some errors carry a six-digit error code that provides additional detail about the specific error condition. For example `405004` error code refers to `Invalid scopes` and is documented [here](#section/Errors/405004-Invalid-scopes). ## 400 Bad Request Bad Request. #### Possible Causes - Incorrect HTTP method used. - Non-existent URL path used. - Malformed syntax in the request. - Missing a required parameter. - Input on the request did not pass validation. - The resource to be modified has moved into a state that is no longer valid. #### Possible Solutions - Retry the request after correcting errors in the request and confirming it's valid. - Verify if the resource to be modified exists and is in a valid state. ## 401 Unauthorized The access token is invalid. #### Possible Causes - No valid access token provided. #### Possible Solutions - Check to ensure that the access token is valid. ## 403 Forbidden Access token does not have permission to perform the requested operation. #### Possible Causes - Access token provided is not authorized to perform the requested operation. #### Possible Solutions - Check to ensure that the scope of the access token is sufficient to perform the requested operation. - Create and use a new access token that has the required scope. ## 404 Not Found The requested object cannot be found. #### Possible Causes - The identifier pointing to the request is incorrect. - The specified resource is no longer available. - You do not have access to the specified resource. #### Possible Solutions - Check that the specified resource exists. ## 409 Conflict The object with the same identifier already exists. #### Possible Causes - Resource was already created, but the request is attempting to create it again. #### Possible Solutions - Check that the resource identifier is unique. - Use [idempotency-key](#section/Common-Resources/Headers) when creating resources. ## 422 Unprocessable Content The request is malformed. #### Possible Causes - Request contains invalid data or syntax errors. #### Possible Solutions - Check the payload for inconsistencies or errors. ## 429 Too Many Requests Too many requests in a given amount of time (\"rate limiting\"). #### Possible Causes - Too many requests were made in a short period of time that exceed the API rate limit allowed. #### Possible Solutions - Try again later. We recommend an exponential backoff of your requests. - Refer to the `Retry-After` header for the number of seconds to wait before retrying the request. ## 423 Locked Access to the Logistics API is locked and denied. #### Possible Causes - Flexport Portal account may be frozen and/or deactivated. #### Possible Solutions - Contact <a href=\"https://support.portal.flexport.com/hc/en-us/articles/1500009448562-Contacting-the-Support-team\">Flexport support</a>. ## 5XX Internal Server Error An internal error has occurred while processing the request (these are uncommon). #### Possible Causes - The request is incorrect and cannot be processed. - The server is currently unable to handle the request. #### Possible Solutions - Verify that the request is correct and retry it. - Retry the request at a later time. ## 405001 Invalid redirect URI The redirect URI specified as a callback for OAuth authorization is invalid. #### Possible Causes - Redirect URI must be `https://deliverr.com` if `identity` is used as the client ID. - Redirect URI must be exactly the same URI as the one registered with the client ID provided. #### Possible Solutions - Verify that the redirect URI is correct. ## 405002 Invalid client_id Invalid client_id. #### Possible Causes - The client ID provided is invalid. The client ID must be `identity` or a valid client ID registered with Flexport. #### Possible Solutions - Submit a valid client ID. ## 405003 Missing scopes Scopes were not provided. #### Possible Causes - Scope parameter was not provided in the request. #### Possible Solutions - Check to ensure the request includes scopes. For all available scopes see [OAuth](#tag/OAuth/operation/AuthorizationRedirect). ## 405004 Invalid scopes Some of the scopes provided are invalid. For all available scopes see [OAuth](#tag/OAuth/operation/AuthorizationRedirect). #### Possible Causes - Scope parameter was provided in the request, but the scope values are invalid. - Incorrect separator was used to separate scopes. #### Possible Solutions - Check to ensure that scopes requested are known and valid. For all available scopes see [OAuth](#tag/OAuth/operation/AuthorizationRedirect). ## 405005 Invalid code The one-time authorization code provided is invalid, expired, or has already been used. #### Possible Causes - Authorization code has already been used. - Authorization code has expired because it was requested longer than a few minutes ago. - Authorization code is invalid. #### Possible Solutions - Restart the [OAuth flow](#tag/OAuth/operation/AuthorizationRedirect) to receive a new authorization code. ## 407001 Invalid order status Operation cannot proceed, because order is in a state that does not allow it. #### Possible Causes - Order retry was requested, however the original order was successful. #### Possible Solutions - Ensure that the order is in the correct state, e.g. if order is being retried the order state should be `Canceled`.
The version of the OpenAPI document: unstable
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 7.0.1
=end
require 'date'
require 'json'
require 'logger'
require 'tempfile'
require 'time'
require 'faraday'
require 'faraday/multipart' if Gem::Version.new(Faraday::VERSION) >= Gem::Version.new('2.0')
module Flexport
class ApiClient
# The Configuration object holding settings to be used in the API client.
attr_accessor :config
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Initializes the ApiClient
# @option config [Configuration] Configuration for initializing the object, default to Configuration.default
def initialize(config = Configuration.default)
@config = config
@user_agent = "OpenAPI-Generator/#{VERSION}/ruby"
@default_headers = {
'Content-Type' => 'application/json',
'User-Agent' => @user_agent
}
end
def self.default
@@default ||= ApiClient.new
end
# Call an API with given options.
#
# @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
# the data deserialized from response body (could be nil), response status code and response headers.
def call_api(http_method, path, opts = {})
begin
response = connection(opts).public_send(http_method.to_sym.downcase) do |req|
build_request(http_method, path, req, opts)
end
if config.debugging
config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
end
unless response.success?
if response.status == 0 && response.respond_to?(:return_message)
# Errors from libcurl will be made visible here
fail ApiError.new(code: 0,
message: response.return_message)
else
fail ApiError.new(code: response.status,
response_headers: response.headers,
response_body: response.body),
response.reason_phrase
end
end
rescue Faraday::TimeoutError
fail ApiError.new('Connection timed out')
rescue Faraday::ConnectionFailed
fail ApiError.new('Connection failed')
end
if opts[:return_type]
data = deserialize(response, opts[:return_type])
else
data = nil
end
return data, response.status, response.headers
end
# Builds the HTTP request
#
# @param [String] http_method HTTP method/verb (e.g. POST)
# @param [String] path URL path (e.g. /account/new)
# @option opts [Hash] :header_params Header parameters
# @option opts [Hash] :query_params Query parameters
# @option opts [Hash] :form_params Query parameters
# @option opts [Object] :body HTTP body (JSON/XML)
# @return [Faraday::Request] A Faraday Request
def build_request(http_method, path, request, opts = {})
url = build_request_url(path, opts)
http_method = http_method.to_sym.downcase
header_params = @default_headers.merge(opts[:header_params] || {})
query_params = opts[:query_params] || {}
form_params = opts[:form_params] || {}
update_params_for_auth! header_params, query_params, opts[:auth_names]
if [:post, :patch, :put, :delete].include?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
if config.debugging
config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
end
end
request.headers = header_params
request.body = req_body
# Overload default options only if provided
request.options.params_encoder = config.params_encoder if config.params_encoder
request.options.timeout = config.timeout if config.timeout
request.url url
request.params = query_params
download_file(request) if opts[:return_type] == 'File' || opts[:return_type] == 'Binary'
request
end
# Builds the HTTP request body
#
# @param [Hash] header_params Header parameters
# @param [Hash] form_params Query parameters
# @param [Object] body HTTP body (JSON/XML)
# @return [String] HTTP body data in the form of string
def build_request_body(header_params, form_params, body)
# http form
if header_params['Content-Type'] == 'application/x-www-form-urlencoded'
data = URI.encode_www_form(form_params)
elsif header_params['Content-Type'] == 'multipart/form-data'
data = {}
form_params.each do |key, value|
case value
when ::File, ::Tempfile
# TODO hardcode to application/octet-stream, need better way to detect content type
data[key] = Faraday::FilePart.new(value.path, 'application/octet-stream', value.path)
when ::Array, nil
# let Faraday handle Array and nil parameters
data[key] = value
else
data[key] = value.to_s
end
end
elsif body
data = body.is_a?(String) ? body : body.to_json
else
data = nil
end
data
end
def download_file(request)
@stream = []
# handle streaming Responses
request.options.on_data = Proc.new do |chunk, overall_received_bytes|
@stream << chunk
end
end
def connection(opts)
opts[:header_params]['Content-Type'] == 'multipart/form-data' ? connection_multipart : connection_regular
end
def connection_multipart
@connection_multipart ||= build_connection do |conn|
conn.request :multipart
conn.request :url_encoded
end
end
def connection_regular
@connection_regular ||= build_connection
end
def build_connection
Faraday.new(url: config.base_url, ssl: ssl_options, proxy: config.proxy) do |conn|
basic_auth(conn)
config.configure_middleware(conn)
yield(conn) if block_given?
conn.adapter(Faraday.default_adapter)
config.configure_connection(conn)
end
end
def ssl_options
{
ca_file: config.ssl_ca_file,
verify: config.ssl_verify,
verify_mode: config.ssl_verify_mode,
client_cert: config.ssl_client_cert,
client_key: config.ssl_client_key
}
end
def basic_auth(conn)
if config.username && config.password
if Gem::Version.new(Faraday::VERSION) >= Gem::Version.new('2.0')
conn.request(:authorization, :basic, config.username, config.password)
else
conn.request(:basic_auth, config.username, config.password)
end
end
end
# Check if the given MIME is a JSON MIME.
# JSON MIME examples:
# application/json
# application/json; charset=UTF8
# APPLICATION/JSON
# */*
# @param [String] mime MIME
# @return [Boolean] True if the MIME is application/json
def json_mime?(mime)
(mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
end
# Deserialize the response to the given return type.
#
# @param [Response] response HTTP response
# @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
def deserialize(response, return_type)
body = response.body
# handle file downloading - return the File instance processed in request callbacks
# note that response body is empty when the file is written in chunks in request on_body callback
if return_type == 'File'
if @config.return_binary_data == true
# return byte stream
encoding = body.encoding
return @stream.join.force_encoding(encoding)
else
# return file instead of binary data
content_disposition = response.headers['Content-Disposition']
if content_disposition && content_disposition =~ /filename=/i
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
prefix = sanitize_filename(filename)
else
prefix = 'download-'
end
prefix = prefix + '-' unless prefix.end_with?('-')
encoding = body.encoding
@tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
@tempfile.write(@stream.join.force_encoding(encoding))
@tempfile.close
@config.logger.info "Temp file written to #{@tempfile.path}, please copy the file to a proper folder "\
"with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
"will be deleted automatically with GC. It's also recommended to delete the temp file "\
"explicitly with `tempfile.delete`"
return @tempfile
end
end
return nil if body.nil? || body.empty?
# return response body directly for String return type
return body if return_type == 'String'
# ensuring a default content type
content_type = response.headers['Content-Type'] || 'application/json'
fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w(String Date Time).include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
# @param [Object] data Data to be converted
# @param [String] return_type Return type
# @return [Mixed] Data in a particular type
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'Boolean'
data == true
when 'Time'
# parse date time (expecting ISO 8601 format)
Time.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object (usually a Hash), return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map { |item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models (e.g. Pet) or oneOf
klass = Flexport.const_get(return_type)
klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
end
end
# Sanitize filename by removing path.
# e.g. ../../sun.gif becomes sun.gif
#
# @param [String] filename the filename to be sanitized
# @return [String] the sanitized filename
def sanitize_filename(filename)
filename.gsub(/.*[\/\\]/, '')
end
def build_request_url(path, opts = {})
# Add leading and trailing slashes to path
path = "/#{path}".gsub(/\/+/, '/')
@config.base_url(opts[:operation]) + path
end
# Update header and query params based on authentication settings.
#
# @param [Hash] header_params Header parameters
# @param [Hash] query_params Query parameters
# @param [String] auth_names Authentication scheme name
def update_params_for_auth!(header_params, query_params, auth_names)
Array(auth_names).each do |auth_name|
auth_setting = @config.auth_settings[auth_name]
next unless auth_setting
case auth_setting[:in]
when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
else fail ArgumentError, 'Authentication token must be in `query` or `header`'
end
end
end
# Sets user agent in HTTP header
#
# @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
def user_agent=(user_agent)
@user_agent = user_agent
@default_headers['User-Agent'] = @user_agent
end
# Return Accept header based on an array of accepts provided.
# @param [Array] accepts array for Accept
# @return [String] the Accept header (e.g. application/json)
def select_header_accept(accepts)
return nil if accepts.nil? || accepts.empty?
# use JSON when present, otherwise use all of the provided
json_accept = accepts.find { |s| json_mime?(s) }
json_accept || accepts.join(',')
end
# Return Content-Type header based on an array of content types provided.
# @param [Array] content_types array for Content-Type
# @return [String] the Content-Type header (e.g. application/json)
def select_header_content_type(content_types)
# return nil by default
return if content_types.nil? || content_types.empty?
# use JSON when present, otherwise use the first one
json_content_type = content_types.find { |s| json_mime?(s) }
json_content_type || content_types.first
end
# Convert object (array, hash, object, etc) to JSON string.
# @param [Object] model object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_http_body(model)
return model if model.nil? || model.is_a?(String)
local_body = nil
if model.is_a?(Array)
local_body = model.map { |m| object_to_hash(m) }
else
local_body = object_to_hash(model)
end
local_body.to_json
end
# Convert object(non-array) to hash.
# @param [Object] obj object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_hash(obj)
if obj.respond_to?(:to_hash)
obj.to_hash
else
obj
end
end
# Build parameter value according to the given collection format.
# @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
def build_collection_param(param, collection_format)
case collection_format
when :csv
param.join(',')
when :ssv
param.join(' ')
when :tsv
param.join("\t")
when :pipes
param.join('|')
when :multi
# return the array directly as typhoeus will handle it as expected
param
else
fail "unknown collection format: #{collection_format.inspect}"
end
end
end
end
|
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#">Doctor Accounting</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Portfolio</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron jumbotron-fluid">
<div class="container text-center">
<img src="img/anonym.png" width="300" class="rounded-circle">
<h1 class="display-4">Doctor Accounting</h1>
<p class="lead">This is a modified jumbotron that occupies the entire horizontal space of its parent.</p>
</div>
</div>
<div class="container">
<div class="row">
<div class="col text-center">
<h1>About</h1>
</div>
</div>
<div class="row">
<div class="col text-center">
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Obcaecati architecto sit nemo quod molestias, cumque ipsum magni eaque minima unde numquam eligendi iure veritatis cupiditate quasi aut, rem doloremque? Necessitatibus.</p>
</div>
<div class="col text-center">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perspiciatis iste et neque magni reprehenderit minus temporibus dignissimos iusto. Ipsam voluptates fuga quod alias sapiente laborum rerum quasi voluptatem dolor recusandae?</p>
</div>
</div>
</div>
<div class="container">
<div id="accordion">
<div class="card">
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Standard Perdagangan
</button>
</h5>
</div>
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
<div class="card-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingTwo">
<h5 class="mb-0">
<button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Keuangan
</button>
</h5>
</div>
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
<div class="card-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingThree">
<h5 class="mb-0">
<button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
Proses Produksi
</button>
</h5>
</div>
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordion">
<div class="card-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col text-center">
<h1>Portfolio</h1>
</div>
</div>
<div class="row">
<div class="col-md">
<div class="card">
<img class="card-img-top" src="img/portfolio/1.jpg" alt="Card image cap">
<div class="card-body">
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
</div>
<div class="col-md">
<div class="card">
<img class="card-img-top" src="img/portfolio/2.jpg" alt="Card image cap">
<div class="card-body">
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
</div>
<div class="col-md">
<div class="card">
<img class="card-img-top" src="img/portfolio/3.jpg" alt="Card image cap">
<div class="card-body">
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md">
<div class="card">
<img class="card-img-top" src="img/portfolio/4.jpg" alt="Card image cap">
<div class="card-body">
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
</div>
<div class="col-md">
<div class="card">
<img class="card-img-top" src="img/portfolio/5.jpg" alt="Card image cap">
<div class="card-body">
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
</div>
<div class="col-md">
<div class="card">
<img class="card-img-top" src="img/portfolio/6.jpg" alt="Card image cap">
<div class="card-body">
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
|
// import React from "react";
// import "./DStyles.css";
// const NotesHeading = ({ title, selected, setSelected }) => {
// const nameInitials = title[0].name
// .split(" ")
// .map((word) => word.slice(0, 2))
// .join("")
// .toUpperCase();
// const newTitle = title[0].name
// .split(" ")
// .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
// .join(" ");
// const handleTitleClick = () => {
// setSelected(title[0].name);
// };
// return (
// <div
// onClick={handleTitleClick}
// className={`group_title_logo ${
// selected === title[0].name ? "highlighted_title" : null
// }`}
// >
// <div className="title_logo" style={{ backgroundColor: title[0].color }}>
// {nameInitials}
// </div>
// <div className="group_title">{newTitle}</div>
// </div>
// );
// };
// export default NotesHeading;
import React from "react";
import "./DStyles.css";
const NotesHeading = ({ title, selected, setSelected }) => {
const nameInitials = title[0].name
.split(" ")
.map((word) => word.charAt(0))
.join("")
.toUpperCase();
const newTitle = title[0].name
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
const handleTitleClick = () => {
setSelected(title[0].name);
};
return (
<div
onClick={handleTitleClick}
className={`group_title_logo ${
selected === title[0].name ? "highlighted_title" : null
}`}
>
<div className="title_logo" style={{ backgroundColor: title[0].color }}>
{nameInitials}
</div>
<div className="group_title">{newTitle}</div>
</div>
);
};
export default NotesHeading;
|
package actions
import (
"encoding/json"
"github.com/fouadelhamri/expense-tracker/model"
"github.com/fouadelhamri/expense-tracker/repository"
"github.com/gorilla/mux"
"gorm.io/gorm"
"log"
"net/http"
"strconv"
)
func LeftGroupAction(db *gorm.DB, res http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
groupDestination := params["id"]
//Check Group if found
groupRepo := repository.NewGroupRepository(db)
group, fetchErr := groupRepo.GetGroupByCode(groupDestination)
if fetchErr != nil {
res.WriteHeader(http.StatusNotFound)
json.NewEncoder(res).Encode(NewApiResponseError(fetchErr.Error()))
return
}
//Check Authorization from headers
key := req.Header.Get("key")
token := req.Header.Get("token")
if len(key) == 0 || len(token) == 0 {
res.WriteHeader(http.StatusBadRequest)
json.NewEncoder(res).Encode(NewApiResponseError("missing headers"))
return
}
subRoute := mux.CurrentRoute(req).Subrouter()
url, err := subRoute.Get("check_authorization").URL("id", key, "password", token)
subRoute.Methods(http.MethodPost)
if err != nil {
res.WriteHeader(http.StatusBadRequest)
json.NewEncoder(res).Encode(NewApiResponseError(err.Error()))
return
}
protocol := "http"
if req.Proto == "HTTP/2" {
protocol = "https"
}
authRes, authErr := http.Get(protocol + "://" + req.Host + url.Path)
if authErr != nil {
log.Fatal(authErr)
}
var apiResponse ApiResponse
json.NewDecoder(authRes.Body).Decode(&apiResponse)
if apiResponse.Status == Error {
res.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(res).Encode(NewApiResponseError("unauthorized user"))
return
}
//Authorized User FOUND
//check if part of this group
currentUserID, _ := strconv.Atoi(key)
if len(group.Users) > 0 {
for _, user := range group.Users {
if user.ID == uint(currentUserID) {
if len(group.Users) == 1 {
//Remove the group
deleteRow := db.Delete(&group)
if deleteRow.Error != nil {
res.WriteHeader(http.StatusBadRequest)
json.NewEncoder(res).Encode(NewApiResponseError(deleteRow.Error.Error()))
return
}
}
updateRow := db.Model(&model.User{}).Where("id = ?", currentUserID).Update("group_id", nil)
if updateRow.Error != nil {
res.WriteHeader(http.StatusBadRequest)
json.NewEncoder(res).Encode(NewApiResponseError(updateRow.Error.Error()))
return
}
res.WriteHeader(http.StatusOK)
json.NewEncoder(res).Encode(NewApiResponseSuccess("You left the group"))
return
}
}
}
res.WriteHeader(http.StatusBadRequest)
json.NewEncoder(res).Encode(NewApiResponseError("You are not part of this group"))
return
}
|
# Problem Description
# The program takes a number and searches the number of times the particular number occurs in a list.
# Problem Solution
# 1. Take in the number of elements for the first list and store it in a variable.
# 2. Take in the elements of the list one by one.
# 3. Then take in the number to be searched in the list.
# 4. Use a for loop to traverse through the elements in the list and increment the count variable.
# 5. Display the value of the count variable which contains the number of times a particular number occurs in a list.
# 6. Exit.
a = []
n = int(input("Enter number of elements : "))
for i in range(1, n + 1):
b = int(input("Enter element : "))
a.append(b)
k = 0
num = int(input("Enter the number to be counted : "))
for j in a :
if (j == num):
k = k + 1
print("Number of times",num,"appears is",k)
# Program Explanation
# 1. User must enter the number of elements for the first list and store it in a variable.
# 2. User must then enter the elements of the list one by one using a for loop and store it in a list.
# 3. User must also enter the number to be search the list for.
# 4. A for loop is used to traverse through the elements in the list and an if statement is used to count a particular number.
# 5. The total count of a particular number in the list is printed.
|
import random
import time
from typing import List
import Main
import Utils
from Constants import Pathes
from Types.Answer import Answer
randomizer = random.Random(time.time())
class Topic:
def __init__(self, question: str, topic_sequence: int, topic_id: int = -1):
self.__id: int = topic_id
self.__question: str = question
self.__answers: List[Answer] = []
self.__topic_sequence = topic_sequence
async def add_answer(self, answer: str) -> Answer:
answers = await self.get_answers()
ans = Answer(answer, len(answers))
self.__answers.append(ans)
return ans
async def get_answers_count(self) -> int:
answers = await self.get_answers()
return len(answers)
def get_question(self):
return self.__question
async def get_answer(self, index: int) -> Answer:
if not self.__answers:
self.__answers = await self.sync_answers()
return self.__answers[index]
async def get_answers(self) -> list[Answer]:
if not self.__answers:
self.__answers = await self.sync_answers()
return self.__answers
async def sync_answers(self):
with open(Pathes.Queries_folder + "/GetAllAnswers.sql") as file:
cur = Main.db.cursor()
request = await Utils.read_async(file)
id_ = await self.get_id()
await Utils.exec_request_async(cur, request, id_)
res = cur.fetchall()
Main.db.commit()
cur.close()
return [Answer(x[0], i) for i, x in enumerate(res)]
async def flush(self, author_id):
with open(Pathes.Queries_folder + "/PostTopic.sql") as file:
cur = Main.db.cursor()
text = await Utils.read_async(file)
request = text.replace("\n", " ")
id_ = await self.get_id()
await Utils.exec_request_async(cur, request, id_, author_id, self.__question, self.__topic_sequence)
Main.db.commit()
cur.close()
for i in self.__answers:
await i.flush(self.__id)
async def delete(self):
with open(Pathes.Queries_folder + "/DeleteTopic.sql") as file:
cur = Main.db.cursor()
text = await Utils.read_async(file)
request = text.replace("\n", " ")
id_ = await self.get_id()
await Utils.exec_request_async(cur, request, id_)
Main.db.commit()
cur.close()
async def get_id(self):
if self.__id != -1:
return self.__id
with open(Pathes.Queries_folder + "/GetTopic.sql") as file:
request = await Utils.read_async(file)
cur = Main.db.cursor()
topic_id = self.__generate_id__()
cur = await Utils.exec_request_async(cur, request, topic_id)
res = cur.fetchone()
while res:
topic_id = self.__generate_id__()
cur = await Utils.exec_request_async(cur, request, topic_id)
res = cur.fetchone()
cur.close()
self.__id = topic_id
return self.__id
@staticmethod
def __generate_id__() -> int:
generated_id = randomizer.randrange(0, 9_223_372_036_854_775_808, 1)
return generated_id
def __bool__(self):
return self.__question != "" and self.__id != -1
|
=== Oh Dear - Monitor Uptime, Performance and Broken Links ===
Contributors: flowdee, kryptonitewp, webdj
Author URI: https://kryptonitewp.com/
Plugin URL: https://ohdear.app/
Donate link: https://github.com/sponsors/flowdee
Tags: ohdear, uptime, performance, broken links
Requires at least: 5.0
Requires PHP: 5.6
Tested up to: 6.1
Stable tag: 1.0.2
License: GPLv3 or later
License URI: http://www.gnu.org/licenses/gpl-3.0.html
This plugin brings Oh Dear uptime, performance and broken links monitoring into your WordPress dashboard.
== Description ==
Oh Dear monitors uptime, performance, broken links, SSL certificates and more!
### Features
* Display your site's uptime monitoring
* Display your site's performance monitoring
* Display your site's broken links
* Dashboard widgets
* Regular updates and improvements: Go through the [changelog](https://wordpress.org/plugins/ohdear/changelog/)
This plugin requires an active [Oh Dear account](https://ohdear.app/).
### Support
* Browse [issue tracker](https://github.com/flowdee/ohdear/issues) on GitHub
### Credits
This plugin is not official made or maintained by Oh Dear. All data provided through the official [Oh Dear API](https://ohdear.app/docs/integrations/api/introduction).
== Installation ==
The installation and configuration of the plugin is as simple as it can be.
1. In your WordPress admin area, go to **Plugins > New Plugin**, search for **Oh Dear** and click **Install now**.
1. Alternatively, [download the plugin files](https://downloads.wordpress.org/plugin/ohdear.trunk.zip) and upload the contents of `ohdear.zip` to your plugins directory, which usually is `/wp-content/plugins/`.
1. Activate the plugin.
1. Access the plugin's setting page by browsing to *Oh Dear > Settings* in your WordPress admin area.
1. Enter your personal API Token which can be found on your [Oh Dear acccount](https://ohdear.app/user-settings/api)
1. Select the website from which the data will be taken from.
1. Access the plugin's dashboard page by browsing to *Oh Dear > Dashboard* in your WordPress admin area.
== Frequently Asked Questions ==
= What do I need to use this plugin? =
To use this plugin you must have an active [Oh Dear account](https://ohdear.app/).
== Screenshots ==
1. Dashboard Widgets
2. Uptime Monitoring
3. Performance Monitoring
4. Broken Links Monitoring
5. Settings Page
== Changelog ==
#### Version 1.0.2 (November 4th, 2022)
- Tweak: Redesign of icon, logo, header image
- Tweak: Updated the API token page link
- Tweak: Granted the Editor user role
- WordPress v6.1 compatibility
#### Version 1.0.1 (August 18th, 2020)
- New: Added a friendly demand for a plugin review to the dashboard page
- Tweak: Prefixed CSS classes to avoid third-party conflicts
- WordPress v5.5 compatibility
#### Version 1.0.0 (August 7th, 2020)
- Initial release
|
'use strict';
// class PersonCl {
// constructor(fullName, birthYear) {
// // What is constructor
// this.fullName = fullName;
// this.birthYear = birthYear;
// }
// // 方法将会被添加到.prototype property
// calcAge() {
// console.log(2037 - this.birthYear);
// }
// greet() {
// console.log(`Hey ${this.firstName}`);
// }
// get age() {
// return 2037 - this.birthYear;
// }
// // 体现get和set在数据验证上的作用
// set fullName(name) {
// console.log(name);
// if (name.includes(' ')) this._fullName = name;
// else alert(`${name} is not a full name`);
// }
// get fullName() {
// return this._fullName;
// }
// static hey() {
// console.log('Hey there 👋');
// console.log(this);
// }
// }
// const jessica = new PersonCl('Jessica Davis', 1996);
// console.log('jessica: ', jessica);
// // 在这里可以看到jessica的prototype
// jessica.calcAge();
// console.log('jessica.age:', jessica.age);
// console.log(jessica.__proto__ === PersonCl.prototype);
// // prototype:prototype表示该函数的原型,也表示一个类的成员的集合。 在通过new创建一个类的实例对象的时候,prototype对象的成员都成为实例化对象的成员。
// // __proto__:
// jessica.greet();
// const walter = new PersonCl('Walter White', 1965);
// PersonCl.hey();
// // set和get对于数据验证非常有用
// const account = {
// owner: 'jonas',
// movements: [200, 530, 120, 300],
// get latest() {
// return this.movements.slice(-1).pop();
// // slice是浅删除的方法,pop是把删除的东西打印出来的方法
// },
// set latest(mov) {
// this.movements.push(mov);
// },
// };
// console.log(account.latest);
// // account.latest(50); 这样写就成了函数了,🙅
// account.latest = 50;
// console.log(account.movements);
// const PersonProto = {
// calcAge() {
// console.log(2037 - this.birthYear);
// },
// init(firstName, birthYear) {
// this.firstName = firstName;
// this.birthYear = birthYear;
// },
// };
// const steven = Object.create(PersonProto);
// console.log(steven);
// steven.name = 'Steven';
// steven.birthYear = 2002;
// steven.calcAge();
// // 验证create方法创建的对象的proto是 直接等于原型的proto 还是 继承的proto
// console.log(steven.__proto__);
// console.log(steven.__proto__ === PersonProto);
// const sarah = Object.create(PersonProto);
// sarah.init('Sarah', 1979);
// sarah.calcAge();
// 1. 用ES6创建Challenge1
// 2. 用一个名为'speedUS'的getter返回当前的时速(mi/h),原来的速度是km/h,换算是:英里 = 公里/1.6
// 3. 用一个名为'speedUS'的setter设置当前速度(把英里转换公里)
// 4. 创造一个新的car来满足以上功能
// 测试用例:
// CAR 1: 'Ford' going at 120 km/h
// class CarCl {
// constructor(make, speed) {
// this.make = make;
// this.speed = speed;
// }
// accelerate() {
// this.speed += 10;
// console.log(`${this.make} is going at ${this.speed} km/h`);
// }
// brake() {
// this.speed -= 5;
// console.log(`${this.make} is going at ${this.speed} km/h`);
// }
// get speedUS() {
// return this.speed / 1.6;
// }
// set speedUS(speed) {
// this.speed = speed * 1.6;
// }
// }
// const ford = new CarCl('ford', 120);
// console.log(ford.speedUS);
// ford.accelerate();
// ford.accelerate();
// ford.brake();
// ford.speedUS = 50;
// console.log(ford);
// const Person = function (firstName, birthYear) {
// this.firstName = firstName;
// this.birthYear = birthYear;
// };
// Person.prototype.calcAge = function () {
// console.log(2037 - this.birthYear);
// };
// const Student = function (firstName, birthYear, course) {
// Person.call(this, firstName, birthYear);
// // 这样使用相当于Person是个常规函数,而在常规函数中,this keyword是 undefined
// // call方法就能把this的指向修正
// this.course = course;
// };
// // linking prototype
// // 学生继承自人类的底层逻辑
// Student.prototype = Object.create(Person.prototype); // 此时Student.prototype是空值
// Student.prototype.introduce = function () {
// console.log(`My name is ${this.firstName} and I study ${this.course}`);
// };
// const mike = new Student('Mike', 2020, 'Computer Science');
// console.log(mike);
// mike.introduce();
// mike.calcAge();
// console.log('mike.__proto__: ', mike.__proto__);
// console.log('mike.__proto__.__proto__: ', mike.__proto__.__proto__);
// console.log(mike instanceof Student);
// console.log(mike instanceof Person);
// Student.prototype.constructor = Student;
// console.dir(Student.prototype.constructor);
// 1. 实现一个电动汽车类,叫做EV,他是Car类的子类,这个EV类他有品牌和当前速度
// 2. 给EV实现一个加速的方法和刹车的方法
// 3. 给EV实现一个加速的方法,能使汽车速度提升20的同时减少1%的费用,还要打印出来
// 测试数据:Tesla以120公里的速度行驶,收取23的费用,根据这个测试数据创建对象,包括accelerate、brake和chargeBattery方法
// 自己写的
// const Car = function (make, current_speed, chargeBattery, chargeTO, decrease) {
// this.make = make;
// this.current_speed = current_speed;
// this.chargeBattery = chargeBattery;
// this.chargeTO = chargeTO;
// this.decrease = decrease;
// };
// const EV = function (make, current_speed, chargeBattery, chargeTO, decrease) {
// Car.call(this, make, current_speed, chargeBattery, chargeTO, decrease);
// function accelerate() {
// current_speed = current_speed + 20;
// decrease = decrease - decrease * 0.01;
// }
// };
// const tesla = new EV('Tesla', 140, 80, 80, 22);
// 老师写的
// const Car = function (make, speed) {
// this.make = make;
// this.speed = speed;
// };
// Car.prototype.accelerate = function () {
// this.speed += 10;
// console.log(`${this.make} is going at ${this.speed}km/h`);
// };
// Car.prototype.brake = function () {
// this.speed -= 5;
// console.log(`${this.make} is going at ${this.speed}km/h`);
// };
// const EV = function (make, speed, charge) {
// Car.call(this, make, speed);
// this.charge = charge;
// };
// // 链接原型
// EV.prototype = Object.create(Car.prototype);
// // 新增原型方法
// EV.prototype.chargeBattery = function (chargeTo) {
// this.charge = chargeTo;
// };
// // 修改原型方法,因为原本原型就有这个方法,所以在这里是新增给自己的原型方法,原型链会先用这个
// EV.prototype.accelerate = function () {
// this.speed += 20;
// this.charge--;
// console.log(
// `${this.make} is going at ${this.speed}km/h, with a charge of ${this.charge}`
// );
// };
// const tesla = new EV('Tesla', 120, 23);
// tesla.chargeBattery(90);
// console.log(tesla);
// tesla.brake();
// tesla.accelerate();
// class PersonCl {
// constructor(fullName, birthYear) {
// this.fullName = fullName;
// this.birthYear = birthYear;
// }
// calcAge() {
// console.log(2037 - this.birthYear);
// }
// greet() {
// console.log(`Hey ${this.fullName}`);
// }
// get age() {
// return 2037 - this.birthYear;
// }
// set fullName(name) {
// if (name.includes(' ')) this._fullName = name;
// else alert(`${name} is not a full name!`);
// }
// get fullName() {
// return this._fullName;
// }
// static hey() {
// console.log('Hey there 👋');
// }
// }
// class StudentCl extends PersonCl {
// // 这里继承的时候不需要再像以前一样:父类.call(……),ES6里这会自动完成
// constructor(fullName, birthYear, course) {
// // 在ES6继承中,需要第一时间用super
// super(fullName, birthYear);
// this.course = course;
// }
// introduce() {
// console.log(`My name is ${this.fullName} and I study ${this.course}`);
// }
// calcAge() {
// console.log(
// `I'm ${
// 2037 - this.birthYear
// } years old, but as a student I feel more like ${
// 2037 - this.birthYear + 10
// }`
// );
// }
// }
// const martha = new StudentCl('Martha Jones', 2012);
// const hary = new StudentCl('Hary Jones', 2012, 'Computer Science');
// martha.introduce();
// martha.calcAge();
// const PersonProto = {
// calcAge() {
// console.log(2037 - this.birthYear);
// },
// init(firstName, birthYear) {
// this.firstName = firstName;
// this.birthYear = birthYear;
// },
// };
// // 继承PersonProto
// const steven = Object.create(PersonProto);
// const StudentProto = Object.create(PersonProto);
// StudentProto.init = function (firstName, birthYear, course) {
// PersonProto.init.call(this, firstName, birthYear);
// // StudentProto自己的变量
// this.course = course;
// };
// // StudentProto自己的变量
// StudentProto.introduce = function () {
// console.log(`My name is ${this.firstName} and I study ${this.course}`);
// };
// const jay = Object.create(StudentProto); // 所以StudentProto是jay的父,PersonProto是jay的爷,jay将会继承StudentProto和PersonProto的所有属性
// jay.init('Jay', 2010, 'Computer Science');
// jay.introduce();
// jay.calcAge();
// 面向对象编程(他有封装和数据隐私的意味)
// JS一般是假封装
// 真正私有的类字段和方法
// Public fields
// Private fields
// Public methods
// Private methods
// 还有相同的 static 版本的四种方法,所以合共八种
// class Account {
// // Public fields
// // 1. 不需要const、let等声明
// // 2. 需要分号结尾
// // 他是通过类构造的,他们不在原型上(很重要)
// // 也可以通过this引用
// locale = navigator.language;
// _movements = [];
// // Private fields
// // 1. 用#开头
// // 也是通过类构造的,不在原型上
// #movements = []; // 此时控制台会报错
// #pin; //相当于定义了一个空变量
// constructor(owner, currnecy, pin) {
// this.owner = owner;
// this.currnecy = currnecy;
// this.#pin = pin; // 对私有变量进行赋值
// this._movements = []; //添加下划线的做法是行内规矩,说明他是一个“被保护”的变量
// this.locale = navigator.language;
// console.log(`Thanks for opening an account, ${this.owner}`);
// }
// // Public methods
// // “被保护”的变量就得通过公共方法来访问
// getMovements() {
// // return this._movements;
// return this.#movements; // 这样访问私有变量才不会报错
// }
// // 对象接口函数 API
// deposit(val) {
// // this._movements.push(val);
// this.#movements.push(val); // 这样访问私有变量才不会报错
// return this;
// }
// withdraw(val) {
// // this.movements.push(-val);
// this.deposit(-val);
// return this;
// }
// requestLoan(val) {
// if (this.#approveLoan(val)) {
// this.deposit(val);
// console.log(`Loan approved`);
// }
// return this;
// }
// static helper() {
// // static变量不能用在所有实例上,只能用在类本身上
// console.log();
// }
// // Private methods
// #approveLoan(val) {
// return true;
// }
// }
// const acc1 = new Account('Jonas', 'EUR', 111);
// console.log(acc1);
// // 这不是一个好方法,应该创建方法
// // acc1.movements.push(250);
// // acc1.movements.push(-140);
// acc1.deposit(250);
// acc1.withdraw(140);
// acc1.requestLoan(1000);
// // acc1._approveLoan(2000); //可以看到这是个内部方法 无法被使用,只能在类的内部使用
// // acc1.#approveLoan(2000); // 原本是使用下划线的,改成这个之后由于现代JS还未支持,所以直接报错
// console.log(acc1.getMovements());
// console.log(acc1);
// console.log(acc1.pin);
// // console.log(acc1.#movements); //直接报错
// Account.helper();
// // 链式
// acc1.deposit(300).deposit(500).withdraw(35).requestLoan(25000).withdraw(4000);
// // 需要这些函数都设置了" return this;"才可链化
// console.log(acc1.getMovements());
// 使用ES6重新创造challenge3
// 创建一个EV类,它是Car类的子类
// EV类有个充电属性,是私有属性
// 实现私有的链接加速和充电电池方法,刹车方法也是如此
// 测试数据: 'Rivian' 以120km/h的速度行驶,并且是23的电
// 自己写的
// class Car {
// make;
// speed;
// constructor(make, speed) {
// this.make = make;
// this.speed = speed;
// }
// accelerate() {
// this.speed += 10;
// console.log(`${this.make} is going at ${this.speed}km/h`);
// }
// brake() {
// this.speed -= 5;
// console.log(`${this.make} is going at ${this.speed}km/h`);
// }
// }
// const EV = new Car('Tesla', 120, 23);
// EV.chargeBattery = function (chargeTo) {
// this.charge = chargeTo;
// };
// EV.accelerate = function () {
// this.speed += 20;
// this.charge--;
// console.log(
// `${this.make} is going at ${this.speed}km/h, with charge ${this.charge}`
// );
// };
// console.log('EV: ', EV);
// EV.accelerate();
// EV.brake();
// EV.accelerate();
// 老师写的
// class CarCl {
// constructor(make, speed) {
// this.make = make;
// this.speed = speed;
// }
// accelerate() {
// this.speed += 10;
// console.log(`${this.make} is going at ${this.speed}km/h`);
// return this;
// }
// brake() {
// this.speed -= 5;
// console.log(`${this.make} is going at ${this.speed}km/h`);
// return this;
// }
// }
// class EVCl extends CarCl {
// constructor(make, speed, charge) {
// super(make, speed);
// this.charge = charge;
// }
// // 新增原型方法
// chargeBattery(chargeTo) {
// this.charge = chargeTo;
// return this;
// }
// // 修改原型方法,因为原本原型就有这个方法,所以在这里是新增给自己的原型方法,原型链会先用这个
// accelerate() {
// this.speed += 20;
// this.#charge--;
// console.log(
// `${this.make} is going at ${this.speed}km/h, with a charge of ${this.charge}`
// );
// return this;
// }
// }
// const rivian = new EVCl('Rivian', 120, 23);
// // console.log(rivian);
// // console.log(rivian.#charge); //行不通的
// rivian
// .accelerate()
// .accelerate()
// .accelerate()
// .accelerate()
// .brake()
// .chargeBattery(50)
// .accelerate();
|
---
title: "Reproducible Computation At Scale In R With {targets}"
author: "[Mickaël CANOUIL](https://mickael.canouil.fr/)"
date: "2021-05-02"
categories:
- Meetup
- Anglais
- Reproductibilité
- Extension
image: 2021-06-17.png
image-alt: |
Affiche de 'Reproducible Computation At Scale In R With {targets}',
un Meetup par Will Landau,
tenu le 17 juin 2021
---
Bonjour à toutes et tous,
R Lille organise un nouveau MeetUp sur le thème de la reproductibilité des analyses :
**Reproducible Computation at Scale in R with {targets}**
<center>
<iframe width="560" height="315" src="https://www.youtube.com/embed/FODSavXGjYg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</center>
```{r}
#| include: false
utils::download.file(
url = "https://raw.githubusercontent.com/RLille/meetups/main/meetups/2021-06-17/ads/2021-06-17.png",
destfile = "2021-06-17.png"
)
```
<!-- <center>

</center> -->
> _[Résumé]_
> L'extension R {targets} (<https://docs.ropensci.org/targets/>) améliore la reproductibilité, la mise à l'échelle et la maintenabilité des projets de science des données dans des domaines utilisants des méthodes de calcul intensif tels que l'apprentissage automatique, l'analyse de données bayésiennes et la statistique génomique.
> {targets} identifie la structure de dépendance des éléments du pipeline d'analyse, ignore les tâches à jour, exécute le reste et gère le stockage des données, tout en offrant des options de calcul distribué.
> {stantargets} (<https://docs.ropensci.org/stantargets/>) et extensions similaires, étendent {targets} pour simplifier la construction de pipelines pour des domaines d'application spécifiques, tels que la validation de modèles bayésiens.
>
> _[Bio]_
> Will Landau (<https://wlandau.github.io/>) travaille pour Eli Lilly and Company (<https://www.lilly.com/>) où il développe des méthodes et des outils pour les statisticiens/cliniciens.
> Il est le créateur et le mainteneur des extensions R {targets} et {drake}.
> Will a obtenu son doctorat en statistique à l'Université d'État de l'Iowa en 2016, durant laquelle il a appliqué des méthodes bayésiennes, des modèles hiérarchiques et réalisé du calcul GPU dans le cadre d'analyse de données RNA-seq.
>
> _[A Propos]_
> Cet événement est organisé par R Lille (Lille, France) et aura lieu en anglais.
Celui-ci sera présenté par **Will Landau** sur invitation de __R Lille__ et aura lieu le **jeudi 17 juin 2021 à 18 h 00 (CEST / UTC + 2)** en ligne.
Les inscriptions sont sur Meetup : <http://meetup.rlille.fr/events/277902715/>
L'ensemble des diapositives sera mis à disposition sur le GitHub du groupe : <https://github.com/RLille/meetups>
Le Meetup sera enrigistré et diffusé sur Youtube (<http://youtube.rlille.fr/>).
À bientôt !
Mickaël CANOUIL
|
import models.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Month;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import Exception.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class UnusualSpendAnalyzerTest {
@BeforeEach
void setUp() {
UnusualSpendAnalyzer.clearCurrent();
UnusualSpendAnalyzer.clearPrevious();
}
@Test
void shouldAbleToGetTheUnusualSpends() throws CustomerValidationException {
Customer customer = Customer.createCustomer(1, "xyz", "rahulbasutkar@gmail.com");
CreditCardManager.assignCard(customer);
Transaction transaction = new Transaction(customer.getId());
transaction.perform(Category.BOOKS, 1200, Month.MARCH);
transaction.perform(Category.GROCERY, 1000, Month.MARCH);
transaction.perform(Category.ELECTRONICS, 800, Month.MARCH);
transaction.perform(Category.BOOKS, 600, Month.FEBRUARY);
transaction.perform(Category.GROCERY, 900, Month.FEBRUARY);
transaction.perform(Category.ELECTRONICS, 500, Month.FEBRUARY);
UnusualSpendAnalyzer unusualSpendAnalyzer=new UnusualSpendAnalyzer();
assertTrue(unusualSpendAnalyzer.calculate(Transaction.getTransactionsByCustomerId()));
}
@Test
void shouldAbleToCalculateTotalAmountOfCurrentMonth() throws CustomerValidationException {
// Create a customer
Customer customer = Customer.createCustomer(1, "xyz", "rahulbasutkar@gmail.com");
CreditCardManager.assignCard(customer);
// Perform transactions for February and March
Transaction transaction = new Transaction(customer.getId());
transaction.perform(Category.BOOKS, 1200, Month.MARCH);
transaction.perform(Category.GROCERY, 1000, Month.MARCH);
transaction.perform(Category.ELECTRONICS, 800, Month.MARCH);
transaction.perform(Category.BOOKS, 600, Month.FEBRUARY);
transaction.perform(Category.GROCERY, 900, Month.FEBRUARY);
transaction.perform(Category.ELECTRONICS, 500, Month.FEBRUARY);
// Create an UnusualSpendAnalyzer instance
UnusualSpendAnalyzer unusualSpendAnalyzer = new UnusualSpendAnalyzer();
// Calculate total spend for each month
unusualSpendAnalyzer.calculate(Transaction.getTransactionsByCustomerId());
int actual= unusualSpendAnalyzer.currentMonthTotal(unusualSpendAnalyzer.getCurrentMonthTransactions());
assertEquals(3000,actual);
}
@Test
void shouldAbleToCalculateTotalAmountOfPrevoiusMonth() throws CustomerValidationException {
// Create a customer
Customer customer = Customer.createCustomer(1, "xyz", "rahulbasutkar@gmail.com");
CreditCardManager.assignCard(customer);
// Perform transactions for February and March
Transaction transaction = new Transaction(customer.getId());
transaction.perform(Category.BOOKS, 1200, Month.MARCH);
transaction.perform(Category.GROCERY, 1000, Month.MARCH);
transaction.perform(Category.ELECTRONICS, 800, Month.MARCH);
transaction.perform(Category.BOOKS, 600, Month.FEBRUARY);
transaction.perform(Category.GROCERY, 900, Month.FEBRUARY);
transaction.perform(Category.ELECTRONICS, 500, Month.FEBRUARY);
// Create an UnusualSpendAnalyzer instance
UnusualSpendAnalyzer unusualSpendAnalyzer = new UnusualSpendAnalyzer();
// Calculate total spend for each month
unusualSpendAnalyzer.calculate(Transaction.getTransactionsByCustomerId());
int actual= unusualSpendAnalyzer.PrevMonthTotal(unusualSpendAnalyzer.getPreviousMonthTransactions());
assertEquals(2000,actual);
}
@Test
void shouldAbleToCalculateTotalByCategoryInCurrentMonth() throws CustomerValidationException {
Customer customer = Customer.createCustomer(1, "xyz", "rahulbasutkar@gmail.com");
CreditCardManager.assignCard(customer);
// Perform transactions for February and March
Transaction transaction = new Transaction(customer.getId());
transaction.perform(Category.BOOKS, 1200, Month.MARCH);
transaction.perform(Category.BOOKS, 200, Month.MARCH);
transaction.perform(Category.GROCERY, 1000, Month.MARCH);
transaction.perform(Category.ELECTRONICS, 800, Month.MARCH);
transaction.perform(Category.BOOKS, 600, Month.FEBRUARY);
transaction.perform(Category.GROCERY, 900, Month.FEBRUARY);
transaction.perform(Category.ELECTRONICS, 500, Month.FEBRUARY);
// Create an UnusualSpendAnalyzer instance
UnusualSpendAnalyzer unusualSpendAnalyzer = new UnusualSpendAnalyzer();
// Calculate total spend for each month
unusualSpendAnalyzer.calculate(Transaction.getTransactionsByCustomerId());
Map<String,Integer> expected=new LinkedHashMap<>();
expected.put("BOOKS",1400);
expected.put("GROCERY",1000);
expected.put("ELECTRONICS",800);
Map<String, Integer> TotalByCategoryActual=unusualSpendAnalyzer.currentMonthTotalByCategory(unusualSpendAnalyzer.getCurrentMonthTransactions());
assertEquals(expected,TotalByCategoryActual);
}
}
|
<template>
<tr>
<th scope="row">{{ user.ID }}</th>
<td>{{ user.username }}</td>
<td>{{ user.name }}</td>
<td>
<!-- Call to action buttons -->
<ul class="list-inline m-0">
<li class="list-inline-item">
<button
class="btn btn-primary btn-sm rounded-0"
type="button"
data-toggle="tooltip"
data-placement="top"
title="Edit"
@click="$router.push(`/edit-member/${user.ID}`)"
>
<i class="fa fa-edit"></i>
</button>
</li>
<li class="list-inline-item">
<button
class="btn btn-danger btn-sm rounded-0"
type="button"
data-toggle="tooltip"
data-placement="top"
title="Delete"
@click="deleteUser"
>
<i class="fa fa-trash"></i>
</button>
</li>
</ul>
</td>
</tr>
</template>
<script>
import axios from "axios";
export default {
name: "user-item",
props: {
user: {
type: Object,
},
},
methods: {
deleteUser() {
if (confirm(`Ban co chac muon xoa user ${this.user.username} !`)) {
axios
.delete(`http://localhost:5050/person/delete/${this.user.ID}`)
.then(() => {
setTimeout(function () {
alert(`Xóa thành công user !`);
location.reload();
}, 1000);
});
}
},
},
};
</script>
<style scoped>
td,
th {
text-align: center;
}
</style>
|
package tabletennis.controller;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.reactive.server.WebTestClient;
import tabletennis.dto.*;
import tabletennis.model.LicenseType;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Sql(statements = {"delete from players", "delete from organizations"})
class OrganizationControllerWebClientIT {
@Autowired
WebTestClient webTestClient;
OrganizationDto org;
PlayerDto player;
@BeforeEach
void setUp() {
player = webTestClient.post()
.uri("api/players")
.bodyValue(new CreatePlayerCommandForTest(
"Kiss Ádám",
LocalDate.of(1999, 7, 7),
"Nagy Éva",
null,
LocalDate.of(2020, 9, 2),
LocalDate.of(2021, 6, 30),
LicenseType.FULL))
.exchange()
.expectBody(PlayerDto.class).returnResult().getResponseBody();
webTestClient.post()
.uri("api/players")
.bodyValue(new CreatePlayerCommandForTest(
"Barna Bálint",
LocalDate.of(1985, 2, 2),
"Fekete Fruzsina",
null,
LocalDate.of(2021, 9, 2),
LocalDate.of(2022, 6, 30),
LicenseType.FULL))
.exchange();
webTestClient.post()
.uri("api/players")
.bodyValue(new CreatePlayerCommandForTest(
"Szőke Szilárd",
LocalDate.of(1956, 3, 3),
"Zöld Zsuzsa",
null,
LocalDate.of(2022, 3, 1),
LocalDate.of(2022, 6, 30),
LicenseType.INDIVIDUAL))
.exchange();
org = webTestClient.post()
.uri("api/organizations")
.bodyValue(new CreateOrganizationCommand(
"BVSC-Zugló", "Budapest", "Kovács Géza", "kg@bvsc.hu", "1234567"))
.exchange()
.expectBody(OrganizationDto.class).returnResult().getResponseBody();
webTestClient.post()
.uri("api/organizations")
.bodyValue(new CreateOrganizationCommand(
"Postás SE", "Budapest", "Lakatos Éva", "le@postas.hu", "7654321"))
.exchange();
}
@Test
void testCreateOrganization() {
webTestClient.post()
.uri("api/organizations")
.bodyValue(new CreateOrganizationCommand(
"ETO", "Győr", "Kertész Sándor", "ks@eto.hu", "2468123"))
.exchange()
.expectStatus().isCreated()
.expectBody(OrganizationDto.class)
.value(p -> assertThat(p.getOrgName()).isEqualTo("ETO"))
.value(p -> assertThat(p.getContact()).isEqualTo("Kertész Sándor"))
.value(p -> assertThat(p.getAddress()).isEqualTo("Győr"));
}
@Test
void testGetOrganizationList() {
webTestClient.get()
.uri(uriBuilder -> uriBuilder.path("api/organizations").build())
.exchange()
.expectBodyList(OrganizationListDto.class)
.value(list -> assertThat(list)
.hasSize(2)
.extracting(OrganizationListDto::getOrgName)
.containsOnly("BVSC-Zugló", "Postás SE"));
}
@Test
void testGetOrganizationById() {
webTestClient.get()
.uri(uriBuilder -> uriBuilder.path("api/organizations/{orgId}").build(org.getOrgId()))
.exchange()
.expectBody(OrganizationDto.class)
.value(org -> assertThat(org)
.extracting(OrganizationDto::getOrgName)
.isEqualTo("BVSC-Zugló"));
}
@Test
void testDeleteOrganization() {
long orgId = webTestClient.post()
.uri("api/organizations")
.bodyValue(new CreateOrganizationCommand(
"ETO", "Győr", "Kertész Sándor", "ks@eto.hu", "2468123"))
.exchange()
.expectBody(OrganizationDto.class).returnResult().getResponseBody().getOrgId();
webTestClient.get()
.uri(uriBuilder -> uriBuilder.path("api/organizations/{orgId}").build(orgId))
.exchange()
.expectStatus().isOk();
webTestClient.delete()
.uri(uriBuilder -> uriBuilder.path("api/organizations/{orgId}").build(orgId))
.exchange()
.expectStatus().isNoContent();
webTestClient.get()
.uri(uriBuilder -> uriBuilder.path("api/organizations/{orgId}").build(orgId))
.exchange()
.expectStatus().isNotFound();
}
@Test
void testTestDeletePlayerFromOrganization() {
webTestClient.post()
.uri(uriBuilder -> uriBuilder.path("api/players/{playerId}/{orgId}").build(player.getPlayerId(), org.getOrgId()))
.exchange()
.expectBody(PlayerDto.class)
.value(p -> assertEquals(org.getOrgId(), p.getOrganization().getOrgId()));
webTestClient.get()
.uri(uriBuilder -> uriBuilder.path("api/players/{id}").build(player.getPlayerId()))
.exchange()
.expectBody(PlayerDto.class)
.value(p -> assertEquals(org.getOrgId(), p.getOrganization().getOrgId()));
webTestClient.delete()
.uri(uriBuilder -> uriBuilder.path("api/organizations/{orgId}/{playerId}").build(org.getOrgId(), player.getPlayerId()))
.exchange()
.expectStatus().isNoContent();
webTestClient.get()
.uri(uriBuilder -> uriBuilder.path("api/players/{id}").build(player.getPlayerId()))
.exchange()
.expectBody(PlayerDto.class)
.value(p -> assertEquals(null, p.getOrganization()));
}
}
|
{-# LANGUAGE DeriveFoldable #-}
module QuadTree where
import Model
import Graphics.Gloss
-- QuadTree related stuff
data QuadTree a = Node BoundingBox [a] (QuadTree a) (QuadTree a) (QuadTree a) (QuadTree a) | EmptyLeaf
deriving (Foldable, Show, Eq)
thresholdObjectsPerQuadrant :: Int
thresholdObjectsPerQuadrant = 6
getCollisionPartners :: (CollisionObject a, CollisionObject b) => a -> QuadTree b -> [b]
getCollisionPartners _ EmptyLeaf = []
getCollisionPartners obj n@(Node bb objs tl tr bl br )
-- seems like we reached civilisation
| not (null objs) = collapse n
-- hmm, we can go deeper, no one is here
| getBB obj `intersects` bb = concatMap (getCollisionPartners obj) [ tl, tr, bl, br]
-- huh, there is no one here
| otherwise = []
getAllInArea :: (CollisionObject b) => BoundingBox -> QuadTree b -> [b]
getAllInArea _ EmptyLeaf = []
getAllInArea area n@(Node bb objs tl tr bl br )
| bb `intersects` area = filter (\obj -> getBB obj `intersects` area) objs ++ concatMap (getAllInArea area) [tl,tr,bl,br]
| otherwise = []
buildQuadTree :: (CollisionObject a, Eq a) => [a] -> Point -> QuadTree a
buildQuadTree l worldSize = insertAll l (Node ((0,0), worldSize) [] EmptyLeaf EmptyLeaf EmptyLeaf EmptyLeaf)
insertAll :: (CollisionObject a, Eq a) => [a] -> QuadTree a -> QuadTree a
insertAll [] t = t
insertAll (x:xs) t@(Node bb objs tl tr bl br) = insertAll xs (insert x t)
insert :: (CollisionObject a, Eq a) => a -> QuadTree a -> QuadTree a
insert x t@(Node bb xs tl tr bl br)
-- doesn't fit, doesn't belong, begone
| not (x `fitsIn` bb) || not (hasCollision x)= t
-- there is room and there are no subnodes!, come in!
| length xs < thresholdObjectsPerQuadrant && not (hasSubNodes t)
= Node bb (x : xs) tl tr bl br
-- no more room! we don't have subnodes! subdivide and insert into subnodes!
| not (hasSubNodes t)
= insertAll (x:xs) (Node bb [] ntl ntr nbl nbr)
-- welp, try the subnodes?
| any (\q -> x `fitsIn` getQTBB q) [ tl, tr, br, bl]
= insertIntoQuadrant x t
| otherwise
= Node bb (x : xs) tl tr bl br
where quadrants@[ntl, ntr, nbl, nbr] = map newNode (toQuadrants bb)
insertIntoQuadrant :: (CollisionObject a, Eq a) => a -> QuadTree a -> QuadTree a
insertIntoQuadrant x t@(Node bb objs tl tr bl br)
| x `fitsIn` bbOf tl = Node bb objs (insert x tl) tr bl br
| x `fitsIn` bbOf tr = Node bb objs tl (insert x tr) bl br
| x `fitsIn` bbOf bl = Node bb objs tl tr (insert x bl) br
| x `fitsIn` bbOf br = Node bb objs tl tr bl (insert x br)
where bbOf (Node bb _ _ _ _ _) = bb
toQuadrants :: BoundingBox -> [BoundingBox]
toQuadrants (tl, (sx, sy)) = [(tl, half), (tl + (hx, 0.0), half), (tl + (0.0 , hy), half), (tl + half, half)]
where half@(hx, hy) = (sx / 2, sy / 2)
collapse :: CollisionObject a => QuadTree a -> [a]
collapse EmptyLeaf = []
collapse (Node _ objs tl tr bl br) = concat [objs , collapse tl , collapse tr , collapse bl , collapse br]
fitsIn :: (CollisionObject a) => a -> BoundingBox -> Bool
fitsIn obj1 bb2 = topLeft bb1 >= topLeft bb2 && bottomRight bb1 <= bottomRight bb2
where bb1 = getBB obj1
newNode :: CollisionObject a => BoundingBox -> QuadTree a
newNode bb = Node bb [] EmptyLeaf EmptyLeaf EmptyLeaf EmptyLeaf
hasSubNodes :: (CollisionObject a, Eq a) => QuadTree a -> Bool
hasSubNodes (Node _ _ tl _ _ _) = tl /= EmptyLeaf
getQTBB :: CollisionObject a => QuadTree a -> BoundingBox
getQTBB (Node bb _ _ _ _ _) = bb
collidesWith :: (CollisionObject a, CollisionObject b) => a -> b -> Bool
collidesWith objA objB | hasCollision objA && hasCollision objB = intersects (getBB objA) (getBB objB)
| otherwise = False
intersects :: BoundingBox -> BoundingBox -> Bool
intersects ((xA, yA), (wA, hA)) ((xB, yB), (wB, hB)) =
xA < xB + wB &&
xA + wA > xB &&
yA < yB + hB &&
yA + hA > yB
-- positive x = right; negative x = left
-- positive y = bottom; negative y = top
overlap :: (CollisionObject a, CollisionObject b) => a -> b -> (Float, Float)
overlap objA objB = (xOverlap , yOverlap)
where ((xA, yA), (wA, hA)) = getBB objA
((xB, yB), (wB, hB)) = getBB objB
xOverlap | xA <= xB = (xA + wA) - xB
| otherwise = xA - (xB + wB)
yOverlap | yA <= yB = (yA + hA) - yB
| otherwise = yA - (yB + hB)
|
@extends('layouts.app')
@section('content')
<div class="container">
<div class="card mt-3 mb-3">
<div class="card-header">Data Karyawan</div>
<div class="card-body d-flex justify-content-end">
<ul class="list-inline mb-0">
<li class="list-inline-item">
<a href="{{ route('datakaryawan.exportExcel') }}" class="btn btn-outline-success">
<i class="bi bi-download me-1"></i><span>Excel</span>
</a>
</li>
<li class="list-inline-item">
<a href="{{ route('datakaryawan.exportPDF') }}" class="btn btn-outline-danger">
<i class="bi bi-download me-1"></i><span>PDF</span>
</a>
</li>
<li class="list-inline-item">|</li>
<li class="list-inline-item">
<button type="button" class="btn btn-primary" data-bs-toggle="modal"
data-bs-target="#createDataKaryawan">
<i class="bi bi-plus-circle me-1"></i><span>Tambah Data</span>
</button>
</li>
</ul>
</div>
<div class="card-body" style="overflow-x:auto;">
{{-- {{ $dataTable->table() }} --}}
<table class="table table-bordered table-hover table-striped mb-0 bg-white datatable"
id="dataKaryawanTable">
<thead>
<tr>
<th>Id</th>
<th>No.</th>
<th>Nama</th>
<th>Status Karyawan</th>
<th>Keahlian</th>
<th>Jabatan</th>
<th>Aksi</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
{{-- start modal section --}}
{{-- modal create --}}
<div class="modal fade" id="createDataKaryawan" tabindex="-1" aria-labelledby="createDataKaryawanModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{ route('datakaryawan.store') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="modal-header">
<h5 class="modal-title" id="createDataKaryawanModalLabel">Tambah Karyawan</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<h4 class="text-center">Data Karyawan</h4>
<div class="form-group">
<label for="nama" class="form-label">Nama</label>
<input class="form-control @error('nama') is-invalid @enderror" type="text" name="nama"
id="namaCreate" value="{{ old('nama') }}" placeholder="Masukkan nama karyawan">
@error('nama')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group mt-1">
<label for="alamat" class="form-label">Alamat</label>
<input class="form-control @error('alamat') is-invalid @enderror" type="text" name="alamat"
id="alamatCreate" value="{{ old('alamat') }}" placeholder="Masukkan alamat karyawan">
@error('alamat')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group mt-1">
<label for="nomorTelepon" class="form-label">Nomor Telepon</label>
<input class="form-control @error('nomorTelepon') is-invalid @enderror" type="tel"
name="nomorTelepon" id="nomorTeleponCreate" value="{{ old('nomorTelepon') }}"
placeholder="Masukkan nomor telepon karyawan">
@error('nomorTelepon')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group my-2">
<label for="statusKaryawan" class="form-label">Status Karyawan</label>
<select class="d-block" name="statusKaryawan" id="statusKaryawanCreate">
<option value="Karyawan_Tetap">Karyawan Tetap</option>
<option value="Karyawan_Kontrak">Karyawan Kontrak</option>
</select>
@error('statusKaryawan')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group mt-1">
<label for="keahlian" class="form-label">Keahlian</label>
<input class="form-control @error('keahlian') is-invalid @enderror" type="text"
name="keahlian" id="keahlianCreate" value="{{ old('keahlian') }}"
placeholder="Masukkan keahlian yang dimiliki karyawan">
@error('keahlian')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group mt-1">
<label for="jabatan" class="form-label">Jabatan</label>
<input class="form-control @error('jabatan') is-invalid @enderror" type="text" name="jabatan"
id="jabatanCreate" value="{{ old('jabatan') }}" placeholder="Masukkan jabatan">
@error('jabatan')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<h4 class="text-center mt-3">Data Akun</h4>
<div class="form-group">
<label for="username" class="form-label">Username</label>
<input class="form-control @error('username') is-invalid @enderror" type="text"
name="username" id="usernameCreate" value="{{ old('username') }}"
placeholder="Masukkan username">
@error('username')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group mt-1">
<label for="email" class="form-label">Email</label>
<input class="form-control @error('email') is-invalid @enderror" type="text"
name="email" id="emailCreate" value="{{ old('email') }}"
placeholder="Masukkan email">
@error('email')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group mt-1">
<label for="password" class="form-label">Password baru</label>
<input class="form-control @error('password') is-invalid @enderror" type="password"
name="password" id="passwordCreate" value="" placeholder="Masukkan password"
autocomplete>
@error('password')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group mt-1">
<label for="password_confirmation" class="form-label">Konfirmasi password baru</label>
<input class="form-control @error('password_confirmation') is-invalid @enderror"
type="password" name="password_confirmation" id="password_confirmationCreate"
value="" placeholder="Masukkan password ulang" autocomplete>
@error('password_confirmation')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group my-2">
<label for="role" class="form-label">Role</label>
<select class="d-block" name="role" id="roleCreate">
<option value="Administrator">Administrator</option>
<option value="Employee">Karyawan Reguler</option>
</select>
@error('role')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<p class="fw-bold">Note : Pastikan username karyawan yang dimasukkan merupakan username yang unik
dan pastikan sudah benar karena tidak dapat diganti setelah data karyawan beserta akun telah
berhasil dibuat.</p>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Simpan Data</button>
</div>
</form>
</div>
</div>
</div>
{{-- modal edit --}}
<div class="modal fade" id="editDataKaryawan" tabindex="-1" aria-labelledby="editDataKaryawanModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{ route('datakaryawan.update', ':id') }}" method="POST" enctype="multipart/form-data">
@csrf
@method('PUT')
<div class="modal-header">
<h4 class="modal-title" id="editDataKaryawanModalLabel">Edit Data Karyawan</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<h5 class="text-center">Data Utama</h5>
<div class="form-group">
<input class="form-control" type="hidden" name="idEdit" id="idEdit" value="">
</div>
<div class="form-group">
<label for="namaEdit" class="form-label">Nama</label>
<input class="form-control @error('namaEdit') is-invalid
@enderror" type="text"
name="namaEdit" id="namaEdit" value="{{ old('namaEdit') }}"
placeholder="Masukkan nama karyawan">
@error('namaEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group">
<label for="alamatEdit" class="form-label">Alamat</label>
<input class="form-control @error('alamatEdit') is-invalid
@enderror" type="text"
name="alamatEdit" id="alamatEdit" value="{{ old('alamatEdit') }}"
placeholder="Masukkan alamat karyawan">
@error('alamatEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group">
<label for="nomorTeleponEdit" class="form-label">Nomor Telepon</label>
<input class="form-control @error('nomorTeleponEdit') is-invalid @enderror" type="tel"
name="nomorTeleponEdit" id="nomorTeleponEdit" value="{{ old('nomorTeleponEdit') }}"
placeholder="Masukkan nomor telepon karyawan">
@error('nomorTeleponEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group my-2">
<label for="statusKaryawanEdit" class="form-label">Status Karyawan</label>
<select class="d-block" name="statusKaryawanEdit" id="statusKaryawanEdit">
<option value="Karyawan_Tetap">Karyawan Tetap</option>
<option value="Karyawan_Kontrak">Karyawan Kontrak</option>
</select>
@error('statusKaryawanEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group">
<label for="keahlianEdit" class="form-label">Keahlian</label>
<input class="form-control @error('keahlianEdit') is-invalid @enderror" type="text"
name="keahlianEdit" id="keahlianEdit" value="{{ old('keahlianEdit') }}"
placeholder="Masukkan keahlian yang dimiliki karyawan">
@error('keahlianEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group">
<label for="jabatanEdit" class="form-label">Jabatan</label>
<input class="form-control @error('jabatanEdit') is-invalid @enderror" type="text"
name="jabatanEdit" id="jabatanEdit" value="{{ old('jabatanEdit') }}"
placeholder="Masukkan jabatan">
@error('jabatanEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<h5 class="text-center mt-3">Data Akun</h5>
<div class="form-group">
<label for="usernameEdit" class="form-label">Username</label>
<input class="form-control @error('usernameEdit') is-invalid @enderror" type="text"
name="usernameEdit" id="usernameEdit" value="" placeholder="Masukkan username"
disabled>
@error('usernameEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group mt-1">
<label for="emailEdit" class="form-label">Email</label>
<input class="form-control @error('emailEdit') is-invalid @enderror" type="text"
name="emailEdit" id="emailEdit" value="" placeholder="Masukkan email">
@error('emailEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group">
<label for="passwordEdit" class="form-label">Password Baru</label>
<input class="form-control @error('passwordEdit') is-invalid @enderror" type="password"
name="passwordEdit" id="passwordEdit" value=""
placeholder="Masukkan password baru (bisa dikosongkan)" autocomplete>
@error('passwordEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group">
<label for="password_confirmationEdit" class="form-label">Konfirmasi Password Baru</label>
<input class="form-control @error('password_confirmationEdit') is-invalid @enderror"
type="password" name="password_confirmationEdit" id="password_confirmationEdit"
value="" placeholder="Masukkan ulang password baru" autocomplete>
@error('password_confirmationEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group my-2">
<label for="roleEdit" class="form-label">Role</label>
<select class="d-block" name="roleEdit" id="roleEdit">
<option value="Administrator">Administrator</option>
<option value="Employee">Karyawan</option>
</select>
@error('roleEdit')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Simpan Perubahan Data</button>
</div>
</form>
</div>
</div>
</div>
{{-- modal detail / show --}}
<div class="modal fade" id="showDataKaryawan" tabindex="-1" aria-labelledby="showModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="" method="POST" enctype="multipart/form-data">
@csrf
@method('PUT')
<div class="modal-header">
<h4 class="modal-title" id="showDataKaryawanModalLabel">Detail Data Karyawan</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="nama" class="form-label">Nama</label>
<input class="form-control @error('nama') is-invalid
@enderror" type="text"
name="nama" id="nama" disabled>
@error('nama')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group">
<label for="alamat" class="form-label">Alamat</label>
<input class="form-control @error('alamat') is-invalid
@enderror" type="text"
name="alamat" id="alamat" disabled>
@error('alamat')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group">
<label for="nomorTelepon" class="form-label">Nomor Telepon</label>
<input class="form-control @error('nomorTelepon') is-invalid @enderror" type="tel"
name="nomorTelepon" id="nomorTelepon" disabled>
@error('nomorTelepon')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group mt-3">
<label for="statusKaryawan" class="form-label">Status Karyawan</label>
<select name="statusKaryawan" id="statusKaryawan" disabled>
<option value="Karyawan_Tetap">Karyawan Tetap</option>
<option value="Karyawan_Kontrak">Karyawan Kontrak</option>
</select>
@error('statusKaryawan')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group">
<label for="keahlian" class="form-label">Keahlian</label>
<input class="form-control @error('keahlian') is-invalid @enderror" type="text"
name="keahlian" id="keahlian" disabled>
@error('keahlian')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
<div class="form-group">
<label for="jabatan" class="form-label">Jabatan</label>
<input class="form-control @error('jabatan') is-invalid @enderror" type="text"
name="jabatan" id="jabatan" disabled>
@error('jabatan')
<div class="text-danger">
<small>{{ $message }}</small>
</div>
@enderror
</div>
</form>
</div>
</div>
</div>
{{-- end modal section --}}
@endsection
@push('scripts')
<script type="module">
$(document).ready(function() {
// show table record with datatable
var table = $("#dataKaryawanTable").DataTable({
serverSide: true,
processing: true,
ajax: "/getDataKaryawan",
columns: [{
data: "id_data_karyawan",
name: "id_data_karyawan",
visible: false
},
{
data: "DT_RowIndex",
name: "DT_RowIndex",
orderable: false,
searchable: false
},
{
data: "nama",
name: "nama"
},
{
data: "status_karyawan",
name: "status_karyawan"
},
{
data: "keahlian",
name: "keahlian"
},
{
data: "jabatan",
name: "jabatan"
},
{
data: "aksi",
name: "aksi",
orderable: false,
searchable: false
},
],
order: [
[0, "desc"]
],
lengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"],
],
});
// Membuka modal secara langsung jika ada error pada input di modal create dan edit
@if (!empty(Session::get('error_in_modal')) && Session::get('error_in_modal') == 1)
$('#createDataKaryawan').modal('show');
@elseif (!empty(Session::get('error_in_modal')) && Session::get('error_in_modal') == 2)
$('#editDataKaryawan').modal('show');
@endif
// Edit form with bootstrap modal with data
$('#dataKaryawanTable').on('click', '.btn-edit', function(event) {
event.preventDefault();
var $tr = $(this).closest('tr');
if ($tr.hasClass('child')) {
$tr = $tr.prev('.parent');
}
var data = table.row($tr).data();
// Populate your edit modal with data
$('#editDataKaryawan input[name="idEdit"]').val(data.id_data_karyawan);
$('#editDataKaryawan input[name="namaEdit"]').val(data.nama);
$('#editDataKaryawan input[name="alamatEdit"]').val(data.alamat);
$('#editDataKaryawan input[name="nomorTeleponEdit"]').val(data.nomor_telepon);
$('#editDataKaryawan select[name="statusKaryawanEdit"]').val(data.status_karyawan);
$('#editDataKaryawan input[name="keahlianEdit"]').val(data.keahlian);
$('#editDataKaryawan input[name="jabatanEdit"]').val(data.jabatan);
$('#editDataKaryawan input[name="usernameEdit"]').val(data.user.username);
$('#editDataKaryawan input[name="emailEdit"]').val(data.user.email);
$('#editDataKaryawan input[name="passwordEdit"]').val(data.user.password);
$('#editDataKaryawan select[name="roleEdit"]').val(data.user.role);
var updateRoute = "{{ route('datakaryawan.update', ':id') }}";
updateRoute.replace(':id', data.id_data_karyawan);
// Set form action URL dynamically
var actionUrl = '/datakaryawan/' + data.id_data_karyawan;
$('#editDataKaryawan form').attr('action', actionUrl);
});
// show form with bootstrap modal
$('#dataKaryawanTable').on('click', '.btn-show', function(event) {
event.preventDefault();
var $tr = $(this).closest('tr');
if ($tr.hasClass('child')) {
$tr = $tr.prev('.parent');
}
var data = table.row($tr).data();
// Populate your show modal with data
$('#showDataKaryawan input[name="nama"]').val(data.nama);
$('#showDataKaryawan input[name="alamat"]').val(data.alamat);
$('#showDataKaryawan input[name="nomorTelepon"]').val(data.nomor_telepon);
$('#showDataKaryawan select[name="statusKaryawan"]').val(data.status_karyawan);
$('#showDataKaryawan input[name="keahlian"]').val(data.keahlian);
$('#showDataKaryawan input[name="jabatan"]').val(data.jabatan);
// Set form action URL dynamically
var actionUrl = '/datakaryawan/' + data.id_data_karyawan;
$('#showDataKaryawan form').attr('action', actionUrl);
});
// delete confirmation with sweetalert by realrashid
$(".datatable").on("click", ".btn-delete", function(e) {
e.preventDefault();
var form = $(this).closest("form");
var nama = $(this).data("nama");
Swal.fire({
title: "Apakah anda yakin ingin menghapus data \n" + nama + "?",
text: "Anda tidak bisa mengembalikan data setelah terhapus!",
icon: "warning",
showCancelButton: true,
confirmButtonClass: "bg-primary",
confirmButtonText: "Ya, hapus!",
cancelButtonText: "Tidak, jangan hapus!"
}).then((result) => {
if (result.isConfirmed) {
form.submit();
}
});
});
});
</script>
@endpush
|
# Level: Medium
# TAGS: Array, Binary Search, Sliding Window, Prefix Sum
from typing import List
class Solution:
# Time: O(N^2) | Space: O(1)
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left, total, n = 0, 0, len(nums)
min_len = float("inf")
for right in range(n):
total += nums[right]
while total >= target:
min_len = min(min_len, right - left + 1)
total -= nums[left]
left += 1
return 0 if min_len == float("inf") else min_len
tests = [
(
(
7,
[2, 3, 1, 2, 4, 3],
),
2,
),
(
(
4,
[1, 4, 4],
),
1,
),
(
(
11,
[1, 1, 1, 1, 1, 1, 1, 1],
),
0,
),
]
|
package board;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class BoardDAO {
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
private Context init;
private DataSource ds;
private static BoardDAO instance = new BoardDAO();
public static BoardDAO getInstance() {
return instance;
}
private BoardDAO() {
try {
init = new InitialContext();
ds = (DataSource) init.lookup("java:comp/env/jdbc/oracle");
} catch (NamingException e) {
e.printStackTrace();
}
}
private void close() {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
}catch (SQLException e) {}
}
private BoardDTO mapping(ResultSet rs) throws SQLException {
BoardDTO dto = new BoardDTO();
dto.setContent(rs.getString("content"));
dto.setIdx(rs.getInt("idx"));
dto.setTitle(rs.getString("title"));
dto.setWriteDate(rs.getDate("writeDate"));
dto.setWriter(rs.getString("writer"));
return dto;
}
public BoardDTO selectOne(int idx) {
BoardDTO dto = null;
String sql ="select * from board where idx = ?";
try {
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, idx);
rs = pstmt.executeQuery();
while(rs.next()) {
dto = mapping(rs);
}
}catch (SQLException e) {
e.printStackTrace();
} finally {close();}
return dto;
}
public int insert(BoardDTO dto) {
int row = 0;
String sql = "insert into board (title, writer, content)"
+ " values(?, ?, ?)";
try {
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dto.getTitle());
pstmt.setString(2, dto.getWriter());
pstmt.setString(3, dto.getContent());
row = pstmt.executeUpdate();
}catch (SQLException e) {
e.printStackTrace();
} finally {close();}
return row;
}
}
|
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
namespace NetworkToolBox {
/// <summary>
/// An adorner class that contains a floating Text into a canvas to provide
/// the ability to move elements for a TreeView control.
/// </summary>
internal sealed class DragAdorner : Adorner {
#region Private Variables
//Visual children
private VisualCollection _visualChildren;
private TreeViewItem _currentTvi;
private bool _isVisible;
private Point _startPos;
private Canvas _canvas;
private TreeViewItem _lastTvi;
private ItemsControl _tviParent;
private int _tviIndex;
private UIElement _adornedElement;
private TextBlock _floatingText;
private bool isDragging;
private bool cancelDragging;
#endregion
public DragAdorner(UIElement adornedElement, UIElement adorningElement) : base(adornedElement) {
_currentTvi = adorningElement as TreeViewItem;
_tviParent = _currentTvi.Parent as ItemsControl;
_tviIndex = _tviParent.Items.IndexOf(_currentTvi);
_adornedElement = adornedElement;
_adornedElement.PreviewKeyDown += _canvas_KeyDown;
Debug.Assert(_currentTvi != null, "No TreeViewItem");
_visualChildren = new VisualCollection(this);
BuildFloatingItem();
}
#region Public Methods
/// <summary>
/// Specifies whether a Layer is visible.
/// </summary>
/// <param name="isVisible"></param>
public void UpdateVisibilty(bool isVisible) {
_isVisible = isVisible;
InvalidateMeasure();
}
#endregion
#region Protected Methods
/// <summary>
/// Override to measure elements.
/// </summary>
protected override Size MeasureOverride(Size constraint) {
if (_isVisible) {
AdornedElement.Measure(constraint);
return new Size(AdornedElement.RenderSize.Width,
AdornedElement.RenderSize.Height);
} else //if it is not in editable mode, no need to show anything.
return new Size(0, 0);
}
/// <summary>
/// override function to arrange elements.
/// </summary>
protected override Size ArrangeOverride(Size finalSize) {
if (_isVisible) {
_canvas.Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height));
} else // if is not is editable mode, no need to show elements.
{
_canvas.Arrange(new Rect(0, 0, 0, 0));
}
return finalSize;
}
/// <summary>
/// override property to return infomation about visual tree.
/// </summary>
protected override int VisualChildrenCount {
get { return _visualChildren.Count; }
}
/// <summary>
/// override function to return infomation about visual tree.
/// </summary>
protected override Visual GetVisualChild(int index) { return _visualChildren[index]; }
#endregion
#region Private Methods
private void BuildFloatingItem() {
// Building a canvas and a floating Text based on TextBlock with mouse move tracking
_startPos = Mouse.GetPosition(_adornedElement);
_canvas = new Canvas();
_canvas.Background = Brushes.Transparent;
_floatingText = new TextBlock() {
Background = Brushes.LightYellow,
Padding = new Thickness(6, 3, 6, 3),
Text = _currentTvi.Header.ToString(),
Visibility = Visibility.Collapsed
};
_floatingText.PreviewKeyDown += _canvas_KeyDown;
_canvas.Children.Add(_floatingText);
_canvas.MouseEnter += _canvas_MouseEnter;
_canvas.MouseMove += _canvas_MouseMove;
_canvas.PreviewMouseUp += _canvas_PreviewMouseUp;
//_canvas.LayoutUpdated += new EventHandler(OnLayoutUpdated);
_visualChildren.Add(_canvas);
}
private void OnLayoutUpdated(object sender, EventArgs e) {
if (_isVisible)
_canvas.Focus();
}
private void _canvas_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) {
if (isDragging && e.Key == System.Windows.Input.Key.Escape) {
cancelDragging = true;
StopDrag();
}
}
private void _canvas_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e) {
if (e.LeftButton != System.Windows.Input.MouseButtonState.Pressed) {
StopDrag();
}
}
private void _canvas_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) {
StopDrag();
var pos = e.GetPosition(this);
object element = AdornedElement.InputHitTest(pos);
while (element.GetType() != typeof(TreeViewItem) && element.GetType() != typeof(TreeView)) {
element = (element as FrameworkElement).TemplatedParent;
if (element == null) return;
}
if (_lastTvi != null) {
_lastTvi.BorderThickness = new Thickness(0, 0, 0, 0);
_lastTvi.BorderBrush = null;
_lastTvi.Background = Brushes.Transparent;
}
if (element is TreeViewItem && (element as TreeViewItem).Header is Container) {
if (_lastTvi != null && _lastTvi != _currentTvi && !IsChild(_lastTvi)) {
_tviParent.Items.RemoveAt(_tviIndex);
_lastTvi.Items.Add(_currentTvi);
_currentTvi.IsSelected = true;
}
} else if (element is TreeView) {
_tviParent.Items.RemoveAt(_tviIndex);
(element as ItemsControl).Items.Add(_currentTvi);
_currentTvi.IsSelected = true;
}
}
private void StopDrag() {
isDragging = false;
UpdateVisibilty(false);
_canvas.MouseMove -= _canvas_MouseMove;
_adornedElement.PreviewKeyDown -= _canvas_KeyDown;
_visualChildren.Clear();
if (_lastTvi != null) {
_lastTvi.BorderThickness = new Thickness(0, 0, 0, 0);
_lastTvi.BorderBrush = null;
_lastTvi.Background = Brushes.Transparent;
}
}
private void _canvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) {
var pos = e.GetPosition(this);
if (_startPos == pos) return;
if (!isDragging) {
isDragging = true;
var background = new SolidColorBrush(Color.FromArgb(15, 0x9a, 0xcd, 0x32));
_canvas.Background = background;
_floatingText.Visibility = Visibility.Visible;
}
if (cancelDragging) StopDrag();
Canvas.SetLeft(_floatingText, pos.X + SystemParameters.CursorHeight / 2);
Canvas.SetTop(_floatingText, pos.Y + SystemParameters.CursorHeight / 2);
object element = AdornedElement.InputHitTest(pos);
while (element.GetType() != typeof(TreeViewItem)) {
element = (element as FrameworkElement).TemplatedParent;
if (element == null) return;
}
var _tvi = element as TreeViewItem;
if (_tvi != null) {
if (_lastTvi != null && _lastTvi != _tvi) {
_lastTvi.BorderThickness = new Thickness(0, 0, 0, 0);
_lastTvi.BorderBrush = null;
_lastTvi.Background = Brushes.Transparent;
};
if (_tvi.Header is Container && _tvi != _currentTvi && !IsChild(_tvi)) {
_tvi.BorderThickness = new Thickness(0, 0, 0, 2);
_tvi.BorderBrush = Brushes.Black;
_tvi.Background = Brushes.AliceBlue;
}
_lastTvi = _tvi;
}
}
private bool IsChild(TreeViewItem tvi) {
var parent = tvi.Parent;
while (parent != null && parent != _currentTvi) {
parent = (parent as FrameworkElement).Parent;
if (parent == _currentTvi) return true;
}
if (parent == _currentTvi) return true;
return false;
}
#endregion
}
}
|
package cn.zttek.thesis.modules.service;
import cn.zttek.thesis.common.base.BaseService;
import cn.zttek.thesis.modules.mapper.OrgMapper;
import cn.zttek.thesis.modules.model.Org;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
/**
* @描述: 组织机构相关业务处理类
* @作者: Pengo.Wen
* @日期: 2016-08-24 16:44
* @版本: v1.0
*/
@Service
public class OrgService extends BaseService<Org> {
@Autowired
private OrgMapper orgMapper;
/**
* 分页查询组织机构信息
* @param page
* @param rows
* @return
* @throws Exception
*/
public PageInfo<Org> listByPage(int page, int rows) throws Exception{
PageHelper.startPage(page, rows);
List<Org> list = orgMapper.selectAll();
PageInfo<Org> pageInfo = new PageInfo<>(list);
return pageInfo;
}
/**
* 检查机构名称是否已存在
* @param org
* @return
* @throws Exception
*/
public boolean checkName(Org org)throws Exception{
log.info("===检查机构名称[" + org.getName() + "]是否已存在===");
Org temp = orgMapper.getByName(org.getName());
if(temp != null && !temp.getId().equals(org.getId())){
return true;
}
return false;
}
/**
* 保存组织架构信息,并建立文件保存目录
* @param org 需要保存的组织机构实体
* @param docRoot 文件保存根目录
* @return
* @throws Exception
*/
public Org insert(Org org, String docRoot) throws Exception {
log.info("===保存组织架构信息,并建立文件保存目录===");
org.setDocroot(org.getName());
super.insert(org);
File file = new File(docRoot, org.getDocroot());
if(!file.exists()){
file.mkdirs();
}
return org;
}
/**
* 删除某个组织机构,在删除前需要检查
* @param id
* @return
* @throws Exception
*/
public String deleteOnCheck(Long id) throws Exception{
log.info("===删除某个组织机构[" + id + "],在删除前需要检查===");
String msg = "";
Org org = this.queryById(id);
//TODO 使用具体业务(论文工作)进行校验组织机构能否被删除
/*Long cnt = orgMapper.countUsed(id);
if(cnt > 0){
msg = "删除失败, 组织机构[" + org.getName() + "]已被使用,请先在组织机构中解除对该组织机构的使用!";
return msg;
}*/
//TODO 待定删除方法
orgMapper.deleteByPrimaryKey(id);
msg = "组织机构[" + org.getName() + "]删除成功!";
return msg;
}
}
|
import { Database, AnyProperty } from 'shared/types';
import { guardIsChecklistRow, guardIsTableRow } from 'shared/assertions';
import {
getIdb,
getDatabaseFromIndexedDb,
editRowInIndexedDb,
getRowByPositionFromIndexedDb,
reorderRowInIndexedDb,
} from 'utilities/idb';
import { formatPropertyValueFromFormData } from 'shared/formatPropertyValueFromFormData';
import {
ExpressWorkerRequest,
ExpressWorkerResponse,
} from '@express-worker/app';
import { handleRequest } from 'middleware/index';
export async function PutDatabaseRow(
req: ExpressWorkerRequest,
res: ExpressWorkerResponse,
) {
return handleRequest(async (req, res) => {
if (req.data._method !== 'PUT') {
return;
}
const idb = await getIdb();
const databaseId = req.params.databaseId || '';
const database: Database<AnyProperty[]> | null =
await getDatabaseFromIndexedDb(databaseId, idb);
if (!database) {
idb.close();
res.status = 404;
res.text('Not found');
return;
}
const id = req.params.id || '';
const existingRow = database.rows.find((row) => row.id === id);
if (!existingRow) {
idb.close();
res.status = 404;
res.text('Not found');
return;
}
const rowToPut = {
id: existingRow.id,
position: existingRow.position,
databaseId: database.id,
};
for (const property of database.properties) {
const formDataValue = formatPropertyValueFromFormData<typeof property>(
req.data[property.id] ?? existingRow[property.id],
property,
);
if (formDataValue === undefined) {
continue;
}
rowToPut[property.id] = formDataValue;
}
if (
!(
guardIsChecklistRow(rowToPut, database) ||
guardIsTableRow(rowToPut, database)
)
) {
idb.close();
res.status = 404;
res.text('Not found');
return;
}
if (guardIsChecklistRow(rowToPut, database)) {
rowToPut.completed = req.data.completed === 'on';
}
if (req.data.position && req.data.position !== existingRow.position) {
const rowToReorder = await getRowByPositionFromIndexedDb(
req.data.position,
databaseId,
idb,
);
await reorderRowInIndexedDb(existingRow, rowToReorder, idb);
rowToPut.position = req.data.position;
}
await editRowInIndexedDb<typeof database>(rowToPut, idb);
idb.close();
const redirectUrl = new URL(
req.data._redirect || `/databases/${databaseId}`,
new URL(req.url).origin,
);
res.redirect(redirectUrl.href);
})(req, res);
}
|
import type { Meta, StoryObj } from '@storybook/react'
import { Button } from '@/components/button/Button.tsx'
const meta = {
title: 'Components/Button',
component: Button,
parameters: {
layout: 'centered',
},
args: {
variant: 'primary',
},
argTypes: {
children: {
description: 'Button text',
defaultValue: '',
type: 'string',
},
onClick: { description: 'Optional click handler' },
},
tags: ['autodocs'],
} satisfies Meta<typeof Button>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {
args: {
children: 'Button',
},
}
|
import React from "react";
import { render, screen, waitFor, waitForElementToBeRemoved } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import "@testing-library/jest-dom/extend-expect";
import { Provider } from "react-redux";
import store from "../store/index";
import App from "../App";
jest.setTimeout(10000);
describe("App", () => {
it("renders the Home component as the default route", async () => {
render(
<MemoryRouter initialEntries={["/"]}>
<App />
</MemoryRouter>
);
expect(screen.getByTestId("home")).toBeInTheDocument();
});
it("renders the NewEmployee component when navigating to /newemployee", async () => {
render(
<Provider store={store}>
<MemoryRouter initialEntries={["/newemployee"]}>
<App />
</MemoryRouter>
</Provider>
);
await waitForElementToBeRemoved(() => screen.getByTestId("progressbar"), { timeout: 10000 });
expect(screen.getByTestId("newEmployee")).toBeInTheDocument();
});
it("renders the ListEmployees component when navigating to /listemployees", async () => {
render(
<Provider store={store}>
<MemoryRouter initialEntries={["/listemployees"]}>
<App />
</MemoryRouter>
</Provider>
);
await waitForElementToBeRemoved(() => screen.getByTestId("progressbar"), { timeout: 10000 });
expect(screen.getByTestId("listEmployees")).toBeInTheDocument();
});
});
|
/* eslint-disable max-classes-per-file */
import {once} from '../../../util';
import {findFuzzyOnce, patchHexToBytes} from '../patch';
import {CPU_TYPE_I386, CPU_TYPE_X86_64} from './constants';
/**
* MacProjectTitlePatch object.
*/
export abstract class MacProjectTitlePatch {
public static readonly CPU_TYPE: number;
protected _data: Buffer;
protected _vmaddr: number;
protected _title: number;
/**
* MacProjectTitlePatch constructor.
*
* @param data Code data.
* @param vmaddr Code address.
* @param title Title address.
*/
constructor(data: Buffer, vmaddr: number, title: number) {
this._data = data;
this._vmaddr = vmaddr;
this._title = title;
}
/**
* Check patch.
*
* @returns True if valid patch, else false.
*/
public abstract check(): boolean;
/**
* Apply patch.
*/
public abstract patch(): void;
}
/**
* MacProjectTitlePatchI386 object.
*/
export abstract class MacProjectTitlePatchI386 extends MacProjectTitlePatch {
public static readonly CPU_TYPE = CPU_TYPE_I386;
}
/**
* MacProjectTitlePatchX8664 object.
*/
export abstract class MacProjectTitlePatchX8664 extends MacProjectTitlePatch {
public static readonly CPU_TYPE = CPU_TYPE_X86_64;
}
export const macProjectTitlePatches: {
CPU_TYPE: number;
new (data: Buffer, vmaddr: number, title: number): MacProjectTitlePatch;
}[] = [
/**
* 11.0.1.152 i386.
*/
class extends MacProjectTitlePatchI386 {
private _offset_ = 0;
/**
* @inheritDoc
*/
public check() {
const found = findFuzzyOnce(
this._data,
patchHexToBytes(
[
// push ebp
'55',
// mov ebp, esp
'89 E5',
// push esi
'56',
// push ebx
'53',
// sub esp, 0x10
'83 EC 10',
// mov esi, DWORD PTR [ebp+0x8]
'8B 75 08',
// mov eax, DWORD PTR [ebp+0xc]
'8B 45 0C',
// mov ebx, DWORD PTR [eax]
'8B 18',
// mov ecx, DWORD PTR [eax+0x4]
'8B 48 04',
// test ecx, ecx
'85 C9',
// cmove ecx, DWORD PTR ds:...
'0F 44 0D -- -- -- --',
// mov DWORD PTR [esp+0x8], ebx
'89 5C 24 08',
// mov DWORD PTR [esp+0x4], ecx
'89 4C 24 04',
// mov edx, DWORD PTR ds:...
'8B 15 -- -- -- --',
// mov eax, DWORD PTR [edx]
'8B 02',
// mov DWORD PTR [esp], eax
'89 04 24',
// call -- -- -- --
'E8 -- -- -- --'
].join(' ')
)
);
if (found === null) {
return false;
}
this._offset_ = found;
return true;
}
/**
* @inheritDoc
*/
public patch() {
const d = this._data;
let i = this._offset_ + 11;
// lea ecx, ...
d.writeUInt8(0x8d, i++);
d.writeUInt8(0x0d, i++);
d.writeInt32LE(this._title, i);
i += 4;
// mov ebx, DWORD PTR [ecx]
d.writeUInt8(0x8b, i++);
d.writeUInt8(0x19, i++);
// add ecx, 0x4
d.writeUInt8(0x83, i++);
d.writeUInt8(0xc1, i++);
d.writeUInt8(0x04, i++);
// nop 6
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
}
},
/**
* 11.0.1.152 x86_64.
*/
class extends MacProjectTitlePatchX8664 {
private _offset_ = 0;
private _offsetJump_ = 0;
/**
* @inheritDoc
*/
public check() {
const found = findFuzzyOnce(
this._data,
patchHexToBytes(
[
// push rbp
'55',
// mov rbp, rsp
'48 89 E5',
// push r12
'41 54',
// push rbx
'53',
// mov r12, rdi
'49 89 FC',
// mov rdx, QWORD PTR [rsi]
'48 8B 16',
// mov rsi, QWORD PTR [rsi+0x8]
'48 8B 76 08',
// test rsi, rsi
'48 85 F6',
// je --
'74 --',
// mov rax, QWORD PTR [rip+...]
'48 8B 05 -- -- -- --',
// mov rdi, QWORD PTR [rax]
'48 8B 38',
// call -- -- -- --
'E8 -- -- -- --'
].join(' ')
)
);
if (found === null) {
return false;
}
// Sanity check the jump target instructions.
const offsetJump = found + 22 + this._data.readInt8(found + 21);
if (
findFuzzyOnce(
this._data.subarray(offsetJump, offsetJump + 7),
patchHexToBytes(
// lea rsi, [rip+...]
'48 8D 35 -- -- -- --'
)
) !== 0
) {
return false;
}
this._offset_ = found;
this._offsetJump_ = offsetJump;
return true;
}
/**
* @inheritDoc
*/
public patch() {
const d = this._data;
let i = this._offset_ + 10;
// lea rsi, [rip+...]
d.writeUInt8(0x48, i++);
d.writeUInt8(0x8d, i++);
d.writeUInt8(0x35, i++);
d.writeInt32LE(this._title - (this._vmaddr + i + 4), i);
i += 4;
// movsxd rdx, DWORD PTR [rsi]
d.writeUInt8(0x48, i++);
d.writeUInt8(0x63, i++);
d.writeUInt8(0x16, i++);
// jmp --
d.writeUInt8(0xeb, i++);
i = this._offsetJump_;
// add rsi, 0x4
d.writeUInt8(0x48, i++);
d.writeUInt8(0x83, i++);
d.writeUInt8(0xc6, i++);
d.writeUInt8(0x04, i++);
// nop 3
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
}
},
/**
* 13.0.0.182 i386.
*/
class extends MacProjectTitlePatchI386 {
private _offset_ = 0;
/**
* @inheritDoc
*/
public check() {
const found = findFuzzyOnce(
this._data,
patchHexToBytes(
[
// push ebp
'55',
// mov ebp, esp
'89 E5',
// push edi
'57',
// push esi
'56',
// sub esp, 0x10
'83 EC 10',
// call 0xd
'E8 00 00 00 00',
// pop edi
'5F',
// mov eax, DWORD PTR [ebp+0xc]
'8B 45 0C',
// mov ecx, DWORD PTR [eax]
'8B 08',
// mov eax, DWORD PTR [eax+0x4]
'8B 40 04',
// mov DWORD PTR [esp+0x8], ecx
'89 4C 24 08',
// test eax, eax
'85 C0',
// cmove eax, DWORD PTR [edi+...]
'0F 44 87 -- -- -- --',
// mov DWORD PTR [esp+0x4], eax
'89 44 24 04',
// mov eax, DWORD PTR [edi+...]
'8B 87 -- -- -- --',
// mov eax, DWORD PTR [eax]
'8B 00',
// mov DWORD PTR [esp], eax
'89 04 24',
// call -- -- -- --
'E8 -- -- -- --'
].join(' ')
)
);
if (found === null) {
return false;
}
this._offset_ = found;
return true;
}
/**
* @inheritDoc
*/
public patch() {
const edi = this._vmaddr + this._offset_ + 13;
const d = this._data;
let i = this._offset_ + 14;
// lea eax, [edi+...]
d.writeUInt8(0x8d, i++);
d.writeUInt8(0x87, i++);
d.writeInt32LE(this._title - edi, i);
i += 4;
// mov ecx, DWORD PTR [eax]
d.writeUInt8(0x8b, i++);
d.writeUInt8(0x08, i++);
// mov DWORD PTR [esp+0x8], ecx
i += 4;
// add eax, 0x4
d.writeUInt8(0x83, i++);
d.writeUInt8(0xc0, i++);
d.writeUInt8(0x04, i++);
// nop 6
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
}
},
/**
* 13.0.0.182 x86_64.
*/
class extends MacProjectTitlePatchX8664 {
private _offset_ = 0;
/**
* @inheritDoc
*/
public check() {
const found = findFuzzyOnce(
this._data,
patchHexToBytes(
[
// push rbp
'55',
// mov rbp, rsp
'48 89 E5',
// push r14
'41 56',
// push rbx
'53',
// mov r14, rdi
'49 89 FE',
// mov rdx, QWORD PTR [rsi]
'48 8B 16',
// mov rsi, QWORD PTR [rsi+0x8]
'48 8B 76 08',
// test rsi, rsi
'48 85 F6',
// cmove rsi, QWORD PTR [rip+...]
'48 0F 44 35 -- -- -- --',
// mov rax, QWORD PTR [rip+...]
'48 8B 05 -- -- -- --',
// mov rdi, QWORD PTR [rax]
'48 8B 38',
// call -- -- -- --
'E8 -- -- -- --'
].join(' ')
)
);
if (found === null) {
return false;
}
this._offset_ = found;
return true;
}
/**
* @inheritDoc
*/
public patch() {
const d = this._data;
let i = this._offset_ + 10;
// lea rsi, [rip+...]
d.writeUInt8(0x48, i++);
d.writeUInt8(0x8d, i++);
d.writeUInt8(0x35, i++);
d.writeInt32LE(this._title - (this._vmaddr + i + 4), i);
i += 4;
// movsxd rdx, DWORD PTR [rsi]
d.writeUInt8(0x48, i++);
d.writeUInt8(0x63, i++);
d.writeUInt8(0x16, i++);
// add rsi, 0x4
d.writeUInt8(0x48, i++);
d.writeUInt8(0x83, i++);
d.writeUInt8(0xc6, i++);
d.writeUInt8(0x04, i++);
// nop 4
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
}
},
/**
* 23.0.0.162 i386.
*/
class extends MacProjectTitlePatchI386 {
private _offset_ = 0;
/**
* @inheritDoc
*/
public check() {
const found = findFuzzyOnce(
this._data,
patchHexToBytes(
[
// push ebp
'55',
// mov ebp, esp
'89 E5',
// push edi
'57',
// push esi
'56',
// sub esp, 0x10
'83 EC 10',
// call 0xd
'E8 00 00 00 00',
// pop edi
'5F',
// mov eax, DWORD PTR [ebp+0xc]
'8B 45 0C',
// mov ecx, DWORD PTR [edi+...]
'8B 8F -- -- -- --',
// mov ecx, DWORD PTR [ecx]
'8B 09',
// mov edx, DWORD PTR [eax]
'8B 10',
// mov eax, DWORD PTR [eax+0x4]
'8B 40 04',
// test eax, eax
'85 C0',
// cmove eax, DWORD PTR [edi+...]
'0F 44 87 -- -- -- --',
// mov DWORD PTR [esp+0x8], edx
'89 54 24 08',
// mov DWORD PTR [esp+0x4], eax
'89 44 24 04',
// mov DWORD PTR [esp], ecx
'89 0C 24',
// call -- -- -- --
'E8 -- -- -- --'
].join(' ')
)
);
if (found === null) {
return false;
}
this._offset_ = found;
return true;
}
/**
* @inheritDoc
*/
public patch() {
const edi = this._vmaddr + this._offset_ + 13;
const d = this._data;
let i = this._offset_ + 25;
// lea eax, [edi+...]
d.writeUInt8(0x8d, i++);
d.writeUInt8(0x87, i++);
d.writeInt32LE(this._title - edi, i);
i += 4;
// mov edx, DWORD PTR [eax]
d.writeUInt8(0x8b, i++);
d.writeUInt8(0x10, i++);
// add eax, 0x4
d.writeUInt8(0x83, i++);
d.writeUInt8(0xc0, i++);
d.writeUInt8(0x04, i++);
// nop 3
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
}
},
/**
* 23.0.0.162 x86_64.
*/
class extends MacProjectTitlePatchX8664 {
private _offset_ = 0;
/**
* @inheritDoc
*/
public check() {
const found = findFuzzyOnce(
this._data,
patchHexToBytes(
[
// push rbp
'55',
// mov rbp, rsp
'48 89 E5',
// push r14
'41 56',
// push rbx
'53',
// mov r14, rdi
'49 89 FE',
// mov rax, QWORD PTR [rip+...]
'48 8B 05 -- -- -- --',
// mov rdi, QWORD PTR [rax]
'48 8B 38',
// mov rdx, QWORD PTR [rsi]
'48 8B 16',
// mov rsi, QWORD PTR [rsi+0x8]
'48 8B 76 08',
// test rsi, rsi
'48 85 F6',
// cmove rsi, QWORD PTR [rip+...]
'48 0F 44 35 -- -- -- --',
// call -- -- -- --
'E8 -- -- -- --'
].join(' ')
)
);
if (found === null) {
return false;
}
this._offset_ = found;
return true;
}
/**
* @inheritDoc
*/
public patch() {
const d = this._data;
let i = this._offset_ + 20;
// lea rsi, [rip+...]
d.writeUInt8(0x48, i++);
d.writeUInt8(0x8d, i++);
d.writeUInt8(0x35, i++);
d.writeInt32LE(this._title - (this._vmaddr + i + 4), i);
i += 4;
// movsxd rdx, DWORD PTR [rsi]
d.writeUInt8(0x48, i++);
d.writeUInt8(0x63, i++);
d.writeUInt8(0x16, i++);
// add rsi, 0x4
d.writeUInt8(0x48, i++);
d.writeUInt8(0x83, i++);
d.writeUInt8(0xc6, i++);
d.writeUInt8(0x04, i++);
// nop 4
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
}
},
/**
* 35.0.0.1 x86_64.
*/
class extends MacProjectTitlePatchX8664 {
private _offset_ = 0;
/**
* @inheritDoc
*/
public check() {
const found = findFuzzyOnce(
this._data,
patchHexToBytes(
[
// push rbp
'55',
// mov rbp, rsp
'48 89 E5',
// push r14
'41 56',
// push rbx
'53',
// mov r14, rdi
'49 89 FE',
// mov rax, QWORD PTR [rip+...]
'48 8B 05 -- -- -- --',
// mov rdi, QWORD PTR [rax]
'48 8B 38',
// mov rdx, QWORD PTR [rsi]
'48 8B 16',
// mov rsi, QWORD PTR [rsi+0x8]
'48 8B 76 08',
// test rsi, rsi
'48 85 F6',
// jne 0x1d
'75 07',
// lea rsi, [rip+...]
'48 8D 35 -- -- -- --',
// call -- -- -- --
'E8 -- -- -- --'
].join(' ')
)
);
if (found === null) {
return false;
}
this._offset_ = found;
return true;
}
/**
* @inheritDoc
*/
public patch() {
const d = this._data;
let i = this._offset_ + 20;
// lea rsi, [rip+...]
d.writeUInt8(0x48, i++);
d.writeUInt8(0x8d, i++);
d.writeUInt8(0x35, i++);
d.writeInt32LE(this._title - (this._vmaddr + i + 4), i);
i += 4;
// movsxd rdx, DWORD PTR [rsi]
d.writeUInt8(0x48, i++);
d.writeUInt8(0x63, i++);
d.writeUInt8(0x16, i++);
// add rsi, 0x4
d.writeUInt8(0x48, i++);
d.writeUInt8(0x83, i++);
d.writeUInt8(0xc6, i++);
d.writeUInt8(0x04, i++);
// nop 5
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
d.writeUInt8(0x90, i++);
}
}
];
export const macProjectTitlePatchesByCpuType = once(() => {
const r = new Map<number, typeof macProjectTitlePatches[0][]>();
for (const Patcher of macProjectTitlePatches) {
// eslint-disable-next-line @typescript-eslint/naming-convention
const {CPU_TYPE} = Patcher;
const list = r.get(CPU_TYPE) || [];
list.push(Patcher);
r.set(CPU_TYPE, list);
}
return r;
});
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package servlet.book;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import newlibary.ru.rhbal.facade.Facade;
import newlibary.ru.rhbal.manager.exception.UserAlreadyExistException;
import servlet.readers.ReadersCreate;
/**
*
* @author User
*/
public class BooksCreate extends HttpServlet {
Facade facade = new Facade();
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
request.setAttribute("Authors", facade.getAllAuthors());
request.getRequestDispatcher("Create.jsp").forward(request, response);
} catch (SQLException ex) {
request.setAttribute("error", ex.getMessage());
getServletConfig().getServletContext().getRequestDispatcher("/Error/SQLConnectionError.jsp").forward(request, response);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
facade.addBook(request.getParameter("name"),
new Integer(request.getParameter("release")),
request.getParameter("genre"),
new Integer(request.getParameter("authorId")));
} catch (SQLException ex) {
request.setAttribute("error", ex.getMessage());
getServletConfig().getServletContext().getRequestDispatcher("/Error/SQLConnectionError.jsp").forward(request, response);
}
response.setStatus(301);
response.addHeader("Location", "/TEstLibaryProjectTomcatNew/Books");
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
import { createServer as createHattipServer } from '@hattip/adapter-node'
import httpProxy from 'http-proxy'
import { setup } from '@vite-env/core'
import { normalizePath } from 'vite'
export const dev = async () => {
const { viteServer, env, runner } = await setup()
if (!env.runModule || !env.selectModule) {
throw new Error('this environment is not supported by vite-env standalone')
}
// handle unhandledRejection so that the process won't exit
process.on('unhandledRejection', (err) => {
console.log('Unhandled Rejection: ', err)
})
await viteServer.listen()
const viteUrlString =
viteServer.resolvedUrls!.local[0] ?? viteServer.resolvedUrls!.network[0]
const viteUrl = new URL(viteUrlString)
const proxyServer = httpProxy.createProxyServer({
target: viteUrlString,
ws: true
})
const hattipServer = createHattipServer(async (ctx) => {
try {
// TODO: should "page reload" clear all modules on vite-node side?
runner.moduleCache.clear()
const resolved = await env.selectModule!(
ctx.request,
viteServer.config.root
)
if (resolved === undefined) {
// NOTE: If Vite uses Universal/Modern middlewares in the future,
// we can avoid using actual HTTP requests.
// It's difficult to convert Node middlewares into them.
// https://github.com/fastly/http-compute-js#notes--known-issues
const newUrl = new URL(ctx.request.url)
newUrl.protocol = viteUrl.protocol
newUrl.host = viteUrl.host
try {
return await fetch(new Request(newUrl.href, ctx.request))
} catch (e) {
console.error('Failed to proxy request to Vite server: ', e)
return new Response(null, { status: 500 })
}
}
const normalizedResolved = normalizePath(resolved)
const module = await runner.executeFile(normalizedResolved)
const res = await env.runModule!(module, ctx.request, {
viteUrl: viteUrlString
})
return res
} catch (e) {
console.error('Error during evaluation: ', e)
return new Response(null, { status: 500 })
}
})
hattipServer.on('upgrade', (req, socket, head) => {
proxyServer.ws(req, socket, head)
})
hattipServer.listen(51733, 'localhost', () => {
console.log('Server listening on http://localhost:51733')
})
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use App\Http\Resources\UserResource;
class AuthController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make(
$request->all(),
[
'firstName' => 'required|string|max:255',
'lastName' => 'required|string|max:255',
'email' => 'required|string|max:255|email|unique:users',
'password' => 'required|string|min:5'
]
);
if ($validator->fails()) {
return response()->json($validator->errors());
}
$user = User::create([
'firstName' => $request->firstName,
'lastName' => $request->lastName,
'email' => $request->email,
'password' => Hash::make($request->password),
'email_verified_at' => now()
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json(['response' => 'success', 'created_user' => new UserResource($user), 'access_token' => $token, 'token_type' => 'Bearer']);
}
public function login(Request $request)
{
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json(['success' => 'false']);
}
$user = User::where('email', $request['email'])->first();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json(['success' => 'true', 'access_token' => $token, 'token_type' => 'Bearer','user'=>$user]);
}
}
|
/* Define o modelo de caixa "border-box", onde a largura e altura dos elementos incluem o preenchimento e a borda, mas não a margem. */
* {
box-sizing: border-box;
}
/* Remove a margem padrão do elemento body. */
body {
margin: 0;
}
/* Remove a margem do elemento header e define a direção dos elementos filhos como uma coluna. */
header {
margin: 0;
display: flex;
flex-direction: column;
}
/* Define a altura do elemento com a classe "header" como 50px e a cor de fundo como preto (#000). */
.header {
height: 50px;
background-color: #000;
}
/* Define a largura do elemento com a classe "slider" como 100% da largura visível da janela (viewport) e a altura como 400px.
O conteúdo que exceder a largura ou altura será oculto. */
.slider {
width: 100vw;
height: 400px;
overflow: hidden;
}
/* Define a altura do elemento com a classe "slider--width" como 100% da altura do pai (slider) e define o elemento como um flex container.
A propriedade "transition" especifica a duração e o tipo de transição para todas as propriedades animadas. */
.slider--width {
height: 100%;
display: flex;
transition: all ease 0.3s;
}
/* Define a largura do elemento com a classe "slider--item" como 100% da largura visível da janela (viewport) e a altura como a altura herdada do elemento pai.
"background-position" define o posicionamento da imagem de fundo no centro, e "background-size" define o dimensionamento da imagem de fundo para cobrir o elemento.
"display: flex;" torna o elemento um flex container e "justify-content: center;" e "align-items: flex-end;" centralizam e alinham os itens filho no centro e na parte inferior, respectivamente.
Também define a cor do texto como branco (#FFF), adiciona uma sombra de texto para melhor legibilidade e define o tamanho da fonte como 50px. */
.slider--item {
width: 100vw;
height: inherit;
background-position: center;
background-size: cover;
display: flex;
justify-content: center;
align-items: flex-end;
color: #FFF;
text-shadow: 0px 1px 1px #333;
font-size: 50px;
}
/* Define o alinhamento dos itens filho do elemento com o ID "slider--item-2" para ficarem alinhados no topo. */
#slider--item-2{
align-items: flex-start;
}
/* Define a posição como "absoluta", permitindo o posicionamento relativo a elementos pai posicionados.
"z-index" define a ordem de empilhamento do elemento. Quanto maior o valor, maior a prioridade na sobreposição.
"display: flex;" torna o elemento um flex container e "justify-content: space-between;" alinha os itens filho com espaçamento igual entre eles horizontalmente.
"align-items: center;" centraliza os itens filho verticalmente. */
.slider--controls {
position: absolute;
z-index: 99;
display: flex;
justify-content: space-between;
align-items: center;
}
/* Define a largura do elemento com a classe "slider--control" como 70px, a altura como 30px e a cor de fundo como branco (#FFF).
"border-radius: 10px;" define o raio dos cantos do elemento, criando bordas arredondadas.
"overflow: hidden;" esconde qualquer conteúdo que exceda os limites do elemento.
"cursor: pointer;" define o cursor do mouse como um ponteiro para indicar interatividade.
"margin: 10px;" adiciona margem externa de 10px em todos os lados do elemento.
"padding: 10px;" adiciona preenchimento interno de 10px em todos os lados do elemento.
"font-size: 10px;" define o tamanho da fonte como 10px. */
.slider--control {
width: 70px;
height: 30px;
background-color: #FFF;
border-radius: 10px;
overflow: hidden;
cursor: pointer;
margin: 10px;
padding: 10px;
font-size: 10px;
}
|
const express = require('express');
const path = require('path');
const http = require('http');
const socketio = require('socket.io');
const formatMessage = require('./utils/messages');
const {userJoin, getCurrentUser, userLeave, getRoomUsers} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
//Set static folder
app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.static("public"));
//const PORT = process.env.PORT || 3000;
//const server = app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
//const io = socketio(server);
const botName = "ChatBot";
//Run when client connects
io.on('connection', socket => {
socket.on('joinRoom', ({username, room}) => {
const user = userJoin(socket.id, username , room);
socket.join(user.room);
//single client emit ,,, welcome current user
socket.emit('message', formatMessage(botName, 'Welcome to CHAT!!'));
//Broadcast when a user connects.... all clients except the user itself
socket.broadcast.to(user.room).emit('message', formatMessage(botName, `${user.username} has joined the chat.`));
//all clients emit
//io.emit();
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
// Listen for chatMessage
socket.on('chatMessage', (msg) => {
const user = getCurrentUser(socket.id);
io.to(user.room).emit('message', formatMessage(user.username, msg));
});
// Runs when client disconnects
socket.on('disconnect', () => {
const user = userLeave(socket.id);
if(user)
{
io.to(user.room).emit('message', formatMessage(botName, `${user.username} has left the chat`));
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
//https://my-pepoard.herokuapp.com/
|
const input = document.getElementsByClassName("input")[0];
const hangmanParts = document.querySelectorAll(".item");
const popup = document.querySelector(".popup");
const success = document.querySelector(".success");
const againButton = document.querySelector(".again");
const wrongs = document.querySelector("#wrongs");
let gameEnded = false;
let pressedKey;
const correctLetters = [];
const wrongLetters = [];
//tahmin edilecek kelime random şekilde seçilir
const getRandomWord = () => {
const words = ["java","python"]
return words[Math.floor(Math.random()* words.length)]
}
let selectedWord = getRandomWord();
//doğru harflerin ekranda gösterimini sağlar.
const display = () => {
input.innerHTML = `
${selectedWord.split('').map(letter => `
<div class="letter">
${correctLetters.includes(letter) ? letter : ' '}
</div>
`).join('')}
`;
const w = input.innerText.replace(/\n/g,'');
if (w === selectedWord) {
popup.style.display = "flex";
success.innerText = "Kazandınız";
againButton.addEventListener("click", isAgainClicked); // isAgainClicked() şeklinde çağrılırsa return değer bekler.
}else{
againButton.addEventListener("click", isAgainClicked);
}
}
// hatalı kelimeleri ekranda gösterir.
const showWrongLetters = () => {
const showWrong = wrongLetters.join(',');
wrongs.innerText = showWrong;
}
// hangman'in partlarını gösterir.
const showHangman = () => {
hangmanParts.forEach((item,index) =>{
const error = wrongLetters.length;
if (index < error){
item.style.display = "block";
}else{
item.style.display = "none";
}
})
}
// tekrar oynaya basılırsa eventine karşılık gelen fonksiyon.
const isAgainClicked = () =>{
correctLetters.splice(0,correctLetters.length);
wrongLetters.splice(0,wrongLetters.length);
pressedKey = null;
selectedWord = getRandomWord();
popup.style.display = "none";
wrongs.innerText ="";
display();
hangmanParts.forEach(item => {
item.style.display = "none";
});
gameEnded = false;
}
//klavye inputlarını dinler.
window.addEventListener("keydown", (e) =>{
if(!gameEnded && e.keyCode >= 65 && e.keyCode <= 95){
pressedKey = e.key;
if(selectedWord.includes(pressedKey)) {
if(!correctLetters.includes(pressedKey)){
correctLetters.push(pressedKey);
console.log(correctLetters);
display();
}
else{
console.log("bu harf zaten var");
}
}else{
if(!wrongLetters.includes(pressedKey)){
wrongLetters.push(pressedKey);
console.log("bu harf kelimede yok");
if(wrongLetters.length == hangmanParts.length){
popup.style.display = "flex";
success.innerText = "Kaybettiniz";
gameEnded = true;
display();
}
showWrongLetters();
showHangman();
}
}
}
});
display();
|
Takes a list of columns and a dataframe and imputes based on
the column type. If it is object type, then most_frequent value
is used for imputation. If it is a float/int type, then the median value is used for imputation.
arguments:
cols: list of columns
df : dataframe containing these columns.
returns:
df: the imputed dataframe
from sklearn.impute import SimpleImputer
def replace_missing_values(cols, df):
for col in cols:
if df[col].dtypes == 'object':
print("Imputing {} column with most frequent value".format(col))
mode_imputer = SimpleImputer(strategy='most_frequent')
df.loc[:, col] = mode_imputer.fit_transform(df[[col]])
elif df[col].dtype == 'float64' or df[col].dtype == 'int64':
print("Imputing {} column with median value".format(col))
median_imputer = SimpleImputer(strategy='median')
df.loc[:, col] = median_imputer.fit_transform(df[[col]])
else:
raise ValueError("Invalid column type")
return df
|
<div class="create-plant-container">
<h3>
<img
class="plant-icon"
src="../../../assets/plant_8889402.png"
alt="plant icon"
/>
Add new plant to your diary:
</h3>
<form [formGroup]="plantForm">
<div class="form-group">
<label for="plantName"> Plant name:</label>
<input
type="text"
formControlName="plantName"
class="form-control"
[ngClass]="{ 'is-invalid': submitted && f['plantName'].errors }"
/>
<div *ngIf="submitted && f['plantName'].errors" class="invalid-feedback">
<div *ngIf="f['plantName'].errors['required']">
Plant name of the plant is required
</div>
<div *ngIf="f['plantName'].errors['maxlength']">
Plant name c'ant be more than 50 characters
</div>
</div>
</div>
<div class="form-group">
<label for="plantNickName">
Plant nickname
<span class="not-required">(not required)</span>:</label
>
<input
type="text"
formControlName="plantNickName"
class="form-control"
[ngClass]="{ 'is-invalid': submitted && f['plantNickName'].errors }"
/>
<div
*ngIf="submitted && f['plantNickName'].errors"
class="invalid-feedback"
>
<div *ngIf="f['plantNickName'].errors['maxlength']">
Plant nickName c'ant be more than 50 characters
</div>
</div>
</div>
<div class="form-group">
<label for="plantFamily">
Plant family <span class="not-required">(not required)</span>:</label
>
<input
type="text"
formControlName="plantFamily"
class="form-control"
[ngClass]="{ 'is-invalid': submitted && f['plantFamily'].errors }"
/>
<div
*ngIf="submitted && f['plantFamily'].errors"
class="invalid-feedback"
>
<div *ngIf="f['plantFamily'].errors['required']">Email is required</div>
<div *ngIf="f['plantFamily'].errors['maxlength']">
Plant nickName c'ant be more than 50 characters
</div>
</div>
</div>
<div class="form-group">
<label for="light"> Select plant light requirement</label>
<select formControlName="light">
<option *ngFor="let light of lightRequirement" [value]="light">
{{ light | titlecase }}
</option>
</select>
</div>
<div class="form-group">
<label for="water"> Plant watering requirements:</label>
<input
type="text"
formControlName="water"
class="form-control"
placeholder="Plant watering needs"
[ngClass]="{ 'is-invalid': submitted && f['water'].errors }"
/>
<div *ngIf="submitted && f['water'].errors" class="invalid-feedback">
<div *ngIf="f['water'].errors['required']">
Plant watering needs are required
</div>
<div *ngIf="f['water'].errors['maxlength']">
Plant watering needs c'ant be more than 50 characters
</div>
</div>
</div>
<div class="form-group">
<label for="water"> Add plant image:</label>
<input
#fileUpload
type="file"
id="image"
name="image"
accept="image/*"
formControlName="image"
(change)="onFileSelected($event)"
required
[ngClass]="{ 'is-invalid': submitted && f['image'].errors }"
formControlName="image"
class="form-control"
style="display: none"
/>
<div class="file-upload">
{{ fileName || "No file uploaded yet." }}
<button
mat-mini-fab
color="primary"
class="upload-btn"
(click)="fileUpload.click()"
>
<span>UPLOAD</span>
</button>
</div>
<div *ngIf="submitted && f['image'].errors" class="invalid-feedback">
<div *ngIf="f['image'].errors['required']">Plant image is required</div>
</div>
</div>
<div class="invalid-feedback" *ngIf="isImage">
{{ isImage }}
</div>
</form>
<div class="image-preview" *ngIf="uploadedImage">
<p>Preview selected image:</p>
<img class="selected-image" [src]="uploadedImage" alt="Uploaded Image" />
<a (click)="clearImage(); fileUpload.value = ''"
><mat-icon class="close-icon" fontIcon="close"></mat-icon>Clear image</a
>
</div>
<div class="invalid-feedback" *ngIf="errorMsg">
{{ errorMsg }}
</div>
<div class="dialog-buttons">
<button class="cancel-btn" mat-button (click)="onCancel()">Cancel</button>
<button
class="add-plant"
mat-button
[disabled]="plantForm.invalid"
(click)="addPlant()"
>
<loading-icon *ngIf="isLoading"></loading-icon>
Add plant
</button>
</div>
</div>
|
import React, { useState, useEffect } from "react";
import "./App.css";
function App() {
const [comments, setComments] = useState([]);
const [filteredComments, setFilteredComments] = useState([]);
const [postIdFilter, setPostIdFilter] = useState("");
const [currentPage, setCurrentPage] = useState(1);
const [commentsPerPage] = useState(10); // Number of comments per page
const [rightPanelComments, setRightPanelComments] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/comments")
.then((response) => response.json())
.then((data) => {
setComments(data);
setFilteredComments(data);
});
}, []);
const handleFilterChange = (e) => {
const filterValue = e.target.value;
setPostIdFilter(filterValue);
if (filterValue === "") {
setFilteredComments(comments);
} else {
const filtered = comments.filter(
(comment) => comment.postId.toString() === filterValue
);
setFilteredComments(filtered);
}
};
const handleCommentClick = (postId) => {
const commentsForPost = comments.filter(
(comment) => comment.postId === postId
);
setRightPanelComments(commentsForPost);
};
const indexOfLastComment = currentPage * commentsPerPage;
const indexOfFirstComment = indexOfLastComment - commentsPerPage;
const currentComments = filteredComments.slice(
indexOfFirstComment,
indexOfLastComment
);
const paginate = (pageNumber) => {
setCurrentPage(pageNumber);
};
return (
<div className="App">
<div className="left-panel">
<h2>Posts</h2>
<input
type="text"
placeholder="Filter by postId"
value={postIdFilter}
onChange={handleFilterChange}
/>
<div className="scrollable-list">
<ul>
{currentComments.map((comment) => (
<li
key={comment.id}
onClick={() => handleCommentClick(comment.postId)}
>
{comment.body}
</li>
))}
</ul>
</div>
<div className="pagination">
<button
onClick={() => paginate(currentPage - 1)}
disabled={currentPage === 1}
>
Previous
</button>
<span className="page-number">{currentPage}</span>
<button
onClick={() => paginate(currentPage + 1)}
disabled={
currentPage ===
Math.ceil(filteredComments.length / commentsPerPage)
}
>
Next
</button>
</div>
</div>
<div className="right-panel">
<h2>Comments</h2>
<div className="scrollable-comments">
<ul>
{rightPanelComments.map((comment) => (
<li key={comment.id}>{comment.body}</li>
))}
</ul>
{/* Add comments here */}
</div>
</div>
</div>
);
}
export default App;
|
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ShoesOnContainers.Web.WebMvc.Infrastructure;
using ShoesOnContainers.Web.WebMvc.Services;
namespace ShoesOnContainers.Web.WebMvc
{
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment environment)
{
Environment = environment;
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public IWebHostEnvironment Environment { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration);
services.AddSingleton<IHttpClient, CustomHttpClient>();
services.AddTransient<ICatalogService, CatalogService>();
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
// disable
// app.UseHsts();
}
// disable for docker
// app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
|
from typing import Union, Tuple, List
import socket
import ipaddress
from datetime import datetime
from django.db import transaction
from django.utils import timezone as dj_timezone
from django.utils.translation import gettext as _
from core import site_configs_manager
from apps.users.models import Email
from apps.users import managers as user_manager
from apps.app_global.models import TimedTaskLock
def get_local_ips() -> List[str]:
return socket.gethostbyname_ex(socket.gethostname())[-1]
# ipaddr = socket.gethostbyname(socket.gethostname())
# return [ipaddr]
# info = socket.getaddrinfo(host=socket.gethostname(), port=None, family=socket.AF_INET, type=socket.SOCK_DGRAM)
# return [info[0][4][0]]
_private_networks = [
ipaddress.IPv4Network('10.0.0.0/8'),
ipaddress.IPv4Network('192.168.0.0/16'),
ipaddress.IPv4Network('172.16.0.0/12'),
]
def get_local_ip_str() -> str:
ips = get_local_ips()
if len(ips) == 1:
return ips[0]
pri_addrs = []
for addr in ips:
try:
ipv4_addr = ipaddress.IPv4Address(addr)
if not ipv4_addr.is_private: # 公网IP直接返回
return addr
if any(ipv4_addr in net for net in _private_networks): # 私网
pri_addrs.append(addr)
except (ipaddress.AddressValueError, ipaddress.NetmaskValueError):
pass
if pri_addrs:
return pri_addrs[0]
return ''
class TaskLockManager:
@staticmethod
def get_task_lock_obj(task: str) -> TimedTaskLock:
"""
获取锁对象,可查询锁状态
"""
if task not in TimedTaskLock.Task.values:
raise Exception(_('无效的定时任务锁标识'))
obj, created = TimedTaskLock.objects.get_or_create(task=task)
return obj
@staticmethod
def acquire_task_lock(task: str, expire_time: datetime) -> Tuple[bool, Union[None, Exception], TimedTaskLock]:
"""
尝试获取并锁定任务锁
:param task: 任务锁的标识
:param expire_time: 如果获得锁,加锁锁定的过期时间,用于后面的任务执行周期拿不到锁时判断历史周期中锁是否存在未释放问题
:return:
False, Exception, TimedTaskLook() # 未得到锁,互斥锁已被锁定
True, None, TimedTaskLook() # 拿到互斥锁
"""
try:
with transaction.atomic():
task_lock = TimedTaskLock.objects.select_for_update().get(task=task)
ok, exc, tlock = TaskLockManager._lock(task_lock=task_lock, expire_time=expire_time)
return ok, exc, tlock
except TimedTaskLock.DoesNotExist:
TaskLockManager.get_task_lock_obj(task=task)
with transaction.atomic():
task_lock = TimedTaskLock.objects.select_for_update().get(task=task)
ok, exc, tlock = TaskLockManager._lock(task_lock=task_lock, expire_time=expire_time)
return ok, exc, tlock
@staticmethod
def _lock(task_lock: TimedTaskLock, expire_time: datetime) -> Tuple[bool, Union[None, Exception], TimedTaskLock]:
"""
:return:
False, Exception, TimedTaskLook() # 未得到锁,互斥锁已被锁定
True, None, TimedTaskLook() # 拿到互斥锁
"""
if task_lock.status == task_lock.Status.RUNNING.value:
return False, Exception(f'Locking,task({task_lock.task}) is running'), task_lock
task_lock.status = task_lock.Status.RUNNING.value
task_lock.expire_time = expire_time
task_lock.notify_time = None
task_lock.save(update_fields=['status', 'expire_time', 'notify_time'])
return True, None, task_lock
@staticmethod
def mark_lock_task_start(
task_lock: TimedTaskLock, start_time: datetime = None
) -> Tuple[bool, Union[None, Exception], TimedTaskLock]:
"""
更新定时任务执行信息
"""
old_start_time = task_lock.start_time
old_end_time = task_lock.end_time
old_host = task_lock.host
old_run_desc = task_lock.run_desc
try:
host_ipv4 = get_local_ip_str()
task_lock.start_time = start_time if start_time else dj_timezone.now()
task_lock.end_time = None
task_lock.host = host_ipv4
task_lock.run_desc = ''
task_lock.save(update_fields=['start_time', 'end_time', 'host', 'run_desc'])
except Exception as exc:
task_lock.start_time = old_start_time
task_lock.end_time = old_end_time
task_lock.host = old_host
task_lock.run_desc = old_run_desc
return False, exc, task_lock
return True, None, task_lock
@staticmethod
def release_task_lock(task: str, run_desc: str) -> Tuple[bool, Union[None, Exception], TimedTaskLock]:
"""
:run_desc: 任务执行结果描述;success, 或者执行发生错误时错误信息
:return:
False, Exception, TimedTaskLock() # 释放锁失败
True, None, TimedTaskLock() # 释放锁成功
"""
with transaction.atomic():
task_lock = TimedTaskLock.objects.select_for_update().get(task=task)
ok, exc, task_lock = TaskLockManager._release(task_lock=task_lock, run_desc=run_desc)
if not ok:
ok, exc, task_lock = TaskLockManager._release(task_lock=task_lock, run_desc=run_desc)
return ok, exc, task_lock
@staticmethod
def _release(task_lock: TimedTaskLock, run_desc: str) -> Tuple[bool, Union[None, Exception], TimedTaskLock]:
"""
:return:
False, Exception, TimedTaskLock() # 释放锁失败
True, None, TimedTaskLock() # 释放锁成功
"""
old_status = task_lock.status
old_expire_time = task_lock.expire_time
old_notify_time = task_lock.notify_time
task_lock.status = task_lock.Status.NONE.value
task_lock.end_time = dj_timezone.now()
task_lock.run_desc = run_desc[0:254]
task_lock.expire_time = None
task_lock.notify_time = None
try:
task_lock.save(update_fields=['status', 'end_time', 'run_desc', 'expire_time', 'notify_time'])
except Exception as exc:
task_lock.status = old_status
task_lock.expire_time = old_expire_time
task_lock.notify_time = old_notify_time
task_lock.end_time = None
task_lock.run_desc = ''
return False, exc, task_lock
return True, None, task_lock
class TaskLock:
"""
不要直接修改任务锁对象,通过方法操作
"""
TaskNames = TimedTaskLock.Task
def __init__(self, task_name: str):
"""
各定时任务锁名定义于 TimedTaskLock.Task,各任务定义唯一对应的锁,不能混用
"""
if task_name not in TimedTaskLock.Task.values:
raise Exception(_('无效的定时任务锁标识'))
self.task_name = task_name
self._task_lock = None
self._is_locked = False # 锁是否已锁定
def _ensure_lock(self):
if not self._task_lock:
self._task_lock = TaskLockManager.get_task_lock_obj(task=self.task_name)
def __getattr__(self, attr):
self._ensure_lock()
try:
return getattr(self._task_lock, attr)
except AttributeError:
return self.__getattribute__(attr)
def save(self):
raise Exception('TaskLock is readonly')
def refresh(self):
"""
从数据库重新加载锁
"""
if self._task_lock:
self._task_lock.refresh_from_db()
else:
self._ensure_lock()
def acquire(self, expire_time: datetime):
"""
:param expire_time: 获得锁加锁锁定时,设置锁的过期时间,用于后面的任务执行周期拿不到锁时判断历史周期中锁是否未释放
:return:
False, Exception # 未得到锁,互斥锁已被锁定
True, None # 拿到互斥锁
"""
if expire_time <= dj_timezone.now():
raise Exception(_('锁过期时间必须大于当前时间'))
ok, exc, tlock = TaskLockManager.acquire_task_lock(task=self.task_name, expire_time=expire_time)
self._task_lock = tlock
if ok:
self._is_locked = True
else:
self._expired_unrelease_notify()
return ok, exc
def mark_start_task(self, start_time: datetime = None):
"""
执行任务前,更新任务锁的任务执行信息,需要先拿到锁才能执行此函数
如更新任务执行开始时间 “start_time”和“host”,清空“end_time”和“run_desc”
:param start_time: 默认为当前时间;各定时器任务如果有时间对齐的需要,可以自行指定
:return:
False, Exception # 失败
True, None # 成功
"""
if not self._is_locked:
raise Exception(_('需要先调用方法“acquire()”成功拿到锁后,确定执行任务前才可以调用方法"mark_start_task()"'))
ok, exc, tlock = TaskLockManager.mark_lock_task_start(task_lock=self._task_lock, start_time=start_time)
if not ok:
ok, exc, tlock = TaskLockManager.mark_lock_task_start(task_lock=self._task_lock, start_time=start_time)
self._task_lock = tlock
return ok, exc
def release(self, run_desc: str):
"""
:run_desc: 任务执行结果描述;success, 或者执行发生错误时错误信息
:return:
False, Exception # 释放锁失败
True, None # 释放锁成功
"""
ok, exc, tlock = TaskLockManager.release_task_lock(task=self.task_name, run_desc=run_desc)
self._task_lock = tlock
if ok:
self._is_locked = False
return ok, exc
def _expired_unrelease_notify(self):
"""
定时任务锁过期未释放发送通知
"""
tlock: TimedTaskLock = self._task_lock
# 锁定状态才发送通知
if tlock.status != TimedTaskLock.Status.RUNNING.value:
return None
nt = dj_timezone.now()
if not tlock.expire_time or tlock.expire_time > nt:
return None
# 锁过期超时
# 已发送过通知,同一天内不再发送
if tlock.notify_time and tlock.notify_time.date() == nt.date():
return None
email = self.notify_unrelease()
return email
def notify_unrelease(self):
"""
锁未释放发送通知
"""
tlock = self._task_lock
message = f"""
您好:
{site_configs_manager.get_website_brand()} 后端服务定时任务锁({tlock.get_task_display()})超时未释放,请尽快手动释放锁,以防影响定时任务执行。
祝好
"""
user_qs = user_manager.filter_user_queryset(is_federal_admin=True)
receivers = user_qs.values_list('username', flat=True) # [u.username for u in user_qs]
if not receivers:
return None
email = Email.send_email(
subject=_('定时任务锁过期未释放通知'),
receivers=receivers,
message=message,
tag=Email.Tag.OTHER.value,
save_db=True, is_feint=False
)
if email.status == Email.Status.SUCCESS.value:
old_notify_time = tlock.notify_time
tlock.notify_time = dj_timezone.now()
try:
tlock.save(update_fields=['notify_time'])
except Exception:
tlock.notify_time = old_notify_time
return email
|
import {
Button,
Col,
Form,
Input,
InputNumber,
Modal,
Radio,
Row,
Select,
Table,
Tabs,
message,
notification,
} from "antd";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import {
callChangePassword,
callCreateSkills,
callFetchCurrentAccount,
callFetchResumesByUserId,
callFetchSkills,
callUpdateSkills,
callUpdateUser,
} from "../../services/api";
import { SKILLS_LIST } from "../../config/sample";
import { useDispatch, useSelector } from "react-redux";
import {
doGetAccountAction,
doUpdateUser,
} from "../../redux/account/accountSlice";
const UserResume = () => {
const [loading, setLoading] = useState(false);
const [resumesUser, setResumesuser] = useState([]);
const fetchResumesByUserId = async () => {
setLoading(true);
const res = await callFetchResumesByUserId();
if (res && res.data) {
setLoading(false);
setResumesuser(res.data);
}
};
useEffect(() => {
fetchResumesByUserId();
}, []);
const columns = [
{
title: "STT",
dataIndex: "index",
render: (text, record, index) => {
return <>{index + 1}</>;
},
},
{
title: "Công Ty",
dataIndex: ["companyId", "name"],
},
{
title: "Vị trí",
dataIndex: ["jobId", "name"],
},
{
title: "Trạng thái",
dataIndex: "status",
},
{
title: "Ngày rải CV",
dataIndex: "createdAt",
render(value, record, index) {
return <>{dayjs(record.createdAt).format("DD-MM-YYYY HH:mm:ss")}</>;
},
},
{
title: "",
dataIndex: "",
render(value, record, index) {
return (
<a
href={`${import.meta.env.VITE_BACKEND_URL}/images/resume/${
record?.url
}`}
target="_blank"
>
Chi tiết
</a>
);
},
},
];
return (
<Table
columns={columns}
dataSource={resumesUser}
loading={loading}
pagination={false}
scroll={{ x: true }}
/>
);
};
const JobByEmail = () => {
const optionsSkills = SKILLS_LIST;
const [form] = Form.useForm();
const [isSubscriber, setIsSubscriber] = useState(false);
const user = useSelector((state) => state.account.user);
const handleRegisterSkills = async () => {
let data = {
email: user?.email,
name: user?.fullname,
skills: [],
};
const res = await callCreateSkills(data);
if (res && res.data) {
message.success("Đăng ký nhận job thành công");
setIsSubscriber(true);
}
};
useEffect(() => {
const init = async () => {
const res = await callFetchSkills();
if (res && res.data) {
setIsSubscriber(true);
form.setFieldValue("skills", res.data.skills);
} else {
setIsSubscriber(false);
}
};
init();
}, []);
const onFinish = async (values) => {
const { skills } = values;
let data = {
email: user?.email,
name: user?.fullname,
skills: skills ? skills : [],
};
const res = await callUpdateSkills(data);
if (res && res.data) {
message.success("Cập nhật skills thành công");
} else {
notification.error({
message: "Đã có lỗi xảy ra",
description: res.message,
});
}
};
return (
<Form form={form} onFinish={onFinish}>
{isSubscriber ? (
<Row gutter={[20, 20]}>
<Col span={24}>
<Form.Item
label="Kỹ năng"
name="skills"
rules={[
{ required: true, message: "Vui lòng chọn ít nhất 1 skill!" },
]}
>
<Select
mode="multiple"
allowClear
placeholder="Chọn kĩ năng"
options={optionsSkills}
/>
</Form.Item>
</Col>
<Col span={24}>
<Button onClick={() => form.submit()}>Cập nhật</Button>
</Col>
</Row>
) : (
<Button onClick={handleRegisterSkills}>Đăng ký</Button>
)}
</Form>
);
};
const UpdateInfo = () => {
const user = useSelector((state) => state.account.user);
const [loading, setLoading] = useState(false);
const [form] = Form.useForm();
const dispatch = useDispatch();
const options = [
{ label: "Nam", value: "MALE" },
{ label: "Nữ", value: "FEMALE" },
];
const onChangeGender = ({ target: { value } }) => {
setGender(value);
};
useEffect(() => {
const init = {
_id: user?._id,
fullname: user?.fullname,
age: user?.age,
gender: user?.gender,
address: user?.address,
};
form.setFieldsValue(init);
}, []);
const onFinish = async (values) => {
const { _id, fullname, age, gender, address } = values;
let data = { fullname, age, gender, address };
setLoading(true);
const res = await callUpdateUser(_id, data);
if (res && res.data) {
setLoading(false);
dispatch(doUpdateUser(res.data.userUpdated));
message.success("Cập nhật thông tin thành công !");
} else {
notification.error({
message: "Có lỗi xảy ra!",
description:
res.message && Array.isArray(res.message)
? res.message[0]
: res.message,
duration: 5,
});
}
};
return (
<Form form={form} onFinish={onFinish}>
<Row gutter={[20, 20]}>
<Col span={0}>
<Form.Item
labelCol={{ span: 6 }}
label="ID"
name="_id"
rules={[{ required: true, message: "Vui lòng nhập _id !" }]}
>
<Input />
</Form.Item>
</Col>
<Col xs={{ span: 24 }} md={{ span: 12 }}>
<Form.Item
labelCol={{ span: 6 }}
label="Họ tên"
name="fullname"
rules={[{ required: true, message: "Vui lòng nhập họ tên !" }]}
>
<Input />
</Form.Item>
</Col>
<Col xs={{ span: 24 }} md={{ span: 12 }}>
<Form.Item
labelCol={{ span: 6 }}
label="Tuổi"
name="age"
rules={[{ required: true, message: "Vui lòng nhập tuổi !" }]}
>
<InputNumber style={{ width: "100%" }} />
</Form.Item>
</Col>
</Row>
<Row gutter={[20, 20]}>
<Col xs={{ span: 24 }} md={{ span: 12 }}>
<Form.Item
labelCol={{ span: 6 }}
label="Giới tính"
name="gender"
rules={[
{ required: true, message: "Vui lòng nhập lại mật khẩu !" },
]}
>
<Radio.Group
options={options}
onChange={onChangeGender}
optionType="button"
buttonStyle="solid"
/>
</Form.Item>
</Col>
<Col xs={{ span: 24 }} md={{ span: 12 }}>
<Form.Item
labelCol={{ span: 6 }}
label="Địa chỉ"
name="address"
rules={[{ required: true, message: "Vui lòng nhập địa chỉ !" }]}
>
<Input />
</Form.Item>
</Col>
</Row>
<Row gutter={[20, 20]}>
<Col span={24} style={{ textAlign: "center" }}>
<Button type="primary" htmlType="submit" loading={loading}>
Cập nhật
</Button>
</Col>
</Row>
</Form>
);
};
const ChangePassword = () => {
const user = useSelector((state) => state.account.user);
const [loading, setLoading] = useState(false);
const [form] = Form.useForm();
const onFinish = async (values) => {
const { confirm_password, current_password, new_password } = values;
setLoading(true);
let data = {
confirm_password, current_password, new_password
}
const res = await callChangePassword(user._id, data);
if (res && res.data) {
setLoading(false);
message.success("Thay đổi mật khẩu thành công")
form.resetFields();
} else {
notification.error({
message: "Có lỗi xảy ra!",
description:
res.message && Array.isArray(res.message)
? res.message[0]
: res.message,
duration: 5,
});
setLoading(false);
}
};
return (
<Form form={form} onFinish={onFinish}>
<Row gutter={[20, 20]} style={{flexDirection: 'column'}} align={"middle"}>
<Col xs={{ span: 24 }} md={{ span: 8 }}>
<Form.Item
labelCol={{ span: 24 }}
label="Mật khẩu hiện"
name="current_password"
rules={[
{ required: true, message: "Vui lòng nhập mật khẩu hiện tại !" },
]}
>
<Input.Password />
</Form.Item>
</Col>
<Col xs={{ span: 24 }} md={{ span: 8 }}>
<Form.Item
labelCol={{ span: 24 }}
label="Mật khẩu mới"
name="new_password"
rules={[
{ required: true, message: "Vui lòng nhập mật khẩu mới !" },
]}
>
<Input.Password />
</Form.Item>
</Col>
<Col xs={{ span: 24 }} md={{ span: 8 }}>
<Form.Item
labelCol={{ span: 24 }}
label="Xác nhận mật khẩu"
name="confirm_password"
rules={[
{ required: true, message: "Vui lòng xác nhận mật khẩu mới !" },
]}
>
<Input.Password />
</Form.Item>
</Col>
</Row>
<Row gutter={[20, 20]}>
<Col span={24} style={{ textAlign: "center" }}>
<Button type="primary" htmlType="submit" loading={loading}>
Cập nhật
</Button>
</Col>
</Row>
</Form>
);
};
const ModalManageAccount = (props) => {
const { openManageAccount, setOpenManageAccount } = props;
const handleOk = () => {
setOpenManageAccount(false);
};
const handleCancel = () => {
setOpenManageAccount(false);
};
const items = [
{
key: "1",
label: "Rải CV",
children: <UserResume />,
},
{
key: "2",
label: "Nhận Jobs qua Email",
children: <JobByEmail />,
},
{
key: "3",
label: "Cập nhật thông tin",
children: <UpdateInfo />,
},
{
key: "4",
label: "Thay đổi mật khẩu",
children: <ChangePassword />,
},
];
const onChange = (key) => {};
return (
<Modal
title="Quản lý tài khoản"
width={800}
open={openManageAccount}
onOk={handleOk}
onCancel={handleCancel}
footer={null}
>
<Tabs defaultActiveKey="1" items={items} onChange={onChange} />
</Modal>
);
};
export default ModalManageAccount;
|
import { FC, memo, useCallback, useEffect, useReducer, useState } from 'react'
import { Button, Modal, Form, Input, Col, Row, Select, Tabs, Table } from 'antd'
import { useAuth } from 'contexts/Authenticate'
import _ from 'lodash'
import CustomerSupportManagementAPI from 'api/CustomerSupportManagementAPI'
import { notify } from 'utils/notify'
import moment from 'moment'
import { CUSTOMER_TYPE } from 'const/customer'
import { checkPermission } from 'utils/check-permission'
import { PERMISSIONS } from 'const/permission'
const { TabPane } = Tabs
const { Option } = Select
const { TextArea } = Input
const { Column, ColumnGroup } = Table
type Props = {
staffs: any
data?: any
studentLevels: any
visible: boolean
toggleModal: (val: boolean) => void
updateData: (item) => void
}
const StudentModal: FC<Props> = ({
staffs,
studentLevels,
visible,
data,
toggleModal,
updateData
}) => {
const [loading, setLoading] = useState(false)
const [form] = Form.useForm()
const { user } = useAuth()
useEffect(() => {
if (visible && !_.isEmpty(data)) {
const renderInputData = () => {
const loop = data.cs_info?.customer_care
const res = {}
for (let index = 0; index < loop.length; index++) {
const iterator = loop[index]
res[`customer_care_customer_type${index}`] =
iterator.customer_type
? Number(iterator.customer_type)
: ''
res[`customer_care_parent_opinion${index}`] =
iterator.parent_opinion
res[`customer_care_teacher_feedback${index}`] =
iterator.teacher_feedback
res[`customer_care_type${index}`] = iterator.type
? Number(iterator.type)
: ''
res[`customer_care_video_feedback${index}`] =
iterator.video_feedback
res[`customer_care_note${index}`] = iterator.note
res[`customer_care_input_level${index}`] =
iterator.input_level
res[`customer_care_output_level${index}`] =
iterator.output_level
}
return res
}
setTimeout(() => {
const temp = renderInputData()
form.setFieldsValue({
...temp,
ref_event: data.cs_info?.ref?.event,
ref_name: data.cs_info?.ref?.name,
ref_phone: data.cs_info?.ref?.phone
// supporter_greeting_call:
// data.cs_info?.supporter?.greeting_call || 0,
// supporter_checking_call:
// data.cs_info?.supporter?.checking_call || 0,
// supporter_scheduled:
// data.cs_info?.supporter?.scheduled || 0,
// supporter_staff_id: data.cs_info?.supporter?.staff_id
})
}, 300)
}
}, [visible])
const handleClose = useCallback(() => {
toggleModal(false)
form.resetFields()
}, [toggleModal])
const renderStaff = () =>
staffs.map((item: any, index) => (
<Option key={`s${item.value}`} value={item.value}>
{item.label}
</Option>
))
const onFinish = useCallback(
(values) => {
setLoading(true)
const dataPost = {
user_id: data.id,
supporter: {
staff_id: data?.student?.staff_id
// greeting_call: values.supporter_greeting_call,
// checking_call: values.supporter_checking_call,
// scheduled: values.supporter_scheduled
},
customer_care: [],
ref: {
name: values.ref_name,
phone: values.ref_phone,
event: values.ref_event
}
}
const loop = data.cs_info?.customer_care
for (let index = 0; index < loop.length; index++) {
const history = loop[index].history || []
const objectPush = {
date: loop[index].date,
customer_type: Number(
values[`customer_care_customer_type${index}`]
),
type: Number(values[`customer_care_type${index}`]),
parent_opinion:
values[`customer_care_parent_opinion${index}`],
video_feedback:
values[`customer_care_video_feedback${index}`],
teacher_feedback:
values[`customer_care_teacher_feedback${index}`],
note: values[`customer_care_note${index}`],
input_level: Number(
values[`customer_care_input_level${index}`]
),
output_level: Number(
values[`customer_care_output_level${index}`]
)
}
const lastHistory = history[history.length - 1]
if (
lastHistory?.customer_type !== objectPush.customer_type ||
lastHistory?.type !== objectPush.type ||
lastHistory?.parent_opinion !== objectPush.parent_opinion ||
lastHistory?.video_feedback !== objectPush.video_feedback ||
lastHistory?.teacher_feedback !==
objectPush.teacher_feedback ||
lastHistory?.input_level !== objectPush.input_level ||
lastHistory?.output_level !== objectPush.output_level
) {
history.push({
...objectPush,
createAt: Date.now(),
cs: `${user.username} - ${user.fullname}` || ''
})
}
dataPost.customer_care.push({ ...objectPush, history })
}
CustomerSupportManagementAPI.updateData(dataPost)
.then((res) => {
notify('success', 'Update info successfully')
toggleModal(false)
const staff = staffs.find(
(e) => e.value === dataPost.supporter.staff_id
)
data = null
updateData({ dataPost, staff })
})
.catch((err) => {
notify('error', err.message)
})
.finally(() => setLoading(false))
},
[form, data]
)
const renderLevel = () => {
const options = []
studentLevels.forEach((element, index) => {
options.push(
<Option key={index} value={Number(element.id)}>
{element.id} - {element.name}
</Option>
)
})
return options
}
const renderCustomerType = () => {
const options = []
// eslint-disable-next-line guard-for-in
for (const property in CUSTOMER_TYPE) {
const value = CUSTOMER_TYPE[property]
options.push(
<Option key={property} value={Number(property)}>
{value}
</Option>
)
}
return options
}
const renderBody = () => (
<>
<Form
name='basic'
layout='vertical'
labelCol={{ span: 24 }}
wrapperCol={{ span: 22 }}
form={form}
onFinish={onFinish}
>
{/* <Row>
<Col span={24}>
<h4>Supporter</h4>
</Col>
<Col span={8}>
<Form.Item
label='Username'
name='supporter_staff_id'
labelAlign='left'
rules={[
{
required: true,
message: 'Enter username'
}
]}
>
<Select
showSearch
placeholder='Choose staff'
optionFilterProp='children'
filterOption={(input, option) =>
option.children
.toString()
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
disabled={
!checkPermission(
PERMISSIONS.csmsm_update_supporter
)
}
>
{renderStaff()}
</Select>
</Form.Item>
</Col>
<Col span={16}></Col>
<Col span={8}>
<Form.Item
label='Greeting call'
name='supporter_greeting_call'
labelAlign='left'
>
<Select placeholder='Choose type'>
<Option value={1}>Done</Option>
<Option value={0}>Not Done</Option>
</Select>
</Form.Item>
</Col>
<Col span={8}>
<Form.Item
label='Scheduled'
name='supporter_scheduled'
labelAlign='left'
>
<Select placeholder='Choose scheduled'>
<Option value={1}>Done</Option>
<Option value={0}>Not Done</Option>
</Select>
</Form.Item>
</Col>
<Col span={8}>
<Form.Item
label='Checking call'
name='supporter_checking_call'
labelAlign='left'
>
<Select placeholder='Choose type'>
<Option value={1}>Done</Option>
<Option value={0}>Not Done</Option>
</Select>
</Form.Item>
</Col>
</Row> */}
<Row>
<Col span={24}>
<h4>Customer care</h4>
</Col>
<div className='border p-2 w-100 mb-3'>
<Tabs
defaultActiveKey={
data &&
(
data.cs_info?.customer_care.length - 1
).toString()
}
>
{data &&
data.cs_info?.customer_care.map(
(item, index) => (
<TabPane
tab={moment(
new Date(item.date)
).format('MM-YYYY')}
key={index}
>
<div className=' w-100 d-flex flex-wrap'>
<Col span={6}>
<Form.Item
label='Customer Type'
name={`customer_care_customer_type${index}`}
labelAlign='left'
>
<Select placeholder='Choose customer type'>
{renderCustomerType()}
</Select>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
label='Type'
name={`customer_care_type${index}`}
labelAlign='left'
>
<Select placeholder='Choose type'>
<Option value={0}>
Call
</Option>
<Option value={1}>
Message
</Option>
</Select>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
label='Input level'
name={`customer_care_input_level${index}`}
labelAlign='left'
>
<Select placeholder='Choose level'>
{renderLevel()}
</Select>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
label='Output level'
name={`customer_care_output_level${index}`}
labelAlign='left'
>
<Select placeholder='Choose level'>
{renderLevel()}
</Select>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
label="Parent's opinion"
name={`customer_care_parent_opinion${index}`}
labelAlign='left'
>
<TextArea
rows={4}
></TextArea>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
label='Teacher feedback'
name={`customer_care_teacher_feedback${index}`}
labelAlign='left'
>
<TextArea
rows={4}
></TextArea>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
label='Video feedback'
name={`customer_care_video_feedback${index}`}
labelAlign='left'
>
<TextArea
rows={4}
></TextArea>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
className='w-100'
label='Note'
name={`customer_care_note${index}`}
labelAlign='left'
>
<TextArea
rows={4}
></TextArea>
</Form.Item>
</Col>
</div>
<Table
className='student-management-table'
size='small'
dataSource={item.history}
rowKey={(record: any) =>
record.createAt
}
scroll={{
x: 500,
y: 200
}}
sticky
pagination={false}
bordered
expandable={{
expandedRowRender: (
record
) => {
return (
<ul className='pt-3'>
<li>
<b>
Parent's
opinion
:
</b>
{
record.parent_opinion
}
</li>
<li>
<b>
Teacher
feedback
:
</b>
{
record.teacher_feedback
}
</li>
<li>
<b>
Video
feedback:
</b>
{
record.video_feedback
}
</li>
<li>
<b>
Note :
</b>
{
record.note
}
</li>
</ul>
)
}
}}
>
<Column
width={100}
title='Time'
dataIndex='createAt'
key='createAt'
render={(
createAt: any,
record: any
) => {
return (
<div className='max-height text-center'>
{moment(
new Date(
createAt
)
).format(
'HH:mm DD-MM-YYYY'
)}
</div>
)
}}
/>
<Column
width={100}
title='CS'
dataIndex='cs'
key='cs'
render={(
cs: any,
record: any
) => {
return (
<div className='max-height text-center'>
{cs}
</div>
)
}}
/>
<Column
width={100}
title='Customer Type'
dataIndex='customer_type'
key='customer_type'
render={(
customer_type: any,
record: any
) => {
const customer_name =
CUSTOMER_TYPE[
customer_type
]
return (
<div className='max-height text-center'>
{customer_name}
</div>
)
}}
/>
<Column
width={100}
title='Input Level'
dataIndex='input_level'
key='input_level'
render={(
input_level: any,
record: any
) => {
const level =
studentLevels.find(
(e) =>
e.id ===
input_level
)
return (
level && (
<div className='max-height text-center'>
{level.id} -{' '}
{level.name}
</div>
)
)
}}
/>
<Column
width={100}
title='Output Level'
dataIndex='output_level'
key='output_level'
render={(
output_level: any,
record: any
) => {
const level =
studentLevels.find(
(e) =>
e.id ===
output_level
)
return (
level && (
<div className='max-height text-center'>
{level.id} -{' '}
{level.name}
</div>
)
)
}}
/>
</Table>
</TabPane>
)
)}
</Tabs>
</div>
</Row>
<Row>
<Col span={24}>
<h4>Referred by</h4>
</Col>
<Col span={8}>
<Form.Item
label='Name'
name='ref_name'
labelAlign='left'
>
<Input placeholder='Input name - username'></Input>
</Form.Item>
</Col>
<Col span={8}>
<Form.Item
label='Phone'
name='ref_phone'
labelAlign='left'
>
<Input placeholder='Input phone'></Input>
</Form.Item>
</Col>
<Col span={8}>
<Form.Item
label='Event'
name='ref_event'
labelAlign='left'
>
<Input placeholder='Input event'></Input>
</Form.Item>
</Col>
</Row>
</Form>
</>
)
return (
<Modal
centered
closable
// maskClosable={true}
visible={visible}
onCancel={() => handleClose()}
title='Edit info'
footer={[
<>
<Button
key='Close'
type='primary'
danger
onClick={() => handleClose()}
>
Close
</Button>
{checkPermission(PERMISSIONS.csmsm_update) && (
<Button
key='save'
type='primary'
onClick={() => form.submit()}
loading={loading}
>
Save
</Button>
)}
</>
]}
width={842}
>
{renderBody()}
</Modal>
)
}
export default memo(StudentModal)
|
import {
ChangeDetectionStrategy,
Component,
forwardRef,
Input,
OnDestroy,
OnInit,
Output,
EventEmitter,
} from "@angular/core";
import {
ControlValueAccessor,
FormControl,
NG_VALUE_ACCESSOR,
} from "@angular/forms";
import { Observable, Subject } from "rxjs";
import { map, takeUntil } from "rxjs/operators";
import { UserTypeDataAccessorService } from "src/app/data-access/user-type-data-accessor.service";
import { ComboBoxOption } from "../../common-widgets/types";
import { MatSelectChange } from "@angular/material/select";
@Component({
selector: "app-user-type-field",
templateUrl: "./user-type-field.component.html",
styleUrls: ["./user-type-field.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => UserTypeFieldComponent),
multi: true,
},
],
})
export class UserTypeFieldComponent
implements OnInit, OnDestroy, ControlValueAccessor
{
@Input() placeholder: string;
@Input() noContentMessage: string;
@Input() selectable = false;
@Input() defaultValue: string;
private onChange = (value: string) => {};
onTouched = () => {};
@Output() selectionChange = new EventEmitter<MatSelectChange>();
private unsubscriber = new Subject();
disabled = false;
control = new FormControl("");
options$: Observable<ComboBoxOption<string>[]>;
constructor(private readonly dataAccessor: UserTypeDataAccessorService) {
this.options$ = this._createSourceObservable();
}
ngOnInit(): void {
this.control.valueChanges
.pipe(takeUntil(this.unsubscriber))
.subscribe((value: string) => {
this.onChange(value);
this.onTouched();
});
}
private _createSourceObservable(): Observable<ComboBoxOption<string>[]> {
return this.dataAccessor.fetch().pipe(
map((types) => {
return types.map((type) => {
return {
key: type.userTypeId,
value: type.userTypeId,
label: type.userTypeName,
};
});
})
);
}
ngOnDestroy(): void {
this.unsubscriber.next();
this.unsubscriber.complete();
}
writeValue(value: string): void {
this.control.setValue(value || "");
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled;
}
onSelectionChange(event) {
this.selectionChange.next(event);
}
}
|
import { Injectable, NotFoundException } from '@nestjs/common';
import { ETaskStatus } from './tasks.model';
import { CCreateTaskDto, CFilterTaskDto } from './tasks.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { TaskEntity } from './task.entity';
import { Repository } from 'typeorm';
@Injectable()
export class TasksService {
constructor(
@InjectRepository(TaskEntity)
private taskRepository: Repository<TaskEntity>,
) {}
async getTasks(filter: CFilterTaskDto): Promise<TaskEntity[]> {
const { search = '', status = null } = filter;
const query = this.taskRepository.createQueryBuilder('task_entity');
if (status) {
query.andWhere('task_entity.status = :status', { status });
}
if (search) {
query.andWhere(
'LOWER(task_entity.title) LIKE LOWER(:search) OR LOWER(task_entity.description) LIKE LOWER(:search)',
{ search: `%${search}%` },
);
}
const tasks = await query.getMany();
return tasks;
}
async getTaskById(id: string): Promise<TaskEntity> {
// TODO: try to get the task
// if not found, throw error 404 not found
// otherwise, return the found task
try {
const task = await this.taskRepository.findOneBy({ id });
if (!task) throw new NotFoundException(`Task with ID ${id} not found`);
return task;
} catch (error) {
console.log(error);
throw new NotFoundException(`Not found`);
}
}
async deleteTaskById(id: string) {
this.getTaskById(id);
await this.taskRepository.softDelete(id);
}
async createTask(createDto: CCreateTaskDto): Promise<TaskEntity> {
const { title, description } = createDto;
try {
const newTask = await this.taskRepository.create({
title,
description,
status: ETaskStatus.OPEN,
});
const save = await this.taskRepository.save(newTask);
console.log({ newTask, save });
return newTask;
} catch (error) {
console.log(error);
throw new NotFoundException(`Something went wrong!`);
}
}
async updateTaskStatus(id: string, status: ETaskStatus) {
const task = await this.getTaskById(id);
task.status = status;
await this.taskRepository.save(task);
return task;
}
}
|
// Copyright 2022 CloudWeGo 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.
package main
import (
"testing"
"github.com/cloudwego/thriftgo/generator"
"github.com/cloudwego/thriftgo/generator/backend"
"github.com/cloudwego/thriftgo/generator/golang"
"github.com/cloudwego/thriftgo/parser"
"github.com/cloudwego/thriftgo/plugin"
"github.com/cloudwego/thriftgo/semantic"
)
// Tests in this file all depend on an environment variable `IDL`
// which will be written by gen_test.go for parsing.
// Export the environment variable before testing.
var idl string
func TestParse(t *testing.T) {
if idl == "" {
t.SkipNow()
}
_, err := parser.ParseFile(idl, nil, true)
if err != nil {
t.Fatalf("parse falied: %s", err.Error())
}
}
func TestGenerate(t *testing.T) {
if idl == "" {
t.SkipNow()
}
g, a := pair(t)
res := g.Generate(a)
if res.Error != nil {
t.Fatalf("generate falied: %s", *res.Error)
}
}
func pair(tb testing.TB) (generator.Generator, *generator.Arguments) {
ast, err := parser.ParseFile(idl, nil, true)
if err != nil {
tb.Fatalf("parse falied: %s", err.Error())
}
checker := semantic.NewChecker(semantic.Options{FixWarnings: true})
resolver, ok := checker.(interface {
ResolveSymbols(t *parser.Thrift) error
})
if ok {
if err = resolver.ResolveSymbols(ast); err != nil {
tb.Fatalf("resolve: %s", err.Error())
}
}
var gen generator.Generator
gen.RegisterBackend(new(golang.GoBackend))
log := backend.LogFunc{
Info: func(v ...interface{}) {},
Warn: func(v ...interface{}) {},
MultiWarn: func(warns []string) {},
}
out := &generator.LangSpec{
Language: "go",
Options: nil,
}
req := &plugin.Request{
Language: out.Language,
Version: "?",
OutputPath: "./gen-go",
Recursive: true,
AST: ast,
}
arg := &generator.Arguments{Out: out, Req: req, Log: log}
return gen, arg
}
func full(tb testing.TB) {
if idl == "" {
tb.SkipNow()
}
g, a := pair(tb)
res := g.Generate(a)
if res.Error != nil {
tb.Fatalf("generate: %s", *res.Error)
}
}
func BenchmarkParse(b *testing.B) {
if idl == "" {
b.SkipNow()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := parser.ParseFile(idl, nil, true)
if err != nil {
b.Fatalf("parse falied: %s", err.Error())
}
}
}
func BenchmarkParseParallel(b *testing.B) {
if idl == "" {
b.SkipNow()
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, err := parser.ParseFile(idl, nil, true)
if err != nil {
b.Fatalf("parse falied: %s", err.Error())
}
}
})
}
func BenchmarkGenerate(b *testing.B) {
if idl == "" {
b.SkipNow()
}
g, a := pair(b)
b.ResetTimer()
for i := 0; i < b.N; i++ {
res := g.Generate(a)
if res.Error != nil {
b.Fatalf("generate falied: %s", *res.Error)
}
}
}
func BenchmarkAll(b *testing.B) {
if idl == "" {
b.SkipNow()
}
for i := 0; i < b.N; i++ {
full(b)
}
}
func BenchmarkSemanticCheck(b *testing.B) {
if idl == "" {
b.SkipNow()
}
ast, err := parser.ParseFile(idl, nil, true)
if err != nil {
b.Fatalf("parse falied: %s", err.Error())
}
checker := semantic.NewChecker(semantic.Options{FixWarnings: true})
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := checker.CheckAll(ast)
if err != nil {
b.Fatalf("generate falied: %s", err.Error())
}
}
}
func BenchmarkSemanticResolve(b *testing.B) {
if idl == "" {
b.SkipNow()
}
checker := semantic.NewChecker(semantic.Options{FixWarnings: true})
resolver, ok := checker.(interface {
ResolveSymbols(t *parser.Thrift) error
})
if !ok {
b.Skip()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
ast, err := parser.ParseFile(idl, nil, true)
if err != nil {
b.Fatalf("parse falied: %s", err.Error())
}
if err = resolver.ResolveSymbols(ast); err != nil {
b.Fatalf("resolve: %s", err.Error())
}
}
}
|
import { MEALS } from "../../data/dummy-data";
import { TOGGLE_FAVORITE, SET_FILTERS } from "../actions/mealActions";
const initialState = {
meals: MEALS,
filteredMeals: MEALS,
favoriteMeals: [],
};
const mealsReducer = (state = initialState, action) => {
switch (action.type) {
case TOGGLE_FAVORITE: //CASE 1
const existingIndex = state.favoriteMeals.findIndex(
(meal) => meal.id === action.mealId
); // check if the meals matchs
if (existingIndex >= 0) {
const updatedFavMeals = [...state.favoriteMeals]; // copy the state
updatedFavMeals.splice(existingIndex, 1); // remove the favorite meal
return { ...state, favoriteMeals: updatedFavMeals }; // return a new state
} else {
const meal = state.meals.find(meal => meal.id === action.mealId);
return { ...state, favoriteMeals: state.favoriteMeals.concat(meal)};
}
case SET_FILTERS: // CASE 2
const appliedFilters = action.filters;
const updatedFilteredMeals = state.meals.filter(meal => {
if (appliedFilters.glutenFree && !meal.glutenFree) {
return false;
}
if (appliedFilters.lactoseFree && !meal.lactoseFree) {
return false;
}
if (appliedFilters.vegetarian && !meal.vegetarian) {
return false;
}
if (appliedFilters.vegan && !meal.vegan) {
return false;
}
return true
});
return {...state, filteredMeals: updatedFilteredMeals };
default:
return state;
}
};
export default mealsReducer;
|
import { useDispatch, useSelector } from "react-redux";
import { logout } from "../utils/context/reducers/authSlice";
import { useNavigate, useLocation, NavLink } from "react-router-dom";
import { toast } from "sonner";
import {
BadgeCheck,
Bell,
BookmarkCheck,
CircleUser,
LayoutDashboard,
ListCollapse,
LogOut,
MessageSquare,
Search,
UserRoundPlus,
} from "lucide-react";
function SideNavBar() {
const location = useLocation();
const navigate = useNavigate();
const dispatch = useDispatch();
const selectUser = (state: any) => state.auth.user;
const user = useSelector(selectUser);
const handleLogout = () => {
dispatch(logout());
localStorage.removeItem("email");
toast.info("Logout Successful");
navigate("/login");
};
return (
<>
<aside className="fixed top-20 left-0 z-30 flex flex-col w-64 h-5/6 mt-4 ms-32 px-4 py-5 overflow-none border-r rounded-xl rtl:border-r-0 rtl:border-l bg-white dark:border-gray-700">
<div className="flex flex-col items-center -mx-2">
<img
className="object-cover w-16 h-16 mx-2 rounded-full border-2 border-white"
src={user.profileImg}
alt="avatar"
/>
<div className="flex items-center">
<h4 className="mx-1 mt-4 font-medium text-black dark:text-gray-200">
{user ? user.userName : ""}
</h4>
{user.isVerified && (
<BadgeCheck size={24} className="mt-4" color="white" fill="#7E3AF2" />
)}
</div>
</div>
<div className="flex flex-col justify-between flex-1 mt-5">
<nav>
<NavLink
to={"/"}
className={`flex items-center px-4 py-2 rounded-md ${
location.pathname === "/"
? "text-purple-600 bg-white"
: "text-gray-800"
}`}
>
<LayoutDashboard size={20} />
<span className="mx-5 ">Dashboard</span>
</NavLink>
<NavLink
className={`flex cursor-pointer items-center px-4 mt-2 py-2 ${
location.pathname === "/explore"
? "text-purple-600 bg-white"
: "text-gray-800"
} rounded-lg`}
to={"/explore"}
>
<Search size={20} />
<span className="mx-5 ">Explore</span>
</NavLink>
<NavLink
className={`flex cursor-pointer items-center px-4 mt-2 py-2 ${
location.pathname === "/notifications"
? "text-purple-600 bg-white"
: "text-gray-800"
} rounded-lg`}
to={"/notifications"}
>
<Bell size={20} />
<span className="mx-5 ">Notifications</span>
</NavLink>
<NavLink
className={`flex items-center px-4 mt-2 py-2 ${
location.pathname === "/messages"
? "text-purple-600 bg-white"
: "text-gray-800"
} rounded-lg`}
to={"/chat"}
>
<MessageSquare size={20} />
<span className="mx-5 ">Messages</span>
</NavLink>
<NavLink
className={`flex items-center px-4 mt-2 py-2 ${
location.pathname === "/follow-requests"
? "text-purple-600 bg-white"
: "text-gray-800"
} rounded-lg`}
to={"/follow-requests"}
>
<UserRoundPlus size={20} />
<span className="mx-5 ">Requests</span>
</NavLink>
<NavLink
className={`flex items-center px-4 mt-2 py-2 ${
location.pathname === "/saved-post"
? "text-purple-600 bg-white"
: "text-gray-800"
} rounded-lg`}
to={"/saved-post"}
>
<BookmarkCheck size={20} />
<span className="mx-5 ">Saved Posts</span>
</NavLink>
<NavLink
className={`flex items-center px-4 mt-2 py-2 ${
location.pathname === "/profile"
? "text-purple-600 bg-white"
: "text-gray-800"
} rounded-lg`}
to={"/profile"}
>
<CircleUser size={20} />
<span className="mx-5 ">Profile</span>
</NavLink>
<NavLink
className={`flex items-center px-4 mt-2 py-2 ${
location.pathname === "/more"
? "text-purple-600 bg-white"
: "text-gray-800"
} rounded-lg`}
to={"/more"}
>
<ListCollapse size={20} />
<span className="mx-5 ">More</span>
</NavLink>
{/* Add more navigation links */}
</nav>
</div>
<div
onClick={handleLogout}
className="flex mt-14 cursor-pointer text-gray-800 px-4"
>
<LogOut size={20} />
<button className="mx-5 ">Logout</button>
</div>
</aside>
</>
);
}
export default SideNavBar;
|
== Week 4 Lecture Notes
----------------------------------------------
-- Video 1 - Regularised Regression
----------------------------------------------
Regularisation:
----------------
Pros: help with bias/variance
helps with model selection
Cons: computationally more demanding on large datasets
Does not perform as well as random forests and boosting
taking out highly correlated variables means you loose some variance but you simplifiy your model.
Hard Thresholding
- - - - - - - - - -
penalty term lambda can reduce
- complexity
- variance
- reduces structure of the problem
Lamba
controls size of coeffs
controls about of regularisation
As lambda tends to 0, we obtain the least squares solution.
As lambda tends to infinity all parameters go to zero
Lasso approach shrinks parameters and helps with model selection
train(x, method='ridge' or 'lasso' or 'relaxo')
----------------------------------------
-- Video 2 - Combining Predictors (ensembling)
----------------------------------------
combine using averaging / voting
Combing classifiers improves accuracy, but reduces interpretability.
101 interpendant classifiers you get 99% accuracy.
Model Stacking (ensemble)
- - - - - - - - - - - -
build 2 models then combine their predictions with the class variable in a data frame and build a new prediction model using the predictions of the two other models as the input features.
eg.
rf_mod <- train(class~., method="rf", data=train)
glm_mod <- train(class~., method="glm", data=train)
# do predictions
rf_pred <- predict(rf_mod, testing)
glm_pred <- predict(glm_mod, testing)
new_df <- data.frame(rf_pred, glm_pred, test$class)
ensemble <- train(class~., method="gam", data= new_df)
predictions <- predict(ensemble, testing)
sqrt(sum((pred1 - testing$wage)^2))
sqrt(sum((pred2 - testing$wage)^2))
sqrt(sum((combined_pred - testing$wage)^2))
go
1. Train
2. Test
3. Validate
Ensembling Method
- - - - - - - - - - -
1. Build an odd number of models
2. Predict with each model on training set.
3. Predict class by majority vote
You could use caretEnsemble() package (beta)
----------------------------------------
-- Video 3 - (Forecasting)
----------------------------------------
difficulties: data over time, trends, seasonality, cyclic.
Subsampling into train and test is more tricky.
Similar problems with spatial data.
Population map, not insights!
Google data
- - -- - - -- -
library(quantmod) # gets stock data
ts1 <- ts() # Timeseries function
decompose(ts1)
library(quantmod) or quandl packages
from.dat <- as.Date("01/01/08", format="%m/%d/%y")
to.dat <- as.Date("12/31/13", format="%m/%d/%y")
getSymbols("GOOG", src="google", from = from.dat, to = to.dat)
head(GOOG)
mGoog <- to.monthly(GOOG)
googOpen <- Op(mGoog)
ts1 <- ts(googOpen,frequency=12)
plot(ts1,xlab="Years+1", ylab="GOOG")
plot(decompose(ts1),xlab="Years+1")
ts1Train <- window(ts1,start=1,end=5)
ts1Test <- window(ts1,start=5,end=(7-0.01))
ts1Train
## Moving Average
plot(ts1Train)
lines(ma(ts1Train,order=3),col="red")
## Exponential Smoothing
yt+1 = alpha * yt (1-alpha)*yt-1
ets1 <- ets(ts1Train,model="MMM")
fcast <- forecast(ets1)
plot(fcast); lines(ts1Test,col="red")
## Model Accuracy
accuracy(fcast,ts1Test)
Books to read: http://en.wikipedia.org/wiki/Forecasting
https://www.otexts.org/fpp/
http://www-bcf.usc.edu/~gareth/ISL/
http://statweb.stanford.edu/~tibs/ElemStatLearn/
http://www.stat.washington.edu/raftery/Research/PDF/fraley2002.pdf
http://en.wikipedia.org/wiki/Linear_discriminant_analysis
http://en.wikipedia.org/wiki/Quadratic_classifier
----------------------------------------
-- Video 4 - (Unsupervised prediction)
----------------------------------------
Unsupervised learning.
When you dont know the target that you are predicting you can
1. build a cluster model
2. name the clusters
3. build a predictor for the clusters
4. score a new dataset with cluster name
Kmeans clustering with IRIS dataset
- - - - - - - - -- -- - - - - - -- - -
kMeans1 <- kmeans(subset(training,select=-c(Species)),centers=3)
training$clusters <- as.factor(kMeans1$cluster)
qplot(Petal.Width,Petal.Length,colour=clusters,data=training)
modFit <- train(clusters ~.,data=subset(training,select=-c(Species)),method="rpart")
table(predict(modFit,training),training$Species)
testClusterPred <- predict(modFit,testing)
table(testClusterPred ,testing$Species)
cl_predict in the clue package
- can be used to create product recommendation engines
READING
- - - - - -
http://en.wikipedia.org/wiki/Recommender_system
http://www-bcf.usc.edu/~gareth/ISL/
|
/// <reference path="../sosete/sosete.component.ts" />
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Bluza } from '../models/Bluza';
import { BluzaService } from '../services/bluza.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-bluza',
templateUrl: './bluza.component.html',
styleUrls: ['./bluza.component.css']
})
export class BluzaComponent implements OnInit {
public bluze: Array<Bluza> = [];
public bluzaForm: FormGroup;
constructor(private readonly BluzaService: BluzaService, private formBuilder: FormBuilder) {
this.bluzaForm = this.formBuilder.group({
descriere: ['', Validators.required],
culoare: ['', Validators.required],
marime: ['', Validators.required],
material: ['', Validators.required],
pret: ['', Validators.required],
hoodie: [false]
});
}
ngOnInit(): void {
this.BluzaService.getAllBluze().subscribe(bluze => {
this.bluze = bluze;
});
}
deleteBluza(id: string | undefined) {
if (id === null || id === undefined)
return;
this.BluzaService.deleteBluza(id).subscribe(() => { window.location = window.location; });
}
onSubmit() {
this.BluzaService.addBluza(this.bluzaForm.value).subscribe(() => { window.location = window.location; });
}
}
|
const express = require("express");
const user_route = express();
const session = require("express-session");
const config = require("../config/config");
const userAuth = require("../middlware/userAuth");
const errorHandler = require("../middlware/errorHandler")
const path = require("path");
user_route.use(
session({ secret: "abcd", resave: false, saveUninitialized: false })
);
user_route.set("views", "./views/users");
//controllers
const userController = require("../controllers/userController");
const addressController = require("../controllers/addressController");
const cartController = require("../controllers/cartController");
const orderController = require("../controllers/orderController");
const couponController = require("../controllers/couponController");
const WishlistController = require("../controllers/wishListController");
//home
user_route.get("/", userController.loadHome);
//register
user_route.get("/register", userAuth.isLogout, userController.loadRegister);
user_route.post("/register", userController.verifyUser);
// verify_from_login
user_route.get("/verify_from_login", userController.verifyFromLogin);
//forget
user_route.get("/forget", userAuth.isLogout, userController.forgetLoad);
user_route.post("/forget", userController.forgetSendEmail);
//reset
user_route.get(
"/resetPassword",
userAuth.isLogout,
userController.resetPassword
);
user_route.post(
"/resetPassword",
userAuth.isLogout,
userController.resetpassVerify
);
//shop
user_route.get("/shop", userController.loadShoping);
//product details
user_route.get("/product_details", userController.productDetails);
user_route.post("/review",userAuth.isLogin,userController.review)
//about
user_route.get("/about", userController.loadAbout);
//contact
user_route.get("/contact", userController.loadContact);
//login
user_route.get("/login", userAuth.isLogout, userController.loadLogin);
user_route.post("/login", userController.verifyLogin);
//otp
user_route.get("/otp", userController.otpVerify);
user_route.post("/otp", userController.otpValidation);
//logout
user_route.get("/logout", userAuth.isLogin, userController.userLogout);
//cart
user_route.get("/cart", userAuth.isLogin, cartController.loadCart);
user_route.post("/addtocart", userAuth.isLogin, cartController.addtoCart);
user_route.get("/deleteCart", userAuth.isLogin, cartController.deletecartitem);
user_route.post(
"/changes",
userAuth.isLogin,
cartController.changes,
cartController.totalproductPrice
);
// product Checkout
user_route.get("/checkout", userAuth.isLogin, cartController.productCheckout);
//order list
user_route.post("/checkout", orderController.placeTheOrder);
user_route.get("/orderplaced", userAuth.isLogin, orderController.orderPlaced);
user_route.post("/verifyPayment", orderController.verifyPayment);
user_route.get("/orderlist", userAuth.isLogin, orderController.orderlistLoad);
user_route.get("/ordershow", userAuth.isLogin, orderController.showorderLoad);
user_route.post(
"/cancelOrder",
userAuth.isLogin,
orderController.canceluserOrder
);
user_route.post("/returnOrder", userAuth.isLogin, orderController.returnOrder);
//wallet
user_route.get("/walletHistory",userController.walletHistory)
user_route.post("/wallet", userController.walletAmount);
// wishlist
user_route.get("/wishList", userAuth.isLogin, WishlistController.loadWishList);
user_route.post("/addToWishlist", WishlistController.addTowishList);
user_route.get(
"/removeWishlist",
userAuth.isLogin,
WishlistController.removeWishlist
);
user_route.get(
"/addFromWish",
userAuth.isLogin,
WishlistController.addFromWish
);
//user_profile
user_route.get("/myacco", userAuth.isLogin, userController.myAcco);
user_route.post("/myacco", userController.profilesubmit);
//Invoice Download
user_route.get("/invoice",userAuth.isLogin,userController.invoiceDownload)
//coupon
user_route.post("/applyCoupon", couponController.applyCoupon);
//address controller
user_route.get("/addAddress", userAuth.isLogin, addressController.addressLoad);
user_route.post("/addAddress", addressController.verifyAddress);
user_route.get("/deleteAddress", addressController.deleteaddress);
user_route.get("/editAddress", addressController.editAddress);
user_route.post("/editAddress", addressController.updateAddress);
user_route.get(
"/addAddresscheck",
userAuth.isLogin,
addressController.addressLoad
);
user_route.get(
"/deleteAddressCheckout",
addressController.deleteaddressCheckout
);
user_route.post("/addAddresscheck", addressController.verifyAddresscheck);
user_route.get("/editAddresscheck", addressController.editAddress);
user_route.post("/editAddresscheck", addressController.posteditaddresscheck);
module.exports = user_route;
|
<!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.0" />
<title>生成器函数的参数和返回值</title>
</head>
<body>
<script>
// 生成器函数的返回值,是通过调用其迭代器对象的 `next()`方法,遇到一个`yield`语句时,返回的对象的 `value` 属性的值。
// 当在生成器函数中显式 `return` 时,会导致生成器立即变成完成状态,即调用`next()`方法返回的对象的 done 属性为 true。如果`return`后面跟了一个值,那么这个值会作为当前调用`next()`方法返回的 value 值。
function* foo() {
console.log('函数内部: 1111')
console.log('函数内部: 2222')
yield 'ok'
console.log('函数内部: 3333')
console.log('函数内部: 4444')
return 'again ok'
console.log('函数内部: 5555')
console.log('函数内部: 6666')
return '函数内部: 7777'
}
const generator = foo()
console.log(generator.next())
console.log(generator.next())
console.log(generator.next())
// 生成器函数的参数,是在调用其迭代器对象的`next()`方法传入的,通过 `yield` 语句左边的变量接收。需要注意的是,如果需要给第一个 `yield` 语句之前的代码传参,就需要将参数传给生成器函数,而不是迭代器对象的 `next()` 方法。
// function* foo(first) {
// console.log('函数内部: 1111', first)
// console.log('函数内部: 2222', first)
// const second = yield 'ok'
// console.log('函数内部: 3333', second)
// console.log('函数内部: 4444', second)
// const third = yield 'again ok'
// console.log('函数内部: 5555', third)
// console.log('函数内部: 6666', third)
// return '函数内部: 7777'
// }
// const generator = foo('first arg')
// generator.next()
// generator.next('second arg')
// generator.next('third arg')
</script>
</body>
</html>
|
<template>
<div class="section">
<div class="flex justify-end">
<NotFancyTitle
cn="学习方式"
en="Learning Methods"
color="red"
right
></NotFancyTitle>
</div>
<div class="grid gap-1" style="grid-template-columns: 3fr 1fr">
<div class="relative">
<img
:src="pageData.learning_methods[current].image"
class="w-full h-full object-cover"
alt="Bg"
/>
<div
class="absolute bottom-0 pa-10 color-white special-bg transition-opacity-300"
:class="{ 'op-0': transition }"
>
<h3>{{ pageData.learning_methods[current].title }}</h3>
<p v-html="pageData.learning_methods[current].content"></p>
</div>
</div>
<div class="grid gap-1">
<div v-for="(method, index) in pageData.learning_methods" :key="method">
<img
:src="method.image"
class="w-full h-full object-cover block opacity-60 transition-all"
:class="{
'!opacity-100': current === index,
'hover:opacity-100 active:brightness-90':
current !== index && !transition
}"
v-on:click="change(index)"
alt="Bg"
/>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { inject, ref } from 'vue'
import NotFancyTitle from '../NotFancyTitle.vue'
const pageData = inject('data')
const current = ref(0)
const transition = ref(false)
function change (index) {
if (index === current.value || transition.value) return
transition.value = true
setTimeout(() => {
current.value = index
setTimeout(() => {
transition.value = false
}, 150)
}, 300)
}
</script>
<style scoped>
.special-bg {
background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.5));
}
</style>
|
<?php
namespace Trustedshops\Trustedshops\Test\Integration;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\App\DeploymentConfig\Reader;
use Magento\Framework\Component\ComponentRegistrar;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Module\ModuleList;
use Magento\TestFramework\ObjectManager;
class ModuleConfigTest extends \PHPUnit_Framework_TestCase
{
protected $moduleName = 'Trustedshops_Trustedshops';
public function testTheModuleIsRegistered()
{
$registrar = new ComponentRegistrar();
$this->assertArrayHasKey($this->moduleName, $registrar->getPaths(ComponentRegistrar::MODULE));
}
public function testTheModuleIsConfiguredAndEnabledInTheTestEnvironment()
{
/** @var ObjectManager $objectManager */
$objectManager = ObjectManager::getInstance();
/** @var ModuleList $moduleList */
$moduleList = $objectManager->create(ModuleList::class);
$this->assertTrue($moduleList->has($this->moduleName), 'The module is not enabled in the test environment');
}
public function testTheModuleIsConfiguredAndEnabledInTheRealEnvironment()
{
/** @var ObjectManager $objectManager */
$objectManager = ObjectManager::getInstance();
/** @var DirectoryList $dirList */
$dirList = $objectManager->create(DirectoryList::class, ['root' => BP]);
/** @var Reader $configReader */
$configReader = $objectManager->create(Reader::class, ['dirList' => $dirList]);
/** @var DeploymentConfig\ $deploymentConfig */
$deploymentConfig = $objectManager->create(DeploymentConfig::class, ['reader' => $configReader]);
/** @var ModuleList $moduleList */
$moduleList = $objectManager->create(ModuleList::class, ['config' => $deploymentConfig]);
$this->assertTrue($moduleList->has($this->moduleName), 'The module is not enabled in the real environment');
}
}
|
from PyQt6.QtWidgets import QMainWindow, QMessageBox, QFileDialog, QApplication, QTabWidget
from PyQt6.QtCore import pyqtSlot, Qt
from ui.main_menu import MainMenu
from load_data.load_orgs import LoadOrgs
from load_data.load_simple import LoadSimple
from load_data.load_faces import LoadFaces
from load_data.import_data import ImportData
from ui.views.org_frame import OrgFrame
from ui.views.group_view import GroupView
from ui.widgets.groups_widget import GroupsWidget
from ui.widgets.position_widget import PositionWidget
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
screen = QApplication.screens()[0]
width, height = screen.size().width(), screen.size().height()
x = width // 4
y = height // 4
self.setGeometry(x, y, x * 2, y * 2)
main_menu = MainMenu(parent=self)
self.setMenuBar(main_menu)
main_menu.groups.triggered.connect(self.nsi_groups)
main_menu.positions.triggered.connect(self.nsi_position)
main_menu.orgs.triggered.connect(self.load_orgs)
main_menu.deps.triggered.connect(self.load_simple)
main_menu.faces.triggered.connect(self.load_faces)
main_menu.about_qt.triggered.connect(self.about_qt)
main_menu.about.triggered.connect(self.about)
self.tab = QTabWidget()
self.tab.setTabsClosable(True)
self.tab.tabCloseRequested.connect(self.close_tab)
self.setCentralWidget(self.tab)
@pyqtSlot()
def nsi_groups(self):
#view = GroupView(self)
widget = GroupsWidget(self)
self.tab.addTab(widget, "Группы должностей")
@pyqtSlot()
def nsi_position(self):
widget = PositionWidget(self)
self.tab.addTab(widget, "Должности")
def about(self):
title = "Цифровые нормативные документы"
text = ("Программа для создания\n" +
"цифровых нормативных документов.")
QMessageBox.about(self, title, text)
@pyqtSlot()
def about_qt(self):
QMessageBox.aboutQt(self, "Цифровые нормативные документы")
@pyqtSlot()
def load_orgs(self):
frame = OrgFrame(parent=self)
self.tab.addTab(frame, "Структура")
@pyqtSlot()
def load_simple(self):
file_dlg = QFileDialog(self, Qt.WindowType.Dialog)
file_dlg.setAcceptMode(QFileDialog.AcceptMode.AcceptOpen)
file_dlg.setNameFilter("Excel files (*.xls *.xlsx)")
if not file_dlg.exec():
return
file_name = file_dlg.selectedFiles()[0]
file_dlg.close()
# load = LoadSimple(file_name)
# load.update_db_deps()
load = ImportData(file_name)
@pyqtSlot()
def load_faces(self):
file_dlg = QFileDialog(self, Qt.WindowType.Dialog)
file_dlg.setAcceptMode(QFileDialog.AcceptMode.AcceptOpen)
file_dlg.setNameFilter("Excel files (*.xls *.xlsx)")
if not file_dlg.exec():
return
file_name = file_dlg.selectedFiles()[0]
load = LoadFaces(file_name)
load.update_db_faces()
@pyqtSlot()
def close_tab(self):
index = self.tab.currentIndex()
print(index)
self.tab.removeTab(index)
|
import React, { useEffect } from "react";
import { Route, Routes } from "react-router-dom";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { Home, Profile, CreateCampaign, CampaignDetails } from "./pages/index";
import { Sidebar, Navbar } from "./components";
import { useConnectionStatus } from "@thirdweb-dev/react";
const App = () => {
const connectionStatus = useConnectionStatus();
useEffect(() => {
connectionStatus === "connected" &&
toast.success("Welcome to Crowdfunding dApp😉");
}, [connectionStatus]);
return (
<div
className={`relative sm:p-8 p-4 min-h-screen flex bg-[#13131a] text-gray-100`}
>
<div className="sm:flex hidden mr-10 relative">
<Sidebar />
</div>
<div className="flex-1 max-sm:w-full max-w-[1280px] mx-auto sm:pr-5">
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
<Route path="/create-campaign" element={<CreateCampaign />} />
<Route path="/campaign-details/:id" element={<CampaignDetails />} />
</Routes>
</div>
<ToastContainer />
</div>
);
};
export default App;
|
const { Visitor } = require("./expr");
module.exports = class AstPrinter extends Visitor {
print(expr) {
return expr.accept(this);
}
visitBinaryExpr(expr) {
return this.parenthesize(expr.operator.lexeme, expr.left, expr.right);
}
visitGroupingExpr(expr) {
return this.parenthesize("group", expr.expression);
}
visitLiteralExpr(expr) {
if (expr.value === null) return "nil";
return expr.value.toString();
}
visitUnaryExpr(expr) {
return this.parenthesize(expr.operator.lexeme, expr.right);
}
parenthesize(name, ...exprs) {
const result = `(${name} ${exprs
.map((expr) => expr.accept(this))
.join(" ")})`;
return result;
}
};
|
# -*- coding: utf8 -*-
import Algorithmia
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import spacy
spacy.load('en')
from spacy.lang.en import English
import nltk
nltk.download('wordnet')
from nltk.corpus import wordnet as wn
from nltk.stem.wordnet import WordNetLemmatizer
nltk.download('stopwords')
en_stop = set(nltk.corpus.stopwords.words('english'))
import random
import gensim
from gensim import corpora
class NewsAnalyser:
def __init__(self):
self.client = Algorithmia.client('simLnScRWPk7koh1Je5IZZP8Z7m1')
self.sentimentAnalyser = SentimentIntensityAnalyzer()
def sentimentAnalysis(self, news):
"""
Sentimental Analysis ( 'positive', 'neutral', 'negative')
:param news: list of dictionaries
:return: modified input list of dictionaries
"""
if len(news) == 0:
print("empty news")
return []
# algo = self.client.algo('nlp/SentimentAnalysis/1.0.5')
# algo.set_options(timeout=100)
for entry in news:
if "EnglishText" in entry and ("Sentiment" not in entry or entry["Sentiment"] is None):
# input = {
# "document": entry['Text'],
# "language": "uk"
# }
#
# sentiment = algo.pipe(input).result[0]['sentiment']
sentiment = self.sentimentAnalyser.polarity_scores(entry["EnglishText"])["compound"]
if sentiment >= 0.5:
sentiment = 'positive'
elif sentiment >= 0:
sentiment = 'neutral'
else:
sentiment = 'negative'
entry['Sentiment'] = sentiment
return news
def autoTag(self, news):
"""
Finding keywords of given list of news
:param news: list of dictionaries
:return: modified input list of dictionaries
"""
if len(news) == 0:
print("empty news")
return []
algo = self.client.algo('nlp/AutoTag/1.0.1')
algo.set_options(timeout=100)
for entry in news:
if "EnglishText" in entry and ("KeyWords" not in entry or entry["KeyWords"] is None):
input = entry['EnglishText']
entry['KeyWords'] = algo.pipe(input).result
return news
def summary(self, news):
"""
Get summary of EnglishText of every news
:param news: list of dictionaries
:return: modified input list of dictionaries
"""
if len(news) == 0:
print("empty news")
return []
algo = self.client.algo('nlp/Summarizer/0.1.8')
algo.set_options(timeout=100)
for entry in news:
if "EnglishText" in entry and ("EnglishSummary" not in entry or entry["EnglishSummary"] is None):
input = entry['EnglishText']
entry['EnglishSummary'] = algo.pipe(input).result
return news
def lemmatizer(self, news):
"""
Maps all words to their canonical forms for easier analysis
:param news: list of dictionaries
:return: modified input list of dictionaries
"""
if len(news) == 0:
print("empty news")
return []
algo = self.client.algo('StanfordNLP/Lemmatizer/0.1.0')
algo.set_options(timeout=300) # optional
for entry in news:
if "EnglishText" in entry and ("EnglishLemmas" not in entry or entry["EnglishLemmas"] is None):
input = entry['EnglishText']
entry['EnglishLemmas'] = algo.pipe(input).result
return news
def translateTextToEnglish(self, news):
"""
Translates Ukrainian to English
:param news: list of dictionaries
:return: modified input list of dictionaries
"""
if len(news) == 0:
print("empty news")
return []
algo = self.client.algo('translation/GoogleTranslate/0.1.1')
algo.set_options(timeout=100) # optional
for entry in news:
if "EnglishText" not in entry or entry["EnglishText"] is None:
input = {
"action": "translate",
"text": entry['Text']
}
entry['EnglishText'] = algo.pipe(input).result["translation"]
return news
def translateSummaryToUkr(self, news):
"""
Translates EnglishSummary to Ukrainian
:param news: list of dictionaries
:return: modified input list of dictionaries
"""
if len(news) == 0:
print("empty news")
return []
algo = self.client.algo('translation/GoogleTranslate/0.1.1')
algo.set_options(timeout=100) # optional
for entry in news:
if "EnglishSummary" in entry and ("UkrSummary" not in entry or entry["UkrSummary"] is None):
input = {
"action": "translate",
"text": entry['EnglishSummary'],
"target_language": "uk"
}
entry['UkrSummary'] = algo.pipe(input).result["translation"]
return news
class LDA:
def __init__(self):
self.NUM_TOPICS = 5
self.parser = English()
self.dictionary = None
self.ldamodel = None
def tokenize(self, text):
lda_tokens = []
tokens = self.parser(text)
for token in tokens:
if token.orth_.isspace():
continue
elif token.like_url:
lda_tokens.append('URL')
elif token.orth_.startswith('@'):
lda_tokens.append('SCREEN_NAME')
else:
lda_tokens.append(token.lower_)
return lda_tokens
def get_lemma(self, word):
lemma = wn.morphy(word)
if lemma is None:
return word
else:
return lemma
def get_lemma2(self, word):
return WordNetLemmatizer().lemmatize(word)
def prepare_text_for_lda(self, text):
tokens = self.tokenize(text)
tokens = [token for token in tokens if len(token) > 4]
tokens = [token for token in tokens if token not in en_stop]
tokens = [self.get_lemma(token) for token in tokens]
return tokens
def prepareDictionary(self):
text_data = []
with open('dataset.csv') as f:
for line in f:
tokens = self.prepare_text_for_lda(line)
if random.random() > .99:
print(tokens)
text_data.append(tokens)
self.dictionary = corpora.Dictionary(text_data)
corpus = [self.dictionary.doc2bow(text) for text in text_data]
import pickle
pickle.dump(corpus, open('corpus.pkl', 'wb'))
self.dictionary.save('dictionary.gensim')
self.ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=self.NUM_TOPICS, id2word=self.dictionary, passes=15)
self.ldamodel.save('model5.gensim')
topics = self.ldamodel.print_topics(num_words=4)
for topic in topics:
print(topic)
def getTopics(self, new_doc):
if self.dictionary is None or self.ldamodel is None:
self.prepareDictionary()
new_doc = self.prepare_text_for_lda(new_doc)
new_doc_bow = self.dictionary.doc2bow(new_doc)
topics = self.ldamodel.get_document_topics(new_doc_bow)
print(topics)
return topics
if __name__ == "__main__":
# test = NewsAnalyser()
# parser = argparse.ArgumentParser()
# parser.add_argument("text", nargs='+')
# news = [{'text': "Олександр Гриценко був призначений на посаду голови правління 'Укрексімбанку' наглядовою радою фінустанови 1 серпня 2014 року. Колективу банку його представила особисто тодішня голова НБУ Валерія Гонтарева. Гриценко змінив на цій посаді Віталія Білоуса, який очолював 'Укрексімбанк' від початку 2013 року. Усі повноваження він отримав 15 серпня 2014 року – безстроково"}]
news = [{'text': "У вівторок зранку помер командир 128-ї гірсько-піхотної бригади Євген Коростельов, який був поранений на передовій кілька днів тому.\nЦю інформацію \"\nBBC News Україна\n\" підтвердили у штабі Об'єднаних сил.\nКомбриг помер близько 4-ї ранку 19 листопада.\nЄвген Коростельов був пораний 12 листопада біля Новотроїцького під час обходу передових позицій.\nВін разом із іншим офіцером \nпідірвався на міні.\n Повідомлялося про серйозні поранення ніг.\n13 листопада комбрига у важкому стані доправили до госпіталя у Харкові.\nВибухом Коростельову відірвало ліву стопу; права нога була повністю пошкоджена, але лікарі врятували її.\nПредставник Інформаційного агентства Міністерства оборони Дмитро Чалий підтвердив кореспонденту \nDepo.Харків\n: \"Сьогодні вночі помер. Стан його різко погіршився\".\nЧалий зазначив, що зараз встановлюється остаточна причина смерті.\nУ Мукачеві у зв’язку із загибеллю Коростельова 19 листопада оголошено Днем жалоби, розпорядився міський голова Андрій Балога.\nЄвген Коростельов став командиром 128-ї бригади лише у вересні цього року. До того він служив у 25-й десантній бригадій, де був начальником артилерії і заступником командира.\nМав звання полковника.\nУ Євгена Коростельова залишилася дружина, донька і син.\nЦе другий український комбриг, який загинув під час війни на Донбасі. Першим був командир 51-ї окремої механізованої бригади Павло Півоваренко, який загинув під час виходу з Іловайська"}]
# test.sentimentAnalysis(news)
# test.autoTag(news)
# print(news[0]['keywords'])
# client = Algorithmia.client('simLnScRWPk7koh1Je5IZZP8Z7m1')
# input = "Нарцис вузьколистий росте в Україні лише на Закарпатті. Долина нарцисів – унікальна природна пам’ятка в урочищі Креші поблизу міста Хуст. Це єдине місце в Східній Європі, де існують природні зарості цієї білосніжної квітки. Схожі, але менші за площею популяції є ще в таких місцях: Альпах, Румунії, деяких країнах на Балканах. Науковці вважають, що багато тисячоліть тому, рятуючись від льодовика, квіти переселилися в хустську долину. Про це місце люди переповідають багато легенд. Одна з них є переспівом давньогрецького міфу про Нарциса. Друга легенда оповідає про татарське лихоліття. Коли ординці напали на Закарпаття та взяли приступом Хотинський замок, місцеві жителі припинили опір і піднесли в дарунок переможцям набиті нарцисовими квітами подушки як знак покори. Вороги зраділи, але вони, звісно, не знали, що нарцис – отруйна квітка, а той, хто засне на такій подушці, ніколи більше не прокинеться. Отже, уранці в ординському таборі мало хто побачив схід сонця. Нажахані подіями, татари втекли зі страшного краю. Долина в період цвітіння – незабутнє видовище. Цей феномен вартий того, аби хоч раз у житті його побачити."
# input = "We live in the computer age, a world increasingly shaped by programmers. Who are they, what motivates them, and what impact will they have on the rest of us?\nThat impact is ever more visible. Everything around us is becoming computerized. Your typewriter is gone, replaced by a computer. Your phone has turned into a computer. So has your camera. Soon your TV and VCR will be components in a computer network. Your car has more processing power in it than a room-sized mainframe did in 1970. Letters, encyclopedias, newspapers, and even your local store are being replaced by the Internet. What's next?\nHackers & Painters examines the world of hackers and the motivations of the people who occupy it. In clear, thoughtful prose that draws on illuminating historical examples, Graham takes readers on a fast-moving tour of what he calls an intellectual Wild West.\nWhy do kids who can't master high school end up as some of the most powerful people in the world? What makes a startup succeed? Will technology create a gap between those who understand it and those who don't? Will Microsoft take over the Internet? What to do about spam?\nIf you want to understand what hackers are up to, this book will tell you. And if you are a hacker, you'll probably recognize in it a portrait of yourself."
# algo = client.algo('SummarAI/Summarizer/0.1.3')
# algo.set_options(timeout=300) # optional
# print(algo.pipe(input).result)
|
<app-navbar></app-navbar>
<form [formGroup]="contractForm" novalidate (ngSubmit)="onSubmit()">
<mat-card class="shipping-card">
<mat-card-header>
<mat-card-title>
<h1 class="font-bold text-2xl mb-3">
Please enter the following contract information
</h1>
</mat-card-title>
</mat-card-header>
<mat-card-content>
<div class="row my-5">
<!-- Contract number field -->
<mat-form-field class="full-width">
<input
matInput
placeholder="Contract number"
formControlName="contractNum"
maxlength="20"
/>
<mat-error
*ngIf="contractForm.controls['contractNum'].hasError('required')"
>
Contract number is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="row my-5">
<!-- Contract start date -->
<mat-form-field class="full-width">
<input
matInput
[matDatepicker]="picker1"
placeholder="Contract start date"
formControlName="startDate"
/>
<mat-datepicker-toggle
matIconSuffix
[for]="picker1"
></mat-datepicker-toggle>
<mat-datepicker #picker1 disabled="false"></mat-datepicker>
<mat-error
*ngIf="contractForm.controls['startDate'].hasError('required')"
>
Contract start date is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="row my-5">
<!-- Contract end date -->
<mat-form-field class="full-width">
<input
matInput
[matDatepicker]="picker2"
placeholder="Contract expiry date"
formControlName="endDate"
[min]="contractForm.controls['startDate'].value"
/>
<mat-datepicker-toggle
matIconSuffix
[for]="picker2"
></mat-datepicker-toggle>
<mat-datepicker #picker2></mat-datepicker>
<mat-error
*ngIf="contractForm.controls['endDate'].hasError('required')"
>
Contract expiry date is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="row my-5">
<!-- Insured name field -->
<mat-form-field class="full-width">
<input
matInput
placeholder="Insured's name"
formControlName="insuredName"
maxlength="50"
/>
<mat-error
*ngIf="contractForm.controls['insuredName'].hasError('required')"
>
Insured's name is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
<div class="row mt-5 mb-10">
<!-- Vehicule registration field -->
<mat-form-field class="full-width">
<input
matInput
placeholder="Vehicule registration"
formControlName="vehiculeRegistration"
maxlength="15"
/>
<mat-error
*ngIf="
contractForm.controls['vehiculeRegistration'].hasError('required')
"
>
Vehicule's registration is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
</mat-card-content>
<mat-card-actions>
<div class="my-5">
<button mat-raised-button color="primary" type="submit" class="mx-2">
Submit
</button>
<button mat-raised-button color="gray" type="reset" class="mx-2">
Reset
</button>
</div>
</mat-card-actions>
</mat-card>
</form>
|
1. Para crear el proyecto con React: npx create-react-app pruebaconfiapp (Obligatorio minúsculas).
2. npm start
3.
--------------------------------------
TUTORIAL REACT, RUTAS PROTEGIDAS CON REACT ROUTER V6
+ Proteccion de Rutas
https://www.youtube.com/watch?v=42tFXd1PdCk
+ Puertas de escape
https://es.react.dev/learn/escape-hatches
https://keepcoding.io/blog/proteccion-de-rutas-con-react-router/
1. Se usa vite o create-react-app: npm create vite
- name: react-router-protected -> React -> JavaScript - Proyecto creado
2. En la carpeta del proyecto: npm i
3. npm i react-router-dom
(8 vulnerabilities (2 moderate, 6 high)
To address all issues (including breaking changes), run:
npm audit fix --force)
4. En App.jsx, dentro de src: eliminar contenido e instalar dos extensiones es7+ react/redux y intellicode, después dar rfce y eliminar la importación de React.
5. En App.css e index.css : eliminar contenido, solo dejar color de fonde en index.
6. Ejecutar proyecto: npm run dev
7. Crear enrutador de React router, importamos desde react-router-dom, se quita el contenido y ponemos un <BrowserRouter> en lugar del div dentro de la funcion App().
8. También se van a poner la multiples rutas agrupadas, para eso importamos y creamos un elemento hijo <Routes>.
9. También existe un elemento Route, que tiene como propiedades el nombre: path y un element, que es lo que va a mostrar.
9. Creamos la carpeta "pages" denrtro de src para crear las multiples páginas. Creamos dentro el archivo index.jsx
10. Importar desde pages en el archivo App.jsx, la o las páginas que queremos mostrar importando la funcion que contiene la vista.
11. El elemento link redicciona a diferentes rutas, se importa desde react-router-dom, para esto creamos la funcion Navigation en App.jsx.
12. https://www.youtube.com/watch?v=-bI0diefasA&ab_channel=Fazt Tutorial de app Nodejs y Mongodb Aplicación completa (Login, Registro,CRUD, ES6+, y más) (OJO)
13. Lanzar servidor: npm run dev
---------------------------------------
|
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-product-search',
templateUrl: './product-search.component.html',
styleUrls: ['./product-search.component.css']
})
export class ProductSearchComponent {
@Input() products: any[] = []; // Récupération de la liste des produits
searchTerm: string = ''; // terme de recherche pour le nom de produit
categorySearchTerm: string = '';
// Filtrage en fonction du terme de recherche
filterProducts(): any[] {
return this.products.filter(product =>
this.filterByName(product) && this.filterByCategory(product)
);
}
private filterByName(product: any): boolean {
if (!this.searchTerm.trim()) {
// si le terme de recherche est vide, on retourne true
return true;
}
return product.name.toLowerCase().includes(this.searchTerm.toLowerCase());
}
private filterByCategory(product: any): boolean {
if (!this.categorySearchTerm.trim()) {
return true;
}
return product.category.toLowerCase().includes(this.categorySearchTerm.toLowerCase());
}
}
|
# {Calculo para PCA funcional multiple} -----------------------------------.####
MFPCA_aux = function(mFData, M, uniExpansions, weights = rep(1, length(mFData)),
fit = FALSE, approx.eigen = FALSE){
p = length(mFData)
N = nObs(mFData)
dimSupp = dimSupp(mFData)
type = vapply(uniExpansions, function(l) {l$type}, FUN.VALUE = "")
m = meanFunction(mFData, na.rm = TRUE)*0
uniBasis = mapply(function(expansion, data) {
do.call(univDecomp, c(list(funDataObject = data), expansion))
}, expansion = uniExpansions, data = mFData, SIMPLIFY = FALSE)
for (j in seq_len(p)) {
if (type[j] == "uFPCA")
m[[j]] = uniBasis[[j]]$meanFunction*0
}
npc = vapply(uniBasis, function(x) {dim(x$scores)[2]}, FUN.VALUE = 0)
if (M > sum(npc)) {
M = sum(npc)
warning("Function MFPCA: total number of univariate basis functions is smaller than given M. M was set to ", sum(npc), ".")
}
if (all(foreach::foreach(j = seq_len(p), .combine = "c") %do% {uniBasis[[j]]$ortho}))
Bchol = NULL
else {
Bchol = Matrix::bdiag(lapply(uniBasis, function(l) {
if (l$ortho)
res = Matrix::Diagonal(n = ncol(l$scores))
else res = Matrix::chol(l$B)
return(res)
}))
}
mArgvals = funData::argvals(mFData)
res = MFPCA:::calcMFPCA(N = N, p = p, Bchol = Bchol, M = M, type = type,
weights = weights, npc = npc, argvals = mArgvals, uniBasis = uniBasis,
fit = fit, approx.eigen = approx.eigen)
res$meanFunction = m
names(res$functions) = names(mFData)
namesList = lapply(mFData, names)
if (!all(vapply(namesList, FUN = is.null, FUN.VALUE = TRUE))) {
if (length(unique(namesList)) != 1)
warning("Elements have different curve names. Use names of the first element for the results.")
row.names(res$scores) <- namesList[[1]]
}
class(res) = "MFPCAfit"
return(res)
}
# {Calculo para PCA híbrido} ----------------------------------------------.####
MFHPCA = function(datos, M = NULL, delta,
omega, scale = FALSE , ...){
if (scale) {
datos = scale_FunDataH(datos)
}
fun_data = datos@funData
vec_data = datos@vecData
p_fun = length(fun_data) # numero de variables funciones
p_vec = ncol(vec_data) # numero de variables vectores
N = nrow(vec_data) # numero de observaciones
# {MFDA de la parte funcional}
uniExpansions_r = list()
for (i in 1:p_fun) {
uniExpansions_r[[i]] = list(type = 'uFPCA',npc = 10) # PCA univariados
}
cat('Calculating MFPCA of the multivariate functional part...','\n')
mfda_r = MFPCA_aux(fun_data, M = 8,uniExpansions = uniExpansions_r)
aport_mfda_r = summary(mfda_r)
L = c(1:8)[round(cumsum(mfda_r$values/sum(mfda_r$values)),2) >= delta][1]
if (is.na(L)) {
mfda_r = MFPCA(fun_data, M = 10,uniExpansions = uniExpansions_r)
L = c(1:10)[round(cumsum(mfda_r$values/sum(mfda_r$values)),2) >= delta][1]
}
if (L == 1) {
scores_mfda = matrix(mfda_r$scores[,1:L] ,ncol = 1)
}else{
scores_mfda = mfda_r$scores[,1:L]
}
# {PCA parte vectorial}
cat('Calculating PCA of the vectorial part...','\n')
pca_r = PCA(vec_data, scale.unit = FALSE, ncp = p_vec, graph = FALSE)
aport_pca_r = t(pca_r$eig)
J = c(1:p_vec)[cumsum(pca_r$eig[,1]/sum(pca_r$eig[,1])) >= delta][1]
pca_r = PCA(vec_data, scale.unit = FALSE, ncp = J, graph = FALSE)
scores_pca = pca_r$ind$coord
# {Estimacion de la matriz V}
scores_join = cbind(scores_mfda, scores_pca)
cat('Calculating MFHPCA of the multivariate functional part...','\n')
V = cov(scores_join)
eigen_V = eigen(V)
# {Calculo de pc_hibridos}
mfdaH_r = list()
mfdaH_r$values = eigen_V$values # valores propios
mfdaH_r$scores = vector() # puntajes del PCA hibrido
cm_i = eigen_V$vectors[1:L,]
dm_i = eigen_V$vectors[-c(1:L),]
eta_i = scores_mfda
gamma_i = scores_pca
# funciones propias (Psi,Theta)
if (is.null(M)) {
values_mi = sort(mfdaH_r$values/sum(mfdaH_r$values), decreasing = TRUE)
M = c(1:(L + J))[round(cumsum(values_mi/sum(values_mi)),2) >= omega][1]
}
# Psi
for (m in 1:M) {
# Psi
fun_i = 0
for (l in 1:L) {
fun_i = mfda_r$functions[l]*cm_i[l,m] + fun_i
}
# Theta
vec_i = 0
for (j in 1:J) {
vec_i = pca_r$svd$V[,j]*dm_i[j,m] + vec_i
}
# Direccion hibrida
if (m == 1) {
dir_i = mfh_data(fun_data = fun_i,vec_data = matrix(vec_i,nrow = 1))
}else{
aux_dir = mfh_data(fun_data = fun_i,vec_data = matrix(vec_i,nrow = 1))
dir_i = append_Mfun(dir_i,aux_dir)
}
}
mfdaH_r$dir = dir_i
# Calculo de scores híbridos
for (i in 1:M) {
D = matrix(dm_i[,i], nrow = N, ncol = J, byrow = TRUE)
C = matrix(cm_i[,i], nrow = N, ncol = L, byrow = TRUE)
score_i = rowSums(scores_mfda*C) + rowSums(scores_pca*D)
mfdaH_r$scores = cbind(mfdaH_r$scores, score_i)
}
# Resultados finales
aport_mfdaH_r = t(cbind(mfdaH_r$values,mfdaH_r$values/sum(mfdaH_r$values),cumsum(mfdaH_r$values/sum(mfdaH_r$values))))
mfdaH_r$values = mfdaH_r$values[1:M]
pca_i = list(MFPCA = mfda_r, PCA = pca_r, J = J, L = L, M = M) # PCA individuales
pcah_i = list(V = V, mfdaH = mfdaH_r, dir = dir_i)
aports_i = list(MFPCA = aport_mfda_r, PCA = aport_pca_r, MFPCAH = aport_mfdaH_r)
results = list(PCAs = pca_i, MFPCAH = pcah_i,Aport = aports_i,eigen_V = eigen_V)
class(results) = 'mfhpca'
return(results)
}
# {Resumen PCA híbrido} ---------------------------------------------------.####
summary.mfhpca = function(object){
mfda_r = object$PCAs$MFPCA
pca_r = object$PCAs$PCA
mfdaH_r = object$MFPCAH$mfdaH
L = object$PCAs$L
J = object$PCAs$J
M = object$PCAs$M
# MFPCA
tab_summary_mfda = round(object$Aport$MFPCA, 3)[,1:L]
tab_summary_mfda[2:3,] = tab_summary_mfda[2:3,]*100
rownames(tab_summary_mfda) = c('val', 'explicada', 'acumulada')
# PCA
tab_summary_pca = round(object$Aport$PCA, 3)[,1:J]
rownames(tab_summary_pca) = rownames(tab_summary_mfda)
colnames(tab_summary_pca) = paste('PC', 1:J)
# MFHPCA
tab_summary_mfdaH = round(object$Aport$MFPCAH, 3)[,1:M]
rownames(tab_summary_mfdaH) = rownames(tab_summary_mfda)
colnames(tab_summary_mfdaH) = paste('PC',1:M)
cat('PCA _____________________________________________________________.','\n')
print(round(tab_summary_pca,4))
cat('MFPCA ___________________________________________________________.','\n')
print(round(tab_summary_mfda,4))
cat('MFHPCA __________________________________________________________.','\n')
print(round(tab_summary_mfdaH,4))
class_scores = class(object$MFPCAH$mfdaH$scores)
class_dir = class(object$MFPCAH$dir)
cat('mfdaH_r$scores:', class_scores,'...', 'puntajes para PCA hibrido','\n')
cat('mfdaH_r$dir:', class_dir,'...',
'direcciones principales PCA hibrido','\n')
}
# {Grafico PCA híbrido} ---------------------------------------------------.####
plot_varexp = function(values){
val_i = values
text_lab = paste0(round(val_i*100,1), '%')
perf = data.frame(i = seq(1, length(val_i)), val_i, text_lab)
max_y = max(perf$val_i)*(1 + 0.1)
ggp = ggplot(perf) +
geom_bar(aes(x = i, y = val_i), stat = 'identity', fill = '#17B978') +
geom_line(aes(x = i, y = val_i), stat = 'identity') +
geom_point(aes(x = i, y = val_i)) +
labs(x = 'i' ,y = 'Valor propio') +
geom_text(aes(x = i, y = val_i), label = text_lab, vjust = -0.4, hjust = 0) +
theme_bw() + ylim(0,max_y)
return(ggp)
}
autoplot.mfhpca = function(object, type = 'var'){
mfda_r = object$PCAs$MFPCA
pca_r = object$PCAs$PCA
mfdaH_r = object$MFPCAH$mfdaH
L = object$PCAs$L
J = object$PCAs$J
M = object$PCAs$M
k = length(object$PCAs$MFPCA$functions)
p = dim(object$PCAs$PCA$var$coord)[1]
N = dim(object$PCAs$PCA$ind$coord)[1]
# Varianza explicada
if (type == 'var') {
p1 = plot_varexp(c(object$Aport$MFPCA[2,1:L])) + ggtitle(paste('MFPCA (k=', k,'L=', L,')'))
p2 = plot_varexp(c(object$Aport$MFPCAH[2,1:M])) + ggtitle(paste('MFHPCA (M=' ,M ,')'))
p3 = plot_varexp(c(object$Aport$PCA[2,1:J]/100)) + ggtitle(paste('PCA (p=', p, 'J=', J, ')'))
plot_i = (p1 + p3)/p2
return(plot_i)
}
# Gráficos de funciones propias y vectores propios PCA
if (type == 'eigen') {
return(autoplot(object$MFPCAH$dir))
}
# Plano factorial
if (type == 'ind') {
scores_mfdaH_r = data.frame(mfdaH_r$scores, id = 1:N)
colnames(scores_mfdaH_r) = c('PC1', 'PC2', 'id')
plot_i = ggplot(scores_mfdaH_r,aes(PC1, PC2)) +
geom_vline(xintercept = 0, color = 'blue') +
geom_hline(yintercept = 0, color = 'blue') + theme_bw() +
geom_point() + ggtitle('MFPCAH') +
geom_text(aes(label = round(id,3)), vjust = -0.4, hjust = 0,size = 3) +
geom_density_2d(alpha = 0.5)
return(plot_i)
}
}
# {Proyecciones con pca hibrido} ------------------------------------------.####
pryc_pca_H = function(data_j,PCA_j){
eigen_V = PCA_j$eigen_V
L = PCA_j$PCAs$L
J = PCA_j$PCAs$J
M = PCA_j$PCAs$M
N = nObs(data_j@funData)
cm_i = eigen_V$vectors[1:L,]
dm_i = eigen_V$vectors[-c(1:L),]
mfda_r = PCA_j$PCAs$MFPCA
pca_r = PCA_j$PCAs$PCA
scores_mfda_j = pryc_pca_F(data_j = data_j@funData,PCA_j = mfda_r)[,1:L]
scores_pca_j = pryc_pca_V(data_j = data_j@vecData,PCA_j = pca_r)[,1:J]
scores_j = vector()
for (i in 1:M) {
D = matrix(dm_i[,i], nrow = N, ncol = J, byrow = TRUE)
C = matrix(cm_i[,i], nrow = N, ncol = L, byrow = TRUE)
score_i = rowSums(scores_mfda_j*C) + rowSums(scores_pca_j*D)
scores_j = cbind(scores_j, score_i)
}
return(scores_j)
}
pryc_pca_F = function(data_j,PCA_j){
proy_pcaF = function(obs_w,dir_w) {
N = nObs(obs_w)
M = nObs(dir_w)
# Calculo de scores híbridos
score_i1 = matrix(nrow = N,ncol = M)
for (m in 1:M) {
score_i1[,m] = c(sapply(list(1:N),function(i,z_j,dir_j){
return(scalarProduct(z_j[i],dir_j))
},z_j = obs_w,dir_j = dir_w[m]))
}
colnames(score_i1) = paste0("scor_",1:M)
return(score_i1)
}
Psi_i = PCA_j$functions
scores_data = proy_pcaF(obs_w = data_j,dir_w = Psi_i)
return(scores_data)
}
pryc_pca_V = function(data_j, PCA_j) {
dir_j = PCA_j$svd$V
ncp = ncol(dir_j)
coord = data_j
coord = crossprod(t(data_j), dir_j)
coord = coord[, 1:ncp, drop = F]
return(coord)
}
# {Reconstruccion de datos apartir de scors y direcciones} ----------------.####
Inv_PCA_H = function(dir_j,scor_j) {
n_fun = length(dir_j@funData)
n_vec = ncol(dir_j@vecData)
N = nrow(scor_j)
simData_fun = vector("list", n_fun)
for (j in seq_len(n_fun)) {
aux_mat = dir_j@funData[[j]]@X
X <- apply(aux_mat,-1, function(v) {
scor_j %*% v
})
if (N == 1)
dim(X) <- c(1, nObsPoints(dir_j@funData[[j]]))
simData_fun[[j]] <- funData(dir_j@funData[[j]]@argvals, X)
}
simData_fun = multiFunData(simData_fun)
simData_vec = scor_j %*% dir_j@vecData
simData_vec = simData_vec[,1:n_vec]
if (n_vec == 1) {
simData_vec = matrix(c(simData_vec),ncol = 1)
}
Z = mfh_data(fun_data = simData_fun,vec_data = simData_vec)
return(Z)
}
Inv_PCA_F = function(dir_j,scor_j) {
n_fun = length(dir_j)
N = nrow(scor_j)
simData_fun = vector("list", n_fun)
for (j in seq_len(n_fun)) {
aux_mat = dir_j[[j]]@X
X <- apply(aux_mat,-1, function(v) {
scor_j %*% v
})
if (N == 1)
dim(X) <- c(1, nObsPoints(dir_j[[j]]))
simData_fun[[j]] <- funData(dir_j[[j]]@argvals, X)
}
simData_fun = multiFunData(simData_fun)
return(simData_fun)
}
|
data_source_title <- data_source |>
mutate(
source_title =
ifelse(
is.na(source_title),
str_extract(document, "^.+_(.+$)", 1),
source_title
)
) |>
count(source_title, country, comment_ideation) |>
filter(!is.na(comment_ideation), comment_ideation != "I2") |>
mutate(
sum = sum(n),
prop = n / sum,
.by = source_title
) |>
filter(!str_detect(comment_ideation, "I0")) |>
mutate(prop_sum = sum(prop), .by = source_title) |>
group_by(country) |>
arrange(desc(prop_sum), source_title, .by_group = TRUE) |>
mutate(rank = rleid(source_title)) |>
filter(rank <= 15) |>
mutate(comment_ideation = factor(comment_ideation,
levels = c("I1", "I1ASC", "I1a")
))
plot_source_title <- data_source_title |>
ggplot(aes(x = reorder(rank, desc(rank)))) +
geom_bar(
aes(y = prop, fill = comment_ideation),
stat = "identity"
) +
geom_text(aes(label = source_title), y = 0, hjust = 0, size = 3) +
coord_flip() +
facet_grid(~country) +
scale_fill_manual(values = col_ideation[3:5], name = "Ideation") +
labs(y = "proportion", x = "") +
theme_classic() +
theme(
strip.text = element_text(size = 12),
panel.grid.major.x = element_line(color = "#bebebec7"),
axis.text.y = element_blank(),
axis.ticks.y = element_blank()
)
ggsave(plot_source_title,
filename = paste0(output, "plot_source_title.png"),
scale = 1.2, width = 10, height = 4.5
)
|
import { MouseEventHandler } from "react";
export interface CustomButtonProps {
title: string;
containerStyles?: string;
handleClick?: MouseEventHandler<HTMLButtonElement>;
btnType?: "button" | "submit";
textStyles?:string
rightIcon:string
}
export interface SearchManuFacturer {
manuFacturer: string;
setManuFacturer: (manufacturer: string) => void;
}
export interface CarCardProps {
city_mpg: number;
class: string;
combination_mpg: number;
cylinders: number;
displacement: number;
drive: string;
fuel_type: string;
highway_mpg: number;
make: string;
model:string;
transmission: string;
year: number;
}
export interface FilterProps {
model?:string
manuFacturer?:string
year?:number
limit?:number
fuel?:string
}
export interface HomeProps {
searchParams: FilterProps;
}
export interface OptionProps {
title:string
value:string
}
export interface CustomFilterProps {
title:string
options:OptionProps[]
}
export interface ShowMoreProps{
pageNumber:number
isNext:boolean
}
|
using ReservationVols.Domain.Response;
using ReservationVols.Infrastructure.Extensions;
using ReservationVols.Infrastructure.Model.Dao;
using System.Collections.Generic;
using System.Linq;
namespace ReservationVols.Infrastructure.Model.Assembler
{
/// <summary>
/// the vol assembler class.
/// </summary>
public static class VolAssembler
{
/// <summary>
/// Converts to domainvollist.
/// </summary>
/// <param name="volDaos">The vol daos.</param>
/// <returns>list of vols result</returns>
public static IEnumerable<VolResult> ToDomainVolList(this IEnumerable<VolDao> volDaos)
{
if (volDaos == null || !volDaos.Any())
{
return new List<VolResult>();
}
return volDaos.ToList().ConvertAll(ToDomainVol);
}
/// <summary>
/// Converts to domainvol.
/// </summary>
/// <param name="volDao">The vol DAO.</param>
/// <returns>vol result</returns>
public static VolResult ToDomainVol(this VolDao volDao)
=> volDao is null
? null
: new VolResult
{
VolId = volDao.Id,
ArrivalCity = volDao.ArrivalCity,
ArrivalDate = volDao.ArrivalDate.ToDateTime(),
DepartCity = volDao.DepartCity,
DepartDate = volDao.DepartDate.ToDateTime(),
PassengersNbr = volDao.PassengersNbr,
VolPrice = volDao.VolPrice,
SpaceAvailable = volDao.SpaceAvailable,
};
}
}
|
const asyncHandler = require('express-async-handler');
const APIError = require("../Helper/APIError");
const CreateResponse = require("../ResponseObject/responseObject");
const updatedFields = require("../Shared/updatedFields");
const {filter, select, sort, pagination} = require("../Shared/queryRequest");
exports.getAllDocuments = (model, modelName = 'Items', ...searchFields) =>
asyncHandler(async (request, response) => {
const filtedFields = filter(request, ...searchFields);
const {page, limit, skip, totalPages} = await pagination(request, await model.countDocuments(filtedFields));
const AllDocuments = await model.find(filtedFields, select(request)).skip(skip).limit(limit).sort(sort(request));
if(AllDocuments.length > 0) {
response.status(200).json(CreateResponse(true, `All ${modelName} are retrieved successfully`, AllDocuments, page, limit, totalPages));
}
else {
response.status(200).json(CreateResponse(true, `Empty, No ${modelName} to show`, AllDocuments, page, limit, totalPages));
}
})
exports.getDocumentById = (model, modelName = 'Item') =>
asyncHandler(async (request, response, next) => {
const document = await model.findById(request.params.id, select(request))
if(!document) {
next(new APIError(`This ${modelName} is not found`, 404));
return;
}
response.status(200).json(CreateResponse(true, `The data of this ${modelName} is retrieved successfully`, [document]));
})
exports.addDocument = (model, modelName = 'Item') =>
asyncHandler(async (request, response) => {
const document = await model.create(request.body);
response.status(201).json(CreateResponse(true, `The ${modelName} is added successfully`, [document]));
})
exports.updateDocument = (model, modelName = 'Item', ...feildsThatAllowToUpdate) =>
asyncHandler(async (request, response, next) => {
const targetFields = updatedFields(request, feildsThatAllowToUpdate);
if(Object.keys(targetFields).length > 0) {
const updatedDocument = await model.findOneAndUpdate({_id: request.params.id}, targetFields, {new: true})
if(!updatedDocument) {
next(new APIError(`This ${modelName} is not found`, 404));
return;
}
await updatedDocument.save();
response.status(200).json(CreateResponse(true, `This ${modelName} is updated successfully`, [updatedDocument]));
return;
}
response.status(200).json(CreateResponse(true, `Nothing is updated`));
})
exports.softDeleteDocument = (model, modelName = 'Item') =>
asyncHandler(async (request, response, next) => {
const deletedDocument = await model.findOneAndUpdate({_id: request.params.id}, {deleted: true, available: false})
if(!deletedDocument) {
next(new APIError(`This ${modelName} is not found`, 404));
return;
}
response.status(204).json();
})
exports.hardDeleteDocument = (model, modelName = 'Item') =>
asyncHandler(async (request, response, next) => {
const deletedDocument = await model.findOneAndDelete({_id: request.params.id})
if(!deletedDocument) {
next(new APIError(`This ${modelName} is not found`, 404));
return;
}
response.status(204).json();
})
|
package com.aurine.cloudx.estate.controller;
import com.aurine.cloudx.common.data.project.ProjectContextHolder;
import com.aurine.cloudx.estate.entity.ProjectLabelConfig;
import com.aurine.cloudx.estate.service.ProjectLabelConfigService;
import com.aurine.cloudx.estate.vo.ProjectLabelConfigVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
/**
* 标签管理
*
* @author 王伟
* @date 2020-05-07 08:09:35
*/
@RestController
@AllArgsConstructor
@RequestMapping("/baseLabelConfig")
@Api(value = "baseLabelConfig", tags = "标签管理")
public class ProjectLabelConfigController {
private final ProjectLabelConfigService projectLabelConfigService;
/**
* 分页查询
*
* @param page 分页对象
* @param projectLabelConfigVo
* @return
*/
@ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page")
public R getLabelConfigPage(Page page, ProjectLabelConfigVo projectLabelConfigVo ) {
return R.ok(projectLabelConfigService.findPage(page, projectLabelConfigVo));
}
/**
* 分页查询
*
* @return
* @author: 王良俊
*/
@ApiOperation(value = "查询所有的标签", notes = "查询所有的标签")
@GetMapping("/allLabel")
public R getAllLabel() {
return R.ok(projectLabelConfigService.list());
}
/**
* 通过id查询标签管理
*
* @param labelId id
* @return R
*/
@ApiOperation(value = "通过id查询", notes = "通过id查询")
@GetMapping("/{labelId}")
public R getById(@PathVariable("labelId") String labelId) {
return R.ok(projectLabelConfigService.getById(labelId));
}
/**
* 新增标签管理
*
* @param projectLabelConfig 标签管理
* @return R
* @Author: 王良俊
*/
@ApiOperation(value = "新增标签管理", notes = "新增标签管理")
@SysLog("新增标签管理")
@PostMapping
@PreAuthorize("@pms.hasPermission('estate_labelconfig_add')")
public R save(@RequestBody ProjectLabelConfig projectLabelConfig) {
return R.ok(projectLabelConfigService.saveLabel(projectLabelConfig));
}
/**
* 修改标签管理
*
* @param projectLabelConfig 标签管理
* @return R
*/
@ApiOperation(value = "修改标签管理", notes = "修改标签管理")
@SysLog("修改标签管理")
@PutMapping
@PreAuthorize("@pms.hasPermission('estate_labelconfig_edit')")
public R updateById(@RequestBody ProjectLabelConfig projectLabelConfig) {
projectLabelConfig.setOperator(null);
ProjectLabelConfigVo projectLabelConfigVo = projectLabelConfigService.selectByLabelId(projectLabelConfig.getLabelId());
if (!projectLabelConfigVo.getProjectId().equals(ProjectContextHolder.getProjectId())) {
throw new RuntimeException("该标签不可修改");
}
return R.ok(projectLabelConfigService.updateById(projectLabelConfig));
}
/**
* 通过id删除标签管理
*
* @param labelId id
* @return R
* @Author: 王良俊
*/
@ApiOperation(value = "通过id删除标签管理", notes = "通过id删除标签管理")
@SysLog("通过id删除标签管理")
@DeleteMapping("/{labelId}")
@PreAuthorize("@pms.hasPermission('estate_labelconfig_del')")
public R removeById(@PathVariable String labelId) {
ProjectLabelConfigVo projectLabelConfigVo = projectLabelConfigService.selectByLabelId(labelId);
if (!projectLabelConfigVo.getProjectId().equals(ProjectContextHolder.getProjectId())) {
throw new RuntimeException("该标签不可删除");
}
return R.ok(projectLabelConfigService.removeById(labelId));
}
@GetMapping("/getLabelByName")
@ApiOperation(value = "通过标签名查询", notes = "通过标签名查询")
public R getTemplateByTitle(String labelName) {
if (ProjectContextHolder.getProjectId() == 1) {
return R.ok(projectLabelConfigService.list(Wrappers.lambdaQuery(ProjectLabelConfig.class).eq(ProjectLabelConfig::getLabelName, labelName)));
} else {
return R.ok();
}
}
}
|
import { createContext, useState, useContext } from "react";
import { UserContext } from "./UserContext";
import axios from "axios";
import { apiUrl } from "../Api/Api";
export const ChatContext = createContext();
const ChatProvider = ({ children }) => {
const {
authState: { user },
} = useContext(UserContext);
const [selectedChat, setSelectedChat] = useState();
const [results, setResults] = useState([]);
const [chats, setChats] = useState([]);
const [fetchAgain, setFetchAgain] = useState(false);
const [message, setMessage] = useState([]);
const [socketConnect, setSocketConnect] = useState(false);
const [notification, setNotification] = useState([]);
// Chọn người để trò chuyển
const accessChat = async (userId) => {
try {
const { data } = await axios.post(`${apiUrl}/chat/access`, { userId });
if (!chats.find((c) => c._id === data._id))
setChats([data.FullChat, ...chats]);
setSelectedChat(data.FullChat);
} catch (error) {
if (error.response.data) return error.response.data;
else return { success: false, message: error.message };
}
};
//Tải tin nhắn
const fetchChats = async () => {
try {
const { data } = await axios.get(`${apiUrl}/chat`);
if (data) return setChats(data.results);
} catch (error) {
if (error.response.data) return error.response.data;
else return { success: false, message: error.message };
}
};
//Tìm kiếm người dùng để thêm vào nhóm
const getUsers = async (query) => {
try {
const { data } = await axios.get(`${apiUrl}/user/search?search=${query}`);
setResults(data.users);
} catch (error) {
if (error.response.data) return error.response.data;
else return { success: false, message: error.message };
}
};
//Tạo nhóm chat
const createGroupChat = async (value) => {
try {
const { data } = await axios.post(`${apiUrl}/chat/group`, value);
setChats([data.fullGroupChat, ...chats]);
} catch (error) {
if (error.response.data) return error.response.data;
else return { success: false, message: error.message };
}
};
//Cập nhật tên nhóm
const renameGroupChat = async (newName) => {
try {
const { data } = await axios.put(`${apiUrl}/chat/rename`, newName);
setSelectedChat(data.updatedChat);
setFetchAgain(!false);
} catch (error) {
if (error.response.data) return error.response.data;
else return { success: false, message: error.message };
}
};
//Mời thêm thành viên
const inviteMember = async (newUser) => {
try {
const { data } = await axios.put(`${apiUrl}/chat/group_add`, newUser);
setSelectedChat(data.added);
setFetchAgain(!false);
} catch (error) {
if (error.response.data) return error.response.data;
else return { success: false, message: error.message };
}
};
//Xóa thành viên khói nhóm
const removeMember = async (dataDelete) => {
try {
const { data } = await axios.put(
`${apiUrl}/chat/group_remove`,
dataDelete,
);
dataDelete.userId === user._id
? setSelectedChat()
: setSelectedChat(data);
setFetchAgain(!false);
} catch (error) {
if (error.response.data) return error.response.data;
else return { success: false, message: error.message };
}
};
// //Gửi tin nhắn
// const handleSendMessage = async (value) => {
// try {
// const { data } = await axios.post(`${apiUrl}/message/send`, value);
// setMessage([...message, data.message]);
// } catch (error) {
// if (error.response.data) return error.response.data;
// else return { success: false, message: error.message };
// }
// };
//Tải tin nhắn từ hệ thống
const handleFetchMessage = async (chatId) => {
try {
const { data } = await axios.get(`${apiUrl}/message/${chatId}`);
setMessage(data.messages);
} catch (error) {
if (error.response.data) return error.response.data;
else return { success: false, message: error.message };
}
};
const data = {
selectedChat,
setSelectedChat,
chats,
setChats,
accessChat,
fetchChats,
getUsers,
results,
setResults,
createGroupChat,
fetchAgain,
setFetchAgain,
renameGroupChat,
inviteMember,
removeMember,
// handleSendMessage,
handleFetchMessage,
message,
setMessage,
setSocketConnect,
socketConnect,
notification,
setNotification,
};
return <ChatContext.Provider value={data}>{children}</ChatContext.Provider>;
};
export default ChatProvider;
|
/**
* External dependencies
*/
var React = require( 'react' ),
debug = require( 'debug' )( 'calypso:my-sites:all-sites' ),
classNames = require( 'classnames' );
/**
* Internal dependencies
*/
var AllSitesIcon = require( 'my-sites/all-sites-icon' ),
Count = require( 'components/count' ),
user = require( 'lib/user' )();
module.exports = React.createClass( {
displayName: 'AllSites',
componentDidMount: function() {
debug( 'The All Sites component is mounted.' );
},
getDefaultProps: function() {
return {
// onSelect callback
onSelect: function() {},
// Set a href attribute to the anchor
href: null,
// Mark as selected or not
isSelected: false,
showCount: true
};
},
propTypes: {
sites: React.PropTypes.object.isRequired,
onSelect: React.PropTypes.func,
href: React.PropTypes.string,
isSelected: React.PropTypes.bool,
showCount: React.PropTypes.bool
},
onSelect: function( event ) {
this.props.onSelect( event );
},
render: function() {
var allSitesClass;
allSitesClass = classNames( {
'all-sites': true,
'is-selected': this.props.isSelected
} );
return (
<div className={ allSitesClass }>
<a className="site__content" href={ this.props.href } onTouchTap={ this.onSelect }>
<AllSitesIcon sites={ this.props.sites.get() } />
<div className="site__info">
<span className="site__title">{ this.translate( 'All My Sites' ) }</span>
<span className="site__domain">{ this.translate( 'Manage all my sites' ) }</span>
</div>
{ this.props.showCount && <Count count={ user.get().visible_site_count } /> }
</a>
</div>
);
}
} );
|
package dev.lukasnehrke.vulnaware.bom.model;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import dev.lukasnehrke.vulnaware.project.model.Project;
import dev.lukasnehrke.vulnaware.storage.model.Asset;
import dev.lukasnehrke.vulnaware.vulnerability.model.Vulnerability;
import jakarta.persistence.*;
import java.util.*;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.lang.Nullable;
@Getter
@Setter
@Entity
@Table(name = "va_boms", uniqueConstraints = { @UniqueConstraint(columnNames = { "project_id", "tag" }) })
@JsonView(Bom.InternalView.class)
public class Bom {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonSerialize(using = ToStringSerializer.class)
@JsonView(Bom.PublicView.class)
private Long id;
/* --- Relationships --- */
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "project_id", nullable = false, updatable = false)
private Project project;
@OneToMany(mappedBy = "bom", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private List<Component> components;
@OneToMany(mappedBy = "bom", fetch = FetchType.LAZY)
private List<Vulnerability> vulnerabilities;
@Nullable
@OneToOne(fetch = FetchType.EAGER)
private Asset asset;
@Embedded
@JsonView(Bom.PublicView.class)
private Metrics metrics;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "va_bom_history", joinColumns = @JoinColumn(name = "bom_id"))
@JsonView(Bom.PublicView.class)
private List<History> history;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "va_bom_annotations", joinColumns = @JoinColumn(name = "bom_id"))
private List<Annotation> annotations = new ArrayList<>();
/* --- Columns --- */
/** Unique tag of this bom. */
@Column(name = "tag", nullable = false)
@JsonView(Bom.PublicView.class)
private String tag;
/** Format of the original bom. */
@Nullable
@Column(name = "format")
@Enumerated(EnumType.STRING)
@JsonView(Bom.PublicView.class)
private BomFormat format;
/** Data format of the original bom. */
@Nullable
@Column(name = "data_format")
@Enumerated(EnumType.STRING)
@JsonView(Bom.PublicView.class)
private DataFormat dataFormat;
/** Format version of the original bom. */
@Nullable
@Column(name = "format_version")
@JsonView(Bom.PublicView.class)
private String formatVersion;
@Nullable
@Column(name = "description", length = 1024)
@JsonView(Bom.PublicView.class)
private String description;
@Column(name = "monitoring", nullable = false)
@JsonView(Bom.PublicView.class)
private boolean monitoring = true;
@Nullable
@Column(name = "last_analyzed_at")
private Date lastAnalyzedAt;
@Column(name = "created_at", nullable = false, updatable = false)
@CreationTimestamp
private Date createdAt;
@Column(name = "updated_at", nullable = false)
@UpdateTimestamp
private Date updatedAt;
public interface PublicView {}
public interface InternalView {}
}
|
import express from "express";
import groupRepository from "../repositories/GroupRepository.js";
import userRepository from "../repositories/UserRepository.js";
import {loginMiddleware} from "../middlewares/loginMiddleware.js";
import {ExpenseModel} from "../models/ExpenseModel.js";
import PDFDocument from "pdfkit";
import {RefundModel} from "../models/RefundModel.js";
import {Parser} from "json2csv";
import debtRepository from "../repositories/DebtRepository.js";
const groupRouter = express.Router();
groupRouter.get("/", loginMiddleware, async (req, res) => {
const groups = await groupRepository.getGroups();
return res.status(200).json(groups);
});
groupRouter.get("/:id", loginMiddleware, async (req, res) => {
const {id} = req.params;
const group = await groupRepository.getGroupById(id);
if (!group) {
return res.status(404).send("Group not found");
}
return res.status(200).json(group);
});
groupRouter.get("/:id/users", loginMiddleware, async (req, res) => {
const {id} = req.params;
const group = await groupRepository.getGroupById(id);
if (group.includes(req.user) === true) {
const users = await userRepository.getUsersByGroup(id, group);
return res.status(200).json(users);
} else {
return res
.status(403)
.send("You are not allowed to see this group's users");
}
});
groupRouter.post("/", loginMiddleware, async (req, res) => {
try {
if (req.body.members.includes(req.user) === false) {
return res
.status(403)
.send("You are not allowed to create a group without yourself");
}
const group = await groupRepository.createGroup(req.body);
for (const member of req.body.members) {
for (const member2 of req.body.members) {
if (member !== member2) {
await debtRepository.updateDebt(group._id, member, member2, {amount: 0})
}
}
}
return res.status(201).json(group);
} catch (e) {
return res.status(400).send(e);
}
});
groupRouter.put("/:id", loginMiddleware, async (req, res) => {
try {
const {id} = req.params;
const groupToUpdate = await groupRepository.getGroupByIdWithoutPopulate(id);
if (groupToUpdate.members.includes(req.user) === false) {
return res.status(403).send("You are not allowed to update this group");
}
if (!groupToUpdate) {
return res.status(404).send("Group not found");
}
await groupRepository.updateGroup(id, req.body);
return res.status(200).send("Group updated");
} catch (e) {
return res.status(400).send(e);
}
});
groupRouter.put("/:id/addUser", loginMiddleware, async (req, res) => {
try {
const {id} = req.params;
const {idUser} = req.body;
const groupToUpdate = await groupRepository.getGroupByIdWithoutPopulate(id);
if (groupToUpdate.members.includes(req.user) === false) {
return res
.status(403)
.send("You are not allowed to add a user to this group");
}
if (!groupToUpdate) {
return res.status(404).send("Group not found");
}
if (groupToUpdate.members.includes(idUser) === true) {
return res.status(400).send("User is already in the group");
}
await groupRepository.addUserToGroup(id, idUser);
for (const member of groupToUpdate.members) {
if (member !== idUser) {
await debtRepository.updateDebt(groupToUpdate._id, member, idUser, {amount: 0})
await debtRepository.updateDebt(groupToUpdate._id, idUser, member, {amount: 0})
}
}
return res.status(200).send("User added to group");
} catch (e) {
return res.status(400).send(e);
}
});
groupRouter.put("/:id/removeUser", loginMiddleware, async (req, res) => {
try {
const {id} = req.params;
const groupToUpdate = await groupRepository.getGroupById(id);
if (!groupToUpdate) {
return res.status(404).send("Group not found");
}
await groupRepository.removeUserFromGroup(id, req.user);
return res.status(200).send("User removed from group");
} catch (e) {
return res.status(400).send(e);
}
});
groupRouter.get("/export/:groupId", async (req, res) => {
const {groupId} = req.params;
const {format} = req.query; // format can be 'pdf' or 'csv'
try {
const expenses = await ExpenseModel.find({idGroup: groupId})
.populate("idUser")
.exec();
const refunds = await RefundModel.find({idGroup: groupId})
.populate("refunderId")
.populate("payerId")
.exec();
if (format === "pdf") {
const doc = new PDFDocument();
let buffers = [];
doc.on("data", buffers.push.bind(buffers));
doc.on("end", () => {
let pdfData = Buffer.concat(buffers);
res.contentType("application/pdf");
res.send(pdfData);
});
doc.fontSize(25).text("Récapitulatif des dépenses et remboursements", {
align: "center",
});
doc.fontSize(20).text("Dépenses :");
for (let expense of expenses) {
if (expense.idUser) {
doc
.fontSize(12)
.text(
`${expense.name} - ${expense.amount}€ par ${expense.idUser.firstname} ${expense.idUser.lastname}`,
);
} else {
doc
.fontSize(12)
.text(
`${expense.name} - ${expense.amount}€ par Utilisateur inconnu`,
);
}
}
doc.addPage().fontSize(20).text("Remboursements :");
for (let refund of refunds) {
if (refund.refunderId) {
doc
.fontSize(12)
.text(
`${refund.refunderId.firstname} ${refund.refunderId.lastname} a remboursé ${refund.amount}€ à ${refund.payerId.firstname} ${refund.payerId.lastname}`,
);
} else {
doc.fontSize(12).text(`Remboursement par Utilisateur inconnu`);
}
}
doc.end();
}
if (format === "csv") {
const expensesData = expenses.map((expense) => ({
name: expense.name,
amount: expense.amount,
user: expense.idUser
? `${expense.idUser.firstname} ${expense.idUser.lastname}`
: "Utilisateur inconnu",
}));
const refundsData = refunds.map((refund) => ({
receiver: refund.payerId,
refunder: refund.refunderId
? `${refund.refunderId.firstname} ${refund.refunderId.lastname}`
: "Utilisateur inconnu",
amount: refund.amount,
}));
const parser = new Parser();
const csvExpenses =
expensesData.length > 0 ? parser.parse(expensesData) : "";
const csvRefunds =
refundsData.length > 0 ? parser.parse(refundsData) : "";
res.header("Content-Type", "text/csv");
res.attachment("recapitulatif.csv");
res.send(csvExpenses + "\n\n" + csvRefunds);
}
} catch (error) {
console.error(error);
res.status(500).send("Erreur lors de la génération du récapitulatif");
}
});
export default groupRouter;
|
import os
import re
import gc
import pandas as pd
from tqdm import tqdm
import src.helper.directory_manager as dm
from src.helper.data_model import CSVHeader,HandWashingType
from src.helper.sampler import sample
from src.helper.logger import Logger as log
from src.utils.config_loader import config_loader as cl
from sklearn.preprocessing import RobustScaler, StandardScaler, MinMaxScaler
# Function to get params:
def read_params():
if cl.config.dataset.name == "features" or cl.config.dataset.name == "processed":
dtype={'relabeled': 'uint8'}
return None, dtype, None
else:
if cl.config.dataset.sensor == "both":
usecols=['datetime','acc x','acc y','acc z','gyro x','gyro y','gyro z','ignore','relabeled']
elif cl.config.dataset.sensor == "acc":
usecols=['datetime','acc x','acc y','acc z','ignore','relabeled']
elif cl.config.dataset.sensor == "gyro":
usecols=['datetime','gyro x','gyro y','gyro z','ignore','relabeled']
else:
log.warning("Invalid sensor type. Use 'both', 'acc' or 'gyro'.")
dtype={'relabeled': 'uint8','ignore':'uint8'}
parse_dates = ["datetime"]
if cl.config.dataset.name == "processed":
usecols.remove('ignore')
usecols.append('sub_id')
dtype.pop('ignore')
dtype['sub_id'] = 'uint8'
return usecols, dtype, parse_dates
# Read csv file
def read_csv_file(filename, chunksize=None, root=False):
# Path
if root:
path = filename
else:
path = os.path.join(dm.get_data_dir(), filename)
# Params
usecols, dtype, parse_dates = read_params()
try:
df = pd.read_csv(path, chunksize=chunksize, usecols=usecols,parse_dates=parse_dates, dtype=dtype)
return df
except FileNotFoundError:
log.error(f"Error: File '{filename}' not found.")
except pd.errors.EmptyDataError:
log.error(f"Error: File '{filename}' is empty.")
except pd.errors.ParserError:
log.error(f"Error: File '{filename}' is corrupted or has parsing issues.")
return pd.DataFrame()
# Clean data
def del_ignored_rows(df_data:pd.DataFrame):
if CSVHeader.IGNORE.value in df_data.columns.tolist():
filtered_df = df_data[df_data[CSVHeader.IGNORE.value] == 0]
return filtered_df
return df_data
# Get iterator of csv file reader.
def get_iterator(filename, chunksize=150):
path = os.path.join(dm.get_data_dir(),filename)
try:
df = pd.read_csv(filename, path)
#log.info("CSV file is readable.")
return df
except FileNotFoundError:
log.error(f"Error: File '{filename}' not found.")
return None
except pd.errors.EmptyDataError:
log.error(f"Error: File '{filename}' is empty.")
return None
except pd.errors.ParserError:
log.error(f"Error: File '{filename}' is corrupted or has parsing issues.")
return None
# Function to get the csv files of the selected subjects
def filter_by(subject:int, files:list):
selected_files = []
# Regex pattern
regex_pattern = r"OCDetect_(\d+)_"
log.info(f"Searching regex pattern: {regex_pattern}")
for file in files:
match = re.search(regex_pattern, file)
if match and int(match.group(1)) == subject:
selected_files.append(file)
return selected_files
# Function to print all rows of csv file
def print_rows(df_sensor, chunk=1000):
for i in range(0, len(df_sensor), chunk):
print(df_sensor.iloc[i:i+chunk])
# Functiont to calculate mean and var and quartiles
def save_to_csv(df_data, folder, file_name):
folder_path = dm.create_folder(folder, dm.FolderType.data)
# Output File path
file_path = os.path.join(folder_path, file_name)
log.info(f"Saving CSV File: {file_path}")
# Save the updated DataFrame to a new CSV file
try:
df_data.to_csv(file_path, sep=",", index=False)
log.info(f"DataFrame saved successfully to path: {file_path}.")
except Exception as e:
msg = "Error encountered while saving the dataframe: " + str(e)
log.critical(msg)
raise Exception(msg)
# release memory
del df_data
gc.collect()
# Function to get new header names from dataframe having rows and columns headers
def get_new_cols_header(df, column_first=True):
# Safety check
if df.empty:
log.warning("DataFrame is empty.")
return
# Get rows and cols headers
row = df.index if column_first else df.columns
cols = df.columns if column_first else df.index
new_header = []
# Loop through and create header
for row_header in row:
for col_header in cols:
new_col_name = f"{col_header}_{row_header}"
new_header.append(new_col_name)
return new_header
# Function to drop columns as required.
def drop_columns(df_data, columns_to_drop):
"""
Drop specified columns from a DataFrame.
Parameters:
df_data (pd.DataFrame): The DataFrame from which columns will be dropped.
columns_to_drop (str or list): A single column header name (str) or a list of column headers names to be dropped.
Returns:
pd.DataFrame: DataFrame with remaining columns.
"""
try:
# Convert columns_to_drop to a list if it's a single string
if isinstance(columns_to_drop, str):
columns_to_drop = [columns_to_drop]
# Drop the columns and return the modified DataFrame
return df_data.drop(columns=columns_to_drop, axis=1)
except KeyError as e:
# Handle the error when one or more columns are not found in the DataFrame
err = f"Error: One or more columns names not found in the DataFrame: {', '.join(e.args)}"
log.error(err)
except Exception as e:
# Handle other unexpected errors
log.error(f"An unexpected error occurred: {str(e)}")
# Return original dataframe in case of errors
return df_data
# Function to check data ratio
def is_imbalance(dataframe, class_column='relabeled', min_ratio=0.2, max_ratio=0.8):
"""
Function to check if the ratio of occurrence of each class data is within the specified range.
Args:
dataframe (pd.DataFrame): Input DataFrame containing class data.
class_column (str): Name of the column containing class labels.
min_ratio (float): Minimum acceptable ratio between classes.
max_ratio (float): Maximum acceptable ratio between classes.
Returns:
bool: True if the ratio of any class is outside the specified range, False otherwise.
"""
class_counts = dataframe[class_column].value_counts()
class_ratios = class_counts / class_counts.sum()
for ratio in class_ratios:
if ratio < min_ratio or ratio > max_ratio:
return True
return False
# Perform data loading from given csv file
def load_file(file_name:str, folder:str,normalized=True, norm_method='standard', features=[], sampling = True):
log.info(f"Loading CSV File: {file_name} from {folder}.")
# Read CSV file
df_data = read_csv_file(file_name, folder)
# Check for empty dataframe
if df_data.empty:
return df_data, df_data
# Check for NaN value
if df_data[features].isna().any().any() and features:
log.info(f"At least one NaN is found in {file_name}")
df_data = df_data.dropna()
# Remove ignored rows
df_data = del_ignored_rows(df_data)
#Create X, y for classifier
X_data = df_data[features] if features else df_data
y_data = df_data[CSVHeader.RELABELED.value]
# Normalize data
if normalized and len(X_data)>0:
X_data = normalize_data(X_data, norm_method)
# Check if data imbalanced
if is_imbalance and sampling:
#Apply sampling algorithm
X_data, y_data = sampler.sample(X_data, y_data)
# Check for NaN
if X_data.isna().any().any():
log.info(f"At least one NaN is found in {file_name}")
X_data = X_data.dropna()
log.info("---"*5)
return X_data, y_data
# Function to load all files from give list
def load_all_files(files, ignore_index=True, add_sub_id=False, root=False):
# Empty list
df_list = []
sub_id = int(files[0].rsplit( "_")[1])
for i in tqdm(range(0,len(files)), desc="Loading CSV Files:"):
temp = read_csv_file(files[i], root=root)
df_list.append(temp)
df = pd.concat(df_list, ignore_index=ignore_index)
if add_sub_id:
df["sub_id"] = sub_id
df["sub_id"] = df["sub_id"].astype("uint8")
log.info(f"{len(files)} csv files loaded successfully. DataFrame Length:{len(df)}")
return df
# # Perform data loading from given csv file
def load_data(subject:str, csv_files:[str], folder:str,normalized=True, norm_method='standard', features=[], sampling = True):
log.info(f"Loading CSV Files of subject {subject} from {folder}.")
X = pd.DataFrame()
y = pd.DataFrame()
for file in csv_files:
X_temp, y_temp = load_file(file, folder,normalized, norm_method, features, sampling)
X = pd.concat([X,X_temp])
y = pd.concat([y, y_temp])
return X, y
# Perform normalization of given dataframe
def normalize_data(X, method='standard', output_as_df=True):
if method == 'standard':
#log.info("Using Standard normalization.")
scaler = StandardScaler()
elif method == 'minmax':
#log.info("Using minmax normalization.")
scaler = MinMaxScaler()
else:
err = "Invalid normalization method. Use 'standard' or 'minmax'."
log.critical(err)
raise ValueError(err)
# Transform the DataFrame
normalized_data = scaler.fit_transform(X)
if output_as_df:
# Convert the normalized data back to a DataFrame
normalized_df = pd.DataFrame(normalized_data, columns=X.columns)
return normalized_df
return normalized_data
# Perform count
def count_labels(df):
# Header name
header = CSVHeader.RELABELED.value
# Safety check
if header not in df.columns:
return None
# Read the CSV file
cHW_count = len(df[df[header]==2])
rHW_count = len(df[df[header]==1])
other_count = len(df[df[header]==0])
# labels_counts = {
# HandWashingType.Compulsive.value:cHW_count,
# HandWashingType.Routine.value:rHW_count,
# HandWashingType.NoHandWash.value:other_count
# }
labels_counts = (other_count,rHW_count,cHW_count)
return labels_counts
# Load x y from dataframe
def load_x_y(df_data,normalized=True, norm_method='standard', features=[]):
if df_data.empty:
log.warning("DataFrame is Empty.")
if df_data['acc x'].isnull().values.any():
print("Dropping NaN")
df_data = df_data.dropna()
# filter
df_data = del_ignored_rows(df_data)
#Create X, y for classifier
x_data = df_data[features] if features else df_data
y_data = df_data[CSVHeader.RELABELED.value]
if normalized and len(x_data)>0:
x_norm = normalize_data(x_data, norm_method)
return x_norm, y_data
# Function to get label distribution
def get_labels_counts(grouped_csv_files,CSV_BLACK_LIST=[]):
#Subjects
subjects = sorted(grouped_csv_files.keys())
# Empty dict
labels_counts_by_subject = {}
# Loop and read csv files
print("=="*20)
print("| Subject | S.NO. | File | Ignored | rHW | cHW | Others | total |")
print("|---------|-------|------|---------|-----|-----|--------|-------|")
for index, subject in enumerate(subjects):
# Counts
rHW_count = 0
cHW_count = 0
other_count = 0
files_counts = []
files = sorted(grouped_csv_files[subject])
total = len(files)
# Loop over files
for index, file in enumerate(files):
if file in CSV_BLACK_LIST:
print(f"Skipping CSV file:{file}")
continue
# Read the CSV file
df = read_csv_file(file)
# Filtered ignored types
df_filtered = del_ignored_rows(df)
df_filtered_len = len(df_filtered)
ignored_total = len(df) - df_filtered_len
# Get labels counts without ignored types
counts = count_labels(df_filtered)
if counts:
# Get per file counts
per_file = {file:
{"cHW":counts[2],
"rHW":counts[1],
"NULL":counts[0],
"ignored":ignored_total
}
}
# Append per files
files_counts.append(per_file)
cHW_count += counts[2]
rHW_count += counts[1]
other_count += counts[0]
print(f"| {subject} | {index+1} | {file} | {ignored_total} | {counts[1]} | {counts[2]} | {counts[0]} | {df_filtered_len} |")
else:
CSV_BLACK_LIST.append(file)
print(f"File has been black listed {subject} : {file}")
# save counts in dict
labels_counts = {
"cHW":cHW_count,
"rHW":rHW_count,
"NULL":other_count,
"files":files_counts
}
#print(f"For subject {subject}: {labels_counts}")
labels_counts_by_subject[subject] = labels_counts
return labels_counts_by_subject
# Function to load all files from give list of subjects and grouped_files
def load_dfs_from(subjects, grouped_files, add_sub_id=False):
dataFrames = []
# Load all csv files:
for sub_id in subjects:
files = grouped_files[sub_id]
temp_df = load_all_files(files, add_sub_id=add_sub_id)
dataFrames.append(temp_df)
# Return concatenated dataframes
return pd.concat(dataFrames, ignore_index=True)
|
import os.path
import yaml
import logging
from typing import Union, Callable, List
import glob
import numpy as np
import glob
from dsautils import dsa_store
from lwautils import lwa_arx # arx
from lwa_antpos import mapping
from astropy.time import Time, TimeDelta
import time
from mnc import settings, common
logger = common.get_logger(__name__)
try:
from lwa_f import snap2_fengine, helpers, snap2_feng_etcd_client # fengine
except ImportError:
logger.warning('No f-eng library found. Skipping.')
try:
from lwa352_pipeline_control import Lwa352CorrelatorControl, BeamPointingControl # xengine
except ImportError:
logger.warning('No x-eng library found. Skipping.')
from mnc import mcs, xengine_beamformer_control
CONFIG_FILE = '/home/pipeline/proj/lwa-shell/mnc_python/config/lwa_config_calim.yaml'
FPG_FILE = '/home/pipeline/proj/lwa-shell/caltech-lwa/snap2_f_200msps_64i_4096c/outputs/snap2_f_200msps_64i_4096c.fpg'
CORE_RADIUS_M = 200.0
class Controller():
""" Parse configuration and control all subsystems in uniform manner.
Ideally, will also make it easy to monitor basic system status.
etcdhost is used by x-engine. data recorders use value set in mnc/common.py code.
Can overload default recorders by providing a list or single string name at instantiation.
"""
def __init__(self, config_file=CONFIG_FILE, etcdhost=None, xhosts=None, npipeline=None, recorders=None):
self.config_file = os.path.abspath(config_file)
conf = self.parse_config(config_file)
self.conf = conf
self.etcdhost = etcdhost
self.xhosts = xhosts
self.npipeline = npipeline
self.set_properties()
allowed = ['drvs', 'drvf'] + [f'dr{n}' for n in range(1,11)] + ['drt1'] # correct input recorder names
if recorders is not None:
if isinstance(recorders, str):
recorders = [recorders]
# clean input
disallowed = [recorder for recorder in recorders if recorder not in allowed]
if len(disallowed):
print(f'Removing unexpected recorder names: {disallowed}')
recorders = [recorder for recorder in recorders if recorder in allowed]
self.conf['dr']['recorders'] = recorders
# report
modes = []
if 'drvs' in self.conf['dr']['recorders']:
modes.append('slow')
if 'drvf' in self.conf['dr']['recorders']:
modes.append('fast')
if 'drt1' in self.conf['dr']['recorders']:
modes.append('teng')
for b in range(1, 11):
if f"dr{b}" in self.conf['dr']['recorders']:
modes.append(f"beam{b}")
logger.info(f"Loaded configuration for {self.nhosts} x-engine host(s) running {self.npipeline} pipeline(s) each")
logger.info(f"Supported recorder modes are: {','.join(modes)}")
if 'beam1' in modes or 'teng' in modes or 'beam2' in modes or 'beam3' in modes or 'beam4' in modes:
logger.info("\t Note: beams 1 and t-engine (VLBI/FRB), beam 2 (Solar), 3 (FRB), and 4 (Jovian) are reserved for specific science applications. Check with those teams before using them.")
logger.info(f"etcd server being used is: {self.etcdhost}")
@staticmethod
def parse_config(config_file):
""" Parse yaml format config_file and return dict
"""
with open(config_file, 'r') as fh:
conf = yaml.load(fh, Loader=yaml.CSafeLoader)
if 'fengines' not in conf:
raise RuntimeError('Config file missing "fengines" key')
if 'xengines' not in conf:
raise RuntimeError('Config file missing "xengines" key')
if 'arx' not in conf:
raise RuntimeError('Config file missing "arx" key')
if 'dr' not in conf:
raise RuntimeError('Config file missing "dr" key')
if 'etcd' not in conf:
raise RuntimeError('Config file missing "etcd" key')
return conf
def set_properties(self):
""" Set properties, then recalculate config properties.
"""
if self.etcdhost is None:
self.etcdhost = self.conf["etcd"]["host"]
# TODO: also use port?
if self.xhosts is None:
self.xhosts = self.conf["xengines"]["xhosts"]
self.nhosts = len(self.xhosts)
if self.npipeline is None:
self.npipeline = self.conf["xengines"]["nxpipeline"]
# select calim names/ips for selected xhosts
calim_name = [self.conf["xengines"]["x_dest_corr_name"][gpu_name] for gpu_name in self.xhosts]
drips = [self.conf["drip_mapping"][name] for name in calim_name]
self.x_dest_corr_ip = [item for item in drips for i in range(self.npipeline)]
self.x_dest_corr_slow_port = self.conf["xengines"]["x_dest_corr_slow_port"]
self.x_dest_corr_fast_port = self.conf["xengines"]["x_dest_corr_fast_port"]
# beamforming
self.x_dest_beam_ip = self.conf["xengines"]["x_dest_beam_ip"]
self.x_dest_beam_port = self.conf["xengines"]["x_dest_beam_port"]
# one p object controls all products on given subband
p = Lwa352CorrelatorControl(self.xhosts, npipeline_per_host=self.npipeline, etcdhost=self.etcdhost, log=logger.getChild('Lwa352CorrelatorControl'))
self.pcontroller = p
self.pipelines = p.pipelines
self.xhosts_up = sorted(set([p.host for p in self.pipelines]))
# data recorder control client
self.drvnums = [ip[-2:]+str(port)[-2:] for (ip, port) in zip(self.x_dest_corr_ip,
self.conf['xengines']['x_dest_corr_slow_port']*self.nhosts)]
self.drc = mcs.Client()
self.bfc = {}
def set_arx(self, preset=None):
""" Set ARX to preset config.
Defaults to preset in configuration file.
"""
aconf = self.conf['arx']
if preset is None:
preset = aconf['preset']
ma = lwa_arx.ARX() # TODO: update to use self.etcdhost
for adr in aconf['adrs']:
ma.load_cfg(adr, preset)
def start_fengine(self, snap2names=None, initialize=False, program=False, force=False, updatesettings=True):
""" Start the fengines on all snap2s.
snap2names argument allows a list of board names (e.g., ['snap02']), but defaults configuration file.
Optionally can initialize and program, which will also run cold_start method regardless of current state.
The config_file used should be available to the pipeline@lwacalimxx user (e.g., /home/pipeline/proj/lwa-shell/mnc_python/config/lwa...*yaml).
updatesettings will load the default settings file after initialization or programming.
"""
fconf = self.conf['fengines']
if snap2names is None:
snap2names = fconf['snap2s_inuse']
else:
raise NotImplementedError("Can't deal with a single snap2 yet. Rerun with snap2names=None to restart all boards.")
if not isinstance(snap2names, list):
snap2names = [snap2names]
ec = snap2_feng_etcd_client.Snap2FengineEtcdControl()
is_programmed = ec.send_command(0, 'fpga', 'is_programmed', n_response_expected=11)
if initialize or program:
if (not all(is_programmed.values()) or force) and program:
resp = ec.send_command(0, 'feng', 'program', timeout=90*11, n_response_expected=11, kwargs={'fpgfile': FPG_FILE})
if len(resp) < 11:
raise RuntimeError('program failed. Check fengine etcd service logs.')
for _ in range(3):
logger.info('Waiting 30s before checking if all snaps are programmed.')
time.sleep(30)
is_programmed = ec.send_command(0, 'fpga', 'is_programmed', n_response_expected=11)
if len(is_programmed) == 11 and all(is_programmed.values()):
break
resp = ec.send_command(0, 'feng', 'initialize', kwargs={'read_only':False}, timeout=90*11, n_response_expected=11)
if len(resp) < 11:
raise RuntimeError(f"F-engine failure. Responses are {resp}")
else:
logger.info('All snaps already programmed.')
for snap2name in snap2names:
print(f"Initializing board {snap2name}")
snap2num = int(snap2name.lstrip('snap'))
resp = ec.send_command(snap2num, 'feng', 'cold_start_from_config',
kwargs={'config_file': self.config_file, 'program': False, 'initialize': True},
timeout=90)
if resp is not None:
raise RuntimeError(f'cold_start_from_config failed for board {snap2name}. Check fengine etcd service logs.')
else:
if not all(is_programmed.values()):
logger.warn("Not all snaps are ready. \n Programmed: {is_programmed}.")
if updatesettings:
settings.update()
def status_fengine(self):
""" Use snap2 etcd client to poll for stats on each fengine.
"""
snap2names = self.conf['fengines']['snap2s_inuse']
stats = {}
ls = dsa_store.DsaStore()
for snap2name in snap2names:
snap2num = snap2name.lstrip('snap')
try:
dd = ls.get_dict(f'/mon/snap/{snap2num}')
except Exception as e:
raise e
if dd is not None:
stats[snap2name] = dd['stats']
timestamp = dd['timestamp']
else:
stats[snap2name] = None
timestamp = None
return timestamp, stats
def configure_xengine(self, recorders=None, calibratebeams=False, full=False, timeout=300, force=False):
""" Restart xengine. Configure pipelines to send data to recorders.
Recorders is list of recorders to configure output to. Defaults to those in config file.
Supported recorders are "drvs" (slow vis), "drvf" (fast vis), "dr[n]" (power beams), "drt1" (teng)
Option "full" will stop/start/clear pipelines/beamformer controllers.
force will apply beam calibration, even if already applied in x-engines.
timeout is for x-engine start_pipelines method.
"""
dconf = self.conf['dr']
if recorders is None:
recorders = dconf['recorders']
elif not isinstance(recorders, (list, tuple)):
recorders = [recorders,]
if full:
logger.info("Stopping/starting pipelines with 20s sleep")
# stop before starting
self.pcontroller.stop_pipelines()
self.stop_xengine()
self.start_xengine(timeout=timeout)
# Clear the beamformer state
self.bfc.clear()
logger.info(f'pipelines up? {self.pcontroller.pipelines_are_up()}')
if not self.pcontroller.pipelines_are_up():
logger.warning(f"Not all X-engine are up. Proceeding with {self.xhosts_up}.")
if calibratebeams:
cal_directory = self.conf['xengines']['cal_directory']
else:
cal_directory = '/pathshouldnotexist'
for recorder in recorders:
# skip vis recorders and assume dr1 sets appropriately for drt1
if recorder in ['drvs', 'drvf', 'drt1']:
continue
num = int(recorder[2:])
logger.info(f"Configuring x-engine for beam {num} on xhosts {self.xhosts_up}")
try:
self.bfc[num] = xengine_beamformer_control.create_and_calibrate(num, servers=self.xhosts_up,
nserver=len(self.xhosts_up),
npipeline_per_server=self.npipeline,
cal_directory=cal_directory,
etcdhost=self.etcdhost, force=force)
except KeyError:
logger.error("KeyError when creating beamformer control. Are data being sent from f to x-engines?")
logger.info(f"Done setting calibration gains for beam {num}")
# overload dest set by default
if self.conf['xengines']['x_dest_beam_port'] is not None:
addr = self.conf['xengines']['x_dest_beam_ip']
port = self.conf['xengines']['x_dest_beam_port']
self.bfc[num].set_beam_dest(addr=addr[num-1], port=port[num-1])
# slow
if 'drvs' in recorders or 'drvf' in recorders:
logger.warn('fast and slow vis are already configured by default. '
'If you changed data destination or antenna selection,'
'you need to restart the X-engine with full=True.')
def control_bf(self, num=1, coord=None, coordtype='celestial', targetname=None,
track=True, uvweight: Union[str, Callable[[float], float]]='core',
flag_ants: List[str]=[],
beam_gain=None, duration=0):
""" Point and track beamformers.
num refers to the beamformer number (1 through 8).
If track=True, target is treated as celestial coords or by target name
If track=False, target is treated as (az, el)
uvweight can be: 'core', 'natural' or a function (see xengine_beamformer_control.set_beam_weights)
flag_ants is a list of antennas (antnames, not corrnums) to exclude from beamformer.
beam_gain optionally specifies the amplitude scaling for the beam.
duration is time to track in seconds (0 means 12 hrs).
target can be:
- source name ('zenith', 'sun') or
- tuple of (ra, dec) in (hourangle, degrees).
- tuple of (az, el) in degrees, if track=False
"""
az, el, ra, dec = None, None, None, None
if coord is not None and coordtype is not None and targetname is None:
assert isinstance(coord, tuple)
if coordtype == 'azel':
az, el = coord
elif coordtype == 'celestial':
ra, dec = coord
elif targetname is None:
logger.warning("Coordinates not fully specified. Pointing at zenith.")
az = 0
el = 90
if num not in self.bfc:
msg = f"X-engine not configured for beam {num}"
logger.error(msg)
raise KeyError(msg)
if len(flag_ants):
flag_ants = [mapping.antname_to_correlator(antname) for antname in flag_ants]
if (callable(uvweight)):
assert uvweight.__code__.co_argcount == 1, "weight function must only take one argument"
self.bfc[num].set_beam_weighting(fnc=weight, flag_ants=flag_ants)
elif (uvweight == 'core'):
self.bfc[num].set_beam_weighting(fnc=_core_weight_func, flag_ants=flag_ants)
elif (uvweight == 'natural'):
self.bfc[num].set_beam_weighting(flag_ants=flag_ants)
else:
raise ValueError(f'Invalid value for weight {weight}')
if beam_gain:
self.bfc[num].set_beam_gain(beam_gain)
if targetname is not None:
self.bfc[num].set_beam_target(targetname)
elif ra is not None:
self.bfc[num].set_beam_target(ra, dec=dec)
elif az is not None:
self.bfc[num].set_beam_pointing(az, el)
if self.bfc[num].cal_set is False:
logger.info(f'beam {num} calibration not set')
# track
if track:
t = xengine_beamformer_control.BeamTracker(self.bfc[num], update_interval=self.conf['xengines']['update_interval'])
if targetname is not None:
t.track(targetname, duration=duration)
elif ra is not None:
t.track(ra, dec=dec, duration=duration)
else:
logging.info(f'Beam {num}: Not tracking for azel input')
else:
logging.info(f'Beam {num}: Not tracking')
def status_xengine(self):
""" Print X-engine status
"""
AGE_THRESHOLD_S = 10
fmt = '{:<16}{:<8}{:<14}{:<14}'
print(fmt.format("Pipeline id:", "alive", "capture_gbps", "corr_gbps"))
for pipeline in self.pipelines:
capture_status = pipeline.capture.get_bifrost_status()
corr_status = pipeline.corr.get_bifrost_status()
if capture_status is None:
raise RuntimeError("Failed to get X-engine capture block status.")
alive = (time.time() - corr_status['time'] < AGE_THRESHOLD_S)
print(fmt.format(f'{pipeline.host}:{pipeline.pipeline_id}',
str(bool(alive)),
f"{capture_status['gbps']:.1f}",
f"{corr_status['gbps']:.1f}"))
def start_xengine(self, timeout=300):
if self.pcontroller.pipelines_are_up():
msg = 'Pipelines are running. Please stop the xengine first.'
logger.error(msg)
raise RuntimeError(msg)
logger.info('Starting X-engine and configuring for visibilities.')
self.pcontroller.start_pipelines(timeout=timeout)
try:
self.pcontroller.configure_corr(dest_ip=self.x_dest_corr_ip, dest_port=self.x_dest_corr_slow_port) # iterates over all slow corr outputs
except KeyError:
msg = "KeyError when configuring correlator. Are data being sent from f to x-engines?"
logger.error(msg)
raise RuntimeError(msg)
xconf = self.conf['xengines']
fast_antnames = xconf.get('fast_vis_ants', [])
if len(fast_antnames):
logger.info("Selecting antennas for fast visibilities.")
elif len(fast_antnames) == 0:
logger.warning("No antennas selected for fast visibilities")
return
# Empty array for visibility selection indices
fast_vis_out = np.zeros([self.pcontroller.pipelines[0].corr_subsel.nvis_out, 2, 2], dtype=int)
# "LWA-007"-style antenna names for fast visibilities
fast_corrids = []
for antname in fast_antnames:
try:
fast_corrids += [mapping.antname_to_correlator(antname)]
except KeyError:
logger.error(f'Couldn\'t convert antenna {antname} to a correlator index')
logger.info('Continuing without this antenna')
# Construct list of all baselines (including autos) for antennas in the list
fast_vis_n = 0
for corridn_a, corrid_a in enumerate(fast_corrids):
for corridn_b, corrid_b in enumerate(fast_corrids[corridn_a:]):
# Add all 4 polarization products
fast_vis_out[fast_vis_n+0] = [[corrid_a, 0], [corrid_b, 0]]
fast_vis_out[fast_vis_n+1] = [[corrid_a, 0], [corrid_b, 1]]
fast_vis_out[fast_vis_n+2] = [[corrid_a, 1], [corrid_b, 1]]
fast_vis_out[fast_vis_n+3] = [[corrid_a, 1], [corrid_b, 0]]
fast_vis_n += 4
for i in range(self.npipeline*self.nhosts):
self.pcontroller.pipelines[i].corr_subsel.set_baseline_select(fast_vis_out)
self.pcontroller.pipelines[i].corr_output_part.set_destination(self.x_dest_corr_ip[i], self.x_dest_corr_fast_port[i%4])
def stop_xengine(self):
""" Stop xengines listed in configuration file.
"""
self.pcontroller.stop_pipelines()
time.sleep(20)
def start_dr(self, recorders=None, t0='now', duration=None, time_avg=1, teng_f1=None, teng_f2=None, f0=1, gain1=1, gain2=1):
""" Start data recorders listed recorders.
Defaults to starting those listed in configuration file.
Recorder list can be overloaded with 'drvs' (etc) or individual recorders (e.g., 'drvs7601').
t0 is either 'now' or a start time (astropy Time, mjd float, and isot strings supported).
duration is length of data recording in milliseconds (required for power beam recording; optional for visibilities).
time_avg is power beam averaging time in milliseconds (integer converted to next lower power of 2).
teng_f1/2 are the central frequencies of t-engine tunings in units of Hz.
f0 sets bandwidth as integer from 1 (250kHz) to 7 (19.6MHz).
gain1/2 are gains on beamformers.
"""
dconf = self.conf['dr']
if recorders is None:
recorders = dconf['recorders']
elif not isinstance(recorders, (list, tuple)):
recorders = [recorders,]
# set start time arguments
if isinstance(t0, str) and t0 == 'now':
mjd = mpm = t0
start = Time.now()
else:
if not isinstance(t0, Time):
try:
start = Time(t0, format='isot')
except ValueError:
start = Time(t0, format='mjd')
else:
start = t0
mjd_dt = start.mjd % 1
mjd = int((start - TimeDelta(mjd_dt, format='jd')).mjd)
mpm = int(mjd_dt * 24 * 3600 * 1e3)
# start ms writing
logger.info(f"Starting recorders {recorders} at {start.mjd} (currently {Time.now().mjd})")
for recorder in recorders:
accepted = False
# power beams
if recorder in [f'dr{n}' for n in range(1,11)]:
if duration is not None:
assert isinstance(time_avg, int)
time_avg = 2 ** int(np.log2(time_avg)) # set to next lower power of 2
accepted, response = self.drc.send_command(recorder, 'record', start_mjd=mjd,
start_mpm=mpm, duration_ms=duration,
time_avg=time_avg)
else:
logger.warn("Power beam recordings require a duration")
elif recorder in [f'drt{n}' for n in range(1,3)]:
assert teng_f1 is not None and teng_f2 is not None, "Need to set teng_f1, teng_f2 frequencies"
assert teng_f1 < 196e6/2 and teng_f2 < 196e6/2, "t-engine tuning frequency too high."
assert (f0 > 0) and (f0 < 8), "f0 (filter number) should be from 1-7 (inclusive)"
if duration is not None:
assert time_avg in [None, 0, 1], "No time averaging can be done for t-engine"
beam = int(recorder[3:])
# central_freq defined in units of 196e9/2**32 OR NOT?
# teng_f1n = int(teng_f1/(196e6/2**32))
# teng_f2n = int(teng_f2/(196e6/2**32))
gain = 1 # TODO: decide if gain needs to be tunable
accepted1, response = self.drc.send_command(f"drt{beam}", "drx", beam=beam, tuning=1,
central_freq=teng_f1, filter=f0, gain=gain1)
if accepted1:
accepted2, response = self.drc.send_command(f"drt{beam}", "drx", beam=beam, tuning=2,
central_freq=teng_f2, filter=f0, gain=gain2)
if accepted1 and accepted2:
accepted, response = self.drc.send_command(recorder, 'record', start_mjd=mjd, beam=beam,
start_mpm=mpm, duration_ms=duration)
else:
logger.warn("tengine tuning command(s) not successful. Not starting data recorder.")
elif recorder in ["drvs", "drvf"] + ["drvs" + num for num in self.drvnums]:
accepted, response = self.drc.send_command(recorder, "start", mjd=mjd, mpm=mpm)
if duration is not None:
if response["status"] != "success":
logger.warn("Data recorder not started successfully. Trying to schedule stop...")
stop = start + TimeDelta(duration/1e3/24/3600, format="jd")
self.stop_dr(recorders=recorder, t0=stop)
else:
print(f"recorder name {recorder} not recognized.")
accepted = False
if not accepted:
logger.warn(f"no response from {recorder}")
elif response['status'] == 'success':
rec_extra_info = ''
try:
rec_extra_info = f" for {duration/1000.0:.3f} s and {time_avg} ms averaging to file {response['response']['filename']}"
except (KeyError, TypeError):
pass
logger.info(f"recording on {recorder}{rec_extra_info}")
else:
logger.warn(f"recording on {recorder} failed: {response['response']}")
if self.drc.read_monitor_point('summary', recorder).value != 'normal':
self.drc.read_monitor_point('info', recorder)
def status_dr(self, recorders=None):
""" Print data recorder info monitor point
"""
dconf = self.conf['dr']
if recorders is None:
recorders = dconf['recorders']
elif not isinstance(recorders, (list, tuple)):
recorders = [recorders,]
# start ms writing
statuses = []
for recorder in recorders:
statuses.append(self.drc.read_monitor_point('op-type', recorder).value)
if self.drc.read_monitor_point('summary', recorder).value != 'normal':
statuses.append(f"WARNING: {recorder} not fully operational: {self.drc.read_monitor_point('info', recorder).value}")
return statuses
def stop_dr(self, recorders=None, t0='now', queue_number=0):
""" Stop data recorders in list recorders.
Defaults to stopping those listed in configuration file.
t0 is stop time (astropy Time object, mjd, or isot format supported).
queue_number is index of queued beamformer observations (default stops most recent == 0).
"""
dconf = self.conf['dr']
if not recorders:
recorders = dconf['recorders']
elif not isinstance(recorders, (list, tuple)):
recorders = [recorders,]
# set start time arguments
if isinstance(t0, str):
assert t0 == 'now'
mjd = mpm = t0
start = Time.now()
else:
if not isinstance(t0, Time):
try:
start = Time(t0, format='isot')
except ValueError:
start = Time(t0, format='mjd')
else:
start = t0
mjd_dt = start.mjd % 1
mjd = int((start - TimeDelta(mjd_dt, format='jd')).mjd)
mpm = int(mjd_dt * 24 * 3600 * 1e3)
for recorder in recorders:
if recorder in ['drvs', 'drvf']:
accepted, response = self.drc.send_command(recorder, 'stop', mjd=mjd, mpm=mpm)
else:
accepted, response = self.drc.send_command(recorder, 'cancel', queue_number=queue_number)
if not accepted:
logger.warn(f"no response from {recorder}")
elif response['status'] == 'success':
logger.info(f"recording on {recorder} stopped")
else:
logger.warn(f"stopping recording on {recorder} failed: {response['response']}")
def _core_weight_func(r: float) -> float:
return 1.0 if r < CORE_RADIUS_M else 0.0
def _single_ant_flags_list(antname: str) -> List[int]:
flag_list = list(range(352))
flag_list.remove(mapping.antname_to_correlator(antname))
return flag_list
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.