text
stringlengths
184
4.48M
{% extends "basicapp/base.html" %} {% block body_block %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <div class="container"> <input type="text" id="create_text" placeholder="type"> <input type="text" id="content" placeholder="type"> <button id="create" data-url="{% url 'basicapp:create'%}" type="button"> Create </button> <br> <br> {% for note in note_list%} <div id={{note.pk}}> <table id="note_list_table"> <tr> <td> <input type="text" class="title" name="" value="{{note.title}}" disabled/> <input type="text" class="content" name="" value="{{note.content}}" disabled/> </td> <td> <span id="editbutton" class="glyphicon glyphicon-pencil" onmouseup="edit(note_id = {{note.pk}})" aria-hidden="true"></span> <button id="updatebutton" data-url="{% url 'basicapp:update' pk=note.pk %}" type="button"> <span class="glyphicon glyphicon-ok" onmouseup="updateFunction(note_id={{note.pk}})" aria-hidden="true"></span> </button> </td> <td> <form action="{% url 'basicapp:delete' pk=note.pk %}" method="POST"> {%csrf_token%} <button id="deletebutton" type="submit"><span class="glyphicon glyphicon-trash trash" aria-hidden="true"></span></button> </form> <button id="removebutton" type="submit"><span id="remove" class="glyphicon glyphicon-remove" onmouseup="removeChange(note_id={{note.pk}})" aria-hidden="true"></span></button> </td> </tr> </table> </div> {% endfor%} </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> function edit(note_id) { var updateButton = document.getElementById(note_id).querySelectorAll("#updatebutton"); var removeButton = document.getElementById(note_id).querySelectorAll("#removebutton"); updateButton[0].style.display="block"; removeButton[0].style.display="block"; var title = document.getElementById(note_id).querySelectorAll(".title"); title[0].removeAttribute("disabled",""); var editButton = document.getElementById(note_id).querySelectorAll("#editbutton"); var deleteButton = document.getElementById(note_id).querySelectorAll("#deletebutton"); editButton[0].style.display="none"; deleteButton[0].style.display="none"; } function updateFunction(note_id) { var updateButton = document.getElementById(note_id).querySelectorAll("#updatebutton"); var urlUpdate = updateButton[0].getAttribute("data-url"); var titleInput = document.getElementById(note_id).querySelectorAll(".title"); title = titleInput[0].value; $.ajax({ type:"POST", url: urlUpdate, dataType:'json', data:{ 'title': title, csrfmiddlewaretoken: '{{ csrf_token }}', } }); titleInput[0].disabled=true; var editButton = document.getElementById(note_id).querySelectorAll("#editbutton"); var deleteButton = document.getElementById(note_id).querySelectorAll("#deletebutton"); editButton[0].style.display="block"; deleteButton[0].style.display="block"; var updateButton = document.getElementById(note_id).querySelectorAll("#updatebutton"); var removeButton = document.getElementById(note_id).querySelectorAll("#removebutton"); updateButton[0].style.display="none"; removeButton[0].style.display="none"; } $("#create").mouseup(function() { $.ajax({ type:"POST", url: $("#create").attr("data-url"), dataType:'json', data:{ 'title': $("#create_text").val(), 'content': $('#content').val(), csrfmiddlewaretoken: '{{ csrf_token }}', }, success(data){ alert(data); } }); location.reload(); }); function removeChange(note_id) { var editButton = document.getElementById(note_id).querySelectorAll("#editbutton"); var deleteButton = document.getElementById(note_id).querySelectorAll("#deletebutton"); editButton[0].style.display="block"; deleteButton[0].style.display="block"; var updateButton = document.getElementById(note_id).querySelectorAll("#updatebutton"); var removeButton = document.getElementById(note_id).querySelectorAll("#removebutton"); updateButton[0].style.display="none"; removeButton[0].style.display="none"; var titleInput = document.getElementById(note_id).querySelectorAll(".title"); titleInput[0].disabled=true; location.reload(); } </script> {% endblock %}
import '../scss/main.scss'; import React, { useState } from 'react'; import Button from 'react-bootstrap/Button'; import Col from 'react-bootstrap/Col'; import Form from 'react-bootstrap/Form'; import InputGroup from 'react-bootstrap/InputGroup'; import Row from 'react-bootstrap/Row'; const Contact = () => { const [validated, setValidated] = useState(false); const handleSubmit = (event) => { const form = event.currentTarget; if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } setValidated(true); }; return ( <div className='container'> <div className='row contact d-flex align-items-center justify-content-between pt-5 pb-5'> <div className='col-md-6 col-12'> <div className='contact__main text-md-start text-center'> <h3 className='contact__main--title'>Contact</h3> <p className='contact__main--text'>Questions or concerns? Just fill out the form below and our support team will get back to you within 24 hours</p> </div> </div> <div className='col-md-6 col-12 text-md-start text-center'> <Form noValidate validated={validated} onSubmit={handleSubmit}> <Row className="mb-3"> <Form.Group as={Col} md="6" controlId="validationCustom01"> <Form.Label></Form.Label> <Form.Control required type="text" placeholder="First name" /> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> </Form.Group> <Form.Group as={Col} md="6" controlId="validationCustom02"> <Form.Label></Form.Label> <Form.Control required type="text" placeholder="Last name" /> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> </Form.Group> <Form.Group as={Col} md="12" controlId="validationCustom03"> <Form.Label></Form.Label> <InputGroup hasValidation> <Form.Control type="number" placeholder="Phone Number" aria-describedby="inputGroupPrepend" required /> <Form.Control.Feedback type="invalid"> Please enter your number. </Form.Control.Feedback> </InputGroup> </Form.Group> </Row> <Form.Select> <option>Select Service</option> <option value="1">Management skills</option> <option value="2">B2B and B2C</option> <option value="3">Consumer Behaviour</option> </Form.Select> <Form.Group className="mb-3 pt-3"> <Form.Check required label="Agree to terms and conditions" feedback="You must agree before submitting." feedbackType="invalid" /> </Form.Group> <Button type="submit" className='contact__button'>Submit form</Button> </Form> </div> </div> </div> ) } export default Contact;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title>Portfolio</title> <meta content="" name="description"> <meta content="" name="keywords"> <!-- Favicons --> <link href="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Icon_S_blue.svg/1024px-Icon_S_blue.svg.png" rel="icon"> <link href="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Icon_S_blue.svg/1024px-Icon_S_blue.svg.png" rel="apple-touch-icon"> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet"> <!-- Vendor CSS Files --> <link href="assets/vendor/aos/aos.css" rel="stylesheet"> <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet"> <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet"> <link href="assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet"> <link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet"> <!-- Template Main CSS File --> <link href="assets/css/style.css" rel="stylesheet"> * Template Name: iPortfolio * Updated: Mar 10 2023 with Bootstrap v5.2.3 * Template URL: https://bootstrapmade.com/iportfolio-bootstrap-portfolio-websites-template/ * Author: BootstrapMade.com * License: https://bootstrapmade.com/license/ </head> <body> <!-- ======= 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="assets/img/40522.jpg" alt="" class="img-fluid rounded-circle"> <h1 class="text-light"><a href="index.html">Kankitanai Jinakung</a></h1> <div class="social-links mt-3 text-center"> <a href="https://l.facebook.com/l.php?u=https%3A%2F%2Ftwitter.com%2FFrankfoxtail%3Ft%3DaTxCDUIp-3zlI32Vam9dEw%26s%3D09%26fbclid%3DIwAR3uJTdEUIoufemni177r9FyuREvnCuP75XQ7A1BQEQTK5lfP_MnyKy7vY8&h=AT0UFQqQQ576MhQ4o7j3ZMW8KfCyXfoigdwvnirrWqtPK-NyL1qyJxnw-Of0IUW8Vg2cfwsmCvl55rgGJql6IKpgc7IRNpZXIY51Vk-kns6lPzzWZQ_UAS5XMvF4GzpOmzlUeuI_b0CP6R0" class="twitter"><i class="bx bxl-twitter"></i></a> <a href="https://www.facebook.com/kankitanai.jinakung" class="facebook"><i class="bx bxl-facebook"></i></a> <a href="https://www.instagram.com/santaff_/" class="instagram"><i class="bx bxl-instagram"></i></a> <a href="#" class="google-plus"><i class="bx bxl-skype"></i></a> <a href="https://www.linkedin.com/in/reallyy-undefined-13b525275/" 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 --> <!-- ======= Hero Section ======= --> <section id="hero" class="d-flex flex-column justify-content-center align-items-center"> <div class="hero-container" data-aos="fade-in"> <h1>Kankitanai Jinakung</h1> <p>But You Can Call me <span class="typed" data-typed-items="TaTar"></span></p> </div> </section><!-- End Hero --> <main id="main"> <!-- ======= About Section ======= --> <section id="about" class="about"> <div class="container"> <div class="section-title"> <h2>About</h2> <p>สวัสดีครับ ผมชื่อ นายกานต์กฤตนัย จินากลึงครับ หรือคุณจะเรียกผมว่า ตาต้า ก็ได้ ผมเป็นนักเรียนที่มาจากโรงเรียนพระปฐมวิทยาลัยและมีความพร้อมที่จะเข้าศึกษาในมหาวิทยาลัย ในสาขา วิทยาการคอมพิวเตอร์ครับ ผมเคยศึกษาในสาขาวิชานี้มาก่อน ซึ่งทำให้ผมคิดว่ามีความรู้และทักษะที่จำเป็นในการเรียนในสาขาวิชานี้ครับ นอกจากนี้ ผมเป็นคนที่มีความตั้งใจและเป้าหมายในการเรียนเป็นอย่างมาก ซึ่งผมจะใช้เวลาว่างของตัวเองในการศึกษาและทบทวนเนื้อหาเพื่อให้เข้าใจเนื้อหาได้อย่างลึกซึ้งและมีความรู้สูงสุดเท่าที่จะเป็นไปได้ และงานอดิเรกอีกอย่างของผมคือการเล่นกีฬาออกกำลังกายครับ </p> </div> <div class="row"> <div class="col-lg-4" data-aos="fade-right"> <img src="assets/img/40524.jpg" class="img-fluid" alt=""> </div> <div class="col-lg-8 pt-4 pt-lg-0 content" data-aos="fade-left"> <h3>Personal Information</h3> <p class="fst-italic"> ประวัติส่วนตัว </p> <div class="row"> <div class="col-lg-6"> <ul> <li><i class="bi bi-chevron-right"></i> <strong>Birthday:</strong> <span>25 Dec 2005</span></li> <li><i class="bi bi-chevron-right"></i> <strong>Website:</strong> <span>My Portfolio</span></li> <li><i class="bi bi-chevron-right"></i> <strong>Phone:</strong> <span>063-982-8822</span></li> <li><i class="bi bi-chevron-right"></i> <strong>City:</strong> <span>Nakhon pathom</span></li> </ul> </div> <div class="col-lg-6"> <ul> <li><i class="bi bi-chevron-right"></i> <strong>Age:</strong> <span>17</span></li> <li><i class="bi bi-chevron-right"></i> <strong>Degree:</strong> <span>student</span></li> <li><i class="bi bi-chevron-right"></i> <strong>Email:</strong> <span>santaffch@gmail.com</span></li> <li><i class="bi bi-chevron-right"></i> <strong>Hobby:</strong> <span>Coding and Basketball</span></li> </ul> </div> </div> <p> The only person you should try to be better than is the person you were yesterday. </p> </div> </div> </div> </section><!-- End About Section --> <!-- ======= Facts Section ======= --> <section id="facts" class="facts"> <div class="container"> <div class="section-title"> <h2>Principles</h2> <p>"อย่าแข่งกับคนอื่น ต้องแข่งกับตัวเอง อย่างน้อยก็ให้เรา เป็นคนที่ดีกว่าเมื่อวานให้ได้"</p> </div> <!--<div class="row no-gutters"> <div class="col-lg-3 col-md-6 d-md-flex align-items-md-stretch" data-aos="fade-up"> <div class="count-box"> <i class="bi bi-emoji-smile"></i> <span data-purecounter-start="0" data-purecounter-end="232" data-purecounter-duration="1" class="purecounter"></span> <p><strong>Happy Clients</strong> consequuntur quae</p> </div> </div> <div class="col-lg-3 col-md-6 d-md-flex align-items-md-stretch" data-aos="fade-up" data-aos-delay="100"> <div class="count-box"> <i class="bi bi-journal-richtext"></i> <span data-purecounter-start="0" data-purecounter-end="521" data-purecounter-duration="1" class="purecounter"></span> <p><strong>Projects</strong> adipisci atque cum quia aut</p> </div> </div> <div class="col-lg-3 col-md-6 d-md-flex align-items-md-stretch" data-aos="fade-up" data-aos-delay="200"> <div class="count-box"> <i class="bi bi-headset"></i> <span data-purecounter-start="0" data-purecounter-end="1453" data-purecounter-duration="1" class="purecounter"></span> <p><strong>Hours Of Support</strong> aut commodi quaerat</p> </div> </div> <div class="col-lg-3 col-md-6 d-md-flex align-items-md-stretch" data-aos="fade-up" data-aos-delay="300"> <div class="count-box"> <i class="bi bi-people"></i> <span data-purecounter-start="0" data-purecounter-end="32" data-purecounter-duration="1" class="purecounter"></span> <p><strong>Hard Workers</strong> rerum asperiores dolor</p> </div> </div> </div> </div>======= --> </section><!-- End Facts Section --> <!-- ======= Skills Section ======= --> <section id="skills" class="skills section-bg"> <div class="container"> <div class="section-title"> <h2>Skills</h2> <p>ความสามารถของผมนะครับ ผมเป็นคนที่ชอบศึกษาโค้ดครับ ภาษาที่ผมชอบสนใจหรือมีพื้นฐานก็จะมีดังนี้ครับ</p> </div> <div class="row skills-content"> <div class="col-lg-6" data-aos="fade-up"> <div class="progress"> <span class="skill">HTML <i class="val"></i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> <div class="progress"> <span class="skill">CSS <i class="val"></i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> <div class="progress"> <span class="skill">JavaScript <i class="val"></i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> </div> <div class="col-lg-6" data-aos="fade-up" data-aos-delay="100"> <div class="progress"> <span class="skill">PHP <i class="val"></i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> <div class="progress"> <span class="skill">Python <i class="val"></i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> <div class="progress"> <span class="skill">Bootstrap 5 <i class="val"></i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> </div> </div> </div> </section><!-- End Skills Section --> <!-- ======= Resume Section ======= --> <section id="resume" class="resume"> <div class="container"> <div class="section-title"> <h2>Education</h2> <p>การศึกษาของผมครับ</p> </div> <div class="row"> <div class="col-lg-6" data-aos="fade-up"> <h3 class="resume-title">Summary</h3> <div class="resume-item pb-0"> <h4>กานต์กฤตนัย จินากลึง</h4> <p><em>ผมคือชายที่มีความฝัน ที่อยากจะเป็นโปรแกรมเมอร์</em></p> <ul> <li>Nakhon Pathom</li> <li>0639828822</li> <li>santaffch@gmail.com</li> </ul> </div> <h3 class="resume-title">Education</h3> <div class="resume-item"> <h4>โรงเรียนอนุบาลนครปฐม </h4> <h5>2011 - 2017</h5> <p><em>ระดับชั้นประถมศึกษา</em></p> <p></p> </div> <div class="resume-item"> <h4>โรงเรียนพระปฐมวิทยาลัย</h4> <h5>2018 - 2020</h5> <p><em>ระดับชั้นมัธยมศึกษาตอนต้น</em></p> <p></p> </div> <div class="resume-item"> <h4>โรงเรียนพระปฐมวิทยาลัย</h4> <h5>2021 - 2023</h5> <p><em>ระดับชั้นมัธยมศึกษาตอนปลาย</em></p> <p></p> </div> </div> <!-- <div class="col-lg-6" data-aos="fade-up" data-aos-delay="100"> <h3 class="resume-title">Professional Experience</h3> <div class="resume-item"> <h4>โรงเรียนพระปฐมวิทยาลัย</h4> <h5>2021 - 2023</h5> <p><em>ระดับชั้นมัธยมศึกษาตอนปลาย </em></p> <ul> <li>Lead in the design, development, and implementation of the graphic, layout, and production communication materials</li> <li>Delegate tasks to the 7 members of the design team and provide counsel on all aspects of the project. </li> <li>Supervise the assessment of all graphic materials in order to ensure quality and accuracy of the design</li> <li>Oversee the efficient use of production project budgets ranging from $2,000 - $25,000</li> </ul> </div> <div class="resume-item"> <h4>Graphic design specialist</h4> <h5>2017 - 2018</h5> <p><em>Stepping Stone Advertising, New York, NY</em></p> <ul> <li>Developed numerous marketing programs (logos, brochures,infographics, presentations, and advertisements).</li> <li>Managed up to 5 projects or tasks at a given time while under pressure</li> <li>Recommended and consulted with clients on the most appropriate graphic design</li> <li>Created 4+ design presentations and proposals a month for clients and account managers</li> </ul> </div> </div> --> </div> </div> </section><!-- End Resume Section --> <!-- ======= Portfolio Section ======= --> <section id="portfolio" class="portfolio section-bg"> <div class="container"> <div class="section-title"> <h2>Portfolio</h2> <p>นี่คือผลงานของผม</p> </div> <div class="row" data-aos="fade-up"> <div class="col-lg-12 d-flex justify-content-center"> <ul id="portfolio-flters"> <li data-filter="*" class="filter-active">All</li> <!-- <li data-filter=".filter-app">App</li> <li data-filter=".filter-card">Card</li> --> </ul> </div> </div> <div class="row portfolio-container" data-aos="fade-up" data-aos-delay="100"> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/comsci.jpg" class="img-fluid" alt=""> <div class="portfolio-links"> <a href="assets/img/portfolio/comsci.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="เป็นงานที่ผมได้ไป open house ของคณะวิทยาศาสตร์ สาขาวิทยาการคอมพิวเตอร์"><i class="bx bx-plus"></i></a> <!-- <a href="portfolio-details.html" title="More Details"><i class="bx bx-link"></i></a> --> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/present.jpg" class="img-fluid" alt=""> <div class="portfolio-links"> <a href="assets/img/portfolio/present.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="เป็นงานพรีเซ็นต์โครงงานห้องเรียนพิเศษครับ"><i class="bx bx-plus"></i></a> <!-- <a href="portfolio-details.html" title="More Details"><i class="bx bx-link"></i></a> --> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/cer.jpg" class="img-fluid" alt=""> <div class="portfolio-links"> <a href="assets/img/portfolio/cer.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="ใบประกาศงาน KMITL future innovator"><i class="bx bx-plus"></i></a> <!-- <a href="portfolio-details.html" title="More Details"><i class="bx bx-link"></i></a> --> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/028-1709-31 2_page-0001.jpg" class="img-fluid" alt=""> <div class="portfolio-links"> <a href="assets/img/portfolio/028-1709-31 2_page-0001.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="ใบประกาศอบรม CIRA CORE"><i class="bx bx-plus"></i></a> <!-- <a href="portfolio-details.html" title="More Details"><i class="bx bx-link"></i></a> --> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/m1.jpg" class="img-fluid" alt=""> <div class="portfolio-links"> <a href="assets/img/portfolio/m1.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="ใบประกาศ Code.org"><i class="bx bx-plus"></i></a> <!-- <a href="portfolio-details.html" title="More Details"><i class="bx bx-link"></i></a> --> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/IMG_20230821_191313_864.jpg" class="img-fluid" alt=""> <div class="portfolio-links"> <a href="assets/img/portfolio/IMG_20230821_191313_864.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="งานแข่ง Hackathon ของ 42bangkok"><i class="bx bx-plus"></i></a> <!-- <a href="portfolio-details.html" title="More Details"><i class="bx bx-link"></i></a> --> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/FB_IMG_1689588543786.jpg" class="img-fluid" alt=""> <div class="portfolio-links"> <a href="assets/img/portfolio/FB_IMG_1689588543786.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="งาน PT energy camp ที่ผมได้เป็น STAFF"><i class="bx bx-plus"></i></a> <!-- <a href="portfolio-details.html" title="More Details"><i class="bx bx-link"></i></a> --> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/Page 59_page-0001.jpg" class="img-fluid" alt=""> <div class="portfolio-links"> <a href="assets/img/portfolio/Page 59_page-0001.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="ใบประกาศ การเข้าอบรม SAMSUNG SOLVE FOR TOMORROW"><i class="bx bx-plus"></i></a> <!-- <a href="portfolio-details.html" title="More Details"><i class="bx bx-link"></i></a> --> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/iot.jpg" class="img-fluid" alt=""> <div class="portfolio-links"> <a href="assets/img/portfolio/iot.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="ใบประกาศ เข้าร่วมประกวดโครงงาน iot"><i class="bx bx-plus"></i></a> <!-- <a href="portfolio-details.html" title="More Details"><i class="bx bx-link"></i></a> --> </div> </div> </div> </div> </div> </section><!-- End Portfolio Section --> <!-- ======= Services Section ======= --> <section id="services" class="services"> <div class="container"> <div class="section-title"> <h2>Facts</h2> <p>สวัสดีครับส่วนนี้จะเป็น Facts เกี่ยวกับตัวผมนะครับก็จะมีดังนี้ครับ</p> </div> <div class="row"> <div class="col-lg-4 col-md-6 icon-box" data-aos="fade-up"> <div class="icon"><i class="bi bi-briefcase"></i></div> <h4 class="title"><a href="">การทำงาน</a></h4> <p class="description">ผมเป็นคนที่มีความมุ่งมั่นในการทำงาน และเป็นคนที่มุ่งหวังที่จะพัฒนาตัวเองให้เก่งขึ้นเรื่อยๆครับ</p> </div> <div class="col-lg-4 col-md-6 icon-box" data-aos="fade-up" data-aos-delay="100"> <div class="icon"><i class="bi bi-card-checklist"></i></div> <h4 class="title"><a href="">ความกระตือรือร้น</a></h4> <p class="description">ผมเป็นคนที่ขยันมากๆครับเพราะผมเชื่อว่าความพยายามเป็นสิ่งที่สำคัญในการสร้างความสำเร็จครับ(BNK48)</p> </div> <div class="col-lg-4 col-md-6 icon-box" data-aos="fade-up" data-aos-delay="200"> <div class="icon"><i class="bi bi-bar-chart"></i></div> <h4 class="title"><a href="">การพัฒนาตัวเอง</a></h4> <p class="description">ผมเป็นคนที่มีความกระตือรือร้นในการพัฒนาตัวเองครับ มีการเรียนรู้อย่างต่อเนื่องเพื่อที่จะพัฒนาตัวเองและเพื่อเป็นคนดีขึ้นครับ</p> </div> <div class="col-lg-4 col-md-6 icon-box" data-aos="fade-up" data-aos-delay="300"> <div class="icon"><i class="bi bi-binoculars"></i></div> <h4 class="title"><a href="">การตรวจสอบและการสังเกตุ</a></h4> <p class="description">ผมมีนิสัยที่ชอบตรวจสอบรายละเอียดของสิ่งต่างๆที่เกี่ยวข้องกับงานที่ผมทำเพื่อให้แน่ใจว่าทุกอย่างถูกต้องและไม่มีข้อผิดพลาดครับ</p> </div> <div class="col-lg-4 col-md-6 icon-box" data-aos="fade-up" data-aos-delay="400"> <div class="icon"><i class="bi bi-brightness-high"></i></div> <h4 class="title"><a href="">ความคิดสร้างสรรค์</a></h4> <p class="description">ผมเป็นคนที่มีจินตนาการและมีความคิดสร้างสรรค์ที่ดีและสามารถสร้างสิ่งใหม่ๆได้ตลอดเวลาครับ</p> </div> <div class="col-lg-4 col-md-6 icon-box" data-aos="fade-up" data-aos-delay="500"> <div class="icon"><i class="bi bi-calendar4-week"></i></div> <h4 class="title"><a href="">การตรงต่อเวลา</a></h4> <p class="description">ผมเป็นคนที่มีความรับผิดชอบสูงในการปฏิบัติงานและการตรงต่อเวลาเป็นเรื่องสำคัญอย่างมากสำหรับผมครับ</p> </div> </div> </div> </section><!-- End Services Section --> <!-- ======= Contact Section ======= --> <section id="contact" class="contact"> <div class="container"> <div class="section-title"> <h2>Contact</h2> <p>ช่องทางการติดต่อ</p> </div> <div class="row" data-aos="fade-in"> <div class="col-lg-5 d-flex align-items-stretch"> <div class="info"> <div class="address"> <i class="bi bi-geo-alt"></i> <h4>Location:</h4> <p>15/2 ม.6 ต.แหลมบัว อ.นครชัยศรี จ.นครปฐม 73120</p> </div> <div class="email"> <i class="bi bi-envelope"></i> <h4>Email:</h4> <p>santaffch@gmail.com</p> </div> <div class="phone"> <i class="bi bi-phone"></i> <h4>Call:</h4> <p>063-982-8822</p> </div> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d25133.849864767457!2d100.13142494188862!3d13.868170554170515!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x30e2ee423bc998e1%3A0x8caf4e663234cc89!2z4LmB4Lir4Lil4Lih4Lia4Lix4LinIOC4leC4s-C4muC4pSDguYHguKvguKXguKHguJrguLHguKcg4Lit4Liz4LmA4Lig4Lit4LiZ4LiE4Lij4LiK4Lix4Lii4Lio4Lij4Li1IOC4meC4hOC4o-C4m-C4kOC4oQ!5e0!3m2!1sth!2sth!4v1683259720308!5m2!1sth!2sth" frameborder="0" style="border:0; width: 100%; height: 290px;" allowfullscreen></iframe> </div> </div> <div class="col-lg-7 mt-5 mt-lg-0 d-flex align-items-stretch"> <form action="forms/contact.php" method="post" role="form" class="php-email-form"> <div class="row"> <div class="form-group col-md-6"> <label for="name">Your Name</label> <input type="text" name="name" class="form-control" id="name" required> </div> <div class="form-group col-md-6"> <label for="name">Your Email</label> <input type="email" class="form-control" name="email" id="email" required> </div> </div> <div class="form-group"> <label for="name">Phone</label> <input type="text" class="form-control" name="subject" id="subject" required> </div> <div class="form-group"> <label for="name">Message</label> <textarea class="form-control" name="message" rows="10" required></textarea> </div> <div class="my-3"> <div class="loading">Loading</div> <div class="error-message"></div> <div class="sent-message">Your message has been sent. Thank you!</div> </div> <div class="text-center"><button type="submit">Send Message</button></div> </form> </div> </div> </div> </section><!-- End Contact Section --> </main><!-- End #main --> <!-- ======= Footer ======= --> <footer id="footer"> <div class="container"> <div class="copyright"> &copy; Copyright <strong><span>Portfolio</span></strong> </div> <div class="credits"> <!-- All the links in the footer should remain intact. --> <!-- You can delete the links only if you purchased the pro version. --> <!-- Licensing information: https://bootstrapmade.com/license/ --> <!-- Purchase the pro version with working PHP/AJAX contact form: https://bootstrapmade.com/iportfolio-bootstrap-portfolio-websites-template/ --> Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a> </div> </div> </footer><!-- End Footer --> <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a> <!-- Vendor JS Files --> <script src="assets/vendor/purecounter/purecounter_vanilla.js"></script> <script src="assets/vendor/aos/aos.js"></script> <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <script src="assets/vendor/glightbox/js/glightbox.min.js"></script> <script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script> <script src="assets/vendor/swiper/swiper-bundle.min.js"></script> <script src="assets/vendor/typed.js/typed.min.js"></script> <script src="assets/vendor/waypoints/noframework.waypoints.js"></script> <script src="assets/vendor/php-email-form/validate.js"></script> <!-- Template Main JS File --> <script src="assets/js/main.js"></script> </body> </html>
import 'dart:io'; import 'package:camera/camera.dart'; import 'package:image/image.dart' as img; import 'package:image_picker/image_picker.dart'; import 'package:path/path.dart' as path; import 'package:path_provider/path_provider.dart'; Future<File?> takePicture(CameraDescription cameraDescription) async { final cameraController = CameraController( cameraDescription, ResolutionPreset.high, ); try { await cameraController.initialize(); final image = await cameraController.takePicture(); cameraController.dispose(); return File(image.path); } catch (e) { cameraController.dispose(); return null; } } Future<File?> pickImageFromGallery() async { final picker = ImagePicker(); final pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile != null) { return File(pickedFile.path); } return null; } Future<File> compressImage(File file) async { final image = img.decodeImage(file.readAsBytesSync()); if (image == null) { throw Exception('Unable to decode image'); } final compressedImage = img.encodeJpg(image, quality: 85); final directory = await getApplicationDocumentsDirectory(); final compressedFile = File(path.join(directory.path, '${path.basenameWithoutExtension(file.path)}_compressed.jpg')) ..writeAsBytesSync(compressedImage); return compressedFile; }
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Spatie\Activitylog\LogOptions; use Spatie\Activitylog\Traits\LogsActivity; use Illuminate\Support\Str; class Unit extends Model { use HasFactory, LogsActivity; protected $guarded = []; public function produk() { return $this->hasMany(Produk::class, 'unit_id'); } public function getActivitylogOptions(): LogOptions { return LogOptions::defaults() ->logAll() ->setDescriptionForEvent(function ($e) { return request()->ip(); }) ->useLogName('Unit'); } protected static function boot() { parent::boot(); static::creating(function ($e) { $e->uuid = Str::uuid(); }); } }
from pathlib import Path from unittest import TestCase, main from socket import socket, AF_INET, SOCK_STREAM, SHUT_RDWR from classes.request import Request from classes.response import Response from enums.status import StatusCode, StatusPhrase from enums.methods import Methods from utils import DateUtilsBase, FileUtilsBase class TestServer(TestCase): """ Test HTTP socket server setUp and tearDown used to open new sockets for each test case """ @classmethod def setUpClass(cls): cls.server_host = "localhost" cls.server_port = 9999 cls.test_file = "test.html" def setUp(self): self.sock = socket(AF_INET, SOCK_STREAM) self.sock.connect((self.server_host, self.server_port)) def tearDown(self): self.sock.shutdown(SHUT_RDWR) self.sock.close() def send(self, message): if not self.sock: return self.sock.sendall(bytes(message, "ascii")) def receive(self): if not self.sock: return return str(self.sock.recv(1024), "ascii") ########## # GET # ########## def test_get_authorized(self): req = Request() self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_200_OK) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_200_OK) self.assertEqual(response.body, "hello :)") def test_get_unauthorized(self): req = Request(context="server.py") self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_403_FORBIDDEN) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_403_FORBIDDEN) self.assertEqual(response.body, "") def test_get_not_exists(self): req = Request(context="t.html") self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_404_NOT_FOUND) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_404_NOT_FOUND) self.assertEqual(response.body, "") def test_get_authorized_and_file_exists(self): req = Request(context=self.test_file) self.send(str(req)) with open(self.test_file, "r") as f: file_body = str(f.read()) expected_response_body = "\r\n".join( file_body.splitlines() ) # Split and rejoin to match line endings response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_200_OK) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_200_OK) self.assertEqual(response.body, expected_response_body) def test_get_authorized_and_file_exists_and_is_cached(self): # Should always be unmodified modified_timestamp = ( FileUtilsBase.get_file_last_modified_time_in_s(Path(self.test_file)) + 10 ) modified_http_date = DateUtilsBase.get_http_date(modified_timestamp) headers = {"If-Modified-Since": modified_http_date} req = Request(context=self.test_file, **headers) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_304_NOT_MODIFIED) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_304_NOT_MODIFIED) self.assertEqual(response.body, "") ########## # HEAD # ########## def test_head_authorized(self): req = Request(method=Methods.HTTP_HEAD) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_200_OK) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_200_OK) self.assertEqual(response.body, "") def test_head_unauthorized(self): req = Request(method=Methods.HTTP_HEAD, context="server.py") self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_403_FORBIDDEN) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_403_FORBIDDEN) self.assertEqual(response.body, "") def test_head_not_exists(self): req = Request(method=Methods.HTTP_HEAD, context="t.html") self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_404_NOT_FOUND) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_404_NOT_FOUND) self.assertEqual(response.body, "") def test_head_authorized_and_file_exists(self): req = Request(method=Methods.HTTP_HEAD, context=self.test_file) self.send(str(req)) # TODO: Assert headers equal? response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_200_OK) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_200_OK) self.assertEqual(response.body, "") def test_head_authorized_and_file_exists_and_is_cached(self): # Should always be unmodified modified_timestamp = ( FileUtilsBase.get_file_last_modified_time_in_s(Path(self.test_file)) + 11 ) modified_http_date = DateUtilsBase.get_http_date(modified_timestamp) headers = {"If-Modified-Since": modified_http_date} req = Request(method=Methods.HTTP_HEAD, context=self.test_file, **headers) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_304_NOT_MODIFIED) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_304_NOT_MODIFIED) self.assertEqual(response.body, "") ########## # POST # ########## def test_post_with_content_length(self): content = "Test data" content_length = len(content) headers = {"Content-Type": "text/plain", "Content-Length": content_length} req = Request(method=Methods.HTTP_POST, body=content, **headers) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_200_OK) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_200_OK) self.assertEqual(response.body, "") def test_post_without_content_length(self): headers = { "Content-Type": "text/plain", } req = Request(method=Methods.HTTP_POST, body="Test data", **headers) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_411_LENGTH_REQUIRED) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_411_LENGTH_REQUIRED) self.assertEqual(response.body, "") ########## # PUT # ########## def test_put_with_content_length(self): content = "Updated test data" content_length = len(content) headers = {"Content-Type": "text/plain", "Content-Length": content_length} req = Request( method=Methods.HTTP_PUT, context=self.test_file, body=content, **headers, ) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_200_OK) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_200_OK) self.assertEqual(response.body, "") def test_put_without_content_length(self): headers = { "Content-Type": "text/plain", } req = Request( method=Methods.HTTP_PUT, context=self.test_file, body="Updated test data", **headers, ) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_411_LENGTH_REQUIRED) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_411_LENGTH_REQUIRED) self.assertEqual(response.body, "") def test_put_unauthorized(self): content = "Updated test data" content_length = len(content) headers = {"Content-Type": "text/plain", "Content-Length": content_length} req = Request( method=Methods.HTTP_PUT, context="server.py", body=content, **headers ) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_403_FORBIDDEN) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_403_FORBIDDEN) self.assertEqual(response.body, "") def test_put_not_exists(self): content = "Updated test data" content_length = len(content) headers = {"Content-Type": "text/plain", "Content-Length": content_length} req = Request( method=Methods.HTTP_PUT, context="t.html", body=content, **headers ) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_404_NOT_FOUND) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_404_NOT_FOUND) self.assertEqual(response.body, "") ########## # DELETE # ########## def test_delete_ok(self): req = Request(method=Methods.HTTP_DELETE, context=self.test_file) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_200_OK) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_200_OK) self.assertEqual(response.body, "") def test_delete_unauthorized(self): req = Request(method=Methods.HTTP_DELETE, context="server.py") self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_403_FORBIDDEN) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_403_FORBIDDEN) self.assertEqual(response.body, "") def test_delete_not_exists(self): req = Request(method=Methods.HTTP_DELETE, context="t.html") self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_404_NOT_FOUND) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_404_NOT_FOUND) self.assertEqual(response.body, "") ########## # Other # ########## def test_unsupported_method_not_ok(self): req = Request(method="UNSUPPORTED", context=self.test_file) self.send(str(req)) response = Response.deserializer(self.receive()) self.assertEqual(response.status_code, StatusCode.HTTP_400_BAD_REQUEST) self.assertEqual(response.status_phrase, StatusPhrase.HTTP_400_BAD_REQUEST) self.assertEqual(response.body, "") if __name__ == "__main__": main()
package onlymash.materixiv.ui.base import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.viewbinding.ViewBinding abstract class BindingBottomSheetDialog<T: ViewBinding> : KodeinBottomSheetDialog() { private var _binding: T? = null val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = onCreateBinding(inflater, container) return binding.root } abstract fun onCreateBinding(inflater: LayoutInflater, container: ViewGroup?): T override fun onDestroyView() { _binding = null super.onDestroyView() } }
import type { PropsWithChildren } from 'react' import { motion, type Variants } from 'framer-motion' import { twMerge } from 'tailwind-merge' import MaskBackground from './MaskBackground' import Container from '../Container' interface Props { title?: React.ReactNode description?: React.ReactNode className?: string } const animation: Variants = { initial: { opacity: 0, translateX: -32 }, animate: { opacity: 1, translateX: 0 }, } const Hero: React.FC<PropsWithChildren<Props>> = ({ title, description, className, children }) => { return ( <MaskBackground> <Container size="lg" className={twMerge( 'relative z-10 flex flex-col justify-center pt-24 min-h-[320px]', className )} > <motion.h2 className="text-4xl mb-8 md:text-5xl font-medium" {...animation} transition={{ delay: 0.1 }} > {title} </motion.h2> <motion.p {...animation} transition={{ delay: 0.2 }} className="mb-8"> {description} </motion.p> </Container> </MaskBackground> ) } export default Hero
package com.HEIclub.demo.b_DAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.HEIclub.demo.a_model.Etudiant; import org.springframework.beans.factory.annotation.Autowired; public class EtudiantDAO { @Autowired private Connection connection; public EtudiantDAO(Connection connection) { } public void insert(Etudiant toAdd) throws SQLException { String sql = "INSERT INTO etudiant (nom, prenom) VALUES (?, ?)"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, toAdd.getNom()); preparedStatement.setString(2, toAdd.getPrenom()); preparedStatement.executeUpdate(); } } public List<Etudiant> findAll() throws SQLException { String sql = "SELECT * FROM etudiant"; List<Etudiant> allEtudiants = new ArrayList<>(); try (PreparedStatement preparedStatement = connection.prepareStatement(sql); ResultSet result = preparedStatement.executeQuery()) { while (result.next()) { allEtudiants.add(new Etudiant( result.getInt("id"), result.getString("nom"), result.getString("prenom"))); } } return allEtudiants; } public Etudiant getById(int etudiantId) throws SQLException { String sql = "SELECT * FROM etudiant WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setInt(1, etudiantId); try (ResultSet result = preparedStatement.executeQuery()) { if (result.next()) { return new Etudiant( result.getInt("id"), result.getString("nom"), result.getString("prenom")); } return null; } } } public void update(Etudiant updatedEtudiant) throws SQLException { String sql = "UPDATE etudiant SET nom = ?, prenom = ? WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, updatedEtudiant.getNom()); preparedStatement.setString(2, updatedEtudiant.getPrenom()); preparedStatement.setInt(3, updatedEtudiant.getId()); preparedStatement.executeUpdate(); } } public void delete(int etudiantId) throws SQLException { String sql = "DELETE FROM etudiant WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setInt(1, etudiantId); preparedStatement.executeUpdate(); } } }
import { isBrowser } from '@pavel/utils' import { useState, useEffect } from 'react' const query = isBrowser ? matchMedia('(prefers-color-scheme: dark)') : { matches: false } export function usePrefersColorScheme() { const [isDark, setIsDark] = useState(query.matches) useEffect(() => { function onChange(event: MediaQueryListEvent) { setIsDark(event.matches) } ;(query as MediaQueryList).addEventListener('change', onChange) return () => { ;(query as MediaQueryList).removeEventListener('change', onChange) } }, []) return isDark }
<template> <v-container :id="'section_'+id" class="_grid_two_image_with_form" :class="{'inverted': inverted}"> <picture class="_image"> <v-image :src="image" :alt="alt" width="650px" height="425px" /> </picture> <div class="_form"> <form :id="'form_'+id" @submit="submit"> <v-input id="name" placeholder="Nome" :maxlength="100" /> <v-input id="telphone" type="tel" placeholder="Telefone" :mask="'(##) #####-####'" :maxlength="15" /> <v-input id="email" type="email" placeholder="E-mail" :maxlength="255" /> <v-input id="city" placeholder="Cidade" :maxlength="255" /> <v-input id="company" placeholder="Empresa" :maxlength="255" /> <v-input id="message" placeholder="Mensagem" type="textarea" :rows="5" /> <div class="_privacy"> <p>{{ sitemap.privacy.text }}</p> <label> <input type="radio" name="accept_privacy" required> <div class="__box" /> <a :href="sitemap.privacy.url" target="_blank"> Aceito todo os termos e condições da Política de Privacidade. </a> </label> <label> <input type="radio" name="accept_privacy" required> <div class="__box" /> <a :href="sitemap.privacy.url" target="_blank"> Não aceito os termos e condições da Política de Privacidade. </a> </label> <label> <input type="checkbox" name="accept_receive_email"> <div class="__box" /> Tenho interesse em receber e-mails da Viener sobre as novidades, ofertas e demais materiais informativos sobre os produtos. </label> </div> <button type="submit"> {{ cta }} </button> </form> </div> </v-container> </template> <script> import sitemap from '@/data/ptbr/sitemap.json' import { useToastStore } from '@/store/toastState' export default { props: { image: { type: String, required: true }, alt: { type: String, required: true }, inverted: { type: Boolean, default: false }, cta: { type: String, default: 'Enviar' }, id: { type: String, required: true } }, data () { return { toast: useToastStore(), sitemap } }, methods: { submit (e) { e.preventDefault() const form = e.target const data = { name: form.name.value, telphone: form.telphone.value, email: form.email.value, city: form.city.value, company: form.company.value, message: form.message.value, subject: 'Formulario de ' + this.id, msg: ` <h2>Formulario vindo do site em:<br> <a href="${window.location.href}"> ${window.location.href}</a> </h2> <br><br> <strong>Nome: </strong> ${form.name.value}<br> <strong>Telefone: </strong> ${form.telphone.value}<br> <strong>Email: </strong> ${form.email.value}<br> <strong>Cidade: </strong> ${form.city.value}<br> <strong>Empresa: </strong> ${form.company.value}<br> <strong>Mensagem: </strong> ${form.message.value}<br> <br> <strong>Uso de dados:</strong> ${form.accept_privacy[0].checked ? 'permitido' : 'negado'}<br> <strong>Envio de emails:</strong> ${form.accept_receive_email.checked ? 'permitido' : 'negado'}<br> ` } this.$api.send(data).then((res) => { this.toast.showToast('Formulário enviado com sucesso') form.reset() }) } } } </script> <style lang="scss"> ._grid_two_image_with_form{ .container{ @apply grid grid-cols-2 gap-100px; ._image{ width: calc(100% + 80px); img { @apply w-full h-full; margin-left: -80px; } } ._form{ @apply flex flex-col justify-center gap-30px; form { @apply grid grid-cols-2 gap-20px; .input-box{ @apply flex-col gap-5px; label { @apply opacity-100 w-auto h-auto text-$text text-22px font-bold; line-height: 22px; } input, textarea { @apply border border-$text rounded-15px; &::placeholder{ @apply text-transparent; } } } #span_input_email, #span_input_message{ @apply col-span-2; } button{ @apply col-start-2 px-27px ml-auto; } ._privacy{ @apply col-span-2 px-5px flex flex-col gap-10px; p{ @apply font-bold text-22px; } label{ @apply text-15px grid gap-10px; grid-template-columns: 15px 1fr; .__box{ @apply w-14px h-14px relative mt-4px border border-$primary; &::after{ content: ''; @apply absolute w-4/5 h-4/5 top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2; transition: background-color 0.2s ease-in-out; } } input{ @apply opacity-0 pointer-events-none absolute; &:checked + .__box::after{ @apply bg-$primary; } } a{ @apply underline; } } } } } } &.inverted .container{ ._image{ @apply col-start-2; img { @apply w-full h-full; margin-left: 0px; } } ._form{ @apply col-start-1 row-start-1; } } } @media screen and (max-width: 768px) { ._grid_two_image_with_form{ .container{ @apply grid-cols-1 gap-50px; ._image{ width: 100%; img { @apply m-0; } } ._form{ @apply flex flex-col justify-center gap-20px; form { @apply grid-cols-1 gap-15px; .input-box{ @apply flex-col gap-5px; label { @apply opacity-100 text-17px; line-height: 22px; } } #span_input_email, #span_input_message{ @apply col-span-1; } button{ @apply col-start-1 px-27px mx-auto; } } } } &.inverted .container{ ._image{ @apply col-start-1; img { @apply w-full h-full; margin-left: 0px; } } ._form{ @apply col-start-1 row-start-1; } } } } </style>
#pragma once #include<iostream> #include<string> #include<fstream> using namespace std; class RomanNumber { private: int value; public: int GetValue() { return this->value; } const int maxValue = 9999; bool isValidDecimalNumber(string s); bool isValidRomanNumber(string s); string convertRomanToDecimal(string s); RomanNumber() { this->value = 1; } RomanNumber(const int &x) { this->value = x; } RomanNumber(const double &x) { int d = x; RomanNumber a(d); this->value = a.value; } RomanNumber(const string &s) { this->value = 0; if (this->isValidDecimalNumber(s)) { int d = 0; for (int i = 0; i < s.size() && s[i] != '.'; i++) d = d * 10 + s[i] - 48; this->value = d; } else if (this->isValidRomanNumber(s)) { string ss = this->convertRomanToDecimal(s); RomanNumber a(ss); this->value = a.value; } else { cout << "Error!\n"; } } RomanNumber(const RomanNumber& x) { this->value = x.value; } operator int() const { return this->value; } operator double() const { return this->value; } operator string() const { return this->toString(); } string toString() const{ string roman = ""; if (this->value > this->maxValue) roman = "The value is larger than the max value"; else if (this->value == 0) { roman = "The value is zero"; } else if (this->value < 0) { roman = "The value is smaller than zero"; } else{ int values[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; string symbols[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; int n = this->value; for (int i = 0; i < 13; i++) { while (n >= values[i]) { roman = roman + symbols[i]; n -= values[i]; } } } return roman; } RomanNumber& operator=(const RomanNumber& other) { if (this != &other) { this->value = other.value; } return *this; } friend istream& operator>>(istream& in, RomanNumber& x) { string s; in >> s; x = RomanNumber(s); return in; } friend ostream& operator<<(ostream& out, RomanNumber x) { out << x.toString(); return out; } RomanNumber operator+(const RomanNumber& x) { return RomanNumber(this->value + x.value); } RomanNumber operator-(const RomanNumber& x) { return RomanNumber(this->value - x.value); } RomanNumber operator*(const RomanNumber& x) { return RomanNumber(this->value * x.value); } RomanNumber operator/(const RomanNumber& x) { return RomanNumber(this->value / x.value); } RomanNumber operator%(const RomanNumber& x) { return RomanNumber(this->value % x.value); } RomanNumber operator+=(const RomanNumber& x) { this->value += x.value; return *this; } RomanNumber operator-=(const RomanNumber& x) { this->value -= x.value; return *this; } RomanNumber operator*=(const RomanNumber& x) { this->value *= x.value; return *this; } RomanNumber operator/=(const RomanNumber& x) { this->value /= x.value; return *this; } RomanNumber operator%=(const RomanNumber& x) { this->value %= x.value; return *this; } bool operator>(const RomanNumber& x) { return this->value > x.value; } bool operator>=(const RomanNumber& x) { return this->value >= x.value; } bool operator==(const RomanNumber& x) { return this->value == x.value; } bool operator<(const RomanNumber& x) { return this->value < x.value; } bool operator<=(const RomanNumber& x) { return this->value <= x.value; } };
package io.reactivex.internal.operators.observable; import io.reactivex.ObservableSource; import io.reactivex.Observer; import io.reactivex.functions.BiPredicate; import io.reactivex.functions.Function; import io.reactivex.internal.observers.BasicFuseableObserver; public final class ObservableDistinctUntilChanged<T, K> extends AbstractObservableWithUpstream<T, T> { final BiPredicate<? super K, ? super K> comparer; final Function<? super T, K> keySelector; public ObservableDistinctUntilChanged(ObservableSource<T> observableSource, Function<? super T, K> function, BiPredicate<? super K, ? super K> biPredicate) { super(observableSource); this.keySelector = function; this.comparer = biPredicate; } /* access modifiers changed from: protected */ @Override // io.reactivex.Observable public void subscribeActual(Observer<? super T> observer) { this.source.subscribe(new DistinctUntilChangedObserver(observer, this.keySelector, this.comparer)); } static final class DistinctUntilChangedObserver<T, K> extends BasicFuseableObserver<T, T> { final BiPredicate<? super K, ? super K> comparer; boolean hasValue; final Function<? super T, K> keySelector; K last; DistinctUntilChangedObserver(Observer<? super T> observer, Function<? super T, K> function, BiPredicate<? super K, ? super K> biPredicate) { super(observer); this.keySelector = function; this.comparer = biPredicate; } @Override // io.reactivex.Observer public void onNext(T t) { if (!this.done) { if (this.sourceMode != 0) { this.downstream.onNext(t); return; } try { K apply = this.keySelector.apply(t); if (this.hasValue) { boolean test = this.comparer.test(this.last, apply); this.last = apply; if (test) { return; } } else { this.hasValue = true; this.last = apply; } this.downstream.onNext(t); } catch (Throwable th) { fail(th); } } } @Override // io.reactivex.internal.fuseable.QueueFuseable public int requestFusion(int i) { return transitiveBoundaryFusion(i); } /* JADX WARN: Type inference failed for: r0v1, types: [T, java.lang.Object] */ /* JADX WARNING: Unknown variable types count: 1 */ @Override // io.reactivex.internal.fuseable.SimpleQueue public T poll() throws Exception { while (true) { ?? r0 = (Object) this.qd.poll(); if (r0 == 0) { return null; } K apply = this.keySelector.apply(r0); if (!this.hasValue) { this.hasValue = true; this.last = apply; return r0; } else if (!this.comparer.test(this.last, apply)) { this.last = apply; return r0; } else { this.last = apply; } } } } }
#include "lists.h" /** * free_listint2 - frees memory allocated to a linked list of integers * while avoiding dangling pointers * @head: a pointer to the head node */ void free_listint2(listint_t **head) { listint_t *tmp; if (head == NULL) return; /* the list is already empty, there's nothing to be free'd */ while (*head != NULL) { tmp = *head; *head = (*head)->next; safe_free(tmp); } } /** * _free - a safer way to free dynamically allocated memory * @ptr: pointer to memory location * * Description: This _free() function takes care of freeing * dynamically allocated memory while ensuring the pointer * @ptr passed to it is not NULL before trying to free it. * Also, after freeing the memory, it sets the pointer @ptr * to NULL to avoid the issue of dangling pointers. */ void _free(void **ptr) { if (ptr != NULL || *ptr != NULL) { free(*ptr); *ptr = NULL; } }
--- title: "STOP struggling with Hamachi on Windows - Solve the Service Stopped problem NOW!" ShowToc: true date: "2023-02-17" author: "Max Randall" --- ***** ## STOP struggling with Hamachi on Windows - Solve the Service Stopped problem NOW! If you're using Hamachi to connect your network devices, you might have experienced the "Hamachi service stopped" error. This error can be frustrating, especially when you need to get your work done quickly. But don't worry, because we've got you covered. In this article, we'll go over some of the most common reasons behind the error and share some tips for fixing it. ### Common reasons behind the Hamachi service stopped error There are several reasons why the Hamachi service can stop working. Some of these reasons include: - An outdated Hamachi client - A corrupt Hamachi client - An outdated or corrupt network driver - A conflict with a security software - A conflict with Windows Firewall ### How to fix the Hamachi service stopped error 1. Update Hamachi The first thing you should try is to update the Hamachi client to the latest version. This is because the error can occur due to an outdated Hamachi client. You can download the latest version of Hamachi from the official website. 2. Uninstall and reinstall Hamachi If updating Hamachi doesn't solve the problem, you might need to uninstall and reinstall the software. This can help fix any issues with a corrupt or outdated client. 3. Update or reinstall the network adapter driver If the issue persists, try updating or reinstalling the network adapter driver. This is because the Hamachi service relies on the network adapter driver to function properly. 4. Disable security software Sometimes, security software can conflict with Hamachi and cause the service to stop working. If this is the case, try disabling your security software temporarily. 5. Allow Hamachi through Windows Firewall If you're using Windows Firewall, make sure that Hamachi is allowed through it. You can do this by adding an inbound rule for Hamachi. ### Conclusion The Hamachi service stopped error can be frustrating, but it's a problem that can be fixed. By following the tips we've shared in this article, you should be able to get your Hamachi connection up and running in no time. Remember to always keep your Hamachi client and network driver up to date to avoid future issues. Happy networking! {{< youtube nwkiU6GG-YU >}} LogMeIn Hamachi Virtual Private Service or VPN for short is one of the most popular and widely used VPN services across the globe. It helps users to mask their IP address while surfing the internet and prevent malicious actors and marketing agencies from capturing the IP address and the information about the websites browsed. However, there are many reports where users have complained of this VPN service not working and displaying messages such as Hamachi Service Stopped in Windows PC. This article focuses on the best ways that are Hamachi Service Stopped Fixes as recommended by experts. ## How To Fix Hamachi Service Stopped Problem in Windows. The reasons as to why this error occurs are not clear but certain resolutions have fixed this issue for many. Here is a list of the methods that are described as the best Hamachi Service stopped fixes in 2021. ### Method 1: Launch Hamachi App in Administrator Mode Administrator Mode in the Windows operating system is a privilege given to Windows Apps by default and can be provided to third-party applications by the administrator of the PC (which is most probably you unless you are using an office computer). This elevated mode helps apps use all the Windows system resources and shared files without restrictions. Here are the steps to run any app in admin mode: Step 1: Make a right-click on the Hamachi app shortcut and select Properties from the context. Step 2: A new window will open where you will have to click on the Compatibility tab. Step 3: Check the box labeled as Run This Program As An Administrator. Step 4: Click on Apply and then OK. Step 5: Relaunch the Hamachi app and check if the Hamachi server status stopped error has been resolved on your PC. ### Method 2: Turn Off Antivirus The next method that can be used as a Hamachi service stop fix is to disable or turn off your Antivirus temporarily to identify if it was being considered a false positive by your Antivirus app. To disable your Antivirus app temporarily, you need to refer to the documentation of your respective Antivirus as there are different methods for different applications. ### Method 3: Enable WMI Service For a VPN to work, you must ensure that the Windows Management Instrumentation service is enabled in Windows 10. To check the current status of the WMI service on your computer, follow these steps: All Antivirus applications work with the same goal of preventing malware from infiltrating your PC. However, if you are not satisfied with your Antivirus and are looking for an alternative, then let me share a secret about what the entire team at WETHEGEEK technical blogs team uses. We have been using Systweak Antivirus for quite some time and found that the Systweak Antivirus is one of the few antivirus software that monitors your system on a real-time basis preventing certified malware and potential threats which means it provides exploit protection to its users. More on Systweak Antivirus, Read Here. Step 1: Press Windows + R on the keyboard to invoke the RUN box. Step 2: Type services.msc followed by the Enter Key. Step 3: A new window will open where you can find all the services in your Windows OS listed alphabetically. Step 4: Scroll down and locate WMI Service or Windows Management Instrumentation and check the status. Step 5: Double Click on the WMI service and a small window will appear. Step 6: Ensure that the Startup Type is set as Automatic, else you can select it from the dropdown options. Step 7: Click on Apply and then on OK. Once the WMI service is set to automatic and is running, you can relaunch the Hamachi app and check if it works fine. ### Method 4: Update Drivers Outdated drivers can create certain issues and errors in your PC. Hence it is important to update your drivers that act as a link between the software and the hardware. It is not possible to update every driver (at least 50) manually by visiting the official websites, downloading and installing them. Hence it is recommended by experts to use driver updater software that will scan, identify and fix all the driver issues by using a few appropriate mouse clicks. Here are the steps: Step 1: Download Advanced Driver Updater from the download button provided below. Step 2: Install the software by making a double click on the downloaded file and then follow the instructions on the screen. Step 3: Open the program and click on the Start Scan Now button. Step 4: The app will now scan your PC and show you the list of driver errors on your screen. Step 5: Click on the Update link beside all the driver anomalies and wait for the process to complete. Step 6: Reboot your computer and this will ensure that the process is complete and check the Hamachi VPN service. ### Method 5: Reinstall Hamachi App The next alternative method that is among Hamachi service stopped fixes is to uninstall the Hamachi app and reinstall it from the original service. Here are the steps: Step 1: Press Windows + S to open the Search box and type Add Remove Programs. Step 2: Click on the best match result that displays what you typed with system settings underneath. Step 3: A new window will open that will display a list of programs installed in your system. Locate the Hamachi app and make a right-click on it to select Uninstall. Step 4: Once the service is uninstalled, you can visit the official website of Hamachi to download and install it again. Step 5: After the installation is complete, reboot your PC and check if you are still facing the Hamachi server status stopped issue. ### Method 6: Use Alternate VPN The final method that can act as a Hamachi service stop fix is to use a different VPN service. If the above 5 methods are not working then there seems to be a compatibility issue between the Hamachi VPN and your Windows OS. Until you are ready to reinstall your Windows OS and all the apps, you may opt for a new VPN service because a complete reinstall of Windows OS does not guarantee that the Hamachi VPN service will work or not. The Final Word On How To Fix Hamachi Service Stopped Problem in Windows There are many VPN services available but Systweak VPN has an edge over others. It is easy to use and has an intuitive interface. Here are some features that might interest you. Access Global Content – Users can watch and listen to content available on the internet without restrictions from geo-location barriers placed by streaming sites. IKev2 – Secure tunnel results in secure data and offers good speed. AES 256-bit. This VPN offers military-grade encryption services and the data is rendered useless even if someone tries to hack it. Kill Switch. This feature ensures that your IP address and sensitive data remain secure even if the VPN server fails for a short while and you have connected through your ISP again. Different Servers & Locations. Systweak VPN boasts of having 4500+ servers in 53+ countries and 200+ different locations. More On Systweak VPN, Click Here. The above methods are compiled from various tech forums where experts drop in suggestions and users vote them positive or negative depending on the efficiency of the method. These methods have worked for many and will resolve the problem of Hamachi server status being stopped on your PC. If you rather not spend time and effort troubleshooting Hamachi VPN then you can directly download Systeak VPN and start using it. Follow us on social media – Facebook, Instagram  and YouTube. ## People Who Read This Post Also Like
<template> <input @blur="blurEvent" :type="type" @input="inputChange" class="f-input" :placeholder="pla" :class="styleCss"/> </template> <script setup > import { inject } from 'vue'; import {computed} from 'vue' import { formItemContextKey } from '../form/src/form-item'; import { watch } from 'vue'; defineOptions({ name:'f-input' }) const props=defineProps({ placeholder:{ type:String, default:'' }, round:{ type:Boolean, default:false }, modelValue:{ type:String, default:"" }, type:{ type:String, default:'text' } }) const pla=computed(()=>{ return props.placeholder }) const styleCss=computed(()=>{ return [props.round ? `f-input--round`:''] }) const emits=defineEmits(['update:modelValue']) const inputChange=(e)=>{ emits('update:modelValue',e.target.value) formItemContext?.validate('change') } const blurEvent=(e)=>{ formItemContext.validate('blur') } const formItemContext=inject(formItemContextKey) </script> <style scoped lang="less"> .f-input{ padding: 10px 15px; padding-right: 30px; outline: none; border: 1px solid #ccc; &--round{ border-radius:10% ; } } </style>
import { eventApi, paymentApi } from '@/apis'; import { DetailItem, EventCard } from '@/components/event'; import { CustomerLayout } from '@/components/layout'; import { Button, Loading, Separator, Skeleton } from '@/components/ui'; import { useEvents } from '@/hooks'; import { Event, NextPageWithLayout } from '@/models'; import { PaymentTicket, ValidateStripeSessionResponse } from '@/types'; import { calculateTime, formatDateToLocaleDate, formatDateToTime } from '@/utils'; import Link from 'next/link'; import { useRouter } from 'next/router'; import { useEffect, useRef, useState } from 'react'; import { LuCalendar, LuCheckCircle2, LuClock, LuMapPin, LuTicket } from 'react-icons/lu'; import QRCode from 'react-qr-code'; interface TicketItemProps { index: number; ticket: PaymentTicket; } const CheckoutConfirmation: NextPageWithLayout = () => { const router = useRouter(); const { paymentId } = router.query; const [isValidating, setIsValidating] = useState<boolean>(false); const [bill, setBill] = useState<ValidateStripeSessionResponse>(); const [event, setEvent] = useState<Event>(); const { events, isLoading: eventLoading } = useEvents(); const handleValidateStripeSession = useRef<any>(null); useEffect(() => { handleValidateStripeSession.current = async () => { setIsValidating(true); try { if (paymentId) { const response = await paymentApi.validateStripeSession( Number.parseInt(paymentId as string) ); const event = await eventApi.getEventById(response.eventId); setEvent(event); setBill(response); } setIsValidating(false); } catch (error) { setIsValidating(false); console.log(error); } }; handleValidateStripeSession.current(); () => handleValidateStripeSession.current; }, [paymentId]); return isValidating || !bill || !event ? ( <div className="flex items-center justify-center w-full min-h-[calc(100vh-56px)]"> <div className="flex flex-col items-center"> <Loading size="large" /> <p className="text-2xl text-neutral-600 font-bold"> Đang kiểm tra giao dịch ... </p> </div> </div> ) : ( <div> <div className="px-32"> <div className="mt-[29px] mb-[39px] p-[34px] rounded-m border-secondary-500 bg-secondary-100 border border-solid flex items-center gap-[22px]"> <LuCheckCircle2 className="text-[44px] text-secondary-500" /> <span className="text-xl font-bold text-neutral-700"> Thanh toán thành công </span> </div> {event && ( <div> <h2 className="text-[32px] font-bold mb-9">{event.name}</h2> <div className="grid grid-cols-4"> <DetailItem icon={<LuCalendar />} title="Thời gian" description={ <div className="flex flex-col"> <span> {event?.eventDate && formatDateToLocaleDate(new Date(event?.eventDate))} </span> <span> {event?.eventDate && formatDateToTime(new Date(event?.eventDate))} </span> </div> } /> <DetailItem icon={<LuClock />} title="Diễn ra trong" description={ event?.ticketStartTime && event?.ticketCloseTime && calculateTime(event?.ticketStartTime, event?.ticketCloseTime) } /> <DetailItem icon={<LuMapPin />} title="Địa điểm" description={event.location} /> <DetailItem icon={<LuTicket />} title={`${bill?.tickets.length} Vé`} description="Email eTicket" /> </div> </div> )} <Separator className="my-[46px]" /> <div> <h3 className="text-2xl font-bold mb-[22px]">Thông tin thanh toán</h3> <div className="flex items-center gap-x-24"> <div className="flex flex-col gap-[5px] items-start"> <div className="text-neutral-550">Mã thanh toán</div> <div>#{bill?.id}</div> </div> <div className="flex flex-col gap-[5px] items-start"> <div className="text-neutral-550">Thời gian</div> <div> {new Date(bill?.createdAt as Date).toLocaleDateString('vi-VN', { dateStyle: 'long' })} </div> </div> <div className="flex flex-col gap-[5px] items-start"> <div className="text-neutral-550">Tổng tiền</div> <div> {(bill?.totalPrice as number)?.toLocaleString('vi-VN')} VNĐ </div> </div> {bill?.paymentMethod && ( <div className="flex flex-col gap-[5px] items-start"> <div className="text-neutral-550">Phương thức thanh toán</div> <div className="capitalize"> {bill?.paymentMethod.card} - **** {bill?.paymentMethod.last4} </div> </div> )} </div> </div> <div className="mt-[58px]"> <h3 className="text-2xl font-bold mb-[22px]">Thông tin liên lạc</h3> <div className="flex items-center gap-x-24"> <div className="flex flex-col gap-[5px] items-start"> <div className="text-neutral-550">Họ tên</div> <div>{bill?.customerName}</div> </div> <div className="flex flex-col gap-[5px] items-start"> <div className="text-neutral-550">Email</div> <div>{bill?.customerEmail}</div> </div> <div className="flex flex-col gap-[5px] items-start"> <div className="text-neutral-550">Số điện thoại</div> <div>{bill?.customerPhone}</div> </div> </div> </div> <div className="mt-[58px]"> <h3 className="text-2xl font-bold mb-[22px]"> Thông tin vé ({bill?.tickets.length}){' '} <span className="text-primary-500"> tổng:{' '} {( ((bill?.totalPrice || 0) / (100 - (bill?.discount || 0))) * 100 ).toLocaleString('vi-VN')}{' '} VNĐ </span> </h3> <div className="flex flex-col gap-5"> {bill && bill.tickets && bill.tickets.length > 0 && bill.tickets.map((ticket, index) => ( <TicketItem key={index} index={index} ticket={ticket} /> ))} </div> </div> <Link href={'/my-tickets'}> <Button type="button" className="text-white mt-10"> Đi đến vé của tôi </Button> </Link> </div> <div className="px-[132px] py-12 mt-[88px]"> <div className="flex items-center justify-between mb-8"> <h2 className="text-[32px] font-bold leading-[48px]"> Sự kiện <span className="text-primary-500">tương tự</span> </h2> <Link href={'/event/search'}> <Button type="button" className="bg-primary-100 text-primary-500 hover:bg-primary-200" > Xem thêm </Button> </Link> </div> <div className="grid grid-cols-2 gap-6"> {eventLoading ? ( <> <Skeleton className="h-[349px]" /> <Skeleton className="h-[349px]" /> </> ) : ( events && events.length > 0 && events ?.slice(0, 2) .map(event => ( <EventCard key={event.id} event={event} size="large" /> )) )} </div> </div> </div> ); }; function TicketItem({ index, ticket }: TicketItemProps) { return ( <div className="py-5 px-[30px] rounded-m bg-neutral-100 border-neutral-200"> <h4 className="flex items-center gap-4 font-bold"> <LuTicket className="text-2xl text-primary-500" /> <span>Vé {index + 1}</span> </h4> <div className="flex items-center"> <div className="flex flex-1 items-center justify-between mr-14 ml-7"> <div className="flex flex-col gap-[5px] items-start"> <div className="text-neutral-550">Họ tên</div> <div>{ticket.ownerName}</div> </div> <div className="flex flex-col gap-[5px] items-start"> <div className="text-neutral-550">Email</div> <div>{ticket.ownerEmail}</div> </div> <div className="flex flex-col gap-[5px] items-start"> <div className="text-neutral-550">Số điện thoại</div> <div>{ticket.ownerPhone}</div> </div> </div> <div className="bg-white rounded-xl flex items-center p-5 gap-5"> <div className="flex-1 flex flex-col items-center text-primary-500 "> <span>Mã vé</span> <span className="font-bold truncate w-[105px]"> {ticket.ticketCode} </span> </div> <div className="w-[105px] h-[105px]"> <QRCode value={ticket.ticketCode || ''} className="w-full h-full" /> </div> </div> </div> </div> ); } CheckoutConfirmation.Layout = CustomerLayout; export default CheckoutConfirmation;
package main // BingoBoard represents the state of a Bingo board. type BingoBoard struct { numbers [][]int called [][]bool } // NewBingoBoard returns a new BingoBoard from a grid of ints. func NewBingoBoard(numbers [][]int) *BingoBoard { b := &BingoBoard{ numbers: numbers, called: make([][]bool, len(numbers)), } for i := range numbers { b.called[i] = make([]bool, len(numbers)) } return b } // Call marks num as called on this board, if present. func (b *BingoBoard) Call(num int) { for i, row := range b.numbers { for j, cel := range row { if cel == num { b.called[i][j] = true return } } } } // HasWon returns true if the board is a winner. func (b *BingoBoard) HasWon() bool { columnCounts := make([]int, len(b.numbers)) for _, row := range b.called { allTrue := true for i, called := range row { if !called { allTrue = false } else { columnCounts[i]++ } } if allTrue { return true } } for _, c := range columnCounts { if c == len(b.called) { return true } } return false } // Score returns the score of this board given the last call before the board won. func (b *BingoBoard) Score(winningCall int) (score int) { for i, row := range b.numbers { for j, cel := range row { if !b.called[i][j] { score += cel } } } score *= winningCall return } // Clear unmarks all board numbers as called. func (b *BingoBoard) Clear() { for _, row := range b.called { for j := range row { row[j] = false } } }
package co.nayan.review.recorddetail import android.annotation.SuppressLint import android.content.res.Configuration import android.graphics.Bitmap import android.graphics.Color import android.graphics.drawable.Drawable import android.net.Uri import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.MediaController import androidx.core.view.children import androidx.recyclerview.widget.RecyclerView import co.nayan.c3v2.core.config.DrawType import co.nayan.c3v2.core.config.Judgment import co.nayan.c3v2.core.config.MediaType import co.nayan.c3v2.core.config.Mode import co.nayan.c3v2.core.models.Record import co.nayan.c3v2.core.utils.* import co.nayan.c3views.crop.CropPhotoView import co.nayan.c3views.dragsplit.DragSplitPhotoView import co.nayan.c3views.paint.PaintPhotoView import co.nayan.c3views.polygon.PolygonPhotoView import co.nayan.c3views.quadrilateral.QuadrilateralPhotoView import co.nayan.c3views.utils.* import co.nayan.review.R import co.nayan.review.databinding.FragmentRecordDetailBinding import co.nayan.review.recordsgallery.RecordItem import co.nayan.review.utils.isVideo import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.load.resource.gif.GifDrawable import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.target.Target import com.bumptech.glide.request.transition.Transition import com.github.chrisbanes.photoview.PhotoView import timber.log.Timber class RecordDetailAdapter( private val recordListener: RecordListener, private val orientation: Int?, private val applicationMode: String?, private val appFlavor: String?, private val showStar: Boolean = false, private val contrastValue: Int = 50, private val infoTouchListener: ((Record?) -> Unit)? = null ) : RecyclerView.Adapter<RecordDetailAdapter.MyViewHolder>() { private val recordItems = arrayListOf<RecordItem>() override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): RecordDetailAdapter.MyViewHolder { return MyViewHolder( FragmentRecordDetailBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: RecordDetailAdapter.MyViewHolder, position: Int) { holder.onBind( recordItems[position], appFlavor, applicationMode, showStar, contrastValue ) } override fun getItemCount(): Int { return recordItems.size } fun addAll(toAdd: List<RecordItem>) { recordItems.addAll(toAdd) notifyDataSetChanged() } fun updateRecords(recordItem: RecordItem?) { val submittedRecordIndex = recordItems.indexOf(recordItem) if (submittedRecordIndex != RecyclerView.NO_POSITION) { recordItems.removeAt(submittedRecordIndex) notifyItemRemoved(submittedRecordIndex) } } fun markRecordAsApproved(recordItem: RecordItem) { val selectedRecordIndex = recordItems.indexOf(recordItem) if (selectedRecordIndex != RecyclerView.NO_POSITION) { recordItems.removeAt(selectedRecordIndex) notifyItemRemoved(selectedRecordIndex) } } fun markRecordAsRejected(recordItem: RecordItem) { val selectedRecordIndex = recordItems.indexOf(recordItem) if (selectedRecordIndex != RecyclerView.NO_POSITION) { recordItems.removeAt(selectedRecordIndex) notifyItemRemoved(selectedRecordIndex) } } inner class MyViewHolder( val binding: FragmentRecordDetailBinding ) : RecyclerView.ViewHolder(binding.root) { // private val recordIdTxt = itemView.recordIdTxt // private val answerTxt = itemView.answerTxt // private val hideOverlayIv = itemView.hideOverlayIv // private val reloadIV = itemView.reloadIV // private val loaderIV = itemView.loaderIV // private val starredIv = itemView.starredIv // private var needsRejectionView = itemView.needsRejectionView // private var needsNoRejectionView = itemView.needsNoRejectionView // private val videoView = itemView.videoView // private val junkRecordIv = itemView.junkRecordIv // private val answerContainer = itemView.answerContainer // private val parentViewController = itemView.parentViewController // private val photoViewContainer = itemView.photoViewContainer // private val resetBtn = itemView.resetBtn // private val approveBtn = itemView.approveBtn // private val statusImg = itemView.statusImg private var applicationMode: String? = null private var recordItem: RecordItem? = null private var appFlavor: String? = null private var drawType: String? = null private var showStar: Boolean = false private var contrastValue: Int = 50 private var recordBitmap: Bitmap? = null private var maskedBitmap: Bitmap? = null fun onBind( recordItem: RecordItem, appFlavor: String? = null, applicationMode: String?, showStar: Boolean, contrastValue: Int ) { this.recordItem = recordItem this.appFlavor = appFlavor this.applicationMode = applicationMode this.showStar = showStar this.contrastValue = contrastValue val recordId = if (recordItem.record.isSniffingRecord == true) recordItem.record.randomSniffingId ?: recordItem.record.id else recordItem.record.id binding.recordIdTxt.text = String.format("Record ID: $recordId") binding.recordIdTxt.setOnTouchListener(recordInfoTouchListener) setupStarredStatus(showStar) setupSniffingView(recordItem.record.isSniffingRecord) setupSubmissionStatus() val url = if (recordItem.record.mediaType == MediaType.VIDEO) recordItem.record.mediaUrl else recordItem.record.displayImage ?: recordItem.record.mediaUrl url?.let { mediaUrl -> if (mediaUrl.isVideo()) { binding.hideOverlayIv.gone() onVideoReady(mediaUrl) } else { binding.hideOverlayIv.visible() binding.reloadIV.gone() binding.loaderIV.visible() setupRecord(recordItem.record) } } binding.hideOverlayIv.setOnTouchListener(hideOverlayListener) binding.reloadIV.setOnClickListener { setupRecord(recordItem.record) } binding.resetBtn.setOnClickListener { recordItem.isApproved = false recordItem.isRejected = true recordListener.onResetClicked(recordItem) } binding.approveBtn.setOnClickListener { recordItem.isApproved = true recordItem.isRejected = false recordListener.onApproveClicked(recordItem) } } @SuppressLint("ClickableViewAccessibility") private val recordInfoTouchListener = View.OnTouchListener { _, event -> val drawableRight = 2 if (event.action == MotionEvent.ACTION_DOWN) { if (event.rawX >= binding.recordIdTxt.right - binding.recordIdTxt.compoundDrawables[drawableRight].bounds.width()) { infoTouchListener?.invoke(recordItem?.record) } } true } @SuppressLint("ClickableViewAccessibility") private val hideOverlayListener = View.OnTouchListener { _, event -> val photoView = binding.photoViewContainer.children.firstOrNull() when (event.action) { MotionEvent.ACTION_DOWN -> { if (binding.junkRecordIv.visibility == View.VISIBLE) binding.junkRecordIv.gone() photoView?.let { when (photoView) { is CropPhotoView -> { photoView.crops.clear() photoView.invalidate() } is QuadrilateralPhotoView -> { photoView.quadrilaterals.clear() photoView.invalidate() } is PolygonPhotoView -> { photoView.points.clear() photoView.invalidate() } is PaintPhotoView -> { photoView.paintDataList.clear() photoView.invalidate() } is DragSplitPhotoView -> { photoView.splitCropping.clear() photoView.invalidate() } else -> { recordBitmap?.let { bitmap -> (photoView as PhotoView).setImageBitmap(bitmap) } } } } } MotionEvent.ACTION_UP -> { photoView?.let { val annotations = recordItem?.record.annotations() recordBitmap?.let { bitmap -> when (photoView) { is CropPhotoView -> { photoView.crops.addAll(annotations.crops(bitmap)) photoView.invalidate() } is QuadrilateralPhotoView -> { photoView.quadrilaterals.addAll( annotations.quadrilaterals( bitmap ) ) photoView.invalidate() } is PolygonPhotoView -> { photoView.points.addAll(annotations.polygonPoints(bitmap)) photoView.invalidate() } is PaintPhotoView -> { photoView.paintDataList.addAll(annotations.paintDataList(bitmap = bitmap)) photoView.invalidate() } is DragSplitPhotoView -> { photoView.splitCropping.addAll(annotations.splitCrops(bitmap)) photoView.invalidate() } else -> { maskedBitmap?.let { maskedBitmap -> (photoView as PhotoView).setImageBitmap(maskedBitmap) } } } } } setAnswer() } } true } private fun setupStarredStatus(showStar: Boolean) { if (showStar && recordItem?.record?.starred == true) binding.starredIv.visible() else binding.starredIv.gone() } private fun setupSniffingView(isSniffingRecord: Boolean?) { if ((appFlavor == "qa" || appFlavor == "dev") && isSniffingRecord == true) { if (recordItem?.record?.needsRejection == true) { binding.needsRejectionView.visible() binding.needsNoRejectionView.gone() } else { binding.needsRejectionView.gone() binding.needsNoRejectionView.visible() } } else { binding.needsNoRejectionView.gone() binding.needsRejectionView.gone() } } @SuppressLint("UseCompatLoadingForDrawables") private fun setupSubmissionStatus() { if (recordItem?.isApproved == true && recordItem?.isRejected == false) { binding.approveBtn.gone() binding.resetBtn.gone() binding.statusImg.visible() binding.statusImg.setImageResource(R.drawable.ic_approved_stamp) } else if (recordItem?.isApproved == false && recordItem?.isRejected == true) { binding.approveBtn.gone() binding.resetBtn.gone() binding.statusImg.visible() binding.statusImg.setImageResource(R.drawable.ic_rejected_stamp) } else if (recordItem?.isApproved == false && recordItem?.isRejected == false) { binding.approveBtn.visible() binding.resetBtn.visible() binding.statusImg.gone() } } private fun loadGif(mediaUrl: String, photoView: PhotoView) { Glide.with(photoView.context) .asGif() .load(mediaUrl) .diskCacheStrategy(DiskCacheStrategy.ALL) .listener(gifRequestListener) .into(photoView) } private fun setupRecord(record: Record) { binding.photoViewContainer.removeAllViews() maskedBitmap = null recordBitmap = null binding.reloadIV.gone() binding.loaderIV.visible() binding.photoViewContainer.invisible() drawType = record.drawType() record.displayImage?.let { mediaUrl -> try { when { mediaUrl.contains("gif") -> { val photoView = PhotoView(itemView.context) photoView.colorFilter = ImageUtils.getColorMatrix(contrastValue) photoView.setOnTouchListener { _, _ -> false } binding.photoViewContainer.addView(photoView) loadGif(mediaUrl, photoView) } else -> { Glide.with(itemView.context) .asBitmap() .diskCacheStrategy(DiskCacheStrategy.ALL) .load(mediaUrl) .into(target) } } setAnswer() } catch (e: Exception) { onBitmapLoadFailed() Timber.e("${e.printStackTrace()}") } } } private val gifRequestListener = object : RequestListener<GifDrawable> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<GifDrawable>, isFirstResource: Boolean ): Boolean { onBitmapLoadFailed() return false } override fun onResourceReady( resource: GifDrawable, model: Any, target: Target<GifDrawable>?, dataSource: DataSource, isFirstResource: Boolean ): Boolean { onBitmapReady() return false } } private val target = object : CustomTarget<Bitmap>() { override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { if (drawType != DrawType.MASK) { onBitmapReady() } drawAnnotations(resource) } override fun onLoadFailed(errorDrawable: Drawable?) { super.onLoadFailed(errorDrawable) onBitmapLoadFailed() } override fun onLoadCleared(placeholder: Drawable?) { binding.photoViewContainer.removeAllViews() } } private fun drawAnnotations(bitmap: Bitmap) { maskedBitmap = null val annotations = recordItem?.record.annotations() if (annotations.isNullOrEmpty()) { val photoView = PhotoView(itemView.context, null) recordBitmap = bitmap loadImage(bitmap, photoView) setAnswer() } else { binding.junkRecordIv.gone() recordBitmap = bitmap when (drawType) { DrawType.BOUNDING_BOX -> { val cropView = CropPhotoView(binding.photoViewContainer.context, null) cropView.reset() cropView.editMode(isEnabled = false) cropView.setBitmapAttributes(bitmap.width, bitmap.height) cropView.crops.addAll(annotations.crops(bitmap)) loadImage(bitmap, cropView) } DrawType.QUADRILATERAL -> { val quadrilateralView = QuadrilateralPhotoView(binding.photoViewContainer.context, null) quadrilateralView.reset() quadrilateralView.editMode(isEnabled = false) quadrilateralView.quadrilaterals.addAll(annotations.quadrilaterals(bitmap)) loadImage(bitmap, quadrilateralView) } DrawType.POLYGON -> { val polygonView = PolygonPhotoView(binding.photoViewContainer.context, null) polygonView.reset() polygonView.editMode(isEnabled = false) polygonView.points.addAll(annotations.polygonPoints(bitmap)) loadImage(bitmap, polygonView) } DrawType.CONNECTED_LINE -> { val paintView = PaintPhotoView(binding.photoViewContainer.context, null) paintView.reset() paintView.editMode(isEnabled = false) paintView.setBitmapAttributes(bitmap.width, bitmap.height) paintView.paintDataList.addAll(annotations.paintDataList(bitmap = bitmap)) loadImage(bitmap, paintView) } DrawType.SPLIT_BOX -> { val dragSplitView = DragSplitPhotoView(binding.photoViewContainer.context, null) dragSplitView.reset() dragSplitView.editMode(isEnabled = false) dragSplitView.setBitmapAttributes(bitmap.width, bitmap.height) dragSplitView.splitCropping.addAll(annotations.splitCrops(bitmap)) loadImage(bitmap, dragSplitView) } DrawType.MASK -> { val imageUrls = annotations.map { it.maskUrl } if (imageUrls.isNullOrEmpty()) { onBitmapReady() val photoView = PhotoView(binding.photoViewContainer.context) photoView.setOnTouchListener { _, _ -> false } recordBitmap?.let { loadImage(it, photoView) } } else downloadMaskBitmaps(imageUrls) } else -> { val photoView = PhotoView(binding.photoViewContainer.context) photoView.setOnTouchListener { _, _ -> false } loadImage(bitmap, photoView) } } } } private fun setAnswer() { val answer = recordItem?.record?.answer() binding.junkRecordIv.gone() when (applicationMode) { Mode.INPUT, Mode.LP_INPUT, Mode.MULTI_INPUT, Mode.CLASSIFY, Mode.DYNAMIC_CLASSIFY, Mode.BINARY_CLASSIFY -> { if (answer.isNullOrEmpty()) binding.answerContainer.gone() else if (answer == Judgment.JUNK) { binding.junkRecordIv.visible() binding.answerContainer.gone() } else { binding.answerContainer.visible() binding.answerTxt.text = answer } } Mode.EVENT_VALIDATION -> { binding.answerContainer.gone() binding.junkRecordIv.gone() } else -> { if (answer == Judgment.JUNK) { binding.answerContainer.visible() binding.answerTxt.text = answer } else binding.answerContainer.gone() } } } private fun onBitmapLoadFailed() { itemView.context?.let { binding.reloadIV.visible() binding.loaderIV.gone() binding.videoView.gone() binding.photoViewContainer.invisible() } } private fun onMaskBitmapLoadFailed() { itemView.context?.let { binding.reloadIV.gone() binding.loaderIV.gone() binding.videoView.gone() binding.photoViewContainer.visible() val photoView = PhotoView(binding.photoViewContainer.context) recordBitmap?.let { loadImage(it, photoView) } } } private fun onBitmapReady() { itemView.context?.let { binding.reloadIV.gone() binding.loaderIV.gone() binding.videoView.gone() binding.photoViewContainer.visible() } } private fun loadImage(bitmap: Bitmap, view: PhotoView) { view.apply { val layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT ) setLayoutParams(layoutParams) setImageBitmap(bitmap) colorFilter = ImageUtils.getColorMatrix(contrastValue) } binding.photoViewContainer.addView(view) } private fun onVideoReady(mediaUrl: String) { binding.photoViewContainer.gone() binding.parentViewController.gone() binding.videoView.visible() binding.reloadIV.gone() binding.loaderIV.gone() // Play Video in VideoView val mediaController = MediaController(itemView.context) binding.videoView.apply { setBackgroundColor(Color.TRANSPARENT) setVideoURI(Uri.parse(mediaUrl)) setOnPreparedListener { binding.videoView.layoutParams = binding.videoView.layoutParams.apply { if (orientation == Configuration.ORIENTATION_PORTRAIT) { val mediaProportion: Float = it.videoHeight.toFloat() / it.videoWidth.toFloat() width = ViewGroup.LayoutParams.MATCH_PARENT height = (binding.videoView.width.toFloat() * mediaProportion).toInt() } else { val mediaProportion: Float = it.videoWidth.toFloat() / it.videoHeight.toFloat() height = ViewGroup.LayoutParams.MATCH_PARENT width = (binding.videoView.height.toFloat() * mediaProportion).toInt() } } it.start() it.isLooping = true it.setOnVideoSizeChangedListener { _, _, _ -> binding.videoView.setMediaController(mediaController) mediaController.setAnchorView(binding.videoView) } } } setAnswer() } private fun downloadMaskBitmaps(imageUrls: List<String?>) { val bitmaps = mutableListOf<Bitmap>() imageUrls.forEachIndexed { index, imageUrl -> try { Glide.with(itemView.context) .asBitmap() .load(imageUrl) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(object : CustomTarget<Bitmap>() { override fun onResourceReady( resource: Bitmap, transition: Transition<in Bitmap>? ) { bitmaps.add(resource) if (index == imageUrls.size - 1) { onBitmapReady() recordBitmap?.let { val photoView = PhotoView(binding.photoViewContainer.context) photoView.setOnTouchListener { _, _ -> false } maskedBitmap = it.overlayBitmap(bitmaps) maskedBitmap?.let { maskedBitmap -> loadImage(maskedBitmap, photoView) } } } } override fun onLoadCleared(placeholder: Drawable?) {} override fun onLoadFailed(errorDrawable: Drawable?) { super.onLoadFailed(errorDrawable) onMaskBitmapLoadFailed() return } }) } catch (e: Exception) { e.printStackTrace() onMaskBitmapLoadFailed() } } } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Works</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <header> <nav> <ul class="nav-bar"> <li class='title'><a href='./index.html'>Portfolio</a></li> <input type='checkbox' id='check' /> <span class="menu"> <li><a href="./index.html">Home</a></li> <li><a href="./Services.html">Services</a></li> <li><a href="./Experiences.html">Experiences</a></li> <li><a href="./Works.html">Works</a></li> <li><button class="button" id="button_contact">Contact me</button></li> <label for="check" class="close-menu"><i class="fas fa-times"></i></label> </span> <label for="check" class="open-menu"><i class="fas fa-bars"></i></label> </ul> </nav> </header> <main class="main"> <h2 id="block--work_elem--h2">My Works/Projects</h2> <div class="block--work--cardcontainer"> <div class="block--work--card"> <p id="block--work--card_elem--p">News homepage</p> <p id="block--work--card_elem--p">This news homepage will be an excellent opportunity to practice your CSS Grid skills. There will be lots of tricky decisions to make and plenty of learning opportunities!</p> <img class="cardimg" src="./UGR-4100-14/src/images/News homepage.png" alt=""> <img class="block--work--card_elem--img" src="./images/News homepage.png" alt=""> </div> <div class="block--work--card"> <p id="block--work--card_elem--p">Single price grid component</p> <p id="block--work--card_elem--p">In this challenge, you will build out the pricing component to the designs provided. This is perfect for beginners and people who want to complete a smaller challenge.</p> <img class="block--work--card_elem--img" src="./images/Single Price Grid Component.png" alt=""> </div> <div class="block--work--card"> <p id="block--work--card_elem--p">Multi-step form</p> <p id="block--work--card_elem--p">An excellent test for your form-building and JS skills, this project will pose many challenges along the way to completion.</p> <img class="block--work--card_elem--img" src="./images/Multi-step form.png" alt=""> </div> <div class="block--work--card"> <p id="block--work--card_elem--p">Newsletter sign-up form with success message</p> <p id="block--work--card_elem--p">This will test your skills with basic form structure, validation, and submission. The success state will also be an excellent opportunity to work with DOM manipulation.</p> <img class="block--work--card_elem--img" src="./images/Newsletter sign-up form with success.png" alt=""> </div> <div class="block--work--card"> <p id="block--work--card_elem--p">Results summary component </p> <p id="block--work--card_elem--p">This challenge has something for everyone. It’s a HTML and CSS only project, but we’ve also provided a JSON file of the test results for anyone wanting to practice JS.</p> <img class="block--work--card_elem--img" src="./images/Results summary component.png" alt=""> </div> <div class="block--work--card"> <p id="block--work--card_elem--p">Age calculator app</p> <p id="block--work--card_elem--p">This challenge is designed to sharpen your JavaScript and form validation skills. Working with dates in JavaScript can be tricky, so this will be a nice test!</p> <img class="block--work--card_elem--img" src="./images/Age calculator app.png" alt=""> </div> </div> </main> <footer> <div class="block--footer"> <div> <ul class="block--footer--links"> <h4>Social Media:</h4> <li><a id="facebook" class="fa fa-facebook"></a></li> <li><a id="instagram" class="fa fa-instagram"></a></li> <li><a id="youtube" class="fa fa-youtube"></a></li> <li><a id="linkedin" class="fa fa-linkedin"></a></li> </ul> </div> <div> <ul class="block--footer--pages"> <h4>Pages</h4> <li><a href="./index.html">Home</a></li> <li><a href="./Services.html">Services</a></li> <li><a href="./Experiences.html">Experiences</a></li> <li><a href="./Works.html">Works</a></li> </ul> </div> </div> <h5>Copyright &copy; 2023 Daniel Asrat</h5> </footer> <script src="./js/index.js"></script> </body> </html>
import React from 'react'; import './checkout.styles.scss'; import CheckoutItem from '../../components/checkout-item/checkout-item'; import StripeCheckoutButton from '../../components/stripe-button/stripe-button.component'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { selectCartItems, selecCartTotal, selectCartTotal } from '../../redux/cart/cart.selectors'; const CheckoutPage = ({ cartItems, total }) => ( <div className='checkout-page'> <div className='checkout-header'> <div className='checkout-block'> <span>Product</span> </div> <div className='checkout-block'> <span>Description</span> </div> <div className='checkout-block'> <span>Quantity</span> </div> <div className='checkout-block'> <span>Price</span> </div> <div className='checkout-block'> <span>Remove</span> </div> </div> { cartItems.map(cartItem => <CheckoutItem key={cartItem.id} cartItem={cartItem} /> ) } <div className='total'> <span>TOTAL: ${total}</span> </div> <StripeCheckoutButton price={total} /> <div className='test-card'> * PLEASE USE THIS TEST CARD FOR PAYMENTS * <br /> <span>4242 4242 4242 4242 - Visa - CVC: Any 3 digits - Date: Any future date</span> </div> </div> ); const mapStateToProps = createStructuredSelector({ cartItems: selectCartItems, total: selectCartTotal }); export default connect(mapStateToProps)(CheckoutPage);
import { RefObject, useEffect, useRef } from "react"; const defaultEvents = ['mousedown', 'touchstart']; function useOnClickOutside<E extends Event = Event>( ref: RefObject<HTMLElement | null>, onClickOutside: (e: E) => void, ) { const savedCallback = useRef(onClickOutside); useEffect(() => { savedCallback.current = onClickOutside; }, [onClickOutside]) useEffect(() => { const handler = (event: any) => { const { current: el } = ref; el && !el.contains(event.target) && savedCallback.current(event); }; for (const eventName of defaultEvents) { document.addEventListener(eventName, handler); } return () => { for (const eventName of defaultEvents) { document.removeEventListener(eventName, handler); } } }, [ref]); } export default useOnClickOutside;
#!/usr/bin/python3 """ module 8-rectangle """ BaseGeometry = __import__('7-base_geometry').BaseGeometry class Rectangle(BaseGeometry): """ A class representing a rectangle. This class inherits from the BaseGeometry class and extends it to specifically handle rectangles. Attributes: __width (int): The width of the rectangle. __height (int): The height of the rectangle. Methods: __init__(width, height): Initializes a new Rectangle instance with the specified width and height. """ def __init__(self, width, height): """ Initialize a new Rectangle. Parameters: width (int): The width of the rectangle. height (int): The height of the rectangle. Raises: TypeError: If either width or height is not an integer. ValueError: If either width or height is less than or equal to 0. """ self.integer_validator("width", width) self.integer_validator("height", height) self.__width = width self.__height = height
/* * Copyright 2023 Szabolcs Bazil Papp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package hu.aestallon.jsmol.json; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; public final class JsonArray extends WrappedValue<List<JsonValue>> implements List<JsonValue>, JsonComplex<JsonValue> { public JsonArray(List<JsonValue> l) {super(l);} @Override public String toString() { return value().stream() .map(Objects::toString) .collect(Collectors.joining(",", "[", "]")); } @Override public Stream<JsonValue> iter() { return super.value().stream(); } @Override public int size() { return super.value().size(); } @Override public boolean isEmpty() { return super.value().isEmpty(); } @Override public boolean contains(Object o) { return super.value().contains(o); } @Override public Iterator<JsonValue> iterator() { return super.value().iterator(); } @Override public Object[] toArray() { return super.value().toArray(); } @Override public <T> T[] toArray(T[] a) { return super.value().toArray(a); } @Override public boolean add(JsonValue jsonValue) { return super.value().add(jsonValue); } @Override public boolean remove(Object o) { return super.value().remove(o); } @Override public boolean containsAll(Collection<?> c) { return new HashSet<>(super.value()).containsAll(c); } @Override public boolean addAll(Collection<? extends JsonValue> c) { return super.value().addAll(c); } @Override public boolean addAll(int index, Collection<? extends JsonValue> c) { return super.value().addAll(index, c); } @Override public boolean removeAll(Collection<?> c) { return super.value().removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return super.value().retainAll(c); } @Override public void clear() { super.value().clear(); } @Override public JsonValue get(int index) { return super.value().get(index); } @Override public JsonValue set(int index, JsonValue element) { return super.value().set(index, element); } @Override public void add(int index, JsonValue element) { super.value().add(index, element); } @Override public JsonValue remove(int index) { return super.value().remove(index); } @Override public int indexOf(Object o) { return super.value().indexOf(o); } @Override public int lastIndexOf(Object o) { return super.value().lastIndexOf(o); } @Override public ListIterator<JsonValue> listIterator() { return super.value().listIterator(); } @Override public ListIterator<JsonValue> listIterator(int index) { return super.value().listIterator(index); } @Override public List<JsonValue> subList(int fromIndex, int toIndex) { return super.value().subList(fromIndex, toIndex); } }
export enum UserPermission { User = 'USER', Admin = 'ADMIN', } export interface User { id: number; permissions: UserPermission[]; email?: string; username: string; urlSlug: string; aboutMarkdown: string; isAllowedToStream: boolean; isInPublicMode: boolean; muxStreamKey?: string; muxPlaybackId?: string; muxLiveStreamStatus?: | 'created' | 'connected' | 'recording' | 'active' | 'disconnected' | 'idle' | 'updated' | 'disabled' | 'deleted'; profileImageUrl: string; stripeCustomerId: string; stripeConnectAccountId: string; createdAt: string; updatedAt: string; } export interface Chat { id: number; user: User; userId: number; parentUser: User; parentUserId: number; message: string; createdAt: string; updatedAt: string; } export interface Payment { id: number; amountInCents: number; stripePaymentIntentId: string; user: User; userId: number; payeeUser: User; payeeUserId: number; showId?: number; isRefunded?: boolean; createdAt: string; updatedAt: string; } export interface ChatEvent { chat?: Chat; payment?: Payment; } export interface Show { id: number; title: string; showtime: string; user: User; minPriceInCents: number; }
import type { FailedResult, Result } from 'paima-sdk/paima-mw-core'; import { PaimaMiddlewareErrorCode, getBlockNumber } from 'paima-sdk/paima-mw-core'; import type { MatchExecutor, RoundExecutor } from 'paima-sdk/paima-executors'; import type { MatchExecutorData, RoundStatusData, UserStats, LobbyState, RoundExecutorBackendData, MatchState, TickEvent, } from '@dice/utils'; import { buildEndpointErrorFxn, MiddlewareErrorCode } from '../errors'; import { auxGetLobbyRaw, auxGetLobbyState, getRawNewLobbies } from '../helpers/auxiliary-queries'; import { calculateRoundEnd } from '../helpers/utility-functions'; import { buildMatchExecutor, buildRoundExecutor } from '../helpers/executors'; import { backendQueryMatchExecutor, backendQueryNftsForWallet, backendQueryOpenLobbies, backendQueryRoundExecutor, backendQueryRoundStatus, backendQuerySearchLobby, backendQueryUserLobbies, backendQueryUserStats, } from '../helpers/query-constructors'; import type { LobbyStates, NewLobbies, PackedLobbyRaw, PackedLobbyState, PackedRoundExecutionState, PackedUserLobbies, PackedUserStats, } from '../types'; import type { WalletAddress } from 'paima-sdk/paima-utils'; import type { IGetPaginatedUserLobbiesResult } from '@dice/db'; async function getLobbyRaw(lobbyID: string): Promise<PackedLobbyRaw | FailedResult> { const errorFxn = buildEndpointErrorFxn('getLobbyRaw'); let packedLobbyRaw: PackedLobbyRaw | FailedResult; try { packedLobbyRaw = await auxGetLobbyRaw(lobbyID); if (!packedLobbyRaw.success) { return errorFxn(packedLobbyRaw.errorMessage); } } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.ERROR_QUERYING_BACKEND_ENDPOINT, err); } try { const { lobby } = packedLobbyRaw; return { success: true, lobby, }; } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.INVALID_RESPONSE_FROM_BACKEND, err); } } async function getLobbyState(lobbyID: string): Promise<PackedLobbyState | FailedResult> { const errorFxn = buildEndpointErrorFxn('getLobbyState'); let packedLobbyState: PackedLobbyState | FailedResult; try { packedLobbyState = await auxGetLobbyState(lobbyID); if (!packedLobbyState.success) { return errorFxn(packedLobbyState.errorMessage); } } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.ERROR_QUERYING_BACKEND_ENDPOINT, err); } try { const { lobby } = packedLobbyState; return { success: true, lobby, }; } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.INVALID_RESPONSE_FROM_BACKEND, err); } } async function getLobbySearch( nftId: number, searchQuery: string, page: number, count?: number ): Promise<LobbyStates | FailedResult> { const errorFxn = buildEndpointErrorFxn('getLobbySearch'); let response: Response; try { const query = backendQuerySearchLobby(nftId, searchQuery, page, count); response = await fetch(query); } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.ERROR_QUERYING_BACKEND_ENDPOINT, err); } try { const j = (await response.json()) as { lobbies: LobbyState[] }; return { success: true, lobbies: j.lobbies, }; } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.INVALID_RESPONSE_FROM_BACKEND, err); } } async function getRoundExecutionState( lobbyID: string, matchWithinLobby: number, roundWithinMatch: number ): Promise<PackedRoundExecutionState | FailedResult> { const errorFxn = buildEndpointErrorFxn('getRoundExecutionState'); let res: Response; let latestBlockHeight: number; try { const query = backendQueryRoundStatus(lobbyID, matchWithinLobby, roundWithinMatch); [res, latestBlockHeight] = await Promise.all([fetch(query), getBlockNumber()]); } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.ERROR_QUERYING_BACKEND_ENDPOINT, err); } try { const roundStatus = (await res.json()) as RoundStatusData; const { roundStarted: start, roundLength: length } = roundStatus; const end = calculateRoundEnd(start, length, latestBlockHeight); return { success: true, round: { executed: roundStatus.executed, usersWhoSubmittedMoves: roundStatus.usersWhoSubmittedMoves, roundEndsInBlocks: end.blocks, roundEndsInSeconds: end.seconds, }, }; } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.INVALID_RESPONSE_FROM_BACKEND, err); } } async function getUserStats(nftId: number): Promise<PackedUserStats | FailedResult> { const errorFxn = buildEndpointErrorFxn('getUserStats'); let res: Response; try { const query = backendQueryUserStats(nftId); res = await fetch(query); } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.ERROR_QUERYING_BACKEND_ENDPOINT, err); } try { const j = (await res.json()) as { stats: UserStats }; return { success: true, stats: j.stats, }; } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.INVALID_RESPONSE_FROM_BACKEND, err); } } async function getNewLobbies( nftId: number, blockHeight: number ): Promise<NewLobbies | FailedResult> { const errorFxn = buildEndpointErrorFxn('getNewLobbies'); try { return getRawNewLobbies(nftId, blockHeight); } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.UNKNOWN, err); } } async function getUserLobbiesMatches( nftId: number, page: number, count?: number ): Promise<PackedUserLobbies | FailedResult> { const errorFxn = buildEndpointErrorFxn('getUserLobbiesMatches'); let res: Response; try { const query = backendQueryUserLobbies(nftId, count, page); res = await fetch(query); } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.ERROR_QUERYING_BACKEND_ENDPOINT, err); } try { const j = (await res.json()) as { lobbies: IGetPaginatedUserLobbiesResult[] }; return { success: true, lobbies: j.lobbies, }; } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.INVALID_RESPONSE_FROM_BACKEND, err); } } async function getOpenLobbies( nftId: number, page: number, count?: number ): Promise<LobbyStates | FailedResult> { const errorFxn = buildEndpointErrorFxn('getOpenLobbies'); let res: Response; try { const query = backendQueryOpenLobbies(nftId, count, page); res = await fetch(query); } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.ERROR_QUERYING_BACKEND_ENDPOINT, err); } try { const j = (await res.json()) as { lobbies: LobbyState[] }; return { success: true, lobbies: j.lobbies, }; } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.INVALID_RESPONSE_FROM_BACKEND, err); } } async function getRoundExecutor( lobbyId: string, matchWithinLobby: number, roundWithinMatch: number, matchState: MatchState ): Promise<Result<RoundExecutor<MatchState, TickEvent>>> { const errorFxn = buildEndpointErrorFxn('getRoundExecutor'); // Retrieve data: let res: Response; try { const query = backendQueryRoundExecutor(lobbyId, matchWithinLobby, roundWithinMatch); res = await fetch(query); } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.ERROR_QUERYING_BACKEND_ENDPOINT, err); } let backendData: RoundExecutorBackendData; try { backendData = (await res.json()) as RoundExecutorBackendData; } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.INVALID_RESPONSE_FROM_BACKEND, err); } // Process data: try { const executor = buildRoundExecutor({ ...backendData, matchState, }); return { success: true, result: executor, }; } catch (err) { return errorFxn(MiddlewareErrorCode.UNABLE_TO_BUILD_EXECUTOR, err); } } async function getMatchExecutor( lobbyId: string, matchWithinLobby: number ): Promise<Result<MatchExecutor<MatchState, TickEvent>>> { const errorFxn = buildEndpointErrorFxn('getMatchExecutor'); // Retrieve data: let res: Response; try { const query = backendQueryMatchExecutor(lobbyId, matchWithinLobby); res = await fetch(query); } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.ERROR_QUERYING_BACKEND_ENDPOINT, err); } let data: MatchExecutorData; try { data = (await res.json()) as MatchExecutorData; } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.INVALID_RESPONSE_FROM_BACKEND, err); } // Process data: try { const executor = buildMatchExecutor(data); return { success: true, result: executor, }; } catch (err) { return errorFxn(MiddlewareErrorCode.UNABLE_TO_BUILD_EXECUTOR, err); } } async function getNftsForWallet(wallet: WalletAddress): Promise<Result<number[]>> { const errorFxn = buildEndpointErrorFxn('getNftsForLobby'); let res: Response; try { const query = backendQueryNftsForWallet(wallet); res = await fetch(query); } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.ERROR_QUERYING_BACKEND_ENDPOINT, err); } try { const nfts = (await res.json()) as number[]; return { success: true, result: nfts, }; } catch (err) { return errorFxn(PaimaMiddlewareErrorCode.INVALID_RESPONSE_FROM_BACKEND, err); } } export const queryEndpoints = { getUserStats, getLobbyRaw, getLobbyState, getLobbySearch, getRoundExecutionState, getOpenLobbies, getUserLobbiesMatches, getNewLobbies, getRoundExecutor, getMatchExecutor, getNftsForWallet, };
import React, { useState } from "react"; import { Link } from "react-router-dom"; import { useColor } from "../../Global/globalState"; import Logo from "../../img/logo2.png"; import { About, Contact, Index, MenuContainer, Portifolio, MainContainer, Social, MainContainerMobile, MainContainerMobileOut } from "./HeaderStyled"; import DensityMediumIcon from "@mui/icons-material/DensityMedium"; import ClearIcon from "@mui/icons-material/Clear"; function Header() { const { color, setColor } = useColor(); const [isOpenMobile, setIsOpenMobile] = useState(false); const onSelector = (id) => { switch (id) { case "index": setColor({ home: "#fff", portfolio: "#E91472", about: "#2291EB", contact: "#A72D84", social: "#01B9E6", }); break; case "portfolio": setColor({ home: "#3EEBE7", portfolio: "#fff", about: "#2291EB", contact: "#A72D84", social: "#01B9E6", }); break; case "about": setColor({ home: "#3EEBE7", portfolio: "#E91472", about: "#fff", contact: "#A72D84", social: "#01B9E6", }); break; case "contact": setColor({ home: "#3EEBE7", portfolio: "#E91472", about: "#2291EB", contact: "#fff", social: "#01B9E6", }); break; case "social": setColor({ home: "#3EEBE7", portfolio: "#E91472", about: "#2291EB", contact: "#A72D84", social: "#fff", }); break; default: break; } }; const mobileMenu = () => { setIsOpenMobile(!isOpenMobile); }; return ( <> <MainContainer> <img src={Logo} alt="logotipo" /> <MenuContainer> <Index color={`${color.home}`}> <Link to="/" onClick={() => onSelector("index")}> HOME </Link> </Index> <Portifolio color={`${color.portfolio}`}> <Link to="/portifolio" onClick={() => onSelector("portfolio")}> PORTFOLIO </Link> </Portifolio> <About color={`${color.about}`}> <Link to="/about" onClick={() => onSelector("about")}> ABOUT </Link> </About> <Contact color={`${color.contact}`}> <Link to="/contact" onClick={() => onSelector("contact")}> CONTACT </Link> </Contact> <Social color={`${color.social}`}> <Link to="/social" onClick={() => onSelector("social")}> SOCIAL </Link> </Social> </MenuContainer> </MainContainer> <MainContainerMobileOut> <div className="container"> <DensityMediumIcon onClick={() => mobileMenu()} /> </div> </MainContainerMobileOut> {isOpenMobile && ( <MainContainerMobile> <div className="menu"> <div className="sub-menu"> <ClearIcon onClick={() => mobileMenu()} /> <Link to="/"> <p>HOME</p> </Link> <Link to="/portifolio"> <p>PORTFOLIO</p> </Link> <Link to="/about"> <p>ABOUT</p> </Link> <Link to="/contact"> <p>CONTACT</p> </Link> <Link to="/social"> <p>SOCIAL</p> </Link> </div> </div> </MainContainerMobile> )} </> ); } export default Header;
### generate graph and table output # Copyright (C) 2019 Leonardo Jost # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. source("functions/helpers.R") #generate table and graphs for cond from MRData dataset generateTableAndGraphsForCondition=function(MRData,conditionString,degreeGraphs=TRUE,timeGraphs=TRUE,legendTitle="cond",lineTypes=FALSE){ #calculate means by angle and interesting condition (important for plotting accuracy) #careful with outliers library(plyr) #averages for each participant and condition MRDataMeansByIDDegcond=ddply(MRData, .(ID,deg,cond), summarize, reactionTime=weighted.mean(reactionTime,typeOutlier=="hit"), hits=sum(typeOutlier=="hit"), misses=sum(typeOutlier=="incorrect"), acc=hits/(hits+misses), outliers=sum(outlier)) #average and sd over all participants MRDataMeansByDegcond=ddply(MRDataMeansByIDDegcond, .(deg,cond), summarize, reactionTimeSd=sd(reactionTime,na.rm=T), reactionTime=mean(reactionTime,na.rm=T), accSd=sd(acc), acc=mean(acc)) #format digits MRDataMeansByDegcond=format(MRDataMeansByDegcond, digits=4) #write table write.table(MRDataMeansByDegcond,file=paste("output\\MRDataMeansByDeg",conditionString,".csv",sep=""),sep=";", col.names=NA) #generate plots if (degreeGraphs) { #all data generateGraphs(MRData,paste("MR/allData/",conditionString,sep=""),legendTitle) #average by participants generateGraphs(MRDataMeansByIDDegcond,paste("MR/meanData/",conditionString,sep=""),legendTitle) #accuracy is always only for averages generateAccGraphs(MRDataMeansByIDDegcond,paste("MR/accData/",conditionString,sep=""),legendTitle) } if (timeGraphs) { #plot line graphs for changes over time generateLineGraphsByTime(MRData[which(MRData$typeOutlier=="hit"),],paste("MR/Timed/",conditionString,sep=""),legendTitle,lineTypes) } } #generate reaction time graphs generateGraphs=function(dataset,title,legendTitle="cond") { library(ggplot2) #plot data as line graph (mean Data by degree and condition) ggplot(dataset,aes(y=reactionTime,x=deg,group=deg,fill=cond, color=cond, linetype=cond, shape=cond)) + stat_summary(na.rm=TRUE, fun.y=mean, geom="line", aes(group=cond,color=cond)) + stat_summary(na.rm=TRUE, fun.y=mean, geom="point", size=2,aes(group=cond,color=cond)) + stat_summary(fun.data=mean_cl_normal,geom="errorbar", width=0.2,aes(group=cond,color=cond)) + scale_x_continuous(breaks=c(0:4)*45)+ labs(x="degrees(°)",y="Reaction Time(ms)",color=legendTitle,fill=legendTitle,linetype=legendTitle,shape=legendTitle) + theme_bw() + theme(legend.position = "bottom") ggsave(paste("figs/",title,"LinePlotByCondDegree.png",sep="")) } #generate lins graphs by time generateLineGraphsByTime=function(dataset,title,legendTitle="cond",lineTypes=FALSE) { if(lineTypes){ condForLineTypes=dataset$condForLineTypes } else { condForLineTypes=dataset$cond } library(ggplot2) #plot data as line graph (mean Data by degree and condition) ggplot(dataset,aes(y=reactionTime,x=endTime, color=condForLineTypes, linetype=condForLineTypes)) + geom_smooth(aes(group=cond,fill=condForLineTypes)) + labs(x="time(min)",y="Reaction Time(ms)",color=legendTitle,linetype=legendTitle,fill=legendTitle) + theme_bw() +theme(legend.position = "bottom") ggsave(paste("figs/",title,"LinePlotByCondTime.png",sep="")) } #generate graphs for accuracy generateAccGraphs=function(dataset,title,legendTitle="cond") { library(ggplot2) #plot data as line graph (mean Data by degree and condition) ggplot(dataset,aes(y=acc,x=deg,group=deg,fill=cond, color=cond, linetype=cond, shape=cond)) + stat_summary(na.rm=TRUE, fun.y=mean, geom="line", aes(group=cond,color=cond)) + stat_summary(na.rm=TRUE, fun.y=mean, geom="point", size=2,aes(group=cond,color=cond)) + stat_summary(fun.data=mean_cl_normal,geom="errorbar", width=0.2,aes(group=cond,color=cond)) + scale_x_continuous(breaks=c(0:4)*45)+ labs(x="degrees(°)",y="Proportion of correct answers",color=legendTitle,fill=legendTitle,linetype=legendTitle, shape=legendTitle) + theme_bw() + theme(legend.position = "bottom") ggsave(paste("figs/",title,"LinePlotByCondDegree.png",sep="")) } #calculate means and mode for questionnaire data and save to csv calculateMeansQuestionnaire=function(verbose,questionnaireData,questionnaireOutFile,handednessGraphFile){ #calculate means and modes by gender and save to csv questionnaireDataMeansByGender=data.frame(lapply(questionnaireData[which(questionnaireData$Gender==levels(as.factor(questionnaireData$Gender))[1]),],meanMode),stringsAsFactors = FALSE) for (genderNumber in 1:length(levels(as.factor(questionnaireData$Gender)))) questionnaireDataMeansByGender[genderNumber,]=lapply(questionnaireData[which(questionnaireData$Gender==levels(as.factor(questionnaireData$Gender))[genderNumber]),],meanMode) questionnaireDataMeansByGender$ID=levels(as.factor(questionnaireData$Gender)) #means overall questionnaireDataMeans=data.frame(lapply(questionnaireData,meanMode),stringsAsFactors = FALSE) #save to csv if (questionnaireOutFile!="") { if(verbose>1){ print(paste("Writing mean and mode data for questionnaires (by gender) to file",paste(questionnaireOutFile,"MeansByGender.csv", sep=""))) print(paste("Writing mean and mode data for questionnaires to file",paste(questionnaireOutFile,"Means.csv", sep=""))) } write.table(questionnaireDataMeansByGender,file=paste(questionnaireOutFile,"MeansByGender.csv", sep=""),sep=";", col.names=NA) write.table(questionnaireDataMeans,file=paste(questionnaireOutFile,"Means.csv", sep=""),sep=";", col.names=NA) #write.table(questionnaireData,file=paste(questionnaireOutFile,".csv", sep=""),sep=";", col.names=NA) } if (handednessGraphFile!="") { if(verbose>1){ print(paste("Writing handedness graph (by gender) to file",handednessGraphFile)) } #plot handedness library(ggplot2) if(length(levels(as.factor(questionnaireData$Gender)))>1) ggplot(questionnaireData,aes(hand)) + geom_histogram(binwidth=0.5,aes(fill=Gender)) +xlab("Handedness") + ylab("Count") + theme_bw() else ggplot(questionnaireData,aes(hand)) + geom_histogram(binwidth=0.5) +xlab("Handedness") + ylab("Count") + theme_bw() ggsave(handednessGraphFile) } } #### other graphs (mostly boxplots) #accuracy graphs generateAccGraphsOld=function(dataset,title) { library(ggplot2) #plot data (all Data by degree and condition, grouped by condition) ggplot(dataset,aes(y=acc,x=deg,group=deg,fill=cond)) + stat_boxplot(na.rm=TRUE, position=position_dodge(2),geom = "errorbar") + geom_boxplot(na.rm=TRUE, position=position_dodge(2)) +theme_bw() + facet_wrap(~cond) + stat_summary(na.rm=TRUE, fun.y=mean, geom="point", shape=20, size=2, color="black", fill="black") + labs(x="degrees(°)",y="accuracy",fill="condition") ggsave(paste("figs/",title,"PlotByDegreeConditionAxis.png",sep="")) #plot data (mean Data by degree and condition, grouped by degrees) ggplot(dataset,aes(y=acc,x=cond,group=cond,fill=cond)) + stat_boxplot(na.rm=TRUE, position=position_dodge(2),geom = "errorbar") + geom_boxplot(na.rm=TRUE, position=position_dodge(2)) +theme_bw() + facet_wrap(~deg) + stat_summary(na.rm=TRUE, fun.y=mean, geom="point", shape=20, size=2, color="black", fill="black") + labs(x="condition",y="accuracy") + guides(fill=FALSE) ggsave(paste("figs/",title,"PlotByDegreeCondition.png",sep="")) } #generate reaction time graphs generateRTGraphsOld=function(dataset,title,outliers=TRUE) { library(ggplot2) #plot data (all Data by degree) ggplot(dataset,aes(y=reactionTime,x=deg,group=deg)) + stat_boxplot(na.rm=TRUE, position=position_dodge(2),geom = "errorbar") + geom_boxplot(na.rm=TRUE, position=position_dodge(2)) +theme_bw() + labs(x="degrees(°)",y="Reaction Time(ms)") ggsave(paste("figs/",title,"PlotByDegree.png",sep="")) if(outliers) { library(plyr) dataset=ddply(dataset, .(deg), mutate, Q1=quantile(reactionTime, 1/4,na.rm=T), Q3=quantile(reactionTime, 3/4,na.rm=T), IQR=Q3-Q1, upper.limit=Q3+1.5*IQR, lower.limit=Q1-1.5*IQR) #plot data (all Data by degree with means and 3*sd) ggplot(dataset,aes(y=reactionTime,x=deg,group=deg)) + stat_boxplot(na.rm=TRUE, position=position_dodge(2),geom = "errorbar") + geom_boxplot(na.rm=TRUE, position=position_dodge(2)) +theme_bw() + stat_summary(na.rm=TRUE, fun.y=mean, geom="point", shape=20, size=2, color="black", fill="black") + stat_summary(fun.data = meanSd3, geom = "pointrange", position = position_dodge(1), fill="red", color="red") + labs(x="degrees(°)",y="Reaction Time(ms)") ggsave(paste("figs/",title,"PlotByDegreeWithMeanSd.png",sep="")) #plot data (all Data by degree with Outlier coloring) ggplot(dataset,aes(y=reactionTime,x=deg,group=deg)) + stat_boxplot(na.rm=TRUE, position=position_dodge(2),geom = "errorbar") + geom_boxplot(na.rm=TRUE, position=position_dodge(2)) +theme_bw() + labs(x="degrees(°)",y="Reaction Time(ms)") + stat_summary(na.rm=TRUE, fun.y=mean, geom="point", shape=20, size=2, color="black", fill="black") + geom_point(data=dataset[dataset$reactionTime > dataset$upper.limit | dataset$reactionTime < dataset$lower.limit,], aes(col=typeOutlier)) ggsave(paste("figs/",title,"PlotByDegreeOutlierColor.png",sep="")) #plot data (all Data by degree without outliers) ggplot(dataset[which(!dataset$outlier),],aes(y=reactionTime,x=deg,group=deg)) + stat_boxplot(na.rm=TRUE, position=position_dodge(2),geom = "errorbar") + geom_boxplot(na.rm=TRUE, position=position_dodge(2)) +theme_bw() + labs(x="degrees(°)",y="Reaction Time(ms)") + stat_summary(na.rm=TRUE, fun.y=mean, geom="point", shape=20, size=2, color="black", fill="black") ggsave(paste("figs/",title,"PlotByDegreeNoOutlier.png",sep="")) } #plot data (all Data by degree and condition, grouped by condition) ggplot(dataset,aes(y=reactionTime,x=deg,group=deg,fill=cond)) + stat_boxplot(na.rm=TRUE, position=position_dodge(2),geom = "errorbar") + geom_boxplot(na.rm=TRUE, position=position_dodge(2)) +theme_bw() + facet_wrap(~cond) + stat_summary(na.rm=TRUE, fun.y=mean, geom="point", shape=20, size=2, color="black", fill="black") + labs(x="degrees(°)",y="Reaction Time(ms)",fill="condition") ggsave(paste("figs/",title,"PlotByConditionDegree.png",sep="")) #plot data (mean Data by degree and condition, grouped by degrees) ggplot(dataset,aes(y=reactionTime,x=cond,group=cond,fill=cond)) + stat_boxplot(na.rm=TRUE, position=position_dodge(2),geom = "errorbar") + geom_boxplot(na.rm=TRUE, position=position_dodge(2)) +theme_bw() + facet_wrap(~deg) + stat_summary(na.rm=TRUE, fun.y=mean, geom="point", shape=20, size=2, color="black", fill="black") + labs(x="condition",y="Reaction Time(ms)") + guides(fill=FALSE) ggsave(paste("figs/",title,"PlotByDegreeCondition.png",sep="")) }
import nnfs from nnfs.datasets import spiral_data import numpy as np import matplotlib.pyplot as plt nnfs.init() class Layer_Dense: def __init__(self, n_inputs, n_neurons): #Initialize weights and biases # O tamanho das dimensões da nossa matriz de pesos será igual a (n_inputs, n_neurons) # onde a quantidade de linha é igual a quantidade de inputs e a quantidade de colunas é igual a quantidade # de neuronios # Os valores dos pesos serão iniciados de forma aleatoria # Ao invés de fazer a transposição quando for fazer o forward eu ja inicializo os pesos para ficar da forma # transposta # Forma transposta (n_inputs, n_neurons) # Não transposta (n_neurons, n_inputs) self.weights = 0.01 * np.random.randn(n_inputs, n_neurons) #Biases é um vetor de 1 linha e n colunas, sendo n a quantidade de neuronios na minha camada atual #E serão iniciados com 0 self.biases = np.zeros((1, n_neurons)) # Forward pass def forward(self, inputs): # Método responsável por fazer a soma dos produtos dos inputs com os pesos e biases self.output = np.dot(inputs, self.weights) + self.biases # Camada exemplo com dados inventados # inputs = np.array([1, 2, 3, 4]) # (1, 4) # layer_dense = Layer_Dense(len(inputs), 3) #(4, 3) # layer_dense.forward(inputs=inputs) # print(layer_dense.output) #(1, 3) # Produto de matrizes # Para que seja possível o tamanho da segunda dimensão da primeira matriz, tem que ser igual ao tamanho da primeira # dimensão da segunda matriz # A matriz resultante vai ter dimensões onde a primeira dimensão é igual a primeira dimensão da primeira matriz, # a segunda dimensão é igual a segunda dimensão da segunda matriz X, y = spiral_data(samples=100, classes=3) #Cada um dos nossos samples consiste em um vetor com dois valores, sendo coordenadas X e Y #Então nossa camada de neuronios terão pesos (2, 3), sendo 3 a quantidade de neuronios layer_dense = Layer_Dense(2, 3) # print(layer_dense.weights) layer_dense.forward(X) print(layer_dense.output[:5])
import { KeyLike, importX509 } from 'jose'; import { pkijs } from '#runtime/pkijs.js'; import { decodeBase64 } from '#runtime/base64.js'; import { X509InvalidCertificateChain, X509NoMatchingCertificate } from '../util/errors.js'; import { certToPEM, pemToCert } from '../util/cert.js'; import { headers, algs } from '../headers.js'; import { WithHeaders } from './WithHeaders.js'; export class SignatureBase extends WithHeaders { constructor( protectedHeaders: Uint8Array | Map<number, unknown>, unprotectedHeaders: Map<number, unknown>, public readonly signature: Uint8Array, ) { super(protectedHeaders, unprotectedHeaders); } /** This parameter is used to indicate the algorithm used for the security processing. This parameter MUST be authenticated where the ability to do so exists. This support is provided by AEAD algorithms or construction (COSE_Sign, COSE_Sign0, COSE_Mac, and COSE_Mac0). This authentication can be done either by placing the header in the protected header bucket or as part of the externally supplied data. The value is taken from the "COSE Algorithms" registry (see Section 16.4). */ public get alg(): number | undefined { return this.protectedHeaders.get(headers.alg) as number || this.unprotectedHeaders.get(headers.alg) as number; } public get algName(): string | undefined { return this.alg ? algs.get(this.alg)?.name : undefined; } /** This parameter identifies one piece of data that can be used as input to find the needed cryptographic key. The value of this parameter can be matched against the 'kid' member in a COSE_Key structure. Other methods of key distribution can define an equivalent field to be matched. Applications MUST NOT assume that 'kid' values are unique. There may be more than one key with the same 'kid' value, so all of the keys associated with this 'kid' may need to be checked. The internal structure of 'kid' values is not defined and cannot be relied on by applications. Key identifier values are hints about which key to use. This is not a security-critical field. For this reason, it can be placed in the unprotected headers bucket. */ public get kid(): Uint8Array | undefined { return this.protectedHeaders.get(headers.kid) as Uint8Array || this.unprotectedHeaders.get(headers.kid) as Uint8Array; } public get x5bag(): Uint8Array[] | undefined { const x5bag = this.protectedHeaders.get(headers.x5bag) || this.unprotectedHeaders.get(headers.x5bag); if (!x5bag) { return } return Array.isArray(x5bag) ? x5bag : [x5bag]; } public get x5chain(): Uint8Array[] | undefined { const x5chain = this.protectedHeaders.get(headers.x5chain) || this.unprotectedHeaders.get(headers.x5chain); if (!x5chain) { return } return Array.isArray(x5chain) ? x5chain : [x5chain]; } /** * Verify the x5chain content of a message with a given list of certificate authorities. * Returns the publicKey for message validation and * the raw x5chain certificate for further processing. * * @param caRoots the list of certificate authorities in pem format * @returns {Promise<{ publicKey: KeyLike, raw: Uint8Array }> */ async verifyX509Chain( caRoots: string[], ): Promise<{ publicKey: KeyLike, raw: Uint8Array }> { const { x5chain } = this; if (!x5chain || x5chain.length === 0) { throw new X509NoMatchingCertificate(); } const chainEngine = new pkijs.CertificateChainValidationEngine({ certs: x5chain.map((c) => pkijs.Certificate.fromBER(c)), trustedCerts: caRoots.map((c) => pkijs.Certificate.fromBER(decodeBase64(pemToCert(c)))), }); const chain = await chainEngine.verify(); if (!chain.result) { throw new X509InvalidCertificateChain(chain.resultMessage); } const x509Cert = certToPEM(x5chain[0]); const publicKey = await importX509( x509Cert, this.algName as string ); return { publicKey, raw: x5chain[0] }; } }
import React, {Component} from 'react'; import Layout from '../../components/Layout'; import Campaign from '../../ethereum/campaign'; import {Card, Grid, Button} from 'semantic-ui-react'; import web3 from '../../ethereum/web3'; import ContributeForm from '../../components/ContributeForm'; import {Link} from '../../routes'; class CampaignShow extends Component{ static async getInitialProps(props){ const campaign = Campaign(props.query.address); const summary = await campaign.methods.getSummary().call(); return{ address: props.query.address, minimumContribution: summary[0], balance: summary[1], requestsCount: summary[2], approversCount: summary[3], manager: summary[4] }; } renderCards(){ //deconstructing const { balance, manager, minimumContribution, requestsCount, approversCount } = this.props; const items = [ { header: manager, meta:'Address of manager', description: 'The manager created this campaign and can create requests to withdraw money.', style: {overflowWrap: 'break-word'} }, { header: minimumContribution, meta: 'Minimum Contribution (wei)', description: 'You must contribute at least this much wei to become an approver.' }, { header: requestsCount, meta: 'Number of Requests', description: 'A request tries to withdraw money from the contract. Requests must be approved by approvers.' }, { header: approversCount, meta: 'Number of Approvers', description: "A number of people who have already contributed to this campaign." }, { header: web3.utils.fromWei(balance, 'ether'), meta: 'Campaign Balance(ether)', description: "The balance is how much money this campaign has left to spend." } ]; return <Card.Group items={items}/> } render(){ return( <Layout> <h3> Campaign Show</h3> <Grid> <Grid.Row> <Grid.Column width={10}> {this.renderCards()} </Grid.Column> <Grid.Column width={6}> <ContributeForm address={this.props.address} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column> <Link route={`/campaigns/${this.props.address}/requests`}> <a> <Button primary>View Request</Button> </a> </Link> </Grid.Column> </Grid.Row> </Grid> </Layout> ); } } export default CampaignShow;
import React,{useEffect} from 'react'; import './App.css'; import AppBar from './AppBar'; import Dashboard from './DashBoard'; import LabelBottomNavigation from './BottomNavigation'; const initialState = true const reducer = (state, action) => { switch(action) { case 'Truth': return false case 'False': return true default: return state } } export const context = React.createContext() function App() { const [theme, dispatch] = React.useReducer(reducer,initialState) useEffect(() => { document.title = "Naveen - DevOps Engineer" },[]) return ( <React.Fragment> <context.Provider value={{themeState: theme, themeDispatch: dispatch}}> <div style={{minWidth:"344px",backgroundColor:"#F9F9F9"}}> <AppBar /> <Dashboard /> <LabelBottomNavigation /> </div> </context.Provider> </React.Fragment> ); } export default App;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <h2>JavaScript Prototype原型对象</h2> <p id="demo"></p> <p id = "nationality"><p> <p id = "name"><p> <script> function Person(first,last,age,eye){ this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } <!--在一个已存在的对象构造器中是不能添加新的属性的--> Person.nationality = "English"; var myFather = new Person("John","Doe",50,"blue"); var myMother = new Person("Sally","Rally",48,"gree"); document.getElementById("demo").innerHTML = "我的父亲年龄是" + myFather.age + "。 我的母亲年龄是" + myMother.age; document.getElementById("demo").innerHTML = "我父亲的国籍是" + myFather.nationality; //获得是null值 <!-- 可用通过prototype添加新的属性--> Person.prototype.nationality = "English" document.getElementById("nationality").innerHTML = "我父亲的国籍是" + myFather.nationality; <!-- 当然也可以通过prototype添加新的方法--> Person.prototype.name = function(){ return this.firstName + " " + this.lastName } document.getElementById("name").innerHTML = "我对父亲是 " + myFather.name(); </script> </body> </html>
// // edrav2.libcloud project // // Author: Denis Bogdanov (16.03.2019) // Reviewer: // /// /// @file Cloud service class declaration /// /// @addtogroup cloud Cloud communication library /// @{ #pragma once #include <objects.h> #include <net.hpp> namespace cmd { namespace cloud { /// /// The class provides interaction with EDR backend portal. /// class CloudService : public ObjectBase<CLSID_CloudService>, public ICommandProcessor, public IService, public IInformationProvider, public ICommand { private: std::recursive_mutex m_mtxData; std::string m_sPolicyCatalogPath; std::string m_sCurrVersion; ThreadPool m_threadPool{ "CloudService::CommunitctionPool" }; ThreadPool::TimerContextPtr m_pTimerCtx; Time m_lastHertbeatTime = 0; net::HttpClient m_httpClient; uint64_t m_nAvgDuration = 0; Size m_nHeartbeatCount = 0; Size m_nNetworkUpdateMask = 0; Size m_nPeriod = 30000; // 30 second Variant m_seqLastIp4; std::wstring m_sLastActiveUser; bool m_fFirstStart = true; bool m_fFinished = false; protected: Variant callHeartbeat(); Variant doHeartbeat(); Variant getConfig(Variant vParams = Dictionary()); Variant getIdentity(Variant vParams = Dictionary()); Variant getPolicy(Variant vParams = Dictionary()); Variant getToken(Variant vParams = Dictionary()); Variant enroll(Variant vParams = Dictionary()); Variant reportEndpointInfo(bool fFull); bool checkCredentials(); void reportOffline(); void reportUninstall(bool fFailSafe); void confirmCommand(std::string_view sCommandId); void updateSettings(Variant vConfig); // // // virtual ~CloudService() override {} public: /// /// Object final construction. /// /// @param vConfig The object configuration includes the following fields: /// **field1** - ??? /// @throw error::InvalidArgument In case of invalid configuration in vConfig. /// void finalConstruct(Variant vConfig); // IService /// @copydoc IService::loadState() virtual void loadState(Variant vState) override {} /// @copydoc IService::saveState() virtual Variant saveState() override { return {}; } /// @copydoc IService::start() virtual void start() override; /// @copydoc IService::start() virtual void stop() override; /// @copydoc IService::shutdown() virtual void shutdown() override; // ICommand /// @copydoc ICommand::execute() virtual Variant execute(Variant vParam) override; /// @copydoc ICommand::getInfo() virtual std::string getDescriptionString() override { return {}; } // ICommandProcessor /// @copydoc ICommandProcessor::execute() virtual Variant execute(Variant vCommand, Variant vParams) override; // IInformationProvider /// @copydoc - IInformationProvider::getInfo() virtual Variant getInfo() override; }; } // namespace cloud } // namespace cmd /// @}
package player import ( "errors" "fmt" "os" "strconv" "strings" "github.com/LeMikaelF/2048/src/engine" "github.com/LeMikaelF/2048/src/grid" ) type Cli struct { engine *engine.Engine } func New() *Cli { return &Cli{ engine: engine.New(), } } type lostError interface { Lost() } func (c *Cli) Run() { for { fmt.Println("Current grid.") fmt.Println(prettyPrint(c.engine.Grid)) direction, err := readDirection() if err != nil { fmt.Printf("error: %v\n", err) return } fmt.Println("") err = c.engine.Next(direction) if _, ok := err.(lostError); ok { fmt.Println("******You lost the game!********") return } } } func readDirection() (engine.Direction, error) { bytes := make([]byte, 4) for { fmt.Println("Press any arrow, then Enter.") _, err := os.Stdin.Read(bytes) if err != nil { return "", errors.New("error reading from stdin") } switch fmt.Sprintf("%v", bytes) { case "[27 91 67 10]": return engine.Right, nil case "[27 91 68 10]": return engine.Left, nil case "[27 91 66 10]": return engine.Down, nil case "[27 91 65 10]": return engine.Up, nil default: fmt.Printf("unknown input %v, try again.\n", bytes) } } } func prettyPrint(grid grid.Grid) string { var sb strings.Builder for iRow, row := range grid { for _, val := range row { sb.WriteString(strconv.Itoa(val)) sb.WriteString(" ") } if iRow != len(grid)-1 { sb.WriteString("\n") } } return sb.String() }
import React from 'react'; import { Switch, Route, useRouteMatch, Link } from "react-router-dom"; import DefaultNavbar from "../components/Navbar"; import { Container } from '../layouts/Container'; import { Column, Row } from '../layouts/Grid'; import BrowserImplementation, { browserPluginData } from '../plugins/Browser'; import ClipboardImplementation, { clipboardPluginData } from '../plugins/Clipboard'; import DeviceImplementation, { devicePluginData } from '../plugins/Device'; import StatusBarImplementation, { statusBarPluginData } from '../plugins/StatusBar'; const allPlugins = [ browserPluginData, clipboardPluginData, devicePluginData, statusBarPluginData, ]; const PluginsPage = () => { // Valores y estados const { path } = useRouteMatch(); return ( <Switch> <Route path={`${path}/${browserPluginData.title}`}> <BrowserImplementation /> </Route> <Route path={`${path}/${clipboardPluginData.title}`}> <ClipboardImplementation/> </Route> <Route path={`${path}/${devicePluginData.title}`}> <DeviceImplementation/> </Route> <Route path={`${path}/${statusBarPluginData.title}`}> <StatusBarImplementation/> </Route> <Route exact path={path}> <DefaultNavbar /> <Container className="pt-3 pb-3"> <header> <h1>Plugins</h1> <p>Pruebas con plugins disponibles en Capacitor</p> </header> <main> <h2 className="mt-3">Official</h2> <Row> {allPlugins.filter(i => i.enabled === true).map(i => <Column key={i.title} xl="3" lg="4" md="6" className="p-1" > <div className="card" style={{height: '100%'}}> <div className="card-body"> <h3 className="card-title">{i.title}</h3> <p className="card-text">{i.description}</p> <Link to={`${path}/${i.title}`}>Ver ejemplos</Link> </div> </div> </Column>)} </Row> </main> </Container> </Route> </Switch> ) } export default PluginsPage;
-- CREATE THE TABLES DROP TABLE Movies; DROP TABLE Writers; DROP TABLE Directors; CREATE TABLE Directors ( DirectorID INT PRIMARY KEY NOT NULL, DirectorCNP INT UNIQUE, DirectorNumberOfDirections INT ); CREATE TABLE Writers ( WriterID INT PRIMARY KEY NOT NULL, WriterNumberOfWritings INT ); CREATE TABLE Movies ( MovieID INT PRIMARY KEY, DirectorID INT FOREIGN KEY REFERENCES Directors(DirectorID), WriterID INT FOREIGN KEY REFERENCES Writers(WriterID), MovieTitle NVARCHAR(50) ); -- GENERATE RANDOM DATA FOR THE TABLES GO CREATE OR ALTER PROCEDURE insertIntoDirectors (@rows INT) AS BEGIN DECLARE @aux INT SET @aux = @rows + 1 WHILE @rows > 0 BEGIN INSERT INTO Directors VALUES(@rows, @aux, @aux % 345) SET @rows = @rows - 1 SET @aux = @aux + 1 END END GO CREATE OR ALTER PROCEDURE insertIntoWriters (@rows INT) AS BEGIN DECLARE @aux INT SET @aux = @rows + 1 WHILE @rows > 0 BEGIN INSERT INTO Writers VALUES(@rows, @aux % 345) SET @rows = @rows - 1 SET @aux = @aux + 1 END END GO CREATE OR ALTER PROCEDURE insertIntoMovies(@rows INT) AS BEGIN DECLARE @directorID INT DECLARE @writerID INT WHILE @rows > 0 BEGIN SET @directorID = (SELECT TOP 1 DirectorID FROM Directors ORDER BY NEWID()) SET @writerID = (SELECT TOP 1 WriterID FROM Writers ORDER BY NEWID()) INSERT INTO Movies VALUES(@rows, @directorID, @writerID, 'movie' + CAST(@directorID + @writerID AS VARCHAR(10))) SET @rows = @rows - 1 END END -- INSERT DATA EXEC insertIntoDirectors 5000; EXEC insertIntoWriters 5000; EXEC insertIntoMovies 5000; SELECT * FROM Directors; SELECT * FROM Writers; SELECT * FROM Movies; /* Remarks (indexes automatically created): - clustered index for DirectorID column from Directors - unique, nonclustered index for DirectorCNP column from Directors - clustered index for WriterID column from Writers - clustered index for MovieID column from Movies */ -- a) -- cluster index scan for Directors - scan the entire table SELECT * FROM Directors; -- cluster index seek for Directors - return a specific subset of rows SELECT * FROM Directors WHERE DirectorID < 100; -- nonclustered index scan for Directors SELECT DirectorCNP FROM Directors; -- nonclustered index seek for Directors SELECT DirectorCNP FROM Directors WHERE DirectorCNP < 5500; -- key lookup - nonclustered index seek + key lookup - the data is found in a nonclustered -- index, but additional data is required SELECT DirectorCNP, DirectorNumberOfDirections FROM Directors WHERE DirectorCNP = 5100; -- b) -- Write a query on table Tb with a WHERE clause of the form WHERE b2 = value and analyze its execution plan. -- Create a nonclustered index that can speed up the query. Examine the execution plan again. SELECT * FROM Writers WHERE WriterNumberOfWritings = 100; GO IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'IX_Writers_WriterNumberOfWritings') DROP INDEX IX_Writers_WriterNumberOfWritings ON Writers GO CREATE NONCLUSTERED INDEX IX_Writers_WriterNumberOfWritings ON Writers(WriterNumberOfWritings) -- cost before creating index: 0.01618 -- cost after creating index: 0.00329 -- c) -- Create a view that joins at least 2 tables. Check whether existing indexes are helpful; -- if not, reassess existing indexes / examine the cardinality of the tables. GO CREATE OR ALTER VIEW View1 AS SELECT M.MovieID, D.DirectorID, W.WriterID FROM Movies M INNER JOIN Directors D ON D.DirectorID = M.DirectorID INNER JOIN Writers W ON W.WriterID = M.WriterID WHERE W.WriterNumberOfWritings > 200 AND D.DirectorNumberOfDirections < 150 GO SELECT * FROM View1; /* with existing indexes (automatically created ones + nonclustered index on b2 in Tb): 0.20087 when adding a nonclustered index on a3 in Ta: 0.18861 when deleting the nonclustered on a3 and b2: 0.21158 automatically created ones + nonclustered on b2 + nonclustered on a3 + nonclustered on (aid, bid) in Tc: 0.18787 */ IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'IX_Directors_DirectorNumberOfDirections') DROP INDEX IX_Directors_DirectorNumberOfDirections ON Directors CREATE NONCLUSTERED INDEX IX_Directors_DirectorNumberOfDirections ON Directors(DirectorNumberOfDirections) IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'IX_Movies_aidbid') DROP INDEX IX_Movies_aidbid ON Movies CREATE NONCLUSTERED INDEX IX_Movies_aidbid ON Movies(DirectorID, WriterID)
package com.onursir.rentACar; import com.onursir.rentACar.Core.utilites.BusinessException; import com.onursir.rentACar.Core.utilites.ProblemDetails; import org.modelmapper.ModelMapper; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; @SpringBootApplication @RestControllerAdvice //hata yakalamak için public class RentACarApplication { public static void main(String[] args) { SpringApplication.run(RentACarApplication.class, args); } @ExceptionHandler @ResponseStatus(code = HttpStatus.BAD_REQUEST) public ProblemDetails handleBusinessException(BusinessException businessException){ ProblemDetails problemDetails = new ProblemDetails(); problemDetails.setMessage(businessException.getMessage()); return problemDetails; } @Bean // model mappar IOC'de constructor'a ihtiyac duyar bu yüzden burda oluşturduk. public ModelMapper getModelMapper(){ return new ModelMapper(); } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AdminGuard } from '../guards/admin.guard'; import { AccountSettingsComponent } from './account-settings/account-settings.component'; import { AccountComponent } from './account/account.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { Graph1Component } from './graph1/graph1.component'; import { DoctorComponent } from './maintenance/doctors/doctor/doctor.component'; import { DoctorsComponent } from './maintenance/doctors/doctors.component'; import { HospitalsComponent } from './maintenance/hospitals/hospitals.component'; import { UsersComponent } from './maintenance/users/users.component'; import { ProgressComponent } from './progress/progress.component'; import { PromisesComponent } from './promises/promises.component'; import { RxjsComponent } from './rxjs/rxjs.component'; import { SearchComponent } from './search/search.component'; const childRoutes: Routes = [ { path: '', component: DashboardComponent, data: { title: 'Dashboard' } }, { path: 'progress', component: ProgressComponent, data: { title: 'Progress' }, }, { path: 'graph1', component: Graph1Component, data: { title: 'Graph' } }, { path: 'account-settings', component: AccountSettingsComponent, data: { title: 'Account Settings' }, }, { path: 'account', component: AccountComponent, data: { title: 'Account' }, }, { path: 'promises', component: PromisesComponent, data: { title: 'Promises' }, }, { path: 'rxjs', component: RxjsComponent, data: { title: 'RXJS' } }, { path: 'users', canActivate: [AdminGuard], component: UsersComponent, data: { title: 'Users Maintenance' }, }, { path: 'hospitals', component: HospitalsComponent, data: { title: 'Hospitals Maintenance' }, }, { path: 'doctors', component: DoctorsComponent, data: { title: 'Doctors Maintenance' }, }, { path: 'doctor/:id', component: DoctorComponent, data: { title: 'Doctor Maintenance' }, }, { path: 'search/:term', component: SearchComponent, data: { title: 'Searches' }, }, ]; @NgModule({ imports: [RouterModule.forChild(childRoutes)], exports: [RouterModule], }) export class ChildRoutesModule {}
#+TITLE: #+DATE: January 7, 2022 #+SINCE: <replace with next tagged release version> #+STARTUP: inlineimages nofold * 零、引言 如果不给你的emacs配置起个独特名字,那么你就没有自己的emacs配置。 起名engine-emacs是因为这些天读了一本书:「人类飞翔史」。 #+attr_html: :width 300px [[file:images/人类飞翔史封面.png]] 早先的风筝,热气球,氢气球等只能在高空中随风逐流。即使发明家制造出来螺旋状,仅靠着脚蹬手摇的人力驱动,在高空中就犹如一根竹竿搅动大海,再筋疲力尽也是徒劳无功。 直到蒸汽动力引擎在工业革命中崭露头角,飞行器才得以挣脱风的束缚,按照人的意愿首次实现定向飞行。 因此,我希望Emacs能给我带来效率,作按照我的意愿前进的动力引擎engine-emacs。 * 一、简介 首先,我没有自己的配置,用的doom-emacs,加了一丢点儿自己的使用习惯。这个engine-emacs项目(或者目录)就是doom-emacs的.doom.d目录(将本项目下载到$HOME目录下之后,更改命名为.doom.d即可)。 doom-emacs分为.emacs.d和.doom.d两大部分。其中.doom.d是用户自定义配置,我也不在.emacs.d中保存任何自定义的内容。自定义信息全部保存在.doom.d中,包括bookmark,snippets等。 在任何时刻,将.emacs.d目录全部删掉,仅保留.doom.d,然后运行M-x doom-reload,便能全须全尾的恢复。 其次,我是在windows11系统上运行的emacs,有些配置和问题是平台独有的。 最后,建议用outshine来阅读elisp的配置代码,结构清晰且赏心悦目。 #+attr_html: :width 300px [[file:images/outshine案例01.png]] * 二、目录结构 目录结构如下。其中init.el, package.el, config.el, custom.el为doom-emacs的标准配置文件,此处不再赘述。 bookmarks-windows文件保存着自定义的bookmarks,snippet目录里存着全部自定义的snippets,theme目录是自定义主题。 engine.emacs目录里的6个文件是给config.el服务的分类配置文件。 #+begin_example |-- init.el |-- packages.el |-- config.el |-- custom.el |-- bookmarks-windows |-- engine.emacs | |-- engine-org-agenda.el | |-- engine-org-babel.el | |-- engine-org-note.el | |-- iscroll.el | |-- email.el | `-- programming-aid.el |-- snippets |-- themes | `-- work-theme.el |-- images |-- readme.org #+end_example * 三、配置结构 所有的配置都写在config.el中,暂时分了九个类别。 ** 0.最关键的键位模式配置 doom模式是vim模式,我用的是vanilla emacs。于是这第一行配置最为关键。 #+begin_src emacs-lisp :tangle yes (setq evil-default-state 'emacs) #+end_src 另外也在key change log部分记录主要的变更。变更记录写在头部,比从git log中查看更加直观。 ** 1.Key and Editing 键位绑定都放在此处,光标的移动,拼写检查,搜索,拼写纠正等等 ** 2.File, Buffers, Directories 文件与目录相关内容,还包括register, bookmarks, dired, archive等等 ** 3.Display(Looks and Feel) themes, modeline, input-methods, emoj, fonts, icons等等 ** 4.Windows Management 窗口管理与Frame管理等 ** 5.Org Mode 我主要用emacs来写笔记,因此org-mode是核心。具体配置在 #+begin_src emacs-lisp :tangle yes (add-to-list 'load-path "~/.doom.d/engine.emacs") (require 'engine-org-babel) (require 'engine-org-agenda) (require 'engine-org-note) (require 'email) (require 'iscroll) #+end_src ** 6.Reading dictionaries, epub-reading 等 ** 7.Programming 包括环境配置等,另有programming-aid.el分类配置。 ** 8.Coding system 这应该在7.programming里。但在windows上,常常出现coding-system的异常报错,因此单独拿出来。 ** Red Alarms 记录配置过程中踩的雷。 * 四、收尾 以上, engine-emacs,盼着每次打开,都能有强劲动力的推背感。
/** * Created by djz on 2023/3/27. */ import React from 'react' import { useNavigate } from "react-router-dom" import { LaptopOutlined, NotificationOutlined } from '@ant-design/icons' import { Menu } from "antd" const getItem = (label, key, icon, children, theme) => { return { key, icon, children, label, theme, } } export default function LayoutBase() { // 路由跳转 let navigate = useNavigate() // 获取路由 let url = window.location.pathname let urlList = url.split('/') // 菜单默认选中 let defaultSelectedKeys = [urlList[urlList.length - 1]] // 左侧菜单 const items = [ getItem('组织管理','org',<LaptopOutlined />), getItem('项目管理','pro',<NotificationOutlined />), getItem('拖拽','drag',<NotificationOutlined />), ] const onClick = (item) => { navigate(`/sys/${item.key}`) } return ( <> <Menu onClick={onClick} mode="inline" defaultSelectedKeys={defaultSelectedKeys} style={{ height: '100%', borderRight: 0 }} items={items} /> </> ) }
import { useState } from 'react'; import { loginFields } from "../constants/FormFields"; import FormAction from "./FormAction"; import FormExtra from "./FormExtra"; import Input from "./Input"; import { validateLogin } from '../utils/ValidationSchema'; import { toast } from 'react-toastify'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; const fields = loginFields; let fieldsState = {}; fields.forEach(field => fieldsState[field.id] = ''); export default function Login() { const [loginState, setLoginState] = useState(fieldsState); const [errors, setErrors] = useState([]); const navigate = useNavigate() const handleChange = (e) => { setLoginState({ ...loginState, [e.target.id]: e.target.value }) } const handleSubmit = (e) => { e.preventDefault(); const error = validateLogin(loginState) error.then(error => { if (!error) { authenticateUser() } setErrors(error) }) } //Handle Login API Integration here const authenticateUser = async () => { try { const { token } = await (await axios.post("http://localhost:3000/user/login", loginState)).data console.log(token) toast.success("user found!") navigate("/home") } catch (e) { toast.error("user not found!") } } return ( <> {errors && <div className="bg-red-600 text-white">{errors.map(error => error.message)}</div>} <form className="mt-8 space-y-6" onSubmit={handleSubmit}> <div className="-space-y-px"> { fields.map(field => <Input key={field.id} handleChange={handleChange} value={loginState[field.id]} labelText={field.labelText} labelFor={field.labelFor} id={field.id} name={field.name} type={field.type} isRequired={field.isRequired} placeholder={field.placeholder} /> ) } </div> <FormExtra /> <FormAction handleSubmit={handleSubmit} text="Login" /> </form> </> ) }
package day06_PrimitiveTypeCastings; public class PrimitiveCastings { public static void main(String[] args) { //IMPLICIT CASTING byte a = 100; short b = a; //short b = (short)a; Smaller primitives can be directly assigned to larger primitive type. int c = b; //int c = (int)b; long d = c; //long = (long)c; float e = d; double f = e; //EXPLICIT CASTING:Larger primitives can NOT be directly assigned to smaller primitive types (need to be cast manually). int x = 55; short y = (short)x; System.out.println(x + " : " + y + "\n\n"); long j = 1000000; short k = (short)j; System.out.println(j + " : " + k + "\n\n"); double l = 2.5; float m = (float)l; System.out.println(l + " : " + m + "\n\n"); double n = 10.8; int s = (int)n; // The result is 10. System.out.println(n + " : " + s + "\n\n"); //Shortcut to fix compile error about explicit casting: Click alt and hit the enter and choose the first (default) solution. double d1 = 20.5; short s1 = (short) d1; } }
import tkinter as tk from tkinter import filedialog from tkinter import ttk from pygame import mixer import os class MusicPlayer: def __init__(self, master): self.master = master self.master.title("Music Player") self.master.geometry("400x300") mixer.init() self.current_song_index = 0 self.playlist = [] self.play_button = tk.Button(master, text="Play", command=self.play_music) self.play_button.pack(pady=10) self.pause_button = tk.Button(master, text="Pause", command=self.pause_music) self.pause_button.pack(pady=10) self.stop_button = tk.Button(master, text="Stop", command=self.stop_music) self.stop_button.pack(pady=10) self.back_button = tk.Button(master, text="Back", command=self.play_previous) self.back_button.pack(side=tk.LEFT, padx=10) self.forward_button = tk.Button(master, text="Forward", command=self.play_next) self.forward_button.pack(side=tk.RIGHT, padx=10) self.choose_button = tk.Button(master, text="Choose Song", command=self.choose_file) self.choose_button.pack(pady=10) self.song_label = tk.Label(master, text="") self.song_label.pack(pady=10) # Volume Slider self.volume_label = tk.Label(master, text="Volume:") self.volume_label.pack() self.volume_slider = ttk.Scale(master, from_=0, to=1, orient=tk.HORIZONTAL, command=self.set_volume) self.volume_slider.set(0.5) self.volume_slider.pack(pady=10) # Position Slider self.position_label = tk.Label(master, text="Position:") self.position_label.pack() self.position_slider = ttk.Scale(master, from_=0, to=100, orient=tk.HORIZONTAL, command=self.set_position) self.position_slider.set(0) self.position_slider.pack(pady=10) def play_music(self): if self.playlist: mixer.music.load(self.playlist[self.current_song_index]) mixer.music.play() self.song_label.config(text=f"Now Playing: {os.path.basename(self.playlist[self.current_song_index])}") def pause_music(self): mixer.music.pause() self.song_label.config(text="Music Paused") def stop_music(self): mixer.music.stop() self.song_label.config(text="Music Stopped") def play_previous(self): if self.playlist: self.current_song_index = (self.current_song_index - 1) % len(self.playlist) self.play_music() def play_next(self): if self.playlist: self.current_song_index = (self.current_song_index + 1) % len(self.playlist) self.play_music() def choose_file(self): file = filedialog.askopenfilename(initialdir="/", title="Select File", filetypes=(("MP3 files", "*.mp3"), ("all files", "*.*"))) if file: self.playlist.append(file) self.song_label.config(text=f"Added: {os.path.basename(file)}") def set_volume(self, val): mixer.music.set_volume(float(val)) def set_position(self, val): if self.playlist: total_length = mixer.Sound(self.playlist[self.current_song_index]).get_length() position = (float(val) / 100) * total_length mixer.music.set_pos(position) if __name__ == "__main__": root = tk.Tk() app = MusicPlayer(root) root.mainloop()
import React from 'react'; import { Text, View, StyleSheet } from 'react-native'; import { spacing, fontSizes } from '../utils/sizes'; import { colors } from '../utils/colors'; const minutesToMillis = (min) => min * 1000 * 60; const formatTime = (time) => (time < 10 ? `0${time}` : time); export const Countdown = ({ minutes, isPaused, onProgress, onEnd, }) => { const interval = React.useRef(null); const [millis, setMillis] = React.useState(minutesToMillis(minutes)); const countDown = () => { setMillis((time) => { if (time === 0) { // do more stuff here clearInterval(interval.current); onEnd(); return time; } const timeLeft = time - 1000; // report the progress onProgress((timeLeft / minutesToMillis(minutes))); return timeLeft; }); }; React.useEffect(() => { setMillis(minutesToMillis(minutes)); }, [minutes]); React.useEffect(() => { if (isPaused) { if (interval.current) clearInterval(interval.current); return; } interval.current = setInterval(countDown, 1000); return () => clearInterval(interval); }, [isPaused]); const minute = Math.floor(millis / 1000 / 60) % 60; const seconds = Math.floor(millis / 1000) % 60; return ( <Text style={styles.text}> {formatTime(minute)}: {formatTime(seconds)} </Text> ); }; const styles = StyleSheet.create({ text: { backgroundColor: 'rgba(94, 132, 226, 0.3)', color: colors.white, fontSize: fontSizes.xxxxl, fontWeight: 'bold', padding: spacing.lg, }, });
using FLG.Cs.IO; using FLG.Cs.Logger; using System; namespace FLG.Cs.Serialization { public class SerializerManager : ISerializerManager { internal const uint VERSION = 0; private Serializer _writeSerializer; private readonly Serializer _binSerializer; private readonly Serializer _jsonSerializer; private readonly Serializer _xmlSerializer; private readonly string _saveDir; internal string SaveDir { get => _saveDir; } private readonly List<ISaveFile> _saveFiles; public IEnumerable<ISaveFile> GetSaveFiles() => _saveFiles; internal void AddSaveFile(ISaveFile saveFile) { _saveFiles.Add(saveFile); } private readonly List<ISerializable> _serializableItems; public void AddSerializable(ISerializable serializable) { _serializableItems.Add(serializable); } public IEnumerable<ISerializable> GetSerializableItems() => _serializableItems; private SerializerManager(ESerializerType t, string saveDir) { _binSerializer = new BinarySerializer(this); _jsonSerializer = new JsonSerializer(this); _xmlSerializer = new XmlSerializer(this); _writeSerializer = t switch { ESerializerType.BIN => _binSerializer, ESerializerType.JSON => _jsonSerializer, ESerializerType.XML => _xmlSerializer, _ => _binSerializer, }; _saveDir = saveDir; _saveFiles = new(); _serializableItems = new(); DiscoverSaveFile(); } public static SerializerManager CreateBinarySerializer(string saveDir) => new(ESerializerType.BIN, saveDir); public static SerializerManager CreateXmlSerializer(string saveDir) => new(ESerializerType.JSON, saveDir); public static SerializerManager CreateJsonSerializer(string saveDir) => new(ESerializerType.XML, saveDir); public void SetSerializerBinary() { _writeSerializer = _binSerializer; } public void SetSerializerJson() { _writeSerializer = _jsonSerializer; } public void SetSerializerXml() { _writeSerializer = _xmlSerializer; } private void DiscoverSaveFile() { if (!Directory.Exists(_saveDir)) { System.IO.Directory.CreateDirectory(_saveDir); return; } string[] exts = { BinarySerializer.SAVE_EXTENSION, JsonSerializer.SAVE_EXTENSION, XmlSerializer.SAVE_EXTENSION }; List<string> saveFiles = IOUtils.GetFilePathsByExtensions(_saveDir, exts); foreach (var file in saveFiles) { Serializer serializer; ESerializerType serializerType; switch (Path.GetExtension(file)) { case BinarySerializer.SAVE_EXTENSION: serializer = _binSerializer; serializerType = ESerializerType.BIN; break; case JsonSerializer.SAVE_EXTENSION: serializer = _jsonSerializer; serializerType = ESerializerType.JSON; break; case XmlSerializer.SAVE_EXTENSION: serializer = _xmlSerializer; serializerType = ESerializerType.XML; break; default: LogManager.Instance.Warn($"Wrong extension for save file at \"{file}\""); return; } var header = serializer.DeserializeHeaderOnly(file); var version = header.version; if (version != VERSION) { LogManager.Instance.Warn($"Save file version does not correspond. Got {version}, expected {VERSION}). For file at \"{file}\""); //? Upgrade/Convert } else { ISaveFile saveFile = new SaveFile(header.name, file, serializerType, header.dateCreated, header.dateLastModified); _saveFiles.Add(saveFile); } } } public void Serialize(string filename) { _writeSerializer.Serialize(filename); } public void Serialize(ISaveFile saveFile) { _writeSerializer.Serialize(saveFile); } public void Deserialize(ISaveFile saveFile) { ESerializerType t = saveFile.GetSerializerType(); switch (t) { case ESerializerType.BIN: _binSerializer.Deserialize(saveFile); break; case ESerializerType.JSON: _jsonSerializer.Deserialize(saveFile); break; case ESerializerType.XML: _xmlSerializer.Deserialize(saveFile); break; default: LogManager.Instance.Warn($"Could not deserialize save file {saveFile.GetName()}, unrecognized type {t}"); break; } } #region Primitive Types public void SaveBool(bool value, string id) => _writeSerializer.SaveBool(value, id); public bool LoadBool(string id) => _writeSerializer.LoadBool(id); public void SaveUint(uint value, string id) => _writeSerializer.SaveUint(value, id); public uint LoadUint(string id) => _writeSerializer.LoadUint(id); public void SaveInt(int value, string id) => _writeSerializer.SaveInt(value, id); public int LoadInt(string id) => _writeSerializer.LoadInt(id); public void SaveLong(long value, string id) => _writeSerializer.SaveLong(value, id); public long LoadLong(string id) => _writeSerializer.LoadLong(id); public void SaveFloat(float value, string id) => _writeSerializer.SaveFloat(value, id); public float LoadFloat(string id) => _writeSerializer.LoadFloat(id); public void SaveDouble(double value, string id) => _writeSerializer.SaveDouble(value, id); public double LoadDouble(string id) => _writeSerializer.LoadDouble(id); public void SaveString(string value, string id) => _writeSerializer.SaveString(value, id); public string LoadString(string id) => _writeSerializer.LoadString(id); #endregion Primitive Types #region Complex Types public void SaveDateTime(DateTime value, string id) { _writeSerializer.SaveDateTime(value, id); } public DateTime LoadDateTime(string id) => _writeSerializer.LoadDateTime(id); #endregion Complex Types } }
<template> <el-form inline :disabled="disabled"> <el-form-item label="一级分类"> <el-select v-model="categoryStore.category1Id" @change="categoryStore.getCategory2List"> <el-option v-for="c1 in categoryStore.category1List" :key="c1.id" :label="c1.name" :value="c1.id" ></el-option> </el-select> </el-form-item> <el-form-item label="二级分类"> <el-select v-model="categoryStore.category2Id" @change="categoryStore.getCategory3List"> <el-option v-for="c2 in categoryStore.category2List" :key="c2.id" :label="c2.name" :value="c2.id" ></el-option> </el-select> </el-form-item> <el-form-item label="三级分类"> <el-select v-model="categoryStore.category3Id"> <el-option v-for="c3 in categoryStore.category3List" :key="c3.id" :label="c3.name" :value="c3.id" ></el-option> </el-select> </el-form-item> </el-form> </template> <script setup lang="ts"> // 三级分类 // 1. 静态搭建 // el-form 的 inline 属性是行内表单 // 2. 初始化数据展示 // 注意: 在咱们项目中没有其他地方使用pinia了,需要专门找一个东西使用使用pinia,我们会把 三级分类组件所有相关数据放pinia // 为了使用pinia而使用pinia // 2.1 api准备 // 2.2 初始化(mounted)的时候调用api // 当页面初始化的时候,只拿了一级分类的数据 // 选择完一级分类之后,请求二级分类数据 // 选择完二级分类之后,请求三级分类数据 // 选择完三级分类诸侯,请求页面数据(放一放) // 和交互混在一块做 // 3. 交互 import { onMounted } from 'vue'; import useCategoryStore from '@/stores/category' const categoryStore = useCategoryStore() // 针对TS传参不同,走的方法可以理解为走的不是同一个方法 // 1. 传数组 // const props = defineProps(['disabled']) // 2. 传对象 // const props = defineProps({ // disabled: { // type: Boolean, // required: true // } // }) // const props = defineProps({ // disabled: boolean // }) // 3. 不传参,加TS类型 // interface PropsModel { // disabled: boolean // } // const props = defineProps<PropsModel>() // console.log(props) // 简化版本 const props = defineProps<{ disabled: boolean }>() onMounted(() => { categoryStore.getCategory1List() }) </script> <style scoped> </style>
import React, { useEffect, useState } from "react"; interface CarouselProps { images: string[]; } const Carousel: React.FunctionComponent<CarouselProps> = ({ images }) => { const [currentImageIndex, setCurrentImageIndex] = useState(0); useEffect(() => { const interval = setInterval(() => { setCurrentImageIndex((prevIndex) => (prevIndex + 1) % images.length); }, 8000); return () => clearInterval(interval); }, [images.length]); return ( <div className="h-full transition-transform duration-700"> <img src={images[currentImageIndex]} srcSet={`${images[currentImageIndex]} 1x, ${images[currentImageIndex]} 2x`} sizes="(max-width: 600px) 100vw, (max-width: 1024px) 50vw, 33.3vw" className="object-cover h-full w-screen" alt={`Image ${currentImageIndex + 1}`} /> </div> ); }; export default Carousel;
import { useState, useEffect } from 'react'; type RequestFunction = (initialValue?: any) => Promise<any>; export function useRequest( requestFn: RequestFunction, initialValue: any, startRequest: boolean ) { const [isRequesting, setIsRequesting] = useState<boolean>(false); const [error, setError] = useState<any>(null); const [requestData, setRequestData] = useState<any>(); useEffect(() => { async function fetchData() { setIsRequesting(true); try { const data = await requestFn(initialValue); setRequestData(data); } catch (error) { setError({ message: error || 'Failed to fetch data.' }); } setIsRequesting(false); } if (startRequest) { // Only execute if startFetching is true fetchData(); } }, [requestFn, initialValue, startRequest]); return { isRequesting, requestData, setRequestData, error, }; }
import { OverlayDiv, WrapperEdit, EditText, LogOutBtn, EditIcon, } from './PopupUser.styled'; import { useState } from 'react'; import { ModalUserProfil } from '../ModalUserProfil'; import { ModalLogOut } from '../ModalLogOut'; export const PopupUser = ({ openPopUp, closePopUp, close }) => { const [isOpenModal, setIsOpenModal] = useState(false); const [isLogOutModal, setIsLogOutModal] = useState(false); const onCloseModal = () => { setIsOpenModal(false); }; const onCloseLogOutModal = () => { setIsLogOutModal(false); }; return ( <OverlayDiv onClick={closePopUp} className={openPopUp ? 'open' : 'close'}> <WrapperEdit onClick={() => setIsOpenModal(true)}> <EditText>Edit profile</EditText> <EditIcon id="icon-edit" /> </WrapperEdit> <LogOutBtn onClick={() => setIsLogOutModal(true)}>Log out</LogOutBtn> <ModalUserProfil isOpen={isOpenModal} close={onCloseModal} /> <ModalLogOut isOpen={isLogOutModal} close={onCloseLogOutModal} /> </OverlayDiv> ); };
/** * Copyright 2013 Glenn McAllister * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.menhir_it.plist; import java.util.EnumSet; /** * PropertyOptions describe how a Property can be used. * * @author gmcallister * */ public enum PropertyOptions { /** * The {@code CAN_WRITE} option allows the value of a {@link Property} * to be modified after it is created. Without this option, a Property is * read-only. */ CAN_WRITE, /** * The {@code CAN_DELETE} option allows a {@link Property} to be removed * from a {@link PropertyList}. Without this option, once a Property has * been added to a list, it cannot be removed from that list. */ CAN_DELETE, /** * The {@code CAN_ENNUMERATE} option allows a {@link Property} that is * part of a {@link PropertyList} to be enumerated. Without this option, if * a Property is in a list, it will be skipped over in an iterator. */ CAN_ENUMERATE; /** * This {@link EnumSet} provides the default set of options that a * Property will have unless otherwise provided by the {@link Property} * creator. */ public static final EnumSet<PropertyOptions> DEFAULT_OPTIONS = EnumSet.of(CAN_WRITE, CAN_DELETE, CAN_ENUMERATE); }
library(tidyverse) library(move) # Movebank credentials mv_creds <- movebankLogin('levi_newediuk', 'COWelk2019') # Load study IDs MV_mamms <- readRDS('output/mammal_studies.rds') # Source HMM function source('functions/GetMovementStates.R') # Download data for(i in unique(MV_mamms$id)) { # Indicate study cat('Processing study ', i, '\n') # If already exists in files, move to next if({any(sapply(list.files('hmm_files/', full.names=TRUE), function(x) str_detect(x, as.character(i))))}) { cat('Study already processed', '\n') next } # Download data and classify movement hmm_states <- movement_states(study_id = i, mv_creds = mv_creds) # If no tracks could be assessed, move on without saving if(nrow(hmm_states) == 0) next # Name file for saving hmm_file_name <- paste0('hmm_files/', str_replace(tolower( unique(hmm_states$individual.taxon.canonical.name)), ' ', '_'), '_', i, '.rds') # If multiple species in study, split them and save as separate .csvs if(length(hmm_file_name) > 1) { # Split data frame into list by taxon multi_taxa <- split(hmm_states, hmm_states$individual.taxon.canonical.name) # Save each individually for(taxa in 1:length(multi_taxa)) { # Make new filename multi_taxa_file_name <- paste0('hmm_files/', str_replace(tolower( unique(multi_taxa[[taxa]]$individual.taxon.canonical.name)), ' ', '_'), '_', i, '.rds') # Save saveRDS(multi_taxa[[taxa]], multi_taxa_file_name) } } else { # Otherwise save as one .csv saveRDS(hmm_states, hmm_file_name) } # Report whether study saved cat('Study ', i, ' saved successfully', '\n') }
import router from "./router"; import store from "./store"; import { Message } from "element-ui"; import NProgress from "nprogress"; // progress bar import "nprogress/nprogress.css"; // progress bar style import { getToken } from "@/utils/auth"; // get token from cookie import getPageTitle from "@/utils/get-page-title"; // import { get } from "core-js/core/dict"; NProgress.configure({ showSpinner: false }); // NProgress Configuration //const whiteList = ["/login"]; // no redirect whitelist 白名单 router.beforeEach(async (to, from, next) => { // start progress bar // 进度条开始 NProgress.start(); // set page title 设置标题 document.title = getPageTitle(to.meta.title); // determine whether the user has logged in 获取token // const hasToken = getToken(); // 获取本地用户信息 const hasGetUserInfo = store.getters.user; if (to.meta.auth) { // 跳转的页面需要鉴权 if (!hasGetUserInfo) { // 没有用户信息 // 获取token const hasToken = getToken(); if (hasToken) { // 有token,还需要验证token的有效性 try { await store.dispatch("user/getInfo"); next(); } catch (err) { // token失效,删除token并删除token,跳转到登录页 await store.dispatch("user/resetToken"); Message.error("登录过期,请重新登录"); next(`/login?redirect=${to.path}`); } } else { // 没有token,要重新登录 next(`/login?redirect=${to.path}`); } } else { // 放行 next(); } // 进度条结束 } else { // 跳转的页面不需要鉴权 if (to.path === "/login" && hasGetUserInfo) { // 登录状态下跳转到登录页面跳转到首页,否则放行 next({ path: "/" }); } else next(); // 进度条结束 } // 下方是vue-element-admin原来的鉴权流程 // 判断是否有token // if (hasToken) { // // 有token // if (to.path === "/login") { // // 要进入登录页 // // if is logged in, redirect to the home page // // 放行 // next({ path: "/" }); // NProgress.done(); // } else { // // 看一下是否有用户信息 // const hasGetUserInfo = store.getters.name; // if (hasGetUserInfo) { // // 有用户信息 // // 放行 // next(); // } else { // // 没有用户信息 // try { // // get user info // // 用token尝试重新获取用户信息 // await store.dispatch("user/getInfo"); // next(); // } catch (error) { // // remove token and go to login page to re-login // // token有问题,删除token // await store.dispatch("user/resetToken"); // Message.error(error || "Has Error"); // // 重新跳转到登录页面 // next(`/login?redirect=${to.path}`); // NProgress.done(); // } // } // } // } else { // /* has no token*/ // // 没有token // if (whiteList.indexOf(to.path) !== -1) { // // in the free login whitelist, go directly // next(); // } else { // // other pages that do not have permission to access are redirected to the login page. // next(`/login?redirect=${to.path}`); // NProgress.done(); // } // } }); router.afterEach(() => { // finish progress bar NProgress.done(); });
import os import pandas as pd import datetime import json from src.scraping_netkeiba import Results, HorseResults, Peds, Return, update_data, get_race_id_list def update_race_data(START_YEAR, END_YEAR, DATA_RACE_RESULTS, DATA_RETURN_RESULTS) -> list: # レースIDのリストを取得 race_ids = get_race_id_list(START_YEAR, END_YEAR) # まずはレース結果のデータを取得 Results.info() pre_race_results = pd.read_csv(DATA_RACE_RESULTS) if os.path.exists(DATA_RACE_RESULTS) else pd.DataFrame() race_results = Results.scrape(race_ids) # 払い戻し表のデータを取得 Return.info() pre_return_data = pd.read_csv(DATA_RETURN_RESULTS) if os.path.exists(DATA_RETURN_RESULTS) else pd.DataFrame() return_data = Return.scrape(race_ids) # 取得したデータを更新 updated_race_results = update_data(pre_race_results, race_results) updated_return_data = update_data(pre_return_data, return_data) # それぞれのデータをCSVファイルに保存 updated_race_results.to_csv(DATA_RACE_RESULTS) updated_return_data.to_csv(DATA_RETURN_RESULTS) return race_ids def update_horse_data(DATA_RACE_RESULTS, DATA_HORSE_RESULTS, DATA_PEDS_RESULTS, race_ids) -> list: # 前回取得した馬IDのリストを取得 pre_horse_results_index = set(pd.read_csv(DATA_RACE_RESULTS, index_col=0).loc[race_ids, "horse_id"].unique()) if os.path.exists(DATA_RACE_RESULTS) else set() # 馬IDのリストを取得 horse_ids = list(set(pd.read_csv(DATA_RACE_RESULTS)["horse_id"].unique()) - pre_horse_results_index) horse_ids = [str(horse_id) for horse_id in horse_ids] # 馬の過去成績のデータを取得 HorseResults.info() pre_horse_results = pd.read_csv(DATA_HORSE_RESULTS) if os.path.exists(DATA_HORSE_RESULTS) else pd.DataFrame() horse_results = HorseResults.scrape(horse_ids) # 血統データを取得 Peds.info() pre_peds_data = pd.read_csv(DATA_PEDS_RESULTS) if os.path.exists(DATA_PEDS_RESULTS) else pd.DataFrame() peds_data = Peds.scrape(horse_ids) # 取得したデータを更新 updated_horse_results = update_data(pre_horse_results, horse_results) updated_peds_data = update_data(pre_peds_data, peds_data) # それぞれのデータをCSVファイルに保存 updated_horse_results.to_csv(DATA_HORSE_RESULTS) updated_peds_data.to_csv(DATA_PEDS_RESULTS) return horse_ids def main(): START_YEAR = 2010 # スクレイピングする年の開始年 END_YEAR = 2023 # スクレイピングする年の終了年 DATA_BASE_DIR = 'data/scraped_data' DATA_RACE_RESULTS = f'{DATA_BASE_DIR}/race_results.csv' DATA_RETURN_RESULTS = f'{DATA_BASE_DIR}/return_data.csv' DATA_HORSE_RESULTS = f'{DATA_BASE_DIR}/horse_results.csv' DATA_PEDS_RESULTS = f'{DATA_BASE_DIR}/peds_data.csv' ONLY_HORSE_RESULTS = False # Trueにするとレース結果のデータを取得せず、馬の過去成績のデータだけを取得する(なんらかの理由でレース結果のみデータを持っている場合に使用) os.makedirs(DATA_BASE_DIR, exist_ok=True) # 前回実行時のメタデータを取得 metadata = {} pre_metadata = json.load(open(f'{DATA_BASE_DIR}/metadata.json')) if os.path.exists(f'{DATA_BASE_DIR}/metadata.json') else {} if len(pre_metadata): print('previous execute date info: ', pre_metadata['date']) metadata["pre_metadata"] = pre_metadata # レースデータを取得 race_ids = update_race_data(START_YEAR, END_YEAR, DATA_RACE_RESULTS, DATA_RETURN_RESULTS) if not ONLY_HORSE_RESULTS else [] horse_ids = update_horse_data(DATA_RACE_RESULTS, DATA_HORSE_RESULTS, DATA_PEDS_RESULTS, race_ids) # メタデータを更新 metadata["date"] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') metadata["append_race_id"] = race_ids metadata["append_horse_id"] = horse_ids with open(f'{DATA_BASE_DIR}/metadata.json', 'w') as f: json.dump(metadata, f, indent=4) if __name__ == "__main__": main()
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* stack.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hnagasak <hnagasak@student.42tokyo.jp> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/10/24 23:30:16 by hnagasak #+# #+# */ /* Updated: 2023/11/04 11:42:25 by hnagasak ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" void set_values(t_stack *stack, int *values, int values_count) { int i; if (values == NULL) return ; i = 0; while (i < values_count) { push(stack, values[values_count - i - 1]); i++; } } int *get_values(t_stack *stack) { int *values; int i; values = (int *)malloc(sizeof(int) * stack->size); i = 0; while (i < stack->size) { values[i] = stack->top->value; stack->top = stack->top->next; i++; } return (values); } /** * Take the first element at the top of A and put it at the top of B. * Do nothing if A is empty. * @param[out] a stack of a * @param[out] b stack of b * @return void */ t_stack *create_stack(char id, int *values, int values_count) { t_stack *stack; stack = (t_stack *)malloc(sizeof(t_stack)); if (stack == NULL) return (NULL); stack->id = id; stack->top = NULL; stack->bottom = NULL; stack->size = 0; set_values(stack, values, values_count); return (stack); } int pop(t_stack *stack) { t_node *remove; int pop_value; if (stack->size < 1) return (-1); remove = stack->top; pop_value = remove->value; if (stack->size > 1) { stack->top = stack->top->next; stack->top->prev = stack->bottom; stack->bottom->next = stack->top; } else { stack->top = NULL; stack->bottom = NULL; } free(remove); remove = NULL; stack->size--; return (pop_value); } void free_stack(t_stack *stack) { t_node *node; t_node *next; node = NULL; while (stack->size > 0) { if (node == NULL) node = stack->top; next = node->next; free(node); node = next; stack->size--; } free(stack); }
package com.atguigu.gmall.product.controller; import com.atguigu.gmall.common.result.Result; import io.minio.*; import io.minio.errors.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; @RestController @RequestMapping("/admin/product") public class FileUploadController { @Value("${minio.endpointUrl}") private String endpointUrl; @Value("${minio.accessKey}") private String accessKey; @Value("${minio.secretKey}") private String secretKey; @Value("${minio.bucketName}") private String bucketName; /** * 文件上传 * * @param file * @return */ //admin/product/fileUpload @PostMapping("/fileUpload") public Result fileUpload(MultipartFile file) { String url = null; try { // Create a minioClient with the MinIO server playground, its access key and secret key. MinioClient minioClient = MinioClient.builder() .endpoint(endpointUrl) .credentials(accessKey, secretKey) .build(); //查询指定桶是否存在 boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build()); if (!found) { //如果桶不存在就创建桶 minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); } else { System.out.println("Bucket 'gmall' already exists."); } //上传文件名 Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); String dateString = dateFormat.format(date); String uuid = UUID.randomUUID().toString().replaceAll("-", ""); String fileName = file.getName(); fileName = dateString + "/" + uuid + fileName; //实现文件内容的上传 minioClient.putObject( PutObjectArgs.builder().bucket(bucketName). object(fileName). stream(file.getInputStream(), file.getSize(), -1) .contentType(file.getContentType()) .build()); //组合访问的路径 url = endpointUrl + "/" + bucketName + "/" + fileName; } catch (Exception e) { e.printStackTrace(); } return Result.ok(url); } }
package com.connectik.cloverlead.service; import com.connectik.cloverlead.Application; import com.connectik.cloverlead.dto.AddressDTO; import com.connectik.cloverlead.dto.Gazetteer; import com.connectik.cloverlead.dto.SearchInput; import com.connectik.cloverlead.model.*; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.MatchQueryBuilder.Type; import org.elasticsearch.index.query.NestedQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHits; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class SearchService { @Autowired private Client esClient; @Value("${es.index.data}") private String dataIndex; @Value("${es.index.gazetteers}") private String gazetteerIndex; @Autowired private FavouriteSearchService favouriteSearchService; @Autowired private CompanyService companyService; @Autowired private OpportunityService opportunityService; @Autowired private UserService userService; @Autowired private ObjectMapper objectMapper; @SuppressWarnings("unchecked") public <T> Page<T> searchEntities(SearchableEntity entityType, SearchInput searchInput) { Map<Long, Float> scores = new HashMap<>(); Pageable page = new PageRequest(searchInput.getPage(), searchInput.getPageSize()); //@formatter:off SearchRequestBuilder search = esClient.prepareSearch(dataIndex) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setFrom(searchInput.getPage() * searchInput.getPageSize()) .setSize(searchInput.getPageSize()) .setFetchSource(false) .setTypes(entityType.getType()) .setQuery(searchQueryBuilder(entityType, searchInput)); //@formatter:on SearchResponse response = search.execute().actionGet(); Assert.state(RestStatus.OK == response.status()); SearchHits docs = response.getHits(); docs.forEach(doc -> scores.put(Long.parseLong(doc.getId()), doc.getScore())); switch (entityType) { case COMPANY: List<Company> companies = companyService.fetchAdditionalInfo(scores.keySet()); companies.sort((c1, c2) -> -1 * scores.get(c1.getId()).compareTo(scores.get(c2.getId()))); return (Page<T>) new PageImpl<>(companies, page, docs.getTotalHits()); case OPPORTUNITY: List<Opportunity> opportunities = opportunityService.findAll(scores.keySet()); opportunities.sort((c1, c2) -> -1 * scores.get(c1.getId()).compareTo(scores.get(c2.getId()))); return (Page<T>) new PageImpl<>(opportunities, page, docs.getTotalHits()); case EXPERT: List<User> experts = userService.find(scores.keySet()); experts.sort((c1, c2) -> -1 * scores.get(c1.getId()).compareTo(scores.get(c2.getId()))); return (Page<T>) new PageImpl<>(experts, page, docs.getTotalHits()); default: throw new RuntimeException("Unsupported search type"); } } public List<Gazetteer> searchGazetteers(String type, String prefix) { QueryBuilder query = StringUtils.isBlank(prefix) ? QueryBuilders.matchAllQuery() : QueryBuilders.matchQuery("name", prefix) // allows too much odd results // .fuzzyTranspositions(true).fuzziness(Fuzziness.AUTO) .type(Type.PHRASE_PREFIX); //@formatter:off SearchRequestBuilder search = esClient.prepareSearch(gazetteerIndex) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setSize(Application.Constants.MAXIMUM_GAZETTEER_RESULTS) .setQuery(query); //@formatter:on if (type != null) { search.setTypes(type); } SearchResponse response = search.execute().actionGet(); Assert.state(RestStatus.OK == response.status()); SearchHits docs = response.getHits(); List<Gazetteer> output = new ArrayList<>(); docs.forEach(doc -> output.add(new Gazetteer((String) doc.getSource().get("name"), doc.getType()))); return output; } public <T> Page<T> searchWithFavourite(Long id, int page, int pageSize) { FavouriteSearch search = favouriteSearchService.getForCurrentUser(id); try { SearchInput input = objectMapper.readValue(search.getParams(), SearchInput.class); input.setPage(page); input.setPageSize(pageSize); return searchEntities(search.getType(), input); } catch (IOException e) { throw new RuntimeException("Cannot deserialize favourite search"); } } private QueryBuilder searchQueryBuilder(SearchableEntity entityType, SearchInput input) { // building the main query... BoolQueryBuilder theQuery = QueryBuilders.boolQuery(); ArrayList<String> queryFields = new ArrayList<>(); //address filter NestedQueryBuilder addressNestedQuery = null; AddressDTO address = input.getAddress(); if (address != null) { BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery(); if (!StringUtils.isBlank(address.getCity())) { nestedBoolQuery.must(QueryBuilders.matchQuery("address.city", address.getCity())); } else if (!StringUtils.isBlank(address.getState())) { nestedBoolQuery.must(QueryBuilders.matchQuery("address.state", address.getState())); } else if (!StringUtils.isBlank(address.getCountry())) { nestedBoolQuery.must(QueryBuilders.matchQuery("address.country", address.getCountry())); } if (nestedBoolQuery.hasClauses()) { addressNestedQuery = QueryBuilders.nestedQuery("address", nestedBoolQuery); } } //specialties filter BoolQueryBuilder specialtiesQuery = QueryBuilders.boolQuery(); if (input.getSpecialties() != null && !input.getSpecialties().isEmpty()) { input.getSpecialties().stream().forEach(s -> specialtiesQuery.should(QueryBuilders.matchPhraseQuery("specialties_analyzed", s))); } //industries filter BoolQueryBuilder industryQuery = QueryBuilders.boolQuery(); if (input.getIndustries() != null && !input.getIndustries().isEmpty()) { input.getIndustries().stream().forEach(i -> industryQuery.should(QueryBuilders.matchPhraseQuery("industries_analyzed", i))); } //for the given type set the query fields and add the corresponding filters switch (entityType) { case COMPANY: queryFields.add("name"); queryFields.add("description"); queryFields.add("website"); queryFields.add("industries_analyzed"); queryFields.add("specialties_analyzed"); if (addressNestedQuery != null) { theQuery.filter(addressNestedQuery); } if (specialtiesQuery.hasClauses()) { theQuery.filter(specialtiesQuery); } if (industryQuery.hasClauses()) { theQuery.filter(industryQuery); } break; case OPPORTUNITY: queryFields.add("name"); queryFields.add("description"); queryFields.add("website"); queryFields.add("specialties_analyzed"); queryFields.add("keywords_analyzed"); if (addressNestedQuery != null) { theQuery.filter(addressNestedQuery); } if (specialtiesQuery.hasClauses()) { theQuery.filter(specialtiesQuery); } break; case EXPERT: queryFields.add("firstName"); queryFields.add("lastName"); queryFields.add("bio"); queryFields.add("industries_analyzed"); queryFields.add("specialties_analyzed"); if (addressNestedQuery != null) { theQuery.filter(addressNestedQuery); } if (specialtiesQuery.hasClauses()) { theQuery.filter(specialtiesQuery); } if (industryQuery.hasClauses()) { theQuery.filter(industryQuery); } break; default: throw new RuntimeException("Unsupported search type"); } if (!StringUtils.isBlank(input.getSearchQuery())) { //multi match query given the query fields theQuery.should(QueryBuilders.multiMatchQuery(input.getSearchQuery(), queryFields.toArray(new String[queryFields.size()]))); //nested address query BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery(); nestedBoolQuery.should(QueryBuilders.matchQuery("address.city", input.getSearchQuery())); nestedBoolQuery.should(QueryBuilders.matchQuery("address.state", input.getSearchQuery())); nestedBoolQuery.should(QueryBuilders.matchQuery("address.country", input.getSearchQuery())); theQuery.should(QueryBuilders.nestedQuery("address", nestedBoolQuery)); } else { if (!StringUtils.isBlank(input.getName())) { theQuery.must(QueryBuilders.matchPhraseQuery("name", input.getName())); } if (!StringUtils.isBlank(input.getDescription())) { theQuery.must(QueryBuilders.matchPhraseQuery("description", input.getDescription())); } } return theQuery; } }
import React, {useState} from "react"; import crypto from "crypto"; /****************************** * Hardcoded Data for scenario * *******************************/ // Let's pretend this is a database and that // these passwords are appropriately encrypted // in a real application const sampleUsers = [{ "name": "Safe User", "email": "safe@example.com", "password": "pw", "lastLogin": "2017-09-22T21:01:13.184Z" }, { "name": "Unsafe User", "email": "test@example.com", "password": "pw", "lastLogin": "2016-01-01T08:51:33.912Z" } ]; //These are the hardcoded breaches that we will //pretend came from an API const sampleBreaches = [{ "name": "Bolt", "domain": "bolt.cd", "breachDate": "2017-03-01", "addedDate": "2017-11-24T08:15:24Z" }, { "name": "Elance", "domain": "elance.com", "breachDate": "2009-01-01", "addedDate": "2017-02-18T02:54:48Z" }, { "name": "Zomato", "domain": "zomato.com", "breachDate": "2017-05-17", "addedDate": "2017-09-04T21:06:46Z" } ] /********************* * Business functions * *********************/ //Takes a user and a boolean has_breaches value //and returns the auth object cooresponding with //that user function buildAuth(user, has_breaches) { if (has_breaches) { return { token: crypto.randomBytes(16).toString("hex"), user: user, meta: { suggestPasswordChange: true, breachedAccounts: sampleBreaches } } } else { return { token: crypto.randomBytes(16).toString("hex"), user: user } } } export default function LoginForm(props) { const [user, setUser] = useState({ email: "", password: "", loginFailed: false }); const updateLogin = (val) => { setUser({ ...user, ...val }); } const handleSubmit = (e) => { e.preventDefault(); // NOTE: Normally would be hooked up to the an API call to determine // if the particular email has breaches, but you should leave this // hard-coded data for now. We're mostly interested in the React // portion of this code. if (user.email === sampleUsers[0].email && user.password === sampleUsers[0].password) { setUser({ ...user, loginFailed: false }); // has no breaches props.onLoginSuccess(buildAuth(user, false)); } else if (user.email === sampleUsers[1].email && user.password === sampleUsers[1].password) { setUser({ ...user, loginFailed: false }); // has breaches props.onLoginSuccess(buildAuth(user, true)); } else { setUser({ ...user, loginFailed: true }); } return false; } return ( <div> {user.loginFailed && ( <div className="alert alert-danger mt-3"> The email or password you provided is incorrect. Please check your entry and try again. </div> )} <div className="py-5 text-center"> <h2>Sign In</h2> </div> <div> <form onSubmit={e => handleSubmit(e)}> <div className="mb-3"> <label htmlFor="email">Email</label> <div className="input-group"> <input type="text" className="form-control" id="email" required onChange={e => updateLogin({ email: e.target.value })} value={user.email} /> </div> </div> <div className="mb-3"> <label htmlFor="password">Password</label> <div className="input-group"> <input type="password" className="form-control" id="password" onChange={e => updateLogin({ password: e.target.value })} required /> </div> </div> <button className="btn btn-primary" type="submit"> Sign In </button> </form> </div> </div> ); }
package com.nicode.campus.web.Controllers; import com.nicode.campus.Services.TestService; import com.nicode.campus.Services.dto.TestAndQuestionRequest; import com.nicode.campus.persistance.Entities.TestEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @Controller @RequestMapping("/api/test") public class TestController { private final TestService testService; @Autowired public TestController(TestService testService) { this.testService = testService; } @PostMapping("/save") public ResponseEntity<TestEntity> save(@RequestBody TestEntity test) { ResponseEntity<TestEntity> response; TestEntity savedTest = this.testService.save(test); if (savedTest != null){ response = ResponseEntity.ok(savedTest); } else { response = new ResponseEntity<>(HttpStatus.NOT_FOUND); } return response; } @GetMapping("/get/{id}") public ResponseEntity<Optional<TestEntity>> get(@PathVariable("id") int id) { return ResponseEntity.ok(testService.getById(id)); } @GetMapping("/getAll") public ResponseEntity<Optional<List<TestEntity>>> getAll(){ return ResponseEntity.ok(testService.getAll()); } @PostMapping("/saveEnt") public ResponseEntity<TestEntity> saveAll(@RequestBody TestAndQuestionRequest request) { ResponseEntity<TestEntity> response; TestEntity savedTest = this.testService.saveEnt(request); if (savedTest != null){ response = ResponseEntity.ok(savedTest); } else { response = new ResponseEntity<>(HttpStatus.NOT_FOUND); } return response; } @PutMapping("/update/{id}") public ResponseEntity<TestEntity> update(@RequestBody TestAndQuestionRequest request, @PathVariable int id){ ResponseEntity<TestEntity> response; Optional<TestEntity> test = this.testService.getById(id); if(test.isPresent()){ TestEntity savedTest = this.testService.saveEnt(request); response = ResponseEntity.ok(savedTest); } else { response = new ResponseEntity<>(HttpStatus.NOT_FOUND); } return response; } @DeleteMapping("/delete/{id}") public ResponseEntity<String> delete(@PathVariable("id") int testId) { boolean deletionResult = this.testService.delete(testId); if (deletionResult) { return ResponseEntity.ok("Evaluación eliminada exitosamente"); } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error al eliminar la evaluación"); } } @DeleteMapping("/deleteAll") public ResponseEntity<String> deleteAll(){ boolean deletionResult = this.testService.deleteAll(); if (deletionResult) { return ResponseEntity.ok("Evaluaciones eliminadas exitosamente"); } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error al eliminar las evaluaciones"); } } }
/** * @author Michele Tomaiuolo - http://www.ce.unipr.it/people/tomamic * @license This software is free - http://www.gnu.org/licenses/gpl.html */ #ifndef ELEMENT_H #define ELEMENT_H #include "node.h" #include "pair.h" #include <string> #include <vector> #include <map> using namespace std; class Element : public Node { public: Element(string type); ~Element(); void addNode(Node* node); void addAttribute(string key, string value); void print(ostream &out, int indent); private: void printAttributes(ostream &out); void printChildren(ostream &out, int indent); string type; vector<Node*> children; vector<Pair*> attributes; // map<string, string> attributes; }; #endif // ELEMENT_H
 <section class="signup-section spad"> <div class="signup-bg set-bg" data-setbg="../../img/signup-bg.jpg"></div> <div class="container-fluid"> <div class="row"> <div class="col-lg-6"> <div class="signup-warp"> <div class="section-title text-white text-left"> <h2>Sign up to became a teacher</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada lorem maximus mauris scelerisque, at rutrum nulla dictum. Ut ac ligula sapien. Suspendisse cursus faucibus finibus.</p> </div> <!-- signup form --> <!--<form class="signup-form"> <input type="text" placeholder="Your Name"> <input type="text" placeholder="Your E-mail"> <input type="text" placeholder="Your Phone"> <label for="v-upload" class="file-up-btn">Upload Course</label> <input type="file" id="v-upload"> <button class="site-btn">Search Couse</button> </form>--> <div *ngIf="errorMessage" class="alert alert-danger">{{ errorMessage }}</div> <form class="signup-form" (submit)="addsubject()"> <div class="form-group"> <label for="subjectName">Subject Name</label> <input type="text" placeholder="subject Name" class="form-control" name="subjectName" #subjectName="ngModel" [(ngModel)]="subject.subjectName" required /> <div class="text-danger" *ngIf="subjectName.touched && subjectName.invalid && subjectName.errors.required">Required</div> </div> <div class="form-group"> <label for="subjectTitle">Subject Title</label> <input type="text" placeholder="Subject Title" class="form-control" #subjectTitle="ngModel" name="subjectTitle" [(ngModel)]="subject.subjectTitle" required /> <div class="text-danger" *ngIf="subjectTitle.touched && subjectTitle.invalid && subjectTitle.errors.required">Required</div> </div> <!--<div class="form-group"> <label for="subjectTitle">Subject Title</label> <input type="text" placeholder="Subject Title" class="form-control" #subjectTitle="ngModel" name="subjectTitle" [(ngModel)]="subject.subjectTitle" required /> <div class="text-danger" *ngIf="subjectTitle.touched && subjectTitle.invalid && subjectTitle.errors.required">Required</div> </div>--> <div class="form-group"> <label for="courseId">Course</label> <select class="form-control" id="courseId" #courseId="ngModel" name="courseId" [(ngModel)]="subject.courseId"> <option *ngFor="let c of courseService.courses" value="{{ c.courseId }}"> {{ c.title }} </option> </select> </div> <div class="form-group"> <input type="submit" class="site-btn" value="Add" [disabled]="subjectName.invalid || subjectTitle.invalid" /> <a routerLink="/course" class="btn btn-default">Cancel</a> <!--<a routerLink="/course" class="class="site-btn">Cancel</a>--> </div> </form> </div> </div> </div> </div> </section>
<!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>Document</title> </head> <body> <div id="conteudo-salvo"></div> <hr> <div> <b>Qual a cor de fundo desejada</b> <input id="corFundo" type="color"> <br> <b>Qual a cor de texto desejada</b> <input id="corTexto" type="color"> <br> <b>Qual o tamanho da fonte</b> <select id="tamanho" > <option value="10px">10px</option> <option value="5em">5em</option> <option value="1000px">1000px</option> </select><br> <b>Qual o conteudo da página</b> <textarea id="conteudo" ></textarea> <br> <button id="submit">Atualiza página</button> </div> <script> const corFundo = document.querySelector("#corFundo") const corTexto = document.querySelector("#corTexto") const tamanho = document.querySelector("#tamanho") const conteudo = document.querySelector("#conteudo") const submit = document.querySelector("#submit") const conteudoSalvo = document.querySelector("#conteudo-salvo") submit.onclick = ()=>{ const inputs = { "corDeFundo": corFundo.value, "corDoTexto": corTexto.value, "tamanhoDaFonte": tamanho.value, "conteudoDinamico": conteudo.value } fetch("http://localhost:5151/WeatherForecast/salvaPrefencia", { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(inputs), }).then(()=>{ atualizaFront() }) } atualizaFront() function atualizaFront(){ fetch("http://localhost:5151/WeatherForecast/buscaPreferencia") .then(e=>e.json()) .then(data => { document.body.style.backgroundColor = data.corDeFundo document.body.style.fontSize = data.tamanhoDaFonte document.body.style.color = data.corDoTexto conteudoSalvo.innerText = data.conteudoDinamico }) } </script> </body> </html>
from django.contrib.auth.models import User from django.test import TestCase from rest_framework.test import APITestCase, APIRequestFactory from ..models import Institute, InstitutePhoto, Teacher, Department, TeacherPhoto, Discipline, Review from ..serializers import InstituteSerializer, InstitutePhotoSerializer, DepartmentSerializer, TeacherCardSerializer, \ TeacherSerializer class InstituteSerializerTestCase(APITestCase): def test_institute_serializer(self): # Создание объекта Institute institute_data = { 'name': 'Example Institute', 'description': 'This is an example institute', 'abbreviation': 'EI', } institute = Institute.objects.create(**institute_data) photos_data = [{'photo': 'photo1.jpg'}, {'photo': 'photo2.jpg'}] for photo_data in photos_data: InstitutePhoto.objects.create(institute=institute, **photo_data) # Создание сериализатора serialized_data = InstituteSerializer(institute).data # Проверка, что сериализатор возвращает ожидаемые данные self.assertEqual(serialized_data['name'], 'Example Institute') self.assertEqual(serialized_data['description'], 'This is an example institute') self.assertEqual(serialized_data['abbreviation'], 'EI') self.assertEqual(len(serialized_data['photos']), len(photos_data)) def test_institute_photo_serializer(self): # Создание объекта Institute institute_data = { 'name': 'Example Institute', 'description': 'This is an example institute', 'abbreviation': 'EI', } institute = Institute.objects.create(**institute_data) photo_data = {'photo': 'sample.jpg', 'institute': institute} photo = InstitutePhoto.objects.create(**photo_data) serializer = InstitutePhotoSerializer(instance=photo) # Проверка, что сериализатор возвращает ожидаемые данные self.assertEqual(serializer.data['photo'], '/media/sample.jpg') class DepartmentSerializerTestCase(APITestCase): def setUp(self): self.user = User.objects.create_superuser(username='123', email='asjdfhkas@gmail.com', password='testpassword') response = self.client.post('/auth/token/login/', {'username': '123', 'password': 'testpassword'}) self.token = response.data['auth_token'] self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) def test_department_serializer(self): institute_data = { 'name': 'Example Institute', 'description': 'This is an example institute', 'abbreviation': 'EI', } institute = Institute.objects.create(**institute_data) department_data = { 'name': 'Example Department', 'description': 'This is an example department', 'institute': institute, } department = Department.objects.create(**department_data) teacher_data = { 'name': 'John Doe', 'institute': institute, 'department': department, 'knowledge_rating': 5, 'teaching_skill_rating': 4, 'easiness_rating': 3, 'communication_rating': 5, 'review_count': 10, 'created_by': self.user } teacher = Teacher.objects.create(**teacher_data) # Создайте сериализатор serializer = DepartmentSerializer(instance=department) # Проверьте, что сериализатор возвращает ожидаемые данные self.assertEqual(serializer.data['name'], 'Example Department') self.assertEqual(len(serializer.data['teachers']), 1) class TeacherSerializerTestCase(APITestCase): def setUp(self): self.user = User.objects.create_superuser(username='1234', email='asjdfhkas@gmail.com', password='testpassword') response = self.client.post('/auth/token/login/', {'username': '1234', 'password': 'testpassword'}) self.token = response.data['auth_token'] self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) def test_teacher_card_serializer(self): # Создание объекта Institute institute_data = { 'name': 'Example Institute', 'description': 'This is an example institute', 'abbreviation': 'EI', } institute = Institute.objects.create(**institute_data) # Создание объекта Department department_data = { 'name': 'Example Department', 'description': 'This is an example department', 'institute': institute, } department = Department.objects.create(**department_data) # Создание объекта Teacher teacher_data = { 'name': 'John Doe', 'institute': institute, 'department': department, 'created_by': self.user } teacher = Teacher.objects.create(**teacher_data) # Создние фото для учителя photo_data = {'photo': 'teacher_photo.jpg', 'teacher': teacher} TeacherPhoto.objects.create(**photo_data) factory = APIRequestFactory() request = factory.get('') serializer = TeacherCardSerializer(instance=teacher, context={'request': request}) # Проверка, что сериализатор возвращает ожидаемые данные self.assertEqual(serializer.data['name'], 'John Doe') self.assertEqual(serializer.data['avg_rating'], '0.000') self.assertTrue('first_photo' in serializer.data) self.assertEqual(serializer.data['first_photo'], request.build_absolute_uri('/media/teacher_photo.jpg')) def test_teacher_serializer(self): # Создание объекта Institute institute_data = { 'name': 'Example Institute', 'description': 'This is an example institute', 'abbreviation': 'EI', } institute = Institute.objects.create(**institute_data) # Создайте объект Department department_data = { 'name': 'Example Department', 'description': 'This is an example department', 'institute': institute, } department = Department.objects.create(**department_data) # Создание объекта Teacher teacher_data = { 'name': 'John Doe', 'institute': institute, 'department': department, 'knowledge_rating': 5, 'teaching_skill_rating': 4, 'easiness_rating': 3, 'communication_rating': 5, 'review_count': 9, 'bio': 'This is John Doe, a great teacher.', 'created_by': self.user, } teacher = Teacher.objects.create(**teacher_data) # Создание фото для учителя photo_data = {'photo': 'teacher_photo.jpg', 'teacher': teacher} TeacherPhoto.objects.create(**photo_data) # Создание дисциплины discipline_data = { 'name': 'Math' } Discipline.objects.create(**discipline_data) discipline = Discipline.objects.get(name='Math') discipline.teachers.add(teacher) user_data = { 'username': 'testuser', 'password': 'testpassword', } user = User.objects.create_user(**user_data) # Создание отзыва review_data = { 'teacher': teacher, 'student': user, 'knowledge_rating': 5, 'teaching_skill_rating': 4, 'easiness_rating': 3, 'communication_rating': 5, 'comment': 'John Doe is an amazing teacher!', 'is_anonymous': False, } Review.objects.create(**review_data) # Создание сериализатора serializer = TeacherSerializer(instance=teacher) # Проверка, что сериализатор возвращает ожидаемые данные self.assertEqual(serializer.data['name'], 'John Doe') self.assertEqual(serializer.data['knowledge_rating'], '5.000') self.assertEqual(serializer.data['teaching_skill_rating'], '4.000') self.assertEqual(serializer.data['easiness_rating'], '3.000') self.assertEqual(serializer.data['communication_rating'], '5.000') self.assertEqual(serializer.data['review_count'], 10) self.assertEqual(serializer.data['bio'], 'This is John Doe, a great teacher.') self.assertEqual(serializer.data['disciplines'][0]['name'], 'Math') self.assertTrue('photos' in serializer.data) self.assertTrue('disciplines' in serializer.data) self.assertTrue('reviews' in serializer.data)
""" @Title: Implementing activation functions @Author(s): Stephen CUI @LastEditor(s): Stephen CUI @CreatedTime: 2023-09-06 16:06:24 @Description: """ import tensorflow as tf from tensorflow import nn print(tf.nn.relu([-3., 3., 10.])) # There are times where we'll want to cap the linearly increasing part of the preceding # ReLU activation function. We can do this by nesting the max(0,x) function in a min() # function. The implementation that TensorFlow has is called the ReLU6 function. This # is defined as min(max(0,x),6). This is a version of the hard-sigmoid function, is # computationally faster, and does not suffer from vanishing (infinitesimally near zero) # or exploding values. print(tf.nn.relu6([-3., 3., 10.])) # The sigmoid function is the most common continuous and smooth activation # function. It is also called a logistic function and has the form 1 / (1 + exp(-x)). The # sigmoid function is not used very often because of its tendency to zero-out the # backpropagation terms during training. print(tf.nn.sigmoid([-10., 0., 1.])) # tf.Tensor([0.26894143 0.5 0.9999546 ], shape=(3,), dtype=float32) # Another smooth activation function is the hyper tangent. The hyper tangent function # is very similar to the sigmoid except that instead of having a range between 0 and # 1, it has a range between -1 and 1. This function has the form of the ratio of the # hyperbolic sine over the hyperbolic cosine. print(tf.nn.tanh([-1., 0., 1.])) # tf.Tensor([-0.7615942 0. 0.7615942], shape=(3,), dtype=float32) # The softsign function is also used as an activation function. The form of this # function is x/(|x| + 1). The softsign function is supposed to be a continuous (but # not smooth) approximation to the sign function. print(tf.nn.softsign([-1., 0., 1.])) # tf.Tensor([-0.5 0. 0.5], shape=(3,), dtype=float32) # Another function, the softplus function, is a smooth version of the ReLU function. # The form of this function is log(exp(x) + 1). print(tf.nn.softplus([-1., 0., 1.])) # tf.Tensor([0.3132617 0.6931472 1.3132616], shape=(3,), dtype=float32) # The Exponential Linear Unit (ELU) is very similar to the softplus function except that # the bottom asymptote is -1 instead of 0. The form is (exp(x) + 1) if x < 0, else x. print(tf.nn.elu([-1., 0., 1.])) # tf.Tensor([-0.63212055 0. 1. ], shape=(3,), dtype=float32) def swish(x): # https://arxiv.org/abs/1710.05941 return x * tf.nn.sigmoid(x) print(swish([-1., 0., 1.])) # tf.Tensor([-0.26894143 0. 0.7310586 ], shape=(3,), dtype=float32)
--- description: "Steps to Make Homemade Peruvian hot chocolate - vegan" title: "Steps to Make Homemade Peruvian hot chocolate - vegan" slug: 677-steps-to-make-homemade-peruvian-hot-chocolate-vegan date: 2020-06-30T19:02:43.051Z image: https://img-global.cpcdn.com/recipes/0ba55583d9e43427/751x532cq70/peruvian-hot-chocolate-vegan-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/0ba55583d9e43427/751x532cq70/peruvian-hot-chocolate-vegan-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/0ba55583d9e43427/751x532cq70/peruvian-hot-chocolate-vegan-recipe-main-photo.jpg author: Eugene Parker ratingvalue: 3.3 reviewcount: 13 recipeingredient: - "1 cup milk of your choice use the mug cup youre going to drink out of" - "1/2 cup water" - "2 tbsp organic cacao powder" - "1 tsp maca powder i skip this if im making this in the evening night" - " generous pinch of ground cinnamon" - " generous pinch of ground cloves or allspice" - "to taste coconut sugar or jaggery the amount depends on the milk you use and your tastebuds" recipeinstructions: - "Heat the milk and water over a gentle to medium heat." - "When it’s warm, add the dry ingredients and whisk together." - "Enjoy 😋" categories: - Recipe tags: - peruvian - hot - chocolate katakunci: peruvian hot chocolate nutrition: 193 calories recipecuisine: American preptime: "PT33M" cooktime: "PT59M" recipeyield: "3" recipecategory: Dinner --- ![Peruvian hot chocolate - vegan](https://img-global.cpcdn.com/recipes/0ba55583d9e43427/751x532cq70/peruvian-hot-chocolate-vegan-recipe-main-photo.jpg) Hey everyone, hope you are having an amazing day today. Today, I will show you a way to prepare a distinctive dish, peruvian hot chocolate - vegan. One of my favorites food recipes. For mine, I am going to make it a little bit unique. This will be really delicious. So, what makes hot chocolate Peruvian I hear you ask? Well, Peruvian hot chocolate is infused with both allspice and cinnamon, giving it a wonderful flavour that kicks it up a gear from your typical hot chocolate recipe. To make it vegan, sub in any &#39;mylk&#39; you like for milk, and instead of condensed milk. Peruvian hot chocolate - vegan is one of the most well liked of recent trending foods in the world. It's appreciated by millions daily. It is simple, it is quick, it tastes delicious. Peruvian hot chocolate - vegan is something which I have loved my whole life. They're fine and they look fantastic. To get started with this recipe, we have to first prepare a few ingredients. You can cook peruvian hot chocolate - vegan using 7 ingredients and 3 steps. Here is how you cook it. <!--inarticleads1--> ##### The ingredients needed to make Peruvian hot chocolate - vegan: 1. Take 1 cup milk of your choice (use the mug/ cup you’re going to drink out of) 1. Take 1/2 cup water 1. Get 2 tbsp organic cacao powder 1. Prepare 1 tsp maca powder (i skip this if i’m making this in the evening/ night) 1. Prepare generous pinch of ground cinnamon 1. Take generous pinch of ground cloves or allspice 1. Take to taste coconut sugar or jaggery - the amount depends on the milk you use and your tastebuds! For my homemade dairy free hot chocolate recipe, instead of combining water, sugar, and cocoa to make a sauce, I decided to streamline it and omit the. Delightfully Dark Chocolate Peruvian Chocolate by Orquidea. With a rich chocolate flavor and a tender crumb, this gluten free vegan chocolate cake is free of refined sugars and will impress all who get to enjoy it! Creamy, healthy, super chocolaty, and topped with Origins of Hot Chocolate. <!--inarticleads2--> ##### Instructions to make Peruvian hot chocolate - vegan: 1. Heat the milk and water over a gentle to medium heat. 1. When it’s warm, add the dry ingredients and whisk together. 1. Enjoy 😋 Chocolate may date as far back as the Olmecs who were the earliest known Mesoamerican civilization. Just cocoa powder is hot cocoa, but this is hot chocolate. It should be richer and creamier. Learn how to make the BEST Vegan Hot Chocolate EVER! This vegan hot chocolate is just the easy recipe you need. So that's going to wrap this up with this special food peruvian hot chocolate - vegan recipe. Thank you very much for reading. I'm confident that you can make this at home. There is gonna be more interesting food at home recipes coming up. Remember to save this page on your browser, and share it to your family, colleague and friends. Thank you for reading. Go on get cooking!
import React, { useState, useEffect } from "react"; import emailjs from "emailjs-com"; import styled from "styled-components"; import { Data } from "./Data"; import { HiMail } from "react-icons/hi"; import { AiFillGithub, AiFillLinkedin } from "react-icons/ai"; import { FaCodepen } from "react-icons/fa"; const Container = styled.section` padding: 3rem 1rem 1rem 1rem; background-color: ${({ theme }) => theme.background}; min-height: 100vh; h2 { text-align: center; color: ${({ theme }) => theme.body}; position: relative; &::before { content: "Let's Talk"; color: ${({ theme }) => theme.primary}; font-size: 1rem; position: absolute; top: -12px; left: 50%; transform: translateX(-50%); } } .contact-info { position: relative; background: ${({ theme }) => theme.bgSecondary}; background-image: url("https://images.unsplash.com/photo-1621849400072-f554417f7051?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80"); padding: 2rem 1rem; text-align: center; margin-top: 2rem; color: ${({ theme }) => theme.textOnImg}; & > * { position: relative; z-index: 2; } &::before { content: ""; position: absolute; top: 0; left: 0; bottom: 0; right: 0; pointer-events: none; background-color: rgba(0, 0, 0, 0.7); z-index: 1; } } form { padding: 1rem 0; background-color: ${({ theme }) => theme.background}; .field { display: flex; flex-direction: column; margin-bottom: 1rem; .flex { display: flex; justify-content: space-between; align-items: center; span { color: #979797; } } label { font-size: 1rem; font-weight: bold; color: ${({ theme }) => theme.body}; } input, textarea { height: 40px; background-color: ${({ theme }) => theme.input}; color: ${({ theme }) => theme.body}; border-radius: 8px; border: 0; padding: 16px; margin-top: 0.5rem; &:focus { border: 3px solid ${({ theme }) => theme.primary}; outline: none; } } textarea { height: 100px; } } } @media screen and (min-width: 500px) { max-width: 900px; margin: 0 auto 3em auto; padding-inline: 2em; } @media screen and (min-width: 1024px) { max-width: 1200px; margin: 0 auto 3em auto; .grid { display: grid; grid-template-columns: 420px 1fr; gap: 1em; border-radius: 12px; margin-top: 2em; border: 1px solid ${({ theme }) => theme.border}; } .contact-info { grid-column: 1/2; text-align: left; margin-top: 0; padding: 2em; background-repeat: no-repeat; background-size: cover; p { margin-block: 1em; } .links { justify-content: flex-start; padding-left: unset; color: ${({ theme }) => theme.body}; } } form { grid-column: 2/3; width: 100%; padding: 2em 1em; } } /* FORM MESSAGE */ .form-message { position: fixed; display: flex; justify-content: center; align-items: center; background-color: ${({ theme }) => theme.formMessageSuccess}; color: ${({ theme }) => theme.body}; font-size: 0.875rem; min-width: 100px; padding: 1em 1.5em; border-radius: 12px; bottom: -100px; left: 50%; transform: translateX(-50%); box-shadow: 0px 1px 3px 1px #00000026; box-shadow: 0px 1px 2px 0px #0000004d; transition: 0.3s ease-in; user-select: none; } .show { bottom: 30px; } `; const Links = styled.div` display: flex; justify-content: center; align-items: center; padding: 16px 32px; a { font-size: 22px; color: ${({ theme }) => theme.textOnImg}; padding: 8px 16px; transition: all 0.2s ease-in-out; &:nth-child(1) { &:hover, &:focus { color: #da0d95; } } &:nth-child(2) { border-left: 3px solid ${({ theme }) => theme.borderOnImg}; border-right: 3px solid ${({ theme }) => theme.borderOnImg}; &:hover, &:focus { color: #be2a2a; } } &:nth-child(3) { border-right: 3px solid ${({ theme }) => theme.borderOnImg}; &:hover, &:focus { color: #bcdb0d; } } &:nth-child(4) { &:hover, &:focus { color: ${({ theme }) => theme.primary}; } } &:hover, &:focus { transform: scale(1.16); } } `; const Contact = ({ ...Data }) => { const [message, setMessage] = useState(""); const [show, setShow] = useState(false); const [error, setError] = useState(false); const sendEmail = e => { e.preventDefault(); emailjs .sendForm( "service_t2rhy24", "template_iyva747", e.target, "user_8lqOgYTwq9QuJL76cFuWh" ) .then( result => { setMessage("Email Sent successfully"); setShow(true); }, error => { setMessage("Someting went wrong!"); setShow(true); } ); e.target.reset(); }; useEffect(() => { const timer = setTimeout(() => { if (show === true) { setShow(false); } }, 3000); return () => clearTimeout(timer); }, [show]); return ( <Container id="contact" onSubmit={sendEmail}> <h2 className="h2">Get In Touch</h2> <div className="grid"> <div className="contact-info"> <h3 className="h4 ">Contact Information</h3> <p className="mt-s"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Repudiandae voluptatum maxime in perspiciatis quae ab quod. </p> <Links className="links"> <a href="mailto:jaheimcbrown@gmail.com" target="_blank"> <HiMail /> </a> <a href="https://github.com/KxngJ" target="_blank"> <AiFillGithub /> </a> <a href="https://codepen.io/kxngj" target="_blank"> <FaCodepen /> </a> <a href="https://www.linkedin.com/in/jaheim-brown-a92076209" target="_blank" > <AiFillLinkedin /> </a> </Links> </div> <form action="#"> <div className="field"> <label htmlFor="name">Name</label> <input type="text" name="name" id="name" required /> </div> <div className="field"> <label htmlFor="email">Email</label> <input type="email" name="email" id="email" required /> </div> <div className="field"> <div className="flex"> <label htmlFor="subject">Subject</label> <span className="body-small">(Optional)</span> </div> <input type="text" name="subject" id="subject" /> </div> <div className="field"> <label htmlFor="message" required> Message </label> <textarea name="message" id="message" /> </div> <div className="btn-container"> <button href="#" className="primary-btn "> Submit </button> </div> </form> </div> <div className={show ? "form-message show" : "form-message"}> <p>{message}</p> </div> </Container> ); }; export default Contact;
//多线程读写 import console; import sqlite; console.log(`尽量不要在客户端软件中多线程同时写sqlite数据库。 把多线程的程序比喻成一家公司,公司只要一个人负责记账就可以了,没必要每个线程都去做这件事。`) var db = sqlite("/test-sqlite-thread.db") //创建表 if( not db.existsTable("film") ){ db.exec( "CREATE TABLE [film](title, length, year, starring);") } //创建线程 var func = function(){ import sqlite; var db = sqlite("/test-sqlite-thread.db") //多线程冲突锁定时的重试次数 db.busyTimeout(10000); thread.lock("PRINT",λ() io.print("正在写数据库,线程ID:",thread.getId()) ) var command = db.prepare("REPLACE INTO film VALUES (@title,@length,@year, 'Jodie Foster');" ) for(i=1;10;1){ command.step( title = "标题"; length = 4; year = thread.getId(); ) } command.finalize(); db.close(); } var t1 = thread.create( func ) var t2 = thread.create( func ) var t3 = thread.create( func ) var t4 = thread.create( func ) var t5 = thread.create( func ) var t6 = thread.create( func ) thread.waitClose(t1,t2,t3,t4,t5,t6) for title, length, year, starring in db.each("SELECT * FROM film") { console.log( title, length, year, starring ) } //删除表 db.exec("DROP TABLE film" ); console.pause(true);
package ch.hsr.testing.unittest.weekenddiscount; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvFileSource; import java.time.LocalDateTime; import static org.junit.jupiter.api.Assertions.*; class WeekendDiscountTimeSlotValidatorTest { WeekendDiscountTimeSlotValidator validator; @BeforeEach void setUp() { validator = new WeekendDiscountTimeSlotValidator(); } /** * Setup a testDate for the exception test */ LocalDateTime testDate = LocalDateTime.of(2023, 2, 25, 12, 0); /** * Checks an exception is thrown, if * isAuthorizedForDiscount gets called without initialising the validator */ @Test void testNotInitialized() { IllegalWeekendNumberException exception = assertThrows(IllegalWeekendNumberException.class, () -> { validator.isAuthorizedForDiscount(LocalDateTime.now()); }); String expectedErrorMessage = "WeekendDiscountTimeSlotValidator has not been initialized correctly!"; assertEquals(expectedErrorMessage, exception.getMessage(), "Expected " + "custom exception message for not initialized number of weekends"); } /** * Checks an exception is thrown, if the initialized weekend number is * bigger than the number of weekends in the month we're trying to get the * discount in. February 2023 doesn't have a 5th weekend. */ @Test void testExceptionForTooManyWeekends() { validator.initializeWithWeekendNumber(5); IllegalWeekendNumberException exception = assertThrows(IllegalWeekendNumberException.class, () -> { validator.isAuthorizedForDiscount(testDate); }); String expectedErrorMessage = "Invalid weekend number: 5"; assertEquals(expectedErrorMessage, exception.getMessage(), "Expected custom exception message for too many weekends"); } /** * Checks an exception is thrown, if the initialized weekend number is 0. */ @Test void testExceptionForZeroAsWeekendNumber() { validator.initializeWithWeekendNumber(0); IllegalWeekendNumberException exception = assertThrows(IllegalWeekendNumberException.class, () -> { validator.isAuthorizedForDiscount(testDate); }); String expectedErrorMessage = "Invalid weekend number: 0"; assertEquals(expectedErrorMessage, exception.getMessage(), "Expected custom exception message for zero weekendNumber"); } /** * Checks an exception is thrown, if the initialized weekend number is * negative. */ @Test void testExceptionForNegativeWeekendNumber() { validator.initializeWithWeekendNumber(-1); IllegalWeekendNumberException exception = assertThrows(IllegalWeekendNumberException.class, () -> { validator.isAuthorizedForDiscount(testDate); }); String expectedErrorMessage = "Invalid weekend number: -1"; assertEquals(expectedErrorMessage, exception.getMessage(), "Expected custom exception message for negative weekendNumber"); } /** * Various checks to loop through possible cases */ @ParameterizedTest @CsvFileSource(resources = "weekendDiscountTimeSlotValidatorTestCases" + ".csv", numLinesToSkip = 1) void testWithCsvInput(int weekendNumber, int year, int month, int day, int hour, int minute, boolean expectedResult, String explanation) throws IllegalWeekendNumberException { validator.initializeWithWeekendNumber(weekendNumber); LocalDateTime testDate = LocalDateTime.of(year, month, day, hour, minute); assertEquals(expectedResult, validator.isAuthorizedForDiscount(testDate)); } }
import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import { useMutation } from '@apollo/client'; import { LOGIN_USER } from '../utils/mutations'; import Button from 'react-bootstrap/Button'; import Form from 'react-bootstrap/Form'; import Container from 'react-bootstrap/Container'; import Auth from '../utils/auth'; const Login = (props) => { const [formState, setFormState] = useState({ email: '', password: '' }); const [login, { error, data }] = useMutation(LOGIN_USER); // update state based on form input changes const handleChange = (event) => { const { name, value } = event.target; setFormState({ ...formState, [name]: value, }); }; // submit form const handleFormSubmit = async (event) => { event.preventDefault(); // console.log(formState); try { const { data } = await login({ variables: { ...formState }, }); Auth.login(data.login.token); } catch (e) { console.error(e); } // clear form values setFormState({ email: '', password: '', }); }; return ( <Container className="p-3 square border border-1 rounded bg-light m-2 mx-auto"> <h4 className="card-header bg-dark rounded text-light p-2">Login</h4> <div className="card-body"> {data ? ( <p> Success! You may now head{' '} <Link to="/">back to the homepage.</Link> </p> ) : ( <Form className="p-2" onSubmit={handleFormSubmit}> <Form.Group className ="mb-3" controlId="formBasicEmail"> <Form.Label>Email Address</Form.Label> <Form.Control type="email" placeholder="Your email" name="email" value={formState.email} onChange={handleChange} /> </Form.Group> <Form.Group className ="mb-3" controlId="formBasicPassword"> <Form.Label>Password</Form.Label> <Form.Control type="password" placeholder="******" name="password" value={formState.password} onChange={handleChange} /> </Form.Group> <Button variant="primary" style={{ cursor: 'pointer' }} type="submit" > Submit </Button> </Form> )} {error && ( <div className="my-3 p-3 bg-danger text-white"> {error.message} </div> )} </div> </Container> ); }; export default Login;
import { IMultifamilyForm } from './types' import { isValidEmail, isValidMobileNumber, isValidFirsttName, isValidLastName, isValidCommunityName, } from 'src/utils/validator' export const useMultifamilyFormValidator = ( form: IMultifamilyForm, errorCodes: any, ) => { const errors: any = validateErrors(form, errorCodes) const formFilled: boolean = isFormComplete(form, errors) return [formFilled, errors] } const validateErrors = (form: IMultifamilyForm, errorCodes: any) => { const errorMessages = { firstNameRequired: { value: 'First name is required', }, lastNameRequired: { value: 'Last name is required', }, communityNameRequired: { value: 'Community name is required', }, communityAddressRequired: { value: 'Community address is required', }, numberOfUnitsRequired: { value: 'Number of units is required', }, emailAddressRequired: { value: 'Email address is required', }, invalidEmailAddress: { value: 'Enter a valid email address', }, phoneNumberRequired: { value: 'Phone number is required', }, phoneNumberDigits: { value: 'Phone number must be 10 digits', }, optForSigning: { value: 'Please select one option', }, } const { firstName, lastName, communityName, communityAddress, numberOfUnits, emailAddress, phoneNumber, optForSigning, } = form const errors: any = {} // First Name if ( firstName.isTouched && (!firstName.value || !isValidFirsttName(firstName.value)) ) { errors['firstName'] = errorCodes?.firstNameRequired?.value || errorMessages?.firstNameRequired?.value } // Last Name if ( lastName.isTouched && (!lastName.value || !isValidLastName(lastName.value)) ) { errors['lastName'] = errorCodes?.lastNameRequired?.value || errorMessages?.lastNameRequired?.value } // Community Name if ( communityName.isTouched && (!communityName.value || !isValidCommunityName(communityName.value)) ) { errors['communityName'] = errorCodes?.communityNameRequired?.value || errorMessages?.communityNameRequired?.value } // Community Address if (communityAddress.isTouched && !communityAddress.value) { errors['communityAddress'] = errorCodes?.communityAddressRequired?.value || errorMessages?.communityAddressRequired?.value } // Number of units if (numberOfUnits.isTouched && !numberOfUnits.value) { errors['numberOfUnits'] = errorCodes?.numberOfUnitsRequired?.value || errorMessages?.numberOfUnitsRequired?.value } // Email address if (emailAddress.isTouched) { if (!emailAddress.value) { errors['emailAddress'] = errorCodes?.emailAddressRequired?.value || errorMessages?.emailAddressRequired?.value } else if (!isValidEmail(emailAddress.value)) { errors['emailAddress'] = errorCodes?.invalidEmailAddress?.value || errorMessages?.invalidEmailAddress?.value } } // Phone Number if (phoneNumber.isTouched) { if (!phoneNumber.value) { errors['phoneNumber'] = errorCodes?.phoneNumberRequired?.value || errorMessages?.phoneNumberRequired?.value } else if (!isValidMobileNumber(phoneNumber.value)) { errors['phoneNumber'] = errorCodes?.phoneNumberDigits?.value || errorMessages?.phoneNumberDigits?.value } } //optForSigning if (optForSigning.isTouched && !optForSigning.value) { errors['optForSigning'] = errorCodes?.optForSigningRequired?.value || errorMessages?.optForSigning?.value } return errors } const isFormComplete = (form: IMultifamilyForm, errors: any = {}) => { if (Object.keys(errors).length !== 0) { return false } const { firstName, lastName, communityName, communityAddress, numberOfUnits, emailAddress, phoneNumber, optForSigning, } = form const nameInputs = firstName.value && lastName.value return Boolean( nameInputs && communityName.value && communityAddress.value && numberOfUnits.value && emailAddress.value && phoneNumber.value && optForSigning.value, ) }
#In[41]:Import necessary packages import cv2 import numpy as np import matplotlib.pyplot as plt # In[42]:Read the image and convert the image into RGB image_path = 'flower.jpg' img = cv2.imread(image_path) img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # In[44]:Display the image plt.imshow(img_rgb) plt.title('Original Image') plt.axis('off') plt.show() # In[45]:Set the pixels to display the ROI hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) lower_yellow = np.array([22, 93, 0])#choose the RGB values accordingly to display specific color upper_yellow = np.array([45, 255, 255]) mask = cv2.inRange(hsv_img, lower_yellow, upper_yellow) # In[48]:Perform bit wise conjunction of the two arrays using bitwise_and segmented_image = cv2.bitwise_and(img, img, mask=mask) # In[49]:Convert the image from BGR2RGB segmented_image_rgb = cv2.cvtColor(segmented_image, cv2.COLOR_BGR2RGB) # In[50]:Display the segmented ROI from an image. plt.imshow(segmented_image_rgb) plt.title('Segmented Image (Yellow)') plt.axis('off') plt.show()
<!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>Froms in BootStrap</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script> </head> <body> <div class="container"> <h1 class="display-6 text-center text-uppercase text-primary">Zealous Registration Form</h1> <div class="row justify-content-center"> <form class="col-lg-6 col-md-9 col-sm-12 mt-4 shadow-lg bg-info "> <div class="row mt-3"> <div class="col"> <label class="form-label">Enter the name</label> <input type="text" name="user" placeholder="please enter name" class="form-control" /> </div> <div class="col"> <label class="form-label">Enter the Date</label> <input type="date" name="date" placeholder="Date please" class="form-control" /> </div> </div> <div class="form-group"> <label class="form-label">Enter the address</label> <textarea name="add" placeholder="Adress here" class="form-control"></textarea> </div> <div class="form-group"> <label class="form-label">Enter the mobileno</label> <input type="tel" name="mobile" placeholder="Number please" class="form-control" /> </div> <div class="form-group"> <label class="form-label"> Select Course</label> <select class="form-select"> <option selected hidden>Courses</option> <option>Java</option> <option>Python</option> <option>Java Script</option> </select> </div> <div class="row justify-content-between mt-4"> <label class="form-label col">Working Process</label> <div class="col"> <input type="radio" name="execution" class="form-check-input" values="Weekends" >Weekends <input type="radio" name="execution" values="Weekdays" class="form-check-input" >Weekdays </div> </div> <div class="row justify-content-center mb-3"> <button class=" col-4 btn btn-outline-success mx-4">Register</button> <button class=" col-4 btn btn-outline-danger ">Cancel</button> </div> </form> </div> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Profile Page</title> <!-- Bootstrap CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <style> body { background-color: #f8f9fa; } .navbar { background-color: #007bff; } .navbar-brand { color: white; font-weight: bold; } .nav-link { color: white; } .card { margin-top: 2rem; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } .card-title { font-weight: bold; } .btn-danger { background-color: #dc3545; border: none; } .ad-card { transition: transform 0.3s, box-shadow 0.3s; cursor: pointer; } .ad-card:hover { transform: translateY(-10px); box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); } .ad-card .card-body { padding: 1rem; } .ad-title { font-weight: bold; } .ad-price { color: green; } .ad-category { color: #007bff; } .footer { background-color: #007bff; color: white; text-align: center; padding: 1rem; position: absolute; bottom: 0; width: 100%; } </style> </head> <body> <!-- Navigation Bar --> <nav class="navbar navbar-expand-lg"> <a class="navbar-brand" href="#" onclick="window.location.href='http://localhost:8000/web_users/home'">MARKETPLACE</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-end" id="navbarNav"> <ul class="navbar-nav"> <script> // Function to get cookie value by name function getCookie(name) { var cookieName = name + "="; var decodedCookie = decodeURIComponent(document.cookie); var cookieArray = decodedCookie.split(';'); for (var i = 0; i < cookieArray.length; i++) { var cookie = cookieArray[i]; while (cookie.charAt(0) === ' ') { cookie = cookie.substring(1); } if (cookie.indexOf(cookieName) === 0) { return cookie.substring(cookieName.length, cookie.length); } } return ""; } // Get user data from cookies var userID = getCookie('userID'); var userFirstName = getCookie('userFirstName'); var userLastName = getCookie('userLastName'); var userUserName = getCookie('userUserName'); // Reference to the navbar var navbar = document.querySelector('.navbar-nav'); // Check if userID cookie exists if (userID) { // Create list item for profile link var profileItem = document.createElement('li'); profileItem.classList.add('nav-item'); // Create a link to profile page var profileLink = document.createElement('a'); profileLink.href = 'http://localhost:8000/web_users/profile/'; profileLink.classList.add('nav-link'); profileLink.textContent = 'Profile'; // Append profile link to profile item profileItem.appendChild(profileLink); // Append profile item to navbar navbar.appendChild(profileItem); } else { // Create list item and link for signup/login var listItem = document.createElement('li'); listItem.classList.add('nav-item'); var link = document.createElement('a'); link.classList.add('nav-link'); link.href = 'http://localhost:8000/web_users/'; link.textContent = 'Signup/Login'; // Append signup/login link to navbar listItem.appendChild(link); navbar.appendChild(listItem); } // Function to handle logout function handleLogout() { deleteCookie('userID'); deleteCookie('userFirstName'); deleteCookie('userLastName'); deleteCookie('userUserName'); deleteCookie('userEmail'); deleteCookie('userCreatedAt'); // Refresh the page after deleting cookies window.location.href = "http://localhost:8000/web_users/"; } // Function to delete a cookie by name function deleteCookie(name) { document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; } </script> </ul> </div> </nav> <!-- User Details Card --> <div class="container"> <div class="card"> <div class="card-body"> <h5 class="card-title">User Details</h5> <p class="card-text"><strong>First Name:</strong> <span id="firstName"></span></p> <p class="card-text"><strong>Last Name:</strong> <span id="lastName"></span></p> <p class="card-text"><strong>Username:</strong> <span id="userName"></span></p> <p class="card-text"><strong>Email:</strong> <span id="email"></span></p> <button class="btn btn-danger" onclick="handleLogout()">Logout</button> </div> </div> <!-- User Ads List --> <div class="card mt-4"> <div class="card-body"> <h5 class="card-title">My Ads</h5> <div id="adsList" class="row"> <!-- Ads will be appended here --> </div> </div> </div> </div> <!-- Bootstrap JS and jQuery (required for Bootstrap) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <!-- Script to populate user details and fetch user ads --> <script> $(document).ready(function() { // Populate user details from cookies $('#firstName').text(getCookie('userFirstName')); $('#lastName').text(getCookie('userLastName')); $('#userName').text(getCookie('userUserName')); $('#email').text(getCookie('userEmail')); // Fetch and display user ads var userID = getCookie('userID'); if (userID) { $.get('http://localhost:8000/ads/fetch_user_ads/' + userID, function(data) { var adsList = $('#adsList'); data.forEach(function(ad) { var adCard = $('<div class="col-md-4 mb-4"></div>'); var adItem = $('<div class="card ad-card"></div>'); var adBody = $('<div class="card-body"></div>'); var adTitle = $('<h5 class="ad-title card-title"></h5>').text(ad.title); var adPrice = $('<p class="ad-price card-text"></p>').text('Price: $' + ad.price); var adLocation = $('<p class="ad-location card-text"></p>').text('Location: ' + ad.location); var adCategory = $('<p class="ad-category card-text"></p>').text('Category: ' + ad.category); adBody.append(adTitle, adPrice, adLocation, adCategory); adItem.append(adBody); adCard.append(adItem); adsList.append(adCard); // Add click event to ad card adCard.on('click', function() { window.location.href = 'http://localhost:8000/web_users/ad_details/?id=' + ad.id; }); }); }); } }); </script> </body> </html>
Exercise 1. Third time’s the charm Try to reach me first Now try to reach me Exercise 3.1 Theeere arre waay too manny lettters inn theese worrdds. There are way too many letters in these words. Exercise 3.2.1 Now now there are are too too many words words. Now there are too many words. Exercise 3.2.2 Mention: Delete the second repeating word. We will be be left with with too many many spaces. We will be left with too many spaces. Exercise 3.3 Who wrote the end to this sentence twice? To this sentence twice? Who wrote the end to this sentence twice? Exercise 3.4 (1) Roses are red (1) Roses are red (2) Violets are blue (3) We learned to use Vim (3) We learned to use Vim (4) And now so will you. Exercise 3.5 Please AA ABC clean DJE DEJYG SSSJ this sentence SAS SAB SSD DDD up. Please clean this sentence up. 3.5 Note – navigating Here is a sentence for you to navigate through words. Exercise 4.1 Thee ae no enogh leters, wht languae ar yu speking? There are not enough letters, what language are you speaking? Exercise 4.2 Reminder: You can use e to navigate to the end of the next unfinished word! This sent does hav finis wor! This sentence doesn’t have finished words! Exercise 4.3 Hold on, this sentence isn’t fin Hold on, this sentence isn’t finished yet! Exercise 4.4 - Use this sentence to place the cursor and open a new line before and after it and write something. Exercise 5. - Use x to correct the sentence - Use u to undo the last command - Use U to undo all changes made to the sentence - Use Ctrl + R to redo the commands (undo the undo’s) Correect thhee mistakkess thenn usse undoo to reeplace thhem. Exercise 6. Use the command to delete a line and the put command to put the sentences in the correct order. (1) Roses are red (3) We learned to use Vim (4) And now so will you. (2) Violets are blue Exercise 7. -Replace character by character in this sentence: Somabocy dossn’t knew haw to tyye! Somebody doesn’t know how to type! - Now try replacing more characters at a time: Somebody replaced wwww words ww here! Somebody replaced some words in here! Exercise 8. Serrby, wdef is wriging thede senxjeyfh?? Seriously, who is writing these sentences?? Exercise 9. Note: Read all the instructions before doing the exercise. - Find out what line you are at (and remember what it is) - Navigate to the bottom of the file - Navigate to the top of the file - Go back to the line you were at Exercise 10. - Search for the word ‘Exercise’ - Find the word lower in the page and upper in the page - Move back and forth with Ctrl + O and Ctrl + I Exercise 11.1 Tooo bee or not tooo bee To be or not to be Exercise 11.2 - Use the substitute command to replace ‘Exercise’ in the whole file - Change it back to Exercise Exercise 12. - Find the matches for all the parentheses: ( where [ does ] ( this { parenthesis } ) end ? ) Exercise 13. - See what files you have in the current directory (reminder: the command is ls) - Make a copy of the file and save it (reminder: use the :w name command) - Check again to see if the new file is there - Remove the copy (reminder: the command is rm) Exercise 14. - Delete some of the following lines using the visual mode who wrote so many useless lines - Select the lines above (what’s left of them) and save them in a new file with the name NEW Exercise 15. - Place the text from the file NEW below: - Paste the list of files from your current directory here: (reminder: use the ls command) Exercise 16. Reminder: $ can be used to go to the end of the line. - Copy the sentence below on the other line: (1) Now there’s two of us! (2) Exercise 17. - Type :help to check how help works - Try to see how r can be used
## 国内文章 ### 一个开源轻量级的C#代码格式化工具(支持VS和VS Code) https://www.cnblogs.com/Can-daydayup/p/18164905 CSharpier是一个开源、免费的C#代码格式化工具,特点是轻量级且依赖Roslyn引擎重构代码格式。支持的IDE包括Visual Studio (2019与2022) 和 Visual Studio Code等。该项目在GitHub上托管,并被集成到C#/.NET/.NET Core优秀项目框架精选列表中。DotNetGuide技术社区也推荐使用CSharpier,并为.NET开发者提供交流与学习的平台。 ### .NET开源、功能强大、跨平台的图表库 - LiveCharts2 https://www.cnblogs.com/Can-daydayup/p/18166862 LiveCharts2是一款.NET开源图表、地图和仪表库,特点是功能强大、简单、灵活且跨平台,支持多种平台如Maui、Uno Platform等。提供在线API文档,并可以通过NuGet安装。为预发行版本,教程举例说明了如何在Blazor Wasm中创建基础柱状图和包含延迟动画的图表。 ### 【YoloDeployCsharp】基于.NET Framework的YOLO深度学习模型部署测试平台 https://www.cnblogs.com/guojin-blogs/p/18172502 该项目是一个基于.NET Framework 4.8开发的深度学习模型部署测试平台,支持YOLO系列模型(YOLOv8至YOLOv9)的图像和视频检测。模型部署采用OpenVINO™、TensorRT、ONNX runtime和OpenCV DNN引擎,在多种设备上提供推理功能。项目自行开发了OpenVINO™和TensorRT的C#接口,并在GitHub上提供源码。支持的模型包括从YOLOv5到YOLOv9以及YOLO World,通过不同的部署工具进行了算力测试。测试结果显示,在GPU上TensorRT具有较好的推理速度,而在CPU上OpenVINO表现出色。项目源码已开源于GitHub,同时提供了相关的搭建和使用教程。 ### Windows下绑定线程到指定的CPU核心 https://www.cnblogs.com/czwy/p/18166365 Windows操作系统提供了SetThreadAffinityMask和SetProcessAffinityMask两个Win32函数,用于将线程或进程绑定到指定的CPU逻辑核心上,以提高执行效率。这两个函数通过设置处理器关联掩码实现绑定,对于超过64核心的CPU需要使用SetThreadGroupAffinity。通过示例代码可以实现绑定线程到特定CPU核心并监测执行时间。这种技术可以帮助提升性能,减少缓存未命中,并且对实时系统和并发控制非常有用。但需要注意的是,如果所绑定的CPU核心已有高负荷,则可能导致性能降低。 ### 您可知道如何通过`HTTP2`实现TCP的内网穿透??? https://www.cnblogs.com/hejiale010426/p/18166935 由于服务器内部网站无法直接访问外网,需要通过申请特定端口才能访问外部IP和端口,这一过程耗时且繁琐。因此,开发了利用现有Http网关端口进行TCP服务转发的Taibai项目,这样可以避免频繁的端口申请和审批。项目中创建了Taibai.Core核心类库,其中的DelegatingStream类继承自Stream,并包装了一个内部流对象,重载了基类的读写和定位等方法,以实现特定的流操作功能。 ### .NET Emit 入门教程:第七部分:实战项目1:将 DbDataReader 转实体 https://www.cnblogs.com/cyq1162/p/18149511 通过.NET Emit中间语言编程可以提高程序性能。ORM实现分为三个阶段:初级阶段利用代码生成器生成基础增删改查代码,效率高但可维护性低;中级阶段使用反射来替代生成器,运行效率低但开发和可绑定性得提高,可通过缓存优化;高级阶段示例通过Emit和ADO.NET读取数据库数据到实体类,兼顾运行效率和可维护性。CYQ.Data的代码示例展示了如何使用Emit将DbDataReader转换到实体对象。 ### 让.NET 8 支持 Windows Vista RTM https://www.cnblogs.com/shanyou/p/18173208 Windows系统每次更新会增加许多API,导致新开源项目往往不再支持早期版本的Windows。.NET 8 AOT编译生成的程序需要Windows 7 SP1以上版本支持的三个函数,YY-Thunks项目通过动态加载和模拟API行为,解决了在旧版本Windows系统上运行程序的问题。该项目支持多种编译器和运行库,易于通过NuGet集成,最新版v1.0.10-Beta3支持了.NET 8的Native AOT。为确保项目兼容性,开发者应查阅YY-Thunks官方文档或源码。 ### C#开源的两款功能强大的录屏神器 https://www.cnblogs.com/Can-daydayup/p/18170962 ScreenToGif是由C#开发的开源屏幕录制及GIF制作工具,ShareX是基于.NET的截图、录屏软件。这两款软件均被收录在C#/.NET/.NET Core优秀项目和框架精选中,该精选旨在分享C#、.NET领域的最新动态和最佳实践。DotNetGuide技术社区提供.NET相关学习资料、技术分享、项目框架推荐等,支持开发者交流和成长。 ### 推荐3款程序员常用的画图工具 https://www.cnblogs.com/Can-daydayup/p/18169082 大姚在DotNetGuide技术社区微信群中推荐了三款程序员常用的画图工具。ProcessOn是一款支持多种图形和实时协作的在线作图工具,虽然免费版有文件数量限制,它提供了AI生成思维导图流程图等功能。Excalidraw是一款开源的虚拟协作白板,可以手绘风格绘制图表。Draw.io是一款无需注册、完全免费的在线绘图工具,适合创建多种类型的图表。这三款工具都被整理到程序员常用工具软件栏目中,供开发者选择。 ### .NET CORE 完美支持AOT 的 ORM SqlSugar 教程 https://www.cnblogs.com/sunkaixuan/p/18170061 AOT适合于工具类项目且具有启动快、禁止反编译等优点,但不适宜于反射多的业务项目。SqlSugar的AOT版本经过实践反复迭代,已支持包括CodeFirst和异步方法,并且在生产中投入使用。支持的数据库有SqlServer(需要特定配置)、MySql、Sqlite和PostgreSQL,Oracle不支持。提供了AOT下的Hello World教程和SqlSugar的简单配置,但AOT存在功能限制,不适合大型项目,只有.NET基础API支持,不支持.NET MVC。 ### .Net 8.0 下的新RPC,IceRPC之试试的新玩法&quot;打洞&quot; https://www.cnblogs.com/xlgwr/p/18169319 IceRPC技术使得防火墙无法阻碍客户端与服务端之间的通信,通过新玩法“打洞”,实现了客户端到服务端的通信模式的翻转。文章详述了IceRPC的调用机制,包括调用器invoker的获取与使用,以及如何在服务端推送通知至客户端。作者还演示了如何通过Slice接口实现服务器向客户端发送异常温度警报的推送通知功能。 ### 自动化测试数据生成:Asp.Net Core单元测试利器AutoFixture详解 https://www.cnblogs.com/ruipeng/p/18163423 AutoFixture是一个开源的.NET库,用于简化单元测试中的安排阶段,并帮助自动生成测试数据。与Bogus相比,AutoFixture的优势在于其可以自动适应类的变化,减少维护成本。AutoFixture支持与NUnit和xUnit等.NET测试框架无缝集成,并且通过Create和CreateMany方法,可以便捷地生成各种类型的测试数据实例。 ### 如何基于surging跨网关跨语言进行缓存降级 https://www.cnblogs.com/fanliang11/p/18173704 Surging是一个开源的微服务引擎,支持rpc服务治理和中间件,能够解决多语言协同研发中的配置统一和数据缓存问题。文章介绍了如何创建和使用拦截器,特别是缓存拦截器,和如何设置缓存键。还提供了如何在多语言调用中应用缓存拦截以及创建拦截模块的方法。文章解释了Surging的两种服务调用方式:接口代理调用和基于routepath调用,在基于接口的场景中,支持复杂类型参数的缓存拦截。 ### Blazor流程编排的艺术:深入Z.Blazor.Diagrams库的使用与实践 https://www.cnblogs.com/xuzeyu/p/18173547 在.NET生态中,Blazor是一个逐渐受到欢迎的前端框架。Z.Blazor.Diagrams库基于Blazor开发,可以高度自定义和扩展,帮助开发者实现流程编排。文章提到库受React图库启发,通过文档和示例帮助开发者快速理解其使用。作者介绍了如何在Blazor应用中引入ZBD,创建流程图,并自定义节点交互。 ### Asp-Net-Core开发笔记:进一步实现非侵入性审计日志功能 https://www.cnblogs.com/deali/p/18165737 该技术文章介绍了ASP.NET Core中通过应用AOP(面向切面编程)来实现动态审计日志功能的高级用法。作者对原有代码进行了重构,创建了新目录结构,并设计了EntityChangeInfo实体来保存实体变化。同时,对AuditLog对象进行了改进,使之包含更详细的操作日志信息。此外,文章还涉及了过滤器(AuditLogAttribute)的简化改进,省略了部分参数,增加了自动获取功能。 ### .Net 8.0 下的新RPC,IceRPC之使用Dev Containers进行 .NET QUIC 精简开发 https://www.cnblogs.com/xlgwr/p/18171004 本文是关于如何使用Dev Containers进行.NET的QUIC协议开发的指导文章。QUIC是一个注重性能和安全的传输协议,适合远程过程调用(RPCs)。但.NET对于QUIC的跨平台支持有限,因此通过使用Dev Containers可以解决这个问题,创建一个可移植、一致的开发环境。文章步骤详细,提供了创建和配置开发容器的详细指引。先决条件包括安装Docker和Visual Studio Code,并通过VS Code的Dev Containers扩展来构建开发容器。最后本文还展示了如何在容器中运行一个简单的QUIC服务器和客户端,以及生成服务器和客户端代码的命令。 ### .Net 8.0 下的新RPC,IceRPC之如何创建连接connection https://www.cnblogs.com/xlgwr/p/18173254 IceRPC支持创建连接,连接是其核心功能,负责发送请求和接收响应。C#中可通过ClientConnection类或ConnectionCache类创建客户端连接,操作简便且可异步连接。服务端通过Server类实例接收连接,并可监听配置的地址上的新连接。连接既支持客户端也支持服务端,且无区别使用同一API。作者强调实践重要性,建议持续练习以提升技能,并欢迎交流。 ### .Net 8.0 下的新RPC,IceRPC之&quot;请求&quot;生命线意义非凡 https://www.cnblogs.com/xlgwr/p/18170054 本文讨论了在RPC(远程过程调用)系统中加入请求截止时间的重要性,以及不设截止时间可能给分布式系统带来的负面影响。文章解释了超时与截止时间的区别,并强调了在实现强健的分布式系统时,设置适当的截止时间的意义。基于截止时间的机制可以通过拦截器和中间件以灵活的方式在IceRPC中实现,提升了性能和可靠性。 ### Unity 热更--AssetBundle学习笔记 1.0【AB包资源加载工具类的实现】 https://www.cnblogs.com/TonyCode/p/18170759 这篇文章主要介绍了如何封装工具类来管理AssetBundle资源的加载。首先实现了一个确保AB资源包只加载一次的LoadAssetBundleManager单例类,采用Dictionary来记录加载的资源。文章还讲解了如何灵活获取主包路径、加载依赖包以及实现异步和同步加载资源的方法。最后,提供了卸载单个及所有AB资源包的功能。 ### C#的基于.net framework的Dll模块编程(五) - 编程手把手系列文章 https://www.cnblogs.com/lzhdim/p/18148913 本文介绍了在C#环境中使用DLL类库的三种方法:静态类、动态类和窗体,只需要引用类库并声明命名空间即可使用。同时也阐述了如何使用其他C# DLL库,方法与前述相同。针对VC++的DLL,需声明函数定义后方可使用,并给出了调用Windows API函数的例子。提供了示例下载链接。 ## 主题 ### 宣布推出第一个真正适用于移动、Web、桌面和嵌入式应用程序的 .NET 单一项目 https://platform.uno/blog/the-first-and-only-true-single-project-for-mobile-web-desktop-and-embedded-in-net/ Uno平台5.2已发布。 此版本包括对 Skia 渲染器的增强,以实现更好的性能、多窗口支持、对 Uno SDK 的改进、对 .NET 9 预览版的支持等。 此外,项目模板已更新,因此单个项目现在可以支持所有平台。 - [发布 5.2.80 · unoplatform/uno](https://github.com/unoplatform/uno/releases/tag/5.2.80) ### 版本 2.3.7 · mysql-net/MySqlConnector https://github.com/mysql-net/MySqlConnector/releases/tag/2.3.7 MySqlConnector 2.3.7 已发布。 此版本修复了多个错误。 ### .NET Aspire 预览版 6 - .NET Aspire https://learn.microsoft.com/en-us/dotnet/aspire/whats-new/preview-6 .NET Aspire 预览版 6 已发布。 此版本包括删除和修改过时的 API、Aspire 仪表板的令牌身份验证、对 Qdrant 矢量数据库的支持以及其他细微更改。 ### 介绍 Elastic 的 OpenTelemetry SDK for .NET https://www.elastic.co/jp/blog/elastic-opentelemetry-distribution-dotnet-applications Elastic .NET OpenTelemetry SDK 的 Alpha 版本现已推出。 Elastic OpenTelemetry 发行版包括 Elastic 的 OpenTelemetry 的默认配置以及使用 OpenTelemetry SDK 的扩展。当前的 alpha 版本与普通版本几乎没有区别,但计划在未来添加更多功能。 ### 使用 .NET 为 Microsoft AI 构建可扩展网关 - .NET 博客 https://devblogs.microsoft.com/dotnet/building-a-scalable-gateway-for-microsoft-ai/ 使用 .NET 和 YARP 为 Microsoft 的 Bing 和 Copilot 等 AI 服务构建前端网关的案例研究。 本文介绍了利用 YARP 灵活配置(例如镜像、速率限制和动态配置更改)的示例。 ### 发布 v8.1.0 · dotnet/orleans https://github.com/dotnet/orleans/releases/tag/v8.1.0 Orleans v8.1.0 已发布。 此版本支持与 Aspire 集成,并包含各种修复和改进。 ## 文章、幻灯片等 ### 在 C# 中使用异步检测阻塞调用 | James Crosswell | 代码博客 https://www.jamescrosswell.dev/posts/async-detecting-blocking-calls 如何调查异步方法中的阻塞调用。 文章介绍了使用Ben.BlockingDetector进行检测,并将其合并到Sentry中,以便可以在Sentry上进行确认。 ### .NET 正则表达式 - 捕获 https://zenn.dev/sayurin/articles/76f6739d7ac75f 关于在 .NET 正则表达式中进行捕获。 当有多个命名捕获时该怎么办,如何在 F# 中自然地处理命名捕获等。 ### 使用主构造函数重构 C# 代码 - .NET 博客 https://devblogs.microsoft.com/dotnet/csharp-primary-constructors-refactoring/ 关于使用主构造函数进行重构。 本文介绍了一个示例,将构造函数中传递 ILogger 等内容的模式替换为主构造函数。 ### 组装 .NET 的 AsciiMath 解析器 https://andrewlock.net/hacking-together-an-asciimath-parser-for-dotnet/ 如何使用 .NET 中的 AsciiMath 解析器。 本文介绍了多种语言的 AsciiMath 解析器,并解释了如何最终使用 Jint 让 JavaScript 实现可从 .NET 运行。 ### 配置 ASP.NET Core Minimal API 以进行生产和大规模使用 - Qiita https://qiita.com/takashiuesaka/items/654c6e0d0bb7c92854a8 介绍使用 ASP.NET Core Minimal API 定义和实现 API 时组织代码的技术(翻译)。使用扩展方法进行聚合、使用MapGroup进行分组等。 - [组织 ASP.NET Core 最小 API](https://www.tessferrandez.com/blog/2023/10/31/organizing-minimal-apis.html) ### 如何在 OpenTelemetry 中的两个跨度之间创建链接 https://dev.to/koma_koma_d/how-to-create-a-link-between-two-spans-in-opentelemetry-424i 关于如何创建连接 OpenTelemetry 跨度的跨度链接。 ### [JWT] 如何解决解码过程中出现的 Unable to demo the payload 错误 https://zenn.dev/o0rororo0o/articles/028202490cc99d 对于 Microsoft.AspNetCore.Authentication.JwtBearer 7.0.14 或更高版本,如果 JWT iat 字段为非数字,则会发生错误。 ### 使用 SearchValues 优化 C# 中的字符串搜索 https://dev.to/admirmujkic/optimizing-string-searches-in-c-with-searchvalues-1105 关于“SearchValues”类的用法和性能,该类是在.NET 8中添加的,可以专门定义用于搜索特定值。 ### ReSharper 和 Rider 2024.1 的第一组错误修复已发布 | .NET 工具博客 https://blog.jetbrains.com/dotnet/2024/04/17/the-first-set-of-bug-fixes-for-resharper-and-rider-2024-1-are-here/ ReSharper 和 Rider 2024.1.1 已发布。 此版本是 ReSharper 和 Rider 2024.1 的第一个错误修复,修复了一些小缺陷。 ### itsmattkc/dotnet9x:.NET 2.0 - 3.5 向后移植到 Windows 9x https://github.com/itsmattkc/dotnet9x 尝试将 .NET Framework 2.0-3.5 向后移植到 Windows 9x 的项目。 -[[Yajiuma PC Watch]将.NET Framework反向移植到Windows 95的强者出现了](https://pc.watch.impress.co.jp/docs/news/yajiuma/1584811.html) ### Visual Studio 会迁移到 .NET Core 并成为多平台吗? - NDepend 博客 https://blog.ndepend.com/visual-studio-multi-platform/ 为了考虑 Visual Studio 是否会转换为 .NET CoreCLR,我们正在对 Visual Studio 当前的程序集结构进行调查和假设。 ## 活动 ### C#性能学习会(2024/04/27 13:30~) https://cs-reading.connpass.com/event/309714/ ### 现代 C# .NET Web 开发 ~ gRPC、GraphQL、Blazor 也可用 ~ (2024/05/15 19:00~) https://sansan.connpass.com/event/316664/ ## 库、存储库、工具等。 ### Cysharp/KcpTransport:KcpTransport 是 RUDP 的纯 C# 实现,用于高性能实时网络通信 https://github.com/Cysharp/KcpTransport [KCP](https://github.com/skywind3000/kcp/blob/master/README.en.md) 的 .NET 移植实现(基于 UDP 的 RUDP 类协议)。 ## 网站、文档等 ### 推文 当一个局部函数被编译成IL时,它就变成了一个名称以“g_”开头的方法,但是关于“g_”。 https://x.com/khyperia/status/1782787967703998667?s=12 `IList<T>` 可能会变成 `IReadOnlyList<T>` 的故事。 https://x.com/terrajobst/status/1782922704997498982?s=12 ## 深入探索 ### List Add 在 `net9.0 Preview 3` 中比在 `net8.0` 中慢得多(几乎是 3 倍) · Issue #101437 · dotnet/runtime https://github.com/dotnet/runtime/issues/101437 ### 关于 .NET 9 List 由于 JIT 更改而可能变慢的问题。目前,这种情况仅发生在 Apple Silicon (Arm64) 上。 https://x.com/davidfowl/status/1782961890580414894?s=12 ## 版权声明 * 国内板块由 InCerry 进行整理 : https://github.com/InCerryGit/WeekRef.NET * 其余内容来自 Myuki WeekRef,由InCerry翻译(已获得授权) : https://github.com/mayuki/WeekRef.NET **由于笔者没有那么多时间对国内的一些文章进行整理,欢迎大家为《.NET周刊-国内文章》板块进行贡献,需要推广自己的文章或者框架、开源项目可以下方的项目地址提交Issue或者在我的微信公众号私信。** 格式如下: * 10~50字左右的标题 * 对应文章或项目网址访问链接 * 200字以内的简介,如果太长会影响阅读体验 https://github.com/InCerryGit/.NET-Weekly ## .NET性能优化交流群 相信大家在开发中经常会遇到一些性能问题,苦于没有有效的工具去发现性能瓶颈,或者是发现瓶颈以后不知道该如何优化。之前一直有读者朋友询问有没有技术交流群,但是由于各种原因一直都没创建,现在很高兴的在这里宣布,我创建了一个专门交流.NET性能优化经验的群组,主题包括但不限于: * 如何找到.NET性能瓶颈,如使用APM、dotnet tools等工具 * .NET框架底层原理的实现,如垃圾回收器、JIT等等 * 如何编写高性能的.NET代码,哪些地方存在性能陷阱 希望能有更多志同道合朋友加入,分享一些工作中遇到的.NET性能问题和宝贵的性能分析优化经验。**目前一群已满,现在开放二群。** 如果提示已经达到200人,可以加我微信,我拉你进群: **ls1075** 另外也创建了**QQ群**,群号: 687779078,欢迎大家加入。 ![image-20230703203249615](./assets/2024-05-05/image-20230703203249615.png)
package arbtest import ( "context" "encoding/binary" "errors" "fmt" "math/big" "strings" "sync" "testing" "time" "github.com/ethereum/go-ethereum/arbitrum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/trie" "github.com/offchainlabs/nitro/arbnode" "github.com/offchainlabs/nitro/execution/gethexec" "github.com/offchainlabs/nitro/util" ) func makeSomeTransfers(t *testing.T, ctx context.Context, builder *NodeBuilder, txCount uint64) { var txs []*types.Transaction for i := uint64(0); i < txCount; i++ { tx := builder.L2Info.PrepareTx("Owner", "User2", builder.L2Info.TransferGas, common.Big1, nil) txs = append(txs, tx) err := builder.L2.Client.SendTransaction(ctx, tx) Require(t, err) } for _, tx := range txs { _, err := builder.L2.EnsureTxSucceeded(tx) Require(t, err) } } func prepareNodeWithHistory(t *testing.T, ctx context.Context, execConfig *gethexec.Config, txCount uint64) (*NodeBuilder, func()) { t.Helper() builder := NewNodeBuilder(ctx).DefaultConfig(t, true) builder.execConfig = execConfig cleanup := builder.Build(t) builder.L2Info.GenerateAccount("User2") makeSomeTransfers(t, ctx, builder, txCount) return builder, cleanup } func fillHeaderCache(t *testing.T, bc *core.BlockChain, from, to uint64) { t.Helper() for i := from; i <= to; i++ { header := bc.GetHeaderByNumber(i) if header == nil { Fatal(t, "internal test error - failed to get header while trying to fill headerCache, header:", i) } } } func fillBlockCache(t *testing.T, bc *core.BlockChain, from, to uint64) { t.Helper() for i := from; i <= to; i++ { block := bc.GetBlockByNumber(i) if block == nil { Fatal(t, "internal test error - failed to get block while trying to fill blockCache, block:", i) } } } func removeStatesFromDb(t *testing.T, bc *core.BlockChain, db ethdb.Database, from, to uint64) { t.Helper() for i := from; i <= to; i++ { header := bc.GetHeaderByNumber(i) if header == nil { Fatal(t, "failed to get last block header") } hash := header.Root err := db.Delete(hash.Bytes()) Require(t, err) } for i := from; i <= to; i++ { header := bc.GetHeaderByNumber(i) _, err := bc.StateAt(header.Root) if err == nil { Fatal(t, "internal test error - failed to remove state from db") } expectedErr := &trie.MissingNodeError{} if !errors.As(err, &expectedErr) { Fatal(t, "internal test error - failed to remove state from db, err: ", err) } } } func TestRecreateStateForRPCNoDepthLimit(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() execConfig := gethexec.ConfigDefaultTest() execConfig.RPC.MaxRecreateStateDepth = arbitrum.InfiniteMaxRecreateStateDepth execConfig.Sequencer.MaxBlockSpeed = 0 execConfig.Sequencer.MaxTxDataSize = 150 // 1 test tx ~= 110 execConfig.Caching.Archive = true execConfig.Caching.SnapshotCache = 0 // disable snapshots // disable trie/Database.cleans cache, so as states removed from ChainDb won't be cached there execConfig.Caching.TrieCleanCache = 0 execConfig.Caching.MaxNumberOfBlocksToSkipStateSaving = 0 execConfig.Caching.MaxAmountOfGasToSkipStateSaving = 0 builder, cancelNode := prepareNodeWithHistory(t, ctx, execConfig, 32) defer cancelNode() execNode, l2client := builder.L2.ExecNode, builder.L2.Client bc := execNode.Backend.ArbInterface().BlockChain() db := execNode.Backend.ChainDb() lastBlock, err := l2client.BlockNumber(ctx) Require(t, err) middleBlock := lastBlock / 2 expectedBalance, err := l2client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(lastBlock)) Require(t, err) removeStatesFromDb(t, bc, db, middleBlock, lastBlock) balance, err := l2client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(lastBlock)) Require(t, err) if balance.Cmp(expectedBalance) != 0 { Fatal(t, "unexpected balance result for last block, want: ", expectedBalance, " have: ", balance) } } func TestRecreateStateForRPCBigEnoughDepthLimit(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() depthGasLimit := int64(256 * util.NormalizeL2GasForL1GasInitial(800_000, params.GWei)) execConfig := gethexec.ConfigDefaultTest() execConfig.RPC.MaxRecreateStateDepth = depthGasLimit execConfig.Sequencer.MaxBlockSpeed = 0 execConfig.Sequencer.MaxTxDataSize = 150 // 1 test tx ~= 110 execConfig.Caching.Archive = true // disable trie/Database.cleans cache, so as states removed from ChainDb won't be cached there execConfig.Caching.TrieCleanCache = 0 execConfig.Caching.MaxNumberOfBlocksToSkipStateSaving = 0 execConfig.Caching.MaxAmountOfGasToSkipStateSaving = 0 builder, cancelNode := prepareNodeWithHistory(t, ctx, execConfig, 32) defer cancelNode() execNode, l2client := builder.L2.ExecNode, builder.L2.Client bc := execNode.Backend.ArbInterface().BlockChain() db := execNode.Backend.ChainDb() lastBlock, err := l2client.BlockNumber(ctx) Require(t, err) middleBlock := lastBlock / 2 expectedBalance, err := l2client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(lastBlock)) Require(t, err) removeStatesFromDb(t, bc, db, middleBlock, lastBlock) balance, err := l2client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(lastBlock)) Require(t, err) if balance.Cmp(expectedBalance) != 0 { Fatal(t, "unexpected balance result for last block, want: ", expectedBalance, " have: ", balance) } } func TestRecreateStateForRPCDepthLimitExceeded(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() execConfig := gethexec.ConfigDefaultTest() execConfig.RPC.MaxRecreateStateDepth = int64(200) execConfig.Sequencer.MaxBlockSpeed = 0 execConfig.Sequencer.MaxTxDataSize = 150 // 1 test tx ~= 110 execConfig.Caching.Archive = true // disable trie/Database.cleans cache, so as states removed from ChainDb won't be cached there execConfig.Caching.TrieCleanCache = 0 execConfig.Caching.MaxNumberOfBlocksToSkipStateSaving = 0 execConfig.Caching.MaxAmountOfGasToSkipStateSaving = 0 builder, cancelNode := prepareNodeWithHistory(t, ctx, execConfig, 32) defer cancelNode() execNode, l2client := builder.L2.ExecNode, builder.L2.Client bc := execNode.Backend.ArbInterface().BlockChain() db := execNode.Backend.ChainDb() lastBlock, err := l2client.BlockNumber(ctx) Require(t, err) middleBlock := lastBlock / 2 removeStatesFromDb(t, bc, db, middleBlock, lastBlock) _, err = l2client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(lastBlock)) if err == nil { Fatal(t, "Didn't fail as expected") } if err.Error() != arbitrum.ErrDepthLimitExceeded.Error() { Fatal(t, "Failed with unexpected error:", err) } } func TestRecreateStateForRPCMissingBlockParent(t *testing.T) { // HeaderChain.headerCache size limit is currently core.headerCacheLimit = 512 var headerCacheLimit uint64 = 512 ctx, cancel := context.WithCancel(context.Background()) defer cancel() execConfig := gethexec.ConfigDefaultTest() execConfig.RPC.MaxRecreateStateDepth = arbitrum.InfiniteMaxRecreateStateDepth execConfig.Sequencer.MaxBlockSpeed = 0 execConfig.Sequencer.MaxTxDataSize = 150 // 1 test tx ~= 110 execConfig.Caching.Archive = true // disable trie/Database.cleans cache, so as states removed from ChainDb won't be cached there execConfig.Caching.TrieCleanCache = 0 execConfig.Caching.MaxNumberOfBlocksToSkipStateSaving = 0 execConfig.Caching.MaxAmountOfGasToSkipStateSaving = 0 builder, cancelNode := prepareNodeWithHistory(t, ctx, execConfig, headerCacheLimit+5) defer cancelNode() execNode, l2client := builder.L2.ExecNode, builder.L2.Client bc := execNode.Backend.ArbInterface().BlockChain() db := execNode.Backend.ChainDb() lastBlock, err := l2client.BlockNumber(ctx) Require(t, err) if lastBlock < headerCacheLimit+4 { Fatal(t, "Internal test error - not enough blocks produced during preparation, want:", headerCacheLimit, "have:", lastBlock) } removeStatesFromDb(t, bc, db, lastBlock-4, lastBlock) headerToRemove := lastBlock - 4 hash := rawdb.ReadCanonicalHash(db, headerToRemove) rawdb.DeleteHeader(db, hash, headerToRemove) firstBlock := lastBlock - headerCacheLimit - 5 fillHeaderCache(t, bc, firstBlock, firstBlock+headerCacheLimit) for i := lastBlock; i > lastBlock-3; i-- { _, err = l2client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(i)) if err == nil { hash := rawdb.ReadCanonicalHash(db, i) Fatal(t, "Didn't fail to get balance at block:", i, " with hash:", hash, ", lastBlock:", lastBlock) } if !strings.Contains(err.Error(), "chain doesn't contain parent of block") { Fatal(t, "Failed with unexpected error: \"", err, "\", at block:", i, "lastBlock:", lastBlock) } } } func TestRecreateStateForRPCBeyondGenesis(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() execConfig := gethexec.ConfigDefaultTest() execConfig.RPC.MaxRecreateStateDepth = arbitrum.InfiniteMaxRecreateStateDepth execConfig.Sequencer.MaxBlockSpeed = 0 execConfig.Sequencer.MaxTxDataSize = 150 // 1 test tx ~= 110 execConfig.Caching.Archive = true // disable trie/Database.cleans cache, so as states removed from ChainDb won't be cached there execConfig.Caching.TrieCleanCache = 0 execConfig.Caching.MaxNumberOfBlocksToSkipStateSaving = 0 execConfig.Caching.MaxAmountOfGasToSkipStateSaving = 0 builder, cancelNode := prepareNodeWithHistory(t, ctx, execConfig, 32) execNode, l2client := builder.L2.ExecNode, builder.L2.Client defer cancelNode() bc := execNode.Backend.ArbInterface().BlockChain() db := execNode.Backend.ChainDb() lastBlock, err := l2client.BlockNumber(ctx) Require(t, err) genesis := bc.Config().ArbitrumChainParams.GenesisBlockNum removeStatesFromDb(t, bc, db, genesis, lastBlock) _, err = l2client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(lastBlock)) if err == nil { hash := rawdb.ReadCanonicalHash(db, lastBlock) Fatal(t, "Didn't fail to get balance at block:", lastBlock, " with hash:", hash, ", lastBlock:", lastBlock) } if !strings.Contains(err.Error(), "moved beyond genesis") { Fatal(t, "Failed with unexpected error: \"", err, "\", at block:", lastBlock, "lastBlock:", lastBlock) } } func TestRecreateStateForRPCBlockNotFoundWhileRecreating(t *testing.T) { // BlockChain.blockCache size limit is currently core.blockCacheLimit = 256 var blockCacheLimit uint64 = 256 ctx, cancel := context.WithCancel(context.Background()) defer cancel() execConfig := gethexec.ConfigDefaultTest() execConfig.RPC.MaxRecreateStateDepth = arbitrum.InfiniteMaxRecreateStateDepth execConfig.Sequencer.MaxBlockSpeed = 0 execConfig.Sequencer.MaxTxDataSize = 150 // 1 test tx ~= 110 execConfig.Caching.Archive = true // disable trie/Database.cleans cache, so as states removed from ChainDb won't be cached there execConfig.Caching.TrieCleanCache = 0 execConfig.Caching.MaxNumberOfBlocksToSkipStateSaving = 0 execConfig.Caching.MaxAmountOfGasToSkipStateSaving = 0 builder, cancelNode := prepareNodeWithHistory(t, ctx, execConfig, blockCacheLimit+4) execNode, l2client := builder.L2.ExecNode, builder.L2.Client defer cancelNode() bc := execNode.Backend.ArbInterface().BlockChain() db := execNode.Backend.ChainDb() lastBlock, err := l2client.BlockNumber(ctx) Require(t, err) if lastBlock < blockCacheLimit+4 { Fatal(t, "Internal test error - not enough blocks produced during preparation, want:", blockCacheLimit, "have:", lastBlock) } removeStatesFromDb(t, bc, db, lastBlock-4, lastBlock) blockBodyToRemove := lastBlock - 1 hash := rawdb.ReadCanonicalHash(db, blockBodyToRemove) rawdb.DeleteBody(db, hash, blockBodyToRemove) firstBlock := lastBlock - blockCacheLimit - 4 fillBlockCache(t, bc, firstBlock, firstBlock+blockCacheLimit) _, err = l2client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(lastBlock)) if err == nil { hash := rawdb.ReadCanonicalHash(db, lastBlock) Fatal(t, "Didn't fail to get balance at block:", lastBlock, " with hash:", hash, ", lastBlock:", lastBlock) } if !strings.Contains(err.Error(), fmt.Sprintf("block #%d not found", blockBodyToRemove)) { Fatal(t, "Failed with unexpected error: \"", err, "\", at block:", lastBlock, "lastBlock:", lastBlock) } } func testSkippingSavingStateAndRecreatingAfterRestart(t *testing.T, cacheConfig *gethexec.CachingConfig, txCount int) { maxRecreateStateDepth := int64(30 * 1000 * 1000) ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctx1, cancel1 := context.WithCancel(ctx) execConfig := gethexec.ConfigDefaultTest() execConfig.RPC.MaxRecreateStateDepth = maxRecreateStateDepth execConfig.Sequencer.MaxBlockSpeed = 0 execConfig.Sequencer.MaxTxDataSize = 150 // 1 test tx ~= 110 execConfig.Caching = *cacheConfig skipBlocks := execConfig.Caching.MaxNumberOfBlocksToSkipStateSaving skipGas := execConfig.Caching.MaxAmountOfGasToSkipStateSaving feedErrChan := make(chan error, 10) l2info, stack, chainDb, arbDb, blockchain := createL2BlockChain(t, nil, t.TempDir(), params.ArbitrumDevTestChainConfig(), &execConfig.Caching) Require(t, execConfig.Validate()) execConfigFetcher := func() *gethexec.Config { return execConfig } execNode, err := gethexec.CreateExecutionNode(ctx1, stack, chainDb, blockchain, nil, execConfigFetcher) Require(t, err) parentChainID := big.NewInt(1337) node, err := arbnode.CreateNode(ctx1, stack, execNode, arbDb, NewFetcherFromConfig(arbnode.ConfigDefaultL2Test()), blockchain.Config(), nil, nil, nil, nil, nil, feedErrChan, parentChainID, nil) Require(t, err) err = node.TxStreamer.AddFakeInitMessage() Require(t, err) Require(t, node.Start(ctx1)) client := ClientForStack(t, stack) StartWatchChanErr(t, ctx, feedErrChan, node) dataDir := node.Stack.DataDir() l2info.GenerateAccount("User2") var txs []*types.Transaction for i := 0; i < txCount; i++ { tx := l2info.PrepareTx("Owner", "User2", l2info.TransferGas, common.Big1, nil) txs = append(txs, tx) err := client.SendTransaction(ctx, tx) Require(t, err) receipt, err := EnsureTxSucceeded(ctx, client, tx) Require(t, err) if have, want := receipt.BlockNumber.Uint64(), uint64(i)+1; have != want { Fatal(t, "internal test error - tx got included in unexpected block number, have:", have, "want:", want) } } bc := execNode.Backend.ArbInterface().BlockChain() genesis := uint64(0) currentHeader := bc.CurrentBlock() if currentHeader == nil { Fatal(t, "missing current block") } lastBlock := currentHeader.Number.Uint64() if want := genesis + uint64(txCount); lastBlock < want { Fatal(t, "internal test error - not enough blocks produced during preparation, want:", want, "have:", lastBlock) } expectedBalance, err := client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(lastBlock)) Require(t, err) node.StopAndWait() cancel1() t.Log("stopped first node") l2info, stack, chainDb, arbDb, blockchain = createL2BlockChain(t, l2info, dataDir, params.ArbitrumDevTestChainConfig(), &execConfig.Caching) execNode, err = gethexec.CreateExecutionNode(ctx1, stack, chainDb, blockchain, nil, execConfigFetcher) Require(t, err) node, err = arbnode.CreateNode(ctx, stack, execNode, arbDb, NewFetcherFromConfig(arbnode.ConfigDefaultL2Test()), blockchain.Config(), nil, node.DeployInfo, nil, nil, nil, feedErrChan, parentChainID, nil) Require(t, err) Require(t, node.Start(ctx)) client = ClientForStack(t, stack) defer node.StopAndWait() bc = execNode.Backend.ArbInterface().BlockChain() gas := skipGas blocks := skipBlocks for i := genesis + 1; i <= genesis+uint64(txCount); i++ { block := bc.GetBlockByNumber(i) if block == nil { Fatal(t, "header not found for block number:", i) continue } gas += block.GasUsed() _, err := bc.StateAt(block.Root()) blocks++ if (skipBlocks == 0 && skipGas == 0) || (skipBlocks != 0 && blocks > skipBlocks) || (skipGas != 0 && gas > skipGas) { if err != nil { t.Log("blocks:", blocks, "skipBlocks:", skipBlocks, "gas:", gas, "skipGas:", skipGas) } Require(t, err, "state not found, root:", block.Root(), "blockNumber:", i, "blockHash", block.Hash(), "err:", err) gas = 0 blocks = 0 } else { if int(i) >= int(lastBlock)-int(cacheConfig.BlockCount) { // skipping nonexistence check - the state might have been saved on node shutdown continue } if err == nil { t.Log("blocks:", blocks, "skipBlocks:", skipBlocks, "gas:", gas, "skipGas:", skipGas) Fatal(t, "state shouldn't be available, root:", block.Root(), "blockNumber:", i, "blockHash", block.Hash()) } expectedErr := &trie.MissingNodeError{} if !errors.As(err, &expectedErr) { Fatal(t, "getting state failed with unexpected error, root:", block.Root(), "blockNumber:", i, "blockHash:", block.Hash(), "err:", err) } } } for i := genesis + 1; i <= genesis+uint64(txCount); i += i % 10 { _, err = client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(i)) if err != nil { t.Log("skipBlocks:", skipBlocks, "skipGas:", skipGas) } Require(t, err) } balance, err := client.BalanceAt(ctx, GetTestAddressForAccountName(t, "User2"), new(big.Int).SetUint64(lastBlock)) Require(t, err) if balance.Cmp(expectedBalance) != 0 { Fatal(t, "unexpected balance result for last block, want: ", expectedBalance, " have: ", balance) } } func TestSkippingSavingStateAndRecreatingAfterRestart(t *testing.T) { cacheConfig := gethexec.TestCachingConfig cacheConfig.Archive = true cacheConfig.SnapshotCache = 0 // disable snapshots cacheConfig.BlockAge = 0 // use only Caching.BlockCount to keep only last N blocks in dirties cache, no matter how new they are // test defaults testSkippingSavingStateAndRecreatingAfterRestart(t, &cacheConfig, 512) cacheConfig.MaxNumberOfBlocksToSkipStateSaving = 127 cacheConfig.MaxAmountOfGasToSkipStateSaving = 0 testSkippingSavingStateAndRecreatingAfterRestart(t, &cacheConfig, 512) cacheConfig.MaxNumberOfBlocksToSkipStateSaving = 0 cacheConfig.MaxAmountOfGasToSkipStateSaving = 15 * 1000 * 1000 testSkippingSavingStateAndRecreatingAfterRestart(t, &cacheConfig, 512) cacheConfig.MaxNumberOfBlocksToSkipStateSaving = 127 cacheConfig.MaxAmountOfGasToSkipStateSaving = 15 * 1000 * 1000 testSkippingSavingStateAndRecreatingAfterRestart(t, &cacheConfig, 512) // lower number of blocks in triegc below 100 blocks, to be able to check for nonexistence in testSkippingSavingStateAndRecreatingAfterRestart (it doesn't check last BlockCount blocks as some of them may be persisted on node shutdown) cacheConfig.BlockCount = 16 testBlockGas := uint64(925000) // one test block ~ 925000 gas skipBlockValues := []uint64{0, 1, 2, 3, 5, 21, 51, 100, 101} var skipGasValues []uint64 for _, i := range skipBlockValues { skipGasValues = append(skipGasValues, i*testBlockGas) } for _, skipGas := range skipGasValues { for _, skipBlocks := range skipBlockValues[:len(skipBlockValues)-2] { cacheConfig.MaxAmountOfGasToSkipStateSaving = skipGas cacheConfig.MaxNumberOfBlocksToSkipStateSaving = uint32(skipBlocks) testSkippingSavingStateAndRecreatingAfterRestart(t, &cacheConfig, 100) } } } func TestGettingStateForRPCFullNode(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() execConfig := gethexec.ConfigDefaultTest() execConfig.Caching.SnapshotCache = 0 // disable snapshots execConfig.Caching.BlockAge = 0 // use only Caching.BlockCount to keep only last N blocks in dirties cache, no matter how new they are execConfig.Sequencer.MaxBlockSpeed = 0 execConfig.Sequencer.MaxTxDataSize = 150 // 1 test tx ~= 110 builder, cancelNode := prepareNodeWithHistory(t, ctx, execConfig, 16) execNode, _ := builder.L2.ExecNode, builder.L2.Client defer cancelNode() bc := execNode.Backend.ArbInterface().BlockChain() api := execNode.Backend.APIBackend() header := bc.CurrentBlock() if header == nil { Fatal(t, "failed to get current block header") } state, _, err := api.StateAndHeaderByNumber(ctx, rpc.BlockNumber(header.Number.Uint64())) Require(t, err) addr := builder.L2Info.GetAddress("User2") exists := state.Exist(addr) err = state.Error() Require(t, err) if !exists { Fatal(t, "User2 address does not exist in the state") } // Get the state again to avoid caching state, _, err = api.StateAndHeaderByNumber(ctx, rpc.BlockNumber(header.Number.Uint64())) Require(t, err) blockCountRequiredToFlushDirties := builder.execConfig.Caching.BlockCount makeSomeTransfers(t, ctx, builder, blockCountRequiredToFlushDirties) exists = state.Exist(addr) err = state.Error() Require(t, err) if !exists { Fatal(t, "User2 address does not exist in the state") } } func TestGettingStateForRPCHybridArchiveNode(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() execConfig := gethexec.ConfigDefaultTest() execConfig.Caching.Archive = true execConfig.Caching.MaxNumberOfBlocksToSkipStateSaving = 128 execConfig.Caching.BlockCount = 128 execConfig.Caching.SnapshotCache = 0 // disable snapshots execConfig.Caching.BlockAge = 0 // use only Caching.BlockCount to keep only last N blocks in dirties cache, no matter how new they are execConfig.Sequencer.MaxBlockSpeed = 0 execConfig.Sequencer.MaxTxDataSize = 150 // 1 test tx ~= 110 builder, cancelNode := prepareNodeWithHistory(t, ctx, execConfig, 16) execNode, _ := builder.L2.ExecNode, builder.L2.Client defer cancelNode() bc := execNode.Backend.ArbInterface().BlockChain() api := execNode.Backend.APIBackend() header := bc.CurrentBlock() if header == nil { Fatal(t, "failed to get current block header") } state, _, err := api.StateAndHeaderByNumber(ctx, rpc.BlockNumber(header.Number.Uint64())) Require(t, err) addr := builder.L2Info.GetAddress("User2") exists := state.Exist(addr) err = state.Error() Require(t, err) if !exists { Fatal(t, "User2 address does not exist in the state") } // Get the state again to avoid caching state, _, err = api.StateAndHeaderByNumber(ctx, rpc.BlockNumber(header.Number.Uint64())) Require(t, err) blockCountRequiredToFlushDirties := builder.execConfig.Caching.BlockCount makeSomeTransfers(t, ctx, builder, blockCountRequiredToFlushDirties) exists = state.Exist(addr) err = state.Error() Require(t, err) if !exists { Fatal(t, "User2 address does not exist in the state") } } func TestStateAndHeaderForRecentBlock(t *testing.T) { threads := 32 ctx, cancel := context.WithCancel(context.Background()) defer cancel() builder := NewNodeBuilder(ctx).DefaultConfig(t, true) builder.execConfig.Caching.Archive = true builder.execConfig.RPC.MaxRecreateStateDepth = 0 cleanup := builder.Build(t) defer cleanup() builder.L2Info.GenerateAccount("User2") errors := make(chan error, threads+1) senderDone := make(chan struct{}) go func() { defer close(senderDone) for ctx.Err() == nil { tx := builder.L2Info.PrepareTx("Owner", "User2", builder.L2Info.TransferGas, new(big.Int).Lsh(big.NewInt(1), 128), nil) err := builder.L2.Client.SendTransaction(ctx, tx) if ctx.Err() != nil { return } if err != nil { errors <- err return } _, err = builder.L2.EnsureTxSucceeded(tx) if ctx.Err() != nil { return } if err != nil { errors <- err return } time.Sleep(10 * time.Millisecond) } }() api := builder.L2.ExecNode.Backend.APIBackend() db := builder.L2.ExecNode.Backend.ChainDb() i := 1 var mtx sync.RWMutex var wgCallers sync.WaitGroup for j := 0; j < threads && ctx.Err() == nil; j++ { wgCallers.Add(1) go func() { defer wgCallers.Done() mtx.RLock() blockNumber := i mtx.RUnlock() for blockNumber < 300 && ctx.Err() == nil { prefix := make([]byte, 8) binary.BigEndian.PutUint64(prefix, uint64(blockNumber)) prefix = append([]byte("b"), prefix...) it := db.NewIterator(prefix, nil) defer it.Release() if it.Next() { key := it.Key() if len(key) != len(prefix)+common.HashLength { Fatal(t, "Wrong key length, have:", len(key), "want:", len(prefix)+common.HashLength) } blockHash := common.BytesToHash(key[len(prefix):]) start := time.Now() for ctx.Err() == nil { _, _, err := api.StateAndHeaderByNumberOrHash(ctx, rpc.BlockNumberOrHash{BlockHash: &blockHash}) if err == nil { mtx.Lock() if blockNumber == i { i++ } mtx.Unlock() break } if ctx.Err() != nil { return } if !strings.Contains(err.Error(), "ahead of current block") { errors <- err return } if time.Since(start) > 5*time.Second { errors <- fmt.Errorf("timeout - failed to get state for more then 5 seconds, block: %d, err: %w", blockNumber, err) return } } } it.Release() mtx.RLock() blockNumber = i mtx.RUnlock() } }() } callersDone := make(chan struct{}) go func() { wgCallers.Wait() close(callersDone) }() select { case <-callersDone: cancel() case <-senderDone: cancel() case err := <-errors: t.Error(err) cancel() } <-callersDone <-senderDone close(errors) for err := range errors { if err != nil { t.Error(err) } } }
import React from 'react' import T from 'prop-types' const Cell = ({ children, width, className }) => { const attributes = { role: 'cell', className: 'c-fixed-table__cell' } if (width) { attributes.style = { width } } if (className) { attributes.className = `${attributes.className} ${className}` } return <div {...attributes}>{children}</div> } Cell.propTypes = { children: T.node, width: T.string, className: T.string } Cell.defaultProps = { width: null, children: null, className: '' } export default Cell
package com.liftoff.project.repository; import com.liftoff.project.model.Product; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import java.util.UUID; @Repository public interface ProductRepository extends JpaRepository<Product, Long> { /** * Finds a product by its unique identifier. * * @param productUuid The unique identifier (UUID) of the product to find. * @return An {@link Optional} containing the product if found, or an empty {@link Optional} if not found. */ @Query("SELECT p FROM Product p WHERE p.uId = :productUuid") Optional<Product> findByUId(@Param("productUuid") UUID productUuid); /** * Finds the top N recently added active products. * * @param n The number of products to retrieve. * @return A list of active products that were recently added, limited to the specified number. */ @Query("SELECT p FROM Product p WHERE p.status = 'ACTIVE' " + "AND p.createdAt IS NOT NULL " + "ORDER BY p.createdAt DESC LIMIT :n") List<Product> findTopNRecentActiveProducts(@Param("n") int n); /** * Finds products with a discount price greater than the specified value * and a discount price end date after the specified date and not null. * * @param discountPrice The minimum discount price to search for. * @param discountPriceEndDate The date to compare with the discount price end date. * @return A list of products that meet the specified criteria. */ List<Product> findProductsByDiscountPriceGreaterThanAndDiscountPriceEndDateAfterAndDiscountPriceEndDateIsNotNull( Double discountPrice, LocalDateTime discountPriceEndDate); /** * Retrieves a list of products with a non-null discount price greater than the specified value. * * @param discountPrice The minimum discount price to filter products by. * @return A list of products with a discount price greater than the specified value and not null. */ List<Product> findProductsByDiscountPriceNotNullAndDiscountPriceGreaterThan( Double discountPrice); }
import React, { useEffect , useState } from 'react' import NewsItem from './NewsItem' import Spinner from './Spinner' import PropTypes from 'prop-types' import InfiniteScroll from "react-infinite-scroll-component" import LoadingBar from 'react-top-loading-bar' const News = (props)=> { const [articles, setarticles] = useState([]) const [loading, setloading] = useState(false) let [page, setpage] = useState(1) const [totalResults, settotalResults] = useState(0) const capitaliseFirstLetter= (string)=> { return string.charAt(0).toUpperCase() + string.slice(1); } const updateNews = async ( )=>{ props.setProgress(10); const url=`https://newsapi.org/v2/top-headlines?country=${props.country}&category=${props.category}&apikey=${process.env.REACT_APP_NEWS_API}&page=${page}&pageSize=${props.pageSize}`; setloading(true) props.setProgress(30); let data= await fetch(url); props.setProgress(50); let parsedData= await data.json(); props.setProgress(70); setarticles(parsedData.articles) settotalResults(parsedData.totalArticles) setloading(false) props.setProgress(100); } useEffect(() => { document.title= `NewsMeow - ${capitaliseFirstLetter(props.category)}`; updateNews(); }, []) const fetchMoreData = async () => { const url=`https://newsapi.org/v2/top-headlines?country=${props.country}&category=${props.category}&apikey=${process.env.REACT_APP_NEWS_API}&page=${page+1}&pageSize=${props.pageSize}`; setpage(++page) let data= await fetch(url); let parsedData= await data.json(); console.log(parsedData); setarticles(articles.concat(parsedData.articles)) settotalResults(parsedData.totalResults) }; return ( <> <h1 className='text-center ' style={{marginTop:'90px'}}> NewsFlash - Top Headlines from {capitaliseFirstLetter(props.category)}</h1> {loading && <Spinner/>} <InfiniteScroll dataLength={articles.length} next={fetchMoreData} hasMore={articles.length !== totalResults} loader={ <Spinner />} > <div className='container my-4'> <div className='row'> {articles.map((element)=>{ return <div className='col-md-4' key= {element.url} > <NewsItem title={element.title} description={element.description} imageUrl={element.urlToImage} newsUrl={element.url} author={element.author} date={element.publishedAt} source={element.source.name} /> </div> })} </div> </div> </InfiniteScroll> </> ) } News.contextTypedefaultProps = { country: 'in', pageSize: 6, category: 'health', } News.propTypes = { country: PropTypes.string, pageSize: PropTypes.number, category: PropTypes.string, } export default News
<?php /** * Custom Drush commands * Drush command to consume data from https://pokeapi.co/ * php version 8.0.28 * * @file * @category Category * @package Drupal\sample_trainer\Services * @author Juan Carlos Pérez <karlitoskillyou@hotmail.com> * @license MIT * @link * * @file */ namespace Drupal\sample_trainer\Command; use Drush\Commands\DrushCommands; /** * Extending drush commands. */ class UpdateTrainer extends DrushCommands { /** * Drush command that give pokedollars to trainers. * * @param int $amount * @command sample_trainer:pokedollars * @aliases stpok * * @usage stpok */ function addPokedollars($amount = 100) { // Loading all nodes ids. $nodes = \Drupal::entityTypeManager()->getStorage('node'); // filtering IDs by pokedollars_balance nodes $nids = $nodes->getQuery() ->condition('type', 'pokedollars_balance') ->execute(); foreach ($nids as $nid) { /** @var \Drupal\node\NodeInterface $node */ $node = $nodes->load($nid); $current_amount = $node->get('field_pokedollars')->value; $new_amount = $current_amount + $amount; $node->set('field_pokedollars', $new_amount); $node->set('field_operation_concept', "$amount pokedollars free"); $node->setNewRevision(TRUE); $node->revision_log = 'Created revision for node' . $nid; $node->save(); } $this->output()->writeln("$amount pokedollars given to all trainers."); } }
package com.miftah.myinstagramfriendslist.repository import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.miftah.myinstagramfriendslist.di.Injection import com.miftah.myinstagramfriendslist.ui.favorite.ViewModelFavorite import com.miftah.myinstagramfriendslist.ui.follow.ViewModelFollow import com.miftah.myinstagramfriendslist.ui.main.ViewModelMain import com.miftah.myinstagramfriendslist.ui.profile.ViewModelProfile import com.miftah.myinstagramfriendslist.ui.setting.ViewModelSetting class ViewModelFactory(private val newsRepository: ProfileRepository) : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(ViewModelMain::class.java)) { return ViewModelMain(newsRepository) as T } else if (modelClass.isAssignableFrom(ViewModelProfile::class.java)) { return ViewModelProfile(newsRepository) as T } else if (modelClass.isAssignableFrom(ViewModelFollow::class.java)) { return ViewModelFollow(newsRepository) as T } else if (modelClass.isAssignableFrom(ViewModelFavorite::class.java)) { return ViewModelFavorite(newsRepository) as T } else if (modelClass.isAssignableFrom(ViewModelSetting::class.java)) { return ViewModelSetting(newsRepository) as T } throw IllegalArgumentException("Unknown ViewModel class: " + modelClass.name) } companion object { @Volatile private var instance: ViewModelFactory? = null fun getInstance(context: Context): ViewModelFactory = instance ?: synchronized(this) { instance ?: ViewModelFactory(Injection.provideRepository(context)) }.also { instance = it } } }
import sys, argparse import pygame as pg import imgui import my_imgui.pygame_imgui as pygame_imgui import numpy as np import moderngl as mgl import glm from camera import Camera from model import * from config import * from shader_program import ShaderProgram from light import Light import taichi as ti # ----------------------------------------------------------------------------------------------------------- class App: def __init__(self, screen_width=1280, screen_height=800, hide_options=True, max_fps=0, nb_body=8, dt=0.005, eps=0.5): self.screen_width = screen_width self.screen_height = screen_height self.max_fps = max_fps self.hide_options = hide_options self.nb_body = nb_body # self.lastTime = time.time() self.currentTime = time.time() self.fps = FPSCounter() self.mode = MODE # pygame init pg.init() pg.display.gl_set_attribute(pg.GL_CONTEXT_MAJOR_VERSION, 4) pg.display.gl_set_attribute(pg.GL_CONTEXT_MINOR_VERSION, 3) pg.display.gl_set_attribute(pg.GL_CONTEXT_PROFILE_MASK, pg.GL_CONTEXT_PROFILE_CORE) pg.display.set_mode((self.screen_width, self.screen_height), flags=pg.OPENGL | pg.HWSURFACE | pg.DOUBLEBUF) # | pg.FULLSCREEN) #pg.display.set_mode((self.screen_width, self.screen_height), flags=pg.OPENGL | pg.DOUBLEBUF | pg.RESIZABLE) # | pg.FULLSCREEN) # IMGUI if not self.hide_options: imgui.create_context() self.imgui_renderer = pygame_imgui.PygameRenderer() imgui.get_io().display_size = self.screen_width, self.screen_height self.eps = eps self.dt = dt # camera control: keys + mouse pg.event.set_grab(GRAB_MOUSE) pg.mouse.set_visible(True) self.u_scroll = 5.0 self.forward = False self.backward = False self.right = False self.left = False self.up = False self.down = False self.mouse_x, self.mouse_y = 0, 0 self.mouse_button_down = False # OpenGL context / options self.ctx = mgl.create_context() if self.mode == mgl.POINTS: self.ctx.enable_only(mgl.PROGRAM_POINT_SIZE | mgl.BLEND) #self.ctx.wireframe = True #self.ctx.front_face = 'cw' #self.ctx.enable(flags=mgl.DEPTH_TEST) #self.ctx.enable(flags=mgl.DEPTH_TEST | mgl.CULL_FACE) self.ctx.enable(flags=mgl.DEPTH_TEST | mgl.CULL_FACE | mgl.BLEND) # time objects self.clock = pg.time.Clock() self.time, self.delta_time, self.num_frames = 0, 0, 0 # light self.light = Light(position=LIGHT_POS) self.all_shaders = ShaderProgram(self.ctx) self.nbody_program = self.all_shaders.get_program("nbody") # camera self.camera = Camera(self, fov=FOV, near=NEAR, far=FAR, position=CAM_POS, speed=SPEED, sensivity=SENSITIVITY) # scene object self.scene = [] self.sim = Simulation(self, self.nbody_program) self.scene.append(self.sim) self.ctx.clear(color = (0.0, 0.0, 0.0)) def destroy(self): self.all_shaders.destroy() for obj in self.scene: obj.destroy() def set_uniform(self, program, u_name, u_value): try: program[u_name] = u_value except KeyError: pass def get_fps(self): self.currentTime = time.time() delta = self.currentTime - self.lastTime if delta >= 1: fps = f"FPS: {self.fps.get_fps():3.0f}" cam_pos = f"CamPos: {int(self.camera.position.x)}, {int(self.camera.position.y)}, {int(self.camera.position.z)}" pg.display.set_caption(fps + " | " + cam_pos) self.lastTime = self.currentTime self.fps.tick() def check_events(self): for event in pg.event.get(): if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): self.destroy() pg.quit() sys.exit() if event.type == pg.KEYDOWN: if event.key == pg.K_UP: self.forward = True if event.key == pg.K_DOWN: self.backward = True if event.key == pg.K_RIGHT: self.right = True if event.key == pg.K_LEFT: self.left = True if event.key == pg.K_LCTRL: self.up = True if event.key == pg.K_LSHIFT: self.down = True if event.type == pg.KEYUP: if event.key == pg.K_UP: self.forward = False if event.key == pg.K_DOWN: self.backward = False if event.key == pg.K_RIGHT: self.right = False if event.key == pg.K_LEFT: self.left = False if event.key == pg.K_LCTRL: self.up = False if event.key == pg.K_LSHIFT: self.down = False if event.type == pg.MOUSEBUTTONDOWN: self.mouse_button_down = True if event.type == pg.MOUSEBUTTONUP: self.mouse_button_down = False if event.type == pg.MOUSEWHEEL: # which, flipped, x, y, touch, precise_x, precise_y self.mouse_scroll(event.x, event.y) if event.type == pg.MOUSEMOTION: mouse_position = pg.mouse.get_pos() self.mouse_pos(mouse_position[0], mouse_position[1]) if not self.hide_options: self.imgui_renderer.process_event(event) # mouse camera control if self.mouse_button_down: mx, my = pg.mouse.get_pos() if self.mouse_x: self.mouse_dx = self.mouse_x - mx else: self.mouse_dx = 0 if self.mouse_y: self.mouse_dy = self.mouse_y - my else: self.mouse_dy = 0 self.mouse_x = mx self.mouse_y = my else: self.mouse_x = 0 self.mouse_y = 0 self.mouse_dx, self.mouse_dy = 0, 0 def mouse_pos(self, x, y, dx=0, dy=0): pass #self.set_uniform(self.world_program, 'u_mouse', (x, y)) def mouse_scroll(self, x, y): self.u_scroll = max(1.0, self.u_scroll + y) #self.set_uniform(self.world_program, 'u_scroll', self.u_scroll) #if y == 1: # self.down = True #if y == -1: # self.up = True def get_time(self): return pg.time.get_ticks() * 0.001 def set_time(self): self.time = pg.time.get_ticks() * 0.001 def show_options_ui(self): imgui.new_frame() imgui.begin("Options", True) _, self.dt = imgui.slider_float("dt", self.dt, 0.001, 1.0) _, self.eps = imgui.slider_float("eps", self.eps, 0.01, 1.0) imgui.end() def run(self): while True: # app.time used for object model motion self.set_time() # pygame events self.check_events() # self.camera.update(self.mouse_dx, self.mouse_dy, self.forward, self.backward, self.left, self.right, self.up, self.down) if CLEAR_ON: self.ctx.clear(color = (0.0, 0.0, 0.0)) for obj in self.scene: obj.update() obj.render() # imgui if not self.hide_options: self.show_options_ui() imgui.render() self.imgui_renderer.render(imgui.get_draw_data()) # show pg.display.flip() # fps self.delta_time = self.clock.tick(self.max_fps) self.get_fps() self.num_frames += 1 # ----------------------------------------------------------------------------------------------------------- # python3 main.py --arch=cpu --body=32 --fps=-1 # python3 main.py --arch=cpu --body=32 --fps=-1 -ho parser = argparse.ArgumentParser(description="") parser.add_argument('-ww', '--width', help='width', default=1280, type=int) parser.add_argument('-hh', '--height', help='width', default=800, type=int) parser.add_argument('-a', '--arch', help='Taichi backend', default="cpu", action="store") parser.add_argument('-f', '--fps', help='Max FPS, 0 for unlimited', default=0, type=int) parser.add_argument('-b', '--body', help='NB Body', default=32, type=int) parser.add_argument('-ho', '--hide_options', help='Options UI', default=False, action="store_true") result = parser.parse_args() args = dict(result._get_kwargs()) print("Args = %s" % args) if args["arch"] in ("cpu", "x64"): ti.init(ti.cpu, debug=0, default_ip=ti.i32, default_fp=ti.f32) elif args["arch"] in ("gpu", "cuda"): ti.init(ti.gpu) elif args["arch"] in ("opengl",): ti.init(ti.opengl) elif args["arch"] in ("vulkan",): ti.init(ti.vulkan) # ----------------------------------------------------------------------------------------------------------- if __name__ == '__main__': app = App(screen_width=args["width"], screen_height=args["height"], max_fps=args["fps"], hide_options=args["hide_options"], nb_body=args["body"], dt=0.005, eps=0.5) app.run()
// // ReadingRowView.swift // SpeedRead // // Created by Dias Manap on 27.10.2022. // import SwiftUI import OrderedCollections struct ReadingRowView: View { let reading: Reading let readingPages: OrderedDictionary<Int, [String]>? let currentPage: Int init(reading: Reading) { self.reading = reading self.readingPages = OrderedDictionary<Int, [String]>.load(on: .cachesDirectory, fromFileName: "\(reading.id).txt") self.currentPage = defaults.integer(forKey: "PageFor\(reading.id)") } var body: some View { NavigationLink(value: Route.reading(reading)) { HStack(spacing: 14) { AsyncImageView(iconLink: reading.iconLink) .frame(width: 60, height: 84) .cornerRadius(8) .padding(.leading, 12) VStack(alignment: .leading, spacing: 0) { Text(reading.title) .foregroundColor(.primary) .font(.system(size: 16, weight: .semibold)) .padding(.bottom, 4) Text(reading.author) .foregroundColor(.primary.opacity(0.5)) .font(.system(size: 14, weight: .semibold)) .padding(.bottom, 18) ReadingProgressBar( pagesRead: currentPage ?? 17, pagesTotal: readingPages?.count ?? 100 ) } .padding(.vertical, 12) .padding(.trailing, 20) } .background(Color.srSecondary) .cornerRadius(12) } } } struct ReadingRowView_Previews: PreviewProvider { static var previews: some View { ReadingRowView(reading: Reading.example) } }
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; // Import the service and controller specific to authentication import { AuthService } from './auth.service'; import { AuthController } from './auth.controller'; // Import the User schema and interface import { User, UserSchema } from './schemas/user.schema'; /** * The AuthModule integrates user authentication features into the application. * It includes models, services, and controllers specific to authentication. */ @Module({ imports: [ // Register the User schema with Mongoose, making it available within the module MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]), ], controllers: [ AuthController, // Register the AuthController to handle HTTP requests ], providers: [ AuthService, // Register the AuthService to provide authentication-related services ], }) export class AuthModule {}
<nav class="navbar is-link" role="navigation" aria-label="main navigation"> <div class="navbar-brand"> <a class="navbar-item" routerLink="/"> <img src="logo.png" alt="App logo"> <h1>{{title}}</h1> </a> <a role="button" #burgerButton class="navbar-burger" [class.is-active]="isBurgerMenuVisible" aria-label="menu" aria-expanded="false" data-target="navbarHome" tabindex="0" (click)="onBurgerClick()" (keyup)="onBurgerClick()"> <span aria-hidden="true"></span> <span aria-hidden="true"></span> <span aria-hidden="true"></span> <span aria-hidden="true"></span> </a> </div> <div id="navbarHome" class="navbar-menu" [class.is-active]="isBurgerMenuVisible"> <div class="navbar-start"> <a class="navbar-item" routerLink="/">Home</a> <div class="navbar-item has-dropdown is-hoverable"> <a class="navbar-link" routerLink="/compendium">Compendium</a> <div class="navbar-dropdown"> <a class="navbar-item" routerLink="/compendium/creatures">Creatures</a> <a class="navbar-item" routerLink="/compendium/equipment">Equipments</a> <a class="navbar-item" routerLink="/compendium/materials">Materials</a> <a class="navbar-item" routerLink="/compendium/monsters">Monsters</a> <a class="navbar-item" routerLink="/compendium/treasure">Treasures</a> </div> </div> </div> <div class="navbar-end"> <div class="navbar-item"> <div class="buttons"> @if (loggedUser) { <p>{{loggedUser.fullName + " (@" + loggedUser.userName + ")"}}</p> <a class="button is-light" (click)="onLogoutClick()" (keyup)="onLogoutClick()" tabindex="0"> Log out </a> } @else { <a class="button is-primary" routerLink="/login"> Log in </a> } </div> </div> </div> </div> </nav>
package main import( "log" "errors" "google.golang.org/grpc" "io" ) func myStreamServerInterceptor2(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { log.Println("[pre stream] my stream server interceptor 2: ", info.FullMethod) err := handler(srv, &myServerStreamWrapper2{ss}) // 本来のストリーム処理 log.Println("[post stream] my stream server interceptor 2: ") return err } type myServerStreamWrapper2 struct { grpc.ServerStream } func (s *myServerStreamWrapper2) RecvMsg(m interface{}) error { err := s.ServerStream.RecvMsg(m) if !errors.Is(err, io.EOF) { log.Println("[pre message] my stream server interceptor 2: ", m) } return err } func (s *myServerStreamWrapper2) SendMsg(m interface{}) error { log.Println("[post message] my stream server interceptor 2: ", m) return s.ServerStream.SendMsg(m) }
package com.app.ycommerce.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToOne; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Entity @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor public class CartItem { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "cart_item_id") private Long id; @ManyToOne @JoinColumn(name = "cart_id") private Cart cart; @OneToOne @JoinColumn(name = "product_id") private Product product; private int quantity; public static CartItem createCartItem(Cart cart, Product product, int quantity) { return CartItem.builder() .cart(cart) .product(product) .quantity(quantity) .build(); } public void addQuantity(int quantity) { this.quantity = this.quantity + quantity; } }
// import { Persona } from './interfaces'; // /******************************caracteristidas de los parametros de las funciones************************ // Explicaremos las caracterisitcas que tienen los parametros de las funciones // parametros obligatorios: // parametros opcionales: // parametros defatult/defecto: // Notas: // 1.- El primer parametro no puede ser opcional // 2.- Siempre los parametros opcionales deben escribirse al final // ************************************************************/ // function suma(x: number, ultimo: number = 10, y?: boolean) { // let suma = x + ultimo; // // if (y == undefined) console.log(suma); // y == undefined ? console.log(suma) : null; // } // suma(10, 20); // /******************************Funcion de flecha************************/ // function impresionDatos() { // console.log("Hola Mundo desde una funcion estandar"); // } // const ArrowFunctionSaludos = (x: number, y: number) => x + y; // /**************************************************************************** // Metodos Array Funcion de flecha // 1. Foreach // 2. Map // 3. Find // 4. Filter // 5. Some // *****************************************************************************/ // let ArregloNumerico: Array<number> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // let personas: Array<Persona> = [ // { // nombre: "Jose Carlos", // apellido: 'Gonzalez', // sexo: "Masculino", // edad: 23, // }, // { // nombre: "Chinese", // apellido: 'Peralta', // sexo: "Masculino", // edad: 23 // }, // { // nombre: "La Daniela", // apellido: 'Estrada', // sexo: "Femenino", // edad: 26, // }, // ]; // // for (let i = 0; i < ArregloNumerico.length; i++) { // // let elemento = ArregloNumerico[i]; // // if (elemento % 2 == 0) { // // console.log("par"); // // } else { // // console.log("impar"); // // } // // } // let ArregloNuevo: any = []; // // Mandando una funcion dentro de una funcion // /*forEach recorre un arreglo y aplica un cambio al valor de sus arreglos*/ // ArregloNuevo = ArregloNumerico.forEach((elemento) => // elemento % 2 == 0 ? elemento : null // ); // /*******************************Map********************************************* // Es similar al forEach ya que por cada valor en el arrelgo le aplica una accion, // la diferencia es que Map nos crea un arreglo nuevo y forEach no // *****************************************************************************/ // ArregloNuevo = ArregloNumerico.map((elemento) => // elemento % 2 == 0 ? "par" : "impar" // ); // /***************************Find********************************* // * // Encuentra 1 valor dentro de un arreglo y nos comparte un valor nuevo // ************************************************************/ // // personas.forEach((elemento) => console.log(elemento)); // // if(elemento.id == 2){ // // return elemento // // } // let persona = personas.find((elemento) => elemento.id == 2); // /***************************Filter********************************* // * // * Encuentra varios valores y regresa uun array con ellos // ************************************************************/ // let personasFemenino = personas.filter((persona) => persona.sexo == "Femenino"); // /***************************Some********************************* // Encuentra un valor dentro de un arreglo y nos regresa un true/false // true=para cuando existe el valor // false = para cuando no existe // ************************************************************/ // personas.some((persona) => persona.id == 3 && persona.nombre == "Chinese"); // console.log("existe");
import { IMerchantDetailTransactionResponse, IMerchantTransactionListRequest, IMerchantTransactionListResponse, IUpdateMerchantOrderStatusRequest, } from '../../../helpers/types/merchant/merchant-order.interface'; import { apiSlice } from '../../api/apiSlice'; export const merchantApi = apiSlice.injectEndpoints({ endpoints: (build) => ({ getMerchantOrders: build.query< IMerchantTransactionListResponse, IMerchantTransactionListRequest >({ query: (params) => ({ url: '/merchants/transactions', method: 'GET', params, }), transformResponse: (response: { data: IMerchantTransactionListResponse; }) => response.data, transformErrorResponse: (response) => response.data, providesTags: ['Merchant Transaction'], }), UpdateMerchantOrderStatus: build.mutation< IMerchantTransactionListResponse, IUpdateMerchantOrderStatusRequest >({ query: (body) => ({ url: `/merchants/transactions/${body.invoice_code}/status`, method: 'PUT', body, }), transformResponse: (response: { data: IMerchantTransactionListResponse; }) => response.data, transformErrorResponse: (response) => response.data, invalidatesTags: ['Merchant Transaction', 'Merchant Transaction Detail'], }), getMerchantOrderDetails: build.query< IMerchantDetailTransactionResponse, string >({ query: (slug) => ({ url: `/merchants/transactions/${slug}`, method: 'GET', }), transformResponse: (response: { data: IMerchantDetailTransactionResponse; }) => response.data, transformErrorResponse: (response) => response.data, providesTags: ['Merchant Transaction Detail'], }), }), }); export const { useGetMerchantOrdersQuery, useUpdateMerchantOrderStatusMutation, useGetMerchantOrderDetailsQuery, } = merchantApi;
/******************************************************************************* * Copyright (c) 1997, 2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.security.web.saml.sample; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.security.cert.X509Certificate; import java.util.Date; import java.util.Enumeration; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class SnoopServlet */ public class SnoopServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SnoopServlet() { super(); // TODO Auto-generated constructor stub } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out; res.setContentType("text/html"); out = res.getWriter(); out.println("<HTML><HEAD><TITLE>Snoop Servlet</TITLE></HEAD><BODY background=\"4038.jpg\">"); out.println("<h1>Snoop Servlet - Request/Client Information</h1>"); out.println("<h2>Requested URL:</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); out.println("<tr><td>" + req.getRequestURL().toString() + "</td></tr></table><BR><BR>"); out.println("<h2>Servlet Name:</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); out.println("<tr><td>" + escapeChar(getServletConfig().getServletName()) + "</td></tr></table><BR><BR>"); Enumeration vEnum = getServletConfig().getInitParameterNames(); if (vEnum != null && vEnum.hasMoreElements()) { boolean first = true; while (vEnum.hasMoreElements()) { if (first) { out.println("<h2>Servlet Initialization Parameters</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); first = false; } String param = (String) vEnum.nextElement(); out.println("<tr><td>" + escapeChar(param) + "</td><td>" + escapeChar(getInitParameter(param)) + "</td></tr>"); } out.println("</table><BR><BR>"); } vEnum = getServletConfig().getServletContext().getInitParameterNames(); if (vEnum != null && vEnum.hasMoreElements()) { boolean first = true; while (vEnum.hasMoreElements()) { if (first) { out.println("<h2>Servlet Context Initialization Parameters</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); first = false; } String param = (String) vEnum.nextElement(); out.println("<tr><td>" + escapeChar(param) + "</td><td>" + escapeChar(getServletConfig().getServletContext().getInitParameter(param)) + "</td></tr>"); } out.println("</table><BR><BR>"); } out.println("<h2>Request Information:</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); print(out, "Request method", req.getMethod()); print(out, "Request URI", req.getRequestURI()); print(out, "Request protocol", req.getProtocol()); print(out, "Servlet path", req.getServletPath()); print(out, "Path info", req.getPathInfo()); print(out, "Path translated", req.getPathTranslated()); print(out, "Character encoding", req.getCharacterEncoding()); print(out, "Query string", req.getQueryString()); print(out, "Content length", req.getContentLength()); print(out, "Content type", req.getContentType()); print(out, "Server name", req.getServerName()); print(out, "Server port", req.getServerPort()); print(out, "Remote user", req.getRemoteUser()); print(out, "Remote address", req.getRemoteAddr()); print(out, "Remote host", req.getRemoteHost()); print(out, "Remote port", req.getRemotePort()); print(out, "Local address", req.getLocalAddr()); print(out, "Local host", req.getLocalName()); print(out, "Local port", req.getLocalPort()); print(out, "Authorization scheme", req.getAuthType()); if (req.getLocale() != null) { print(out, "Preferred Client Locale", req.getLocale().toString()); } else { print(out, "Preferred Client Locale", "none"); } Enumeration ee = req.getLocales(); while (ee.hasMoreElements()) { Locale cLocale = (Locale) ee.nextElement(); if (cLocale != null) { print(out, "All Client Locales", cLocale.toString()); } else { print(out, "All Client Locales", "none"); } } print(out, "Context Path", escapeChar(req.getContextPath())); if (req.getUserPrincipal() != null) { print(out, "User Principal", escapeChar(req.getUserPrincipal().getName())); } else { print(out, "User Principal", "none"); } out.println("</table><BR><BR>"); Enumeration e = req.getHeaderNames(); if (e.hasMoreElements()) { out.println("<h2>Request Headers:</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); String Value = null; while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println("<tr><td>" + escapeChar(name) + "</td>"); out.println("<td>"); int start = 0; Value = escapeChar(req.getHeader(name)); if (Value.length() > 70) { for (int j = 70; j <= Value.length(); j = j + 70) { out.println(Value.substring(start, j) + "<br>"); start = j; } if (start <= Value.length()) { out.println(Value.substring(start)); } } else { out.println(Value + "<br>"); } out.println("</td></tr>"); } out.println("</table><BR><BR>"); } e = req.getParameterNames(); if (e.hasMoreElements()) { out.println("<h2>Servlet Parameters (Single Value style):</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println("<tr><td>" + escapeChar(name) + "</td><td>" + escapeChar(req.getParameter(name)) + "</td></tr>"); } out.println("</table><BR><BR>"); } e = req.getParameterNames(); if (e.hasMoreElements()) { out.println("<h2>Servlet Parameters (Multiple Value style):</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String vals[] = (String[]) req.getParameterValues(name); if (vals != null) { out.print("<tr><td>" + escapeChar(name) + "</td><td>"); out.print(escapeChar(vals[0])); for (int i = 1; i < vals.length; i++) out.print(", " + escapeChar(vals[i])); out.println("</td></tr>"); } } out.println("</table><BR><BR>"); } String cipherSuite = (String) req.getAttribute("javax.net.ssl.cipher_suite"); if (cipherSuite != null) { X509Certificate certChain[] = (X509Certificate[]) req.getAttribute("javax.net.ssl.peer_certificates"); out.println("<h2>HTTPS Information:</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); out.println("<tr><td>Cipher Suite</td><td>" + escapeChar(cipherSuite) + "</td></tr>"); if (certChain != null) { for (int i = 0; i < certChain.length; i++) { out.println("client cert chain [" + i + "] = " + escapeChar(certChain[i].toString())); } } out.println("</table><BR><BR>"); } Cookie[] cookies = req.getCookies(); if (cookies != null && cookies.length > 0) { out.println("<H2>Client Cookies:</H2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); String Value = null; for (int i = 0; i < cookies.length; i++) { out.println("<tr><td>" + escapeChar(cookies[i].getName()) + "</td>"); out.println("<td>"); Value = cookies[i].getValue(); int start = 0; if (Value.length() > 70) { for (int j = 70; j <= Value.length(); j = j + 70) { out.println(Value.substring(start, j) + "<br>"); start = j; } if (start <= Value.length()) { out.println(Value.substring(start)); } } else { out.println(escapeChar(Value)); } out.println("</td></tr>"); } out.println("</table><BR><BR>"); } e = req.getAttributeNames(); if (e.hasMoreElements()) { out.println("<h2>Request Attributes:</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println("<tr><td>" + escapeChar(name) + "</td><td>" + escapeChar(req.getAttribute(name).toString()) + "</td></tr>"); } out.println("</table><BR><BR>"); } e = getServletContext().getAttributeNames(); /* * if ( e.hasMoreElements() ) * { * out.println("<h2>ServletContext attributes:</h2>"); * out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); * while ( e.hasMoreElements() ) * { * String name = (String)e.nextElement(); * out.println("<tr><td>" + escapeChar(name) + "</td><td>" + escapeChar(getServletContext().getAttribute(name).toString()) * + "</td></tr>"); * } * out.println("</table><BR><BR>"); * } */ HttpSession session = req.getSession(false); if (session != null) { out.println("<h2>Session information:</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); print(out, "Session ID", session.getId()); print(out, "Last accessed time", new Date(session.getLastAccessedTime()).toString()); print(out, "Creation time", new Date(session.getCreationTime()).toString()); String mechanism = "unknown"; if (req.isRequestedSessionIdFromCookie()) { mechanism = "cookie"; } else if (req.isRequestedSessionIdFromURL()) { mechanism = "url-encoding"; } print(out, "Session-tracking mechanism", mechanism); out.println("</table><BR><BR>"); Enumeration vals = session.getAttributeNames(); if (vals.hasMoreElements()) { out.println("<h2>Session values</h2>"); out.println("<TABLE Border=\"2\" WIDTH=\"65%\" BGCOLOR=\"white\">"); while (vals.hasMoreElements()) { String name = (String) vals.nextElement(); String charname = escapeChar(name); out.println("<tr><td>" + charname + "</td><td>" + escapeChar(session.getAttribute(name).toString()) + "</td></tr>"); } out.println("</table><BR><BR>"); } } out.println("</body></html>"); } /************************************************************************************************************************ * Methods ************************************************************************************************************************/ private void print(PrintWriter out, String name, String value) { out.println("<tr><td>" + name + "</td><td>" + (value == null ? "&lt;none&gt;" : escapeChar(value)) + "</td></tr>"); } private void print(PrintWriter out, String name, int value) { out.print("<tr><td>" + name + "</td><td>"); if (value == -1) { out.print("&lt;none&gt;"); } else { out.print(value); } out.println("</td></tr>"); } private String escapeChar(String str) { char src[] = str.toCharArray(); int len = src.length; for (int i = 0; i < src.length; i++) { switch (src[i]) { case '<': // to "&lt;" len += 3; break; case '>': // to "&gt;" len += 3; break; case '&': // to "&amp;" len += 4; break; } } char ret[] = new char[len]; int j = 0; for (int i = 0; i < src.length; i++) { switch (src[i]) { case '<': // to "&lt;" ret[j++] = '&'; ret[j++] = 'l'; ret[j++] = 't'; ret[j++] = ';'; break; case '>': // to "&gt;" ret[j++] = '&'; ret[j++] = 'g'; ret[j++] = 't'; ret[j++] = ';'; break; case '&': // to "&amp;" ret[j++] = '&'; ret[j++] = 'a'; ret[j++] = 'm'; ret[j++] = 'p'; ret[j++] = ';'; break; default: ret[j++] = src[i]; break; } } return new String(ret); } private static void writeIndentation(ByteArrayOutputStream os, int indent) { for (int j = 0; j < indent; j++) { os.write('\t'); os.write('\t'); os.write('\t'); os.write('\t'); } } }
// --- Directions // Given a string, return a new string with the reversed // order of characters // --- Examples // reverse('apple') === 'leppa' // reverse('hello') === 'olleh' // reverse('Greetings!') === '!sgniteerG' const reverseStringOne = (str) => { return str.split("").reverse().join(""); }; const reverseStringTwo = (str) => { let reversed = ""; for (let character of str) { reversed = character + reversed; console.log(reversed); } return reversed; }; const reverseStringThree = (str) => { return str.split("").reduce((reversed, character) => character + reversed, ""); }; console.log(reverseStringThree("shubham"));
<meta charset="UTF-8"> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <div id="app"> <ul> <li v-for = "(cor, i) in cores" :key='cor'> {{i+1}}) {{cor}} </li> <!-- :key é a identidade do elemento no vue, o id por exemplo é uma ótima chave--> </ul> <button @click="cores.push('branca')"> Add cor</button> <hr> <div v-for = "(cor, i) in cores"> <h1> {{cor}}</h1> <p>{{i}}</p> </div> <hr> <ul> <li v-for = "pessoa in pessoas"> <span v-for="(valor, chave, index) in pessoa"> {{ chave }} = {{ valor }} ({{index}}) </span><!-- deixa todos os elementos em uma linha no DOM --> </li> </ul> <div v-for="n in 10"> {{n}}</div> </div> <script> new Vue({ el:'#app', //essa instância do vue passa a controlar o trecho de HTML com esse elemento data:{ cores: ['vermelho', 'verde', 'amarelo', 'azul'], pessoas: [ {nome: 'Ana', idade: 26, peso: 59}, {nome: 'Gui', idade: 29, peso: 72} ] } }) </script> <style> ul { list-style:none; } h1, p { display: inline; } </style>
import { Box, Button, Divider, Fade, FormControl, Grow, IconButton, InputLabel, MenuItem, Modal, Select, Slide, Snackbar, TextField, Typography } from "@mui/material"; import * as React from "react"; import {useEffect, useState} from "react"; import {environment} from "../../environments/environments"; import Category from "../../models/Category"; import CloseIcon from '@mui/icons-material/Close'; const ProductDetail = ({isOpen, onClose, product, loadProduct, message, openSnackbar}) => { const [categories, setCategories] = useState([]); const [formData, setFormData] = useState({ descripcion: '', marca: '', precio: '', categoria: '', }); useEffect(() => { // Cuando se cargan los datos del producto, actualiza el estado de formData con esos datos if (product) { setFormData({ descripcion: product.descripcion, marca: product.marca.nombre, precio: product.precio, categoria: product.categoria.id, }); } }, [product]); useEffect(() => { // console.log("Producto: ", product); loadCategories(); }, []); const loadCategories = () => { fetch(environment.baseURL + 'categorias') .then(response => response.json()) .then(data => { let category = data.map(c => new Category(c)); setCategories(category); }).catch((error) => { console.log("Error...", error); }); } const updateProduct = () => { const producto = { descripcion: formData.descripcion, precio: parseFloat(formData.precio), version: product.version, categoria: { id: formData.categoria }, marca: { nombre: formData.marca } } console.log("Producto: ", producto); fetch(environment.baseURL + 'productos/' + product.id, { method: 'PUT', headers: { 'Content-type': 'application/json', }, body: JSON.stringify(producto) }) .then(response => { if (response.ok) { loadProduct(); return response.json().then(data => { if (data.message) { openSnackbar(true); message(data.message); } }); } else { return response.json().then(data => { if (data.error) { throw new Error(data.error); } else { throw new Error("Error al actualizar el producto....."); } }); } }) .catch((error) => { openSnackbar(true); message(error.message); }); } return ( <Modal open={isOpen} onClose={onClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description"> <Box sx={style}> <Typography id="modal-modal-title" variant="h6" component="h2" style={{textAlign: 'center', fontWeight: 'bold'}}> Editar producto </Typography> <Divider style={{marginTop: 8, width: '100%'}}/> <div style={{padding: 10, textAlign: 'center'}}> <TextField style={{marginBottom: 15}} id="standard-basic" label="Nombre" variant="standard" value={formData.descripcion} onChange={(e) => setFormData({...formData, descripcion: e.target.value})} /> <TextField style={{marginBottom: 15}} id="standard-basic" label="Marca" variant="standard" value={formData.marca} onChange={(e) => setFormData({...formData, marca: e.target.value})} /> <TextField style={{marginBottom: 15}} id="standard-basic" label="Precio" variant="standard" value={formData.precio} onChange={(e) => setFormData({...formData, precio: e.target.value})} /> <Box sx={{width: '60%', marginLeft: 10, marginTop: 2}}> <FormControl fullWidth> <InputLabel id="demo-simple-select-label">Categoria</InputLabel> <Select abelId="demo-simple-select-label" id="demo-simple-select" label="Categoria" value={formData.categoria} onChange={(e) => setFormData({...formData, categoria: e.target.value})} sx={{textAlign: 'start'}} > {categories.map(c => ( <MenuItem value={c.id}> {c.nombre} </MenuItem> ))} </Select> </FormControl> </Box> </div> <div style={{textAlign: 'center', padding: 30}}> <Button style={{marginRight: 10}} onClick={onClose} variant={'outlined'} color="error">Cancelar</Button> <Button style={{marginLeft: 10}} onClick={() => updateProduct()} variant={'outlined'}>Aceptar</Button> </div> </Box> </Modal> ); } const style = { position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: 400, bgcolor: 'background.paper', border: '1px solid gray', // boxShadow: 3, p: 4, borderRadius: 2 }; export default ProductDetail;
# Battery-Emulator ⚡🔋 ![GitHub release (with filter)](https://img.shields.io/github/v/release/dalathegreat/BYD-Battery-Emulator-For-Gen24?color=%23008000) ![GitHub Repo stars](https://img.shields.io/github/stars/dalathegreat/BYD-Battery-Emulator-For-Gen24?color=%23008000) ![GitHub forks](https://img.shields.io/github/forks/dalathegreat/BYD-Battery-Emulator-For-Gen24?color=%23008000) ![GitHub actions](https://img.shields.io/github/actions/workflow/status/dalathegreat/BYD-Battery-Emulator-For-Gen24/compile-all-batteries.yml?color=0E810E) ![Static Badge](https://img.shields.io/badge/made-with_love-blue?color=%23008000) This software enables EV battery packs to be used for stationary storage. It achieves this by converting the EV battery CAN data into a brand battery format that solar inverters can understand. This makes it extremely cheap and easy to use large EV batteries in a true plug'n'play fashion! ![alt text](https://github.com/dalathegreat/BYD-Battery-Emulator-For-Gen24/blob/main/Images/Fronius.png) ## Hardware requirements 📜 This code fits on the LilyGo ESP32 T-CAN485 devboard , see https://github.com/Xinyuan-LilyGO/T-CAN485 You will also need a complete EV battery. [See the battery compability list on which are supported.](https://github.com/dalathegreat/BYD-Battery-Emulator-For-Gen24/wiki#supported-batteries-list) Finally, you will need a [compatible hybrid solar inverter](https://github.com/dalathegreat/BYD-Battery-Emulator-For-Gen24/wiki#supported-inverters-list), for example the "Fronius Gen24" or "GoodWe ET" ## Installation basics 🪛 1. Connect one end of the LilyGo RS485 to the Gen24 Modbus 2. Connect the other end of the LilyGo to the CAN side of the battery 3. Wire up high voltage cable between the Gen24 and the battery 4. Add a 5-12V power source to power the LilyGo and 12V to the battery (uninterruptible PSU or 12V lead acid recommended in parallel) 5. Some batteries need manual pre-charge circuit and positive/negative contactor control. Others are automatic. See the wiki for more info. 6. Enjoy a big cheap grid connected battery! ## Wiring example, LEAF battery 💡 Here's how to wire up the communication between the components. ![alt text](https://github.com/dalathegreat/BYD-Battery-Emulator-For-Gen24/blob/main/Images/Wiring.png) Here's how to connect the high voltage lines ![alt text](https://github.com/dalathegreat/BYD-Battery-Emulator-For-Gen24/blob/main/Images/HighVoltageWiring.png) For more examples showing wiring, see each battery types own Wiki page. For instance the [Nissan LEAF page](https://github.com/dalathegreat/BYD-Battery-Emulator-For-Gen24/wiki/Nissan-LEAF-battery#wiring-diagram) ## How to compile the software 💻 1. Download the Arduino IDE: https://www.arduino.cc/en/software 2. When the Arduino IDE has been started; Click "File" in the upper left corner -> Preferences -> Additional Development >Board Manager URL -> Enter the URL in the input box https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json 3. Go to "Boards Manager", and install the ESP32 package by Espressif Systems 4. The arduino settings should be set to "ESP32 Dev Module" with the following settings; ![alt text](https://github.com/Xinyuan-LilyGO/T-CAN485/blob/main/img/arduino_setting.png) 5. Select which battery type you will use, along with other optional settings. This is done in the USER_SETTINGS.h file. 6. Press Verify and Upload to send the sketch to the board. NOTE: In some cases, the LilyGo must be powered through the main power connector instead of USB-C when performing the initial firsmware upload. NOTE: On Mac, the following USB driver may need to be installed: https://github.com/WCHSoftGroup/ch34xser_macos This video explains all the above mentioned steps: https://youtu.be/_mH2AjnAjDk ## Dependencies 📖 This code uses two libraries, ESP32-Arduino-CAN (https://github.com/miwagner/ESP32-Arduino-CAN/) slightly modified for this usecase, and the eModbus library (https://github.com/eModbus/eModbus). Both these are already located in the Software folder for an easy start. It is also based on the info found in the following excellent repositories/websites: - https://gitlab.com/pelle8/gen24 - https://github.com/burra/byd_battery - https://github.com/flodorn/TeslaBMSV2 - https://github.com/SunshadeCorp/can-service - https://github.com/openvehicles/Open-Vehicle-Monitoring-System-3 - https://github.com/dalathegreat/leaf_can_bus_messages - https://github.com/rand12345/solax_can_bus - https://github.com/Tom-evnut/BMWI3BMS/ SMA-CAN - Renault Zoe CAN Matrix https://docs.google.com/spreadsheets/u/0/d/1Qnk-yzzcPiMArO-QDzO4a8ptAS2Sa4HhVu441zBzlpM/edit?pli=1#gid=0 - Pylon hacking https://www.eevblog.com/forum/programming/pylontech-sc0500-protocol-hacking/ ## Like this project? 💖 Leave a ⭐ If you think this project is useful. Consider hopping onto my Patreon to encourage more open-source projects! <a href="https://www.patreon.com/dala"> <img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" width="160"> </a>
<!DOCTYPE html> <html> <title>Sasso carta forbice</title> <head> <style> </style> </head> <body> <p>Sasso Carta Forbice</p> <button onclick=" play('sasso'); ">Sasso</button> <button onclick=" play('carta'); ">Carta</button> <button onclick=" play('forbice'); ">Forbice</button> <button onclick=" punteggio.vittoria = 0; punteggio.sconfitta = 0; punteggio.pareggio = 0; localStorage.removeItem('punteggio'); ">Reset</button> <script> const punteggio = JSON.parse(localStorage.getItem('punteggio')) || { vittoria: 0, sconfitta: 0, pareggio: 0 }; function play(mossaGiocatore) { const mossaComputer = sceltaMossaComputer(); let risultato = ''; if (mossaGiocatore === 'sasso') { if (mossaComputer === 'sasso') { risultato = 'Pareggio.'; } else if (mossaComputer === 'carta') { risultato = 'Sconfitta.'; } else { risultato = 'Vittoria.'; } } else if (mossaGiocatore === 'carta') { if (mossaComputer === 'sasso') { risultato = 'Vittoria.'; } else if (mossaComputer === 'carta') { risultato = 'Pareggio.'; } else { risultato = 'Sconfitta.'; } } else { if (mossaComputer === 'sasso') { risultato = 'Sconfitta.'; } else if (mossaComputer === 'carta') { risultato = 'Vittoria.'; } else { risultato = 'Pareggio.'; } } if (risultato === 'Vittoria.') { punteggio.vittoria++; } else if (risultato === 'Pareggio.') { punteggio.pareggio++; } else { punteggio.sconfitta++; } localStorage.setItem('punteggio', JSON.stringify(punteggio)); alert(`Hai scelto ${mossaGiocatore}. Il Computer ha scelto ${mossaComputer}. ${risultato} Vittorie: ${punteggio.vittoria}, Sconfitte: ${punteggio.sconfitta}, Pareggi: ${punteggio.pareggio}.`); }; function sceltaMossaComputer() { // raccomandazione --> nome di azione nel nome della fun const numeroCasuale = Math.random(); let mossaComputer = ''; if (numeroCasuale >= 0 && numeroCasuale < 1/3) { mossaComputer = 'sasso'; } else if (numeroCasuale >= 1/3 && numeroCasuale < 2/3) { mossaComputer = 'carta'; } else { mossaComputer = 'forbice'; } //console.log(mossaComputer); return mossaComputer; } </script> </body> </html>
// To parse this JSON data, do // // final quranJuzModel = quranJuzModelFromJson(jsonString); import 'dart:convert'; QuranJuzModel quranJuzModelFromJson(String str) => QuranJuzModel.fromJson(json.decode(str)); String quranJuzModelToJson(QuranJuzModel data) => json.encode(data.toJson()); class QuranJuzModel { String? typename; List<GetQuranJuzChapter>? getQuranJuzChapter; QuranJuzModel({ this.typename, this.getQuranJuzChapter, }); factory QuranJuzModel.fromJson(Map<String, dynamic> json) => QuranJuzModel( typename: json["__typename"], getQuranJuzChapter: json["Get_Quran_Juz_Chapter"] == null ? [] : List<GetQuranJuzChapter>.from(json["Get_Quran_Juz_Chapter"]!.map((x) => GetQuranJuzChapter.fromJson(x))), ); Map<String, dynamic> toJson() => { "__typename": typename, "Get_Quran_Juz_Chapter": getQuranJuzChapter == null ? [] : List<dynamic>.from(getQuranJuzChapter!.map((x) => x.toJson())), }; } class GetQuranJuzChapter { Typename? typename; int? juzChapterNo; String? juzNameArb; String? juzNameEn; String? juzNameTamil; JuzName? juzNameHindi; JuzName? juzNameMalayalam; JuzName? juzNameTelugu; JuzName? juzNameUrdu; String? surahVersesStart; String? surahVersesEnd; int? totalVerses; GetQuranJuzChapter({ this.typename, this.juzChapterNo, this.juzNameArb, this.juzNameEn, this.juzNameTamil, this.juzNameHindi, this.juzNameMalayalam, this.juzNameTelugu, this.juzNameUrdu, this.surahVersesStart, this.surahVersesEnd, this.totalVerses, }); factory GetQuranJuzChapter.fromJson(Map<String, dynamic> json) => GetQuranJuzChapter( typename: typenameValues.map[json["__typename"]]!, juzChapterNo: json["juz_chapter_no"], juzNameArb: json["juz_name_arb"], juzNameEn: json["juz_name_en"], juzNameTamil: json["juz_name_tamil"], juzNameHindi: juzNameValues.map[json["juz_name_hindi"]]!, juzNameMalayalam: juzNameValues.map[json["juz_name_malayalam"]]!, juzNameTelugu: juzNameValues.map[json["juz_name_telugu"]]!, juzNameUrdu: juzNameValues.map[json["juz_name_urdu"]]!, surahVersesStart: json["surah_verses_start"], surahVersesEnd: json["surah_verses_end"], totalVerses: json["total_verses"], ); Map<String, dynamic> toJson() => { "__typename": typenameValues.reverse[typename], "juz_chapter_no": juzChapterNo, "juz_name_arb": juzNameArb, "juz_name_en": juzNameEn, "juz_name_tamil": juzNameTamil, "juz_name_hindi": juzNameValues.reverse[juzNameHindi], "juz_name_malayalam": juzNameValues.reverse[juzNameMalayalam], "juz_name_telugu": juzNameValues.reverse[juzNameTelugu], "juz_name_urdu": juzNameValues.reverse[juzNameUrdu], "surah_verses_start": surahVersesStart, "surah_verses_end": surahVersesEnd, "total_verses": totalVerses, }; } enum JuzName { NULL } final juzNameValues = EnumValues({ "null": JuzName.NULL }); enum Typename { QURAN_JUZ_CHAPTER } final typenameValues = EnumValues({ "quran_juz_chapter": Typename.QURAN_JUZ_CHAPTER }); class EnumValues<T> { Map<String, T> map; late Map<T, String> reverseMap; EnumValues(this.map); Map<T, String> get reverse { reverseMap = map.map((k, v) => MapEntry(v, k)); return reverseMap; } }
local tictactoe = require("tictactoe") local bot = { _version = "0.0.1" } bot.__index = bot bot.random = math.random bot.state = { symbol = tictactoe.noughts, } -- scores: tie, crosses, noughts local scores = { 0, 20, -20 } function bot:init_as(value) self.symbol = value end function bot:random_move() while true do for i = 1, 3 do for j = 1, 3 do if tictactoe.get(i, j) == tictactoe.empty then if bot.random() > 0.6 then tictactoe.set(i, j, self.symbol) return end end end end end end function bot:minimax(is_maximizing, depth) local result, who = tictactoe.has_winner() if result or tictactoe.is_complete() then return scores[who+1] end local best_score = is_maximizing and -math.huge or math.huge for i = 1, 3 do for j = 1, 3 do if tictactoe.get(i, j) == tictactoe.empty then tictactoe.set(i, j, is_maximizing and tictactoe.crosses or tictactoe.noughts) local score = bot.minimax(self, not is_maximizing, depth + 1) best_score = is_maximizing and math.max(score - depth, best_score) or math.min(score + depth, best_score) tictactoe.set(i, j, tictactoe.empty) end end end return best_score end function bot:best_move() local is_maximizing = (self.symbol == tictactoe.crosses) local best_score = is_maximizing and -math.huge or math.huge local initial_depth = 0 local x, y = nil, nil for i = 1, 3 do for j = 1, 3 do if tictactoe.get(i, j) == tictactoe.empty then tictactoe.set(i, j, self.symbol) local score = bot.minimax(self, not is_maximizing, initial_depth) tictactoe.set(i, j, tictactoe.empty) local a = is_maximizing and (score > best_score) local b = not is_maximizing and (score < best_score) if a or b then best_score = score x, y = i, j end end end end if not (x and y) then return end tictactoe.set(x, y, self.symbol) end local bound = { init_as = function(...) return bot.init_as(bot.state, ...) end, random_move = function(...) return bot.random_move(bot.state, ...) end, best_move = function(...) return bot.best_move(bot.state, ...) end, } setmetatable(bound, bot) return bound
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>复习DOM</title> </head> <body> <div id="div1"> <span></span> <span></span> <span></span> <p> <span></span><span></span> </p> </div> <script> // -> 获取页面中元素的方法 // document.getElementById() // context.getElementsByTagName(tagName) -> 把指定容器中子子孙孙备份的所有标签名为tagName的都获取到了 // context.getElementsByClassName(className) -> 在IE6-8下不兼容 // document.getElementsByName() -> 在IE浏览器中只对表单元素的name其作用 // document.body // document.documentElement // context.querySelector/ context.querySelectorAll -> 在IE6-8下不兼容,通过这个获取的节点集合不存在DOM映射 // -> 描述节点和节点之间关系的属性 (在标准的浏览器当中,会把空格换行和文本当做节点来处理) // childNodes // children -> IE6-8下获取的结果和标准浏览器下获取的结果不一致 // parentNode // previousSibling/ previousElementSibling // nextSibling/ nextElementSibling // lastChild/ lastElementChild // firstChild/ firstElementChild // -> DOM的增删改 // createElement // document.createDocumentFragment // appendChild // insertBefore // cloneNode(true/false) // replaceChild // removeChild // get/set/removeAttribute // -> DOM盒子模型 var oDiv = document.getElementById('div1'); console.log(oDiv.getElementsByTagName('span')); // -> 接下来写的所有方法在jQuery的作用和方法名一模一样 // -> function chilredn -> 获取某一个容器中的所有元素子节点(还可以筛选出指定标签名的) // -> function getElementsByClass -> 通过元素的样式类名获取一组元素(兼容所有浏览器) -> jQuery没有,但是jQuery的一部分选择器也是基于这个方法原理来实现的 // -> 获取上一个哥哥元素节点 (previous),获取下一个弟弟元素节点 (next)、获取所有哥哥元素节点 (prevAll)、获取所有弟弟元素节点 (nextAll)、获取相邻的两个元素节点 (sibling)、获取所有兄弟节点 (siblings) // -> 获取第一个元素子节点 (firstChild)、获取最后一个元素子节点 (lastChild) -> jQuery也没有 // -> index 获取当前元素的索引 // -> prepend -> 和appendChild对应,是增加到某一个容器开头 // insertAfter -> 和insertBefore对应,是增加到容器中某一个元素后面 // addClass 增加样式类名 // removeClass 删除样式类名 // hasClass 判断是否存在某一个样式 // -> jQuery: css // getCSS // setCSS // setGroupCSS // -> 基于内之泪的原型拓展一些常用的方法 </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>路由嵌套</title> </head> <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <body> <div id="app"> <router-link to="/login" replace>login</router-link> <router-link to="/register" replace>register</router-link> <router-view></router-view> </div> <template id="tmp"> <div> <p>我是register组件</p> <router-link to="/forget">forget</router-link> <router-view></router-view> </div> </template> <script> const LOG = { template: '<div>hello world</div>' } const REG = { template: "#tmp" } const FORGET = { template: '<div>我是register的子组件</div>' } // 注册并配置路由映射 const routes = [ { path: '/login', component: LOG }, { path: '/register', component: REG, children: [ { path: '/forget', component: FORGET, } ] } ] // 注册路由组件 const router = new VueRouter({ routes }) // 创建viewMode实例 new Vue({ el: '#app', data:{}, router }) </script> </body> </html>
| Name | Access Modifiers | Objects | Inhert From | Number Of Function | | ---- | ---------------- | ------- | ----------- | ------------------ | | ---- | Plublic | 2 | none | 11 | ## Objects ```C# VirustotalScaner VirustotalScaner = new VirustotalScaner(); ``` ```C# public static Form1 myform = Application.OpenForms.OfType<Form1>().FirstOrDefault(); ``` ## Methods | Name | Type | Access Modifiers | Description | | ---- | ---- | ---------------- | ----------- | | [GetProcessesInfo]() | Void | Public | Retrieve information about running processes | | [Process_StartTime]() | String | Public | Take a process ID as input and retrieves the start time of the corresponding process | | [Process_image_path]() | Static - String | Public | Take a process name as input and retrieves the executable path of the corresponding process | | [Number_Instances]() | Int | Public | Takes a process name as input and returns the number of instances of processes with that name | | [GetParentProcessId]() | Int | Private | Take a process ID as input and retrieves the parent process ID using WMI | | [Parent_process]() | String | Public | Take a process ID as input and retrieves the parent process ID | | [GetProcessUserAccount]() | String | Private | Retrieve the user account associated with a given process | | [GetProcessOwner]() | Static - String | Private | Retrieves the owner of a given process using WMI | | [P_user_acount]() | String | Public | Take a process name as input and returns the user account associated with that process | | [Process_Hash_MD5]() | Static - String | Public | Take a file path as input and calculates the MD5 hash of the file | | [VirusTotalScanner]() | Static - String | Public | This method is a placeholder for VirusTotal scanning functionality | <br> ## GetProcessesInfo The object of this function is to Retrieve information about running processes. ```c# public void GetProcessesInfo() { Process[] processes = Process.GetProcesses(); foreach (Process process in processes) { try { myform.processTable1.Rows.Add(process.ProcessName.ToLower(), process.Id, Parent_process(process.Id), Process_StartTime(process.Id), "Number_Instances(process.ProcessName)", Process_image_path(process.ProcessName), P_user_acount(process.ProcessName), Process_Hash_MD5(Process_image_path(process.ProcessName))," "); } catch (Exception ex) { } } } ``` Here's how the function works: - It uses the `Process.GetProcesses()` method to get an array of all running processes. - For each process, it adds relevant information to the `myform.processTable1` DataGridView control on the main form. - The added information includes process name, ID, parent process ID, start time, number of instances, executable path, user account, and an empty placeholder for the VirusTotal scan result. <br> ## Process_StartTime The object of this function is to Take a process ID as input and retrieves the start time of the corresponding process ```c# public string Process_StartTime(int pro_id) { string p_time = ""; try { Process process = Process.GetProcessById(pro_id); DateTime S_Time = process.StartTime; p_time = S_Time.ToString(); } catch (Exception e) { } return p_time; } ``` Here's how the function works: - It converts the process ID to a `Process` object and gets the start time from the `StartTime` property. - The start time is returned as a formatted string. <br> ## Process_image_path The object of this function is to Take a process name as input and retrieves the executable path of the corresponding process. ```c# public static string Process_image_path(string p_name) { Process[] processesq = Process.GetProcessesByName(p_name); string executablePath = ""; foreach (Process processa in processesq) { try { executablePath = processa.MainModule.FileName; } catch (Exception ex) { } } return executablePath; } ``` Here's how the function works: - It uses `Process.GetProcessesByName()` to get an array of processes with the given name. - For each process, it attempts to get the executable path from the `MainModule.FileName` property. - The executable path of the last process in the array is returned. <br> ## Number_Instances The object of this function is to Takes a process name as input and returns the number of instances of processes with that name. ```c# public int Number_Instances(string pr_name) { Process[] processes = Process.GetProcessesByName(pr_name); try { return processes.Length; } catch (Exception ex) { return processes.Length; } } ``` Here's how the function works: - It uses `Process.GetProcessesByName()` to get an array of processes with the given name and returns the array length. <br> ## GetParentProcessId The object of this function is to Take a process ID as input and retrieves the parent process ID using WMI ```c# private int GetParentProcessId(int processId) { string query = $"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {processId}"; using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { using (ManagementObjectCollection processList = searcher.Get()) { foreach (ManagementObject obj in processList) { return Convert.ToInt32(obj["ParentProcessId"]); } } } throw new Exception("Parent process not found."); } ``` Here's how the function works: - It executes a WMI query to retrieve the parent process ID from the `Win32_Process` class. - The parent process ID is returned as an integer. <br> ## Parent_process The object of this function is to Take a process ID as input and retrieves the parent process ID. ```c# public string Parent_process(int processId) { string parent = ""; int parentProcessId = GetParentProcessId(processId); try { parent = parentProcessId.ToString(); } catch (Exception e) { } return parent; } ``` Here's how the function works: - It calls the `GetParentProcessId()` method to get the parent process ID. - The parent process ID is returned as a string. <br> ## GetProcessUserAccount The object of this function is to Retrieve the user account associated with a given process. ```c# private string GetProcessUserAccount(string processName) { try { Process process = Process.GetProcessesByName(processName)[0]; string processOwner = GetProcessOwner(process); return processOwner; } catch (IndexOutOfRangeException) { throw new Exception("Process not found."); } catch (Exception ex) { throw new Exception("Error occurred while retrieving process user account.", ex); } } ``` Here's how the function works: - They use WMI queries to retrieve process information and the associated user account. - `GetProcessUserAccount()` calls `GetProcessOwner()` to extract the user account from the query result. <br> ## GetProcessOwner The object of this function is to provided retrieves the owner of a given process using WMI (Windows Management Instrumentation) queries. ```c# private static string GetProcessOwner(Process process) { string query = "SELECT * FROM Win32_Process WHERE ProcessId = " + process.Id; ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); ManagementObjectCollection processList = searcher.Get(); foreach (ManagementObject obj in processList) { string[] argList = new string[] { string.Empty, string.Empty }; int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)); if (returnVal == 0) { // argList[0] contains the domain, argList[1] contains the username return $"{argList[0]}\\{argList[1]}"; } } return "Unknown"; } ``` Here's how the function works: - The method takes a `Process` object as input, representing the process for which you want to retrieve the owner. - It constructs a WMI query using the process ID to find the corresponding process in the `Win32_Process` class. - It uses a `ManagementObjectSearcher` to execute the query and retrieve a collection of `ManagementObject` instances that match the query conditions. - The method then iterates through the collection of `ManagementObject` instances. - For each `ManagementObject`, it prepares an argument list (an array of strings) with two empty strings. - It invokes the method `GetOwner` on the `ManagementObject` instance, passing the argument list. - The return value of the `GetOwner` method is an integer. If the return value is 0, it means the method call was successful, and the owner information is available. - If the return value is 0, the method extracts the domain and username from the argument list and combines them to create the owner's full name in the format "domain\username". - If the return value is not 0, the method returns "Unknown" to indicate that the owner information could not be retrieved. - Finally, the method returns the owner information or "Unknown" depending on the result of the WMI query. <br> ## P_user_acount The object of this function is to Take a process name as input and returns the user account associated with that process. ```c# public string P_user_acount(string processName) { string processUserAccount = ""; try { processUserAccount = GetProcessUserAccount(processName); } catch (Exception ex) { } return (processUserAccount); } ``` Here's how the function works: - It calls the `GetProcessUserAccount()` method to get the user account. - The user account is returned as a string. <br> ## Process_Hash_MD5 The object of this function is to Take a file path as input and calculates the MD5 hash of the file. ```c# public static string Process_Hash_MD5(string file_path) { if(file_path == string.Empty) { return ""; } string output; using (var md5 = MD5.Create()) { using (var stream = File.OpenRead(file_path)) { byte[] checksum = md5.ComputeHash(stream); output = BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower(); return (output); } } } ``` Here's how the function works: - It uses the `MD5` class to compute the hash of the file contents. - The hash value is returned as a lowercase string. <br> ## VirusTotalScanner This method is a placeholder for VirusTotal scanning functionality. ```c# public static string VirusTotalScanner(string fileHash) { return ""; } ``` Here's how the function works: - It currently returns an empty string. <p> Overall, the `RuningProcessInfo` class provides methods to gather and display information about running processes, including process names, IDs, start times, executable paths, parent processes, user accounts, and MD5 hashes of process image files. Additionally, it includes a placeholder for VirusTotal scanning, which could be further developed to perform actual scanning operations. </p>