text
stringlengths
184
4.48M
<template> <v-dialog v-model="dialog" max-width="350"> <template v-slot:activator="{ on }"> <v-list-item v-on="on" @click="readComment"> 수정 </v-list-item> </template> <v-card color="basil"> <v-text-field v-model="content" class="px-3"></v-text-field> <v-card-text></v-card-text> <v-card-actions> <v-btn @click="btnCancle" text > Cancle </v-btn> <v-spacer></v-spacer> <v-btn @click="modifyComment" text> Modify </v-btn> </v-card-actions> </v-card> </v-dialog> </template> <script> import axios from 'axios' import { mapActions, mapState } from 'vuex' export default { name: 'CommentModifyForm', props: { commentNo: { }, qnaNo: { } }, data () { return { dialog: false, content: null } }, computed: { ...mapState([ 'comments', 'comment' ]) }, mounted () { this.fetchComment(this.commentNo) }, methods: { ...mapActions([ 'fetchComment', 'fetchComments' ]), btnCancle () { this.dialog = false }, modifyComment () { const content = this.content axios.patch(`http://localhost:7777/comment/modify/${this.commentNo}`, { content }) .then(() => { alert('수정이 완료되었습니다') this.fetchComments(this.qnaNo) this.dialog = false }) }, readComment () { this.fetchComment(this.commentNo) this.content = this.comment.content } } } </script>
import React, { Component } from 'react'; import Person from '../components/Person/Person'; import AddPerson from '../components/AddPerson/AddPerson'; import {connect} from 'react-redux'; import * as actionTypes from '../store/actions'; class Persons extends Component { // state = { // persons: [] // } // personAddedHandler = () => { // const newPerson = { // id: Math.random(), // not really unique but good enough here! // name: 'Max', // age: Math.floor( Math.random() * 40 ) // } // this.setState( ( prevState ) => { // return { persons: prevState.persons.concat(newPerson)} // } ); // } // personDeletedHandler = (personId) => { // this.setState( ( prevState ) => { // return { persons: prevState.persons.filter(person => person.id !== personId)} // } ); // } render () { return ( <div> <AddPerson personAdded={this.props.personAddedHandler} /> {this.props.persons.map(person => ( <Person key={person.id} name={person.name} age={person.age} clicked={() => this.props.personDeletedHandler(person.id)}/> ))} </div> ); } } const mapProps=state=>{ return { persons:state.persons } } const mapActions=dispatch=>{ return{ personAddedHandler:(name,age)=>dispatch({type:actionTypes.ADD_PERSON,person:{name:name,age:age}}), personDeletedHandler:(id)=>dispatch({type:actionTypes.DELETE_PERSON,id:id}) } } export default connect(mapProps,mapActions)(Persons);
using UnityEngine; public abstract class Bullet : MonoBehaviour { [Header("Player References")] [SerializeField] protected Player_Stats m_playerStatsCS; [Header("Bullet Settings")] [SerializeField] protected int m_bulletDamage; [SerializeField] protected float m_bulletSpeed; [SerializeField] protected bool m_lifeTimeDestroy; [SerializeField] protected float m_bulletLifeTime; [SerializeField] protected bool m_doesSlow; protected float m_despawnTimer; [Space(20)] [Header(" ----- Bullet ImpactVFX Settings -----")] [SerializeField] protected string m_impactSFX; [Space(5)] [SerializeField] protected bool m_hasImpactVFX; [SerializeField] protected GameObject m_bulletImpactVFX; [Space(20)] [SerializeField] protected Rigidbody2D m_bulletRB; [SerializeField] protected Transform m_bulletTF; protected virtual void Start() { LaunchBullet(); } protected virtual void Update() { if (m_lifeTimeDestroy) { CountBulletLifetimeDestroy(); } } protected virtual void CountBulletLifetimeDestroy() { m_despawnTimer += Time.deltaTime; if (m_despawnTimer >= m_bulletLifeTime) { m_despawnTimer = 0; Destroy(gameObject); } } protected virtual void LaunchBullet() { m_bulletRB.velocity = (m_bulletTF.position - InputManager.I.GetWorldMousePosition()) * -m_bulletSpeed; } protected void OnCollisionEnter2D(Collision2D collision) { if(!collision.collider.CompareTag("Player_Collider")) Impact(collision.collider); } protected virtual void Impact(Collider2D _otherCollider) { Health health = _otherCollider.GetComponent<Health>(); if (health != null) { health.TakeDamage(m_bulletDamage); //if(_otherCollider.CompareTag("Enemy") && m_doesSlow) //{ // health.Slow(); //} } if (m_hasImpactVFX) PlayImpactVFX(); //TODO: Add ImpactSFX //AudioManager.I.Play(m_impactSFX); Destroy(gameObject); } protected virtual void PlayImpactVFX() { if(!m_bulletImpactVFX) return; float vfxOffsetFromWall = 0.1f; var obj = Instantiate(m_bulletImpactVFX, m_bulletTF.position, m_bulletTF.rotation); Transform objTF = obj.transform; // Player position for direction to player Vector3 playerDir = GameManager.I.GetPlayerTransform().position - objTF.position; objTF.position += playerDir * vfxOffsetFromWall; } public virtual void SetOwner(Player_Stats _playerStatsCS) { m_playerStatsCS = _playerStatsCS; } }
import React, { useMemo, useState } from "react" import NavBar from "./ui/navBar" import Help from "./ui/help" import FooterSlider from "./ui/footer-slider" import Leaderboard from "./ui/leaderboard" import Standings from "./ui/standings" import Options from "./ui/options" import Stats from "./ui/stats" import { f1Main, content, } from "../../styles/component/f1/container.module.scss" import { generateAverageTable, orderAverageTable, calcData, orderLeaderboards, calcLeaderboardRdDiffs, generateEntrantDiffTotals, orderEntrantDiffTotals, filteredPlayers, getControPlayers, countPlayerEntries, } from "./calc" import { Entrant, Players, Round } from "./classes" export default function F1Container(props: { drivers: { [key: string]: Entrant } finalNoOfRaces: number helpNotes: JSX.Element playerGroupsArr: string[] players: Players rounds: Round[] statsNotes: (isSeasonOver: boolean) => JSX.Element teams: { [key: string]: Entrant } year: number }) { //State const [entrantType, setEntrantType] = useState("driver") const [playerGroup, setPlayerGroup] = useState(props.playerGroupsArr[0]) const [selectedRound, setSelectedRound] = useState(props.rounds.length - 1) const [mode, setMode] = useState("leaderboard") const [isSeasonOver, setIsSeasonOver] = useState( props.rounds.length === props.finalNoOfRaces ) //Handlers function changeEntrantTypeHandler(newEntrantType: string) { setEntrantType(newEntrantType) } function changePlayerGroupHandler(playerGroup: string) { setPlayerGroup(playerGroup) } function changeRoundHandler(newRoundNo: number) { setSelectedRound(newRoundNo) setIsSeasonOver(newRoundNo + 1 === props.finalNoOfRaces) } function changeModeHandler(newMode: string) { setMode(newMode) } const data = useMemo(() => { let { teams, drivers, rounds, players } = props //Populate players.average with prediction tables created by finding the mean positions of everyone else's predictions players = generateAverageTable(players, drivers, "driver") players = generateAverageTable(players, teams, "team") //Order the prediction tables in players.average players = orderAverageTable(players, "driver") players = orderAverageTable(players, "team") //Based on the player predictions and round data, calculate the differences in entrant predictions for each player, their diff totals and their count of each diffs calcData(players, rounds) //The leadboards have been generated, but aren't in the correct order so this function will order players based on performance orderLeaderboards(rounds, "driver") orderLeaderboards(rounds, "team") //Calculate how players have moved on the leaderboards compared to the previous round calcLeaderboardRdDiffs(rounds, "driver") calcLeaderboardRdDiffs(rounds, "team") //Tally up how accurate each player has been generateEntrantDiffTotals(rounds, players, "driver", drivers) generateEntrantDiffTotals(rounds, players, "team", teams) //Order the players in each round by their percentage correct, highest first orderEntrantDiffTotals(rounds, "driver") orderEntrantDiffTotals(rounds, "team") return { teams: teams, drivers: drivers, rounds: rounds, players: players } }, [props]) const controDriverPredictions = getControPlayers(data.players, "driver") const controTeamPredictions = getControPlayers(data.players, "team") const noOfPredictions = { driver: countPlayerEntries(data.players, "driver"), team: countPlayerEntries(data.players, "team"), } return ( <div className={f1Main}> <NavBar changeMode={changeModeHandler} activeMode={mode} /> <div className={content}> {mode === "leaderboard" || mode === "standings" ? ( <Options mode={mode} playerGroupsArr={props.playerGroupsArr} changePlayerGroup={changePlayerGroupHandler} changeEntrantType={changeEntrantTypeHandler} /> ) : ( "" )} {mode === "leaderboard" && ( <Leaderboard entrantType={entrantType} roundNo={selectedRound} roundData={data.rounds} /> )} {mode === "standings" && ( <Standings year={props.year} roundData={data.rounds} entrantType={entrantType} roundNo={selectedRound} filteredPlayers={filteredPlayers( data.players, playerGroup, entrantType )} /> )} {mode === "help" && <Help year={props.year}>{props.helpNotes}</Help>} {mode === "stats" && ( <Stats roundData={data.rounds} selectedRound={selectedRound} isSeasonOver={isSeasonOver} controDriverPredictions={controDriverPredictions} controTeamPredictions={controTeamPredictions} noOfPredictions={noOfPredictions} > {props.statsNotes(isSeasonOver)} </Stats> )} </div> { //If not in help mode, display the footer slider mode !== "help" && ( <FooterSlider selectedRound={selectedRound} noOfRounds={data.rounds.length} trackName={data.rounds[selectedRound].trackName} changeRound={changeRoundHandler} /> ) } </div> ) }
// // PostTableViewCell.swift // osek_revival // // Created by Исмаил Орумбеков on 07.05.2024. // import Foundation import UIKit class PostTableViewCell: UITableViewCell{ static let identifier = "PostTableViewCell" var isConfigured = false var currentEmail = "" var onAuthorPressed: (() -> Void)? private var authorView: AuthorView = { let view = AuthorView() view.isUserInteractionEnabled = true view.configure(authorNickName: "author", authorImage: nil) return view }() private lazy var spaceView: UIView = { let view = UIView() view.backgroundColor = .black return view }() private lazy var customContentView: UIView = { let view = UIView() view.backgroundColor = Resources.Colors.passiveBackgroundColor view.layer.cornerRadius = 10 return view }() private lazy var titleLabel: UILabel = { let label = UILabel() label.font = .systemFont(ofSize: 20, weight: .bold) label.textAlignment = .left label.numberOfLines = 0 label.textColor = .white return label }() private lazy var postImageView: UIImageView = { let imageView = UIImageView() imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFill return imageView }() private lazy var descriptionLabel: UILabel = { let label = UILabel() label.font = .systemFont(ofSize: 18) label.textAlignment = .left label.textColor = .white label.numberOfLines = 3 label.text = "fsdlfgknsfgnje ewkrjgnwke jbgwek jbrgklew bkgb ewkrjb gkwerbjgenrw nlwekjr " return label }() private lazy var interactionStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.spacing = 10 stackView.alignment = .center stackView.distribution = .equalSpacing return stackView }() private lazy var likeButton: UIButton = { let button = UIButton() button.tintColor = .white button.backgroundColor = Resources.Colors.passiveColor button.layer.cornerRadius = 25 button.setImage(UIImage(systemName: "heart"), for: .normal) return button }() private lazy var commentButton: UIButton = { let button = UIButton() button.tintColor = .white button.backgroundColor = Resources.Colors.passiveColor button.layer.cornerRadius = 25 button.setImage(UIImage(systemName: "message"), for: .normal) return button }() private lazy var repostButton: UIButton = { let button = UIButton() button.tintColor = .white button.backgroundColor = Resources.Colors.passiveColor button.layer.cornerRadius = 25 button.setImage(UIImage(systemName: "arrowshape.turn.up.right"), for: .normal) return button }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(viewModel: PostViewModel){ let description: String = viewModel.description ?? "" currentEmail = viewModel.author.email titleLabel.text = viewModel.title descriptionLabel.text = description authorView.setTitle(nickName: viewModel.author.nickName) guard !isConfigured else {return} isConfigured = true if let data = viewModel.postImageData{ postImageView.image = UIImage(data: data) }else if let url = viewModel.postImageURL{ let task = URLSession.shared.dataTask(with: url) {[weak self] data, _, _ in guard let data = data else{return} viewModel.postImageData = data DispatchQueue.main.async { self?.postImageView.image = UIImage(data: data) } } task.resume() } } } extension PostTableViewCell{ func setupUI() { addViews() setUpConstraints() configure() } func addViews() { contentView.addSubview(customContentView) customContentView.addSubview(authorView) customContentView.addSubview(postImageView) customContentView.addSubview(titleLabel) customContentView.addSubview(descriptionLabel) customContentView.addSubview(interactionStackView) interactionStackView.addArrangedSubview(likeButton) interactionStackView.addArrangedSubview(commentButton) interactionStackView.addArrangedSubview(repostButton) contentView.addSubview(spaceView) } func setUpConstraints() { customContentView.snp.makeConstraints { make in make.top.equalToSuperview() make.leading.equalToSuperview() make.trailing.equalToSuperview() make.bottom.equalToSuperview().offset(-10) } spaceView.snp.makeConstraints { make in make.width.equalToSuperview() make.bottom.equalToSuperview() make.height.equalTo(10) } authorView.snp.makeConstraints { make in make.top.equalToSuperview().offset(5) make.height.equalTo(60) make.leading.equalToSuperview().offset(10) make.trailing.equalToSuperview().offset(-10) } titleLabel.snp.makeConstraints { make in make.top.equalTo(authorView.snp.bottom).offset(20) make.leading.equalToSuperview().offset(10) make.trailing.equalToSuperview().offset(-10) make.height.lessThanOrEqualTo(60) } postImageView.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(15) make.width.equalToSuperview() make.height.equalToSuperview().multipliedBy(0.55) make.centerX.equalToSuperview() } descriptionLabel.snp.makeConstraints { make in make.leading.equalTo(titleLabel.snp.leading) make.trailing.equalTo(titleLabel.snp.trailing) make.top.equalTo(postImageView.snp.bottom).offset(15) make.centerX.equalToSuperview() make.height.lessThanOrEqualTo(45) } interactionStackView.snp.makeConstraints { make in make.width.equalToSuperview().multipliedBy(0.5) make.height.equalTo(50) make.top.equalTo(descriptionLabel.snp.bottom).offset(10) make.leading.equalTo(descriptionLabel.snp.leading) } likeButton.snp.makeConstraints { make in make.width.height.equalTo(50) } commentButton.snp.makeConstraints { make in make.width.height.equalTo(50) } repostButton.snp.makeConstraints { make in make.width.height.equalTo(50) } } func configure(){ contentView.backgroundColor = UIColor.clear backgroundColor = UIColor.clear contentView.frame = contentView.frame.inset(by: UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 0)) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(authorViewTapped)) authorView.addGestureRecognizer(tapGesture) } } @objc extension PostTableViewCell{ func authorViewTapped(){ guard let authorPessed = onAuthorPressed else{return} authorPessed() } }
import React, { useState } from 'react'; import axios from 'axios'; const InputForm = () => { const [formData, setFormData] = useState({ cc_num: '', merchant: '', amt: '', sender_ip: '', merch_ip: '' }); const [prediction, setPrediction] = useState(null); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; const handleSubmit = (e) => { e.preventDefault(); console.log(formData); axios.post('http://127.0.0.1:5000/predict', new URLSearchParams(formData)) .then(response => { console.log(response.data); setPrediction(response.data); }) .catch(error => { console.error('Error making API request:', error); }); }; const formStyle = { width: '50%', margin: 'auto', marginTop: '50px', textAlign: 'center', padding: '20px', boxShadow: '0 0 10px rgba(0, 0, 0, 0.1)', borderRadius: '5px' }; const inputStyle = { width: '100%', padding: '10px', marginBottom: '10px', borderRadius: '5px', border: '1px solid #ccc', boxSizing: 'border-box', fontSize: '14px' }; const buttonStyle = { width: '100%', backgroundColor: '#4CAF50', color: 'white', padding: '10px 15px', borderRadius: '5px', border: 'none', cursor: 'pointer', fontSize: '16px' }; const resultStyle = { marginTop: '20px' }; const getResultMessage = () => { const numericPrediction = parseInt(prediction, 10); return numericPrediction === 0 ? "Valid Transaction" : "Fraud Transaction"; }; return ( <div style={formStyle}> <form onSubmit={handleSubmit}> <div> <input type="text" name="cc_num" style={inputStyle} placeholder="Credit Card Number" required onChange={handleChange} /> </div> <div> <input type="text" name="merchant" style={inputStyle} placeholder="Merchant" required onChange={handleChange} /> </div> <div> <input type="text" name="amt" placeholder="Amount" style={inputStyle} required onChange={handleChange} /> </div> <div> <input type="text" name="sender_ip" placeholder="sender ip" style={inputStyle} required onChange={handleChange} /> </div> <div> <input type="text" name="merch_ip" placeholder="merchant ip" style={inputStyle} required onChange={handleChange} /> </div> <button type="submit" style={buttonStyle}>Predict</button> </form> {prediction !== null && ( <div style={resultStyle}> <h2>Prediction Result</h2> <p>Prediction: {getResultMessage()}</p> </div> )} </div> ); }; export default InputForm;
import { useEffect } from "react" import { useMemo } from "react" import { useDispatch, useSelector } from "react-redux" import { NavLink, useLocation, useNavigate } from "react-router-dom" import { changeExamMode } from "../../store/examMode" import request from "../../utils/request" import { Btn } from "./styled" export const Button = (props) => { // // const dispatch = useDispatch() const navigator = useNavigate() const location = useLocation() const { text, height, long, background, socket, answerSubmit, setSubmit, fontsize } = props // // const NAV = ({ text, socket }) => { const path = text.toLowerCase().replace(" ", "") const { kind, list: naviList } = useSelector((state) => state.mode) let currentCommand = useMemo(() => location.pathname.slice(1).split("/")[2]) const { userId } = useSelector((state) => state.user.data) const handleBtn = (e) => { if (currentCommand.indexOf("%20") !== -1) { currentCommand = currentCommand.replace("%20", " ") } const cases = e.target.innerHTML const includesArray = naviList .map((v) => v.command) .find((array) => array.some((obj) => obj.command === currentCommand)) .map((v) => v.command) const presentIndex = includesArray.indexOf(currentCommand) if (cases === "Next" || cases === "Next Level") { setSubmit && setSubmit(false) const nextCommand = includesArray[presentIndex + 1] if (nextCommand) navigator(`/quiz/${kind}/${nextCommand}`) } else if (cases === "Prev") { const prevCommand = includesArray[presentIndex - 1] if (prevCommand) navigator(`/quiz/${kind}/${prevCommand}`) } } const handleSocket = () => { kind === "linux" ? socket.emit("send", "clear") : socket.emit("send", "system clear") } const handleExam = () => { dispatch(changeExamMode()) handleSocket() } const handleClose = () => { navigator("/") } const hadleSubmit = async () => { const { answer, setSubmit } = answerSubmit if (answer) { const response = await request.post("/quiz/exam", { userId, command: currentCommand, answer }) const { data } = response.data if (data === true) { data && setSubmit(true) } else if (data === false) { alert("오답입니다. 다시 시도하여 주세요!") } else { alert(data) } } } switch (text) { case "Exam": return ( <div className="NLink" onClick={handleExam}> {text} </div> ) case "Submit": return ( <div className="NLink" onClick={hadleSubmit}> {text} </div> ) case "Prev": case "Next": case "Next Level": return ( <div className="NLink" onClick={handleBtn}> {text} </div> ) case "Clear": return ( <div className="NLink" onClick={handleSocket}> {text} </div> ) case "닫기": return ( <div className="NLink" onClick={handleClose}> {text} </div> ) case "Free Terminal": return <NavLink to={`/quiz/${kind}/${path}`}>{text}</NavLink> case "등록": return ( <div className="NLink" onClick={answerSubmit}> {text} </div> ) default: return <NavLink to={path}>{text}</NavLink> } } return ( <> <Btn height={height} long={long} background={background} fontsize={fontsize}> <NAV text={text} answerSubmit={answerSubmit} socket={socket} /> </Btn> </> ) }
import 'dart:io'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:chatapp/widgets/auth/auth_form.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class AuthScreen extends StatefulWidget { const AuthScreen({super.key}); @override State<AuthScreen> createState() => _AuthScreenState(); } class _AuthScreenState extends State<AuthScreen> { final _auth = FirebaseAuth.instance; var _isLoading = false; _submitAuthForm( String email, String password, String username, // File image, bool isLogin, BuildContext ctx,) async { UserCredential authResult; try { setState(() { _isLoading = true; }); if (isLogin) { authResult = await _auth.signInWithEmailAndPassword( email: email, password: password, ); } else { authResult = await _auth.createUserWithEmailAndPassword( email: email, password: password, ); // final ref = FirebaseStorage.instance // .ref() // .child('user_image') // .child(authResult.user!.uid + '.jpg'); // // await ref.putFile(image); // // final url = await ref.getDownloadURL(); await FirebaseFirestore.instance .collection('users') .doc(authResult.user!.uid) .set({ 'username': username, 'email': email, //'image_url': url, }); } } on PlatformException catch (err) { String? message = 'An error occurred, please check your credentials!'; if (err.message != null) { message = err.message; } ScaffoldMessenger.of(ctx).showSnackBar( SnackBar( content: Text(message!), backgroundColor: Theme .of(ctx) .errorColor, ), ); setState(() { _isLoading = false; }); } catch (err) { print(err); setState(() { _isLoading = false; }); } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme .of(context) .primaryColor, body: AuthForm( _submitAuthForm, _isLoading, ), ); } }
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordResetForm from django.contrib.auth.models import User from blogs.models import Profile from django import forms class SignUpForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' class EditProfileForm(UserChangeForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) is_superuser = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check', 'disabled': True})) is_staff = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check', 'disabled': True})) is_active = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check', 'disabled': True})) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'is_superuser', 'is_staff', 'is_active', ] class AddBioForm(forms.ModelForm): class Meta: model = Profile fields = ['bio', 'profile_image', 'website_url', 'facebook_url', 'instagram_url', 'linkedin_url'] widgets = { 'bio': forms.Textarea(attrs={'class': 'form-control'}), 'website_url': forms.TextInput(attrs={'class': 'form-control'}), 'facebook_url': forms.TextInput(attrs={'class': 'form-control'}), 'instagram_url': forms.TextInput(attrs={'class': 'form-control'}), 'linkedin_url': forms.TextInput(attrs={'class': 'form-control'}), } class EditBioForm(forms.ModelForm): class Meta: model = Profile fields = ['bio', 'profile_image', 'website_url', 'facebook_url', 'instagram_url', 'linkedin_url'] widgets = { 'bio': forms.Textarea(attrs={'class': 'form-control'}), 'website_url': forms.TextInput(attrs={'class': 'form-control'}), 'facebook_url': forms.TextInput(attrs={'class': 'form-control'}), 'instagram_url': forms.TextInput(attrs={'class': 'form-control'}), 'linkedin_url': forms.TextInput(attrs={'class': 'form-control'}), }
import axios from "axios"; export interface DataType { key: React.Key; ID: number; Address?: string; Company?: string; OrderSummary?: string; Orderer?: string; contact?: string; StartDate?: string; Status?: string; EndDate?: string; } export const data = async (): Promise<DataType[]> => { const response = await axios.get<DataType[]>("/dashboard/workorder"); const newData: DataType[] = response.data.map((item) => ({ ...item, key: item.ID, StartDate: formatDate(item.StartDate), EndDate: formatDate(item.EndDate), })); return newData; }; function formatDate(dateString: string | null) { if (!dateString) { return null; } const date = new Date(dateString); const year = date.getFullYear(); const month = ("0" + (date.getMonth() + 1)).slice(-2); const day = ("0" + date.getDate()).slice(-2); return `${year}-${month}-${day}`; }
import React from 'react' import Head from 'next/head' import { CustomHeadProps } from '@/lib/components/shared/custom-head/custom-head.types' const CustomHead = ({ title, description, keywords, author, }: CustomHeadProps) => { return ( <Head> <title>{title}</title> {description && <meta name="description" content={description} />} {keywords && <meta name="keywords" content={keywords} />} {author && <meta name="author" content={author} />} <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.ico" /> </Head> ) } export default CustomHead
FontUtils.java Class: font-related utility methods. // PACKAGE package uk.blankaspect.ui.jfx.font; //---------------------------------------------------------------------- // IMPORTS import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; //---------------------------------------------------------------------- // CLASS: FONT-RELATED UTILITY METHODS /** * This class contains utility methods that relate to JavaFX {@linkplain Font fonts}. */ public class FontUtils { // Constructors /** * Prevents this class from being instantiated externally. */ private FontUtils() { } //------------------------------------------------------------------ // Class methods /** * Returns the size of the default JavaFX font. * * @return the size of the default JavaFX font. */ public static double getDefaultSize() { return Font.getDefault().getSize(); } //------------------------------------------------------------------ /** * Returns the size of the default JavaFX font multiplied by the specified factor. * * @param factor * the factor by which the size of the default JavaFX font will be multiplied. * @return the size of the default JavaFX font multiplied by {@code factor}. */ public static double getSize( double factor) { return Font.getDefault().getSize() * factor; } //------------------------------------------------------------------ /** * Returns the {@linkplain Font#getDefault() default font} whose size is scaled by the specified factor. * * @param sizeFactor * the factor by which the size of the default font will be scaled. * @return the default font scaled by {@code sizeFactor}. */ public static Font defaultFont( double sizeFactor) { Font font = Font.getDefault(); return Font.font(font.getFamily(), font.getSize() * sizeFactor); } //------------------------------------------------------------------ /** * Returns the bold variant of the {@linkplain Font#getDefault() default font}. * * @return the bold variant of the default font. */ public static Font boldFont() { return boldFont(Font.getDefault(), 1.0); } //------------------------------------------------------------------ /** * Returns the bold variant of the specified font. * * @param font * the font whose bold variant is required. * @return the bold variant of {@code font}. */ public static Font boldFont( Font font) { return boldFont(font, 1.0); } //------------------------------------------------------------------ /** * Returns the bold variant of the {@linkplain Font#getDefault() default font} whose size is multiplied by the * specified factor. * * @param sizeFactor * the factor by which the size of the default font will be multiplied. * @return the bold variant of the default font scaled by {@code sizeFactor}. */ public static Font boldFont( double sizeFactor) { return boldFont(Font.getDefault(), sizeFactor); } //------------------------------------------------------------------ /** * Returns the bold variant of the specified font whose size is multiplied by the specified factor. * * @param font * the font whose bold variant is desired. * @param sizeFactor * the factor by which the size of {@code font} will be multiplied. * @return the bold variant of {@code font} scaled by {@code sizeFactor}. */ public static Font boldFont( Font font, double sizeFactor) { return Font.font(font.getFamily(), FontWeight.BOLD, font.getSize() * sizeFactor); } //------------------------------------------------------------------ /** * Returns the italic variant of the {@linkplain Font#getDefault() default font}. * * @return the italic variant of the default font. */ public static Font italicFont() { return italicFont(Font.getDefault(), 1.0); } //------------------------------------------------------------------ /** * Returns the italic variant of the specified font. * * @param font * the font whose italic variant is desired. * @return the italic variant of {@code font}. */ public static Font italicFont( Font font) { return italicFont(font, 1.0); } //------------------------------------------------------------------ /** * Returns the italic variant of the {@linkplain Font#getDefault() default font} whose size is multiplied by the * specified factor. * * @param sizeFactor * the factor by which the size of the default font will be multiplied. * @return the italic variant of the default font scaled by {@code sizeFactor}. */ public static Font italicFont( double sizeFactor) { return italicFont(Font.getDefault(), sizeFactor); } //------------------------------------------------------------------ /** * Returns the italic variant of the specified font whose size is multiplied by the specified factor. * * @param font * the font whose italic variant is desired. * @param sizeFactor * the factor by which the size of {@code font} will be multiplied. * @return the italic variant of {@code font} scaled by {@code sizeFactor}. */ public static Font italicFont( Font font, double sizeFactor) { return Font.font(font.getFamily(), FontPosture.ITALIC, font.getSize() * sizeFactor); } //------------------------------------------------------------------ /** * Returns the bold italic variant of the {@linkplain Font#getDefault() default font}. * * @return the bold italic variant of the default font. */ public static Font boldItalicFont() { return boldItalicFont(Font.getDefault()); } //------------------------------------------------------------------ /** * Returns the bold italic variant of the specified font. * * @param font * the font whose bold italic variant is desired. * @return the bold italic variant of {@code font}. */ public static Font boldItalicFont( Font font) { return boldItalicFont(font, 1.0); } //------------------------------------------------------------------ /** * Returns the bold italic variant of the {@linkplain Font#getDefault() default font} whose size is multiplied by * the specified factor. * * @param sizeFactor * the factor by which the size of the default font will be multiplied. * @return the bold italic variant of the default font scaled by {@code sizeFactor}. */ public static Font boldItalicFont( double sizeFactor) { return boldItalicFont(Font.getDefault(), sizeFactor); } //------------------------------------------------------------------ /** * Returns the bold italic variant of the specified font whose size is multiplied by the specified factor. * * @param font * the font whose italic variant is desired. * @param sizeFactor * the factor by which the size of {@code font} will be multiplied. * @return the bold italic variant of {@code font} scaled by {@code sizeFactor}. */ public static Font boldItalicFont( Font font, double sizeFactor) { return Font.font(font.getFamily(), FontWeight.BOLD, FontPosture.ITALIC, font.getSize() * sizeFactor); } //------------------------------------------------------------------ } //----------------------------------------------------------------------
package com.icanhasnom.fliplist; import java.util.ArrayList; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.RemoteViews; import android.widget.RemoteViewsService; class WidgetListProvider implements RemoteViewsService.RemoteViewsFactory { private ItemList itemList; private static String tag="WidgetListProvider"; private ArrayList<Item> myListItems = new ArrayList<Item>(); private Context mContext; private int mAppWidgetId; ListManager myListManager; public WidgetListProvider(Context context, Intent intent) { mContext = context; mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); updateData(); Log.d(tag,"Factory created"); } private void updateData() { myListManager = new ListManager(mContext); itemList = myListManager.getItemList(0); } @Override public void onCreate() { // In onCreate() you setup any connections / cursors to your data // source. Heavy lifting, // for example downloading or creating content etc, should be deferred // to onDataSetChanged() // or getViewAt(). Taking more than 20 seconds in this call will result // in an ANR. //for (int i = 0; i < mCount; i++) { // itemList.add(new Item(i + "!")); //} // We sleep for 3 seconds here to show how the empty view appears in the // interim. // The empty view is set in the StackWidgetProvider and should be a // sibling of the // collection view. Log.d(tag,"onCreate called for widget id: " + mAppWidgetId); //try { // Thread.sleep(3000); //} catch (InterruptedException e) { // e.printStackTrace(); //} } @Override public void onDestroy() { // In onDestroy() you should tear down anything that was setup for your // data source, // eg. cursors, connections, etc. Log.v(tag,"destroy called for widget id: " + mAppWidgetId); myListItems.clear(); } @Override public int getCount() { Log.v(tag,"getCount(): " + itemList.size()); return itemList.size(); } @Override public RemoteViews getViewAt(int position) { // position will always range from 0 to getCount() - 1. // We construct a remote views item based on our widget item xml file, // and set the // text based on the position. RemoteViews remoteView = new RemoteViews(mContext.getPackageName(), R.layout.activity_item_list_view); Item listItem = itemList.get(position); Log.v(tag,"listItem.getName(): " + listItem.getName()); remoteView.setTextViewText(R.id.itemName, listItem.getName()); remoteView.setTextViewText(R.id.itemInfo, listItem.getDescription()); return remoteView; //if (position % 2 == 0) { // rv.setImageViewResource(R.id.widget_layout, R.drawable.fire); //} else { // rv.setImageViewResource(R.id.widget_layout, R.drawable.ente); //} // rv.setTextViewText(R.id.widget_item, // mWidgetItems.get(position).text); // Next, we set a fill-intent which will be used to fill-in the pending // intent template // which is set on the collection view in StackWidgetProvider. //Bundle extras = new Bundle(); //extras.putInt(StackWidgetProvider.EXTRA_ITEM, position); //Intent fillInIntent = new Intent(); //fillInIntent.putExtras(extras); //rv.setOnClickFillInIntent(R.id.widget_item, fillInIntent); // You can do heaving lifting in here, synchronously. For example, if // you need to // process an image, fetch something from the network, etc., it is ok to // do it here, // synchronously. A loading view will show up in lieu of the actual // contents in the // interim. //try { // System.out.println("Loading view " + position); // Thread.sleep(500); //} catch (InterruptedException e) { // e.printStackTrace(); //} // Return the remote views object. } @Override public RemoteViews getLoadingView() { // You can create a custom loading view (for instance when getViewAt() // is slow.) If you // return null here, you will get the default loading view. return null; } @Override public int getViewTypeCount() { return 1; } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return true; } @Override public void onDataSetChanged() { // This is triggered when you call AppWidgetManager // notifyAppWidgetViewDataChanged // on the collection view corresponding to this factory. You can do // heaving lifting in // here, synchronously. For example, if you need to process an image, // fetch something // from the network, etc., it is ok to do it here, synchronously. The // widget will remain // in its current state while work is being done here, so you don't need // to worry about // locking up the widget. } }
+++ title = "Paludisme" prefix = "le " description = "Recommandations pour la prévention du paludisme et la prise en charge d'une suspicion d'accès palustre. Prophylaxie anti moustiques et atovaquone Malarone ..." synonyms = ["Malaria"] auteurs = ["Jean-Baptiste FRON"] date = "2021-02-17T12:42:00+02:00" publishdate = "2021-02-17" lastmod = "2023-10-03" specialites = ["infectiologie"] annees = "2018" sources = ["SPILF", "HCSP"] tags = ["fievre", "vaccin", "voyage"] anglais = ["Malaria"] sctid = "61462000" icd10 = "B54" image = true imageSrc = "Moustique anophèle vecteur du paludisme. Culicidae, Anopheles sp. Photo de Techuser sur Foter.com / CC BY-NC-ND" slider = true todo = "Prescrire, ttt ambulatoire accès palustre" +++ {{%article-summary%}} *Le traitement de l'accès palustre non grave n'est pas encore abordé* - Toute fièvre dans les 3 mois suivant le retour d'une zone impaludée est un paludisme jusqu'à preuve du contraire - Toute suspicion de paludisme est une **urgence** diagnostique et thérapeutique (service de maladies infectieuses et tropicales, médecine interne ou *Urgences*) - Paludisme réfuté mais doute persistant: deuxième test 12-24 heures plus tard (frottis sanguin, goutte épaisse, test de diagnostic rapide) - Voyage tropical: protection contre les moustiques et évaluer la nécessité d'une chimioprophylaxie médicamenteuse (voir *Indication à la prophylaxie palustre*) - Le paludisme autochtone est une [maladie à déclaration obligatoire]({{< relref "maladies-declaration-obligatoire.md" >}}) - Les séjours en zones d'endémie palustre sont déconseillés durant la grossesse (*CRAT*) {{%/article-summary%}} {{%collapse "Définition" %}} Paludisme : de l'ancien français << palus >> (marécage) ou aussi malaria, littéralement << mauvais air >>. : Maladie infectieuse due au parasite du genre *Plasmodium* (5 types: *Plasmodium falciparum* surtout voire *P. vivax*, *P. malariae*, *P. ovale* ou *P knowlesi*) transmise par les moustiques femelles du genre *Anopheles* (piqûres de 23 à 6 heures). La moitié de la population mondiale vit en zone d'endémie avec 600.000 morts chaque année. : Personnes à risque de forme grave: femme enceinte, nourrissons et enfants avant 6 ans, personnes âgées, [PVVIH]({{< relref "vih-sida.md" >}}) et [aspléniques]({{< relref "asplenie.md" >}}). : Absence de transmission du parasite sous 18°C. > << Un des principaux facteurs de risque pour les accès graves et les décès est le retard au diagnostic, souvent lié à une prise en charge inadaptée des patients lors d'une première consultation >> (*HCSP 2023*) {.alert .alert-warning} ### Abréviations Anofel : Association française des enseignants et praticiens hospitaliers titulaires de parasitologie et mycologie médicales CMIT : Collège des Universitaires des Maladies Infectieuses et Tropicales CNR : Centre National de Référence du Paludisme cpP : comprimé pédiatrique CPAP : chimioprophylaxie antipaludique P. : *Plasmodium* PPAV : protection personnelle anti-vectorielle (= protection contre les piqûres de moustiques et autres insectes) {.dl-inline} ### Diagnostic différentiel d'une fièvre au retour de voyage Un accès palustre doit être éliminé avant d'étayer les autres causes de fièvre au retour de voyage: - Salmonelloses - Arboviroses - [Hépatites virales](/tags/hepatite/) - Amœbose hépatique - Helminthoses - Bactérioses cosmopolites ### Épidémiologie du paludisme en France - Incidence: 4995 cas estimés en 2021 (9 présumés autochtones, *CNR*) 99,5% contractés en **Afrique subsaharienne** et 88,8 % par *Plasmodium falciparum*, sans diminution. - 87,6% des patients sont des voyageurs retournant au pays - Formes graves: 16,2% (2021), à 98,6% par *P falciparum* - Décès en France: 8 (2021) L'Afrique subsaharienne comptabilise 90% des cas mondiaux de paludisme. {{< card-link-external title="Malaria Atlas Project" subtitle="Données sur le paludisme" url="https://data.malariaatlas.org/">}} {{% /collapse %}} {{%collapse "Signes de gravité et critères d'hospitalisation du paludisme" %}} Les accès palustres graves sont quasi exclusivement liés à *Plasmodium falciparum* (99% des diagnostics en France) voire *Plasmodium knowlesi*. {{%warning%}} Appel du 15 en cas de suspicion d'accès palustre grave: - Troubles neurologiques Obnubilation, confusion, somnolence, prostration, coma, convulsion. - Défaillance viscérale - Hypotension sévère - Hémorragie - Ictère - Pâleur marquée - Hypoglycémie {{%/warning%}} > << Tout accès palustre à *P. falciparum* peut évoluer vers une forme grave et entraîner le décès du patient >> (*CMIT 2021*) ### Critères d'hospitalisation pour paludisme - Terrain - Jeune enfant - Facteur de risque de forme grave Personne âgée, grossesse, comorbidités, grossesse. - Clinique et biologique - Tout signe de gravité - Thrombopénie < 50.000, anémie < 10, créatininémie > 150 µmol/L - **Parasitémie** > 2% - Impossibilité d'avoir un diagnostic parasitologique fiable et rapide - Troubles digestifs ne permettant pas un traitement oral - Traitement ambulatoire impossible Contexte psycho-social, isolement. - Échec d'un premier traitement > — *CMIT 2021* {{% /collapse %}} {{%collapse "Clinique" %}} > << Toute fièvre dans les 3 mois suivant le retour d'une zone d'endémie est un paludisme jusqu'à preuve du contraire >> (*Anofel 2022*, rappelé par *HCSP 2023*) << quels que soient les symptômes associés et même si un foyer infectieux ou une co-infection (dengue) est identifié >> (*SPILF 2020*) et << toute fièvre doit faire rechercher un antécédent de séjour en zone d'endémie (*CMIT 2021*) {.alert .alert-warning} L'incubation du paludisme est asymptomatique et dure: - Minimum 7 jours pour *P. falciparum*, 10 à 15 jours pour les autres - Maximum 2 mois pour *P. falciparum*, 3 ans *P. vivax* et *ovale*, plus de 10 ans pour *P. malariae*. Interrogatoire, signes et symptômes de l'accès palustre simple de l'adulte, **tableau pseudo-grippal dans les 3 mois suivants le retour de voyage** d'une zone endémique: - Voyage dans les 3 mois en pays impaludé - Date de retour - Chimioprophylaxie antipaludique utilisée - Antécédent de traitements antipaludiques curatifs déjà utilisés - **Syndrome pseudo-grippal** - Fièvre élevée, brutale et intermittente (rarement stéréotypée tierce par *P. falciparum*) - Frissons, sueurs - Phases quasi asymptomatiques - Céphalées - Myalgies - Troubles digestifs Douleurs abdominales, nausées, vomissements, diarrhées. - Examen clinique normal (neurologique ++) - Thrombopénie très fréquente (VPN élevée) Après quelques jours, tableau d'**anémie hémolytique fébrile**: - [Ictère]({{< relref "ictere.md" >}}), urines foncées - Hépatomégalie (enfant surtout) - [Splénomégalie]({{< relref "splenomegalie.md" >}}) > << Toute convulsion fébrile chez un enfant au retour d'une zone d'endémie palustre doit faire évoquer un accès palustre grave >> (*Anofel 2022*) Chez l'enfant, se méfier d'un tableau clinique à prédominance digestive. Toute suspicion de paludisme est une **urgence** diagnostique et thérapeutique (service de maladies infectieuses et tropicales, médecine interne ou *Urgences*) {.alert .alert-warning} ### Accès palustre simple à fièvre périodique Dans les suites d'une primo-infection non traitée: fièvre tierce ou quarte. Épisode fébrile vespéral quotidien (*P. knowlesi*), tous les 2 (*P. vivax* ou ov*ale) 3 jours (*P. malariae*) avec triade successive: 1. Frissons intenses pendant 1 heure 2. Fièvre élevée pendant 3-4 heures 3. Sueurs profuses pendant 2-4 heures avec sensation de bien-être Le tableau d'anémie hémolytique (splénomégalie) s'aggrave progressivement. {{% /collapse %}} {{%collapse "Indication à la prophylaxie palustre selon le pays de destination" %}} > Les séjours en zones d'endémie palustre sont déconseillés durant la grossesse (*CRAT*) - et chez les enfants ne pouvant prendre de prophylaxie (*HCSP*) {.alert .alert-info} Ces 3 sites permettent d'évaluer les recommandations concernant la nécessité d'un traitement préventif contre le paludisme. {{< card-link-external title="Vaccins recommandés et prévention palustre selon l'Institut Pasteur pour un voyage" url="https://www.pasteur.fr/fr/centre-medical/preparer-son-voyage" subtitle="Institut Pasteur" image="pasteur" >}} {{< card-link-external title="Vaccins et conseils par pays" url="https://www.diplomatie.gouv.fr/fr/dossiers-pays/" subtitle="France Diplomatie" image="ministere" >}} {{< card-link-external title="Vaccins recommandés et conseils médicaux par destination" url="https://pasteur-lille.fr/centre-prevention-sante-longevite/vaccins-et-voyages/preparer-ses-voyages/" subtitle="Pasteur Lille" image="pasteur" >}} ### Indication à la chimioprophylaxie antipaludique selon le type de voyage {{< table title="Indication de la chimioprophylaxie du paludisme (CPAP) et des autres moyens de prévention en zone d'endémie de paludisme selon le continent et les conditions de séjour. HCSP 2023" >}} | Type de séjour | Amérique tropicale,<br>Haïti et Rép Dom. | Afrique sub-<br>saharienne<br>et Yémen | Asie du Sud<br>et Sud-Est | Papouasie<br>Nvle Guinée<br>et Îles Salomon | |----------------|------------------------------------------|----------------------------------------|---------------------------|---------------------------------------------| | Pour tous | PPAV + CS si F | idem | idem | idem | | Séjour conventionnel | Non | CPAP<sup>1</sup> | Non | CPAP<sup>1</sup> | | Séjour non conventionnel<br>< 1m avec<br>nuitées en zone<br>rurale/forestière | Non³<br>TTR si isolé | CPAP<sup>1</sup> | Non³<br>TTR si isolé | CPAP<sup>1</sup> | | Séjour non conventionnel<br>+1m avec<br>nuitées en zone<br>rurale/forestière | Avis spé | CPAP<sup>1</sup> | Avis spé | CPAP<sup>1</sup> | | Expatriation prolongée | Avis spé | - Sahel: CPAP<br>en saison pluies²<br>- Forestière:<br>toute l'année | Avis spé | CPAP | {{< /table >}} > **Légende**: **CS si F** = Consultation sans délai si fièvre pendant le séjour ou dans les 3 mois qui suivent le retour et information sur la notion de voyage dans les 3 derniers mois ; **TTR** = traitement de réserve antipaludique <sup>1</sup> sauf les zones non à risque d'Afrique australe (Afrique du Sud hors région Nord Est, Sud de la Namibie et du Botswana) ² début dès le début de la saison des pluies; arrêt 6 semaines après la fin des pluies ³ pour les zones à risque élevé de transmission du paludisme, consulter le tableau 10 du HCSP (p. 130) pour éventuellement adapter cette recommandation au niveau de risque réel du voyageur Choix de la chimioprophylaxie antipaludique (CPAP): - Afrique subsaharienne (sauf Afrique du Sud), Papouasie: CPAP systématique - Voyageurs à risque de paludisme grave, quel que soit le risque: femme enceinte, nourrissons et enfants avant 6 ans, personnes âgées, personnes immunodéprimées ([PVVIH]({{< relref "vih-sida.md" >}})) et [aspléniques]({{< relref "asplenie.md" >}}) - **Séjour << conventionnel >>** en Asie ou Amérique du Sud: mesures de PPAV seules Séjour de courte durée (< 1 mois), majoritairement en zone urbaine ou sur des sites touristiques classiques avec quelques nuitées en zone rurale mais dans des conditions d'hébergement satisfaisantes (hôtels, maisons). - **Séjour << non conventionnel >>**: avis spécialisé - Routards, militaires, séjour improvisé, mission humanitaire ou une exploration scientifique. 1 ou + parmi: durée supérieure à un mois, nombre élevé de nuitées en zone rurale, hébergements précaires (tente, habitations non protégées), périple pendant la saison des pluies ou dans une région de forte transmission palustre. - En situation d'isolement: intérêt d'un avis spécialisé pour le traitement présomptif d'urgence (traitement de réserve) > En cas de cas complexe, prendre l'avis d'un centre de conseils aux voyageurs et de vaccination internationaux (CVI). **NB.** Absence de transmission du paludisme sous 18°C. #### Situations particulières - Séjour << conventionnel >> de moins de 7 jours en zone à risque faible à modéré: PPAV seule possible si consignes de consultation pour fièvre comprises. - Séjours itératifs cours (aviation ...): avis spécialisé - Partie du séjour en zone endémique: la CPAV ne couvre que la période d'exposition - Séjour de longue durée Séjour initial: CPAP pendant 3-6 mois puis évaluation par expert local. En situation à haut risque (facteur de risque, Afrique subsaharienne): maintenir le plus longtemps possible (toute la durée de l'expatriation si le risque le justifie). {{% /collapse %}} {{%collapse "Molécules en prévention du paludisme" %}} La prophylaxie anti-palustre (chimioprophylaxie médicamenteuse) n'élimine pas complètement le risque de forme grave {.alert .alert-warning} La chimioprophylaxie antipaludique (CPAP) n'est disponible que sur ordonnance et aucune des molécules n'est remboursée (la doxycycline est la moins chère). De plus, l'achat hors pharmacie française n'est pas recommandé. {{< outils/cpap >}} ### Les mesures de protection anti-vectorielles (PPAV) Les mesures de protection contre les piqûres d'insectes sont toujours associées (voir [voyage]({{< relref "voyage.md" >}})). {{< traitements/ppav >}} ### Les vaccins contre le paludisme Deux vaccins contre le paludisme existent (RTS,S et R21/Matrix-M), dont le premier est recommandé l'OMS pour les enfants résidant en zone de moyenne et haute endémicité {.alert .alert-info} ### Atovaquone-proguanil Spécialités: [atovaquone/proguanil 250/100 mg](https://base-donnees-publique.medicaments.gouv.fr/affichageDoc.php?specid=66395950&typedoc=R) et [cpP atovaquone/proguanil 62,5/25 mg](https://base-donnees-publique.medicaments.gouv.fr/affichageDoc.php?specid=68303281&typedoc=R), comprimés uniquement. Prise quotidienne pendant le repas à heure fixe, avec une boisson ou un produit lacté (sucré si besoin, goût amer). - Personne > 40 kg 1 cp (250/100 mg) par jour - Enfant de 31 à 40 kg 3 cpP (62,5/25 mg) par jour en 1 prise - Enfant de 21 à 30 kg 2 cpP (62,5/25 mg) par jour en 1 prise - Enfant de 11 à 20 kg 1 cpP (62,5/25 mg) par jour - Enfant de 8 à 11 kg (hors AMM) Préparation magistrale équivalente à 3/4 cpP par jour - Enfant de 5 à 7 kg (hors AMM) Préparation magistrale équivalente à 1/2 cpP par jour > cpP = comprimé pédiatrique (62,5/25 mg), doses selon *HCSP/SPF voyage* {{%info%}} À débuter la veille ou le jour du départ et poursuivre 7 jours après le retour. La prise en continu est limitée à 3 mois consécutifs. {{%/info%}} **Effets indésirables de l'atovaquone-proguanil**: augmentation de l'INR sous AVK **Contre-indication:** insuffisance rénale sévère ### Doxycycline (monohydrate ou hyclate) Possible uniquement à partir de 8 ans (hors grossesse): [doxycycline monohydratée](https://base-donnees-publique.medicaments.gouv.fr/affichageDoc.php?specid=63307856&typedoc=R) cp 50/100 mg ou [doxycycline hyclate](https://base-donnees-publique.medicaments.gouv.fr/affichageDoc.php?specid=67061569&typedoc=R) cp 50/100 mg. - Poids ≥ 40 kg 1 cp à 100 mg pendant le dîner - Poids < 40 kg 1 cp à 50 mg pendant le dîner {{%info%}} À débuter la veille du départ et poursuivre 4 semaines après le retour. Débuter au mieux 3 semaines avant pour évaluer correctement la tolérance. Prendre pendant le dîner, au moins 1h avant le coucher. Contre-indiqué avant 8 ans, pendant la grossesse et en association avec les rétinoïdes par voie générale. {{%/info%}} **Contre-indications:** grossesse, allaitement, âge < 8 ans **Effets indésirables:** photosensibilisation, déséquilibre d'un traitement par AVK ### Méfloquine En dernière intention. Spécialité: [Lariam®](https://base-donnees-publique.medicaments.gouv.fr/affichageDoc.php?specid=65999556&typedoc=R) (cp sécable) uniquement, de préférence au cours du repas. - Personne ≥ 46 kg 1 cp à 250 mg 1 fois par semaine - Enfant de 31 à 45 kg 3/4 cp à 250 mg 1 fois par semaine - Enfant de 20 à 30 kg 1/2 cp à 250 mg 1 fois par semaine - Enfant de 15 à 19 kg 1/4 cp à 250 mg 1 fois par semaine - Enfant de 5 à 14 kg (hors AMM) Préparation magistrale équivalente à 1/8 cp 1 fois par semaine Peut être utilisée pendant la grossesse. **Effets indésirables:** anxiété, tristesse, dépression, agitation, confusion, tendance suicidaire, céphalées, vertiges, troubles du sommeil. Arrêt immédiat en cas de survenue. **Contre-indications:** antécédent de convulsions, de troubles neuro-psychiques, insuffisance hépatique sévère, traitement par acide valproïque À débuter la première fois au moins 10 jours avant le départ et poursuivre 3 semaines après le retour. Au mieux 3 semaines avant pour évaluer correctement la tolérance. Ensuite débuter 3 jours avant l'entrée dans la zone à risque. {.alert .alert-info} ### Chloroquine La chimioprophylaxie anti-palustre par chloroquine a été définitivement retirée en 2022. {{% /collapse %}} {{%collapse "Traitement ambulatoire du paludisme" %}} Après bilan diagnostique en urgence, la prise en charge d'un paludisme à *P. falciparum* non compliqué peut être réalisée en ambulatoire uniquement si tous les critères suivants sont remplis: - Absence de critère de gravité - Absence de terrain à risque: grossesse, jeune enfant, comorbidité, splénectomie, immunodépression, contexte socio-éducatif défavorable (compréhension, observance) - Présence d'un entourage - Absence de complication - Diagnostic parasitologique fiable - Absence d'échec d'un premier traitement - Absence de vomissements - Absence de facteur de risque de mauvaise tolérance - Antipaludique mis à disposition (pharmacie hospitalière ou service) et première prise surveillée pendant 2 heures - Proximité d'un hôpital, numéro d'urgence fourni - Consultation de contrôle possible à J3 et J7 et J28 par un spécialiste - Frottis sanguin et goutte épaisse à J3 (parasitémie < 25% de la valeur initiale), J7 (parasitémie nulle) et J28 - NFS à J7, J14, J21 et J28 si accès grave - Plaquettes > 50.000/mm³, Hb > 10 g/dL, créatininémie < 150 µmol/L - Parasitémie < 2% La prise en charge ambulatoire d'un paludisme à Plasmodium non falciparum est la règle (identique à *falciparum* pour *knowlesi*). ### Traitement ambulatoire du paludisme non compliqué Le traitement de première intention du paludisme est une combinaison à base de dérivés l'artémisinine (ACT): arténimol–pipéraquine (Eurartésim®) ou artéméther–luméfantrine (Riamet®). Les traitements d'intention moindre sont l'atovaquone-proguanil voire la quinine (3<sup>e</sup> intention). {{% /collapse %}} {{%sources%}} - [Pasteur. Paludisme : la prise en charge des malades du paludisme à Plasmodium falciuparum mise en périle dans la Corne de l'Afrique. 28/09/2023.](https://www.pasteur.fr/fr/espace-presse/documents-presse/paludisme-prise-charge-malades-du-paludisme-plasmodium-falciparum-mise-peril-corne-afrique) - {{< references/voyageur >}} - Anofel. Paludisme. Parasitoses et mycoses des régions tempérées et tropicales. 2022. - [CMIT. Paludisme. Item 170. ECN.Pilly. 2021. (PDF)](https://www.infectiologie.com/UserFiles/File/pilly-etudiant/ecn-2020-170-web.pdf) - [Bouchaud O et al. Prise en charge et prévention du paludisme d'importation - Mise à jour 2018 des RPC 2007. Médecine et Maladies Infectieuses. 2020.](https://www.sciencedirect.com/science/article/pii/S0399077X19310613) - [Egmann G et al; SFMU. Accès palustres : diagnostic et traitement. 2014. (PDF)](https://www.sfmu.org/upload/70_formation/02_eformation/02_congres/Urgences/urgences2014/donnees/pdf/028.pdf) - [Centre National de Référence du Paludisme](https://cnr-paludisme.fr) - [Institut Pasteur. Recommandations générales - Prévention du paludisme.](https://www.pasteur.fr/fr/centre-medical/vaccination/recommandations-generales#prvention-du-paludisme) {{%/sources%}} {{% modal title="Répulsifs pour la PPAV" id="modal-repulsifs" size="lg"%}} {{< traitements/repulsifs >}} {{% /modal %}}
import { useState } from 'react'; import Draggable from 'react-draggable'; import { FaTimes, FaWindowMinimize, FaWindowMaximize } from 'react-icons/fa'; function Window({ id, title, content, onClose, onMinimize, onMaximize, isMinimized, isMaximized }) { return ( <Draggable handle=".handle" cancel=".no-drag"> <div className={`absolute bg-gray-900 border border-gray-700 shadow-lg rounded-lg ${ isMaximized ? 'w-full h-full' : 'min-w-[300px] max-w-[800px]' } ${isMinimized ? 'hidden' : ''} resize overflow-hidden`} style={{ touchAction: 'none' }} > <div className="handle bg-gray-900 text-white p-2 flex justify-between items-center rounded-t-lg cursor-move touch-none"> <div className="flex items-center space-x-2"> <button className="w-3 h-3 bg-green-500 rounded-full" onClick={() => onMaximize(id)}></button> <button className="w-3 h-3 bg-yellow-500 rounded-full" onClick={() => onMinimize(id)}></button> <button className="w-3 h-3 bg-red-500 rounded-full" onClick={() => onClose(id)}></button> </div> <span className="font-bold flex-grow text-center">{title}</span> <div className="w-6"></div> </div> <div className="bg-gray-900 text-white p-4 overflow-y-auto no-drag" style={{ maxHeight: 'calc(100vh - 50px)' }}> {content} </div> </div> </Draggable> ); } export default Window;
/** *Submitted for verification at Arbiscan.io on 2024-04-20 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.24; contract SponsorContract { // Mapping to store owner status mapping(address => bool) public isOwner; // Event for ownership changes event OwnershipGranted(address indexed newOwner); event OwnershipRevoked(address indexed oldOwner); constructor(address _owner1, address _owner2) { isOwner[_owner1] = true; isOwner[_owner2] = true; emit OwnershipGranted(_owner1); emit OwnershipGranted(_owner2); } modifier onlyOwner() { require(isOwner[msg.sender], "Caller is not an owner"); _; } receive() external payable {} // Function to allow owners to execute transactions on behalf of the contract function sponsorTransaction(address target, bytes calldata data) public onlyOwner { (bool success, ) = target.call(data); require(success, "Transaction failed"); } // Function to allow owners to execute transactions function executeTransaction(address target, bytes memory data) public payable onlyOwner { (bool success, ) = target.call{value: msg.value}(data); require(success, "Transaction failed"); } // Administrative functions to manage owners function addOwner(address newOwner) public onlyOwner { isOwner[newOwner] = true; emit OwnershipGranted(newOwner); } function removeOwner(address oldOwner) public onlyOwner { isOwner[oldOwner] = false; emit OwnershipRevoked(oldOwner); } }
import { useState, useEffect } from "react" import Article from "./Article"; export default function Countries() { const [countries, setCountries] = useState( [] ); const [searchText, setSearchText] = useState(""); const regions = [ { name: "Europe" }, { name: "Asia" }, { name: "Africa" }, { name: "Oceania" }, { name: "Americas" }, { name: "Antarctic" } ] //empty dependency array so that it only runs once on the initial render useEffect(() => { const getCountries = async() => { try { const res = await fetch("https://restcountries.com/v3.1/all"); const data = await res.json(); setCountries(data.slice(0, 10)); } catch(error) { console.error(error); } }; getCountries(); }, []); async function searchCountry() { try { const res = await fetch(`https://restcountries.com/v3.1/name/${searchText}`); const data = await res.json(); setCountries(data); } catch (error) { console.error(error) } } async function filterByRegion(region) { try { const res = await fetch(`https://restcountries.com/v3.1/region/${region}`); const data = await res.json(); setCountries(data); } catch (error) { console.error(error) } } function handleSearchCountry(e) { e.preventDefault(); searchCountry(); } function handleFilterByRegion(e) { e.preventDefault(); filterByRegion(); } return <> {!countries ? ( <h1 className="text-gray-900 font-bold uppercase tracking-wide flex items-center justify-center text-center h-screen text-4xl dark:text-white"> Loading...</h1>) : ( <section className="container mx-auto p-8"> {/* form */} <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between mb-8"> <form onSubmit={handleSearchCountry} autoComplete="off" className="max-w-4xl md:flex-1"> <input type="text" name="search" id="search" placeholder="Search for a country by its name" required value={searchText} onChange={(e) => setSearchText(e.target.value)} className="py-3 px-4 text-gray-600 placeholder-gray-600 w-full shadow rounded outline-none dark:text-gray-400 dark:placeholder-gray-400 dark:bg-gray-800 dark:focus:bg-gray-700 transition-all duration-200" /> </form> <form onSubmit={handleFilterByRegion}> <select name="filter-by-region" id="filter-by-region" className="w-52 py-3 px-4 outline:none shadow rounded bg-white text-gray-600 dark:text-gray-400 dark:bg-gray-800 dark:focus:bg-gray-700" value={regions.name} onChange={(e) => filterByRegion(e.target.value)} > {regions.map((region, index) => ( <option key={index} value={region.name}>{region.name}</option> ))} </select> </form> </div> <div className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4"> {countries.map((country) => ( <Article key={country.name.common} {...country}/> ))} </div> </section> )} </> }
package com.sethondrunninggroop.web.controller; import com.sethondrunninggroop.web.dto.ClubDto; import com.sethondrunninggroop.web.models.Club; import com.sethondrunninggroop.web.service.ClubService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller public class ClubController { private ClubService clubService; @Autowired public ClubController(ClubService clubService) { this.clubService = clubService; } @GetMapping("/clubs") public String listClubs(Model model){ List<ClubDto> clubs = clubService.findAllClubs(); model.addAttribute("clubs",clubs); return "clubs-list"; } @GetMapping("/clubs/{clubId}") public String clubDetail(@PathVariable("clubId") long clubId, Model model){ ClubDto clubDto = clubService.findClubById(clubId); model.addAttribute("club", clubDto); return "clubs-detail"; } @GetMapping("/clubs/new") public String createClubForm(Model model){ Club club = new Club(); model.addAttribute("club",club); return "clubs-create"; } @GetMapping("/clubs/{clubId}/delete") public String deleteClub(@PathVariable("clubId") Long clubId){ clubService.delete(clubId); return "redirect:/clubs"; } @GetMapping("/clubs/search") public String searchClub(@RequestParam(value = "query") String query, Model model){ List<ClubDto> clubs = clubService.searchClub(query); model.addAttribute("clubs", clubs); return "clubs-list"; } @PostMapping("/clubs/new") public String saveClub(@ModelAttribute("club") Club club){ clubService.saveClub(club); return "redirect:/clubs"; } @GetMapping("clubs/{clubId}/edit") public String editClubForm(@PathVariable("clubId") long clubId, Model model ){ ClubDto club = clubService.findClubById(clubId); model.addAttribute("club", club); return "clubs-edit"; } @PostMapping("/clubs/{clubId}/edit") public String updateClub(@PathVariable("clubId") Long clubId, @ModelAttribute("club") ClubDto club){ club.setId(clubId); clubService.updateClub(club); return "redirect:/clubs"; } }
<template> <div> <v-row class="py-0 mt-1"> <v-col cols="12" class="py-0"> <span class="subtitle-1">Add a new filter</span> </v-col> </v-row> <v-row> <v-col cols="4"> <!-- Filter --> <v-select v-model="new_filter.filter" hint="Filter" :items="filters_options['vulns']" item-text="name" item-value="attribute" label="Select" persistent-hint return-object single-line outlined dense clearable ></v-select> </v-col> <!-- Criteria --> <v-col cols="3"> <v-select :disabled="new_filter.filter == ''" v-model="new_filter.criteria" hint="Criteria" :items="new_filter_criterias" item-text="text" item-value="value" label="Criteria" persistent-hint single-line outlined dense ></v-select> </v-col> <!-- Value --> <v-col cols="4" v-if="this.new_filter.filter.criteria == 'text' || this.new_filter.filter.criteria == 'numeric'"> <v-text-field :disabled="new_filter.filter == '' || new_filter.criteria == null" v-model="new_filter.value" v-if="this.new_filter.filter.criteria != 'bool'" :type="this.new_filter.filter.criteria == 'numeric'?'number':''" hint="Value" label="..." outlined dense v-on:keyup.enter="addFilter" ></v-text-field> </v-col> <v-col cols="4" v-if="this.new_filter.filter.criteria == 'date'"> <v-menu v-model="new_filter_date_menu" :nudge-right="40" transition="scale-transition" offset-y min-width="290px" > <template v-slot:activator="{ on, attrs }"> <v-text-field v-model="new_filter_date" append-icon="mdi-calendar" v-bind="attrs" v-on="on" outlined dense ></v-text-field> </template> <v-date-picker v-model="new_filter.value" @input="new_filter_date_menu = false" ></v-date-picker> </v-menu> </v-col> <!-- Add button --> <v-col cols="1"> <v-btn :disabled="(new_filter.value == '' && new_filter.filter.criteria != 'bool') || new_filter.criteria == null" fab small outlined color="deep-orange" @click="addFilter" title="Add new filter" class="mt-0" ><v-icon>mdi-plus</v-icon> </v-btn> </v-col> </v-row> <v-row class="pt-2"> <v-col cols="12" class="py-0" v-if="filters.length > 0"> <span class="subtitle-1">Applied filters:</span> </v-col> <v-col cols="12" class="py-0" v-else> <span class="subtitle-2 font-italic">No filter applied yet</span> </v-col> </v-row> <v-row v-for='(f, index) in filters' :key="index" align="center"> <v-col cols="auto"> <v-icon @click="removeFilter(index)">mdi-delete-outline</v-icon> </v-col> <v-col cols="4"> <v-select v-model="f.filter" :items="filters_options[scope]" item-text="name" item-value="attribute" return-object single-line outlined dense hide-details ></v-select> </v-col> <v-col cols="3"> <v-select v-model="f.criteria" :items="criterias[f.filter.criteria]" item-text="text" item-value="value" single-line outlined dense hide-details ></v-select> </v-col> <v-col cols="4"> <v-text-field v-model="f.value" v-if="f.filter.criteria != 'bool'" outlined dense hide-details ></v-text-field> </v-col> </v-row> <v-row align="start" justify="start"> <v-col> <v-btn color="deep-orange" :disabled="filters.length == 0" small class="mr-2" @click="applySearchFilters">Search</v-btn> </v-col> </v-row> </div> </template> <script> import moment from 'moment'; export default { name: "AdvancedSearch", props: { scope: { type: String, default: 'vulns' } }, data: () => ({ new_filter_date: new Date().toISOString().substr(0, 10), new_filter_date_menu: false, new_filter: { filter: '', criteria: null, value: '' }, new_filter_criterias: [], filters: [], filters_options: { 'vulns': [ { name: 'CVE', attribute: 'cveid', criteria: 'text'}, { name: 'Summary', attribute: 'summary', criteria: 'text'}, { name: 'Score', attribute: 'score', criteria: 'numeric'}, { name: 'CVSSv2', attribute: 'cvss', criteria: 'numeric'}, { name: 'CVSSv2 Vector', attribute: 'cvss_vector', criteria: 'text'}, { name: 'CVSSv3', attribute: 'cvss3', criteria: 'numeric'}, { name: 'CVSSv3 Vector', attribute: 'cvss3_vector', criteria: 'text'}, // { name: 'Exploit count', attribute: 'exploit_count', criteria: 'numeric'}, // { name: 'Is monitored ?', attribute: 'monitored', criteria: 'bool'}, { name: 'Is exploitable ?', attribute: 'is_exploitable', criteria: 'bool'}, { name: 'Is confirmed ?', attribute: 'is_confirmed', criteria: 'bool'}, { name: 'Is in the News ?', attribute: 'is_in_the_news', criteria: 'bool'}, { name: 'Is in the Wild ?', attribute: 'is_in_the_wild', criteria: 'bool'}, { name: 'Published at', attribute: 'published', criteria: 'date'}, // 'product': 'text' ] }, criterias: { 'text': [ { text: 'Equals', value: ''}, // { text: 'Not equals', value: 'not_exact'}, { text: 'Contains', value: 'contains'}, // { text: 'Not contains', value: 'not_contains'}, { text: 'Contains (ignore case)', value: 'icontains'}, // { text: 'Not contains (ignore case)', value: 'not_icontains'}, ], 'numeric': [ { text: 'Equals', value: ''}, { text: 'Greater than', value: 'gt'}, { text: 'Greater than or equals', value: 'gte'}, { text: 'Less than', value: 'lt'}, { text: 'Less than or equals', value: 'lte'}, ], 'date': [ { text: 'At', value: 'date'}, { text: 'After', value: 'date__gt'}, { text: 'After or at', value: 'date__gte'}, { text: 'Before', value: 'date__lt'}, { text: 'Before or at', value: 'date__lte'}, ], 'bool': [ { text: 'Yes', value: 'true'}, { text: 'No', value: 'false'}, ], } }), mounted() { }, watch: { new_filter: { handler() { this.new_filter_criterias = this.criterias[this.new_filter.filter.criteria] }, deep: true }, }, computed: { }, methods: { addFilter(){ this.filters.push(this.new_filter); this.new_filter = { filter: '', criteria: null, value: '' } this.applySearchFilters() }, removeFilter(idx){ this.filters.splice(idx, 1); this.applySearchFilters() }, applySearchFilters(){ // Format the filters let filters_str = ''; this.filters.forEach(function (f) { // console.log(f); var f_str = ''; if (f.filter.criteria == 'bool'){ f_str = "&"+f.filter.attribute+"="+f.criteria; } else if (f.criteria == ''){ f_str = "&"+f.filter.attribute+"="+f.value; } else { f_str = "&"+f.filter.attribute+"__"+f.criteria+"="+f.value; } filters_str += f_str }); // console.log(filters_str) this.$emit('advanced_search_filters', filters_str); }, } }; </script> <style> </style>
# accounts/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils import timezone class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" if not email: raise ValueError('This object requires an email') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): # add additional fields in here email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) document = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' def __str__(self): return self.email
package com.particeep.test.akka import akka.actor.{ Actor, ActorSystem, Props } /** * Question about Akka framework http://akka.io * * When receiving a message that says "Hello", BasicActor must print "Hello there." * It must print "What?" when receiving any other message */ class BasicActor extends Actor { def receive: Receive = { case "Hello" => print("Hello there.") case _ => print("What?") } def print(message:String): Unit = println(message) } object FireActor { /** * Create an instance of BasicActor * * Make it print "Hello there." and "What?" */ def fireActor(): Unit = { val system = ActorSystem("ActorSystem") val basicActor = system.actorOf(Props[BasicActor], name = "basicActor") basicActor ! "Hello" basicActor ! "How are you?" } }
import { render, waitFor, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import '@testing-library/jest-dom' import LoginForm from '@/components/Login/LogInForm' import { signIn } from 'next-auth/react' import { makeStore } from '@/redux/store' import { Provider } from 'react-redux' import { toast } from 'react-toastify' jest.mock('next-auth/react') jest.mock('next/router', () => { return { __esModule: true, useRouter: jest.fn(() => ({ route: '/', pathname: '', query: '', asPath: '', push: jest.fn(), })), } }) jest.mock('react-hook-form', () => ({ useForm: jest.fn().mockReturnValue({ register: jest.fn(), handleSubmit: jest.fn((fn) => fn), formState: { errors: {} }, }), })) const mockToastError = () => { const errorSpy = jest.spyOn(toast, 'error') return errorSpy } describe('LoginForm', () => { it('submits form with email and password and succeeds', async () => { render( <Provider store={makeStore()}> <LoginForm /> </Provider>, ) const mockSignIn = signIn as jest.MockedFunction<typeof signIn> mockSignIn.mockResolvedValue({ error: undefined, status: 200, ok: true, url: null, }) userEvent.type(screen.getByPlaceholderText('Email'), 'test@example.com') userEvent.type(screen.getByPlaceholderText('Password'), 'password123') userEvent.click(screen.getByRole('button', { name: /sign in/i })) waitFor(() => { expect(screen.getByPlaceholderText('Email')).toHaveValue( 'test@example.com', ) expect(screen.getByPlaceholderText('Password')).toHaveValue('password123') }) await waitFor(() => { expect(mockSignIn).toHaveBeenCalled() }) }) it('calls onSubmit with the form data', async () => { render( <Provider store={makeStore()}> <LoginForm /> </Provider>, ) const errorSpy = mockToastError() // Mock the signIn function to resolve with a success const mockSignIn = signIn as jest.MockedFunction<typeof signIn> mockSignIn.mockResolvedValue({ error: 'Login failed', status: 401, ok: false, url: null, }) userEvent.type(screen.getByPlaceholderText('Email'), 'test@example.com') userEvent.type(screen.getByPlaceholderText('Password'), 'password123') userEvent.click(screen.getByRole('button', { name: /sign in/i })) await waitFor(() => { expect(errorSpy).toHaveBeenCalled() }) expect(errorSpy).toHaveBeenCalledWith('Login failed') errorSpy.mockRestore() }) })
from collections import deque N, K = map(int, input().split()) M = 100000 dist = [[-1, 0] for _ in range(M+1)] #첫번째 인덱스는 최소시간을 의미, 두번째는 최소시간으로 도달하는 방법수를 의미 def BFS(start): queue = deque([start]) dist[start] = [0, 1] while queue: cur = queue.popleft() for next in (cur-1, cur+1, cur*2): if 0 <= next <= M: # 이전에 방문한 노드가 아니라면 if dist[next][0] == -1: queue.append(next) dist[next] = [dist[cur][0] + 1, dist[cur][1]] # 이미 방문한적이 있다면, 더 최소시간으로 갱신 else: # 방문할 노드의 최소시간과 이미 저장된 최소시간이 같다면 방법수 1증가 if dist[next][0] == dist[cur][0] + 1: dist[next][1] += dist[cur][1] dist[next][0] = min(dist[next][0], dist[cur][0] + 1) BFS(N) print(dist[K][0]) print(dist[K][1])
package com.peterlaurence.trekme.core.map.data.dao import com.peterlaurence.trekme.core.excursion.domain.model.Excursion import com.peterlaurence.trekme.core.map.data.mappers.toData import com.peterlaurence.trekme.core.map.data.mappers.toDomain import com.peterlaurence.trekme.core.map.data.models.ExcursionRefFileBased import com.peterlaurence.trekme.core.map.data.models.ExcursionRefKtx import com.peterlaurence.trekme.core.map.data.models.MapFileBased import com.peterlaurence.trekme.core.map.domain.dao.ExcursionRefDao import com.peterlaurence.trekme.core.map.domain.models.ExcursionRef import com.peterlaurence.trekme.core.map.domain.models.Map import com.peterlaurence.trekme.util.FileUtils import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.update import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json import kotlinx.serialization.encodeToString import java.io.File class ExcursionRefDaoImpl( private val ioDispatcher: CoroutineDispatcher, private val json: Json ) : ExcursionRefDao { override suspend fun importExcursionRefs(map: Map) = withContext(ioDispatcher) { val directory = (map as? MapFileBased)?.folder ?: return@withContext val refsDir = File(directory, excursionRefsDir) runCatching { if (!refsDir.exists()) return@withContext val refFiles = refsDir.listFiles { it: File -> it.isFile && it.nameWithoutExtension.toIntOrNull() != null && it.name.endsWith(".json") } ?: emptyArray() val refs = refFiles.map { json.decodeFromString<ExcursionRefKtx>(FileUtils.getStringFromFile(it)) to it }.distinctBy { /* Protect against copy-paste of an excursion ref file */ it.first.id } map.excursionRefs.update { refs.map { it.toDomain() } } } Unit } override suspend fun createExcursionRef(map: Map, excursion: Excursion): ExcursionRef? = withContext(ioDispatcher) { val existing = map.excursionRefs.value.firstOrNull { it.id == excursion.id } /* If the reference already exists, fast return it */ if (existing != null) return@withContext existing val directory = (map as? MapFileBased)?.folder ?: return@withContext null val refsDir = File(directory, excursionRefsDir).also { val success = if (!it.exists()) it.mkdir() else true if (!success) return@withContext null } runCatching { val refFiles = refsDir.listFiles { it: File -> it.isFile && it.nameWithoutExtension.toIntOrNull() != null && it.name.endsWith(".json") } ?: emptyArray() val count = refFiles.size val newRefFile = File(refsDir, "$count.json") val data = ExcursionRefKtx(id = excursion.id, name = excursion.title, visible = true) val st = json.encodeToString(data) FileUtils.writeToFile(st, newRefFile) val newRef = Pair(data, newRefFile).toDomain() map.excursionRefs.update { it + newRef } newRef }.getOrNull() } override suspend fun saveExcursionRef(map: Map, ref: ExcursionRef) = withContext(ioDispatcher) { val refFileBased = (ref as? ExcursionRefFileBased) ?: return@withContext runCatching { if (!refFileBased.file.exists()) return@withContext val content = json.encodeToString(refFileBased.toData()) FileUtils.writeToFile(content, refFileBased.file) } Unit } override suspend fun removeExcursionRef(map: Map, ref: ExcursionRef) = withContext(ioDispatcher) { val refFileBased = (ref as? ExcursionRefFileBased) ?: return@withContext runCatching { if (refFileBased.file.delete()) { map.excursionRefs.update { it.filterNot { r -> r.id == ref.id } } } } Unit } override suspend fun removeExcursionRef(map: Map, excursionRefId: String) { val ref = map.excursionRefs.value.firstOrNull { it.id == excursionRefId } if (ref != null) { removeExcursionRef(map, ref) } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Flex Basics</title> <style> /* When the parent is in Display Flex all the childs are going to be flex */ #container { display: flex; /* changes the direction of the itens, note that flex has a default direction of row */ /* flex-direction: column; */ } #container .item { /* I use the flex propety to define the porportion of the itens,, it is something really similiar with the grid system when we use "1fr" to determine the proportion of the items */ flex: 1; } #container .item:first-child { flex: 2; } #container2 { display: flex; /* After 12 itens in the container the screen will have a scroll bar or you could use the propety wrap to jump to another line */ flex-wrap: wrap; } .item { background: #f4f4f4; border: #ccc 1px solid; padding: 1rem; text-align: center; margin: 0.75rem; } </style> </head> <body> <div id="container"> <div class="item"><h3> Item 1</h3></div> <div class="item"><h3> Item 2</h3></div> <div class="item"><h3> Item 3</h3></div> </div> <div id="container2"> <div class="item"><h3> Item 1</h3></div> <div class="item"><h3> Item 2</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> <div class="item"><h3> Item 3</h3></div> </div> </body> </html>
package edu.handong.analysis.datamodel; import java.util.ArrayList; import java.util.HashMap; public class Student { private String studentId; private ArrayList<Course> coursesTaken; private HashMap<String,Integer> semestersByYearAndSemester; public String getStudentId() { return studentId; } public HashMap<String, Integer> getSemestersByYearAndSemester() { semestersByYearAndSemester = new HashMap<String,Integer>(); int count = 1; for(Course tempCourse : coursesTaken) { String temp = (Integer.toString(tempCourse.getYearTaken())+"-"+Integer.toString(tempCourse.getSemesterCourseTaken())).trim(); //tempHash.putIfAbsent(temp, count++); if(semestersByYearAndSemester.isEmpty()) { semestersByYearAndSemester.put(temp, count); count++; } else { if(semestersByYearAndSemester.containsKey(temp)) continue; else { semestersByYearAndSemester.put(temp, count); count++; } } } return semestersByYearAndSemester; } public void setStudentId(String studentId) { this.studentId = studentId; } public ArrayList<Course> getCoursesTaken() { return coursesTaken; } public Student(String studentId) { this.studentId = studentId; this.coursesTaken = new ArrayList<Course>(); this.semestersByYearAndSemester = new HashMap<String,Integer>(); } // constructor public void addCourse(Course newRecord) { coursesTaken.add(newRecord); } public HashMap<String,Integer> loadStudentCourseRecords(){ //어레이리스트에서 yearTaken과 semesterTaken을 합쳐 String으로 저장한다 -> key HashMap<String,Integer> tempHash = new HashMap<String,Integer>(); int count = 1; for(Course tempCourse : coursesTaken) { String temp = (Integer.toString(tempCourse.getYearTaken())+"-"+Integer.toString(tempCourse.getSemesterCourseTaken())).trim(); //tempHash.putIfAbsent(temp, count++); if(tempHash.isEmpty()) { tempHash.put(temp, count); count++; } else { if(tempHash.containsKey(temp)) continue; else { tempHash.put(temp, count); count++; } } } return tempHash; } public int getNumCourseInNthSementer(int semester) { int count=0; //semestersByYearAndSemester에서 해당하는 semester를 찾는다 for(Course tempCourse : coursesTaken) { String courseInfo = Integer.toString(tempCourse.getYearTaken()) + "-" + Integer.toString(tempCourse.getSemesterCourseTaken()); if(semester == getSemestersByYearAndSemester().get(courseInfo)) { count++; } } //count를 늘려준다. return count; } }
// 424. // time - O(n) * time to find max value in map (which is constant) // space - O(n) for map class Solution { public int characterReplacement(String s, int k) { HashMap<Character, Integer> frequency = new HashMap<>(); //tracks freq of each letter in s int left = 0; //tracks left of current window int result = 0; //return value - length of largest substring for(int right = 0; right < s.length(); right++) { //account for current char at right frequency.put(s.charAt(right), frequency.getOrDefault(s.charAt(right), 0) + 1); //as long as current window is not valid int maxFrequencyInCurrentSubstring = Collections.max(frequency.values()); //gets the freq of max freq char while(left <= right && (right - left + 1) - (maxFrequencyInCurrentSubstring) > k) { //all remaining chars in current window can't be replaces with max freq char in k steps //remove char at left frequency.put(s.charAt(left), frequency.get(s.charAt(left)) - 1); if(frequency.get(s.charAt(left)) == 0) { frequency.remove(s.charAt(left)); } left++; } //current window is valid if(left <= right) { result = Math.max(result, right - left + 1); } } return result; } }
<!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>Mobile Phone Store</title> <!-- Bootstrap Link --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- Custom CSS Link --> <link rel="stylesheet" href="css/style.css"> </head> <body> <!-- Header section start --> <header> <div class="container mt-4"> <div class="text-center"> <h1 class="text-white mb-3">My awesome phone store</h1> <p class="suggestion">Search Suggestion: samsung, oppo, iPhone, air, tab, watch</p> <div class="d-flex justify-content-center"> <input id="input-field" class="form-control w-50" type="text" placeholder="Enter your phone name"> <button onclick="loadData()" class="btn btn-primary ms-1">Search</button> </div> <!-- Wrong value error message --> <p id="wrong-value-error" class="w-50 bg-danger text-white py-3 text-center mx-auto mt-3 img-radius fs-6">Your enter a wrong phone name!! Please write a correct phone name!!</p> <!-- empty error message --> <p id="empty-error" class="w-50 bg-danger text-white py-3 text-center mx-auto mt-3 img-radius fs-6">Your input box is empty!! Please write any phone name!!</p> <!-- spinner start --> <div class="d-flex justify-content-center"> <div id="spinner" class="spinner-border text-primary mt-5 fs-3" role="status"> <span class="visually-hidden">Loading...</span> </div> </div> </div> </div> </header> <!-- Main section start --> <main> <!-- Modal section start --> <section> <div class="container"> <div class="row"> <div class="col"> <div id="modal-div"> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header p-2"> <h5 class="modal-title" id="exampleModalLabel"></h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button> </div> <!-- Modal body --> <div class="modal-body"> <div class="d-flex justify-content-center"> <img id="modal-img" class="w-auto h-100 img-fluid" src="" alt=""> </div> <div id="modal-details" class="text-center"> </div> </div> <div class="modal-footer p-0"> <button type="button" class="btn btn-primary p-1" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </div> </div> </div> </section> <!-- Card section start --> <section> <div class="container mt-5"> <div id="card-section" class="row row-cols-1 row-cols-md-4 g-4 mb-4"> </div> <div id="show-more-div" class="d-flex justify-content-center mb-3"> <button id="show-more-btn" class="btn btn-primary px-4 rounded-pill">Show more</button> </div> <div id="show-all-div" class="d-flex justify-content-center"> <button id="show-all" class="btn btn-primary px-4 mb-3">Show all</button> </div> </div> </section> </main> <!-- Bootstrap Js link --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <!-- Custom Js link --> <script src="js/app.js"></script> </body> </html>
#pragma once #include <vector> #include <string> #include <map> class Attribute { public: enum class AttrTypes { INT, DOUBLE, STRING, LIST }; Attribute(); Attribute(int code, std::string alias, AttrTypes type, std::vector<std::string> value); const int& code() const; const std::string& alias() const; const AttrTypes& type() const; const std::vector<std::string>& value() const; void setCode(int code); void setAlias(std::string alias); void setType(const AttrTypes &type); void setValue(const std::vector<std::string> &value); private: int m_code; std::string m_alias; AttrTypes m_type; std::vector<std::string> m_value; }; class ComplexAttribute { public: ComplexAttribute(); ComplexAttribute(int code, std::string alias, const std::vector<Attribute> &attrs); int code() const; std::string alias() const; std::vector<Attribute> attibutes() const; Attribute getAttributeByCode(std::string code) const; void setCode(int code); void setAlias(std::string alias); void addAttribute(Attribute attr); bool hasAttribute(std::string code) const; private: int m_code; std::string m_alias; std::vector<Attribute> m_attrs; std::map<std::string, Attribute> m_code_to_attr; }; class Fe2spRef { public: Fe2spRef(); Fe2spRef(int refId, int refType, int orientation, int scamin, int scamax, std::string spatial); int refId() const; int refType() const; int orientation() const; int scamin() const; int scamax() const; const std::string spatial() const; void setRefId(int refId); void setRefType(int refType); void setOrientation(int orientation); void setScamin(int scamin); void setScamax(int scamax); void setSpatial(std::string spatial); private: int m_refId = -1; int m_refType; int m_orientation; int m_scamin; int m_scamax; std::string m_spatial = "noGeometry"; }; class IsolatedPoint { public: IsolatedPoint(float latitude, float longitude); IsolatedPoint(); float lat() const; float lon() const; void setLat(float lat); void setLon(float lon); private: float m_lat; float m_lon; }; class Feature { public: Feature(int m_id, int m_class, std::string alias , std::vector<Attribute> m_intAttrs , std::vector<ComplexAttribute> m_complexAttrs , Fe2spRef fe2sp /*, IsolatedPoint m_isolatedPoint*/); Feature(); int id() const; int classId() const; const std::string &classAlias() const; std::vector<Attribute> intAttrs() const; std::vector<ComplexAttribute> complexAttrs() const; IsolatedPoint isolatedPoint() const; Fe2spRef fe2spRef() const; void setId(int id); void setClass(int classId); void setClassAlias(std::string classAlias); void setIntAttrs(std::vector<Attribute> intAttrs); void setComplexAttrs(const std::vector<ComplexAttribute> &complexAttrs); void setIsolatedPoint(const IsolatedPoint &isolatedPoint); void setFe2spRef(const Fe2spRef &fe2spRef); void addIntAttr(Attribute attr); void addComplexAttr(ComplexAttribute attr); Attribute getAttributeByCode(std::string code) const; ComplexAttribute getComplexAttributeByCode(std::string code) const; bool hasComplexAttribute(std::string code) const; bool hasSimpleAttribute(std::string code) const; private: int m_id; int m_class; std::string m_classAlias; std::vector<Attribute> m_intAttrs; std::vector<ComplexAttribute> m_complexAttrs; Fe2spRef m_fe2spRef; IsolatedPoint m_isolatedPoint; std::map<std::string, Attribute> m_code_to_attr; std::map<std::string, ComplexAttribute> m_code_to_cAttr; };
--- title: "Prototype - An agent-based platform to evaluate the performance of sampling designs and modelling approaches when estimating animal abundance" author: "Denner A. B. Fabiano, Iuri E. P. Ferreira" date: "27/10/2021" output: html_document: code_folding: hide --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## Packages ```{r} #install.packages("landscapeR") #install.packages("raster") library(raster) library(landscapeR) ``` ## To generate the landscape Função que cria o ambiente (paisagem). O usuário pode configurar o tamanho da rede ``l.size``, o *vetor* número de fragmentos ``n.patches``, com três níveis de recurso (pobre, intermediário, rico), e cobertura de cada tipo de fragmento ``cover`` (soma da ``cover`` < 1). + default para ``l.size`` é 100 px, + default para ``n.patches`` é 2 fragmentos de cada tipo, + default para ``cover`` é de 25% para cada fragmento. ```{r} land.create <- function(l.size = 100, n.patches = c(2, 2, 2), cover = c(0.25, 0.25, 0.25)){ # Cria valores de qualidade / recursos val <- c(1, 3, 7) # Cover = cobertura de cada tipo de paisagem (soma < 1) if( sum(cover) > 1 ){print("Erro. Cobertura total não pode ser maior do que 1"); break} # Total de recursos t.r <- val %*% cover #### Criando a matriz de recurso #### # criando uma paisagem vazia - só com zeros m <- matrix(0, l.size, l.size) # the empty landscape # transformando a matriz em raster r <- raster(m, xmn=0, xmx=l.size, ymn=0, ymx=l.size) # cria sobre o raster r manchas disjuntas que # representam fragmentos pobres (i=1), # intermediários (i=2) e ricos (i=3) for(i in 1:length(cover)){ r <- makeClass(r, n.patches[i], round(cover[i]*l.size^2/n.patches[i]), val = val[i]) } # retorna o que é importante return( list("raster"=r,"recursos"=t.r) ) } # fim da função land.create # teste obj <- land.create(200, c(1, 2, 3), c(0.20,0.15,0.30)) # exemplo: criar uma paisagem grande, pobre e muito fragmentada obj <- land.create(l.size = 500, n.patches = c(10, 3, 3), cover = c(0.30, 0.05, 0.05) ) plot(obj$raster) ``` ## Solitary animals / population sim. Each time step is one hour. Simulations will represent 21 consecutive weeks. We considered the first twenty weeks needed to individuals establish the natural pattern of occupancy from random initial positions (adaptation phase). The remaining week is used to simulate the deposition of traces on the environment and level of patch occupancy. We considered the individual rate of four traces produced every day. + ``n`` is the number of animal on the environment + ``ra`` é o argumento que recebe o raster da paisagem + ``time`` is the number of weeks (adaptation + study phases) + ``where`` is where the animals are placed at the start of simulation (over all the environment or only where there are resources) ```{r} animal.mov<-function( n = 100, ra = NULL, time = 21, where = "resource"){ # Time in weeks (20 adaptation + 1 experiment) if(time<=1){print("Error. At least two weeks are necessary!"); break} # Total de tempo gasto nas simulações (em horas) time.step<-round(time)*7*24 # Tempo total de adaptação (em horas) time.step.adapt<-(round(time)-1)*7*24 # Número de animais (n) # r = valores do raster (formato de matriz) if(is.null(ra)){print("Erro. Inserir os valores do raster no segundo argumento"); break} # Extraindo valores do raster, na forma de matriz r<-values(ra,format="matrix") # Neste caso, r vira uma matriz auxiliar # dimensão da paisagem l<-dim(r)[1] # Gera coordenadas inicias x e y para cada # um dos n indivíduos simulados # Aleatoriamente ou só onde tem recursos? if(where=="random"||where=="resource"){ if(where=="random"){ # distribuição espacial sem restrições # posição inicial dos indíviduos (x_0, y_0) M <- matrix( sample(1:l,2*n,replace=TRUE) , ncol=2) } else{ # entra no else se for "resource" # distribuição espacial apenas aonde tem recurso coords<-NULL for(i in 2:(l-1)){ for(j in 2:(l-1)){ if(r[i,j]>0){coords<-rbind(coords,c(i,j))} # coords são os pontos onde tem recurso } # end for 1 } # end for 2 size <- dim(coords)[1] # tamanho do objeto coords # sorteio das posições iniciais dentro de coords k <- sample.int(size, n, replace=TRUE) M <- coords[k,] # matriz de posição dos animais } # fim else if random } else{ print("Error. where must be random or resource"); break } # Paramos aqui! Agora precisamos discutir as regras de #movimentação. R<-NULL MAUX<-M R[[1]]<-M classe<-c(1,2,3,4,5,6,7,8,9) traces<-NULL for(j in 2:time.step){ # Atualização for(i in 1:n){ x<-M[i,1]; y<-M[i,2] if(j>time.step.adapt&j%%6==0){traces<-rbind(traces,c(x,y))} if(x==1|x==l|y==1|y==l){ yaux<-y; xaux<-x if(x==1){xaux<-x+1} if(x==l){xaux<-x-1} if(y==1){yaux<-y+1} if(y==l){yaux<-y-1} MAUX[i,]<-c(xaux,yaux) } else{ # atualização dentro da matriz v.aux<-c(r[x-1,y+1],r[x,y+1],r[x+1,y+1], r[x-1,y],r[x,y],r[x+1,y], r[x-1,y-1],r[x,y-1],r[x+1,y-1]) if(sum(v.aux)>0){ p.aux<-v.aux/sum(v.aux) cl<-sample(classe,1,prob=p.aux) } else{ cl<-sample(classe,1) } switch(cl, MAUX[i,]<-c(x-1,y+1), MAUX[i,]<-c(x,y+1), MAUX[i,]<-c(x+1,y+1), MAUX[i,]<-c(x-1,y), MAUX[i,]<-c(x,y), MAUX[i,]<-c(x+1,y), MAUX[i,]<-c(x-1,y-1), MAUX[i,]<-c(x,y-1), MAUX[i,]<-c(x+1,y-1), ) } # fim else } # fim i M<-MAUX R[[j]]<-M } # fim j return(list("Evol"=R,"Traces"=traces,"time.step"=time.step,"time.step.adapt"=time.step.adapt)) } # teste da função mov_results <- animal.mov(n = 100, ra = obj$raster) mov_results ``` ## Individual tracks' viewer The track is registered hour by hour. ```{r} # To insert the output of the animal.mov function tracks.viewer<-function(obj=NULL, r=NULL, adapt=FALSE){ if(is.null(obj)){print("Erro. Inserir os resultados da simulação"); break} # r = valores do raster (formato de matriz) if(is.null(r)){print("Erro. Inserir os valores do raster no segundo argumento"); break} # number of animals / tracks n<-dim(obj$Evol[[1]])[1] time.step<-obj$time.step time.step.adapt<-obj$time.step.adapt tracks<-NULL for(i in 1:n){ coords<-NULL for(j in 1:time.step){ coords<-rbind(coords,obj$Evol[[j]][i,]) } tracks[[i]]<-coords } if(adapt==FALSE){ plot(flip(t(r),direction='y'))+for(i in 1:n) lines(tracks[[i]][(time.step.adapt+1):time.step,],type='l',cex=0.05,col=1)+points(tracks[[i]][time.step,1],tracks[[i]][time.step,2],cex=0.8,col=2, pch=19)} else{ plot(flip(t(r),direction='y'))+for(i in 1:n) lines(tracks[[i]][1:time.step.adapt,],type='l',cex=0.05,col=4) + lines(tracks[[i]][(time.step.adapt+1):time.step,],type='l',cex=0.05,col=1)+ points(tracks[[i]][time.step,1],tracks[[i]][time.step,2],cex=0.8,col=2,pch=19) } } # fim function # ``` ## Viewer for traces ```{r} # To insert the output of the animal.mov function traces.viewer<-function(obj=NULL, r=NULL){ if(is.null(obj)){print("Erro. Inserir os resultados da simulação"); break} # r = valores do raster (formato de matriz) if(is.null(r)){print("Erro. Inserir os valores do raster no segundo argumento"); break} #flip(t(rtest),direction='y') plot(flip(t(r),direction='y'))+points(obj$Traces,cex=0.3,pch=19,col=1) } ``` ## Make Line transects ```{r} tracks.set<-function(obj=NULL,ra=NULL,l=30,sampling="random",dir=NULL,loc=NULL, con=0.01){ # ntracks = number of transects # l = length of transects # w = width of transects # r = valores do raster (formato de matriz) if(is.null(obj)){print("Erro. Inserir o objeto tipo animal.mov"); break} if(is.null(ra)){print("Erro. Inserir os valores do raster no segundo argumento"); break} ll<-dim(ra)[1] if(is.null(dir)){dir<-runif(1,0,360)} if(is.null(loc)){loc<-round(runif(2,ll/9,ll*8/9))} if(sampling=="random"||sampling=="convenience"){ if(sampling=="random"){ # spt = NULL -> then random locations m <- matrix(0, ll, ll) # the empty landscape r <- raster(m, xmn=0, xmx=ll, ymn=0, ymx=ll) rtest<-makeLine(r, l, direction = dir, convol = con, spt = loc, edge = FALSE, bgr=0, rast = TRUE, val = 10) } else{ rtest<-makeLine(ra, l, direction = dir, convol = con, spt = loc, edge = FALSE, bgr=7, rast = TRUE, val = 10) } # end first else } else{ print("Error. Sampling design must be at random or by convenience") } # end second else area.t<-sum(values(rtest,format="matrix")==10) coverage<-area.t/(ll^2) coord<-NULL for(i in 1:ll){ for(j in 1:ll){ if(rtest[i,j]==10){coord<-rbind(coord,c(i,j))} } } traces<-din$Traces counts<-0 for(k in 1:dim(traces)[1]){ if(rtest[traces[k,1],traces[k,2]]==10){counts<-counts+1} } plot(flip(t(ra),direction='y'))+points(coord[,1],coord[,2],col="blue",pch=15,type="p",xlim=c(0,ll),ylim=c(0,ll),cex=0.5)+points(traces,pch=15,cex=0.2) return(list("transect"=rtest,"coverage"=coverage,"area"=area.t, "counts"=counts)) } ``` ## Basic Workflow ### To create scenarios / landscapes ```{r} # l.size de 500 = 50 segundos de simulação land<-land.create(l.size=500,n.patches=c(3,3,3),cover=c(0.15,0.20,0.25)) plot(land$raster) ``` ### To simulate moviments ```{r} rm(list="ra") ra<-land$raster (pop.size<-round(land$recursos*20)) # 20 foi arbitrário # Execução da rotina start_time <- Sys.time() din<-animal.mov(n=pop.size,ra=ra,time=21,where="resource") end_time <- Sys.time() end_time - start_time # traces positions #din$Traces ``` ### To visualize tracks ```{r} tracks.viewer(obj=din, r=ra, adapt=TRUE) ``` ### To visualize traces in environment ```{r} traces.viewer(obj=din,r=ra) ``` ### To set sampling transects and to count traces ```{r} tracks<-tracks.set(obj=din,ra=ra,sampling="random", l=3000,con=0.05) tracks$coverage tracks$counts ```
<template> <!-- ======= Mobile nav toggle button ======= --> <i class="bi bi-list mobile-nav-toggle d-xl-none"></i> <!-- ======= Header ======= --> <header id="header"> <div class="d-flex flex-column"> <div class="profile"> <img :src="url" alt="" class="img-fluid rounded-circle" /> <h1 class="text-light"><a href="index.html">Alex Smith</a></h1> <div class="social-links mt-3 text-center"> <a href="#" class="twitter" ><i class="bx bxl-twitter"></i ></a> <a href="#" class="facebook" ><i class="bx bxl-facebook"></i ></a> <a href="#" class="instagram" ><i class="bx bxl-instagram"></i ></a> <a href="#" class="google-plus" ><i class="bx bxl-skype"></i ></a> <a href="#" class="linkedin" ><i class="bx bxl-linkedin"></i ></a> </div> </div> <nav id="navbar" class="nav-menu navbar"> <ul> <li> <a href="#hero" class="nav-link scrollto active" ><i class="bx bx-home"></i> <span>Home</span></a > </li> <li> <a href="#about" class="nav-link scrollto" ><i class="bx bx-user"></i> <span>About</span></a > </li> <li> <a href="#resume" class="nav-link scrollto" ><i class="bx bx-file-blank"></i> <span>Resume</span></a > </li> <li> <a href="#portfolio" class="nav-link scrollto" ><i class="bx bx-book-content"></i> <span>Portfolio</span></a > </li> <li> <a href="#services" class="nav-link scrollto" ><i class="bx bx-server"></i> <span>Services</span></a > </li> <li> <a href="#contact" class="nav-link scrollto" ><i class="bx bx-envelope"></i> <span>Contact</span></a > </li> </ul> </nav> <!-- .nav-menu --> </div> </header> <!-- End Header --> </template> <script> import url from "../datas/api.json"; import axios from "axios"; import setting from "../datas/api.json"; export default { data() { return { url: "", }; }, methods: { async fetchData() { try { const res = await axios.get( "http://localhost/vuetest/public/api/profile" ); this.url = setting.api.url + "/public/assets/img/" + res.data.data[0].image; } catch (error) { console.error("Error fetching data:", error); } }, }, mounted() { this.fetchData(); }, }; </script> <style lang="scss" scoped></style>
const express = require("express") const path = require("path") require("dotenv").config() const app = express() const port = process.env.PORT || 3000 const fs = require("fs-extra") const { template } = require("lodash") const fetch = require("node-fetch") const WDS_MODE = process.argv.includes("--wds") const WDS_HOST = "http://127.0.0.1:8080" app.use("/static", express.static("./web_dist")) app.use("/public", express.static("./web/public")) const http = require("http") app.get("/s3/*", function (req, res) { http.get( process.env.IMAGES_BUCKET_URL + req.url.replace("/s3/", ""), function (proxyRes) { proxyRes.pipe(res) }, ) }) app.get("/", async (req, res) => { return res.redirect("/app/") }) app.get("/app/*", async (req, res) => { let manifest if (WDS_MODE) { manifest = await (await fetch(WDS_HOST + "/static/manifest.json")).json() Object.keys(manifest).forEach( key => (manifest[key] = `${WDS_HOST}/static/${manifest[key]}`), ) } else { manifest = await fs.readJson(path.resolve("./web_dist/manifest.json")) Object.keys(manifest).forEach( key => (manifest[key] = `/static/${manifest[key]}`), ) } const html = fs.readFileSync(path.resolve("./web/index.html.ejs"), "utf-8") const tmpl = template(html) const s = tmpl({ assets: manifest, }) res.send(s) }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
import React from 'react'; import Pagination from '../components/Pagination/Pagination'; import { useAppSelector } from '../redux/hooks'; import Container from '@mui/material/Container'; import CardList from '../components/Card/CardList'; import { User } from '../api/Models/User'; interface Props { setModalHandler: (id: number) => void; } const CardView: React.FC<Props> = ({ setModalHandler }) => { const [currentPage, setCurrentPage] = React.useState(1); const { users, searchParam } = useAppSelector((store) => ({ searchParam: store.users.searchParam, users: store.users.data, })); const filteredUsers = React.useMemo( (listArr: User[] = []) => { users.forEach((user) => { if ( user.name.toLowerCase().includes(searchParam.toLowerCase()) || user.username.toLowerCase().includes(searchParam.toLowerCase()) || user.email.toLowerCase().includes(searchParam.toLowerCase()) ) { listArr.push(user); } }); return listArr; }, [users, searchParam] ); const cutList = React.useMemo( (listArr: User[] = []) => { const cutPageItemsStart = (currentPage - 1) * 4; const cutPageItemsEnd = currentPage * 4; filteredUsers.forEach((item, index) => { if (index >= cutPageItemsStart && index < cutPageItemsEnd) { listArr.push(item); } }); return listArr; }, [filteredUsers, currentPage] ); return ( <div> <Container maxWidth="lg"> <CardList list={cutList} setModalHandler={setModalHandler} /> <Pagination currentPage={currentPage} limit={4} total={filteredUsers.length} onPageChange={(page: number) => setCurrentPage(page)} /> </Container> </div> ); }; export default CardView;
import {Request, Response, Router} from "express" import authMiddleware, {authJWTMiddleware} from "../middlewares/auth" import postsValidator from "../validators/posts.validator" import commentsValidator, {postIdValidator} from "../validators/comments.validator" import {postsService} from "../domain/posts.service" import {CommentType, PaginationResultType} from "../repositories/mongo/types" import {BloggerType, PostType} from "../repositories/types" import {bloggersService} from "../domain/bloggers.service" import {commentsService} from "../domain/comments.service" import {LoginRequest} from "../types/request.type"; export const postsRouter = Router({}) postsRouter.post( `/`, authMiddleware, [...postsValidator], async (req: Request, res: Response) => { const blogger: BloggerType | null = await bloggersService.findBloggerById(req.body.bloggerId) if (!blogger) { return res.sendStatus(404) } const newPost: PostType | null = await postsService.createPost(req.body.title, req.body.shortDescription, req.body.content, req.body.bloggerId, "Andrey Makhnev") if (!newPost) { return res.sendStatus(404) } res.status(201).send(newPost) }) postsRouter.delete( `/:id`, authMiddleware, async (req: Request, res: Response) => { const post: PostType | null = await postsService.findPostById(req.params.id) if (!post) { return res.sendStatus(404) } const isDeleted: boolean = await postsService.removePostById(req.params.id) if (!isDeleted) { res.sendStatus(404) } else { res.sendStatus(204) } } ) postsRouter.put( `/:id`, authMiddleware, [...postsValidator], async (req: Request, res: Response) => { const post: PostType | null = await postsService.findPostById(req.params.id) if (!post) { return res.sendStatus(404) } else { const blogger: BloggerType | null = await bloggersService.findBloggerById(req.body.bloggerId) if (!blogger) { return res.sendStatus(404) } const isUpdated: boolean = await postsService.updatePost(req.params.id, req.body.title, req.body.shortDescription, req.body.content, req.body.bloggerId) if (isUpdated) { return res.sendStatus(204) } else { return res.sendStatus(404) } } } ) postsRouter.get( `/`, async (req: Request, res: Response) => { const {PageNumber, PageSize} = req.query const page = PageNumber ? PageNumber : 1 const pageSize = PageSize ? PageSize : 10 const posts: PaginationResultType<PostType[]> = await postsService.findAllPosts(+page, +pageSize) res.status(200).send(posts) } ) postsRouter.get( `/:id`, async (req: Request, res: Response) => { const post: PostType | null = await postsService.findPostById(req.params.id) if (!post) { return res.sendStatus(404) } res.send(post) } ) postsRouter.post( `/:postId/comments`, authJWTMiddleware, [...commentsValidator], async (req: LoginRequest, res: Response) => { const post: PostType | null = await postsService.findPostById(req.params.postId) if (!post) { return res.sendStatus(404) } const newComment = { content: req.body.content, userId: req.user?._id, userLogin: req.user?.login, addedAt: new Date(), postId: req.params.postId } const comment: CommentType | null = await commentsService.createComment(newComment) if (!comment) { return res.sendStatus(404) } res.status(201).send(comment) } ) postsRouter.get( `/:postId/comments`, postIdValidator, async (req: Request, res: Response) => { const post: PostType | null = await postsService.findPostById(req.params.postId) if (!post) { return res.sendStatus(404) } const page: number = req.query.PageNumber ? +req.query.PageNumber : 1 const pageSize: number = req.query.PageSize ? +req.query.PageSize : 10 const comments: PaginationResultType<CommentType[]> = await commentsService.findAllComments(req.params.postId, page, pageSize) res.status(200).send(comments) } )
import axios from 'axios'; import { useState } from 'react'; import { useMutation, useQuery } from 'react-query'; import { useNavigate, useParams } from 'react-router-dom'; import { supportRoute, supporttrRoute } from 'utils/APIRoutes'; import SupportPaymentUI from './payment.presenter'; import { userState } from 'recoil/user'; import { useRecoilValue } from 'recoil'; import axiosApiInstance from 'commons/utils/axiosInstance'; import { IPayment } from './payment.types'; declare global { interface Window { IMP: { init: (arg0: string) => void; request_pay: ( arg0: { pg: string; pay_method: string; name: string; amount: string; buyer_email: string; buyer_name: string; buyer_tel: string; buyer_addr: string; }, arg1: (rsp: IPayment) => void, ) => void; }; } } export default function SupportPayment() { const { id } = useParams(); const userInfo = useRecoilValue(userState); const navigate = useNavigate(); const [selectAmount, setSelectAmount] = useState('1000'); const [isComplete, setIsComplete] = useState(false); const { data } = useQuery('detailList', async () => { const { data } = await axios.get(`${supportRoute}/${id}`); return data; }); const { mutate: supportPayment, data: paymentData } = useMutation( async (rsp: { imp_uid: string }) => { return await axiosApiInstance.post(supporttrRoute, { impUid: rsp.imp_uid, amount: Number(selectAmount), donation: id, }); }, { onSuccess: () => { setIsComplete(true); }, onError: err => { console.log(err); }, }, ); const onClickPayment = (e: { preventDefault: () => void }) => { e.preventDefault(); const IMP = window.IMP; IMP.init('imp76469515'); IMP.request_pay( { pg: 'html5_inicis', pay_method: 'card', name: '얼스마스', amount: selectAmount, buyer_email: userInfo.email, buyer_name: userInfo.name, buyer_tel: userInfo.phone, buyer_addr: userInfo.address1, }, (rsp: IPayment) => { if (rsp.success) { supportPayment(rsp); } else { alert(rsp.error_msg); navigate(`/support/${id}`); } }, ); }; return ( <SupportPaymentUI data={data} selectAmount={selectAmount} setSelectAmount={setSelectAmount} onClickPayment={onClickPayment} supportPayment={supportPayment} isComplete={isComplete} paymentData={paymentData} /> ); }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>엘리먼트 복제하기</title> <style> .selected { background-color: blue; color: white; } .head { background-color: black; color: white; } .no { background-color: yellow; } </style> <script src='jquery-1.11.1.js'></script> <script> // empty() : 콘텐츠 완전 제거 // $('<h1>'): h1 태그 생성, 끝 태그는 생략해도 된다. // $(자식).appendTo(부모) => 부모의 막내 자식으로 추가 // $(자식).prependTo(부모) => 부모의 첫째 자식으로 추가 // $(엘리먼트).insertAfter(형제) //$(부모).append(자식) //$(부모).prepend(자식) // clone() => 선택된 객체 복제한당 /* $(function() { setInterval(function() { $('img:first').clone().appendTo('body') }, 1000); }); */ </script> </head> <body> <img src=Penguins.jpg width=150> <img src=cat01.jpg width=150> <img src=dog01.jpg width=150> <img src=dog02.jpg width=150> <img src=dog03.jpg width=150> <h1>0000000000000</h1> <div id='d1'> <h2>aaaaaaaa</h2> </div> <div id='d2'> <h2>bbbbbbbb</h2> </div> <script> // Flip the flipbox from bottom to top $("flipBT").observe('click', function(){ new Flip($("flipBox"), { direction: 'bt', color: '#D46419', content: '<div class="demo-one">Hello!<br/>I\'m a flip-box!<br/> :) </div>' }); }); // Flip the flipbox from top to bottom $("flipTB").observe('click', function(){ new Flip($("flipBox"), { direction: 'tb', color: '#B34212', startSpeed: 0.6, endSpeed: 0.4, content: '<div class="demo-two">Hey!<br/><span style="font-size:14px">You can change me with<br/><code style="font-family:monospace;padding-left:10px">content: $("myId").innerHTML</code></span><br/><br/>Enjoy!</div>' }); }); // Flip the flipbox from left to right $("flipLR").observe('click', function(){ new Flip($("flipBox"), { direction: 'lr', color: '#341405', content: '<div class="demo-three">I\'m simple html!</div>' }); }); // Flip the flipbox from right to left $("flipRL").observe('click', function(){ new Flip($("flipBox"), { direction: 'rl', startSpeed: 1.0, endSpeed: 1.0, color: '#166665', content: '<div class="demo-four">' + $('logo').up('a').title + '<br/><span style="font-size:11px">This is a taken directly from this page<code style="display:block;color:#fff;padding:5px;font-family:monospace">$("logo").up("a").title</code></span></div>' }); }); // Example 1 $("flipEx1").observe('click', function(){ new Flip($("flipBox"), { direction: 'tb', startFx: Effect.Transitions.pulse, endFx: Prototype.Browser.IE ? Effect.Transitions.linear : Effect.Transitions.spring, startSpeed: 0.8, endSpeed: 0.3, color: '#341405', content: '<div class="demo-one">Example 1</div>' }); }); // Example 2 $("flipEx2").observe('click', function(){ new Flip($("flipBox"), { direction: 'bt', startFx: Effect.Transitions.circIn, endFx: Effect.Transitions.circOut, color: '#341405', content: '<div class="demo-two">Example 2</div>' }); }); // Example 3 $("flipEx2").observe('click', function(){ new Flip($("flipBox"), { startFx: Effect.Transitions.backIn, endFx: Effect.Transitions.backOut, startSpeed: 0.3, endSpeed: 0.3, color: '#166665', content: '<div class="demo-three">Example 3</div>' }); }); </script> </body> </html>
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; // Import Containers import { DefaultLayoutComponent } from './containers'; import { P404Component } from './views/error/404.component'; import { P500Component } from './views/error/500.component'; import { LoginComponent } from './views/login/login.component'; import { RegisterComponent } from './views/register/register.component'; //Form component import { ClientdashboardComponent } from './views/forms/registration/clientdashboard/clientdashboard.component'; import { UserDashboardComponent } from './views/forms/usermanager/user-dashboard/user-dashboard.component'; import {VehicleDashboardComponent} from './views/forms/registration/vehicle-dashboard/vehicle-dashboard.component'; import {ClientVehiclesComponent} from './views/forms/registration/client-vehicles/client-vehicles.component'; import {OwnerDashboardComponent} from './views/forms/registration/owner-dashboard/owner-dashboard.component'; import {NewClaimsComponent} from './views/forms/Claims/new-claims/new-claims.component'; import { NewClaimsEditorComponent} from './views/forms/Claims/new-claims-editor/new-claims-editor.component'; import {AmendClaimDashboardComponent} from './views/forms/Claims/amend-claim-dashboard/amend-claim-dashboard.component'; import { SubmitToSupervisorDashboardComponent } from './views/forms/Claims/submit-to-supervisor-dashboard/submit-to-supervisor-dashboard.component'; import { AuthoriseDashboardComponent } from './views/forms/Claims/authorise-dashboard/authorise-dashboard.component'; import { BookKeepingComponent } from './views/forms/Claims/book-keeping/book-keeping.component'; import { ContinueWithTheGroupComponent } from './views/forms/Claims/continue-with-the-group/continue-with-the-group.component'; import { ClaimListingDashboardComponent } from './views/forms/Claims/claim-listing-dashboard/claim-listing-dashboard.component'; import { OwnersNotLinkedComponent } from './views/forms/registration/owners-not-linked/owners-not-linked.component'; import { ReportViewerComponent } from './views/forms/Reports/report-viewer/report-viewer.component'; import { ReportViewerDashboardComponent } from './views/forms/Reports/report-viewer-dashboard/report-viewer-dashboard.component'; import { ClientTypeComponent } from './views/forms/Lookups/client-type/client-type.component'; import { RankTypesComponent } from './views/forms/Lookups/rank-types/rank-types.component'; import { TitleTypesComponent } from './views/forms/Lookups/title-types/title-types.component'; import { NationalityComponent } from './views/forms/Lookups/nationality/nationality.component'; import { RefundRatesComponent } from './views/forms/Lookups/refund-rates/refund-rates.component'; import { FileUploadComponent } from './views/forms/Files/file-upload/file-upload.component'; import { ReadyForPaymentComponent } from './views/forms/Claims/ready-for-payment/ready-for-payment.component'; import { FinalisedClaimsComponent } from './views/forms/Claims/finalised-claims/finalised-claims.component'; import { SearchVehicleComponent } from './views/forms/Claims/search-vehicle/search-vehicle.component'; export const routes: Routes = [ { path: '', redirectTo: 'dashboard', pathMatch: 'full', }, { path: '404', component: P404Component, data: { title: 'Page 404' } }, { path: '500', component: P500Component, data: { title: 'Page 500' } }, { path: 'login', component: LoginComponent, data: { title: 'Login Page' } }, { path: 'register', component: RegisterComponent, data: { title: 'Register Page' } }, { path: '', component: DefaultLayoutComponent, data: { title: 'Home' }, children: [ { path: 'registration/client', component: ClientdashboardComponent, data: { title: 'Client Dashboard' } }, { path: 'registration/clientVehicles/:clientId', component: VehicleDashboardComponent, data: { title: 'Vehicle Dashboard' } }, { path: 'registration/vehicles', component: ClientVehiclesComponent, data: { title: 'Vehicle Dashboard' } }, { path: 'registration/Owners', component: OwnerDashboardComponent, data: { title: 'Owners Dashboard' } }, { path: 'registration/OwnersNotLinked', component: OwnersNotLinkedComponent, data: { title: 'Owners Not Linked Dashboard' } }, { path: 'claims/readyforpayment', component: ReadyForPaymentComponent, data: { title: 'Claims Ready For Payment Dashboard' } }, { path: 'claims/searchVehicle', component: SearchVehicleComponent, data: { title: 'Search Vehicles' } }, { path: 'claims/claimListings', component: ClaimListingDashboardComponent, data: { title: 'Claim Listing Dashboard' }, runGuardsAndResolvers: 'paramsChange', }, { path: 'claims/finalisedClaims', component: FinalisedClaimsComponent, data: { title: 'Finalised Claims Dashboard' }, runGuardsAndResolvers: 'paramsChange', }, { path: 'Claims/NewClaims', component: NewClaimsComponent, data: { title: 'Register Claims Dashboard' } }, { path: 'Claims/ClaimsEditor', component: NewClaimsEditorComponent, data: { title: 'Register Claims' } }, { path: 'Claims/AmendClaim', component: AmendClaimDashboardComponent, data: { title: 'Amend Claims' } }, { path: 'Claims/ContinueWithGroup', component: ContinueWithTheGroupComponent, data: { title: 'Continue with Group' } }, { path: 'Claims/SubmitToSupervisor', component: SubmitToSupervisorDashboardComponent, data: { title: 'Submit To Supervisor' } }, { path: 'Claims/Authorise', component: AuthoriseDashboardComponent, data: { title: 'Authorise Claims' } }, { path: 'Claims/bookkeeping', component: BookKeepingComponent, data: { title: 'Bookkeeping' } }, { path: 'Reports/ReportViewer', component: ReportViewerComponent, data: { title: 'Reports Viewer' } }, { path: 'Reports/ReportViewerDashboard', component: ReportViewerDashboardComponent, data: { title: 'Reports Dashboard' } }, { path: 'Files/FileUpload', component: FileUploadComponent, data: { title: 'File Uploadwer' } }, { path: 'usermanager/UserDashboard', component: UserDashboardComponent, data: { title: 'Manage Users' } }, { path: 'Lookups/LookupClientType', component: ClientTypeComponent, data: { title: 'Manage Client Types' } }, { path: 'Lookups/RankTypes', component: RankTypesComponent, data: { title: 'Manage Rank Types' } }, { path: 'Lookups/TitleTypes', component: TitleTypesComponent, data: { title: 'Manage Title Types' } }, { path: 'Lookups/Nationality', component: NationalityComponent, data: { title: 'Manage Nationality' } }, { path: 'Lookups/RefundRates', component: RefundRatesComponent, data: { title: 'Manage Refund Rates' } }, { path: 'base', loadChildren: () => import('./views/base/base.module').then(m => m.BaseModule) }, { path: 'dashboard', loadChildren: () => import('./views/dashboard/dashboard.module').then(m => m.DashboardModule) }, { path: 'notifications', loadChildren: () => import('./views/notifications/notifications.module').then(m => m.NotificationsModule) }, ] }, { path: '**', component: P404Component } ]; @NgModule({ imports: [ RouterModule.forRoot(routes, {}) ], exports: [ RouterModule ] }) export class AppRoutingModule {}
# %% from typing import Optional import torch import torch.nn as nn from pythae.models import VAE, VAEConfig from pythae.data.datasets import BaseDataset from pythae.models.nn import BaseEncoder, BaseDecoder from pythae.models.base.base_utils import ModelOutput from pydantic.dataclasses import dataclass from pythae.pipelines import TrainingPipeline @dataclass class CVAEConfig(VAEConfig): """Configuration class for CVAE model""" channels: int = 3 image_height: int = 128 image_width: int = 128 class_size: int = 3 latent_dim: int = 10 def __post_init__(self): super().__post_init__() self.input_dim = ( self.channels * self.image_height * self.image_width + self.class_size ) class Custom_encoder(BaseEncoder): """Encoder for CVAE model Parameters ---------- args : ModelConfig Configuration class for CVAE model """ def __init__(self, args=None): BaseEncoder.__init__(self) self.layers = nn.Sequential( nn.Linear(args.input_dim, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 16), nn.ReLU(), nn.Linear(16, args.latent_dim), ) def forward(self, x: torch.Tensor) -> ModelOutput: out = self.layers(x) log_covariance = out output = ModelOutput(embedding=out, log_covariance=log_covariance) return output class Custom_decoder(BaseDecoder): """Decoder for CVAE model Parameters ---------- args : ModelConfig Configuration class for CVAE model """ def __init__(self, args=None): BaseDecoder.__init__(self) self.class_size = args.class_size self.layers = nn.Sequential( nn.Linear(args.latent_dim + args.class_size, 16), nn.ReLU(), nn.Linear(16, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, args.input_dim), nn.Sigmoid(), ) def forward(self, x: torch.Tensor) -> ModelOutput: out = self.layers(x) output = ModelOutput( reconstruction=out[:, : -self.class_size], ) return output class CVAE(VAE): def __init__( self, model_config: VAEConfig, encoder: Optional[BaseEncoder] = None, decoder: Optional[BaseDecoder] = None, ): super().__init__(model_config, encoder, decoder) self.model_name = "CVAE" self.input_dim = model_config.input_dim self.class_size = model_config.class_size self.encoder = encoder self.decoder = decoder def conditional_encoder(self, x, y): inputs = torch.cat([x, y], 1) # (bs, feature_size+class_size) return self.encoder(inputs) def conditional_decoder(self, z, y): inputs = torch.cat([z, y], 1) # (bs, latent_size+class_size) return self.decoder(inputs) def forward(self, inputs: BaseDataset, **kwargs): """ Forward pass of the model Args: inputs (BaseDataset): input data **kwargs: additional arguments Returns: ModelOutput: model outputs """ x = inputs.data # image y = inputs.labels # one-hot encoding encoder_output = self.conditional_encoder(x, y) mu, log_var = encoder_output.embedding, encoder_output.log_covariance std = torch.exp(0.5 * log_var) z, _ = self._sample_gauss(mu, std) recon_x = self.conditional_decoder(z, y)["reconstruction"] loss, recon_loss, kld = self.loss_function(recon_x, x, mu, log_var, z) output = ModelOutput( recon_loss=recon_loss, reg_loss=kld, loss=loss, recon_x=recon_x, z=z, ) return output if __name__ == "__main__": cvae_config = CVAEConfig( latent_dim=10, class_size=3, ) # Generate random data n_samples = 100 x = torch.randn(n_samples, 3, 128, 128).view(n_samples, -1) y = torch.randn(n_samples, 3) inputs = BaseDataset(data=x, labels=y) encoder = Custom_encoder(cvae_config) decoder = Custom_decoder(cvae_config) # # Test encoder # encoder_input = torch.cat([x, y], 1) # encoder_output = encoder(encoder_input)["embedding"] # decoder_input = torch.cat([encoder_output, y], 1) # decoder_output = decoder(decoder_input)["reconstruction"] # print(decoder_output.shape) # # Test forward pass # model = CVAE(cvae_config, encoder, decoder) # model_output = model(inputs) # print(model_output.keys()) # Build the model model = CVAE(model_config=cvae_config, encoder=encoder, decoder=decoder) # Build the Pipeline pipeline = TrainingPipeline(model=model) pipeline( train_data=inputs, # eval_data=inputs, )
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style rel="stylesheet" type="text/css"> .leftPanel { width: 300px; height: 600px; border: 1px solid #ccc; float:left; margin-right:20px; } .contentPanel { width: 800px; height: 600px; border: 1px solid #ccc; float:left; } </style> <script src="js/jquery-1.11.3/jquery.js"></script> <script> //成功时设置目标div的内容 function success(text, target) { $(target).html(text); } //出错时的处理 function fail(code, target) { $(target).html('Error code: ' + code); } //构造访问路径 function consPath(file) { var path = "http://"; path = path + window.location.host; var pathname = window.location.pathname; path = path + pathname.substr(0, pathname.lastIndexOf("/")) + "/" + file; return path; } //获取file内容,并显示在id为target的元素中 function getContent(file, target) { file = consPath(file); var request = new XMLHttpRequest(); // 新建XMLHttpRequest对象 request.onreadystatechange = function () { // 状态发生变化时,函数被回调 if (request.readyState === 4) { // 成功完成 // 判断响应结果: if (request.status === 200) { // 成功,通过responseText拿到响应的文本: return success(request.responseText, target); } else { // 失败,根据响应码判断失败原因: return fail(request.status); } } else { // HTTP请求还在继续... } } // 发送请求: request.open('GET', file); request.send(); } </script> </head> <body> <div class="leftPanel"> <a href="#" onclick="getContent('content.html','#target')">点我会把我超链的内容显示在下面的div中</a> </div> <div class='contentPanel' id="target"></div> </body> </html>
export interface Project { name: string; status: string; role: string; stack: string[]; description: string; logo: string; links: { label: string; href: string; }[]; } export const PROJECTS: Project[] = [ { name: 'VinoSeeker', role: 'Full Stack Developer', status: 'Ongoing', stack: [ 'JavaScript', 'React', 'Redux', 'Ionic', 'SASS', 'Tailwind', 'Node.js', 'Express.js', 'PostgreSQL', ], description: 'A geo-social networking service that allows users to discover wines and wineries, record their experiences, and share with friends.', logo: '/logos/vinoseeker.png', links: [ { label: 'vinoseeker.com', href: 'https://vinoseeker.com/' } ], }, { name: 'Cranberry', role: 'Side Project', status: 'Ongoing', stack: [ 'TypeScript', 'React', 'Redux', 'C#', '.NET', 'EF Core', 'MySQL' ], description: 'A play on "quitting cold turkey," Cranberry is a daily tracker with motivating metrics to help users quit smoking.', logo: '/logos/cranberry.png', links: [ { label: 'cranberry.onrender.com', href: 'http://cranberry-axec.onrender.com/', }, { label: 'github.com', href: 'https://github.com/jfpalchak/cranberry' }, ], }, { name: 'EOL Messenger', role: 'Side Project', status: '2023', stack: [ 'JavaScript', 'C#', '.NET', 'SignalR', 'EF Core', 'MySQL' ], description: 'An early 2000\'s inspired public chat room, with user-to-user private chats.', logo: '/logos/eol.svg', links: [ { label: 'eol-app.onrender.com', href: 'https://eol-app.onrender.com/' }, { label: 'github.com', href: 'https://github.com/jfpalchak/EOL.Solution', }, ], }, { name: 'Dungeon Adventure', role: 'Side Project', status: '2023', stack: [ 'JavaScript', 'Bootstrap', 'HTML/CSS', 'webpack', 'babel' ], description: 'A text-based adventure game, where the user navigates and interacts with the world via text input.', logo: '/logos/adventure.svg', links: [ { label: 'github.io/text-adventure', href: 'https://jfpalchak.github.io/text-adventure/', }, { label: 'github.com', href: 'https://github.com/jfpalchak/text-adventure', }, ], }, ];
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var RecordSchema = new Schema({ created: { type: Date, default: Date.now }, active: { type: Boolean, default: true }, group_id: { type: Number, required: 'Group ID is required' }, territory_id: { type: Number }, contact_name: { type: String }, address: { type: String, required: 'Address is required', default: '', trim: true }, address2: { type: String, default: '', trim: true }, city: { type: String, required: 'City is required', default: '', trim: true }, state: { type: String, enum: ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'], uppercase: true, required: 'Select a valid state' }, phone: { type: String, default: '', trim: true }, notes: { type: String, default: '', trim: true }, location: { type: [Number], index: '2dsphere' } }); mongoose.model('Record', RecordSchema);
import { ProductsController } from '../controllers/products'; import { ProductsImagesController } from '../controllers/productsImages'; import { OrdersRabbitmqController } from '../controllers/ordersRabbitmq'; import { CustomersController } from '../controllers/customers'; import { OrdersController } from '../controllers/orders'; import { type DbConnection } from '../../domain/interfaces/dbconnection'; import express, { type RequestHandler, type Request, type Response } from 'express'; import bodyParser from 'body-parser'; import cors from 'cors'; import { Global } from '../adapters'; import { swaggerSpec } from '../../infrastructure/swagger/swagger'; import path from 'path'; export class FastfoodApp { private readonly _dbconnection: DbConnection; private readonly _rabbitMqService: any; public readonly _app = express(); private server: any = null; constructor (dbconnection: DbConnection, rabbitMQService: any) { this._dbconnection = dbconnection; this._rabbitMqService = rabbitMQService; void OrdersRabbitmqController.startConsuming(this._dbconnection, this._rabbitMqService); this._app = express(); } start (): void { this._app.use(cors()); this._app.use(bodyParser.json({ limit: '10mb' })); this._app.disable('x-powered-by'); this._app.use( (err: any, req: Request, res: Response, next: express.NextFunction) => { res.setHeader('Connection', 'keep-alive'); res.setHeader('Keep-Alive', 'timeout=30'); res.setHeader('Content-Security-Policy', "default-src 'self'"); res.setHeader('X-Content-Type-Options', 'nosniff'); if (err instanceof SyntaxError && err.message.includes('JSON')) { const errorGlobal: any = Global.error( 'O body não esta em formato JSON, verifique e tente novamente.', 400 ); return res.status(errorGlobal.statusCode || 404).send(errorGlobal); } else { next(); } } ); const port = process.env.PORT ?? 8080; this._app.get('/swagger.json', (req: Request, res: Response) => { res.setHeader('Content-Type', 'application/json'); res.send(swaggerSpec); }); // eslint-disable-next-line @typescript-eslint/no-var-requires const swaggerUi = require('swagger-ui-express'); this._app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); this._app.get('/', (async (_req: Request, res: Response): Promise<void> => { res.status(200).send(JSON.stringify({ service: 'Orders', version: 'TC-5' })); }) as RequestHandler); this._app.get('/painel', (async (_req: Request, res: Response): Promise<void> => { const filePath = path.join( path.resolve(__dirname, '../../'), 'Painel.html' ); res.sendFile(filePath); }) as RequestHandler); /** * @swagger * /products: * get: * summary: Retorna a listagem de produtos cadastrados * tags: * - Products * parameters: * - name: category * in: query * description: categoria do produto (opcional) * required: false * schema: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: array * items: * type: object * properties: * _id: * type: string * _name: * type: string * _price: * type: number * _category: * type: string * _description: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.get('/products', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { category } = req.query; const products = await ProductsController.getProducts( category, this._dbconnection ); res.status(products.statusCode || 404).send(products); }) as RequestHandler); /** * @swagger * /products/:id: * get: * summary: Retorna um produto cadastrados * tags: * - Products * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do produto a ser localizado * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _name: * type: string * _price: * type: number * _category: * type: string * _description: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.get('/products/:id', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const products = await ProductsController.getProductsById( id, this._dbconnection ); res.status(products.statusCode || 404).send(products); }) as RequestHandler); /** * @swagger * /products: * post: * summary: Cadastra um novo produto * tags: * - Products * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * name: * type: string * price: * type: number * category: * type: string * description: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _name: * type: string * _price: * type: number * _category: * type: string * enum: [ACCOMPANIMENT, DESSERT, DRINK, SNACK] * _description: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.post('/products', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { name, price, category, description } = req.body; const products = await ProductsController.setProduct( name, price, category, description, this._dbconnection ); res.status(products.statusCode || 404).send(products); }) as RequestHandler); /** * @swagger * /products/:id: * put: * summary: Atualiza um produto especifico * tags: * - Products * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do produto a ser localizado * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * name: * type: string * price: * type: number * category: * type: string * description: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _name: * type: string * _price: * type: number * _category: * type: string * enum: [ACCOMPANIMENT, DESSERT, DRINK, SNACK] * _description: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.put('/products/:id', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const { name, price, category, description } = req.body; const products = await ProductsController.updateProduct( id, name, price, category, description, this._dbconnection ); res.status(products.statusCode || 404).send(products); }) as RequestHandler); /** * @swagger * /products/:id: * delete: * summary: Remove um produto especifico * tags: * - Products * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do produto a ser localizado * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.delete('/products/:id', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const products = await ProductsController.removeProductsById( id, this._dbconnection ); res.status(products.statusCode || 404).send(products); }) as RequestHandler); /** * @swagger * /orders: * post: * summary: Cadastra um novo pedido * tags: * - Orders * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * customerId: * type: string * orderItens: * type: array * items: * type: object * properties: * productId: * type: string * quantity: * type: number * obs: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _protocol: * type: number * _customerId: * type: string * _status: * type: string * _payment: * type: string * _itens: * type: array * items: * type: object * properties: * _id: * type: string * _orderId: * type: string * _productId: * type: string * _price: * type: number * _quantity: * type: number * _obs: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.post('/orders', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { customerId, orderItens } = req.body; const order = await OrdersController.setOrder( customerId, orderItens, this._dbconnection, this._rabbitMqService ); res.send(order); }) as RequestHandler); /** * @swagger * /orders/open: * get: * summary: Retorna os pedidos com suas descrições, ordenados por recebimento e status, podendo ser alterado via parametro se ordena por recebimento ou status individualmente também. * tags: * - Orders * parameters: * - in: query * name: column * required: false * schema: * type: string * enum: * - status * - created_at * description: coluna a ser ordenada * - in: query * name: order * required: false * schema: * type: string * enum: * - asc * - desc * description: tipo de ordenação (asc ou desk) * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: array * items: * type: object * properties: * _id: * type: string * _protocol: * type: number * _customerId: * type: string * _status: * type: string * _payment: * type: string * _itens: * type: array * items: * type: object * properties: * _id: * type: string * _orderId: * type: number * _productId: * type: string * _price: * type: number * _quantity: * type: number * _obs: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.get('/orders/open', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { status } = req.params; const products = await OrdersController.getOrdersByOpen( status, this._dbconnection ); res.send(products); }) as RequestHandler); /** * @swagger * /orders/status/:status: * get: * summary: Retorna os pedidos por status * tags: * - Orders * parameters: * - in: path * name: status * required: true * schema: * type: string * description: status do pedido a ser listado * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: array * items: * type: object * properties: * _id: * type: string * _protocol: * type: number * _customerId: * type: string * _status: * type: string * _payment: * type: string * _itens: * type: array * items: * type: object * properties: * _id: * type: string * _orderId: * type: number * _productId: * type: string * _price: * type: number * _quantity: * type: number * _obs: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.get( '/orders/status/:status', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { status } = req.params; const products = await OrdersController.getOrdersByStatus( status, this._dbconnection ); res.send(products); } ) as RequestHandler); /** * @swagger * /orders/:id: * put: * summary: Atualiza o status de um pedido * tags: * - Orders * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do pedido a ser atualizado * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * status: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _protocol: * type: number * _customerId: * type: string * _status: * type: string * _payment: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.put('/orders/:id', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const { status, payment, paymentReference, productionReference } = req.body; const products = await OrdersController.updateOrder( id, '', status, payment || null, paymentReference ?? '', productionReference ?? '', this._rabbitMqService, this._dbconnection ); res.send(products); }) as RequestHandler); /** * @swagger * /orders/:id/payment: * put: * summary: Atualiza o pagamento de um pedido * tags: * - Orders * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do pedido a ser atualizado * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * payment: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _protocol: * type: number * _customerId: * type: string * _status: * type: string * _payment: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.put( '/orders/:id/payment', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const { payment, paymentReference, productionReference } = req.body; const products = await OrdersController.updatePaymentOrder( id, payment, paymentReference, productionReference, this._dbconnection ); res.send(products); } ) as RequestHandler); /** * @swagger * /orders/:id: * get: * summary: Retorna os pedidos por id * tags: * - Orders * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do pedido a ser listado * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _protocol: * type: number * _customerId: * type: string * _status: * type: string * _itens: * type: array * items: * type: object * properties: * _id: * type: string * _orderId: * type: number * _productId: * type: string * _price: * type: number * _quantity: * type: number * _obs: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.get('/orders/:id', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const products = await OrdersController.getOrdersById( id, this._dbconnection ); res.send(products); }) as RequestHandler); /** * @swagger * /orders/:id: * delete: * summary: Remove um pedido especifico * tags: * - Orders * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do pedido a ser removido * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.delete('/orders/:id', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const products = await OrdersController.removeOrdersById( id, this._dbconnection ); res.send(products); }) as RequestHandler); /** * @swagger * /products/:id/images: * get: * summary: Retorna as imagens de um produto cadastrado * tags: * - ProductsImages * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do produto a ser localizado as imagesns * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: array * items: * type: object * properties: * _id: * type: string * _productId: * type: string * _name: * type: string * _size: * type: number * _type: * type: string * _base64: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ // eslint-disable-next-line @typescript-eslint/no-misused-promises this._app.get( '/products/:id/images', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const products = await ProductsImagesController.getProductsImagesByProductId( { productId: id }, this._dbconnection ); res.send(products); } ) as RequestHandler); /** * @swagger * /products/:id/images: * post: * summary: Cadastra uma imagem dentro de um produto * tags: * - ProductsImages * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do produto a ser cadastrado a imagem * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * name: * type: string * size: * type: number * type: * type: string * base64: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _name: * type: string * _price: * type: number * _category: * type: string * enum: [ACCOMPANIMENT, DESSERT, DRINK, SNACK] * _description: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.post( '/products/:id/images', // eslint-disable-next-line @typescript-eslint/no-misused-promises (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const { name, size, type, base64 } = req.body; const products = await ProductsImagesController.setProductImage( id, name, size, type, base64, this._dbconnection ); res.send(products); } ) as RequestHandler); /** * @swagger * /products/:id/images/:imageId: * get: * summary: Retorna uma imagen especifica de um produto cadastrado * tags: * - ProductsImages * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do produto a ser localizado a imagem * - in: path * name: imageId * required: true * schema: * type: string * description: id da imagem a ser localizada dentro do produto * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: array * items: * type: object * properties: * _id: * type: string * _productId: * type: string * _name: * type: string * _size: * type: number * _type: * type: string * _base64: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.get( '/products/:id/images/:imageId', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id, imageId } = req.params; const products = await ProductsImagesController.getProductsImagesByProductId( { _id: imageId, productId: id }, this._dbconnection ); res.send(products); } ) as RequestHandler); /** * @swagger * /products/:id/images/:imageId: * put: * summary: Atualiza uma imagem dentro de um produto * tags: * - ProductsImages * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do produto a ser localizado a imagem * - in: path * name: imageId * required: true * schema: * type: string * description: id da imagem a ser atualizada dentro do produto * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * name: * type: string * size: * type: number * type: * type: string * base64: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _name: * type: string * _price: * type: number * _category: * type: string * enum: [ACCOMPANIMENT, DESSERT, DRINK, SNACK] * _description: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.put( '/products/:id/images/:imageId', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id, imageId } = req.params; const { name, size, type, base64 } = req.body; const products = await ProductsImagesController.updateProductImage( imageId, id, name, size, type, base64, this._dbconnection ); res.send(products); } ) as RequestHandler); /** * @swagger * /products/:id/images/:imageId: * delete: * summary: Remove uma imagem dentro de produto especifico * tags: * - ProductsImages * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do produto a ser localizado * - in: path * name: imageId * required: true * schema: * type: string * description: id da imagem a ser removida dentro do produto * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.delete( '/products/:id/images/:imageId', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { imageId } = req.params; const products = await ProductsImagesController.removeProductsImagesById( imageId, this._dbconnection ); res.send(products); } ) as RequestHandler); /** * @swagger * /customers: * get: * summary: Retorna a listagem de clientes cadastrados * tags: * - Customers * parameters: * - name: cpf * in: query * description: cpf (opcional) * required: false * schema: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: array * items: * type: object * properties: * _id: * type: string * _name: * type: string * _mail: * type: string * _cpf: * type: number * _birthdate: * type: date * _subscription: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.get('/customers', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { cpf } = req.query; const products = await CustomersController.getCustomers( cpf, this._dbconnection ); res.send(products); }) as RequestHandler); /** * @swagger * /customers/:id: * get: * summary: Retorna um cliente cadastrados * tags: * - Customers * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do cliente a ser localizado * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _name: * type: string * _mail: * type: string * _cpf: * type: number * _birthdate: * type: date * _subscription: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.get('/customers/:id', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const products = await CustomersController.getCustomersById( id, this._dbconnection ); res.send(products); }) as RequestHandler); /** * @swagger * /customers: * post: * summary: Cadastra um novo cliente * tags: * - Customers * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * name: * type: string * mail: * type: string * cpf: * type: number * birthdate: * type: date * phone: * type: string * subscription: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _name: * type: string * _mail: * type: string * _cpf: * type: number * _birthdate: * type: date * _subscription: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.post('/customers', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { name, mail, cpf, birthdate, phone, subscription } = req.body; const products = await CustomersController.setCustomer( name, mail, cpf, birthdate, phone, subscription, this._dbconnection ); res.send(products); }) as RequestHandler); /** * @swagger * /customers/:id: * put: * summary: Atualiza um cliente especifico * tags: * - Customers * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do cliente a ser atualizado * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * name: * type: string * mail: * type: string * cpf: * type: number * birthdate: * type: date * subscription: * type: string * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: object * properties: * _id: * type: string * _name: * type: string * _mail: * type: string * _cpf: * type: number * _birthdate: * type: date * _subscription: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.put('/customers/:id', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const { name, mail, cpf, birthdate, phone, subscription } = req.body; const products = await CustomersController.updateCustomer( id, name, mail, cpf, birthdate, phone, subscription, this._dbconnection ); res.send(products); }) as RequestHandler); /** * @swagger * /customers/:id: * delete: * summary: Remove um cliente especifico * tags: * - Customers * parameters: * - in: path * name: id * required: true * schema: * type: string * description: id do cliente a ser removido * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * data: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.delete('/customers/:id', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); const { id } = req.params; const products = await CustomersController.removeCustomersById( id, this._dbconnection ); res.send(products); }) as RequestHandler); /** * @swagger * /customers/lgpd: * post: * summary: Efetua remoção de dasos sensiveis solicitados pelo cliente * tags: * - Customers * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * cpf: * type: number * remove_name: * type: boolean * remove_phone: * type: boolean * remove_mail: * type: boolean * remove_all: * type: boolean * responses: * 200: * description: Successful response * content: * application/json: * schema: * type: object * properties: * status: * type: string * 404: * description: Products not found * content: * application/json: * schema: * type: object * properties: * status: * type: string * message: * type: string */ this._app.post('/customers/lgpd', (async (req: Request, res: Response): Promise<void> => { res.setHeader('Content-type', 'application/json'); // eslint-disable-next-line @typescript-eslint/naming-convention const { cpf, remove_name, remove_phone, remove_mail, remove_all } = req.body; const customers = await CustomersController.getCustomers( cpf, this._dbconnection ); const count = customers?.data?.length ?? 0; if (count > 0) { for (const customer of customers?.data) { if (remove_all) { await CustomersController.removeCustomersById( customer?._id, this._dbconnection ); } else { await CustomersController.updateCustomer( customer?._id, remove_name ? ' ' : customer?._name, remove_mail ? ' ' : customer?._mail, customer?._cpf, customer?._birthdate, remove_phone ? ' ' : customer?._phone, customer?._subscription, this._dbconnection ); } } } res.send({ statusCode: 200, status: 'success', data: { affected: count } }); }) as RequestHandler); this._app.use((req, res) => { res.status(404).send(''); }); this.server = this._app.listen(port, () => { }); this.server.keepAliveTimeout = 30 * 1000; this.server.headersTimeout = 35 * 1000; } stop (): void { this.server.close(); } }
import React, { useState, useRef, useEffect } from 'react'; import axios from 'axios'; import Button from 'react-bootstrap/Button'; import Modal from 'react-bootstrap/Modal'; import CompanyForm from '@components/CompanyForm'; import Col from 'react-bootstrap/Col'; import Form from 'react-bootstrap/Form'; import Row from 'react-bootstrap/Row'; import useGetData from '@hooks/useGetData'; import endPoints from '@services/api'; import { addCompany, updateCompany, deleteCompany } from '@services/api/companies'; import styles from '@styles/Modal.module.scss' import styles2 from '@styles/ModalForm.module.scss'; function CompanyModal(props) { const cities = useGetData(endPoints.cities.getCities); const formRef = useRef(null); const [city, setCity] = useState(null); const [ID, setID] = useState(null); const modalOpened = () => { setID(props.id); } const handleSubmit = (e) => { e.preventDefault(); const formData = new FormData(formRef.current); const data = { id: ID, name: formData.get('name'), city: city, direction: formData.get("direction"), email: formData.get("email"), phone: formData.get("phone") } if (props.editing === "true") { console.log("UPDATING") console.log(data) updateCompany(data).then((response) => { console.log(response); }) } else { console.log("POSTING") addCompany(data).then((response) => { console.log(response); }) } } return ( <Modal {...props} className={styles.modalContainer} size="xl" aria-labelledby="contained-modal-title-vcenter" centered onShow={() => modalOpened()} > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter"> {props.data ? `Editar "${props.data}"` : "Nueva compañía"} </Modal.Title> </Modal.Header> <Modal.Body> <Form ref={formRef} onSubmit={handleSubmit}> <Row className="mb-4"> <Form.Group as={Col} controlId="formGridName"> <Form.Label>Nombre</Form.Label> <Form.Control name="name" type="text" /> </Form.Group> <Form.Group value={city} onChange={(e) => setCity(e.target.value)} as={Col} controlId="formGridCity"> <Form.Label>Ciudad</Form.Label> <Form.Select defaultValue="Seleccionar..."> {cities.map(data => ( <option>{data.Name}</option> )) } </Form.Select> </Form.Group> <Form.Group as={Col} controlId="formGridJob"> <Form.Label>Dirección</Form.Label> <Form.Control name="direction" type="text" /> </Form.Group> <Form.Group as={Col} controlId="formGridEmail"> <Form.Label>Email</Form.Label> <Form.Control name="email" type="text" /> </Form.Group> <Form.Group as={Col} controlId="formGridCompany"> <Form.Label>Teléfono</Form.Label> <Form.Control name="phone" type="text" /> </Form.Group> </Row> <Button className={styles2.addContact} variant="primary" type="submit" onClick={props.onHide}> Guardar Compañía </Button> </Form> </Modal.Body> <Button className={styles.deleteContact} variant="light" onClick={props.onHide}>Eliminar Compañía</Button>{' '} <Modal.Footer> </Modal.Footer> </Modal> ); } export default CompanyModal;
// Leetcode 1609 // This can be solved using left to right (BFS) - this will be more easier // This can be solved recursive way // Recursive solution (DFS) using extra space (unordered_map) class Solution { public: bool dfs(TreeNode *root, int level, unordered_map<int, int> &mp) { if(!root) return true; int value = root->val; if(((level+1)%2)!=(value%2)) return false; if(mp.find(level)!=mp.end()) { if(level%2==0 && mp[level]>=value) return false; if(level%2==1 && mp[level]<=value) return false; } mp[level] = value; int l = dfs(root->left, level+1, mp); if(!l) return false; int r = dfs(root->right, level+1, mp); return (l && r); } bool isEvenOddTree(TreeNode* root) { if(!root) return true; unordered_map<int, int> mp; return dfs(root, 0, mp); } }; // Traverse through left to right (BFS) class Solution { public: bool isEvenOddTree(TreeNode* root) { if(!root) return true; queue<TreeNode*>q; q.push(root); bool isEven = true; int prev; while(!q.empty()) { int size = q.size(); for(int i=0; i<size; ++i) { TreeNode *curr = q.front(); q.pop(); int value = curr->val; if(isEven) { if(value%2==0) return false; if(i && (prev>=value)) return false; } else { if(value%2==1) return false; if(i && (prev<=value)) return false; } if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); prev = value; } isEven = isEven ? false : true; } return true; } }; // Traverse through right to left class Solution { public: bool isEvenOddTree(TreeNode* root) { if(!root) return true; queue<TreeNode*>q; q.push(root); bool isEven = true; int prev; while(!q.empty()){ int t = q.size(); for(int i=t-1; i>=0; --i) { TreeNode *curr = q.front(); int value = curr->val; q.pop(); if(isEven) { if(value%2==0) return false; if(i!=t-1 && (value>=prev)) return false; } else { if(value%2==1) return false; if(i!=t-1 && (value<=prev)) return false; } prev = value; if(curr->right) q.push(curr->right); if(curr->left) q.push(curr->left); } isEven = isEven ? false : true; } return true; } };
import tabula import requests import tempfile import pandas as pd def intervalo_esperado_portaria_parse(df): #intervalo minimois between a [ and a ; df["min_esperado"] = df["Intervalo esperado"].str.extract(r"\[(.*?);") #intervalo maximo is between a ; and a ] df["max_esperado"] = df["Intervalo esperado"].str.extract(r";(.*?)\]") return df def intervalo_aceitavel_portaria_parse(df): #intervalo minimois between a [ and a ; df["min_aceitavel"] = df["Intervalo aceitável"].str.extract(r"\[(.*?);") # ge the sencond part of the string after the U df["max_aceitavel"] = df["Intervalo aceitável"].str.split("U").str[1] df["max_aceitavel"] = df["max_aceitavel"].str.extract(r"\;(.*?)]") return df def download_and_extract_table(url, pages): """ Função para extrair tabelas de um documento pdf e juntar num dataframe :param pages: paginas do documento pdf a extrair as tabelas :return: dataframe com as tabelas extraidas """ with tempfile.TemporaryDirectory() as tmpdirname: response = requests.get(url, timeout=10) # Add timeout argument here pdf_path = f"{tmpdirname}/file.pdf" with open(pdf_path, "wb") as f: f.write(response.content) list_df = tabula.read_pdf(pdf_path, pages=pages) df = pd.concat(list_df) df.reset_index(drop=True, inplace=True) return df def preprocess_idg(df): """ Função para pré-processar o dataframe que tem infomração sobre os indicadores com impacto no IDG """ # colect all the cells in the dataframe that has only numbers and no text # these cells are the id of the indicators # create a list with the id of the indicators # print(df["Unnamed: 3"].loc[7]) return df def process_portaria_411a_2023(df): df = pd.DataFrame(df) #rename columns df.rename(columns={ "Unnamed: 0": "Dimensão", "N.o": "id", "Unnamed: 1": "Nome", "Unnamed: 2": "Ponderação", "Valores": "Intervalo esperado", "Variações": "Intervalo aceitável", }, inplace=True) # remover as linhas que não interessam df.drop([0,1], axis=0, inplace=True) # reset index df.reset_index(drop=True, inplace=True) # remove " . . . " from "Dimensão" column and "Nome" column df["Dimensão"] = df["Dimensão"].str.replace(" .", "") df["Nome"] = df["Nome"].str.replace(" .", "") # remove all lines that have <NA> df.dropna(axis=0, inplace=True) # adicionar uma linha que não foi lida automaticamente df.loc[41] = ["Gestão da Doença", "261", "Utentes com avaliação do risco de úlcera de pé", "1,5", "[87;100]", "[70;87[U]100;100]"] # remove " caracter from "Ponderação" column df["Ponderação"] = df["Ponderação"].str.replace('"', '') # extract the min and max values from "intervalos" into 4 new columns df = intervalo_esperado_portaria_parse(df) df = intervalo_aceitavel_portaria_parse(df) # substitute , to . so it can be converted to float in ponderacao and intervalo_esperado_minimo, intervalo_esperado_maximo, intervalo_aceitavel_minimo, intervalo_aceitavel_maximo df["Ponderação"] = df["Ponderação"].str.replace(",", ".") df["min_esperado"] = df["min_esperado"].str.replace(",", ".") df["max_esperado"] = df["max_esperado"].str.replace(",", ".") df["min_aceitavel"] = df["min_aceitavel"].str.replace(",", ".") df["max_aceitavel"] = df["max_aceitavel"].str.replace(",", ".") return df
<?php namespace admin; use \View; use \Response; use \Input; use \Validator; use \Redirect; use \Config; class OptionsController extends \admin\BaseController { /** * Option Repository * * @var Option */ protected $option; public function __construct(Option $option) { $this->option = $option; } /** * Display a listing of the resource. * * @return Response */ public function index() { $options = $this->option->all(); return View::make('admin.options.index', compact('options')); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return View::make('admin.options.create'); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $input = Input::all(); $validation = Validator::make($input, Option::$rules); if ($validation->passes()) { $this->option->create($input); return Redirect::route('admin.options.index'); } return Redirect::route('admin.options.create') ->withInput() ->withErrors($validation) ->with('message', 'There were validation errors.'); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { $option = $this->option->findOrFail($id); return View::make('admin.options.show', compact('option')); } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { $option = $this->option->find($id); if (is_null($option)) { return Redirect::route('admin.options.index'); } return View::make('admin.options.edit', compact('option')); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $input = array_except(Input::all(), '_method'); $validation = Validator::make($input, Option::$rules); if ($validation->passes()) { $option = $this->option->find($id); $option->update($input); return Redirect::route('admin.options.show', $id); } return Redirect::route('admin.options.edit', $id) ->withInput() ->withErrors($validation) ->with('message', 'There were validation errors.'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { $this->option->find($id)->delete(); return Redirect::route('admin.options.index'); } }
import { Entity } from "../entities/entity"; // Basic repo operations declarations export interface RepositoryInterface<E extends Entity<object>> { insert(entity: E): Promise<void> findById(id: string): Promise<E> findAll(): Promise<E[]> update(entity: E): Promise<void> delete(id: string): Promise<void> } export type SortDirection = 'asc' | 'desc'; export type SearchProps = { page?: number perPage?: number sort?: string | null sortDir?: SortDirection | null filter?: string | null } export type SearchResultProps<E extends Entity<object>> = { items: E[] total: number currentPage: number perPage: number sort: string | null sortDir: SortDirection | null filter: string | null } export class SearchParams { protected _page: number = 1 protected _perPage: number = 10 protected _sort: string | null protected _sortDir: SortDirection | null protected _filter: string | null constructor(props: SearchProps = {}) { Object.assign(this, props); } get page() { return this._page; } private set page(value: number) { this._page = value; } get perPage() { return this._perPage; } private set perPage(value: number) { this._perPage = value; } get sort() { return this._sort; } private set sort(value: string | null) { this._sort = value; } get sortDir() { return this._sortDir; } private set sortDir(value: SortDirection | null) { this._sortDir = value; } get filter() { return this._filter; } private set filter(value: string | null) { this._filter = value; } } export class SearchResult<E extends Entity<object>> { readonly items: E[] readonly total: number readonly currentPage: number readonly perPage: number readonly lastPage: number readonly sort: string | null readonly sortDir: SortDirection | null readonly filter: string | null constructor(props: SearchResultProps<E>) { Object.assign(this, props); this.lastPage = Math.ceil(this.total / this.perPage); } toJSON(forceJsonEntity = false) { return { items: forceJsonEntity ? this.items.map(item => { item.toJSON(); }) : this.items, total: this.total, currentPage: this.currentPage, perPage: this.perPage, lastPage: this.lastPage, sort: this.sort, sortDir: this.sortDir, filter: this.filter, }; } } // Searchable repo operations declarations export interface SearchableRepositoryInterface< E extends Entity<object>, PaginationInput = SearchParams, PaginationOutput = SearchResult<E>, > extends RepositoryInterface<E> { search(searchProps: PaginationInput): Promise<PaginationOutput> }
'use strict'; const mongoose = require('mongoose') const validator = require('validator') const bcrypt = require('bcryptjs') // Making a Mongoose model a little differently: a Mongoose Schema // Allows us to add additional functionality. const UserSchema = new mongoose.Schema({ name: { type: String, required: true, minlength: 1, trim: true, }, username:{ type:String, required:true, minlength:1, trim: true, unique: true }, password: { type: String, required: true, minlength: 1 }, phoneNumber: { type: String, required: true, minlength: 5 }, houses: [String] }) // An example of Mongoose middleware. // This function will run immediately prior to saving the document // in the database. UserSchema.pre('save', function(next) { const user = this; // binds this to User document instance // checks to ensure we don't hash password more than once if (user.isModified('password')) { // generate salt and hash the password bcrypt.genSalt(10, (err, salt) => { bcrypt.hash(user.password, salt, (err, hash) => { user.password = hash next() }) }) } else { next() } }) UserSchema.statics.findByUsernamePassword = function (username, password) { const User = this; // binds this to the User model // First find the user by their email return User.findOne({ username: username }).then((user) => { if (!user) { return Promise.reject(); // a rejected promise } // if the user exists, make sure their password is correct return new Promise((resolve, reject) => { bcrypt.compare(password, user.password, (err, result) => { if (result) { resolve(user); } else { reject(); } }); }); }); }; // make a model using the User schema const User = mongoose.model('User', UserSchema) module.exports = { User, UserSchema }
import React from 'react'; import '../styles/favourites.css'; import CommonSection from '../components/UI/CommonSection'; import Helmet from '../components/Helmet/Helmet'; import { Container, Row, Col } from 'reactstrap'; import { motion } from "framer-motion"; import { favActions } from '../redux/slices/favSlice'; import { useSelector, useDispatch } from 'react-redux'; import { Link } from 'react-router-dom'; const Favourites = () => { const favItems = useSelector(state => state.favourites.favItems); const totalAmount = useSelector(state => state.favourites.totalAmount); return <Helmet title={"Favourites"}> <CommonSection title="Favourite Products" /> <section> <Container> <Row> <Col lg='9'> { favItems.length === 0 ? ( <h2 className='fs-4 text-center'>No item added to Favourites</h2> ) : ( <table className='table boarded'> <thead> <tr> <th>Image</th> <th>Title</th> <th>Price</th> <th>Qty</th> <th>Delete</th> </tr> </thead> <tbody> { favItems.map((item, index) => ( <Tr item={item} key={index} /> )) } </tbody> </table> ) } </Col> <Col lg='3'> <div> <h6 className='d-flex align-items-center justify-content-between'> Subtotal <span className='fs-4 fw-bold'>{totalAmount}₸</span> </h6> </div> <div> <button className='buy__btn w-100'> <Link to='/products'>Continue Exploring</Link> </button> </div> </Col> </Row> </Container> </section> </Helmet> }; const Tr = ({ item }) => { const dispatch = useDispatch(); const deleteProduct = ()=>{ dispatch(favActions.deleteItem(item.id)) } return ( <tr> <td><img src={item.imgUrl} alt="" /></td> <td>{item.productName}</td> <td>{item.price}</td> <td>{item.quantity}</td> <td><motion.i whileTap={{ scale: 1.2 }} onClick={deleteProduct} class="ri-delete-bin-line" ></motion.i></td> </tr> ); }; export default Favourites;
package iterator.composite; import iterator.MenuItem; import java.util.ArrayList; import java.util.Iterator; public class Menu extends MenuComponent{ ArrayList menuComponents = new ArrayList(); String nome; public Menu(String nome) { this.nome = nome; } @Override public void add(MenuComponent menu) { menuComponents.add(menu); } @Override public void remove(MenuComponent menu) { menuComponents.remove(menu); } @Override public MenuItem getChild(int i) { return (MenuItem) menuComponents.get(i); } @Override public String getNome() { return nome; } @Override public void print() { System.out.println("\n"+getNome()); System.out.println("----------"); Iterator iterator = menuComponents.iterator(); while (iterator.hasNext()) { MenuComponent mc = (MenuComponent) iterator.next(); mc.print(); } } }
package day02 import scala.io.Source case class Game(id: Int, cubes: List[Cubes]) case class Cubes(red: Int, green: Int, blue: Int) case class Bag(red: Int, green: Int, blue: Int) def gamePt1(line: String): Int = val bag = Bag(12, 13, 14) val game = parseGame(line) val allPossible = game.cubes.forall(c => isPossible(c, bag)) if allPossible then game.id else 0 def isPossible(cubes: Cubes, bag: Bag): Boolean = val redPossible = cubes.red <= bag.red val greenPossible = cubes.green <= bag.green val bluePossible = cubes.blue <= bag.blue redPossible && greenPossible && bluePossible def gamePt2(line: String): Int = val game = parseGame(line) val fewestColors = game.cubes.reduce((c1, c2) => getFewestColors(c1, c2)) fewestColors.red * fewestColors.green * fewestColors.blue def getFewestColors(c1: Cubes, c2: Cubes): Cubes = val red = Math.max(c1.red, c2.red) val green = Math.max(c1.green, c2.green) val blue = Math.max(c1.blue, c2.blue) Cubes(red, green, blue) def parseGame(line: String): Game = line match case s"Game $id: $cubes" => val cubesList = cubes.split(";").toList.map(parseCubes) Game(id.toInt, cubesList) def parseCubes(cubes: String): Cubes = val red = parseColor(cubes, "red") val green = parseColor(cubes, "green") val blue = parseColor(cubes, "blue") Cubes(red, green, blue) def parseColor(cubes: String, color: String): Int = val regex = s".*?([0-9]+) $color.*".r cubes match case regex(number) => number.toInt case _ => 0 @main def main(): Unit = val lines = Source.fromResource("day02.txt").getLines().toList println("Pt1: " + lines.map(gamePt1).sum) println("Pt2: " + lines.map(gamePt2).sum) val example = """ |Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green |Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue |Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red |Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red |Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green |""".stripMargin.split("\n").toList.filter(s => !s.isBlank)
import 'package:flutter/material.dart'; class EmailTextField extends StatelessWidget { const EmailTextField({ super.key, void Function(String)? onChanged, String? Function(String?)? validator, }) : _onChanged = onChanged, _validator = validator; final void Function(String)? _onChanged; final String? Function(String?)? _validator; @override Widget build(BuildContext context) { return TextFormField( keyboardType: TextInputType.emailAddress, textInputAction: TextInputAction.next, decoration: const InputDecoration( label: Text('Email'), prefixIcon: Icon(Icons.email_rounded), ), onChanged: _onChanged, validator: _validator, ); } }
import { EmailsService } from './../emails/emails.service'; import { BadRequestException, Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { User } from '@prisma/client'; import * as argon2 from 'argon2'; import { EmailValidationsService } from 'src/email-validations/email-validations.service'; import { PrismaService } from 'src/prisma/prisma.service'; @Injectable() export class PasswordsService { constructor( private emailsService: EmailsService, private emailValidationService: EmailValidationsService, private configService: ConfigService, private prismaService: PrismaService, ) {} async updatePassword(email, password) { const hash = await this.hashPassword(password); const update = await this.prismaService.user.update({ where: { emailAddress: email }, data: { password: hash }, }); if (update) { const passwordChangeEmail = await this.emailsService.passwordChange( email, ); return { message: 'password updated successfully', update }; } else { throw new BadRequestException('unable to update password'); } } async hashPassword(pass) { try { console.log('entered password hashing'); const hash = await argon2.hash(pass, { type: argon2.argon2id }); if (hash) { return hash; } } catch (err) { throw err; } } async comparePassword(password: string, userPassword: string): Promise<any> { try { const result = await argon2.verify(userPassword, password); return result; } catch (ex) { throw ex; } } generateRandomString(length) { const randomChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let result = ''; for (let i = 0; i < length; i++) { result += randomChars.charAt( Math.floor(Math.random() * randomChars.length), ); } return result; } createUrl(user: User, hash: string) { const url = `${ this.configService.get('FORGET_PASSWORD_URL') + 'v1/auth/forget-password-email-link' }?hash=${hash}&email=${user.emailAddress}`; return url; } async forgetPassword(user: User) { const hash = this.generateRandomString(7); const url = this.createUrl(user, hash); const emailValidation = { type: 'passwordValidation', hash: hash, active: false, userId: user.id, }; const validate = await this.emailValidationService.create(emailValidation); if (validate) { await this.emailsService.forgetPassword(user, url); return { message: 'forgot password email sent' }; } } }
import { ProductStatus as Status } from "@prisma/client"; import { Box } from "~/styled-system/jsx"; import { getProductStatus } from "~/utils/getProductStatus"; interface Props { status: Status; } export const ProductStatus = ({ status }: Props) => { const inStock = status === Status.IN_STOCK; const soldOut = status === Status.SOLD_OUT; const backorder = status === Status.BACKORDER; const bgColor = inStock ? "green.200" : soldOut ? "red.200" : backorder ? "blue.200" : "gray.200"; const fgColor = inStock ? "green.700" : soldOut ? "red.700" : backorder ? "blue.700" : "gray.700"; return ( <Box bgColor={bgColor} rounded="md" display="inline-block" fontSize="xs" fontWeight="semibold" px={2} py={0.5} color={fgColor} > {getProductStatus(status)} </Box> ); };
import { mobile, backend, creator, web, javascript, typescript, html, css, reactjs, redux, tailwind, nodejs, mongodb, git, angular, figma, meta, starbucks, tesla, shopify, tripguide, threejs, Ww, Pretty, dantist, edo, sabi, telus, fiver, makerLogo, easy, } from "../assets"; export const navLinks = [ { id: "about", title: "About", }, { id: "work", title: "Work", }, { id: "contact", title: "Contact", }, ]; const services = [ { title: "Frontend Developer", icon: web, }, { title: "React Native Developer", icon: mobile, }, { title: "Backend Developer", icon: backend, }, { title: "Content Creator", icon: creator, }, ]; const technologies = [ { name: "HTML 5", icon: html, }, { name: "CSS 3", icon: css, }, { name: "JavaScript", icon: javascript, }, { name: "TypeScript", icon: typescript, }, { name: "React JS", icon: reactjs, }, { name: "Redux Toolkit", icon: redux, }, { name: "Tailwind CSS", icon: tailwind, }, { name: "Node JS", icon: nodejs, }, { name: "MongoDB", icon: mongodb, }, { name: "Three JS", icon: threejs, }, { name: "git", icon: git, }, { name: "angular", icon: angular, }, ]; const experiences = [ { title: "Frontend Developer", company_name: "Makers", icon: makerLogo, iconBg: "#E6DEDD", date: "December 2023 - Marth 2023", points: [ "Developing and maintaining web applications using React.js and other related technologies.", "Collaborating with cross-functional including designers, product managers, and other developers to create high-quality products.", "Implementing responsive design and ensuring cross-browser compatibility.", "Participating in code reviews and providing constructive feedback to other developers.", ], }, { title: "Fullstack Developer ", company_name: " Freelance", icon: fiver, iconBg: "#E6DEDD", date: "Marth 2023 - May 2023", points: [ "working with backends development using Node.js as well as using databases MongoDB,SQL.", "creation of websites of varying complexity for business.", "client side development using React, Angular libraries.", ], }, { title: "Frontend Developer", company_name: "Easy QR menu", icon: easy, iconBg: "#E6DEDD", date: "June 2023 - November 2023", points: [ "Developing and maintaining web applications using React.js and other related technologies.", "Collaborating with cross-functional including designers, product managers, and other developers to create high-quality products.", "Implementing responsive design and ensuring cross-browser compatibility.", "Participating in code reviews and providing constructive feedback to other developers.", ], }, ]; const testimonials = [ { testimonial: "I thought it was impossible to make a website as beautiful as our product, but Rick proved me wrong.", name: "Sara Lee", designation: "CFO", company: "Acme Co", //image: "https://randomuser.me/api/portraits/women/4.jpg", }, { testimonial: "I've never met a web developer who truly cares about their clients' success like Rick does.", name: "Chris Brown", designation: "COO", company: "DEF Corp", //image: "https://randomuser.me/api/portraits/men/5.jpg", }, { testimonial: "After Rick optimized our website, our traffic increased by 50%. We can't thank them enough!", name: "Lisa Wang", designation: "CTO", company: "456 Enterprises", // image: "https://randomuser.me/api/portraits/women/6.jpg", }, ]; const projects = [ { name: "Dental clinic", description: "my first project when I became a freelancer this project is a dental clinic and the clinic itself is located in Kigali in Rwanda and this site also contains all the data about the clinic", tags: [ { name: "react", color: "blue-text-gradient", }, { name: "sass", color: "green-text-gradient", }, ], image: dantist, source_code_link: "https://github.com/emirlan0706/dental_clinic_project", }, { name: "Pretty-shop", description: "Pretty Shop is a website for selling furniture and accessories, one of the first projects I made", tags: [ { name: "React", color: "blue-text-gradient", }, { name: "css", color: "green-text-gradient", }, { name: "Redux", color: "pink-text-gradient", }, ], image: Pretty, source_code_link: "https://github.com/emirlan0706/pretty_shop_react_app_v2", }, { name: "Colab", description: "my collaboration with freelancer Ted to create a website using the Next.js technology stack", tags: [ { name: "Next.js", color: "blue-text-gradient", }, { name: "firebase", color: "green-text-gradient", }, ], image: Ww, source_code_link: "https://github.com/emirlan0706/store_app_colab", }, ]; export { services, technologies, experiences, testimonials, projects };
import { create } from "zustand"; import { persist } from "zustand/middleware"; type AuthStore = { user: user | null; login: (email: string, token: string, username: string) => void; logout: () => void; }; export type user = { email: string; username: string; token: string; }; const useAuthStore = create<AuthStore>()( persist( (set) => ({ user: null, login: (email: string, token: string, username: string) => { set(() => ({ user: { email, token, username } })); }, logout: () => { set(() => ({ user: null })); }, }), { name: "user" } ) ); export default useAuthStore;
package bank.management.system; import java.awt.Color; import java.awt.Font; import java.awt.Image; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPasswordField; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.sql.ResultSet; @SuppressWarnings("serial") public class Login extends JFrame implements ActionListener { JButton login, clear, signup; JLabel text, cardno, pin; JTextField cardTextField; JPasswordField pinTextField; public Login() { super("Automated Teller Machine"); getContentPane().setBackground(Color.WHITE); setLayout(null); ImageIcon i1=new ImageIcon(ClassLoader.getSystemResource("icons/logo.jpg"));// It will get the image from given location Image i2=i1.getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT);// it will scale the given image accourding to our given width and hight ImageIcon i3=new ImageIcon(i2);// we can not directly pass Image object in JLabel we have to convert it first into ImageIcon object JLabel label=new JLabel(i3); label.setBounds(70, 10, 100, 100); add(label); text=new JLabel("Welcome to ATM"); text.setFont(new Font("Times New Roman",Font.BOLD,38)); text.setBounds( 200, 40, 400, 40); add(text); cardno=new JLabel("Card No:"); cardno.setFont(new Font("Ralway",Font.BOLD,28)); cardno.setBounds( 120, 150, 150, 30); add(cardno); cardTextField=new JTextField(); cardTextField.setBounds(300, 150, 230, 30); cardTextField.setFont(new Font("Times New Roman",Font.BOLD,13)); add(cardTextField); pin=new JLabel("PIN:"); pin.setFont(new Font("Ralway",Font.BOLD,28)); pin.setBounds( 120, 220, 150, 30); add(pin); pinTextField=new JPasswordField(); pinTextField.setBounds(300, 220, 230, 30); pinTextField.setFont(new Font("Times New Roman",Font.BOLD,13)); add(pinTextField); login=new JButton("SIGN IN"); login.setBounds(300,300,100,30); login.setBackground(Color.BLACK); login.setForeground(Color.WHITE); login.addActionListener(this); add(login); clear=new JButton("CLEAR"); clear.setBounds(430,300,100,30); clear.setBackground(Color.BLACK); clear.setForeground(Color.WHITE); clear.addActionListener(this); add(clear); signup=new JButton("SIGN UP"); signup.setBounds(300,350,230,30); signup.setBackground(Color.BLACK); signup.setForeground(Color.WHITE); signup.addActionListener(this); add(signup); setSize(800,480); setVisible(true); setLocation(350,200);// It will set the initial location of main Frame } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == clear) { cardTextField.setText(""); pinTextField.setText(""); } else if(e.getSource() == login) { Connect con=new Connect(); String cardnumber=cardTextField.getText(); @SuppressWarnings("deprecation") String pinnumber=pinTextField.getText(); String query="SELECT * FROM LOGIN WHERE card_number = '"+cardnumber+"' AND pin_number = '"+pinnumber+"'"; try { ResultSet rs=con.stm.executeQuery(query); if(rs.next()) { setVisible(false); new Transactions(cardnumber).setVisible(true); } else { JOptionPane.showMessageDialog(null,"Incorrect Card Number or Pin"); } } catch(Exception ex) { System.out.println(ex); } } else if(e.getSource() == signup) { setVisible(false); new SignupOne().setVisible(true); } } public static void main(String arg[]) { new Login(); } }
import { Component, OnInit } from '@angular/core'; import { Validators, FormBuilder, FormGroup, FormControl } from '@angular/forms'; import { VendorService } from '../../vendors/vendor.service'; import { Router } from '@angular/router'; import { NotificationService } from 'src/app/shared/services/notification.service'; import { ConsumerService } from '../consumer.service'; @Component({ selector: 'app-edit-consumer', templateUrl: './edit-consumer.component.html', styleUrls: ['./edit-consumer.component.sass'] }) export class EditConsumerComponent implements OnInit { title: string = 'Update Consumer'; editConsumer: FormGroup; submitted: boolean = false; consumerData:any; // @ViewChild('alertConfirmationModal') alertModelPopUp: AlertmodalpopupComponent; constructor(private formBuilder: FormBuilder, public router: Router, private consumerService: ConsumerService, private notification: NotificationService) { this.consumerData = window.history.state?.consumerData; } ngOnInit(): void { this.editConsumer = this.formBuilder.group({ id: [''], name: ['', Validators.required], email: [''], mobileNumber: [''], billingAddress: [''], isActive: [true] }); this.initialize(this.consumerData); } get f() { return this.editConsumer.controls; } initialize(consumerData: any): void { if (consumerData) { (<FormControl>this.f['id']).setValue(consumerData.id); (<FormControl>this.f['name']).setValue(consumerData.name); (<FormControl>this.f['email']).setValue(consumerData.email); (<FormControl>this.f['mobileNumber']).setValue(consumerData.mobileNumber); (<FormControl>this.f['billingAddress']).setValue(consumerData.billingAddress); } } update(): void { this.submitted = true; this.f.mobileNumber.setValue(this.f.mobileNumber.value.toString()); if (this.editConsumer.invalid) { return; } this.consumerService.updateConsumer(this.editConsumer.value) .subscribe((data: any) => { this.cancel(); return this.notification.successMessage("Successfully updated"); }, error => { return this.notification.errorMessage(error); }); } cancel(): void { this.router.navigate(['/service/consumers']); } }
import React from "react" interface ContainerProps { children: React.ReactNode flex?: boolean flexCol?: boolean justifyBetween?: boolean mobileResponsive?: boolean } export const Container: React.FC<ContainerProps> = ({ ...ContainerProps }) => { return ( <div className={`${ContainerProps.flex && "flex items-center"} ${ContainerProps.flexCol && "flex-col"} ${ContainerProps.justifyBetween && "justify-between"} ${ContainerProps.mobileResponsive ? "px-0 md:px-4 xl:container" : "px-4 xl:container"}`}> {ContainerProps.children} </div> ) }
from pathlib import Path import torch import numpy as np import torch from torch.utils.data import DataLoader from tqdm import tqdm from lru.architectures import DLRU, DLRUConfig import f16_utils import wandb import hydra @hydra.main(version_base=None, config_path="conf", config_name="config") def get_config(config): global cfg cfg = config print(cfg) if __name__ == "__main__": # not the suggested way to handle the config, but i wanna work in __main__ for the moment get_config() torch.manual_seed(42) device = cfg.device if torch.cuda.is_available() else "cpu" torch.set_num_threads(10) torch.set_float32_matmul_precision("high") n_u = 1 n_y = 3 if cfg.log_wandb: wandb.init( project="sysid-ss-bench", #name="run1", config=dict(cfg) ) config = DLRUConfig(d_model=cfg.d_model,d_state=cfg.d_state, n_layers=cfg.n_layers, ff=cfg.ff) model = DLRU(n_u, n_y, config).to(device) ds_dict = f16_utils.load_data_dict() scaler_y, scaler_u = f16_utils.make_scalers(ds_dict["F16Data_FullMSine_Level5"]) scaled_datasets = f16_utils.make_scaled_datasets(ds_dict, scaler_y, scaler_u) train_data = f16_utils.make_subsequence_datasets(scaled_datasets, subseq_len=cfg.seq_len) train_loader = DataLoader(train_data, batch_size=cfg.batch_size, shuffle=True) optimizer = torch.optim.AdamW(model.parameters(), lr=cfg.lr) save_folder = Path("ckpt") save_folder.mkdir(exist_ok=True) LOSS = [] # Train best_loss = np.inf for epoch in range(cfg.epochs): for itr, (batch_y, batch_u) in tqdm(enumerate(train_loader)): optimizer.zero_grad() batch_y = batch_y.to(device) batch_u = batch_u.to(device) batch_y_sim = model(batch_u) loss = torch.nn.functional.mse_loss(batch_y_sim[:, cfg.skip:, :], batch_y[:, cfg.skip:, :]) loss_reg = torch.tensor(0.0, device=batch_u.device, dtype=batch_u.dtype) if cfg.reg_type == "modal" and cfg.reg_lambda > 0.0: for layer in range(cfg.n_layers): lambdas_abs = torch.exp(-torch.exp(model.blocks[layer].lru.nu_log)) loss_reg = loss_reg + cfg.reg_lambda*lambdas_abs.mean() elif cfg.reg_type == "hankel" and cfg.reg_lambda > 0.0: for layer in range(cfg.n_layers): hankel_values = model.blocks[layer].lru.hankel_singular_values(cc=False) loss_reg = loss_reg + cfg.reg_lambda*hankel_values.mean() elif cfg.reg_type == "hankel_cc" and cfg.reg_lambda > 0.0: for layer in range(cfg.n_layers): hankel_values = model.blocks[layer].lru.hankel_singular_values(cc=True) loss_reg = loss_reg + cfg.reg_lambda*hankel_values.mean() loss = loss + loss_reg #if epoch == 0 and itr == 1875: # ad loss.backward() optimizer.step() if itr % 100 == 0: print(loss.item(), loss_reg.item()) if cfg.log_wandb: wandb.log({"loss": loss.item()}) if cfg.reg_lambda > 0: wandb.log({"loss_reg": loss_reg.item()}) if itr % 1000 == 0: if loss < best_loss: best_loss = loss.item() checkpoint = { 'scaler_u': scaler_u, 'scaler_y': scaler_y, 'model': model.state_dict(), 'LOSS': np.array(LOSS), 'cfg': cfg } print("Saving model...") torch.save(checkpoint, save_folder / f"{cfg.out_name}.pt") LOSS.append(loss.item()) checkpoint = { 'scaler_u': scaler_u, 'scaler_y': scaler_y, 'model': model.state_dict(), 'LOSS': np.array(LOSS), 'cfg': cfg } torch.save(checkpoint, save_folder / f"{cfg.out_name}_last.pt")
import React, {useEffect, useState} from 'react'; import FeedModal from './FeedModal'; import FeedPhotos from './FeedPhotos'; import propTypes from 'prop-types'; import { useDispatch, useSelector } from 'react-redux'; import { loadNewPhotos, resetFeedState } from '../../store/feed'; import Loading from '../../Helper/Loading'; import Error from '../../Helper/Error'; const Feed = ({user}) => { const [modalPhoto, setMoldaPhoto] = useState(null); const { infinite, loading, list, error} = useSelector(state => state.feed); const dispatch = useDispatch() useEffect(() => { dispatch(resetFeedState()) dispatch(loadNewPhotos({user, total: 6})) }, [dispatch, user]) useEffect(() => { let wait = false; function infiniteScroll(){ if(infinite){ const scroll = window.scrollY; const height = document.body.scrollHeight - window.innerHeight; if (scroll > height * 0.75 && !wait) { dispatch(loadNewPhotos({user, total: 6})) wait = true; setTimeout(() => { wait = false; }, 3000); } } } window.addEventListener('wheel', infiniteScroll); window.addEventListener('scroll', infiniteScroll); return () => { window.addEventListener('wheel', infiniteScroll); window.addEventListener('scroll', infiniteScroll); }; }, [infinite, dispatch, user]); return ( <div> {modalPhoto && <FeedModal photo={modalPhoto} setMoldaPhoto={setMoldaPhoto}/>} {loading && <Loading />} {error && <Error error={error}/>} {list.length > 0 && <FeedPhotos setMoldaPhoto={setMoldaPhoto} />} {!infinite && !user && ( <p style={{ textAlign: 'center', padding: '2rem 0 4rem 0', color: '#888' }}> Não existem mais postagens. </p> )} </div> ); }; Feed.defaultProps = { user: 0 } Feed.propTypes = { user: propTypes.oneOfType([ propTypes.string.isRequired, propTypes.number.isRequired, ]) } export default Feed;
package com.DSA.Tree.BinaryTree; // Binary tree Create(Insert) and Search and Same tree problem solved class BSTNode{ int data; BSTNode childLeft; BSTNode childRight; public BSTNode(int key) { data = key; childLeft = childRight = null; } } public class BinaryTreeAll { static BSTNode root; static BSTNode root1; // public BinaryTreeAll() { // root = null; // root1 = null; // } public BSTNode insert(BSTNode node, int data){ if (node == null) { node = new BSTNode(data); }else{ if(data < node.data){ node.childLeft = insert(node.childLeft, data); }else{ node.childRight = insert(node.childRight,data); } } return node; } public void printTree(BSTNode node, String prefix){ if(node == null){ return; } System.out.println(prefix + " + " + node.data); printTree(node.childLeft , prefix + " "); printTree(node.childRight , prefix + " "); } public boolean searchTree(BSTNode node, int val){ boolean found = false; while((node!=null) && !found) { int nodeVal = node.data; if (val < nodeVal) node = node.childLeft; else if (val > nodeVal) node = node.childRight; else { found = true; break; } } return found; } public static void main(String[] args) { BinaryTreeAll bTree = new BinaryTreeAll(); root = bTree.insert(root, 55); root = bTree.insert(root, 20); root = bTree.insert(root, 90); root = bTree.insert(root, 80); root = bTree.insert(root, 50); root = bTree.insert(root, 35); root = bTree.insert(root, 15); root = bTree.insert(root, 75); bTree.printTree(root," "); System.out.println(bTree.searchTree(root,35)); BinaryTreeAll bTree1 = new BinaryTreeAll(); root1 = bTree1.insert(root1, 55); root1 = bTree1.insert(root1, 20); root1 = bTree1.insert(root1, 90); root1 = bTree1.insert(root1, 80); root1 = bTree1.insert(root1, 50); root1 = bTree1.insert(root1, 35); root1 = bTree1.insert(root1, 15); root1 = bTree1.insert(root1, 65); bTree.printTree(root1," "); System.out.println(bTree.searchTree(root1,35)); System.out.println("Is Identical : "+ isIdenticalTree(bTree.root,bTree1.root1)); } private static boolean isIdenticalTree(BSTNode root, BSTNode root1) { if(root == null && root1 == null) return true; if(root !=null && root1 != null){ return ((root.data == root1.data) && isIdenticalTree(root.childLeft,root1.childLeft) && isIdenticalTree(root.childRight,root1.childRight)); } return false; } }
import { writeTextFile, BaseDirectory, readDir, FileEntry, readTextFile, } from "@tauri-apps/api/fs"; import { insertContentItem } from "./db"; import { buildContentItemIndex } from "./getContent"; export const CONTENT_DIR = "content"; export async function createFile( contentId: string, title: string ): Promise<boolean> { const content = `--- id: ${contentId} title: ${title} ---`; try { const file = await readTextFile(`${CONTENT_DIR}/${kebabCase(title)}.md`, { dir: BaseDirectory.AppData, }); // If file already exists, return false if (file) return false; } catch (e) { console.error(e); } await writeTextFile(`${CONTENT_DIR}/${kebabCase(title)}.md`, content, { dir: BaseDirectory.AppConfig, }); const contentItemIndex = await buildContentItemIndex({ name: `${kebabCase(title)}.md`, path: `${CONTENT_DIR}/${kebabCase(title)}.md`, }); await insertContentItem(contentItemIndex); return true; } export async function getFile(name: string): Promise<string> { return readTextFile(`${CONTENT_DIR}/${name}`, { dir: BaseDirectory.AppData, }); } export async function getFiles(): Promise<FileEntry[]> { const files = await readDir(CONTENT_DIR, { dir: BaseDirectory.AppData, recursive: true, }); return files.filter((file) => file?.name?.endsWith(".md")); } export function kebabCase(string: string) { return string .replace(/([a-z])([A-Z])/g, "$1-$2") .replace(/[\s_]+/g, "-") .toLowerCase(); }
/** * place_classes.h * * @date 14.07.2023 * @author Joel Santos */ #pragma once #include "swot_manipulation_bt/manipulation.h" /** * @class CheckObjRequired * @brief Synchronous action node for checking which object is required for placing. * @details This synchronous action node checks which object is required for the placing operation. */ class CheckObjRequired : public BT::SyncActionNode { private: Manipulation& manipulation_; public: CheckObjRequired(const std::string& name, Manipulation& manipulation); ~CheckObjRequired() override; BT::NodeStatus tick() override; }; /** * @class CheckWSFree * @brief Synchronous action node for checking if the workspace is free for placing. * @details This synchronous action node checks if the workspace is free for the placing operation. */ class CheckWSFree : public BT::SyncActionNode { private: Manipulation& manipulation_; public: CheckWSFree(const std::string& name, Manipulation& manipulation); ~CheckWSFree() override; BT::NodeStatus tick() override; }; /** * @class MoveToTray * @brief Synchronous action node for moving to the designated tray. * @details This synchronous action node moves the robot to the designated tray where the object * required is located. */ class MoveToTray : public BT::SyncActionNode { private: Manipulation& manipulation_; public: MoveToTray(const std::string& name, Manipulation& manipulation); ~MoveToTray() override; BT::NodeStatus tick() override; }; /** * @class PickFromTray * @brief Synchronous action node for picking an object from the tray. * @details This synchronous action node picks an object from the tray before placing. */ class PickFromTray : public BT::SyncActionNode { private: Manipulation& manipulation_; public: PickFromTray(const std::string& name, Manipulation& manipulation); ~PickFromTray() override; BT::NodeStatus tick() override; }; /** * @class MoveToDropPos * @brief Synchronous action node for moving to the drop position. * @details This synchronous action node moves the robot to the designated drop position for placing the object. */ class MoveToDropPos : public BT::SyncActionNode { private: Manipulation& manipulation_; public: MoveToDropPos(const std::string& name, Manipulation& manipulation); ~MoveToDropPos() override; BT::NodeStatus tick() override; };
import { Body, Controller, Get, Post, Request, UseGuards, } from '@nestjs/common'; import { AppService } from './app.service'; import { LocalAuthGuard } from './modules/auth/local-auth.guard'; import { AuthService } from './modules/auth/auth.service'; import { CreateUserDto } from './modules/user/dto/create-user.dto'; import { JwtAuthGuard } from './modules/auth/jwt-auth.guards'; @Controller() export class AppController { constructor( private readonly appService: AppService, private readonly authService: AuthService, ) {} @Get() getHello(): string { return this.appService.getHello(); } @UseGuards(LocalAuthGuard) @Post('login') async login(@Request() req) { return this.authService.login(req.user); } @Post('register') async register(@Body() user: CreateUserDto) { return this.authService.register(user); } @UseGuards(JwtAuthGuard) @Get('whoami') whoami(@Request() req) { return req.user; } }
# [724. 寻找数组的中心下标](https://leetcode-cn.com/problems/find-pivot-index) [English Version](/solution/0700-0799/0724.Find%20Pivot%20Index/README_EN.md) ## 题目描述 <!-- 这里写题目描述 --> <p>给你一个整数数组 <code>nums</code>,请编写一个能够返回数组 <strong>“中心下标” </strong>的方法。</p> <p>数组<strong> 中心下标</strong><strong> </strong>是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。</p> <p>如果数组不存在中心下标,返回 <code>-1</code> 。如果数组有多个中心下标,应该返回最靠近左边的那一个。</p> <p><strong>注意:</strong>中心下标可能出现在数组的两端。</p> <p> </p> <p><strong>示例 1:</strong></p> <pre> <strong>输入:</strong>nums = [1, 7, 3, 6, 5, 6] <strong>输出:</strong>3 <strong>解释:</strong> 中心下标是 3 。 左侧数之和 (1 + 7 + 3 = 11), 右侧数之和 (5 + 6 = 11) ,二者相等。 </pre> <p><strong>示例 2:</strong></p> <pre> <strong>输入:</strong>nums = [1, 2, 3] <strong>输出:</strong>-1 <strong>解释:</strong> 数组中不存在满足此条件的中心下标。</pre> <p><strong>示例 3:</strong></p> <pre> <strong>输入:</strong>nums = [2, 1, -1] <strong>输出:</strong>0 <strong>解释:</strong> 中心下标是 0 。 下标 0 左侧不存在元素,视作和为 0 ; 右侧数之和为 1 + (-1) = 0 ,二者相等。 </pre> <p> </p> <p><strong>提示:</strong></p> <ul> <li><code>nums</code> 的长度范围为 <code>[0, 10000]</code>。</li> <li>任何一个 <code>nums[i]</code> 将会是一个范围在 <code>[-1000, 1000]</code>的整数。</li> </ul> ## 解法 <!-- 这里可写通用的实现逻辑 --> 前缀和。 <!-- tabs:start --> ### **Python3** <!-- 这里可写当前语言的特殊实现逻辑 --> ```python class Solution: def pivotIndex(self, nums: List[int]) -> int: s, presum = sum(nums), 0 for i, v in enumerate(nums): if (presum << 1) == s - v: return i presum += v return -1 ``` ### **Java** <!-- 这里可写当前语言的特殊实现逻辑 --> ```java class Solution { public int pivotIndex(int[] nums) { int n = nums.length, s = 0; for (int e : nums) { s += e; } int presum = 0; for (int i = 0; i < n; ++i) { // presum == sums - nums[i] - presum if (presum << 1 == s - nums[i]) { return i; } presum += nums[i]; } return -1; } } ``` ### **TypeScript** ```ts function pivotIndex(nums: number[]): number { let rightSum = nums.reduce((a, c) => a + c, 0), leftSum = 0; for (let i = 0; i < nums.length; i++) { rightSum -= nums[i]; if (leftSum == rightSum) return i; leftSum += nums[i]; } return -1; } ``` ### **C++** ```cpp class Solution { public: int pivotIndex(vector<int> &nums) { int s = 0; for (int e : nums) s += e; int presum = 0; for (int i = 0; i < nums.size(); ++i) { if (presum * 2 == s - nums[i]) return i; presum += nums[i]; } return -1; } }; ``` ### **Go** ```go func pivotIndex(nums []int) int { s := 0 for _, e := range nums { s += e } presum := 0 for i, e := range nums { if presum<<1 == s-e { return i } presum += e } return -1 } ``` ### **...** ``` ``` <!-- tabs:end -->
-- 🌟 Exercise 1 : Bootcamp -- Instructions -- For this exercise, you will have to find some requests on your own! -- Create -- Create a database called bootcamp. -- Create a table called students. -- Add the following columns: -- id -- last_name -- first_name -- birth_date -- The id must be auto_incremented. -- Make sure to choose the correct data type for each column. CREATE TABLE students (id SERIAL, first_name VARCHAR (50),last_name VARCHAR (50),birth_date DATE); -- Insert -- Insert the data seen above to the students table. Find the most efficient way to insert the data. -- Insert your last_name, first_name and birth_date to the students table (Take a look at the id given). INSERT INTO students ( first_name ,last_name ,birth_date) VALUES ('Marc','Benichou','02/11/1998'), ('Yoan','Cohen','03/12/2010'), ('Lea','Benichou','27/07/1987'), ('Amelia','Dux','07/04/1996'), ('David','Grez','14/06/2003'), ('Omer','Simpson','03/10/1980'); -- Select -- Fetch all of the data from the table. SELECT * FROM students; -- Fetch all of the students first_names and last_names. SELECT first_name,last_name FROM students; -- For the following questions, only fetch the first_names and last_names of the students. -- Fetch the student which id is equal to 2. SELECT first_name,last_name FROM students WHERE id=2; -- Fetch the student whose last_name is Benichou AND first_name is Marc. SELECT first_name,last_name FROM students WHERE last_name='Benichou' AND first_name='Marc'; -- Fetch the students whose last_names are Benichou OR first_names are Marc. SELECT first_name,last_name FROM students WHERE last_name='Benichou' OR first_name='Marc'; -- Fetch the students whose first_names contain the letter a. SELECT first_name,last_name FROM students WHERE first_name LIKE '%a%'; -- Fetch the students whose first_names start with the letter a. SELECT first_name,last_name FROM students WHERE first_name LIKE 'a%'; -- Fetch the students whose first_names end with the letter a. SELECT first_name,last_name FROM students WHERE first_name LIKE '%a'; -- Fetch the students whose second to last letter of their first_names are a (Example: Leah). SELECT first_name,last_name FROM students WHERE first_name LIKE '%a_'; -- Fetch the students whose id’s are equal to 1 AND 3 . SELECT first_name,last_name FROM students WHERE id=1 OR id=3; -- Fetch the students whose birth_dates are equal to or come after 1/01/2000. (show all their info). SELECT first_name,last_name,birth_date FROM students WHERE birth_date>'01/01/2000';
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { MdClose } from 'react-icons/md'; import './NavBar.scss'; export default class NavBar extends Component { static propTypes = { title: PropTypes.string, subtitle: PropTypes.string, leftSlot: PropTypes.node, rightSlot: PropTypes.node, theme: PropTypes.string, leftSlotClickHandler: PropTypes.func, rightSlotClickHandler: PropTypes.func, }; handleLeftSlotClick = () => { const { leftSlotClickHandler } = this.props; if (!leftSlotClickHandler) { return false; } return leftSlotClickHandler(); }; handleRightSlotClick = () => { const { rightSlotClickHandler } = this.props; if (!rightSlotClickHandler) { return false; } return rightSlotClickHandler(); }; render() { const { theme, leftSlot, title, subtitle, rightSlot, leftSlotClickHandler, rightSlotClickHandler, } = this.props; const leftClass = `NavBar__LeftSlot ${ leftSlot && leftSlotClickHandler ? 'pointer' : '' }`; const rightClass = `NavBar__RightSlot ${ rightSlot && rightSlotClickHandler ? 'pointer' : '' }`; return ( <div className={`NavBar NavBar--theme-${theme || 'none'}`}> <div className="NavBar__Wrapper"> <div className={leftClass} onClick={this.handleLeftSlotClick}> {leftSlot !== undefined ? leftSlot : null} </div> <div className="NavBar__Center"> {title && <div className="NavBar__Title">{title}</div>} {subtitle && <div className="NavBar__subtitle">{subtitle}</div>} </div> <div className={rightClass} onClick={this.handleRightSlotClick}> {rightSlot !== undefined ? rightSlot : <MdClose />} </div> </div> </div> ); } }
package dfs import "dfs_leetcode/utils" // Note: sum of a path, not sum of subTree!!! // [5,4,8,11,null,13,4,7,2,null,null,null,1], the path is 7 -> 11 -> 4 -> 5 -> 8 -> 13 = 48 var minVal int = -1000 func MaxpathSum(root *utils.TreeNode) int { if root == nil { return 0 } leftPathSum, rightPathSum, leftPathDFS, rightPathDFS := minVal, minVal, minVal, minVal bothPathSum, rootLeftSum, rootRightSum := root.Val, root.Val, root.Val if root.Left != nil { leftPathSum = maxSumOfARoot(root.Left) bothPathSum += leftPathSum rootLeftSum += leftPathSum leftPathDFS = MaxpathSum(root.Left) } if root.Right != nil { rightPathSum = maxSumOfARoot(root.Right) bothPathSum += rightPathSum rootRightSum += rightPathSum rightPathDFS = MaxpathSum(root.Right) } return findMax(root.Val, leftPathSum, rightPathSum, bothPathSum, rootLeftSum, rootRightSum, leftPathDFS, rightPathDFS) } func maxSumOfARoot(root *utils.TreeNode) int { if root == nil { return 0 } return findMaxOfTwo(root.Val, root.Val+findMaxOfTwo(maxSumOfARoot(root.Left), maxSumOfARoot(root.Right))) } func findMaxOfTwo(a, b int) int { if a > b { return a } return b } func findMax(rootVal, leftVal, rightVal, bothPathVal, rootLeftVal, rootRightVal, leftPath, rightPath int) int { arr := []int{} arr = append(arr, rootVal) arr = append(arr, leftVal) arr = append(arr, rightVal) arr = append(arr, bothPathVal) arr = append(arr, rootLeftVal) arr = append(arr, rootRightVal) arr = append(arr, leftPath) arr = append(arr, rightPath) maxVal := minVal for _, val := range arr { if val > maxVal { maxVal = val } } return maxVal } func MaxpathSumIdea(root *utils.TreeNode) int { res := 0 dfsIdea(root, &res) return res } func dfsIdea(root *utils.TreeNode, res *int) int { if root == nil { return 0 } leftSum := findMaxOfTwo(dfsIdea(root.Left, res), 0) // handles the root value is negative case rightSum := findMaxOfTwo(dfsIdea(root.Right, res), 0) // handles the root value is negative case *res = findMaxOfTwo(*res, leftSum+rightSum+root.Val) return findMaxOfTwo(leftSum, rightSum) + root.Val }
import Foundation import MediaPlayer // sourcery: name = Playlist protocol Playlistable: Mockable { func create(shuffled: Bool) -> [MPMediaItem] func find(ids: [UInt64]) -> [MPMediaItem] } final class Playlist: Playlistable { private let authorization: Authorization private let mediaQuery: MediaQuery.Type init(authorization: Authorization, mediaQuery: MediaQuery.Type) { self.authorization = authorization self.mediaQuery = mediaQuery // note: NSNotification.Name.MPMediaLibraryDidChange indicates when the music library changes. // this would be useful for an automatic refresh, but it isn't really required as we create a new playlist // when hitting the shuffle button. might be useful at some point } func create(shuffled: Bool) -> [MPMediaItem] { guard authorization.isAuthorized else { return [] } if var tracks = mediaQuery.songs().items { if shuffled { tracks.shuffle() } return tracks } else { return [] } } func find(ids: [MPMediaEntityPersistentID]) -> [MPMediaItem] { guard authorization.isAuthorized else { return [] } let query = mediaQuery.songs() return ids.compactMap { (id: MPMediaEntityPersistentID) -> MPMediaItem? in let predicate = MPMediaPropertyPredicate(value: id, forProperty: MPMediaItemPropertyPersistentID) query.addFilterPredicate(predicate) let items = query.items query.removeFilterPredicate(predicate) return items?.first // expecting unique id per media item, so take first } } } // MARK: - [MPMediaItem] private extension Array where Element == MPMediaItem { mutating func shuffle() { guard !isEmpty else { return } (0..<(count - 1)).forEach { let remainingCount = count - $0 let exchangeIndex = $0 + Int(arc4random_uniform(UInt32(remainingCount))) swapAt($0, exchangeIndex) } } }
<template> <div class="container"> <router-link class="item row" :to="{ name: 'watch', query: { v: formatId(), }, }" > <div class="col c-6 m-4 l-3 item__img"> <img :src="video.snippet.thumbnails.medium.url" alt="img-video" /> <span>{{ video.contentDetails.duration | durationVideo }}</span> </div> <div class="col c-6 m-8 l-9 item__content"> <h3 class="item__content-title max-line">{{ video.snippet.title }}</h3> <div class="item__content-middle"> <span class="item__content-name-channel">{{ video.snippet.channelTitle }}</span> <span class="item__content-view" >{{ viewCount() | formatView }} lượt xem</span > </div> <div class="item__content-des max-line"> {{ video.snippet.description }} </div> </div> </router-link> <button class="item__content-add" v-if="!id && checkVideo"> <i class="fas fa-ellipsis-v"></i> <ul class="item__content-add-list" @click="addWachtLate"> <li class="item__content-add-item"> <i class="fas fa-clock"></i> <span>Lưu vào danh sách xem sau</span> </li> </ul> </button> </div> </template> <script> import { mapActions, mapState } from "vuex"; export default { props: { item: { type: Object, default: null, }, id: { type: String, default: null, }, checkVideo: { type: Boolean, default: false, }, }, async created() { this.callData(); }, computed: { returnItem() { return this.item; }, }, data() { return { styleObject: { display: "none", }, video: "", }; }, methods: { ...mapActions("listVideo", ["setVideo", "addInformVideo"]), ...mapActions("user", ["addVideo"]), async callData() { if (this.id) { await this.setVideo({ part: "statistics,contentDetails,snippet", id: this.id, }); this.video = this.$store.state.listVideo.video.data.items[0]; } else this.video = this.returnItem; }, formatId() { if (this.id == null) { if (this.$route.name == "Trending" || this.$route.name == "Playlist") { return this.item.id; } else { return this.item.id.videoId; } } return this.id; }, viewCount() { if (this.id) { return this.video.statistics.viewCount; } return this.video.snippet.view; }, addWachtLate() { this.addVideo({ type: "watchLate", video: { id: this.item.id, timeAt: new Date().getTime(), }, }); }, }, }; </script> <style> .item__content-add { position: absolute; top: 0; right: 10%; font-size: 2rem; color: rgba(0, 0, 0, 0.7); cursor: pointer; width: 40px; height: 40px; text-align: center; outline: none; border: none; border-radius: 3px; } .item__content-add:hover > i { color: black; } .item__content-add-list { display: none; position: absolute; right: -50px; list-style: none; background: var(--white-color); padding: 0; width: 300px; border-radius: 3px; } .item__content-add-item { display: flex; padding: 12px; justify-content: space-between; align-items: center; } .item__content-add:focus .item__content-add-list { animation: fadeIn linear 0.3s; display: block; } .item__content-add-item:hover { background-color: rgba(0, 0, 0, 0.2); border-radius: 3px; } </style> <style scoped> .container { position: relative; } .item { padding: 8px 12px; text-decoration: none; color: var(--text-color); } .item__img { position: relative; } .max-line { overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; } .item__img > span { background-color: rgba(0, 0, 0, 0.8); position: absolute; bottom: 10px; right: 16px; color: white; font-size: 1.4rem; font-weight: 600; line-height: 1.8rem; padding: 2px; border-radius: 2px; } .item__img > img { width: 100%; height: 100%; } .item__content { max-width: 640px; min-width: 0px; position: relative; } .item__content-title { font-size: 1.8rem; font-weight: 500; line-height: 2.4rem; margin: 0; } .item__content-middle { font-size: 1.4rem; line-height: 2rem; color: rgba(0, 0, 0, 0.7); } .item__content-view { margin-left: 12px; } .item__content-des { font-size: 1.4rem; line-height: 1.8rem; color: rgba(0, 0, 0, 0.7); margin-top: 12px; } @media (max-width: 739px) { .item__content-view { display: block; margin-left: 0; } } </style>
interface Car { manufacturer: string; model: string; [key: string]: any; } function storeCarInfo(manufacturer: string, model: string, ...extras: [string, any][]): Car { const car: Car = { manufacturer, model }; for (const [key, value] of extras) { car[key] = value; } return car; } // Calling storeCarInfo() with required and optional information const carInfo = storeCarInfo("Tesla", "Model 3", ["color", "red"], ["feature", "autopilot"]); // Printing the car object console.log(carInfo);
package ru.baccasoft.cherkizovo.data.repos.implimentations import android.content.Context import android.os.Handler import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import ru.baccasoft.cherkizovo.R import ru.baccasoft.cherkizovo.data.* import ru.baccasoft.cherkizovo.data.core.network.models.UserId import ru.baccasoft.cherkizovo.data.repos.DocumentActionsRepo import ru.baccasoft.cherkizovo.data.repos.DocumentsRepo import ru.baccasoft.cherkizovo.data.repos.ViewedDocumentsRepo import ru.baccasoft.cherkizovo.extantions.toCalendar import ru.baccasoft.cherkizovo.features.agreementList.AgreementItemVo import ru.baccasoft.cherkizovo.features.agreementList.AgreementRightSegmentVo import ru.baccasoft.cherkizovo.features.agreementList.ExecutionMethod import ru.baccasoft.cherkizovo.features.documentDetal.* import ru.baccasoft.cherkizovo.features.documentsList.DocumentType import ru.baccasoft.cherkizovo.features.documentsList.TaskListItemEndComparator import ru.baccasoft.cherkizovo.features.documentsList.TaskListItemStartComparator import ru.baccasoft.cherkizovo.features.documentsList.TaskListItemVo import ru.baccasoft.cherkizovo.features.filterDocuments.Filter import ru.baccasoft.cherkizovo.features.filterDocuments.FilterShow import ru.baccasoft.cherkizovo.features.processedDocumentsList.ProcessedTaskListItemVo import java.math.BigDecimal import java.util.* import kotlin.collections.ArrayList import kotlin.random.Random.Default.nextBoolean import kotlin.random.Random.Default.nextInt /**** * Фейковый репозиторий для документов, нужен чтобы тестить UI документов без сервера, * в случае любых действий над документом просто удаляет его из списка доков */ class DocumentsFakeRepoImpl( private val viewedTasksRepo: ViewedDocumentsRepo, private val docChangeNotificator: DocChangeNotificator ): DocumentsRepo, DocumentActionsRepo { private val fakes = getFakeList() private val delay = 500L private var filter = Filter() override fun getDocuments( ctx: Context, onSuccess: (List<TaskListItemVo>, List<TaskListItemVo>, Int) -> Unit, onError: (DataAccessError) -> Unit ) { val viewedIds = viewedTasksRepo.getItems() fakes.forEach { val itemData = it.getFavIdentifier() it.isNew = !viewedIds.contains(itemData) } val filterList = filterDocuments() Handler().postDelayed({ onSuccess(ArrayList(), fakes, fakes.size) }, delay) return } override fun getProcessedDocuments( ctx: Context, userId: String, onSuccess: (List<ProcessedTaskListItemVo>, Long) -> Unit, onError: (DataAccessError) -> Unit ) { val viewedIds = viewedTasksRepo.getItems() fakes.forEach { val itemData = it.getFavIdentifier() it.isNew = !viewedIds.contains(itemData) } val filterList = filterDocuments() Handler().postDelayed({ onSuccess(ArrayList(), fakes.size.toLong()) }, delay) return } override fun getDocumentDetail( approvalId: Long, ctx: Context, onSuccess: (TaskDetalVo) -> Unit, onError: (DataAccessError) -> Unit ) { Handler().postDelayed({onSuccess(getFakeDetal(approvalId, nextBoolean()))},delay) } private fun getFakeList():ArrayList<TaskListItemVo>{ val out = ArrayList<TaskListItemVo>() for (i in 1..20){ out.add(getOneListItem(i.toLong())) } return out } private fun getOneListItem(id: Long): TaskListItemVo { val type = getRndDocType() val out = TaskListItemVo( taskId = id, title= "title $id", endDate= "endDate", startDate = "startDate", isOverdue = false, subTitle= "subTitle:" + type.name, rightHint= "rightHint", directionText= "directionText", funcText= "funcText", catText= "catText", isNew = false, approvalListId = id, actions = getActions(id), documentType = type, subWorkId = -1, traceError = false, sumText = "sumText", contractIds = "test".split("") ) return out } private fun getRndDocType(): DocumentType{ val types = DocumentType.values() val rndType = types[nextInt(types.size)] return rndType } private fun getActions(taskId: Long): List<DocumentActionData>{ val positive = DocumentActionData( approvalId = 0L, actionType = ActionType.POSITIVE, approvalListId = taskId, subWorkId = -1, dispositionType = "approve", disposition = "Согласовано", comment = "" ) val negative = DocumentActionData( approvalId = 0L, actionType = ActionType.NEGATIVE, approvalListId= taskId, subWorkId = -1, dispositionType = "reject", disposition= "Отклонено", comment = "" ) val group = DocumentActionData( approvalId = 0L, actionType = ActionType.GROUP_ACCEPT, approvalListId= taskId, subWorkId = -1, dispositionType = "", disposition= "", comment = "" ) val out = ArrayList<DocumentActionData>() out.add(positive) out.add(negative) out.add(group) return out } private fun getFakeDetal(id: Long, isGroup: Boolean): TaskDetalVo{ val docs = ArrayList<TaskDocumentVo>() val attachs = ArrayList<AttachmentVO>() attachs.add( AttachmentVO( "attach 1 йцуйцу йцуй йцуйцуйцуйц уййцуйцу йцуйцу йцуйцу йцу ййцу", "http://ya.ru", "Договор sdjhfk hksjf ksjhfsdkjfh sdfsdkjfh sdfkjsd sfkjsdhfj skfhs dk sdfskjdf sdfs sfs sdf sdf sddfsddfsdf s.docx" ) ) attachs.add( AttachmentVO( "attach 2 йцуйц йцуйц йцу йцуйц уйцу йцу йцу йцу йцуйц у йцу", "33095712", "Договор.docx" ) ) docs.add( TaskDocumentVo( docTitle= "docTitle 1", docSubtitle= "docSubtitle", rightTitle= "rightTitle", docSummText= "docSummText", docLawTimeText= "docLawTimeText", docInnerTimeText= "docInnerTimeText", capexCodeHint= "capexCodeHint", capexCodeText= "capexCodeText", capexHint= "capexHint", capexText= "capexText", bottomText= "bottomTex", attachs = attachs ) ) docs.add( TaskDocumentVo( docTitle= "docTitle 2", docSubtitle= "docSubtitle", rightTitle= "rightTitle", docSummText= "docSummText", docLawTimeText= "docLawTimeText", docInnerTimeText= "docInnerTimeText", capexCodeHint= "capexCodeHint", capexCodeText= "capexCodeText", capexHint= "capexHint", capexText= "capexText", bottomText= "bottomTex", attachs = attachs ) ) val type = getRndDocType() val out = TaskDetalVo( docId= id, title= "title $id", subTitle= "subTitle $id", rightTitle="rightTitle", date="date", startDate = "startDate", isOverdue = false, commentAuthor = "commentAuthor", commentText = "commentText", commentDate = "commentDate", standardForm = "standardForm", directionText= "directionText $type" , funcText= "funcText", catsText= "catsText", sidesText= "sidesText", collisionsLogText= "collisionsLogText", needCorpAgreementText= "needCorpAgreementText", agentNumberText= "agentNumberText", versionNumberText= "versionNumberText", barCodeText= "barCodeText", documentFullSum = "sample sum", actions = getActions(id), approvalListId= -1, docs = docs, documentType = type, level= "", subWorkID = -1, errorText = "", pvpLinks = arrayListOf( LinkVo("Протокол выбора поставщика ПВП-126", "Согласование", "Требуется уточнение данных")), ipLinks = arrayListOf() ) return out } override fun getAgreementsForDocument( taskId: Long, ctx: Context, onSuccess: (List<AgreementItemVo>) -> Unit, onError: (DataAccessError) -> Unit ) { val out = ArrayList<AgreementItemVo>() @ColorInt var prevItemColor = ContextCompat.getColor(ctx, R.color.transparent) for( a in 0..3){ val itemColor = prevItemColor val rightItems = ArrayList<AgreementRightSegmentVo>() for (i in 0..2) { val item = AgreementRightSegmentVo( topHint = "Безопасность", delegator = "Петров", executor = "Петров", executionMethod = ExecutionMethod.DELEGATED, date = "10.02.2020", showRedIcon = false, showGreenIcon = true, refPartners = "ЧМПЗ, Группа Черкизово, Название ЮЛ, Название ЮЛ", refNumbers = "ОТД-2795,ДС-1, ДС-2" ) rightItems.add(item) } val item = AgreementItemVo( title = "Подписание", startDateText = "", endDateText = "", prevItemColor = prevItemColor, currentItemColor = itemColor, rightSegments = rightItems ) prevItemColor = itemColor out.add(item) } onSuccess(out) } override fun getCommentsForDocument( taskId: Long, ctx: Context, onSuccess: (List<CommentVo>) -> Unit, onError: (DataAccessError) -> Unit ) { onSuccess(ArrayList()) } override fun filterDocuments(): List<TaskListItemVo> { val taskListItemVo = ArrayList<TaskListItemVo>() taskListItemVo.addAll(fakes.filter { filterTaskListItem(it) }) if (filter.sortAscClose != null) { Collections.sort(taskListItemVo, TaskListItemEndComparator()) if (filter.sortAscClose == false) taskListItemVo.reverse() } if (filter.sortAscBegin != null) { Collections.sort(taskListItemVo, TaskListItemStartComparator()) if (filter.sortAscBegin == false) taskListItemVo.reverse() } return taskListItemVo } override fun saveFilter( filterShow: FilterShow?, dateFromClose: String, dateSinceClose: String, dateFromBegin: String, dateSinceBegin: String, sortAscClose: Boolean?, sortAscBegin: Boolean? ) { this.filter = Filter( filterShow ?: FilterShow.SHOW_ALL, dateFromClose.toCalendar()?.time, dateSinceClose.toCalendar()?.time, dateFromBegin.toCalendar()?.time, dateSinceBegin.toCalendar()?.time, sortAscClose, sortAscBegin ) } override fun clearFilter() { filter = Filter() } override fun getFilter() = filter override fun delegate( docIds: List<String>, docApprovalIds: List<String>, personId: Long, onSuccess: () -> Unit, onError: (String) -> Unit ) { val ids = docIds.map {it.toLong() } val items = fakes.filter{ids.contains(it.approvalListId)} fakes.removeAll(items) val docIds = docIds.mapNotNull { it.toLongOrNull() } docChangeNotificator.notifyDocumentChange(docIds, false) Handler().postDelayed({onSuccess()},delay) } override fun addAction( list: List<DocumentActionData>, username: String, onSuccess: () -> Unit, onError: (String) -> Unit ) { val ids = list.map {it.approvalListId } val items = fakes.filter{ids.contains(it.approvalListId)} fakes.removeAll(items) val docIds = list.map { it.approvalListId } docChangeNotificator.notifyDocumentChange(docIds, false) Handler().postDelayed({onSuccess()},delay) } override fun addComment( approvalId: Long, comment: String, onSuccess: () -> Unit, onError: (DataAccessError) -> Unit ) { onError(CommonDataAccessError("not implemented")) } override fun acceptGroupAction( approvalListId: Long, subWorkId: Long, onSuccess: () -> Unit, onError: (DataAccessError) -> Unit ) { docChangeNotificator.notifyDocumentChange( listOf(approvalListId), true ) Handler().postDelayed({onSuccess()},delay) // Handler().postDelayed({onError(GroupTaskActionError(true))},delay) // Handler().postDelayed({onError(GroupTaskActionError(true))},delay) } private fun filterTaskListItem(taskListItemVo: TaskListItemVo): Boolean { val typePassed = when (filter.showDocuments) { FilterShow.SHOW_ALL -> taskListItemVo.documentType == DocumentType.COMMON || taskListItemVo.documentType == DocumentType.GROUP_TASK || taskListItemVo.documentType == DocumentType.COMMENT_DECISION FilterShow.SHOW_OUR -> taskListItemVo.documentType == DocumentType.COMMENT_DECISION || taskListItemVo.documentType == DocumentType.COMMON FilterShow.SHOW_GROUP -> taskListItemVo.documentType == DocumentType.GROUP_TASK } val dateEnd = taskListItemVo.endDate.toCalendar()?.time val dateCloseFromPassed = when { filter.timeCloseFrom == null -> true dateEnd == null -> false else -> dateEnd.after(filter.timeCloseFrom) || dateEnd == filter.timeCloseFrom } val dateCloseSincePassed = when { filter.timeCloseSince == null -> true dateEnd == null -> false else -> dateEnd.before(filter.timeCloseSince) || dateEnd == filter.timeCloseSince } val dateStart = taskListItemVo.startDate.toCalendar()?.time val dateBeginFromPassed = when { filter.timeBeginFrom == null -> true dateStart == null -> false else -> dateStart.after(filter.timeBeginFrom) || dateStart == filter.timeBeginFrom } val dateBeginSincePassed = when { filter.timeBeginSince == null -> true dateStart == null -> false else -> dateStart.after(filter.timeBeginSince) || dateStart == filter.timeBeginSince } return typePassed && dateCloseFromPassed && dateCloseSincePassed && dateBeginFromPassed && dateBeginSincePassed } }
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'; import { MinioService } from 'nestjs-minio-client'; import { ConfigService } from '@nestjs/config'; import { User } from '@user/entities/user.entity'; import { BufferedFile } from '@root/minio-client/file.model'; import * as crypto from 'node:crypto'; @Injectable() export class MinioClientService { private readonly logger: Logger; private readonly baseBucket: string; public get client() { return this.minio.client; } constructor( private readonly minio: MinioService, private readonly configService: ConfigService, ) { this.logger = new Logger('MinioStorageService'); this.baseBucket = this.configService.get<string>('MINIO_BUCKET'); } public async uploadProfileImg( user: User, file: BufferedFile, categoryName: string, baseBucket: string = this.baseBucket, ): Promise<string> { if (!(file.mimetype.includes('jpg') || file.mimetype.includes('png'))) { throw new HttpException( 'Error uploading file type', HttpStatus.BAD_REQUEST, ); } const temp_filename = Date.now().toString(); const hashedFileName = crypto .createHash('md5') .update(temp_filename) .digest('hex'); const ext = file.originalname.substring( file.originalname.lastIndexOf('.'), file.originalname.length, ); const metaData = { 'Content-Type': file.mimetype, 'X-Amz-Meta-Testing': 1234, }; const filename = hashedFileName + ext; const fileBuffer = file.buffer; const filePath = `${categoryName}/${user.id}/${filename}`; if (`${categoryName}/${user.id}`.includes(user.id)) { await this.deleteFolderContents( this.baseBucket, `${categoryName}/${user.id}/`, ); } this.client.putObject( baseBucket, filePath, fileBuffer, fileBuffer.length, metaData, function (err) { if (err) throw new HttpException( 'Error uploading file', HttpStatus.BAD_REQUEST, ); }, ); return `http://${this.configService.get('MINIO_ENDPOINT')}:${this.configService.get('MINIO_PORT')}/${this.configService.get('MINIO_BUCKET')}/${filePath}`; } deleteFolderContents = async (bucketName, folderPath) => { const objectsList = []; const stream = this.client.listObjects(bucketName, folderPath, true); for await (const obj of stream) { objectsList.push(obj.name); } if (objectsList.length > 0) { const deleteResult = await this.client.removeObjects( bucketName, objectsList, ); console.log('Deleted Objects:', deleteResult); } else { console.log('No Objects found to delete'); } }; }
方法一 合并后排序 ``` void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { for(int i=m,j=0;i<m+n;i++,j++) nums1[i]=nums2[j]; sort(nums1.begin(),nums1.end()); } ``` 方法二 双指针1 从前到后 ``` void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int p=0,i=0,j=0; vector<int> tmp(nums1.begin(),nums1.begin()+m); while(i<m&&j<n) nums1[p++] = (tmp[i] < nums2[j]) ? tmp[i++] : nums2[j++]; while(j<n) nums1[p++] = nums2[j++]; while(i<m) nums1[p++] = tmp[i++]; } ``` 方法三 双指针2 从后到前 ``` class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int p1=m-1,p2=n-1,p=m+n-1; while(p1>=0&&p2>=0){ nums1[p--]=nums1[p1]>nums2[p2]? nums1[p1--]:nums2[p2--]; } if(p1<0){ while (p2 >= 0) nums1[p--] = nums2[p2--]; } } }; ```
import { Outlet } from "react-router-dom" import Header from "./Header" import Menu from "./Menu" import MainStyle from "./MainStyle" import { useEffect } from "react" import { useAppDispatch } from "../store/store" import { setTheme } from "../store/ThemeSlice" const Layout = () => { const mainStyle = MainStyle(); const dispatch = useAppDispatch() useEffect(()=>{ const theme = localStorage.getItem("theme"); dispatch(setTheme(theme == "true")) } , [dispatch]) return ( <div className="d-flex" style={{background: mainStyle.background , color: mainStyle.color}}> <div> <Menu /> </div> <div className="w-100 app"> <Header /> <div className="p-3 outlet" > <Outlet></Outlet> </div> <footer className="text-center"> <p>Made With <span className="fs-3 fw-semibold text-danger">Kamel Maher</span></p> </footer> </div> </div> ) } export default Layout
package game.interfaces; import edu.monash.fit2099.engine.actors.Actor; /** * A consumable interface * Created by: * @author Wong Yik Ping * Modified by: * */ public interface Consumable { /** * Implements what happen when a consumable is consumed * * @param actor actor consuming the item * @return result of consumption of item */ String consumeItem(Actor actor); /** * return quantity of consumable remaining * @return quantity of consumable remaining */ int getCurrentAmount(); /** * return max quantity of consumable available * @return max quantity of consumable available */ int getMaxAmount(); }
<template> <div class="border border-gray-500 dark:border-gray-300 rounded-md p-3 mx-auto w-full lg:w-2/3 xl:w-1/2"> <h3 class="text-2xl font-semibold text-center text-gray-900 dark:text-white">{{ props.title }}</h3> <div class="text-center mb-2"> <a v-for="link in props.links" :href="link.url" class="font-mono inline-block hover:underline mx-2">{{ link.label }}</a> </div> <p class="text-lg whitespace-pre-wrap mb-2 text-gray-500 dark:text-gray-400"> <slot></slot> </p> <img :src="props.image" alt="" class="max-w-full max-h-96 mx-auto"> </div> </template> <script setup lang="ts"> import type { PropType } from "vue"; const props = defineProps({ title: String, links: Object as PropType<{ label: string, url: string }[]>, image: String }); </script>
import { AppBar, Toolbar, IconButton, Typography } from '@material-ui/core'; import { KeyboardArrowLeft, KeyboardArrowRight } from '@material-ui/icons'; import { useEffect, useState } from 'react'; import { Link, useLocation } from 'react-router-dom'; import useStyles from './styles'; const Navbar = ({ setPath }) => { const classes = useStyles(); const location = useLocation(); const [nextPage, setNextPage] = useState('/') const [previousPage, setPreviousPage] = useState('/') useEffect(() => { const paths = ['/', '/Sushi', '/Maze', '/Contact'] paths.forEach((path, index) => { if (location.pathname === path) { setPreviousPage(paths[index === 0 ? 3 : index - 1]) setNextPage(paths[(index + 1) % paths.length]) } }) }, [location]) return ( <> <AppBar position='fixed' className={classes.appbar} > <Toolbar > <IconButton onClick={() => setPath(previousPage)} aria-label="previous" component={Link} to={previousPage} className={classes.hover}> <KeyboardArrowLeft /> </IconButton> <Typography onClick={() => setPath('/')} component={Link} to="/" variant="h5" className={classes.hover} style={{ fontWeight: '600', textDecoration: 'none' }} > James Hall </Typography> <IconButton onClick={() => setPath(nextPage)} aria-label="next" component={Link} to={nextPage} className={classes.hover} > <KeyboardArrowRight /> </IconButton> <Typography onClick={() => setPath('/Sushi')} component={Link} to="/Sushi" variant="h6" className={classes.buttons} > Sushi </Typography> <Typography onClick={() => setPath('/Maze')} component={Link} to="/Maze" variant="h6" className={classes.buttons}> Maze </Typography> <Typography onClick={() => setPath('/Contact')} component={Link} to="/Contact" variant="h6" className={classes.buttons} > Contact </Typography> </Toolbar> </AppBar > </> ); }; export default Navbar
// Copyright (c) Meta Platforms, Inc. and affiliates. (http://www.meta.com) #pragma once #include "Python.h" #include <functional> #include <memory> #include <string> #include <vector> namespace jit { struct Option { // required std::string cmdline_flag; std::string environment_variable; std::function<void(std::string)> callback_on_match; std::string flag_description; // optional std::string flag_param_name; std::string debug_message; bool hidden_flag = false; Option(){}; std::string getFormatted_cmdline_flag(); std::string getFormatted_environment_variable(); Option( const std::string cmdline_flag, const std::string environment_variable, std::function<void(std::string)> callback_on_match, const std::string flag_description) { this->cmdline_flag = cmdline_flag; this->environment_variable = environment_variable; this->callback_on_match = callback_on_match; this->flag_description = flag_description; } // Normally, when the relevant flag is set a debug log message // will be generated. By setting the debug message here, this // auto generated message will be overriden Option& withDebugMessageOverride(const std::string debug_message) { this->debug_message = debug_message; return *this; } // Allows the definition of a flag parameter name which will // apear on the expanded help message for the Option Option& withFlagParamName(const std::string flag_param_name) { this->flag_param_name = flag_param_name; return *this; } // Set this to true to hide the flag from the help text Option& isHiddenFlag(const bool hidden_flag) { this->hidden_flag = hidden_flag; return *this; } private: std::string getFormatted(std::string); }; struct FlagProcessor { Option& addOption( const std::string cmdline_flag, const std::string environment_variable, std::function<void(int)> callback_on_match, const std::string flag_description); Option& addOption( const std::string cmdline_flag, const std::string environment_variable, std::function<void(std::string)> callback_on_match, const std::string flag_description); Option& addOption( const std::string cmdline_flag, const std::string environment_variable, bool& variable_to_bind_to, const std::string flag_description); Option& addOption( const std::string cmdline_flag, const std::string environment_variable, int& variable_to_bind_to, const std::string flag_description); Option& addOption( const std::string cmdline_flag, const std::string environment_variable, size_t& variable_to_bind_to, const std::string flag_description); Option& addOption( const std::string cmdline_flag, const std::string environment_variable, std::string& variable_to_bind_to, const std::string flag_description); // passing the xoptions dict from the command line will result in the // associated 'variable_to_bind_to' previously passed being assigned with the // appropriate value if the key exists in this map. If it cannot be found then // the environment variables will be interrogated and the associated value // assigned. // * In the case of a string variable_to_bind_to this will be a string // representation of the value // * In the case of a size_t variable_to_bind_to this will be a size_t // parse of the value // * In the case of a int variable_to_bind_to this will be a 1 (no further // parsing takes place). void setFlags(PyObject* xoptions); // Generates a nicely formatted representation of the added Option // flag_description's previously registered std::string jitXOptionHelpMessage(); // Return true if one or more flags have been registered bool hasOptions(); // Return true if the option has been added and false otherwise. bool canHandle(const char* provided_option); private: std::vector<std::unique_ptr<Option>> options_; }; } // namespace jit
const searchFood = async () => { const searchField = document.getElementById("search-field"); const searchText = searchField.value; searchField.value = ""; const url = `https://www.themealdb.com/api/json/v1/1/search.php?s=${searchText}`; const res = await fetch(url); const data = await res.json(); displaySarchResult(data) // fetch(url) // .then((res) => res.json()) // .then((data) => displaySarchResult(data)); .catch((error) => console.log(error)); }; const displaySarchResult = (meals) => { const searchResult = document.getElementById("search-result"); searchResult.innerHTML = ""; for (let meal of meals.meals) { // console.log(meal); const div = document.createElement("div"); div.classList.add("col"); div.innerHTML = `<div onclick="loadMealDetail(${meal.idMeal})" class="card"> <img src="${meal.strMealThumb}" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">${meal.strMeal}</h5> <p class="card-text"> ${meal.strInstructions.slice(0, 200)} </p> </div> </div>`; searchResult.appendChild(div); } }; const loadMealDetail = (mealid) => { console.log(mealid); const url = `https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealid}`; fetch(url) .then((res) => res.json()) .then((data) => displayMealDetails(data.meals[0])); }; const displayMealDetails = (meal) => { console.log(meal); const mealDetails = document.getElementById("meal-details"); mealDetails.textContent = ""; const div = document.createElement("div"); div.classList.add("card"); div.innerHTML = ` <img src="${meal.strMealThumb}" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">${meal.strMeal}</h5> <p class="card-text"> ${meal.strInstructions.slice(0, 150)} </p> <a href="${ meal.strYoutube }" class="btn btn-primary">Go somewhere</a> </div> `; mealDetails.appendChild(div); };
import { render, screen } from '@testing-library/react'; import App from './paginas/Principal/App'; import { BrowserRouter, MemoryRouter, Routes, Route } from 'react-router-dom'; import Cartoes from './componentes/Cartoes'; import AppRoutes from './routes'; describe('Rotas da aplicação', () => { test('Deve renderizar a rota principal', () => { render(<App/>, { wrapper: BrowserRouter }); const usuario = screen.getByText('Olá, Joana :)!'); expect(usuario).toBeInTheDocument(); }); test('Deve renderizar a rota Cartões', () => { const rota = '/cartoes'; render(<MemoryRouter initialEntries={[rota]}> <Routes> <Route path='/' element={<App/>}> <Route path='cartoes' element={<Cartoes/>}/> </Route> </Routes> </MemoryRouter>); const meusCartoes = screen.getByText('Meus cartões'); expect(meusCartoes).toHaveTextContent('Meus cartões'); }) // testando o useLocation test('Deve renderizar a localização da rota atual', () => { const rota = '/'; render(<MemoryRouter initialEntries={[rota]}> <App/> </MemoryRouter>); const localizacaoAtual = screen.getByTestId('local'); expect(localizacaoAtual).toHaveTextContent(rota); }); test('Deve renderizar rotas serviços', () => { const rota = '/servicos' render(<MemoryRouter initialEntries={[rota]}> <AppRoutes/> </MemoryRouter>) const texto = screen.getByText('Empréstimo') expect(texto).toBeInTheDocument() }) test('Deve renderizar a página 404', () => { const rota = '/pagina_nao_existente'; render(<MemoryRouter initialEntries={[rota]}> <AppRoutes/> </MemoryRouter>); const paginaErro = screen.getByTestId('pagina-404'); expect(paginaErro).toContainHTML('<h1>Ops! Não encontramos a página</h1>'); }) })
<?php namespace Hitocean\Generator\Commands\Generators\Frontend\Writer; use Hitocean\Generator\Commands\Generators\FileAdmin; use Illuminate\Support\Str; class ServiceWriter { public static function createFile(string $folder, string $name, string $route) { $directory = static::path($folder, $name); $lowerName = Str::lower($name); $upperName = Str::ucfirst($name); $pluralUpperName = Str::pluralStudly($upperName); FileAdmin::writeFile( 'model', base_path($directory), [ 'upperNamePlural' => $pluralUpperName, 'upperName' => $upperName, 'lowerName' => $lowerName, 'route' => $route, ], base_path('app/Console/Generators/Frontend/Stubs/service.stub') ); } private static function path($rootName, $name): string { $upperName = Str::ucfirst($name); return "frontend/$rootName/services/{$upperName}Service.ts"; } }
import React, {useContext, useState} from 'react' import profilepic3 from "../images/profilepic3.jpg" import { collection, doc, getDoc, getDocs, query, serverTimestamp, setDoc, updateDoc, where } from "firebase/firestore"; import {db} from '../firebase'; import {AuthContext} from '../context/AuthContext'; import {FcAddImage} from 'react-icons/fc'; import {BsSearch} from 'react-icons/bs'; import {IoMdClose, IoMdCloseCircleOutline} from 'react-icons/io'; const Search = () => { const [username, setUsername] = useState("") const [user, setUser] = useState("") const [err, setErr] = useState(false) const {currentUser} = useContext(AuthContext) // Search user const handleSearch = async () => { // checking with Enter const q = query(collection(db, "users"), where("displayName", "==", username)) try { // Getting searched user data.. const querySnapshot = await getDocs(q); querySnapshot.forEach((doc) => { // doc.data() is never undefined for query doc snapshots setUser(doc.data()) }); } catch (error) { setErr(true) } } // Press Enter const handleKey = (e) => { e.code === "Enter" && handleSearch(); } // click search user const handleSelect = async () => { // check whether the group( chats in firestore) exists, if not create. const combinedId = currentUser.uid > user.uid ? currentUser.uid + user.uid : user.uid + currentUser.uid console.log(combinedId); try { const res = await getDoc(doc(db, "chats", combinedId)); if (! res.exists()) { // create chat in chat collection await setDoc(doc(db, "chats", combinedId), {messages: []}); // create user chats await updateDoc(doc(db, "userChat", currentUser.uid), { [combinedId + ".userInfo"]: { uid: user.uid, displayName: user.displayName, photoURL: user.photoURL }, [combinedId + ".date"]: serverTimestamp() }); await updateDoc(doc(db, "userChat", user.uid), { [combinedId + ".userInfo"]: { uid: currentUser.uid, displayName: currentUser.displayName, photoURL: currentUser.photoURL }, [combinedId + ".date"]: serverTimestamp() }); } } catch (error) {} setUser(null) setUsername("") } const handleClose = () => { setUser(null) } return ( <> <div className='md:pr-20 md:pl-5 p-5 md:pt-0 pt-7 flex gap-5'> <input className="w-full placeholder:font-italitc border relative md:bg-gray-100 placeholder-gray-500 drop-shadow-md md:rounded-2xl rounded-lg md:py-2 py-4 pl-3 pr-10 focus:outline-none" placeholder="Search user" type="text" value={username} onKeyDown={handleKey} onChange={ e => setUsername(e.target.value) }/> <div className=' md:hidden bg-white px-7 py-1 rounded-lg '> <h1 className='absolute top-[108px] right-[36px] md:hidden text-gray-500' onClick={handleSearch}><BsSearch size={26}/> </h1> </div> { err ? <span className='bg-green-600'>user not found</span> : "" } </div> {/* search user */} { user && <div className=' fixed bg-black bg-opacity-25 backdrop-blur-sm md:fle justify-center items-center z-20 md:w-[27%] w-full '> <div className='absolut'> <div className=' flex items-center p-2 gap-3 bg-gray-200 cursor-pointer w-screen md:w-full relative ' onClick={handleSelect}> <img className='h-16 w-16 bg-red-400 rounded-full object-cover' src={ user.photoURL } alt="sdf"/> <h1 className=' text-sm font-medium'> { user.displayName }</h1> </div> <h1 className=' absolute top-7 right-9 cursor-pointer' onClick={handleClose}><IoMdCloseCircleOutline size={26}/></h1> </div> </div> } <div className='h-[1px] bg-black mx-5 '></div> </> ) } export default Search
///// //// FullScreenAssetViewController.swift /// Copyright © 2019 Dmitriy Borovikov. All rights reserved. // import UIKit import Photos protocol FullScreenAssetViewControllerProtocol { func selectPhoto(asset: PHAsset) } class FullScreenAssetViewController: UIViewController, UIScrollViewDelegate { private let scrollView = UIScrollView() private let imageView = UIImageView() private let activityIndicator = UIActivityIndicatorView(style: .whiteLarge) var asset: PHAsset! var delegate: FullScreenAssetViewControllerProtocol? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white scrollView.frame = view.bounds scrollView.contentInsetAdjustmentBehavior = .never scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(scrollView) scrollView.delegate = self addGestureRecognizers() let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(tapDoneButton(_:))) navigationItem.rightBarButtonItem = doneItem let cancelItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(tapCancelButton(_:))) navigationItem.leftBarButtonItem = cancelItem scrollView.addSubview(self.imageView) activityIndicator.frame = view.bounds activityIndicator.backgroundColor = .lightGray scrollView.addSubview(activityIndicator) activityIndicator.hidesWhenStopped = true activityIndicator.startAnimating() PHImageManager.default().requestFullImage(for: asset) .done { image, _ in self.imageView.image = image self.activityIndicator.stopAnimating() self.imageView.sizeToFit() self.scrollView.contentSize = self.imageView.bounds.size self.setZoomScale() let yOffset = self.scrollView.frame.size.height - self.imageView.frame.size.height self.scrollView.contentOffset = CGPoint(x: 0, y: -yOffset / 2) }.catch { error in self.navigationController?.popViewController(animated: true) } } @objc func tapDoneButton(_ sender: Any) { delegate?.selectPhoto(asset: asset) navigationController?.popViewController(animated: true) } @objc func tapCancelButton(_ sender: Any) { navigationController?.popViewController(animated: true) } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } override func viewWillLayoutSubviews() { setZoomScale() } func scrollViewDidZoom(_ scrollView: UIScrollView) { let imageSize = imageView.frame.size let scrollSize = scrollView.bounds.size let verticalPadding = imageSize.height < scrollSize.height ? (scrollSize.height - imageSize.height) / 2 : 0 let horizontalPadding = imageSize.width < scrollSize.width ? (scrollSize.width - imageSize.width) / 2 : 0 scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding) } func setZoomScale() { let imageViewSize = imageView.bounds.size let scrollViewSize = scrollView.bounds.size let widthScale = scrollViewSize.width / imageViewSize.width let heightScale = scrollViewSize.height / imageViewSize.height scrollView.minimumZoomScale = min(widthScale, heightScale) scrollView.zoomScale = scrollView.minimumZoomScale } func addGestureRecognizers() { let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(recognizer:))) singleTap.numberOfTapsRequired = 1 singleTap.delegate = self scrollView.addGestureRecognizer(singleTap) let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(recognizer:))) doubleTap.numberOfTapsRequired = 2 scrollView.addGestureRecognizer(doubleTap) } @objc func handleSingleTap(recognizer: UITapGestureRecognizer) { let isHidden = !(navigationController?.navigationBar.isHidden ?? true) navigationController?.setNavigationBarHidden(isHidden, animated: true) view.backgroundColor = isHidden ? .black : .white } @objc func handleDoubleTap(recognizer: UITapGestureRecognizer) { if (scrollView.zoomScale > scrollView.minimumZoomScale) { scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true) } else { scrollView.setZoomScale(scrollView.maximumZoomScale, animated: true) } } } extension FullScreenAssetViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
//package com.gstdev.cloud.rest.service.configuration; // //import com.gstdev.cloud.commons.ass.core.annotation.ConditionalOnSwaggerEnabled; //import com.gstdev.cloud.commons.ass.core.context.ServiceContextHolder; //import com.gstdev.cloud.commons.ass.definition.constants.BaseConstants; //import com.gstdev.cloud.rest.core.definition.OpenApiServerResolver; //import com.gstdev.cloud.rest.condition.properties.SwaggerProperties; //import com.google.common.collect.ImmutableList; //import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; //import io.swagger.v3.oas.annotations.security.*; //import io.swagger.v3.oas.models.ExternalDocumentation; //import io.swagger.v3.oas.models.OpenAPI; //import io.swagger.v3.oas.models.info.Info; //import io.swagger.v3.oas.models.info.License; //import io.swagger.v3.oas.models.servers.Server; //import jakarta.annotation.PostConstruct; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; //import org.springframework.boot.context.properties.EnableConfigurationProperties; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; // ///** // * <p>Description: 服务信息配置类 </p> // * // * @author : cc // * @date : 2021/6/13 13:40 // */ //@Configuration(proxyBeanMethods = false) //@ConditionalOnSwaggerEnabled //@EnableConfigurationProperties(SwaggerProperties.class) //@SecuritySchemes({ // @SecurityScheme(name = BaseConstants.OPEN_API_SECURITY_SCHEME_BEARER_NAME, type = SecuritySchemeType.OAUTH2, bearerFormat = "JWT", scheme = "bearer", // flows = @OAuthFlows( // password = @OAuthFlow(authorizationUrl = "http://localhost:8101/oauth2/authorize", tokenUrl = "http://localhost:8101/oauth2/token" // , refreshUrl = "http://localhost:8101/oauth2/token", scopes = @OAuthScope(name = "all")) //// password = @OAuthFlow(authorizationUrl = "${herodotus.endpoint.authorization-uri}", tokenUrl = "${herodotus.endpoint.access-token-uri}", refreshUrl = "${herodotus.endpoint.access-token-uri}", scopes = @OAuthScope(name = "all")), //// clientCredentials = @OAuthFlow(authorizationUrl = "${herodotus.endpoint.authorization-uri}", tokenUrl = "${herodotus.endpoint.access-token-uri}", refreshUrl = "${herodotus.endpoint.access-token-uri}", scopes = @OAuthScope(name = "all")) //// authorizationCode = @OAuthFlow(authorizationUrl = "${herodotus.platform.endpoint.user-authorization-uri}", tokenUrl = "${herodotus.platform.endpoint.access-token-uri}", refreshUrl = "${herodotus.platform.endpoint.access-token-uri}", scopes = @OAuthScope(name = "all")) // )), //}) //public class SpringdocConfiguration { // // private static final Logger log = LoggerFactory.getLogger(SpringdocConfiguration.class); // // @PostConstruct // public void postConstruct() { // log.debug("[GstDev Cloud] |- Module [Open Api] Auto Configure."); // } // // @Bean // @ConditionalOnMissingBean // public OpenApiServerResolver openApiServerResolver() { // OpenApiServerResolver resolver = () -> { // Server server = new Server(); // server.setUrl(ServiceContextHolder.getInstance().getUrl()); // return ImmutableList.of(server); // }; // log.trace("[GstDev Cloud] |- Bean [Open Api Server Resolver] Auto Configure."); // return resolver; // } // // @Bean // @ConditionalOnMissingBean // public OpenAPI createOpenApi(OpenApiServerResolver openApiServerResolver) { // return new OpenAPI() // .servers(openApiServerResolver.getServers()) // .info(new Info().title("Herodotus Cloud") // .description("Herodotus Cloud Microservices Architecture") // .version("Swagger V3") // .license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/"))) // .externalDocs(new ExternalDocumentation() // .description("Herodotus Cloud Documentation") // .url(" https://www.herodotus.cn")); // } //}
"use client" import { useLoadImage } from "@/hooks/useLoadImage" import { Song } from "@/types/types" import Image from "next/image" type MediaItemProps = { song: Song, onClick?: (id: string) => void } const MediaItem = ({song, onClick}: MediaItemProps) => { const imageUrl = useLoadImage(song) const handleClick = () => { if(onClick){ return onClick(song.id) } // default turn on player } return ( <div onClick={handleClick} className="flex items-center gap-x-3 cursor-pointer hover:bg-neutral-800/50 w-full p-2 rounded-md"> <div className="relative rounded-md min-h-[48px] min-w-[48px] overflow-hidden"> <Image src={imageUrl || "/images/liked.png"} alt="song" fill className="object-cover" /> </div> <div className="flex flex-col gap-y-1 overflow-hidden"> <p className="text-white truncate "> {song.title} </p> <p className="text-neutral-400 text-sm truncate"> {song.author} </p> </div> </div> ) } export default MediaItem
import { storageService } from "./async-storage.service.js" import { utilService } from "./util.service.js" const TOYS_KEY = 'toyDB' export const oldToyService = { query, remove, save, getEmptyToy, getToyById, getLabels, getDefaultFilter, } _createToys() //* Data Model const labels = [ 'On wheels', 'Box game', 'Art', 'Baby', 'Doll', 'Puzzle', 'Outdoor', 'Battery Powered', 'Thinking', 'Sport' ] const toy = { _id: 't101', name: 'Talking Doll', price: 123, labels: ['Doll', 'Battery Powered', 'Baby'], createdAt: 1631031801011, inStock: true, } function query(filterBy = {}, sortBy = {}) { console.log("🚀 ~ query ~ sortBy:", sortBy) console.log("🚀 ~ query ~ filterBy:", filterBy) return storageService.query(TOYS_KEY) .then(toys => { if (filterBy.txt) { const regex = new RegExp(filterBy.txt, 'i') toys = toys.filter(toy => regex.test(toy.name)) } if (filterBy.inStock !== '') { if (filterBy.inStock === 'true' || filterBy.inStock === true) { toys = toys.filter(toy => toy.inStock === 'true' || toy.inStock === true) } else { toys = toys.filter(toy => toy.inStock === 'false' || toy.inStock === false) } } if (filterBy.label) { toys = toys.filter(toy => toy.labels.includes(filterBy.label)) } if (sortBy.by) { if (sortBy.by === 'name') { toys.sort((toy1, toy2) => sortBy.asc * toy2.name.localeCompare(toy1.name)) } if (sortBy.by === 'price') { toys.sort((toy1, toy2) => sortBy.asc * (toy2.price - toy1.price)) } if (sortBy.by === 'createdAt') { toys.sort((toy1, toy2) => sortBy.asc * (toy2.createdAt - toy1.createdAt)) } } console.log("🚀 ~ query ~ toys:", toys) return toys }) } function remove(toyId) { return storageService.remove(TOYS_KEY, toyId) } function save(toy) { if (toy._id) { toy.name = toy.name toy.price = toy.price toy.inStock = toy.inStock return storageService.put(TOYS_KEY, toy) } else { toy.name = toy.name toy.price = toy.price toy.inStock = toy.inStock toy.labels = toy.labels toy.createdAt = new Date().getTime() toy.inStock = true return storageService.post(TOYS_KEY, toy) } } function getEmptyToy() { return { name: '', price: '', labels: [], createdAt: '', inStock: 'true' } } function getToyById(toyId) { return storageService.get(TOYS_KEY, toyId) } function getLabels() { return labels } function getDefaultFilter() { return { txt: '', inStock: '', label: '' } } //* Demo Data function _createToys() { let toys = utilService.loadFromStorage(TOYS_KEY) if (!toys || !toys.length) { toys = [] toys.push(_createToy('Painting pages', 150, ['Art', 'Baby'])) toys.push(_createToy('Truck', 80, ['Car', 'Battery Powered', 'On Wheels'])) toys.push(_createToy('Talking Doll', 125, ['Doll', 'Battery Powered', 'Baby'])) toys.push(_createToy('Puzzle', 125, ['Puzzle', 'Thinking'])) toys.push(_createToy('Lego', 270, ['Box game', 'Thinking'])) toys.push(_createToy('Ball', 45, ['Outdoor', 'Sport'])) } utilService.saveToStorage(TOYS_KEY, toys) } function _createToy(toyName, toyPrice, toyLabels) { const toy = { _id: utilService.makeId(), name: toyName || '', price: toyPrice || '', labels: toyLabels || ['Doll', 'Battery Powered', 'Baby'], createdAt: new Date().getTime(), inStock: true, } return toy }
using System; using static MuseMapalyzr.ConfigReader; namespace MuseMapalyzr { public class PatternMultiplier { private static MuseMapalyzrConfig Conf = ConfigReader.GetConfig(); private static MuseMapalyzrConfig UnrankedConf = ConfigReader.GetUnrankedConfig(); private static MuseMapalyzrConfig GetRightConfig(bool ranked) { if (ranked) return Conf; return UnrankedConf; } private static double SmoothStep(double x) { return x * x * (3 - 2 * x); } private static double EaseInCubic(double x) { return Math.Pow(x, 4); } private static double EaseInOut(double x) { return 3 * Math.Pow(x, 2) - 2 * Math.Pow(x, 3); } private static double Clamp(double value, double min, double max) { return Math.Max(min, Math.Min(max, value)); } public static double NothingButTheoryMultiplier(double nps, bool ranked) { double lowerBound = GetRightConfig(ranked).NothingButTheoryLowBound; double upperBound = GetRightConfig(ranked).NothingButTheoryUpBound; double lowerClamp = GetRightConfig(ranked).NothingButTheoryLowClamp; double upperClamp = GetRightConfig(ranked).NothingButTheoryUpClamp; double t = (nps - lowerClamp) / (upperClamp - lowerClamp); t = Clamp(t, 0, 1); return lowerBound + (upperBound - lowerBound) * SmoothStep(t); } public static double ZigZagMultiplier(double nps, bool ranked) { double lowerBound = GetRightConfig(ranked).ZigZagLowBound; double upperBound = GetRightConfig(ranked).ZigZagUpBound; double lowerClamp = GetRightConfig(ranked).ZigZagLowClamp; double upperClamp = GetRightConfig(ranked).ZigZagUpClamp; double t = (nps - lowerClamp) / (upperClamp - lowerClamp); t = Clamp(t, 0, 1); return lowerBound + (upperBound - lowerBound) * EaseInCubic(t); } public static double EvenCircleMultiplier(double nps, bool ranked) { double lowerBound = GetRightConfig(ranked).EvenCircleLowBound; double upperBound = GetRightConfig(ranked).EvenCircleUpBound; double t = Clamp(nps / 30, 0, 1); return lowerBound + (upperBound - lowerBound) * EaseInOut(t); } public static double SkewedCircleMultiplier(double nps, bool ranked) { double lowerBound = GetRightConfig(ranked).SkewedCircleLowBound; double upperBound = GetRightConfig(ranked).SkewedCircleUpBound; double t = Clamp(nps / 30, 0, 1); return lowerBound + (upperBound - lowerBound) * EaseInOut(t); } public static double StreamMultiplier(double nps, bool ranked) { double lowerBound = GetRightConfig(ranked).StreamLowBound; double upperBound = GetRightConfig(ranked).StreamUpBound; double lowerClamp = GetRightConfig(ranked).StreamLowClamp; double upperClamp = GetRightConfig(ranked).StreamUpClamp; double t = (nps - lowerClamp) / (upperClamp - lowerClamp); t = Clamp(t, 0, 1); return lowerBound + (upperBound - lowerBound) * SmoothStep(t); } public static double ZigZagLengthMultiplier(double numNotes, double nps, bool ranked) { double lowerBound = GetRightConfig(ranked).ZigZagLengthLowBound; double upperBound = GetRightConfig(ranked).ZigZagLengthUpBound; double lowerClamp = GetRightConfig(ranked).ZigZagLengthLowClamp; double upperClamp = GetRightConfig(ranked).ZigZagLengthUpClamp; double npsThreshold = GetRightConfig(ranked).ZigZagLengthNpsThreshold; if (nps > npsThreshold) { double t = (numNotes - lowerClamp) / (upperClamp - lowerClamp); t = Clamp(t, 0, 1); return lowerBound + (upperBound - lowerBound) * EaseInCubic(t); } return 1; } public static double NothingButTheoryLengthMultiplier(double numNotes, double multiplier, bool ranked) { double lowerBound = 0; double upperBound = 1; double lowerClamp = 6; double upperClamp = 10; double additional = multiplier - 1; double t = (numNotes - lowerClamp) / (upperClamp - lowerClamp); t = Math.Max(Math.Min(t, 1), 0); double lengthMultiplier = lowerBound + (upperBound - lowerBound) * SmoothStep(t); double newAddtional = lengthMultiplier * additional; return 1 + newAddtional; } public static double FourStackMultiplier(double nps, bool ranked) { double lowerBound = GetRightConfig(ranked).FourStackLowBound; double upperBound = GetRightConfig(ranked).FourStackUpBound; double lowerClamp = GetRightConfig(ranked).FourStackLowClamp; double upperClamp = GetRightConfig(ranked).FourStackUpClamp; double t = (nps - lowerClamp) / (upperClamp - lowerClamp); t = Math.Max(Math.Min(t, 1), 0); return lowerBound + (upperBound - lowerBound) * SmoothStep(t); } public static double ThreeStackMultiplier(double nps, bool ranked) { double lowerBound = GetRightConfig(ranked).ThreeStackLowBound; double upperBound = GetRightConfig(ranked).ThreeStackUpBound; double lowerClamp = GetRightConfig(ranked).ThreeStackLowClamp; double upperClamp = GetRightConfig(ranked).ThreeStackUpClamp; double t = (nps - lowerClamp) / (upperClamp - lowerClamp); t = Math.Max(Math.Min(t, 1), 0); return lowerBound + (upperBound - lowerBound) * SmoothStep(t); } public static double TwoStackMultiplier(double nps, bool ranked) { double lowerBound = GetRightConfig(ranked).TwoStackLowBound; double upperBound = GetRightConfig(ranked).TwoStackUpBound; double lowerClamp = GetRightConfig(ranked).TwoStackLowClamp; double upperClamp = GetRightConfig(ranked).TwoStackUpClamp; double t = (nps - lowerClamp) / (upperClamp - lowerClamp); t = Math.Max(Math.Min(t, 1), 0); return lowerBound + (upperBound - lowerBound) * SmoothStep(t); } public static double VaryingStacksMultiplier(double nps, bool ranked) { double lowerBound = GetRightConfig(ranked).VaryingStacksLowBound; double upperBound = GetRightConfig(ranked).VaryingStacksUpBound; double lowerClamp = GetRightConfig(ranked).VaryingStacksLowClamp; double upperClamp = GetRightConfig(ranked).VaryingStacksUpClamp; double t = (nps - lowerClamp) / (upperClamp - lowerClamp); t = Math.Max(Math.Min(t, 1), 0); return lowerBound + (upperBound - lowerBound) * SmoothStep(t); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using DungeonMaster.Enums; using DungeonMaster.Misc; using DungeonMaster.Models.Heroes; using DungeonMaster.Models.Skills; using DungeonMaster.Models.Skills.Statuseffects.Buffs; using DungeonMaster.Models.Skills.Statuseffects.Debuffs; using DungeonMaster.UI; using Godot; using Attribute = DungeonMaster.Enums.Attribute; namespace DungeonMaster.Models; public abstract partial class BaseUnit : Node3D, INotifyPropertyChanged { public delegate void RoundFinishedEventHandler(); public Dictionary<BaseSupportSkill, bool> ActiveSkills = new(); public List<Buff> Buffs = new(); private int charisma = 4; private int constitution = 4; private double currentHitpoints; private double currentMana; public List<Debuff> Debuffs = new(); private int dexterity = 4; private int intuition = 4; private int level = 1; private int logic = 4; private double maximumHitpoints; private int quickness = 4; public List<BaseSkill> Skills = new(); protected Vector4 SpriteOutlineColorInvisible = new(0, 0, 0, 0); private int strength = 4; private int willpower = 4; private int wisdom = 4; protected abstract Vector4 SpriteOutlineColorHover { get; } protected abstract Vector4 SpriteOutlineColorClicked { get; } //Stats [Export] public string Displayname { get; set; } [Export] [Statdisplay] public int Level { get => level; set { if (value == level) return; level = value; OnPropertyChanged(); } } [Export] [Statdisplay] public int Strength { get => strength; set { if (value == strength) return; strength = value; OnPropertyChanged(); } } [Export] [Statdisplay] public int Constitution { get => constitution; set { if (value == constitution) return; constitution = value; OnPropertyChanged(); } } [Export] [Statdisplay] public int Dexterity { get => dexterity; set { if (value == dexterity) return; dexterity = value; OnPropertyChanged(); OnPropertyChanged(nameof(MeleeDefenseBase)); OnPropertyChanged(nameof(RangedDefenseBase)); } } [Export] [Statdisplay] public int Wisdom { get => wisdom; set { if (value == wisdom) return; wisdom = value; OnPropertyChanged(); OnPropertyChanged(nameof(MagicDefenseBase)); } } [Export] [Statdisplay] public int Quickness { get => quickness; set { if (value == quickness) return; quickness = value; OnPropertyChanged(); OnPropertyChanged(nameof(MeleeDefenseBase)); OnPropertyChanged(nameof(RangedDefenseBase)); OnPropertyChanged(nameof(BaseInitiative)); } } [Export] [Statdisplay] public int Intuition { get => intuition; set { if (value == intuition) return; intuition = value; OnPropertyChanged(); OnPropertyChanged(nameof(BaseInitiative)); } } [Export] [Statdisplay] public int Logic { get => logic; set { if (value == logic) return; logic = value; OnPropertyChanged(); OnPropertyChanged(nameof(SocialDefenseBase)); } } [Export] [Statdisplay] public int Willpower { get => willpower; set { if (value == willpower) return; willpower = value; OnPropertyChanged(); OnPropertyChanged(nameof(MagicDefenseBase)); } } [Export] [Statdisplay] public int Charisma { get => charisma; set { if (value == charisma) return; charisma = value; OnPropertyChanged(); OnPropertyChanged(nameof(SocialDefenseBase)); } } [Export] [Statdisplay] public double MaximumHitpoints { get => maximumHitpoints; set { if (value.Equals(maximumHitpoints)) return; maximumHitpoints = value; OnPropertyChanged(); } } [Export] [Statdisplay] public double CurrentHitpoints { get => currentHitpoints; set { currentHitpoints = value; OnPropertyChanged(); } } [Export] [Statdisplay] public double MaximumMana { get; set; } [Export] [Statdisplay] public double CurrentMana { get => currentMana; set { currentMana = value; OnPropertyChanged(); } } [Export] [Statdisplay] public double ManaregenerationRate { get; set; } //Modifier [Export] [Statdisplay] public double InitiativeModifier { get; set; } [Export] [Statdisplay] public double MeleeAttackratingModifier { get; set; } [Export] [Statdisplay] public double RangedAttackratingModifier { get; set; } [Export] [Statdisplay] public double MagicAttackratingModifier { get; set; } [Export] [Statdisplay] public double SocialAttackratingModifier { get; set; } public bool IsStunned { get; set; } public bool IsDead => CurrentHitpoints <= 0; //Defense [Statdisplay] public int ArmorSlashNormal { get; set; } [Statdisplay] public int ArmorSlashGood { get; set; } [Statdisplay] public int ArmorSlashCritical { get; set; } [Statdisplay] public int ArmorPierceNormal { get; set; } [Statdisplay] public int ArmorPierceGood { get; set; } [Statdisplay] public int ArmorPierceCritical { get; set; } [Statdisplay] public int ArmorCrushNormal { get; set; } [Statdisplay] public int ArmorCrushGood { get; set; } [Statdisplay] public int ArmorCrushCritical { get; set; } [Statdisplay] public int ArmorFireNormal { get; set; } [Statdisplay] public int ArmorFireGood { get; set; } [Statdisplay] public int ArmorFireCritical { get; set; } [Statdisplay] public int ArmorIceNormal { get; set; } [Statdisplay] public int ArmorIceGood { get; set; } [Statdisplay] public int ArmorIceCritical { get; set; } [Statdisplay] public int ArmorLightningNormal { get; set; } [Statdisplay] public int ArmorLightningGood { get; set; } [Statdisplay] public int ArmorLightningCritical { get; set; } //Melee [Statdisplay] public double MeleeDefenseBase => 2 * Dexterity + Quickness; [Export] public double MeleeDefense { get; set; } [Export] [Statdisplay] public double MeleeDefensmodifier { get; set; } public double ModifiedMeleeDefense => FetchRollFor(SkillCategory.Melee, () => MeleeDefense * MeleeDefensmodifier); //Ranged [Statdisplay] public double RangedDefenseBase => 2 * Quickness + Dexterity; [Export] public double RangedDefense { get; set; } [Export] [Statdisplay] public double RangedDefensemodifier { get; set; } public double ModifiedRangedDefense => FetchRollFor(SkillCategory.Ranged, () => RangedDefense * RangedDefensemodifier); //Magic [Statdisplay] public double MagicDefenseBase => 2 * Willpower + Wisdom; [Export] public double MagicDefense { get; set; } [Export] [Statdisplay] public double MagicDefensemodifier { get; set; } public double ModifiedMagicDefense => FetchRollFor(SkillCategory.Magic, () => MagicDefense * MagicDefensemodifier); //Social [Statdisplay] public double SocialDefenseBase => 2 * Logic + Charisma; [Export] public double SocialDefense { get; set; } [Export] [Statdisplay] public double SocialDefensemodifier { get; set; } public double ModifiedSocialDefense => FetchRollFor(SkillCategory.Social, () => SocialDefense * SocialDefensemodifier); //Initiative public double BaseInitiative => 2 * Intuition + Quickness; [Export] public double Initiative { get; set; } [Export] public double InitiativeFlatAdded { get; set; } public double ModifiedInitiative => FetchRollFor(SkillCategory.Initiative, () => Initiative * InitiativeModifier) + InitiativeFlatAdded; [Export] [Statdisplay] public int MaximumActionpoints { get; set; } [Export] [Statdisplay] public int CurrentActionpoints { get; set; } [Export] public double FlatDamagebonus { get; set; } public BaseSkill SelectedSkill { get; set; } public int XpToSpendForLevelUp => this.GetXpToSpendForLevelUp(); [Export] public PackedScene FloatingCombatText { get; set; } public event PropertyChangedEventHandler PropertyChanged; public event RoundFinishedEventHandler OnRoundFinished; //public PackedScene FloatingCombatTextScene { get; set; } = (PackedScene)ResourceLoader.Load("res://UI/doubleing_combat_text.tscn"); public void InvokeRoundFinished() => OnRoundFinished?.Invoke(); public virtual void InstatiateFloatingCombatText(int receivedDamage, string sourceName, HitResult hitResult = HitResult.None) { try { var cameraUnposition = GetViewport().GetCamera3D().UnprojectPosition(GlobalPosition); var floatingCombatTextInstance = FloatingCombatText.Instantiate<FloatingCombatText>(); floatingCombatTextInstance.Display = floatingCombatTextInstance.GetNode<Label>("Label"); floatingCombatTextInstance.Display.Text = receivedDamage <= 0 ? "Miss" : receivedDamage.ToString(); floatingCombatTextInstance.Damage = receivedDamage; floatingCombatTextInstance.Position = cameraUnposition + new Vector2(0, -50); floatingCombatTextInstance.Show(); switch (hitResult) { case HitResult.Good: floatingCombatTextInstance.Display.AddThemeColorOverride("font_color", Colors.Orange); floatingCombatTextInstance.Display.Text += "!"; break; case HitResult.Critical: floatingCombatTextInstance.Display.AddThemeColorOverride("font_color", Colors.Red); floatingCombatTextInstance.Display.Text += "!!"; break; } floatingCombatTextInstance.Display.Text += $" ({sourceName})"; AddChild(floatingCombatTextInstance); } catch (Exception e) { Console.WriteLine(e); } } public int Get(Attribute attribute) => attribute switch { Attribute.Strength => Strength, Attribute.Constitution => Constitution, Attribute.Dexterity => Dexterity, Attribute.Quickness => Quickness, Attribute.Intuition => Intuition, Attribute.Logic => Logic, Attribute.Willpower => Willpower, Attribute.Wisdom => Wisdom, Attribute.Charisma => Charisma, Attribute.None => 0, _ => throw new ArgumentOutOfRangeException(nameof(Attribute)) }; private double FetchRollFor(SkillCategory category, Func<double> returnDefaultModifiedDefense) { var matchingDefenseSkills = Skills.Where(s => s is BaseSupportSkill { Subcategory: SkillSubcategory.Defense or SkillSubcategory.Special, AffectedCategories: not null } supportSkill && supportSkill.AffectedCategories.Any(ac => ac == category.ToString())) .ToList(); return !matchingDefenseSkills.Any() ? returnDefaultModifiedDefense() : matchingDefenseSkills.First().GetTacticalRoll(this); } public double GetUnmodifiedNaturalRollFor(SkillCategory category) => category switch { SkillCategory.Melee => MeleeDefenseBase, SkillCategory.Ranged => RangedDefenseBase, SkillCategory.Magic => MagicDefenseBase, SkillCategory.Social => SocialDefenseBase, _ => 0 }; protected void SetInitialHitpointsAndMana() { OnPropertyChanged(nameof(Constitution)); OnPropertyChanged(nameof(Wisdom)); } protected string GibSkillresult(BaseSkill skill, BaseUnit target) => skill switch { BaseWeaponSkill weaponSkill => weaponSkill.Activate(this, target), _ => skill.Activate(this) }; public abstract (int, int) GetApproximateDamage(BaseSkill ability); public abstract string UseAbility(BaseSkill ability, HitResult hitResult, BaseUnit target = null); public abstract void DieProperly(Main mainScene); public virtual void InitiativeBestimmen(double modifier = 1) => Initiative = modifier * BaseInitiative.InfuseRandomness(); public virtual void SetPosition(Vector3 spawnPosition, Vector3 positionToLookAt) { } public virtual void Initialize() => CurrentHitpoints = MaximumHitpoints; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { switch (propertyName) { case nameof(Constitution) or nameof(Strength): double healthMod = 1; if (this is Hero hero1) healthMod += hero1.Class.Health; var oldMaxhealth = MaximumHitpoints; MaximumHitpoints = (3 * Constitution + 2 * Strength) * healthMod; var maxHealthDifference = MaximumHitpoints - oldMaxhealth; CurrentHitpoints += maxHealthDifference; break; case nameof(Wisdom) or nameof(Logic): double manaMod = 1; if (this is Hero hero2) manaMod += hero2.Class.Mana; var oldMaxMana = MaximumMana; MaximumMana = (2 * Wisdom + Logic) * manaMod; var maxManaDifference = MaximumMana - oldMaxMana; CurrentMana += maxManaDifference; break; } PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(propertyName); return true; } }
import "../../Styles/CareBooking.css" import axios from "axios" import { v4 as uuidv4 } from 'uuid'; import React, { useState } from 'react' import { FiCheck } from "react-icons/fi"; import { Box,Text, Toast, useToast } from '@chakra-ui/react' import { BiChevronRight,BiRupee } from "react-icons/bi"; import { BsStopwatch } from "react-icons/bs"; import { MdShop } from "react-icons/md"; import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, Modal, ModalBody, ModalCloseButton, ModalContent, ModalHeader, ModalOverlay, useDisclosure , } from '@chakra-ui/react' import { useParams } from "react-router-dom"; import TestCarousel from "../../components/CarePageComponent/Carousel/TestCarousel"; import Information from "../../components/CarePageComponent/Information/Information"; import { useSelector } from "react-redux"; import Footer from "../../components/Footer"; const CareBooking = () => { const [TestData,SetTestData]=useState({}) const { isOpen, onOpen, onClose } = useDisclosure() const toast = useToast() const { currentUser } = useSelector((store) => store.auth); console.log(currentUser) const [ShowADDbtn,setShowADDbtn]=useState(true) let param=useParams() let {Booking_id}=param React.useEffect(()=>{ axios.get(`https://wake-healthy.vercel.app/Lab_Test_Card/${Booking_id}`) .then((data)=>{ SetTestData(data.data) }) },[]) const HandleADD_Btn =(item)=>{ setShowADDbtn(false) toast({ render: () => ( <Box color='white' p={3} bg='blue.500'> <p>{item.title} - {item.Test}</p> <p>For {currentUser} | Male</p> </Box> ), position: 'top-right', isClosable: true, status: "success", duration: 2000, }) axios.post(" https://wakehealhty-update.onrender.com/CareCart",{...item,"id":uuidv4()}) } return ( <Box className='Booking_main_div'> <Box className="Book_div"> <Box className="image_div"> <img src={TestData.image} alt="" /> </Box> <Box className="Book_now_div"> <Breadcrumb ml="30px" spacing='4px' fontSize="13px" separator={<BiChevronRight color='gray.500' />}> <BreadcrumbItem> <BreadcrumbLink color="#00000080" href='#'>Home</BreadcrumbLink> </BreadcrumbItem> <BreadcrumbItem> <BreadcrumbLink color="#00000080" href='/care'>Care </BreadcrumbLink> </BreadcrumbItem> <BreadcrumbItem > <BreadcrumbLink color="#00000080" href='#'>Diagnostic Test</BreadcrumbLink> </BreadcrumbItem> <BreadcrumbItem isCurrentPage> <BreadcrumbLink color="#000000" href='#'>{TestData.title}</BreadcrumbLink> </BreadcrumbItem> </Breadcrumb> <Box className="Booking_card"> <Box className="card_top_div"> <Text fontSize={{ base: '14px', md: '17px', lg: '20px' }} >{TestData.title}</Text> <Box display="flex" flexDirection="row" > <Text display="flex" justifyContent="center" alignItems="center" color="#888E9E"><BiRupee/><del>{TestData.Price}</del> </Text> <Text display="flex" justifyContent="center" alignItems="center"><BiRupee/>{TestData.Offer_price} </Text> </Box> </Box> <Box p="0 12px"> <Text fontSize={{ base: '10px', md: '11px', lg: '13px' }} color="#888E9E" textAlign="left">{TestData.desp}</Text> </Box> <Box className="card_bottom_div" > <Box > <Text fontSize="13px" display="flex" flexDirection="row" alignItems="center" color="#888E9E" > <BsStopwatch/>{TestData.Test} </Text> <Text fontSize="13px" display="flex" flexDirection="row" alignItems="center" color="#888E9E" ><MdShop/> {TestData.time}</Text> </Box> { ShowADDbtn? <button className="butnow_btn" onClick={()=>HandleADD_Btn(TestData)} ><b>ADD</b> </button>: <Box display="flex" flexDirection="row" alignItems="center"> <FiCheck color="green.200"/> <Text color="green.300">Added</Text> </Box> } </Box> </Box> </Box> </Box> <Box className="TestCarousel_div"> <Box className="Test_Include_box"> <TestCarousel/> </Box> <Box className="Healthians_box"> <Box w="100%" p="10px" display="flex" flexDirection="row"> <Box w="40%" display="flex" justifyContent="space-around" gap="10px" fontSize={{ base: '10px', md: '12px', lg: '15px' }} color="#5A5A5A"> <Text>Fulfilled By</Text> <img src="https://cdn-media.cure.fit/image/carefit/healthians_logo.png" alt="image_abc" width="60px" /> </Box> <Box w="60%" textAlign="right" color="#FF3238" fontSize="13px"> <Text onClick={onOpen}>Know More</Text> <Modal onClose={onClose} size={"xl"} isOpen={isOpen} p="20px"> <ModalOverlay /> <ModalContent> <ModalHeader> <img src="https://cdn-media.cure.fit/image/carefit/healthians_logo.png" alt="pic" width="100px" /> </ModalHeader> <ModalCloseButton /> <ModalBody> <Box> <Text>About</Text> <Text color="#5A5A5A" fontSize="12px">Healthians is India’s largest provider of health test at-home service, creating a new benchmark in quality. 600+ trained technicians. 46 touch-point technology for assured quality collection & testing. DMLT & WHO certified phlebotomist </Text> </Box> <Box display="flex" flexDirection="row" mt="13px" alignItems="center"> <img src="https://cdn-media.cure.fit/image/carefit/diagnostics/bloodsample.png" alt="picc" width="40px"/> <Text fontSize="12px" color="#5A5A5A">Sample collected by and processed by Healthians and its partner labs</Text> </Box> <Box display="flex" flexDirection="row" mt="13px" alignItems="center"> <img src="https://cdn-media.cure.fit/image/carefit/digital.png" alt="picc" width="40px"/> <Text fontSize="12px" color="#5A5A5A">Schedule, track and view your reports on the care.fit app</Text> </Box> </ModalBody> </ModalContent> </Modal> </Box> </Box> <Box mt="20px" textAlign="left" ml="40px" color="#5A5A5A" fontSize={{ base: '10px', md: '12px', lg: '15px' }} > <ul> <li>DMLT and WHO certified phlebotomists</li> <li>46 touch-point technology for assured quality collection & testing</li> </ul> </Box> </Box> </Box> <Information /> <Footer /> </Box> ) } export default CareBooking
<!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap Link --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Amatic+SC&family=Cairo&family=Chakra+Petch&family=Dancing+Script&family=Edu+SA+Beginner&family=Indie+Flower&family=Press+Start+2P&display=swap" rel="stylesheet"> <!-- External CSS --> <link rel="stylesheet" href="./index.css"> <title>Portfolio</title> </head> <body> <!-- NAV BAR --> <div class="bg-dark sticky-top top-0"> <nav class="navbar navbar-expand-lg navbar-dark bg-danger bg-gradient --bs-bg-opacity"> <div class="container-fluid"> <a class="navbar-brand" href="#landing"> <img src="https://i.postimg.cc/pV0w6ZWZ/download20210800042409.png" class="img-fluid"> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ms-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link" aria-current="page" href="#aboutme">About Me</a> </li> <li class="nav-item"> <a class="nav-link" href="#projects">Projects</a> </li> <li class="nav-item"> <a class="nav-link" href="#contact">Contact Me</a> </li> </ul> </div> </div> </nav> </div> <!-- END OF NAV BAR --> <!-- MAIN CONTENT SECTION --> <!-- LANDING PAGE --> <div class="container-fluid p-0 mt-0" id="landing"> <div class="content"> <div class="left-side"> <div class="main-container"> <h1>Elaine</h1> <h4>Full-Stack Developer in Training</h4> <p></p> <a href="#aboutme" class="btn">About Me</a> </div> </div> <div class="right-side bg-dark d-none d-lg-block"></div> </div> <!-- END OF LANDING PAGE --> <!-- ABOUT ME PAGE --> <div class="container-fluid" id="aboutme"> <div class="about-me d-inline-block justify-content-center row" id="profile"> <div class="card card-me col"> <div class="card-header"> Degree </div> <div class="card-body"> <blockquote class="blockquote mb-0"> <p class="pt-3">BS Electrical Engineering</p> <footer class="blockquote-footer">Studied 2011-2017</footer> </blockquote> </div> </div> <div class="card card-me col"> <div class="card-header"> Work Experience </div> <div class="card-body"> <blockquote class="blockquote mb-0"> <p class="pt-3">Software Engineer</p> <footer class="blockquote-footer">Worked 2018-2020</footer> </blockquote> </div> </div> <div class="name-2 d-flex justify-content-center align-items-center"> <h2 class="col-12 col-md-8 mt-5 pt-5">Elaine Diaz</h2> <div class="col-3 d-none d-lg-block"><img src="https://i.postimg.cc/j52WQcq1/download20210800042409.png" class="img-fluid mb-5"></div> </div> </div> </div> <!-- END OF ABOUT ME PAGE --> <!-- FUTURE PROJECTS --> <div class="projects p-2" id="projects"> <h1 class="mb-5">Future Projects</h1> <div class="d-block d-md-flex flex-column justify-content-between"> <!-- GAME PROFILE --> <div class="card"> <div class="row-card"> <div class="col-md-7"> <h2 class="card-title mt-2 offset-1 bg-dark ms-3">Game Profile</h2> <p class="p-3 m-3">The ultimate archive of Games played in different platforms with Streams, Screenshots and More. Schedules of playtimes can also serve as a good data source to formulate charts to see trends of most-played, titles played with friends and achievements. This can showcase different tools, mods and wikis for favourite games. An online record for game reviews and guides will also be available.</p> </div> <div class="col-md-5 d-none d-md-block"> <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="https://i.postimg.cc/MpMCrhv0/game-pixel-gif.gif" class="d-block w-100" alt="cute-pixel"> </div> <div class="carousel-item"> <img src="https://i.postimg.cc/hP6rMPws/apo-high-w-fix.gif" class="d-block w-100" alt="neon-pixel"> </div> <div class="carousel-item"> <img src="https://i.postimg.cc/tgR6yKnw/28a1e36191eb43fae5347624b17edf10.gif" class="d-block w-100" alt="nihon-pixel"> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> </div> </div> <!-- END OF GAME PROFILE --> <!-- RECIPE CORNER --> <div class="card"> <div class="row-card"> <div class="col-md-5 d-none d-md-block bg-dark text-align-center rounded"> <div class="row-food-1 bg-light p-2 d-flex w-100"> <div class="col-3 col-md-6 me-3"><img src="https://i.postimg.cc/9MSsP08y/image-4.jpg" class="img-fluid" alt="fd1"></div> <div class="col-3 col-md-6"><img src="https://i.postimg.cc/pLx4JgZc/image-2.jpg" class="img-fluid" alt="fd2"></div> </div> <div class="row-food-2 bg-light p-2 d-flex w-100"> <div class="col-3 col-md-6 me-3"><img src="https://i.postimg.cc/bYD7y0rg/image-1.jpg" class="img-fluid" alt="fd3"></div> <div class="col-3 col-md-6"><img src="https://i.postimg.cc/7Zs9JcQ2/image-3.jpg" class="img-fluid" alt="fd4"></div> </div> </div> <div class="col-md-7"> <h2 class="card-title mt-2 bg-dark ms-2">Recipe Corner</h2> <p class="p-3 m-3">A collection of tasty and healthy treats for everyone that is mostly centered on plant-based ingredients. A journey on discovering vegan alternatives in a meat-centered country gave me a chance to appreciate underrated meals. Very simple to prepare but certainly fulfilling.</p> </div> </div> </div> <!-- END OF RECIPE CORNER --> <!-- ART GALLERY --> <div class="card card-art container-fluid d-flex align-items-center justify-content-center" id="card-art"> <div class="row-card"> <div class="col-md-7"> <h2 class="card-title mt-2 bg-dark ms-2">Art Gallery</h2> <p id="p-art" class="p-3 m-3">A Webpage to showcase artwork pieces. Not only for personal art but also for saving references and studies. Traditional arts, digital, literary works and journals can alse be archived here. It would technically be a personal blog of sorts. </p> </div> <div class="d-none d-md-block col-md-4"> <div class="card"> <img src="https://i.postimg.cc/TYRFHx9D/image-5.jpg" class="img-fluid" alt="crow"> <div class="card-body"> <p class="card-text-1">Pen & Ink.</p> </div> </div> </div> <div class="d-none d-md-block col-md-4"> <div class="card"> <img src="https://i.postimg.cc/T1xFxvvB/image-7.jpg" class="img-fluid" alt="drgn"> <div class="card-body"> <p class="card-text-2">Colored Pencil.</p> </div> </div> </div> </div> </div> <!-- END OF ART GALLERY --> </div> </div> <!-- END OF FUTURE PROJECTS --> <!-- CONTACT ME HERE --> <div class="bg-dark text-light container-fluid pb-5" id="contact"> <h2 class="p-3">Contact Me Here..</h2> <div class="d-flex justify-content-center align-items-center"> <div class="p-3 bg-secondary col-md-8"> <form target="_blank" action="http://google.com"> <!-- name --> <div class="mb-3"> <label for="formGroupExampleInput" class="form-label">Name</label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Your Name"> </div> <!-- email --> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">E-mail address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="name@example.com"> </div> <!-- contact number --> <div class="mb-3"> <label for="formGroupExampleInput" class="form-label">Contact Number</label> <input type="number" class="form-control" id="formGroupExampleInput" placeholder="+63 900 000 000"> </div> <!-- text area --> <div class="mb-3"> <label for="exampleFormControlTextarea1" class="form-label">Leave a Message Here</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="7"></textarea> </div> <!-- button --> <button type="submit" class="btn btn-dark p-1">Send Email</button> </form> </div> </div> </div> <!-- END OF CONTACT ME HERE --> </div> <!-- END OF MAIN CONTENT SECTION --> <!-- FOOTER --> <footer> <span>Terms of Service</span> <span>|</span> <span>Privacy Policy</span> <span>|</span> <span>All Rights Reserved</span> </footer> <!-- FOOTER --> <!-- JS Bundle Script --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </body> </html>
import { Skeleton } from "@/components/ui/skeleton"; const Loading = () => { return ( <div className="flex flex-row-reverse gap-[48px] px-6 mb-10"> {/* Skeleton for StickyWrapper content */} <div className="w-80 flex flex-col space-y-6 mb-10"> {/* Placeholder for UserProgress */} <Skeleton className="h-24 w-full rounded-lg mb-10" /> {/* Conditional Placeholder for Promo */} <Skeleton className="h-12 w-full rounded-lg" /> {/* Placeholder for Quests */} <Skeleton className="h-36 w-full rounded-lg" /> </div> {/* Skeleton for FeedWrapper content */} <div className="flex-1 space-y-5"> <div className="flex flex-col items-center"> {/* Placeholder for Image */} <Skeleton className="h-24 w-24 rounded-full" /> {/* Placeholder for Shop Title */} <Skeleton className="h-6 w-3/4 rounded" /> {/* Placeholder for Description */} <Skeleton className="h-4 w-5/6 rounded" /> {/* Placeholder for Items */} <div className="w-full flex flex-col items-center justify-center mt-6 space-y-2"> <div className="w-full mt-6 flex flex-col items-center justify-center"> {Array.from({ length: 5 }).map((_, index) => ( <div key={index} className="flex justify-center mb-4 last:mb-0" style={{ transform: `translateX(${index % 2 === 0 ? 10 * index : -10 * index}px)`, }} > <Skeleton className="h-16 w-16 rounded-full" /> </div> ))} </div> </div> </div> </div> </div> ); }; export default Loading;
package javav.mvc.controller; import javav.mvc.model.ConnectClass; import javav.mvc.model.GestiuneBDModel; import javav.mvc.view.GestiuneBDView; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class GestiuneBDController { private GestiuneBDModel model; private GestiuneBDView view; public GestiuneBDController(GestiuneBDModel model, GestiuneBDView view) { this.model = model; this.view = view; refreshTable(); view.getAddButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String valuta = view.getValutaField().getText(); double curs = Double.parseDouble(view.getCursField().getText()); String dataActualizare = view.getDataField().getText(); addRecord(valuta, curs, dataActualizare); } }); view.getUpdateButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selectedRow = view.getTable().getSelectedRow(); if (selectedRow != -1) { int id = (int) view.getTable().getValueAt(selectedRow, 0); String valuta = view.getValutaField().getText(); double curs = Double.parseDouble(view.getCursField().getText()); String dataActualizare = view.getDataField().getText(); updateRecord(id, valuta, curs, dataActualizare); } } }); view.getDeleteButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selectedRow = view.getTable().getSelectedRow(); if (selectedRow != -1) { int id = (int) view.getTable().getValueAt(selectedRow, 0); deleteRecord(id); } } }); } private void refreshTable() { model.setRowCount(0); Connection connection = ConnectClass.getConnection(); try { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM CursValutar"); while (resultSet.next()) { int id = resultSet.getInt("ID"); String valuta = resultSet.getString("Valuta"); double curs = resultSet.getDouble("Curs"); String dataActualizare = resultSet.getString("DataActualizare"); model.addRow(new Object[]{id, valuta, curs, dataActualizare}); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } private void addRecord(String valuta, double curs, String dataActualizare) { Connection connection = ConnectClass.getConnection(); try { Statement statement = connection.createStatement(); String query = String.format("INSERT INTO CursValutar (Valuta, Curs, DataActualizare) VALUES ('%s', %.2f, '%s')", valuta, curs, dataActualizare); statement.executeUpdate(query); statement.close(); connection.close(); refreshTable(); } catch (SQLException e) { e.printStackTrace(); } } private void updateRecord(int id, String valuta, double curs, String dataActualizare) { Connection connection = ConnectClass.getConnection(); try { Statement statement = connection.createStatement(); String query = String.format("UPDATE CursValutar SET Valuta = '%s', Curs = %.2f, DataActualizare = '%s' WHERE ID = %d", valuta, curs, dataActualizare, id); statement.executeUpdate(query); statement.close(); connection.close(); refreshTable(); } catch (SQLException e) { e.printStackTrace(); } } private void deleteRecord(int id) { Connection connection = ConnectClass.getConnection(); try { Statement statement = connection.createStatement(); String query = String.format("DELETE FROM CursValutar WHERE ID = %d", id); statement.executeUpdate(query); statement.close(); connection.close(); refreshTable(); } catch (SQLException e) { e.printStackTrace(); } } }
/* See LICENSE for licensing and NOTICE for copyright. */ package org.passay; import org.testng.annotations.DataProvider; /** * Unit test for {@link LengthRule}. * * @author Middleware Services */ public class LengthRuleTest extends AbstractRuleTest { /** * @return Test data. * * @throws Exception On test data generation failure. */ @DataProvider(name = "passwords") public Object[][] passwords() throws Exception { return new Object[][] { {new LengthRule(8, 10), new PasswordData("p4T3#6Tu"), null, }, {new LengthRule(8, 10), new PasswordData("p4T3t#6Tu"), null, }, {new LengthRule(8, 10), new PasswordData("p4T3to#6Tu"), null, }, { new LengthRule(8, 10), new PasswordData("p4T36"), codes(LengthRule.ERROR_CODE_MIN), }, { new LengthRule(8, 10), new PasswordData("p4T3j76rE@#"), codes(LengthRule.ERROR_CODE_MAX), }, {new LengthRule(8), new PasswordData("p4T3#6Tu"), null, }, { new LengthRule(8), new PasswordData("p4T3t#6Tu"), codes(LengthRule.ERROR_CODE_MAX), }, { new LengthRule(8), new PasswordData("p4T3to#6Tu"), codes(LengthRule.ERROR_CODE_MAX), }, { new LengthRule(8), new PasswordData("p4T36"), codes(LengthRule.ERROR_CODE_MIN), }, { new LengthRule(8), new PasswordData("p4T3j76rE@#"), codes(LengthRule.ERROR_CODE_MAX), }, {new LengthRule(0, 10), new PasswordData("p4T3#6Tu"), null, }, {new LengthRule(0, 10), new PasswordData("p4T3t#6Tu"), null, }, {new LengthRule(0, 10), new PasswordData("p4T3to#6Tu"), null, }, {new LengthRule(0, 10), new PasswordData("p4T36"), null, }, { new LengthRule(0, 10), new PasswordData("p4T3j76rE@#"), codes(LengthRule.ERROR_CODE_MAX), }, {new LengthRule(8, Integer.MAX_VALUE), new PasswordData("p4T3#6Tu"), null, }, {new LengthRule(8, Integer.MAX_VALUE), new PasswordData("p4T3t#6Tu"), null, }, {new LengthRule(8, Integer.MAX_VALUE), new PasswordData("p4T3to#6Tu"), null, }, { new LengthRule(8, Integer.MAX_VALUE), new PasswordData("p4T36"), codes(LengthRule.ERROR_CODE_MIN), }, {new LengthRule(8, Integer.MAX_VALUE), new PasswordData("p4T3j76rE@#"), null, }, }; } /** * @return Test data. * * @throws Exception On test data generation failure. */ @DataProvider(name = "messages") public Object[][] messages() throws Exception { return new Object[][] { { new LengthRule(8, 10), new PasswordData("p4T3j76rE@#"), new String[] { String.format("Password must be no more than %s characters in length.", 10), }, }, { new LengthRule(8, 10), new PasswordData("p4T36"), new String[] {String.format("Password must be %s or more characters in length.", 8), }, }, }; } }
''' Representa um multilayer perceptron (MLP) Contém as seguintes camadas: - Camada de entrada (__input_layer) - Camada oculta (__hidden_layer) - Camada de saída (__output_layer) Implementa um algoritmo de treinamento que realiza a parada antecipada quando a diferença entre a taxa de erro da iteração atual com a anterior é menor que um determinado valor (definido nos parâmetros da rede). ''' from entities.hidden_layer import HiddenLayer from entities.output_layer import OutputLayer from data.data_mlp import DataMlp from entities.parameters import Parameters from .input_layer import InputLayer import math class NeuralNetwork: __id = 0 def __init__(self, params: Parameters, data_mlp: list[DataMlp]=None, weight_list: list=None): self.__params = params self.__input_layer = InputLayer(data_mlp) self.__hidden_layer = HiddenLayer(params.total_hidden_perceptrons, params.input_vector_dimension) self.__output_layer = OutputLayer(params.total_output_percetrons, params.total_hidden_perceptrons) self.__error_info = [] self.__final_era = None self.__final_error = 0 self.__carry_weights(weight_list) NeuralNetwork.__id += 1 self.__id = NeuralNetwork.__id @property def hidden_layer(self) -> HiddenLayer: return self.__hidden_layer @property def output_layer(self) -> OutputLayer: return self.__output_layer @property def error_info(self) -> list[(int, float)]: return self.__error_info # Processa um vetor de dados pelas camadas da MLP def __feedforward(self, vector: list[int]) -> list[float]: hidden_layer_output = self.__hidden_layer.output(vector) output = self.__output_layer.output(hidden_layer_output) return output # Realiza uma iteração completa dos dados e acumula o erro do aprendizado por era def __iterate_data(self) -> float: accumulated_error = 0 for data in self.__input_layer.data: hidden_layer_output = self.__hidden_layer.output(data.vector) outputs = self.__output_layer.output(hidden_layer_output) accumulated_error += self.__mean_squared_error(outputs, data.target) output_error_rate = self.__output_layer.update_weights(self.__params.learning_rate, data.target, hidden_layer_output, outputs) self.__hidden_layer.update_weights(self.__params.learning_rate, output_error_rate, data.vector) return accumulated_error # Calcula o erro médio quadrático da rede def __mean_squared_error(self, outputs: list[float], targets: list[int]) -> float: error = 0 for output, target in zip(outputs, targets): error += math.pow((target - output), 2) error /= 2 return error # Realiza o treinamento da MLP def train_neural_network(self) -> None: current_error = 0 print("Start learn") for era in range(self.__params.total_eras): previous_error = current_error current_error = self.__iterate_data() self.__error_info.append((era, current_error)) print(f"- Error[{era}] = {current_error}") if abs(current_error - previous_error) < self.__params.error_rate: break self.__final_era = era self.__final_error = current_error print("finished") # Gera a saída da rede para uma data entrada def output(self, vector: list[int]) -> list[float]: return self.__feedforward(vector) def __carry_weights(self, weight_list: list) -> None: if weight_list: self.__hidden_layer.carry_weights(weight_list[0]) self.__output_layer.carry_weights(weight_list[1]) def __repr__(self) -> str: return f'''MLP= [ - Id={self.__id}, - {self.__params}, - {self.__input_layer}, - {self.__hidden_layer}, - {self.__output_layer} - Final_era= {self.__final_era} - Final_error = {self.__final_error} ]'''
<template> <div class="relative lg:block lg:space-y-10 p-2 md:grid md:grid-cols-12 lg:h-full" > <div v-if="!menuIsActive"> <button v-if="!menuIsActive && !toggleFilterForm" class="btn btn-success gap-2 text-white" @click="toggleFilterForm = !toggleFilterForm" > <!-- <span v-if="!toggleFilterForm"> --> <mdicon name="play-circle-outline" /> Get Started <!-- </span> --> </button> <button v-else class="btn btn-ghost absolute right-4 z-50 text-red-600" @click="toggleFilterForm = !toggleFilterForm" > <!-- <span v-if="!toggleFilterForm"> --> <mdicon name="close" size="22" /> <!-- </span> --> </button> </div> <FilterForm v-if="menuIsActive || toggleFilterForm" /> </div> </template> <script setup> import { ref } from "vue"; import FilterForm from "./FilterForm.vue"; const toggleFilterForm = ref(false); const MOBILE_BREAKPOINT = 1024; const width = ref(document.body.offsetWidth); const menuIsActive = ref(width.value > MOBILE_BREAKPOINT); // const toggleMenu = () => (menuIsActive.value = !menuIsActive.value); window.addEventListener("resize", function () { width.value = document.body.offsetWidth; // console.log(width.value); menuIsActive.value = width.value > MOBILE_BREAKPOINT; }); </script>
#include <Eigen/Dense> #include <iostream> #include <functional> // for std::function #include <Eigen/SparseCore> #include <Eigen/SparseLU> // New version 1.1: using sparse matrices, dropping general nonlinear solver, using error instead of residual //! \brief Implements a single step of the fixed point iteration $x^{(k+1)} = A(x^{(k)})^{-1} * b$ //! \tparam func type of the lambda function implementing A(x) //! \tparam Vector type for the vector b, x, x_new $\in \mathbf{R}^2$ //! \param[in] A lambda function implementing A(x) //! \param[in] b rhs vector $b \in \mathbf{R}^n$ //! \param[in] x previous step $x^{(k)}$ //! \param[out] x_new next step $x^{(k+1)}$ template <class func, class Vector> void fixed_point_step(const func& A, const Vector & b, const Vector & x, Vector & x_new) { // Next step auto T = A(x); Eigen::SparseLU<Eigen::SparseMatrix<double>> Ax_lu; Ax_lu.analyzePattern(T); Ax_lu.factorize(T); x_new = Ax_lu.solve(b); } //! \brief Implements a single step of the Netwon iteration for $x^{(k+1)}$ //! Exploits Sherman-Morrison-Woodbury formula for fast inversion of rank-one modification of a matrix. //! \tparam func type of the lambda function implementing A(x) //! \tparam Vector type for the vector b, x, x_new $\in \mathbf{R}^2$ //! \param[in] A lambda function implementing A(x) //! \param[in] b rhs vector $b \in \mathbf{R}^n$ //! \param[in] x previous step $x^{(k)}$ //! \param[out] x_new next step in Newton iteration $x^{(k+1)}$ template <class func, class Vector> void newton_step(const func& A, const Vector & b, const Vector & x, Vector & x_new) { // Reuse LU decomposition with SMW auto T = A(x); Eigen::SparseLU<Eigen::SparseMatrix<double>> Ax_lu; Ax_lu.analyzePattern(T); Ax_lu.factorize(T); // Solve a bunch of systems auto Axinv_b = Ax_lu.solve(b); auto Axinv_x = Ax_lu.solve(x); // Next step x_new = Axinv_b + Ax_lu.solve(x*x.transpose()*(x-Axinv_b)) / (x.norm() + x.dot(Axinv_x) ); } template <class func, class Vector> void fixed_point_method(const func& A, const Vector& b, const double atol, const double rtol, const int max_itr) { auto fix_step = [&A, &b] (const Eigen::VectorXd & x, Eigen::VectorXd & x_new) { fixed_point_step(A, b, x, x_new); }; auto x = b; auto x_new = x; for( int itr = 0; itr<max_itr; itr++) { // till max itr fix_step(x, x_new); // Advance to next step double r = (x - x_new).norm();// Compute residual std::cout << "[Step " << itr << "] Error: " << r << std::endl; // atol, termination if (r < atol) { std::cout << "[CONVERGED] in " << itr << " it. due to atol. err = " << r << " < " << atol << "." << std::endl; break; } // rtol, termination if (r < rtol*x_new.norm()) { std::cout << "[CONVERGED] in " << itr << " it. due to rtol. err = " << r << " < " << rtol*x_new.norm() << "." << std::endl; break; } x = x_new; } std::cout << std::endl << "x^*_fix = " << std::endl << x_new << std::endl; } template <class func, class Vector> void newton_method(const func& A, const Vector& b, const double atol, const double rtol, const int max_itr) { auto newt_step = [&A, &b] (const Eigen::VectorXd & x, Eigen::VectorXd & x_new) { newton_step(A, b, x, x_new); }; auto x = b; auto x_new = x; for( int itr = 0; itr < max_itr; itr++) { // till max itr newt_step(x, x_new);// Advance to next step double r = (x - x_new).norm();// Compute residual std::cout << "[Step " << itr << "] Error: " << r << std::endl; // atol, termination if (r < atol) { std::cout << "[CONVERGED] in " << itr << " it. due to atol. err = " << r << " < " << atol << "." << std::endl; break; } // rtol, termination if (r < rtol*x_new.norm()) { std::cout << "[CONVERGED] in " << itr << " it. due to rtol. err = " << r << " < " << rtol*x_new.norm() << "." << std::endl; break; } x = x_new; } std::cout << std::endl << "x^*_newt = " << std::endl << x_new << std::endl; } int main(void) { double atol = 1e-13; double rtol = 1e-11; int max_itr = 100; // Define a test vector and test rhs and x0 = b int n = 8; Eigen::SparseMatrix<double> T(n,n); T.reserve(3); for(int i = 0; i < n; ++i) { if(i > 0) T.insert(i,i-1) = 1; T.insert(i,i) = 0; if(i < n-1) T.insert(i,i+1) = 1; } Eigen::VectorXd b = Eigen::VectorXd::Random(n); // Define a lambda function implementing A(x) auto A = [&T, n] (const Eigen::VectorXd & x) -> Eigen::SparseMatrix<double> & { double nrm = x.norm(); for(int i = 0; i < n; ++i) { T.coeffRef(i,i) = 3 + nrm; } return T; }; fixed_point_method(A, b, atol, rtol, max_itr); newton_method(A, b, atol, rtol, max_itr); }
import { render, screen, fireEvent } from "@testing-library/react"; import Header from "./Header"; describe("Header Component", () => { test("renders the header with navigation links", () => { render(<Header />); const homeLink = screen.getByText("Home"); const menuLink = screen.getByText("Menu"); const cartLink = screen.getByText("Cart"); const logoImage = screen.getByAltText("logo"); expect(homeLink).toBeInTheDocument(); expect(menuLink).toBeInTheDocument(); expect(cartLink).toBeInTheDocument(); expect(logoImage).toBeInTheDocument(); }); test('initially sets active tab to "main"', () => { render(<Header />); const homeLink = screen.getByText("Home"); expect(homeLink).toHaveClass("text-black"); }); test("removes scroll event listener on unmount", () => { const addEventListenerSpy = jest.spyOn(window, "addEventListener"); const removeEventListenerSpy = jest.spyOn(window, "removeEventListener"); const { unmount } = render(<Header />); expect(addEventListenerSpy).toHaveBeenCalledWith( "scroll", expect.any(Function) ); unmount(); expect(removeEventListenerSpy).toHaveBeenCalledWith( "scroll", expect.any(Function) ); }); });
--- title: Etkinlik görünümleri (eski) | Microsoft Docs ms.date: 11/15/2016 ms.prod: visual-studio-dev14 ms.technology: vs-workflow-designer ms.topic: reference helpviewer_keywords: - activities, activity views - views, activity - activity views ms.assetid: 83dc68cd-2cb2-45c2-9a6e-10d82053171a caps.latest.revision: 5 author: jillre ms.author: jillfra manager: jillfra ms.openlocfilehash: 9b65a46d5d0061eeaf3ad707affea1423e5fca5d ms.sourcegitcommit: bad28e99214cf62cfbd1222e8cb5ded1997d7ff0 ms.translationtype: MT ms.contentlocale: tr-TR ms.lasthandoff: 11/21/2019 ms.locfileid: "74297539" --- # <a name="activity-views-legacy"></a>Etkinlik Görünümleri (Eski) [!INCLUDE[wf](../includes/wf-md.md)]tarafından sağlanan etkinliklerin birçoğu, iş akışlarının oluştuğu, eski [!INCLUDE[wfd1](../includes/wfd1-md.md)]birçok tasarım görünümüne sahip olabilir. **Araç kutusundan** bir etkinlik Tasarımcısını Tasarım yüzeyine sürüklediğinizde ve bundan sonra etkinliği her seçtiğinizde, **iş akışı** menüsünü kullanarak veya seçili etkinliğe sağ tıklayarak farklı tasarım görünümleri arasında geçiş yapabilirsiniz. Ayrıca, işaretçiyi seçili bir etkinliğin adının üzerine getirdiğinizde, farklı görünümler arasında geçiş yapmak için kullanabileceğiniz bir aşağı açılan sekme kümesi görüntülenir. Her etkinliğin en az bir görünümü vardır; Bu, **araç kutusundan** bir etkinlik Tasarımcısını Tasarım yüzeyine sürüklediğinizde gösterilen varsayılan görünümüdür. Bu etkinlik varsayılan görünümü menülerde ve sekmede **Görünüm [etkinlik türü]** seçeneği olarak kullanılabilir (örneğin, **paralel görünüm**). Etkinliklerin çoğunda ek görünümler ve farklı etkinlikler farklı görünümlere sahip olabilir. Örneğin, [TransactionScopeActivity](https://go.microsoft.com/fwlink?LinkID=65093) etkinliği Dengeleme görünümüne sahiptir ve [EventHandlingScopeActivity](https://go.microsoft.com/fwlink?LinkID=65030) etkinliği bir olay görünümü içerir. Windows Workflow Foundation ile birlikte gelen etkinliklerin birçoğu, [CancellationHandlerActivity](https://go.microsoft.com/fwlink?LinkID=65050) ve bunlarla Ilişkili bir [FaultHandlersActivity](https://go.microsoft.com/fwlink?LinkID=65055) görüntülemek Için, aynı görüntüleme **iptali işleyicisine** sahiptir ve hata tasarım görünümlerini **görüntüler** . Aşağıdaki tabloda her bir görünümün adı ve açıklaması listelenmektedir. |Menü/sekme seçeneği|Açıklama| |----------------------|-----------------| |**Görünüm [etkinlik türü]**|Seçilen etkinliğin varsayılan grafik temsilini görüntülemek için bu menüyü veya sekme seçeneğini belirleyin.| |**Iptal Işleyicisini görüntüle**|Seçili etkinlikle ilişkili [CancellationHandlerActivity](https://go.microsoft.com/fwlink?LinkID=65050) görüntülemek için bu menüyü veya sekme seçenek görünümünü seçin.| |**Hata Işleyicisini görüntüle**|Seçili etkinlikle ilişkili [FaultHandlersActivity](https://go.microsoft.com/fwlink?LinkID=65055) görüntülemek için bu menüyü veya sekme seçenek görünümünü seçin.| |**Dengeleme Işleyicisini görüntüle**|Seçili [TransactionScopeActivity](https://go.microsoft.com/fwlink?LinkID=65093)Ile Ilişkili [CompensationHandlerActivity](https://go.microsoft.com/fwlink?LinkID=65053) 'yi görüntülemek için bu menüyü veya sekme seçenek görünümünü seçin.| |**Olay Işleyicisini görüntüle**|Seçili [EventHandlingScopeActivity](https://go.microsoft.com/fwlink?LinkID=65030)Ile ilişkili [EventHandlersActivity](https://go.microsoft.com/fwlink?LinkID=65018) görüntülemek için bu menüyü veya sekme seçenek görünümünü seçin.| Benzer görünümler hakkında daha fazla bilgi için bkz. [sıralı Iş akışı görünümleri (eski)](../workflow-designer/sequential-workflow-views-legacy.md). ## <a name="see-also"></a>Ayrıca Bkz. [Eski Iş akışı etkinlikleri](../workflow-designer/legacy-workflow-activities.md) [sıralı iş akışı görünümleri (eski)](../workflow-designer/sequential-workflow-views-legacy.md)