text
stringlengths
184
4.48M
using System.ComponentModel; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Identity; namespace AppCurso.ViewModels { public class UsuarioViewModel { [DisplayName("Código")] public int Id { get; set; } [DisplayName("E-mail")] [Required(ErrorMessage = "Campo obrigatório")] [EmailAddress(ErrorMessage = "E-mail inválido")] public string Email { get; set; } = ""; [DisplayName("Senha")] [Required(ErrorMessage = "Campo obrigatório")] [StringLength(100, ErrorMessage = "A senha deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 6)] [DataType(DataType.Password)] [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{6,}$", ErrorMessage = "A senha deve conter pelo menos uma letra maiúscula, uma letra minúscula, um caractere especial e um número.")] public string Senha { get; set; } = ""; [DisplayName("Confirmar Senha")] [Required(ErrorMessage = "Campo obrigatório")] [Compare("Senha", ErrorMessage = "As senhas não coincidem")] public string ConfirmacaoSenha { get; set; } = ""; } }
/** *Submitted for verification at Etherscan.io on 2022-11-28 */ // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract SetUp { mapping(address => mapping(address => bool)) onlyMasters; mapping(address => bytes[]) pubKeys; mapping(address => bytes[]) metadatas; uint fee; address _contractOwner; constructor() { _contractOwner = msg.sender; } modifier onlyMaster(address _address) { require(onlyMasters[_address][msg.sender], 'sender is not master'); _; } modifier onlyOwner() { require(_contractOwner == msg.sender, 'sender is not owner'); _; } function setMasters(address master_address) external { if (master_address == address(0x0)) { onlyMasters[msg.sender][msg.sender] = true; } else { onlyMasters[msg.sender][master_address] = true; } } function setPubKey(address _address, bytes[] memory _pubKey) external { if (pubKeys[_address].length != 0) { require( onlyMasters[_address][msg.sender], 'Data is set already and sender is not master.' ); } else { require( onlyMasters[_address][msg.sender] || _address == msg.sender, 'You cannot set the value for this address.' ); } pubKeys[_address] = _pubKey; } function setMetadata(address _address, bytes[] memory _metadata) external { if (metadatas[_address].length != 0) { require( onlyMasters[_address][msg.sender], 'Data is set already and sender is not master.' ); } else { require( onlyMasters[_address][msg.sender] || _address == msg.sender, 'You cannot set the value for this address.' ); } metadatas[_address] = _metadata; } function getMetadata( address _address ) external view returns (bytes[] memory _metadata) { return metadatas[_address]; } function isMasterAddress( address to_address, address master_address ) external view returns (bool isMaster) { return onlyMasters[to_address][master_address]; } function getPubKey( address _address ) external view returns (bytes[] memory _pubkey) { return pubKeys[_address]; } function setFee(uint new_fee) external onlyOwner { fee = new_fee; } }
package Part1; // // Title: Student Class // Author: Ceyda Kuşçuoğlu // Description: This class holds the student information and compare them according to their id,semesterNo and name // public class Student implements Comparable<Student> { private String name; // Holds the name value for student object private long id;// Holds the id value for student object private int semesterNo;// Holds the semester no value for student object public Student(String name, long id, int semesterNo) // // Summary: Assigns a value to the variables // Precondition: Name is a string,id is long and semesterNo is int // Postcondition: The value of the variables is set. // { this.name = name; this.id = id; this.semesterNo = semesterNo; } public String getName() { return name; } public long getId() { return id; } public int getSemesterNo() { return semesterNo; } @Override public int compareTo(Student other) // // Summary: Overrides compareTo method for student objects // Precondition: Takes student object // Postcondition: Students have been compared // { // Compare by id if (this.id < other.id) { return -1; } else if (this.id > other.id) { return 1; } // Compare by semesterNo if (this.semesterNo < other.semesterNo) { return -1; } else if (this.semesterNo > other.semesterNo) { return 1; } // Compare by name return this.name.compareTo(other.name); } }
import { createUserWithEmailAndPassword } from "firebase/auth"; import { useState } from "react"; import { notification } from "antd"; import { useNavigate } from "react-router"; import { auth } from "../firebase"; const inpClass = "bg-[#85789A] rounded-[20px] w-full px-3 py-1"; const labelClass = "text-[#85789A] text-[13px] font-bold p-2"; const SignUp = () => { const [formData, setFormData] = useState({ email: "", password: "", confirmPassword: "", }); const navigate = useNavigate(); function handleChange(e) { const { value, name } = e.target; setFormData({ ...formData, [name]: value, }); } async function handleSubmit(e) { e.preventDefault(); if (formData.password === formData.confirmPassword) { try { const userCredential = await createUserWithEmailAndPassword( auth, formData.email, formData.password ); const user = await userCredential.user; sessionStorage.setItem("userInfo", JSON.stringify(user)); navigate("/"); notification["success"]({ message: "Signed Up!", description: "You have successfully signed up!", }); setFormData({ email: "", password: "", confirmPassword: "", }); } catch (error) { notification["error"]({ message: "Error!", description: error.toString(), }); } } else { alert("Password confirmation does not match! Please, try again!"); } } return ( <form onSubmit={handleSubmit} className="flex flex-col gap-3"> <section> <p className={labelClass}>User Email</p> <input className={inpClass} type="text" name="email" id="email" minLength={6} maxLength={50} required onChange={handleChange} value={formData.email} /> </section> <section> <p className={labelClass}>Password</p> <input className={inpClass} type="password" name="password" id="password" minLength={6} maxLength={50} required onChange={handleChange} value={formData.password} /> </section> <section> <p className={labelClass}>Confirm Password</p> <input className={inpClass} type="password" name="confirmPassword" id="confirmPassword" minLength={6} maxLength={50} required onChange={handleChange} value={formData.confirmPassword} /> </section> <section className="flex items-center gap-1 ml-3"> <input type="checkbox" className="cursor-pointer" name="signedIn" id="signedIn" onChange={handleChange} checked={formData.signedIn} /> <label htmlFor="signedIn" className="text-white font-bold text-[11px]"> Keep Me Signed In </label> </section> <button className="bg-[#EEC110] m-2 rounded-2xl text-white font-bold text-[11px] p-[6px] "> SIGN UP </button> </form> ); }; export default SignUp;
<div id="users" class="page-layout carded fullwidth" fusePerfectScrollbar> <!-- TOP BACKGROUND --> <div class="top-bg mat-accent-bg"></div> <!-- / TOP BACKGROUND --> <!-- CENTER --> <div class="center"> <!-- HEADER --> <div class="header white-fg" fxLayout="column" fxLayoutAlign="center center" fxLayout.gt-xs="row" fxLayoutAlign.gt-xs="space-between center"> <!-- APP TITLE --> <div class="logo my-12 m-sm-0" fxLayout="row wrap" fxLayoutAlign="start center"> <button class="mr-0 mr-sm-16" mat-icon-button (click)="back()"> <mat-icon>arrow_back</mat-icon> </button> <!-- <mat-icon class="logo-icon mr-16" *fuseIfOnDom [@animate]="{value:'*',params:{delay:'50ms',scale:'0.2'}}">shopping_basket</mat-icon> --> <span class="logo-text h1" *fuseIfOnDom [@animate]="{value:'*',params:{delay:'100ms',x:'-25px'}}">{{member.name}}</span> </div> <!-- / APP TITLE --> <!-- SEARCH --> <div class="search-input-wrapper mx-12 m-md-0" fxFlex="1 0 auto" fxLayout="row wrap" fxLayoutAlign="start center"> <label for="search" class="mr-8"> <mat-icon class="secondary-text">search</mat-icon> </label> <mat-form-field floatPlaceholder="never" fxFlex="1 0 auto"> <input id="search" matInput #filter placeholder="Search"> </mat-form-field> </div> <!-- / SEARCH --> <button mat-raised-button [routerLink]="'/users/new/'+memberId" class="add-user-button mat-white-bg my-12 mt-sm-0"> <span>ADD NEW USER</span> </button> </div> <!-- / HEADER --> <!-- CONTENT CARD --> <div class="content-card mat-white-bg"> <mat-table class="users-table" #table [dataSource]="dataSource" matSort [@animateStagger]="{value:'50'}" fusePerfectScrollbar> <!-- ID Column --> <ng-container cdkColumnDef="id"> <mat-header-cell *cdkHeaderCellDef mat-sort-header>Id</mat-header-cell> <mat-cell *cdkCellDef="let user"> <p class="text-truncate">{{user.id}}</p> </mat-cell> </ng-container> <!-- Name Column --> <ng-container cdkColumnDef="name"> <mat-header-cell *cdkHeaderCellDef mat-sort-header>Name</mat-header-cell> <mat-cell *cdkCellDef="let user"> <p class="text-truncate">{{user.name}}</p> </mat-cell> </ng-container> <!-- Email Column --> <ng-container cdkColumnDef="email"> <mat-header-cell *cdkHeaderCellDef fxHide mat-sort-header fxShow.gt-md>Email</mat-header-cell> <mat-cell *cdkCellDef="let user" fxHide fxShow.gt-md> <p class="category text-truncate"> {{user.email}} </p> </mat-cell> </ng-container> <!-- userName Column --> <ng-container cdkColumnDef="userName"> <mat-header-cell *cdkHeaderCellDef mat-sort-header fxHide fxShow.gt-xs>User Name</mat-header-cell> <mat-cell *cdkCellDef="let user" fxHide fxShow.gt-xs> <p class="price text-truncate"> {{user.userName}} </p> </mat-cell> </ng-container> <!-- Action Column --> <ng-container cdkColumnDef="action"> <mat-header-cell *cdkHeaderCellDef>Action</mat-header-cell> <mat-cell *matCellDef="let user" (click)="$event.stopPropagation()"> <button mat-button (click)="onDelete(user.id)"> <mat-icon>delete</mat-icon> </button> </mat-cell> </ng-container> <mat-header-row *cdkHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *cdkRowDef="let user; columns: displayedColumns;" class="user" matRipple [routerLink]="'/users/'+user.id+'/'+memberId"> </mat-row> </mat-table> <mat-paginator #paginator [length]="dataSource.filteredData.length" [pageIndex]="0" [pageSize]="10" [pageSizeOptions]="[5, 10, 25, 100]" (page)="getServerPaginationData( $event )"> </mat-paginator> </div> <!-- / CONTENT CARD --> </div> <!-- / CENTER --> </div>
function [J, grad] = linearRegCostFunction(X, y, theta, lambda) %LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear %regression with multiple variables % [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the % cost of using theta as the parameter for linear regression to fit the % data points in X and y. Returns the cost in J and the gradient in grad m = length(y); J = (1/(2*m)) * sum((X * theta - y).^2, index=1) + (lambda / (2 * m)) * sum(theta(2:size(theta, 1)).^2); grad = (1/m) * ((X' * (X * theta - y)) + lambda * [0; theta(2:size(theta, 1))]); end
import { useState } from "react" import ErrorDialog from "./dialog/ErrorDialog" import HotkeysDialog from "./dialog/HotkeysDialog" import MessageDialog from "./dialog/MessageDialog" import WarningDialog from "./dialog/WarningDialog" interface CollapsableMessageProps { isCollapsedByDefault: boolean type?: "warn" | "error" | "info" | "hotkeys" onDismiss?: () => void dialog: { title: string message: JSX.Element | string } collapsedMessage: JSX.Element | string showCollapsedMessage?: boolean onConfirm?: () => void showSubHeader?: boolean } const CollapsableMessage = ({ isCollapsedByDefault, onDismiss, dialog, type = "warn", collapsedMessage, showCollapsedMessage = false, onConfirm, showSubHeader, }: CollapsableMessageProps) => { const [isCollapsed, setIsCollapsed] = useState(isCollapsedByDefault) const onClose = () => { setIsCollapsed(true) if (onDismiss) { onDismiss() } } const hotkeysOnDone = () => { setIsCollapsed(true) if (onConfirm) { onConfirm() } } let Dialog switch (type) { case "warn": Dialog = WarningDialog break case "error": Dialog = ErrorDialog break case "info": Dialog = MessageDialog break case "hotkeys": Dialog = HotkeysDialog break } return ( <> <div onClick={() => setIsCollapsed(false)} className="cursor-pointer" > {collapsedMessage} </div> {(!isCollapsed || showCollapsedMessage) && ( <Dialog open={true} title={dialog.title} message={dialog.message} buttonLabel="OK" onCancel={onClose} onDone={type === "hotkeys" ? hotkeysOnDone : onClose} onClickOutside={onClose} showSubHeader={showSubHeader} /> )} </> ) } export default CollapsableMessage
import { addMinutes, format, formatDistanceStrict, getTime } from 'date-fns'; import { Tournament } from '../../../../types/tournament'; import { formatTimeUntilTournament, getTournamentRange, } from '../../TournamentList/helpers'; const offsetTimezone = (date: Date, utcOffsetMinutes: number) => { const currentOffset = date.getTimezoneOffset(); return addMinutes(date, currentOffset + utcOffsetMinutes); }; export const isInSameTimeZone = (utcOffsetMinutes: number) => { const now = new Date(); return now.getTimezoneOffset() === utcOffsetMinutes * -1; }; export const getLocalTime = (utcOffsetMinutes: number) => { const now = new Date(); if (now.getDay() !== offsetTimezone(now, utcOffsetMinutes).getDay()) { return format(offsetTimezone(now, utcOffsetMinutes), 'eee LLL d h:mm aaa'); } return format(offsetTimezone(now, utcOffsetMinutes), 'h:mm aaa'); }; export const getLocalizedTournamentTime = ( tournament: Tournament, utcOffsetMinutes: number ) => { const [startDate] = getTournamentRange(tournament); let tournamentStartTime = new Date( Date.UTC( startDate.getFullYear(), startDate.getMonth(), startDate.getDate(), 8 - utcOffsetMinutes / 60, 30, 0 ) ); return tournamentStartTime; }; export const getRawTimeUntilTournament = ( tournament: Tournament, utcOffsetMinutes: number ) => getTime(getLocalizedTournamentTime(tournament, utcOffsetMinutes)) - getTime(new Date()); export const getTimeUntilTournament = ( tournament: Tournament, utcOffsetMinutes?: number ) => { if (!utcOffsetMinutes) { return formatTimeUntilTournament(tournament); } const tournamentStartTime = getLocalizedTournamentTime( tournament, utcOffsetMinutes ); // Ceil is fine closer to the tournament, because we don't usually start right at 9 AM. // For dates, two nights before would still be "two days" instead of "one day" rounded. return formatDistanceStrict(tournamentStartTime, new Date(), { roundingMethod: 'ceil', }); };
import React from 'react'; import Card from '@mui/material/Card'; import CardActions from '@mui/material/CardActions'; import CardContent from '@mui/material/CardContent'; import Button from '@mui/material/Button'; import Typography from '@mui/material/Typography'; import './CardArticles.css'; import EditArticle from './edit_article/EditArticle'; import Popup from '../../Popup_menu/Popup'; const CardArticles = ({article, getArticles}) => { const [anchorEl, setAnchorEl] = React.useState(null); const [open, setOpen] = React.useState(false); const [placement, setPlacement] = React.useState(); const handleClick = (newPlacement) => (event) => { setAnchorEl(event.currentTarget); setOpen((prev) => placement !== newPlacement || !prev); setPlacement(newPlacement); }; return ( <Card sx={{ minWidth: 275, mt: 1.5, mb: 1.5 }}> <CardContent> <Typography variant="h4" component="div"> {article.title} </Typography> <Typography sx={{ mb: 1.5 }} color="text.secondary"> {article.author.username} </Typography> <Typography variant="body3"> {article.description} </Typography> <Typography variant="body2" sx={{ mt: 1.5 }}> {article.body} </Typography> </CardContent> <CardActions className='card__footer'> <Button onClick={handleClick('bottom-start')} size="small">Edit article</Button> <Popup anchorEl={anchorEl} open={open} placement={placement}> <EditArticle getArticles={getArticles} article={article}/> </Popup> </CardActions> </Card> ); } export default CardArticles;
// Copyright (C) 2015 basysKom GmbH, opensource@basyskom.com // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef QOPCUANODE_H #define QOPCUANODE_H #include <QtOpcUa/qopcuabrowserequest.h> #include <QtOpcUa/qopcuaglobal.h> #include <QtOpcUa/qopcuamonitoringparameters.h> #include <QtOpcUa/qopcuareferencedescription.h> #include <QtOpcUa/qopcuatype.h> #include <QtOpcUa/qopcuabrowsepathtarget.h> #include <QtOpcUa/qopcuarelativepathelement.h> #include <QtCore/qdatetime.h> #include <QtCore/qdebug.h> #include <QtCore/qvariant.h> #include <QtCore/qobject.h> #include <QtCore/qmap.h> QT_BEGIN_NAMESPACE class QOpcUaNodePrivate; class QOpcUaNodeImpl; class QOpcUaClient; class QOpcUaHistoryReadRawRequest; class QOpcUaHistoryReadResponse; class Q_OPCUA_EXPORT QOpcUaNode : public QObject { Q_OBJECT public: Q_DECLARE_PRIVATE(QOpcUaNode) static Q_DECL_CONSTEXPR QOpcUa::NodeAttributes mandatoryBaseAttributes(); static Q_DECL_CONSTEXPR QOpcUa::NodeAttributes allBaseAttributes(); typedef QMap<QOpcUa::NodeAttribute, QVariant> AttributeMap; QOpcUaNode(QOpcUaNodeImpl *impl, QOpcUaClient *client, QObject *parent = nullptr); virtual ~QOpcUaNode(); bool readAttributes(QOpcUa::NodeAttributes attributes = mandatoryBaseAttributes()); bool readAttributeRange(QOpcUa::NodeAttribute attribute, const QString &indexRange); bool readValueAttribute(); QVariant attribute(QOpcUa::NodeAttribute attribute) const; QVariant valueAttribute() const; QOpcUa::UaStatusCode attributeError(QOpcUa::NodeAttribute attribute) const; QOpcUa::UaStatusCode valueAttributeError() const; QDateTime sourceTimestamp(QOpcUa::NodeAttribute attribute) const; QDateTime serverTimestamp(QOpcUa::NodeAttribute attribute) const; bool writeAttribute(QOpcUa::NodeAttribute attribute, const QVariant &value, QOpcUa::Types type = QOpcUa::Types::Undefined); bool writeAttributeRange(QOpcUa::NodeAttribute attribute, const QVariant &value, const QString &indexRange, QOpcUa::Types type = QOpcUa::Types::Undefined); bool writeAttributes(const AttributeMap &toWrite, QOpcUa::Types valueAttributeType = QOpcUa::Types::Undefined); bool writeValueAttribute(const QVariant &value, QOpcUa::Types type = QOpcUa::Types::Undefined); bool enableMonitoring(QOpcUa::NodeAttributes attr, const QOpcUaMonitoringParameters &settings); bool disableMonitoring(QOpcUa::NodeAttributes attr); bool modifyMonitoring(QOpcUa::NodeAttribute attr, QOpcUaMonitoringParameters::Parameter item, const QVariant &value); QOpcUaMonitoringParameters monitoringStatus(QOpcUa::NodeAttribute attr); bool modifyEventFilter(const QOpcUaMonitoringParameters::EventFilter &eventFilter); bool modifyDataChangeFilter(QOpcUa::NodeAttribute attr, const QOpcUaMonitoringParameters::DataChangeFilter &filter); bool browseChildren(QOpcUa::ReferenceTypeId referenceType = QOpcUa::ReferenceTypeId::HierarchicalReferences, QOpcUa::NodeClasses nodeClassMask = QOpcUa::NodeClass::Undefined); QString nodeId() const; QOpcUaClient *client() const; bool callMethod(const QString &methodNodeId, const QList<QOpcUa::TypedVariant> &args = QList<QOpcUa::TypedVariant>()); bool resolveBrowsePath(const QList<QOpcUaRelativePathElement> &path); bool browse(const QOpcUaBrowseRequest &request); QOpcUaHistoryReadResponse *readHistoryRaw(const QDateTime &startTime, const QDateTime &endTime, quint32 numValues, bool returnBounds); QOpcUaHistoryReadResponse *readHistoryRaw(const QDateTime &startTime, const QDateTime &endTime, quint32 numValues, bool returnBounds, QOpcUa::TimestampsToReturn timestampsToReturn); QOpcUaHistoryReadResponse *readHistoryEvents(const QDateTime &startTime, const QDateTime &endTime, QOpcUaMonitoringParameters::EventFilter &filter, quint32 numValues = 0); Q_SIGNALS: void attributeRead(QOpcUa::NodeAttributes attributes); void attributeWritten(QOpcUa::NodeAttribute attribute, QOpcUa::UaStatusCode statusCode); void dataChangeOccurred(QOpcUa::NodeAttribute attr, QVariant value); void attributeUpdated(QOpcUa::NodeAttribute attr, QVariant value); void valueAttributeUpdated(const QVariant &value); void eventOccurred(QVariantList eventFields); void monitoringStatusChanged(QOpcUa::NodeAttribute attr, QOpcUaMonitoringParameters::Parameters items, QOpcUa::UaStatusCode statusCode); void enableMonitoringFinished(QOpcUa::NodeAttribute attr, QOpcUa::UaStatusCode statusCode); void disableMonitoringFinished(QOpcUa::NodeAttribute attr, QOpcUa::UaStatusCode statusCode); void methodCallFinished(QString methodNodeId, QVariant result, QOpcUa::UaStatusCode statusCode); void browseFinished(QList<QOpcUaReferenceDescription> children, QOpcUa::UaStatusCode statusCode); void resolveBrowsePathFinished(QList<QOpcUaBrowsePathTarget> targets, QList<QOpcUaRelativePathElement> path, QOpcUa::UaStatusCode statusCode); private: Q_DISABLE_COPY(QOpcUaNode) }; Q_OPCUA_EXPORT QDebug operator<<(QDebug dbg, const QOpcUaNode &node); QT_END_NAMESPACE Q_DECLARE_METATYPE(QOpcUaNode::AttributeMap) inline Q_DECL_CONSTEXPR QOpcUa::NodeAttributes QOpcUaNode::mandatoryBaseAttributes() { return QOpcUa::NodeAttribute::NodeId | QOpcUa::NodeAttribute::NodeClass | QOpcUa::NodeAttribute::BrowseName | QOpcUa::NodeAttribute::DisplayName; } inline Q_DECL_CONSTEXPR QOpcUa::NodeAttributes QOpcUaNode::allBaseAttributes() { return QOpcUa::NodeAttribute::NodeId | QOpcUa::NodeAttribute::NodeClass | QOpcUa::NodeAttribute::BrowseName | QOpcUa::NodeAttribute::DisplayName | QOpcUa::NodeAttribute::Description | QOpcUa::NodeAttribute::WriteMask | QOpcUa::NodeAttribute::UserWriteMask; } #endif // QOPCUANODE_H
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>Adelaide 36ers not Official Website</title> <!-- css link --> <!-- <link rel="stylesheet" href="css/style.css" />--> <!-- fontawesome CDN --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" /> <!-- end of fontawesome CDN --> <link rel="shortcut icon" href="assets/fav.png" /> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Bootstrap CDN for Carousel --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous" /> <!-- css --> <link rel="stylesheet" href="style.css" /> <!-- google fonts --> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Anton&family=Changa+One:ital@0;1&family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet" /> <!-- font awesome --> <!-- <script src="https://kit.fontawesome.com/d7456ee4cf.js" crossorigin="anonymous"></script>--> <!-- Bootstrap JS for carousel --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous" ></script> </head> <body> <header> <div class="navWrapper"> <nav class="menuBar"> <div class="logoContainer"> <h4 class="logo"> <span class="red"><span class="blue">.</span>fan</span ><span class="blue">Shop</span> </h4> </div> <div class="navigationContainer"> <ul class="navLinks"> <!-- <li><a class="navLink" href="#">Arrivals</a></li>--> <li> <a class="navLink" href="https://adelaide36ersstore.com/collections" >Clothing</a > </li> <!-- <li><a class="navLink" href="#">Newsletter</a></li>--> <li> <a class="navLink" href="https://www.adelaide36ers.com/pages/club-staff" >Contact</a > </li> </ul> </div> </nav> </div> <div class="textWrapper"> <div class="textContainer"> <h1 class="mainHeading"> Basketball<br /> is Back<span class="blue">.</span> </h1> <h2 class="subHeading"> Welcome to the promo landing page!<br /> The most convenient location to purchase your merchandise. </h2> <span ><button class="mainButton" onclick="window.location.href='https://adelaide36ersstore.com';" > Shop now </button></span > </div> </div> </header> <main> <section class="newArrivals"> <h2 class="text-center">New Arrivals<span class="red">.</span></h2> <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel" > <div class="carousel-inner"> <div class="carousel-item active"> <img src="images/1.png" class="d-block w-30 mx-auto img-fluid" alt="..." /> </div> <div class="carousel-item"> <img src="images/2.png" class="d-block w-30 mx-auto img-fluid" alt="..." /> </div> <div class="carousel-item"> <img src="images/3.png" class="d-block w-30 mx-auto img-fluid" alt="..." /> </div> </div> <a class="carousel-control-prev" href="#carouselExampleCaptions" role="button" data-bs-slide="prev" > <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleCaptions" role="button" data-bs-slide="next" > <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </a> </div> <div class="btnContainer"> <!-- <button class="button redBack">Add to cart</button> --> <button class="button blueBack" onclick="window.location.href='https://adelaide36ersstore.com/collections/new';" > See more </button> </div> </section> <section class="clothingSection"> <div class="clothingWrapper"> <div class="clothingContainer"> <a href="https://adelaide36ersstore.com/collections/youth"> <div class="leftImg imageStyle"></div> <div class="bottomBtn blueBack"> <p>YOUTH</p> </div> </a> </div> <div class="clothingContainer"> <a href="https://adelaide36ersstore.com/collections/women"> <div class="rightImg imageStyle"></div> <div class="bottomBtn redBack"> <p>WOMEN</p> </div> </a> </div> </div> </section> <section class="newsletter"> <h1>Sign Up and get deals to your Inbox<span class="red">.</span></h1> <form action="https://formspree.io/f/mknybekg" method="POST"> <input type="email" placeholder="Email Address" name="email" /> <button class="subscribe" type="submit">Subscribe</button> </form> </section> </main> <footer> <h4 class="logo"> <span class="red"><span class="blue">.</span>fan</span ><span class="blue">Shop</span> </h4> <div class="socialContainer"> <a href="https://www.facebook.com/Adelaide36ers" ><i class="fab fa-facebook-f"></i ></a> <a href="https://twitter.com/Adelaide36ers" ><i class="fab fa-twitter"></i ></a> <a href="https://www.instagram.com/adelaide36ers" ><i class="fab fa-instagram"></i ></a> <a href="https://www.youtube.com/user/36ersTV" ><i class="fab fa-youtube"></i ></a> </div> </footer> </body> </html>
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; // https://www.acmicpc.net/problem/1976 public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static int N, M; static int[] parent; public static void main(String[] args) throws IOException { // union find 로 조상을 만들어 준다 // 모든 여행지의 조상이 같으면 YES 출력, 아니면 NO 출력 N = Integer.parseInt(br.readLine()); M = Integer.parseInt(br.readLine()); parent = new int[N]; for(int i=0; i<N; i++) { parent[i] = i; } for(int i=0; i<N; i++) { st = new StringTokenizer(br.readLine()); for(int j=0; j<N; j++) { if(Integer.parseInt(st.nextToken()) == 1) { union(i, j); } } // for(j) } // for(i) st = new StringTokenizer(br.readLine()); int tmp = find(Integer.parseInt(st.nextToken())-1); for(int i=1; i<M; i++) { if(find(Integer.parseInt(st.nextToken())-1)!=tmp) { System.out.println("NO"); System.exit(0); } } System.out.println("YES"); } // main() public static int find(int a) { if(parent[a] == a) { return a; }else { return parent[a] = find(parent[a]); } } public static void union(int a, int b) { a = find(a); b = find(b); if(a!=b) { parent[b] = a; } } }
<template> <div> <h1>Odczytaj wiadomość</h1> <form @submit.prevent="getMessage"> <label for="uuid">UUID:</label> <input v-model="uuid" type="text" id="uuid" name="uuid" required> <button type="submit">Pobierz</button> </form> <div v-if="messageData"> <h2>Wiadomość:</h2> <p><strong>UUID:</strong> {{ messageData.uuid }}</p> <p><strong>Wiadomość:</strong> {{ messageData.message }}</p> <p><strong>Utworzono:</strong> {{ messageData.created_at }}</p> </div> </div> </template> <script> export default { data() { return { uuid: '', messageData: null, }; }, methods: { async getMessage() { try { const uuid = this.uuid; const response = await fetch(`http://127.0.0.1:8000/api/message/${uuid}`); if (response.ok) { this.messageData = await response.json(); } else { alert('Wystąpił błąd podczas pobierania wiadomości.'); this.messageData = null; } } catch (error) { console.error('Wystąpił błąd:', error); this.messageData = null; } }, }, }; </script>
import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:real_world_flutter/domain/repository/user_repository.dart'; import 'package:real_world_flutter/domain/util/logger.dart'; import 'package:real_world_flutter/presentation/navigation/app_navigation.dart'; import 'package:real_world_flutter/presentation/ui/auth/organisms/sign_up/sign_up_view_model.dart'; typedef _Vm = SignUpViewModel; typedef _Notifier = SignUpStateNotifier; typedef _Provider = AutoDisposeStateNotifierProvider<_Notifier, _Vm>; class SignUpStateNotifier extends StateNotifier<_Vm> { final UserRepository _userRepository; final GoRouter _goRouter; SignUpStateNotifier( super.state, this._userRepository, this._goRouter, ); static final provider = _Provider((ref) { return _Notifier( const _Vm(), ref.watch(UserRepository.provider), ref.watch(AppNavigation.provider).router, ); }); void onUpdateUsername(String? value) { state = _updateEnableOfSignUp( state.copyWith(username: value ?? ''), ); } void onUpdateEmail(String? value) { state = _updateEnableOfSignUp( state.copyWith(email: value ?? ''), ); } void onUpdatePassword(String? value) { state = _updateEnableOfSignUp( state.copyWith(password: value ?? ''), ); } void onTapHaveAccount() { _goRouter.go('/login'); } void onTapErrorDialogOk() { state = state.copyWith(errorMessage: null); } Future<void> onTapSignUp() async { state = state.copyWith(isLoading: true); if (state.email.isEmpty || state.password.isEmpty) { state = state.copyWith( errorMessage: 'Please Enter Email and Password.', ); return; } final result = await _userRepository.signUp( username: state.username, email: state.email, password: state.password, ); result.when( success: (user) { pLogger.d(user.toJson()); state = state.copyWith(isLoading: false); }, failed: (err) { pLogger.e(err.toJson()); state = state.copyWith( isLoading: false, errorMessage: err.message, ); }, ); } _Vm _updateEnableOfSignUp(_Vm newState) { return newState.copyWith( isEnableSignUpButton: newState.username.isNotEmpty && newState.email.isNotEmpty && newState.password.isNotEmpty, ); } }
# FHIR Client Service This is a demo Python Flask application that serves as a client service for interacting with a FHIR (Fast Healthcare Interoperability Resources) server. It provides a set of RESTful API endpoints for creating and retrieving FHIR resources such as patients, observations, medications, and conditions. ## Prerequisites Before running the application, make sure you have the project prerequisites installed: ``` pip install -r requirements.txt ``` ## Configuration The application requires certain configuration settings to be set up before running. These settings are stored in a `.env` file. Create a file named `.env` in the project root directory and provide the following configuration variables: ``` APP_ID=your_app_id API_BASE=your_fhir_server_base_url APP_SECRET=your_app_secret REDIRECT_URI=your_redirect_uri ``` Replace `your_app_id`, `your_fhir_server_base_url`, `your_app_secret`, and `your_redirect_uri` with the appropriate values for your FHIR server and application setup. ## Running the Application To run the application locally, execute the following command in the project root directory: ``` flask run --debug ``` The application will start running on `http://localhost:5000`. ## API Endpoints The application provides the following API endpoints: ### Patient - `GET /patient/<patient_id>`: Retrieve a patient by ID. - `POST /patient`: Create a new patient. ### Observation - `GET /observation/<observation_id>`: Retrieve an observation by ID. - `POST /observation`: Create a new observation. ### Medication - `GET /medication/<medication_id>`: Retrieve a medication by ID. - `POST /medication`: Create a new medication. ### Condition - `GET /condition/<condition_id>`: Retrieve a condition by ID. - `POST /condition`: Create a new condition. ## FHIR Compliance This application aims to comply with the FHIR v4 specification. It uses the `fhirclient` library to interact with the FHIR server and handle FHIR resources. ## Error Handling The application handles common error scenarios, such as resource not found (404 error). When a requested resource is not found, the application returns an appropriate error response in JSON format.
import { useState, useEffect } from "react"; import { Box, TextField, Autocomplete, CircularProgress, Avatar, } from "@mui/material"; import { usePeople } from "../../hooks/usePeople"; const server = process.env.REACT_APP_BASE_SERVER; export default function PeoplePicker({ itemListId, setItemData }) { const [open, setOpen] = useState(false); const { people, getByListId, loading } = usePeople(itemListId); useEffect(() => { if (open) { getByListId(); } }, [open, getByListId, itemListId]); return ( <Autocomplete open={open} onChange={(e, value) => setItemData("assignedToUser", value?._id)} onOpen={() => { setOpen(true); }} onClose={() => { setOpen(false); }} isOptionEqualToValue={(option, value) => option.displayName === value.displayName } getOptionLabel={(option) => option.displayName} options={people} loading={loading} renderOption={(props, option) => ( <Box {...props}> <Avatar sx={{ marginRight: "1rem" }} src={`${server}${option.avatar}`} alt={option.displayName} /> {option.displayName} </Box> )} renderInput={(params) => ( <TextField {...params} label="Assign To User" InputProps={{ ...params.InputProps, endAdornment: ( <> {loading ? ( <CircularProgress color="inherit" size={20} /> ) : null} {params.InputProps.endAdornment} </> ), }} /> )} /> ); }
import { useState } from 'react'; import { Link } from 'react-router-dom'; import { useMutation } from '@apollo/client'; import { ADD_USER } from '../../utils/mutations.js'; import Auth from '../../utils/auth.js'; const Signup = () => { const [formState, setFormState] = useState({ username: '', email: '', password: '', }); const [addUser, { error, data }] = useMutation(ADD_USER); const handleChange = (event) => { const { name, value } = event.target; setFormState({ ...formState, [name]: value, }); }; const handleFormSubmit = async (event) => { event.preventDefault(); console.log(formState); try { const { data } = await addUser({ variables: { ...formState }, }); Auth.login(data.addUser.token); } catch (e) { console.error(e); } }; return ( <main className=""> {/* <h4 className="center">Sign Up</h4> */} <div className="flexCol"> {data ? ( <p> Success! You may now head{' '} <Link to="/">back to the homepage.</Link> </p> ) : ( <form className='flexCol login-card' onSubmit={handleFormSubmit}> <h2 className="center">Sign Up</h2> <input className="signup-form-input" placeholder="Create a Username" name="username" type="text" value={formState.name} onChange={handleChange} /> <input className="signup-form-input" placeholder="Enter Email" name="email" type="email" value={formState.email} onChange={handleChange} /> <input className="signup-form-input" placeholder="Create a Password" name="password" type="password" value={formState.password} onChange={handleChange} /> <button className="button" style={{ cursor: 'pointer' }} type="submit" > Sign Up </button> </form> )} {error && ( <div className=""> {error.message} </div> )} </div> </main> ); }; export default Signup;
import { useState } from "react"; import TodoItem from "./TodoItem"; import TodoSearch from "./TodoSearch"; const TodoList = ({todo, onUpdate, onDelete, onEdit, onModify}) => { const [search, setSearch] = useState(""); const onChangeSearch = (e) => { setSearch(e.target.value); } const getSearchResult = () => { return search === "" ? todo : todo.filter((it) => it.content.toLowerCase().includes(search.toLowerCase())) }; return (<div className="TodoList"> <div className="list_wrapper"> {getSearchResult().map((it) => ( <TodoItem key={it.id} {...it} onUpdate={onUpdate} onDelete={onDelete} onEdit={onEdit} onModify={onModify}/>)) } </div> <TodoSearch search={search} onChangeSearch={onChangeSearch} /> </div>) }; export default TodoList;
import { z, defineCollection } from "astro:content" const blog = defineCollection({ schema: z.object({ title: z.string(), subtitle: z.string().optional(), description: z.string().max(250), pubDate: z.string().transform((str) => new Date(str)), update: z .string() .transform((str) => new Date(str)) .optional(), mainImg: z .string() .transform((str) => `/images/blog/${str}`) .optional(), tags: z.array(z.string()), next: z .object({ text: z.string(), link: z.string(), }) .optional(), previus: z .object({ text: z.string(), link: z.string(), }) .optional(), }), }) export const collections = { blog }
package com.shopfam.admin.category; import com.shopfam.common.entity.*; import com.shopfam.common.exception.CategoryNotFoundException; import org.springframework.data.domain.*; import jakarta.transaction.Transactional; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeSet; import java.util.Comparator; import java.util.SortedSet; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @Transactional public class CategoryService { public static final int ROOT_CATEGORIES_PER_PAGE = 4; @Autowired private CategoryRepository repo; public List<Category> listByPage(CategoryPageInfo pageInfo , int pageNum , String sortDir , String keyword){ Sort sort = Sort.by("name"); if(sortDir.equals("asc")) { sort = sort.ascending(); }else if (sortDir.equals("desc")){ sort = sort.descending(); } Pageable pageable = PageRequest.of(pageNum -1, ROOT_CATEGORIES_PER_PAGE , sort); Page<Category> pageCategories = null; if(keyword != null && !keyword.isEmpty()) { pageCategories = repo.search(keyword ,pageable); }else { pageCategories = repo.findRootCategories(pageable); } List<Category> rootCategories = pageCategories.getContent(); pageInfo.setTotalElements(pageCategories.getTotalElements()); pageInfo.setTotalPages(pageCategories.getTotalPages()); if(keyword != null && !keyword.isEmpty()) { List<Category> searchResult = pageCategories.getContent(); for (Category category : searchResult) { category.setHasChildren(category.getChildren().size() > 0); } return searchResult; }else { return listHierarchicalCategories(rootCategories , sortDir); } } private List<Category> listHierarchicalCategories(List<Category> rootCategories , String sortDir){ List<Category> HierarchicalCategories = new ArrayList<>(); for(Category rootCategory : rootCategories) { HierarchicalCategories.add(Category.copyFull(rootCategory)); Set<Category> children = sortSubCategories(rootCategory.getChildren() , sortDir); for(Category subCategory : children) { String name = "--" + subCategory.getName(); HierarchicalCategories.add(Category.copyFull(subCategory , name)); listSubHierarchicalCategories(HierarchicalCategories , subCategory , 1 , sortDir); } } return HierarchicalCategories; } private void listSubHierarchicalCategories( List<Category> HierarchicalCategories, Category parent , int subLevel , String sortDir) { Set<Category> children = sortSubCategories(parent.getChildren() , sortDir); int newSubLevel = subLevel + 1; for(Category subCategory : children) { String name = ""; for(int i = 0 ; i < newSubLevel ; i++) { name += "--"; } name += subCategory.getName(); HierarchicalCategories.add(Category.copyFull(subCategory , name)); listSubHierarchicalCategories(HierarchicalCategories , subCategory , newSubLevel , sortDir); } } public Category save(Category category) { Category parent = category.getParent(); if(parent!= null) { String allParentIds = parent.getAllParentIDs() == null ? "-" : parent.getAllParentIDs(); allParentIds += String.valueOf(parent.getId()) + "-"; category.setAllParentIDs(allParentIds); } return repo.save(category); } public List<Category> listCategoriesUsedInForm(){ List<Category> categoriesUsedInForm = new ArrayList<>(); Iterable<Category> categoriesInDB = repo.findRootCategories(Sort.by("name").ascending()); for (Category category : categoriesInDB) { categoriesUsedInForm.add(Category.copyIdAndName(category)); Set<Category> children = sortSubCategories(category.getChildren()); for(Category subCategory : children) { String name = "--" + subCategory.getName(); categoriesUsedInForm.add(Category.copyIdAndName(subCategory.getId() , name)); listSubCategoriesUsedInForm(categoriesUsedInForm , subCategory , 1); } } return categoriesUsedInForm; } private void listSubCategoriesUsedInForm(List<Category> categoriesUsedInForm, Category parent , int subLevel) { int newSubLevel = subLevel + 1; Set<Category> children = sortSubCategories(parent.getChildren()); for(Category subCategory : children ) { String name = ""; for(int i=0;i<newSubLevel ; i++) { name += "--"; } name += subCategory.getName(); categoriesUsedInForm.add(Category.copyIdAndName(subCategory.getId() , name)); listSubCategoriesUsedInForm(categoriesUsedInForm , subCategory , newSubLevel); } } public Category get(Integer id) throws CategoryNotFoundException{ try { return repo.findById(id).get(); }catch (NoSuchElementException ex) { throw new CategoryNotFoundException("Could not find any category with ID" + id); } } public String checkUnique(Integer id ,String name , String alias) { boolean isCreatingNew = (id == null || id == 0); Category categoryByName = repo.findByName(name); if(isCreatingNew) { if(categoryByName != null) { return "DuplicateName"; }else { Category categoryByAlias = repo.findByAlias(alias); if(categoryByAlias != null) { return "DuplicateAlias"; } } }else { if(categoryByName != null && categoryByName.getId() != id) { return "DuplicateName"; } Category categoryByAlias = repo.findByAlias(alias); if(categoryByAlias != null && categoryByAlias.getId()!=id) { return "DuplicateAlias"; } } return "OK"; } private SortedSet<Category> sortSubCategories(Set<Category> children){ return sortSubCategories(children , "asc"); } private SortedSet<Category> sortSubCategories(Set<Category> children , String sortDir){ SortedSet<Category> sortedChildren = new TreeSet<>(new Comparator<Category>() { @Override public int compare(Category cat1, Category cat2) { if(sortDir.equals("asc")) { return cat1.getName().compareTo(cat2.getName()); }else { return cat2.getName().compareTo(cat1.getName()); } } }); sortedChildren.addAll(children); return sortedChildren; } public void updateCategoryEnabledStatus(Integer id , boolean enabled) { repo.updateEnabledStatus(id, enabled); } public void delete(Integer id) throws CategoryNotFoundException { Long countById = repo.countById(id); if(countById == null || countById == 0) { throw new CategoryNotFoundException("Could not find any category with ID " + id); } repo.deleteById(id); } }
const locator = require('../locator/LoginPageLocator') class LoginPage { async visit(path) { cy.visit(path) return cy.url().should('eq', path) } async verify_login_page() { cy.xpath(locator.datatestid.logo, { timeout: 10000 }).should('be.visible') cy.xpath(locator.datatestid.login_text_title, { timeout: 10000 }).should('be.visible') cy.xpath(locator.datatestid.email_input, { timeout: 10000 }).should('be.visible') cy.xpath(locator.datatestid.pass_input, { timeout: 10000 }).should('be.visible') cy.xpath(locator.datatestid.btn_login, { timeout: 10000 }).should('be.visible') } async type_email(email) { cy.xpath(locator.datatestid.email_input) .type(email) .should('have.value', email) } async type_password(password) { cy.xpath(locator.datatestid.pass_input) .type(password) .should('have.value', password) } async click_login_button() { cy.xpath(locator.datatestid.btn_login).click() } async verify_login_failed() { cy.get(locator.datatestid.err_login_message).should('be.visible') } } module.exports = LoginPage
/* eslint-disable prettier/prettier */ import { Body, Controller, Delete, Get, HttpCode, Param, Post, Put, UseGuards, UseInterceptors } from '@nestjs/common'; import { plainToInstance } from 'class-transformer'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { RestauranteEspecializadoDto } from '../restaurante-especializado/restaurante-especializado.dto'; import { RestauranteEspecializadoEntity } from '../restaurante-especializado/restaurante-especializado.entity'; import { Role } from '../user/role.enum'; import { Roles } from '../user/roles.decorator'; import { BusinessErrorsInterceptor } from '../shared/interceptors/business-errors.interceptor'; import { PaisRestauranteService } from './pais-restaurante.service'; @UseGuards(JwtAuthGuard) @Controller('paises') @UseInterceptors(BusinessErrorsInterceptor) export class PaisRestauranteController { constructor(private readonly paisRestauranteService: PaisRestauranteService) { } @Post(':paisId/restaurantesEspecializados/:restauranteId') @Roles(Role.ADMIN, Role.USERW) async addRestaurantePais(@Param('paisId') paisId: string, @Param('restauranteId') restauranteId: string) { return await this.paisRestauranteService.addRestaurantePais(paisId, restauranteId); } @Get(':paisId/restaurantesEspecializados/:restauranteId') @Roles(Role.ADMIN, Role.READALL) async findRestauranteByPaisIdRestauranteId(@Param('paisId') paisId: string, @Param('restauranteId') restauranteId: string) { return await this.paisRestauranteService.findRestauranteByPaisIdRestauranteId(paisId, restauranteId); } @Get(':paisId/restaurantesEspecializados') @Roles(Role.ADMIN, Role.READALL) async findRestaurantesByPaisId(@Param('paisId') paisId: string) { return await this.paisRestauranteService.findRestaurantesByPaisId(paisId); } @Put(':paisId/restaurantesEspecializados') @Roles(Role.ADMIN, Role.USERW) async associateRestaurantesPais(@Body() restaurantesDto: RestauranteEspecializadoDto[], @Param('paisId') paisId: string) { const restaurantes = plainToInstance(RestauranteEspecializadoEntity, restaurantesDto) return await this.paisRestauranteService.associateRestaurantesPais(paisId, restaurantes); } @Delete(':paisId/restaurantesEspecializados/:restauranteId') @Roles(Role.ADMIN, Role.USERD) @HttpCode(204) async deleteRestaurantePais(@Param('paisId') paisId: string, @Param('restauranteId') restauranteId: string) { return await this.paisRestauranteService.deleteRestaurantePais(paisId, restauranteId); } }
import { Workbook, Worksheet, Fill } from 'exceljs'; import { TripRequest } from '../../database'; import Utils from '../../utils/index'; import generateReportData from './ReportData'; class GenerateExcelBook { getCellStyle(isColHeader: boolean) { if (isColHeader) { return { name: 'Times New Roman', color: { argb: '000000' }, family: 2, size: 13, bold: true, }; } return { name: 'Times New Roman', color: { argb: '000000' }, size: 11, bold: false, }; } getCellFillColor(color: string) { return { type: 'gradient', gradient: 'angle', degree: 0, stops: [ { position: 0, color: { argb: color } }, { position: 1, color: { argb: color } }, ], }; } getWorkBook(tripData: TripRequest[]): Workbook { const workbook = this.getNewWorkBook(2); const sheet1 = workbook.getWorksheet(1); this.prepareSummary(sheet1, tripData); const sheet2 = workbook.getWorksheet(2); sheet2.name = 'Trip Details'; sheet2.mergeCells('A2:K3'); sheet2.columns.forEach((column) => { // eslint-disable-next-line no-param-reassign column.width = 24; }); const pageHeader = sheet2.getCell('K3'); this.prepareSheetMainHeader(pageHeader, 'Details'); const headers = [ 'S/N', 'Requested On', 'Departure Date', 'Pickup', 'Destination', 'Requested By', 'Department', 'Passenger', 'Approved By', 'Confirmed By', ]; this.populateSheetRowData(sheet2, headers, 'A', 5, true); this.generateRows(sheet2, tripData, 'A', 6); return workbook; } getNewWorkBook(numberOfSheets: number): Workbook { const workBook = new Workbook(); workBook.lastModifiedBy = 'Tembea Bot'; workBook.created = new Date(); workBook.modified = new Date(); for (let i = 1; i <= numberOfSheets; i += 1) { workBook.addWorksheet(`Sheet${i}`); } return workBook; } prepareSummaryCellHeader(summaryCell: any): void { const summaryCellHeader = summaryCell; summaryCellHeader.value = 'Summary'; summaryCellHeader.alignment = { vertical: 'middle', horizontal: 'center' }; summaryCellHeader.font = { color: { argb: 'ffffff' }, bold: true, family: 1, size: 14, name: 'Times New Roman', }; summaryCellHeader.fill = this.getCellFillColor('1768ff'); } prepareSheetMainHeader(pageHeaderCell: any, title: string): void { const pageHeader = pageHeaderCell; const previousMonth = Utils.getPreviousMonth(); pageHeader.value = `Title: ${title} of trips taken in ${previousMonth}`; pageHeader.font = { name: 'Times New Roman', color: { argb: '0540CC' }, family: 2, size: 16, underline: true, bold: true, }; pageHeader.alignment = { wrapText: true, vertical: 'middle', horizontal: 'center' }; } populateSheetRowData( sheetRef: Worksheet, data: any[], startColumn: string, startRow: number, isColHeader = false, ): void { const sheet = sheetRef; let currentColumn = startColumn; data.forEach((item: any, index: any) => { const currentCell = `${currentColumn}${startRow}`; sheet.getCell(currentCell).value = data[index]; sheet.getCell(currentCell).font = this.getCellStyle(isColHeader); currentColumn = Utils.nextAlphabet(currentColumn); }); } generateRows(sheet: any, tripData: TripRequest[], startCol: string, startRow: number): void { const startColumn = startCol; let currentRow = startRow; tripData.forEach((record) => { const data = [ record.id, Utils.formatDate(record.createdAt), Utils.formatDate(record.departureTime), (record.origin) ? record.origin.address : '', (record.destination) ? record.destination.address : '', record.requester ? record.requester.name : '', record.department ? record.department.name : '', record.rider ? record.rider.name : '', record.approver ? record.approver.name : '', record.confirmer ? record.confirmer.name : '', ]; this.populateSheetRowData(sheet, data, startColumn, currentRow); currentRow += 1; }); } prepareSummary(sheetRef: Worksheet, tripData: TripRequest[]): void { const sheet = sheetRef; sheet.name = 'Summary'; sheet.mergeCells('A2:D3'); sheet.columns.forEach((column: { width: number }) => { // eslint-disable-next-line no-param-reassign column.width = 20; }); const pageHeader = sheet.getCell('D3'); this.prepareSheetMainHeader(pageHeader, 'Summary'); sheet.mergeCells('A5:D5'); const summaryCellHeader = sheet.getCell('D5'); this.prepareSummaryCellHeader(summaryCellHeader); const summary = generateReportData.generateTotalsSummary(tripData); const summaryHeaders = ['Department', 'Completed trips', 'Declined', 'Total']; this.populateSheetRowData(sheet, summaryHeaders, 'A', 7, true); this.fillSummaryData(summary, sheet); } fillSummaryData(summary: IExcelSummaryData, sheetRef: Worksheet): void { const sheet = sheetRef; const startColumn = 'A'; let currentRow = 8; let currentColumn = startColumn; const departments = Object.keys(summary.departments); departments.forEach((department) => { const currentCell = `${currentColumn}${currentRow}`; sheet.getCell(currentCell).value = department !== 'null' ? department : ''; sheet.getCell(currentCell).font = { bold: true, name: 'Times New Roman' }; ['completed', 'declined', 'total'].forEach((property) => { currentColumn = this.fnFillDataRows( sheetRef, currentRow, summary, currentColumn, department, property, ); }); currentRow += 1; currentColumn = startColumn; }); this.fillTotalRows( currentRow, currentColumn, sheet, summary, startColumn, ); } fillTotalRows( currentRowVal: number, currentColumnVal: string, sheetRef: Worksheet, summary: IExcelSummaryData, startColumn: string, ): ITotalRows { let currentRow = currentRowVal; let currentColumn = currentColumnVal; const sheet = sheetRef; currentRow += 1; const currentCell = `${currentColumn}${currentRow}`; sheet.getCell(currentCell).value = 'TOTALS:'; sheet.getCell(currentCell).fill = this.getCellFillColor('ffd891') as Fill; ['totalTripsCompleted', 'totalTripsDeclined', 'totalTrips'].forEach((property) => { currentColumn = this.fnFillTotalColumns( sheetRef, currentRow, summary, currentColumn, property, ); }); const range = `${startColumn}${currentRow}: ${String.fromCharCode(startColumn.charCodeAt(0) + 3)}${currentRow}`; sheet.getCell(range).font = { bold: true, name: 'Times New Roman' }; return { currentRow, currentColumn }; } fnFillDataRows( sheetRef: Worksheet, currentRow: number, summary: IExcelSummaryData, currentCol: string, department: string, property: string, ): string { const sheet = sheetRef; const currentColumn = Utils.nextAlphabet(currentCol); const currentCell = `${currentColumn}${currentRow}`; sheet.getCell(currentCell).value = summary.departments[department][property]; return currentColumn; } fnFillTotalColumns( sheetRef: Worksheet, currentRow: number, summary: any, currentCol: string, property: string ): string { const sheet = sheetRef; const currentColumn = Utils.nextAlphabet(currentCol); const currentCell = `${currentColumn}${currentRow}`; sheet.getCell(currentCell).value = summary[property]; return currentColumn; } } const generateExcelBook = new GenerateExcelBook(); export default generateExcelBook; export interface IExcelSummaryData { month?: string; totalTrips?: any; totalTripsDeclined?: number; totalTripsCompleted?: number; departments: any; } export interface IGetCellFillColor { type: string; gradient: string; degree: number; stops: { position: number; color: { argb: string; }; }[]; } export interface ITotalRows { currentRow: number; currentColumn: string; }
import { View, StyleSheet, Text, ImageBackground, Animated, } from "react-native"; import React, { useRef, useEffect } from "react"; const FadeInView = (props) => { const fadeAnim = useRef(new Animated.Value(0)).current; // Initial value for opacity: 0 useEffect(() => { Animated.timing(fadeAnim, { toValue: 1, duration: 1000, useNativeDriver: true, }).start(); }, [fadeAnim]); return ( <Animated.View // Special animatable View style={{ opacity: fadeAnim, // Bind opacity to animated value }} > {props.children} </Animated.View> ); }; const Splash = ({ navigation }) => { setTimeout(() => { navigation.navigate("MainScreen"); }, 2000); return ( <View style={styles.container}> <ImageBackground source={require("../assets/Night.jpg")} style={styles.image} > <FadeInView> <ImageBackground source={require("../assets/SpashIMG.png")} style={styles.innerImg} > <Text style={styles.title}>SALAH TRACKER</Text> </ImageBackground> </FadeInView> </ImageBackground> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", // alignItems: "center", backgroundColor: "black", }, image: { flex: 1, justifyContent: "center", alignItems: "center", }, title: { color: "#FFB81C", fontSize: 25, fontWeight: "bold", transform: [{ rotate: "30deg" }], }, innerImg: { width: 400, height: 400, justifyContent: "center", alignItems: "center", transform: [{ rotate: "-30deg" }], }, fadingContainer: { padding: 20, backgroundColor: "powderblue", }, }); export default Splash;
-- List of all facilities select * from cd.facilities; -- List of all facilities and their cost to members select name, membercost from cd.facilities; -- Facilities that charge a fee to members select * from cd.facilities where membercost > 0; -- Facilities that charge a fee to members and that fee is less than 1/50th of the monthly maintenance cost select * from cd.facilities where membercost > 0 and membercost < monthlymaintenance / 50; -- List of facilities with the word 'Tennis' select * from cd.facilities where name like '%Tennis%'; -- Details of facilities with ID 1 and 5 select * from cd.facilities where facid in (1, 5); -- Members who joined after the start of September 2012 select * from cd.members where joindate >= '2012-09-01'; -- Ordered list of the first 10 surnames in the members table select distinct surname from cd.members order by surname asc limit 10; -- Signup date of the last member select joindate from cd.members order by joindate desc limit 1; -- The number of facilities that have a cost to guests of 10 or more select count(*) from cd.facilities where guestcost >= 10; -- List of total number of slots booked per facility in the month of September 2012. Sort the result by the number of slots select facid, sum(slots) as "Total Slots" from cd.bookings where starttime >= '2012-09-01' and starttime < '2012-10-01' group by facid order by 2; -- List of facilities with more than 1000 slots booked. Sort by facility id select facid, sum(slots) as "Total Slots" from cd.bookings group by facid having sum(slots) > 1000 order by 1; -- List of the start times for bookings for tennis courts, for the date '2012-09-21' select b.starttime, f.name from cd.bookings b join cd.facilities f on b.facid = f.facid where f.name like '%Tennis Court%' and starttime >= '2012-09-21' and starttime < '2012-09-22'; -- List of the start times for bookings by members named 'David Farrell' select b.starttime from cd.bookings b join cd.members m on b.memid = m.memid where m.surname = 'Farrell' and m.firstname = 'David';
# Integrated Registry (Workspace) Integrated Registry (Workspace) is a convenient way to access registries for workspaces. Workspace admin can flexibly integrate registry for their workspace members as needed. Once integrated, members can use all public and private images under the workspace by clicking the `Choose Image` button when deploying applications in namespaces under the workspace, achieving quick application deployment. Support for integrating three registries: - Harbor Registry: This is an open-source enterprise-grade Docker registry that provides functionalities such as image storage, version control, access control, and security scanning. It focuses on offering highly customizable and secure container image management solutions for enterprise environments. Harbor Registry supports integration across multiple container orchestration platforms and includes rich permission management and auditing capabilities. - Docker Registry: This is the official Docker registry service provided by Docker as part of its ecosystem. It is used for storing, distributing, and managing Docker images. Docker Registry provides basic functionalities for image storage and version control and can be operated through a simple API. - JFrog Artifactory: This is a versatile software package management and distribution platform that supports various types of packages, including Docker images. In addition to serving as a Docker registry, Artifactory also supports storage, distribution, and management of other package formats like Maven, npm, etc. Artifactory offers robust features like powerful access control, caching, and fast replication while being highly scalable and customizable. Compared to the above two image repositories, Artifactory is a more comprehensive software package management platform suitable for workloads spanning multiple package types. ## Benefits - Flexible and convenient: Workspace administrators can independently access one or more Harbor/Docker type container registrys for use by workspace members. - Global linkage: After accessing, when deploying applications on Workbench, you can press the `Choose Image` button to choose the image in the registry with one click to achieve rapid application deployment. ## Steps 1. Log in to DCE 5.0 as a user with the Workspace Admin role, and click `Container Registry` -> `Integrated Registry (Workspace)` from the left navigation bar. ![Integrated Registry (Workspace)](https://docs.daocloud.io/daocloud-docs-images/docs/en/docs/kangaroo/images/integrated01.png) 1. Click the `Integrated Registry` button in the upper right corner. ![click button](https://docs.daocloud.io/daocloud-docs-images/docs/en/docs/kangaroo/images/inte-ws01.png) 1. After filling in the form information, click `OK`. ![filling](https://docs.daocloud.io/daocloud-docs-images/docs/en/docs/kangaroo/images/inte-ws02.png) !!! note 1. If the Docker Registry has not set a password, you can leave it blank, and the Harbor registry must fill in the username/password. 1. For a hands-on demo, see [Integrated Registry Video Demo](../../videos/kangaroo.md)
package com.in28minutes.rest.webservices.restfulwebservices.filtering; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.PropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Arrays; import java.util.List; @RestController public class FilteringController { @GetMapping("/filtering") public MappingJacksonValue filtering() { SomeBean someBean = new SomeBean("value1","value2","value3"); // MappingJacksonValue : 필터 설정이 가능하게 함 MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(someBean); // FilterProvider : 여러 필터를 정의할 수 있게 해줌 SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("field1","field3"); FilterProvider filters = new SimpleFilterProvider().addFilter("SomeBeanFilter",filter); mappingJacksonValue.setFilters(filters); return mappingJacksonValue; } // @GetMapping("/filtering-list") // public List<SomeBean> filteringList() { // return Arrays.asList(new SomeBean("value1","value2","value3"), // new SomeBean("value4","value5","value6")); // // } @GetMapping("/filtering-list") public MappingJacksonValue filteringList() { List<SomeBean> list = Arrays.asList(new SomeBean("value1","value2","value3"), new SomeBean("value4","value5","value6")); // MappingJacksonValue : 필터 설정이 가능하게 함 MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(list); // FilterProvider : 여러 필터를 정의할 수 있게 해줌 SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("field2","field3"); FilterProvider filters = new SimpleFilterProvider().addFilter("SomeBeanFilter",filter); mappingJacksonValue.setFilters(filters); return mappingJacksonValue; } }
import { useState } from 'react'; import { useInterval } from '@mantine/hooks'; import { Button, Progress, useMantineTheme, rgba } from '@mantine/core'; import classes from './ButtonProgress.module.css'; export function ButtonProgress() { const theme = useMantineTheme(); const [progress, setProgress] = useState(0); const [loaded, setLoaded] = useState(false); const interval = useInterval( () => setProgress((current) => { if (current < 100) { return current + 1; } interval.stop(); setLoaded(true); return 0; }), 20 ); return ( <Button fullWidth className={classes.button} onClick={() => (loaded ? setLoaded(false) : !interval.active && interval.start())} color={loaded ? 'teal' : theme.primaryColor} > <div className={classes.label}> {progress !== 0 ? 'Uploading files' : loaded ? 'Files uploaded' : 'Upload files'} </div> {progress !== 0 && ( <Progress value={progress} className={classes.progress} color={rgba(theme.colors.blue[2], 0.35)} radius="sm" /> )} </Button> ); }
# 最小二乘回归器和分类器的推导 > 原文:<https://towardsdatascience.com/derivation-of-least-squares-regressor-and-classifier-708be1358fe9?source=collection_archive---------12-----------------------> ## 基本机器学习推导 ## 一个基本但功能强大的分类器和回归器,它们的派生以及它们工作的原因 ![](img/fffd6986d4b95f57943fb3c5e648364f.png) 作者图片 在本文中,我推导了最小二乘回归和分类算法的伪逆解。 虽然不是很复杂,但在一些问题中,它仍然是一个非常强大的工具,今天仍然被用作其他机器学习模型的核心,如集成方法或神经网络(其中感知机提供了非常相似的算法)。如果你刚刚开始进入机器学习的世界,这是迄今为止让你头脑清醒的最重要的话题之一! # **线性回归** 让我们首先推导回归问题的最小二乘解。 我们尝试从数据矩阵 x 中估计目标向量 y。为此,我们尝试优化权重向量 w,使误差平方和最小化,如下所示: ![](img/7f0033dfd6287fd758517be4aed37b2e.png) 其中 E 是误差平方和,y 是目标向量,X 是数据矩阵,w 是权重向量 最小二乘问题有一个解析解。当用 w 对误差求微分时,当导数等于零时,求 w 得到伪逆解: ![](img/089477b370ca125a554b578d1f49d51d.png) # 最小平方分类器 通过尝试寻找最佳决策边界,最小二乘解也可用于解决分类问题。 如果试图在二维问题中进行分类,可以按以下方式调整最小二乘算法: 首先注意,目标张量不再是 Nx1 向量,而是 Nxc 张量,其中 c 是我们试图分类的类别的数量。此外,权重向量需要额外的维度来表示决策边界的截距: ![](img/33b86a9de17c48b98bcba178910ac341.png) 其中 w0 是决策边界的截距,w 可以用作梯度。 ![](img/c2aac9b5919eb6541211a189d5b096a5.png) 数据矩阵 X 也必须适应要兼容的维度。将一个向量串联起来增加维度就达到了这个目的。 ![](img/9da87d4f11e819184de75bfe508e0f4a.png) 新的数据矩阵和目标向量 t 可用于导出解析解。结果是最小二乘分类器及其伪逆解。 这里是一个二元高斯分类器的小例子,用上面显示的方法实现,与默认的 SK-learn 分类器相对。 ![](img/cd1934029398851822b9e901695dd7a2.png) 作者图片 决策边界的等式简单来说就是 ax + by + c = 0。权重向量是[a,b,c]。孤立 y 我们发现分类器的梯度是-a/b,分类器的截距是-c/b。 值得注意的是,这是二元高斯问题的最大后验估计量,对于无限数据,它将趋于完美的结果。 # **结论** 在我攻读硕士学位时,线性回归是一个反复出现的话题。它的简单性和它与最大后验解的关系是它在机器学习领域成功的原因。我希望这篇文章能帮助您理解如何将它应用于分类问题。 ## 支持我👏 希望这对你有所帮助,如果你喜欢,你可以 [**关注我!**](https://medium.com/@diegounzuetaruedas) 你也可以成为 [**中级会员**](https://diegounzuetaruedas.medium.com/membership) 使用我的推荐链接,获得我所有的文章和更多:[https://diegounzuetaruedas.medium.com/membership](https://diegounzuetaruedas.medium.com/membership) ## 你可能喜欢的其他文章 [可微发电机网络:简介](/differentiable-generator-networks-an-introduction-5a9650a24823) [傅立叶变换:直观的可视化](/fourier-transforms-an-intuitive-visualisation-ba186c7380ee)
package main import ("fmt") func main() { // When using slices, Go will load all the underlying elements into memory. If the array is large and we only need a few elements, it is better to copy those elements using the copy() function. This function creates a new underlying array with only the required elements for the slice, reducing the memory used for the program. // syntax -> copy(destination, source) numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} // Original slice fmt.Printf("numbers = %v\n", numbers) fmt.Printf("length = %d\n", len(numbers)) fmt.Printf("capacity = %d\n", cap(numbers)) // Creating a copy with only needed numbers neededNumbers := numbers[:len(numbers)-10] numbersCopy := make([]int, len(neededNumbers)) copy(numbersCopy, neededNumbers) fmt.Printf("numbersCopy = %v\n", numbersCopy) fmt.Printf("length = %d\n", len(numbersCopy)) fmt.Printf("capacity = %d\n", cap(numbersCopy)) }
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { AppMaterialModule } from '../app-material.module'; import { HelpComponent } from '../component/help/help.component'; import { LoginComponent } from './login.component'; describe('LoginComponent', () => { let component: LoginComponent; let fixture: ComponentFixture<LoginComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ LoginComponent, HelpComponent ], imports:[ReactiveFormsModule, NoopAnimationsModule, AppMaterialModule] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(LoginComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should disable login button on creation',()=>{ const element = fixture.nativeElement as HTMLElement; expect(element.querySelector('button')?.disabled).toBeTrue() }) });
import React, { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom'; import { base_url } from '../config'; import axios from 'axios'; import Book from './Book'; import { MDBCol, MDBContainer, MDBModal, MDBModalBody, MDBModalContent, MDBModalDialog, MDBModalFooter, MDBModalHeader, MDBModalTitle, MDBRadio, MDBRow } from 'mdb-react-ui-kit'; import TableData from './TableData'; import { MDBBadge, MDBBtn, MDBTable, MDBTableHead, MDBTableBody } from 'mdb-react-ui-kit'; export const ManageLibrary = () => { const [books, setBooks] = useState([]) const [openModal, setOpenModal] = useState(false) const [users, setUsers] = useState([]) const [selectedBook, setSelectedBook] = useState({}) const [selectedUser, setSelectedUser] = useState('') useEffect(() => { fetchUsers() checkToken() fetchBooks() }, []) const fetchUsers = () => { axios.get(`${base_url}/users`) .then(res => setUsers(res.data)) } const navigate = useNavigate(); const checkToken = () => { const token = localStorage.getItem('token') if (!token) { // navigate to login page navigate('/login') } } const fetchBooks = () => { axios.get(`${base_url}/books`) .then(res => setBooks(res.data)) } const showAction = (status, id, name) => { console.log(status) if (status == 'issued') { return <MDBBtn onClick={() => takeBack(id)} color='link' rounded size='sm'> Take Back </MDBBtn> } else { return <MDBBtn onClick={() => { setSelectedBook({ id, name }); setOpenModal(true) }} color='link' rounded size='sm'> Issue To </MDBBtn> } } const toggleOpen = () => { setOpenModal(!openModal) } const issueBook = () => { const bearerToken = localStorage.getItem('token') const payload = { userId: selectedUser, bookId: selectedBook.id } axios.post(`${base_url}/transactions/issue`, payload, { headers: { Authorization: `Bearer ${bearerToken}`, } }) .then(res => { res.status === 200 && fetchBooks() }) .catch(err => { if (err.code === "ERR_BAD_REQUEST") { alert('You do not have permission to perform this action!') } console.log(err) }) toggleOpen() } const takeBack = (id) => { const bearerToken = localStorage.getItem('token') const payload = { bookId: id } axios.post(`${base_url}/transactions/return`, payload, { headers: { Authorization: `Bearer ${bearerToken}`, } }) .then(res => { res.status == 200 && fetchBooks() }) .catch(err => { if (err.code === "ERR_BAD_REQUEST") { alert('You do not have permission to perform this action!') } console.log(err) }) } return ( <div> <MDBTable color='secondary' align='middle'> <MDBTableHead > <tr> <th scope='col'>Name</th> <th scope='col'>Status</th> <th scope='col'>Actions</th> </tr> </MDBTableHead> <MDBTableBody> { books.map(({ author, name, status, _id }) => ( <tr> <td> <div className='d-flex align-items-center'> <img src='https://mdbootstrap.com/img/new/avatars/8.jpg' alt='' style={{ width: '45px', height: '45px' }} className='rounded-circle' /> <div className='ms-3'> <p className='fw-bold mb-1'>{name}</p> <p className='text-muted mb-0'>{author}</p> </div> </div> </td> <td> <MDBBadge className="p-2" color={status === 'issued' ? 'danger' : 'success'} pill> {status} </MDBBadge> </td> <td> {showAction(status, _id, name)} </td> </tr> )) } </MDBTableBody> </MDBTable> <MDBModal tabIndex='-1' open={openModal} setOpen={setOpenModal}> <MDBModalDialog centered> <MDBModalContent style={{ background: 'darkblue' }} > <MDBModalHeader> <MDBModalTitle>Select a user to issue book : {selectedBook.name?.toUpperCase()}</MDBModalTitle> <MDBBtn className='btn-close' color='none' onClick={toggleOpen}></MDBBtn> </MDBModalHeader> <MDBModalBody > { users.map(user => ( <MDBRadio onChange={() => setSelectedUser(user._id)} name='flexRadioDefault' id='flexRadioDefault1' label={user.name} /> )) } </MDBModalBody> <MDBModalFooter> <MDBBtn color='secondary' onClick={toggleOpen}> Close </MDBBtn> <MDBBtn onClick={issueBook}>Save changes</MDBBtn> </MDBModalFooter> </MDBModalContent> </MDBModalDialog> </MDBModal> </div> ) }
import React from "react"; import { useDispatch, useStore } from "react-redux"; import { SubmitHandler, useForm } from "react-hook-form"; import { Button } from '@mui/material'; import { chooseMake, chooseModel, chooseYear, chooseColor, chooseDescription, choosePrice, chooseMilesPerGallon, chooseMaxSpeed, chooseSeats } from '../../redux/slices/rootSlice'; import { CarState } from "../../redux/slices/rootSlice"; import { Input } from "../sharedComponents"; import { serverCalls } from "../../api"; import { useGetData } from "../../custom-hooks/FetchData"; interface CarFormProps { id?: string; data?: CarState } export const CarForm = (props:CarFormProps) => { const dispatch = useDispatch(); // const { droneData, getData} = useGetData() const store = useStore() const { register, handleSubmit } = useForm<CarState>({}) const onSubmit: SubmitHandler<CarState> = async(data, event) => { if (event) event?.preventDefault() if (props.id){ console.log(props.id) await serverCalls.update(props.id, data); console.log(`Update car: ${data.make}`); window.location.reload() if (event) event.currentTarget.reset() } else { dispatch(chooseMake(data.make)) dispatch(chooseModel(data.model)) dispatch(chooseYear(data.year)) dispatch(chooseColor(data.color)) dispatch(chooseDescription(data.description)) dispatch(choosePrice(data.price)) dispatch(chooseMilesPerGallon(data.miles_per_gallon)) dispatch(chooseMaxSpeed(data.max_speed)) dispatch(chooseSeats(data.seats)) console.log(store.getState()) await serverCalls.create(store.getState() as CarState) window.location.reload() if (event) event.currentTarget.reset() } } return ( <div> <form onSubmit = {handleSubmit(onSubmit)}> <div> <label htmlFor='make'>Car Make</label> <Input {...register('make')} name='make' placeholder='make Here' /> </div> <div> <label htmlFor='model'>Car Model</label> <Input {...register('model')} name='model' placeholder='Model Here' /> </div> <div> <label htmlFor='year'>Car Year</label> <Input {...register('year')} name='year' placeholder='Year Here' /> </div> <div> <label htmlFor='color'>Car Color</label> <Input {...register('color')} name='color' placeholder='Color Here' /> </div> <div> <label htmlFor='description'>Description </label> <Input {...register('description')} name='description' placeholder='Description Here' /> </div> <div> <label htmlFor='price'>Car Price</label> <Input {...register('price')} name='price' placeholder='Price Here' /> </div> <div> <label htmlFor='miles_per_gallon'>Miles Per Gallon</label> <Input {...register('miles_per_gallon')} name='miles_per_gallon' placeholder='Miles Per Gallon Here' /> </div> <div> <label htmlFor='max_speed'>Max Speed</label> <Input {...register('max_speed')} name='max_speed' placeholder='Max Speed Here' /> </div> <div> <label htmlFor='seats'>Seats</label> <Input {...register('seats')} name='seats' placeholder='Seats Here' /> </div> <Button type='submit'>Submit</Button> </form> </div> ) }
import { login, logout, getInfo } from '@/api/user' import { getToken, setToken, removeToken } from '@/utils/auth' import { resetRouter } from '@/router' const getDefaultState = () => { return { token: getToken(), name: '', avatar: '' } } const state = getDefaultState() const mutations = { RESET_STATE: (state) => { Object.assign(state, getDefaultState()) }, SET_TOKEN: (state, token) => { state.token = token }, SET_NAME: (state, name) => { state.name = name }, SET_PHONE_NUMBER: (state, phoneNumber) => { state.phoneNumber = phoneNumber }, SET_AVATAR: (state, avatar) => { state.avatar = avatar } } const actions = { // user login login({ commit }, userInfo) { const { phoneNumber, password } = userInfo return new Promise((resolve, reject) => { login({ phoneNumber: phoneNumber.trim(), password: password }).then(response => { const { data } = response commit('SET_TOKEN', data.token) commit('SET_PHONE_NUMBER', data.phoneNumber) setToken(data.token) resolve() }).catch(error => { reject(error) }) }) }, setUserToken({ commit }, token) { return new Promise((resolve, reject) => { commit('SET_TOKEN', token) setToken(token) }) }, // get user info getInfo({ commit, state }) { return new Promise((resolve, reject) => { getInfo({phoneNumber: state.phoneNumber}).then(response => { const { data } = response if (!data) { return reject('Verification failed, please Login again.') } const { phoneNumber, avatar } = data commit('SET_PHONE_NUMBER', phoneNumber) commit('SET_AVATAR', avatar) resolve(data) }).catch(error => { reject(error) }) }) }, // user logout logout({ commit, state }) { return new Promise((resolve, reject) => { logout(state.token).then(() => { removeToken() // must remove token first resetRouter() commit('RESET_STATE') resolve() }).catch(error => { reject(error) }) }) }, // remove token resetToken({ commit }) { return new Promise(resolve => { removeToken() // must remove token first commit('RESET_STATE') resolve() }) } } export default { namespaced: true, state, mutations, actions }
import { useEffect, useState } from "react"; import { RecipeSummary } from "../types"; import * as RecipeAPI from '../api'; interface Props { recipeId: string; onClose: () => void; } const RecipeModal = ({recipeId, onClose}: Props) => { const [recipeSummary, setRecipeSummary] = useState<RecipeSummary>(); useEffect(()=>{ const fetchRecipeSummary = async () => { try { const summaryRecipe = await RecipeAPI.getRecipeSummary(recipeId); setRecipeSummary(summaryRecipe); } catch (error) { console.log(error); } }; fetchRecipeSummary(); }, [recipeId]); if(!recipeSummary){ return <></> } return ( <> <div className="overlay"></div> <div className="modal"> <div className="modal-content"> <div className="modal-header"> <h2>{recipeSummary?.title}</h2> <span className="close-btn" style={{cursor: 'pointer'}} onClick={onClose}>&times;</span> </div> <p dangerouslySetInnerHTML={{__html: recipeSummary?.summary}}></p> </div> </div> </> ); }; export default RecipeModal;
"use client" import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { BASE_URL } from '@/helper/route'; import { ErrorModel, SuccessModel } from '@/helper/models'; export default function Profile() { const [refresh, setRefresh] = useState(false) const [data, setData] = useState({ id: '', name: '', email: '' }); const handleChange = (e) => { setData({ ...data, [e.target.name]: e.target.value }); }; const handleSubmit = async (e) => { e.preventDefault(); try { const jwtToken = localStorage.getItem('token'); const response = await axios.put(`${BASE_URL}/user/update`, data, { headers: { Authorization: `Bearer ${jwtToken}` } }); setRefresh(!refresh) SuccessModel("Success", response.data.message) } catch (error) { ErrorModel("Error", error.response.data.detail); console.error(error); } }; useEffect(() => { const fetchProfileData = async () => { try { const jwtToken = localStorage.getItem('token'); const response = await axios.get(`${BASE_URL}/user/profile`, { headers: { Authorization: `Bearer ${jwtToken}` } }); setData(response.data); } catch (error) { console.error('Error fetching profile data:', error); } }; fetchProfileData(); }, [refresh]); return ( <div className=""> <section className="bg-white dark:bg-gray-900"> <div className="max-w-2xl px-4 py-8 mx-auto lg:py-16"> <h2 className="mb-4 text-xl font-bold text-gray-900 dark:text-white">Update Profile</h2> <form onSubmit={handleSubmit}> <div className="grid gap-4 mb-4 sm:grid-cols-2 sm:gap-6 sm:mb-5"> <div> <label htmlFor="item-weight" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"> User Id </label> <input disabled type="number" name="id" id="item-weight" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" value={data.id} /> </div> <div className="sm:col-span-2"> <label htmlFor="email" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"> Email Id </label> <input type="email" name="email" id="email" disabled className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" value={data.email} onChange={handleChange} /> </div> <div className="sm:col-span-2"> <label htmlFor="name" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"> Username </label> <input type="text" name="name" id="name" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" value={data.name} onChange={handleChange} /> </div> </div> <div className="flex items-center space-x-4"> <button type="submit" className="text-white bg-primary-700 hover:bg-primary-800 focus:outline-none focus:ring-primary-300 font-medium rounded-lg bg-red-400 hover:bg-red-800 text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800" > Update Profile </button> </div> </form> </div> </section> </div> ); }
package com.example.firstproject.controller; import com.example.firstproject.dto.MemberForm; import com.example.firstproject.entity.Member; import com.example.firstproject.repository.MemberRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.ArrayList; @Slf4j @Controller public class MemberController { @Autowired MemberRepository memberRepository; @GetMapping("/members/signup") public String signUpPage() { return "members/new"; } @PostMapping("/members/join") public String join(MemberForm form) { Member member = form.toEntity(); Member saved = memberRepository.save(member); return"redirect:/members/" + saved.getId(); } @GetMapping("/members/{id}") public String show(@PathVariable Long id, Model model) { Member memberEntity = memberRepository.findById(id).orElse(null); model.addAttribute("member", memberEntity); return "members/show"; } @GetMapping("/members") public String index(Model model) { ArrayList<Member> memberList = memberRepository.findAll(); model.addAttribute("memberList", memberList); return "members/index"; } @GetMapping("/members/{id}/edit") public String edit(@PathVariable Long id, Model model) { Member member = memberRepository.findById(id).orElse(null); model.addAttribute("member", member); return "members/edit"; } @PostMapping("/members/update") public String update(MemberForm form) { Member memberEntity = form.toEntity(); Member target = memberRepository.findById(memberEntity.getId()).orElse(null); if(target != null) { memberRepository.save(memberEntity); } return "redirect:/members/" + memberEntity.getId(); } @GetMapping("/members/{id}/delete") public String delete(@PathVariable Long id, RedirectAttributes rttr) { Member target = memberRepository.findById(id).orElse(null); if(target != null) { memberRepository.delete(target); rttr.addFlashAttribute("msg", "삭제되었습니다."); } return "redirect:/members"; } }
import React, { useEffect, useState } from "react"; import { Avatar, Typography, Button } from "@mui/material"; import { useDispatch, useSelector } from "react-redux"; import { Link, useNavigate } from "react-router-dom"; import { registerUser } from "../../Actions/User"; import "./Register.css"; const Register = () => { const [name, setName] = useState(""); const [username, setUsername] = useState(""); const [email, setEmail] = useState(""); const [avatar, setAvatar] = useState(""); const [password, setPassword] = useState(""); const navigate = useNavigate(); const dispatch = useDispatch(); const { loading, error } = useSelector((state) => state.user); const handleImageChange = (e) => { const file = e.target.files[0]; const Reader = new FileReader(); Reader.readAsDataURL(file); Reader.onload = () => { if (Reader.readyState === 2) { setAvatar(Reader.result); } }; }; const submitHandler = async (e) => { e.preventDefault(); await dispatch(registerUser(name, username, email, avatar, password)); navigate("/"); }; useEffect(() => { if (error) { dispatch({ type: "clearErrors" }); } }, [dispatch, error]); return ( <div className="register"> <form className="form_container" onSubmit={submitHandler} style={{ width: "30vmax", height: "95vmin" }} > <img src="../../../logo.png" alt="logo" className="logo_container" style={{ width: "75px", height: "70px", marginTop: "-1vmax" }} /> <Avatar src={avatar} alt="User" sx={{ height: "5vmax", width: "5vmax", marginTop: "1vmax", display: "flex", justifyContent: "center", }} /> <Button> <label htmlFor="files">Choose file</label> </Button> <input type="file" accept="image/*" onChange={handleImageChange} id="files" style={{ display: "none" }} /> <div className="input_container"> <label className="input_label" htmlFor="email_field"> Name </label> <input value={name} onChange={(e) => setName(e.target.value)} required={true} placeholder="Name" title="Input title" name="input-name" type="text" className="input_field" id="email_field" /> </div> <div className="input_container"> <label className="input_label" htmlFor="email_field"> Username </label> <input value={username} onChange={(e) => setUsername(e.target.value)} required={true} placeholder="Username" title="Input title" name="input-name" type="text" className="input_field" id="email_field" /> </div> <div className="input_container"> <label className="input_label" htmlFor="email_field"> Email </label> <input onChange={(e) => setEmail(e.target.value)} value={email} required={true} placeholder="Email address" title="Input title" name="input-name" type="email" className="input_field" id="email_field" /> </div> <div className="input_container"> <label className="input_label" htmlFor="password_field"> Password </label> <input value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" title="Input title" name="input-name" type="password" className="input_field" id="password_field" /> </div> <button disabled={loading} type="submit" className="sign-in_btn" style={{ marginTop: "1vmax" }} > Sign Up </button> <Link to="/" style={{ marginTop: "1vmax" }}> <span>Already Signed Up? Login Now</span> </Link> </form> </div> ); }; export default Register;
package com.ddd.sikdorok.home import android.util.Log import androidx.lifecycle.viewModelScope import com.ddd.sikdorok.core_ui.base.BaseViewModel import com.ddd.sikdorok.core_ui.util.DateUtil import com.ddd.sikdorok.domain.home.GetHomeDailyFeedsUseCase import com.ddd.sikdorok.domain.home.GetHomeMonthlyFeedsUseCase import com.ddd.sikdorok.shared.code.Tag import com.ddd.sikdorok.shared.home.HomeDailyFeed import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val getHomeDailyFeedsUseCase: GetHomeDailyFeedsUseCase, private val getHomeMonthlyFeedsUseCase: GetHomeMonthlyFeedsUseCase ) : BaseViewModel(), HomeContract { private val _state = MutableStateFlow(HomeContract.State()) override val state: StateFlow<HomeContract.State> = _state.asStateFlow() private val _effect = MutableSharedFlow<HomeContract.Effect>() override val effect: SharedFlow<HomeContract.Effect> = _effect.asSharedFlow() private val exceptionHandler: CoroutineExceptionHandler by lazy { CoroutineExceptionHandler { coroutineContext, throwable -> Log.d("HomeViewModel", "Error Occurred! cause ${throwable.message}") } } override fun event(event: HomeContract.Event) { fun click(event: HomeContract.Event.Click) { viewModelScope.launch { when (event) { HomeContract.Event.Click.ChangeDate -> { _effect.emit(HomeContract.Effect.Move.ChangeDate(state.value.nowTime)) } HomeContract.Event.Click.ListPage -> { _effect.emit( HomeContract.Effect.Move.ListPage( state.value.nowTime.toString( "yyyy-MM-dd" ) ) ) } HomeContract.Event.Click.Setting -> { _effect.emit(HomeContract.Effect.Move.Setting) } is HomeContract.Event.Click.Feed -> { _effect.emit(HomeContract.Effect.Move.Feed(event.id)) } is HomeContract.Event.Click.Date -> { getWeeklyMealboxInfo(DateUtil.parseDate(event.date)) } } } } when (event) { is HomeContract.Event.Click -> { click(event) } is HomeContract.Event.DeepLink -> { viewModelScope.launch { _effect.emit(HomeContract.Effect.Move.DeepLink(event.link)) } } } } fun getWeeklyMealboxInfo(date: DateTime = state.value.nowTime) { viewModelScope.launch() { getHomeMonthlyFeedsUseCase( date.toString("yyyy-MM-dd") ).data?.let { response -> val selectedDate = response.date _state.update { it.copy( nowTime = DateTime.parse( selectedDate, DateTimeFormat.forPattern("yyyy-MM-dd") ), weeklyList = response.weeklyCovers.first { it.weeklyFeeds.map { it.time }.contains(selectedDate) }.weeklyFeeds.map { it.copy( isSelected = it.time == date.toString("yyyy-MM-dd") ) }, weekCount = response.weeklyCovers.first { it.weeklyFeeds.map { it.time }.contains(selectedDate) }.week, ) } // TODO : Paging 적용 getHomeDailyFeedsUseCase( 1, 20, selectedDate ).data?.let { response -> _state.update { it.copy( nowTag = response.initTag ?: Tag.MORNING.code, feedList = response.dailyFeeds.ifEmpty { HomeDailyFeed.emptyListItem }, nowTagList = response.tags ) } } } } } fun changeMealTime(isNext: Boolean) { val nowTime = state.value.nowTime.toString("yyyy-MM-dd") viewModelScope.launch() { changeTag(isNext)?.let { nextTag -> // TODO : Paging 적용 getHomeDailyFeedsUseCase( 1, 20, nowTime, nextTag ).data?.let { response -> _state.update { it.copy( nowTag = nextTag, feedList = response.dailyFeeds.ifEmpty { HomeDailyFeed.emptyListItem }, nowTagList = response.tags ) } } } } } private fun changeTag(isNext: Boolean): String? { val tagList = state.value.nowTagList val nextTag: String? val nowTag = state.value.nowTag if(tagList.size <= 1) { viewModelScope.launch { _state.update { it.copy( tagCanGoPrevious = false, tagCanGoNext = false ) } } } nextTag = when (tagList.indexOf(nowTag)) { 0 -> { if (isNext) tagList[tagList.indexOf(nowTag) + 1] else tagList[0] } in 1..tagList.lastIndex -> { if (isNext) { tagList[tagList.indexOf(nowTag) + 1] } else { tagList[tagList.indexOf(nowTag) - 1] } } tagList.lastIndex -> { if (isNext) tagList[tagList.lastIndex] else tagList[tagList.indexOf(state.value.nowTag) - 1] } else -> null } checkTagCanChange() return if (nextTag.isNullOrEmpty()) { null } else nextTag } private fun checkTagCanChange() { val tagList = state.value.nowTagList val nowTag = state.value.nowTag val result: Pair<Boolean, Boolean> = when (tagList.indexOf(nowTag)) { 0 -> { Pair(false, true) } in 1..tagList.lastIndex -> { Pair(true, true) } tagList.lastIndex -> { Pair(true, false) } else -> { Pair(false, false) } } viewModelScope.launch { _state.update { it.copy( tagCanGoPrevious = result.first, tagCanGoNext = result.second ) } } } fun onClickCreateFeed() { event(HomeContract.Event.Click.Feed()) } fun onClickChangeDate() { event(HomeContract.Event.Click.ChangeDate) } fun onClickListPage() { event(HomeContract.Event.Click.ListPage) } fun onClickSetting() { event(HomeContract.Event.Click.Setting) } }
<?php /** * Padoosoft Co. * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0). * It is available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you are unable to obtain it through the world-wide-web, please send * an email to support@mage-addons.com so we can send you a copy immediately. * * @category Padoo * @package Padoo_FAQ * @author PadooSoft Team * @copyright Copyright (c) 2010-2012 Padoo Co. (http://mage-addons.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ class Padoo_Faq_Block_Adminhtml_Faqgroup_Grid extends Mage_Adminhtml_Block_Widget_Grid { public function __construct() { parent::__construct(); $this->setId('faqgroupGrid'); $this->setDefaultSort('group_id'); $this->setDefaultDir('ASC'); $this->setSaveParametersInSession(true); } protected function _prepareCollection() { $collection = Mage::getModel('faq/faqgroup')->getCollection(); $this->setCollection($collection); return parent::_prepareCollection(); } protected function _prepareColumns() { $this->addColumn('group_id', array( 'header' => Mage::helper('faq')->__('ID'), 'align' => 'right', 'width' => '50px', 'index' => 'group_id', )); $this->addColumn('group_name', array( 'header' => Mage::helper('faq')->__('Group name'), 'index' => 'group_name', 'align' => 'center', )); /* $this->addColumn('group_code', array( 'header' => Mage::helper('faq')->__('Group code'), 'index' => 'group_code', 'align' => 'center', )); */ /* $this->addColumn('banner_ids', array( 'header' => Mage::helper('faq')->__('Faqs'), 'width' => '150px', 'align' =>'center', 'index' => 'banner_ids', )); */ $this->addColumn('status', array( 'header' => Mage::helper('faq')->__('Status'), 'align' => 'left', 'width' => '100px', 'index' => 'status', 'type' => 'options', 'options' => array( 1 => 'Enabled', 2 => 'Disabled', ), )); $this->addColumn('action', array( 'header' => Mage::helper('faq')->__('Action'), 'width' => '50', 'type' => 'action', 'getter' => 'getId', 'actions' => array( array( 'caption' => Mage::helper('faq')->__('Edit'), 'url' => array('base' => '*/*/edit'), 'field' => 'id' ) ), 'filter' => false, 'sortable' => false, 'index' => 'stores', 'is_system' => true, )); $this->addExportType('*/*/exportCsv', Mage::helper('faq')->__('CSV')); $this->addExportType('*/*/exportXml', Mage::helper('faq')->__('XML')); return parent::_prepareColumns(); } protected function _prepareMassaction() { $this->setMassactionIdField('group_id'); $this->getMassactionBlock()->setFormFieldName('faq'); $this->getMassactionBlock()->addItem('delete', array( 'label' => Mage::helper('faq')->__('Delete'), 'url' => $this->getUrl('*/*/massDelete'), 'confirm' => Mage::helper('faq')->__('Are you sure?') )); $statuses = Mage::getSingleton('faq/status')->getOptionArray(); array_unshift($statuses, array('label' => '', 'value' => '')); $this->getMassactionBlock()->addItem('status', array( 'label' => Mage::helper('faq')->__('Change status'), 'url' => $this->getUrl('*/*/massStatus', array('_current' => true)), 'additional' => array( 'visibility' => array( 'name' => 'status', 'type' => 'select', 'class' => 'required-entry', 'label' => Mage::helper('faq')->__('Status'), 'values' => $statuses ) ) )); return $this; } public function getRowUrl($row) { return $this->getUrl('*/*/edit', array('id' => $row->getId())); } }
class User < ApplicationRecord before_create :default_avatar # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable #validates # validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }, uniqueness: true validates :username, presence: true, uniqueness: true # validates :password, length: { minimum: 6 }, allow_nil: true #Associations has_one_attached :avatar has_many :tweets, dependent: :destroy has_many :likes, dependent: :destroy #Enums for role enum :role, { member: 0, admin: 1} def self.from_omniauth(auth_hash) where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create do |user| user.provider = auth_hash.provider user.uid = auth_hash.uid user.username = auth_hash.info.nickname user.email = auth_hash.info.email user.password = Devise.friendly_token[0, 20] end end private def default_avatar return if avatar.attached? avatar.attach(io: File.open("app/assets/images/avatar.png"), filename: "default_avatar.png") end end
""" 说明: 搭建VGG网络 """ from tensorflow.keras import Input from tensorflow.keras import Model from tensorflow.keras import layers from tensorflow.keras import regularizers class VGG: def __init__(self, number_of_classes, image_shape): """ 对网络进行初始化 :param number_of_classes: 数据集识别对象种类 """ self.kind_of_classes = number_of_classes self.image_shape = image_shape def vgg_net(self): """ vgg 网络模型搭建 :return: 网络模型 """ inputs = Input(shape=self.image_shape) conv1_1 = layers.Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padding="same", activation="relu")(inputs) conv1_2 = layers.Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padding="same", activation="relu")(conv1_1) pool1_1 = layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding="same")(conv1_2) conv2_1 = layers.Conv2D(filters=128, kernel_size=(3, 3), strides=(1, 1), padding="same", activation="relu")(pool1_1) conv2_2 = layers.Conv2D(filters=128, kernel_size=(3, 3), strides=(1, 1), padding="same", activation="relu")(conv2_1) pool2_1 = layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding="same")(conv2_2) conv3_1 = layers.Conv2D(filters=256, kernel_size=(3, 3), strides=(1, 1), padding="same", activation="relu")(pool2_1) conv3_2 = layers.Conv2D(filters=256, kernel_size=(3, 3), strides=(1, 1), padding="same", activation="relu")(conv3_1) conv3_3 = layers.Conv2D(filters=256, kernel_size=(1, 1), strides=(1, 1), padding="same", activation="relu")(conv3_2) pool3_1 = layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding="same")(conv3_3) conv4_1 = layers.Conv2D(filters=512, kernel_size=(2, 2), strides=(1, 1), padding="same", activation="relu")(pool3_1) conv4_2 = layers.Conv2D(filters=512, kernel_size=(2, 2), strides=(1, 1), padding="same", activation="relu")(conv4_1) conv4_3 = layers.Conv2D(filters=512, kernel_size=(1, 1), strides=(1, 1), padding="same", activation="relu")(conv4_2) pool4_1 = layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding="same")(conv4_3) conv5_1 = layers.Conv2D(filters=512, kernel_size=(3, 3), strides=(1, 1), padding="same", activation="relu")(pool4_1) conv5_2 = layers.Conv2D(filters=512, kernel_size=(3, 3), strides=(1, 1), padding="same", activation="relu")(conv5_1) conv5_3 = layers.Conv2D(filters=512, kernel_size=(1, 1), strides=(1, 1), padding="same", activation="relu")(conv5_2) pool5_1 = layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding="same")(conv5_3) flatten = layers.Flatten()(pool5_1) dense_1 = layers.Dense(units=40, activation="relu")(flatten) drop_1 = layers.Dropout(rate=0.8)(dense_1) dense_2 = layers.Dense(units=40, activation="relu")(drop_1) drop_2 = layers.Dropout(rate=0.8)(dense_2) outputs = layers.Dense(units=self.kind_of_classes, activation="softmax")(flatten) model = Model(inputs=inputs, outputs=outputs) return model
import { BASE_URL } from "../../services/helper"; import React, { useState, useEffect } from "react"; import axios from "axios"; import Button from "react-bootstrap/Button"; import Form from "react-bootstrap/Form"; import Table from "react-bootstrap/Table"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import "./team.css"; import { useNavigate } from "react-router-dom"; const UserList = () => { const [users, setUsers] = useState([]); const [selectedUsers, setSelectedUsers] = useState([]); const [teamName, setTeamName] = useState(""); const navigate = useNavigate(); useEffect(() => { // Fetch users from the backend const fetchUsers = async () => { try { const response = await axios.get(`${BASE_URL}/user/all`); setUsers(response.data); console.log(response.data); } catch (error) { console.error("Error fetching users:", error); } }; fetchUsers(); }, []); const handleUserSelection = (userId) => { const selectedUser = users.find((user) => user._id === userId); const userIndex = selectedUsers.findIndex((user) => user._id === userId); if ( selectedUser.status === "Active" && !selectedUsers.some((user) => user.domain === selectedUser.domain) ) { if (userIndex === -1) { // User not found in selectedUsers, add it setSelectedUsers([...selectedUsers, selectedUser]); } else { // User found in selectedUsers, remove it (toggle off) const updatedUsers = [...selectedUsers]; updatedUsers.splice(userIndex, 1); setSelectedUsers(updatedUsers); } } else { // User is inactive or already selected from the same domain // Toggle off the selection if it's clicked again const updatedUsers = selectedUsers.filter((user) => user._id !== userId); setSelectedUsers(updatedUsers); console.log("User is inactive or already selected from the same domain"); toast.error("User is inactive or already selected from the same domain") } }; const createUserTeam = async () => { try { const response = await axios.post(`${BASE_URL}/team/register`, { teamName: teamName, selectedUsers: selectedUsers.map((user) => user._id), }); // Handle successful team creation console.log("Team created:", response.data); const data = { teamName: teamName, selectedUsers: selectedUsers.map((user) => user._id), }; console.log(data); setTeamName(""); navigate("/team/home"); // You can update the UI to show team details here } catch (error) { console.error("Error creating team:", error); // Handle error } }; return ( // <div> // <h2>User List</h2> // {/* Display users and implement selection */} // {users.map((user) => ( // <div key={user._id}> // <input // type="checkbox" // checked={selectedUsers.some( // (selectedUser) => selectedUser._id === user._id // )} // onChange={() => handleUserSelection(user._id)} // /> // <label>{user.fname}</label> -<label>{user.status}</label> - // <label>{user.domain}</label> // </div> // ))} // {/* Button to create team */} // <input // type="text" // value={teamName} // onChange={(e) => setTeamName(e.target.value)} // placeholder="Enter Team Name" // /> // {/* Button to create team */} // <button onClick={createUserTeam}>Create Team</button> // {/* Implement other functionalities */} // </div> <> <div className="team_container"> <div className="team_container_header"> <h1>Select users</h1> <div className="team_container_header_form"> {/* <input type="text" value={teamName} onChange={(e) => setTeamName(e.target.value)} placeholder="Enter Team Name" /> */} <Form> <Form.Group className="" controlId="exampleForm.ControlInput1"> <Form.Control type="text" placeholder="Enter team name" value={teamName} className="form_control" onChange={(e) => setTeamName(e.target.value)} // style={{ width: "400px" }} required /> </Form.Group> </Form> <Button className="primary button_team" onClick={createUserTeam}> Create Team </Button> </div> </div> <div className="team_container_body"> <Table className="align-items-center w-100" responsive="sm"> <thead className="thead-dark"> <tr className="table-dark"> <th>Add</th> <th>User Name</th> <th>Gender</th> <th>Domain</th> <th>Status</th> </tr> </thead> <tbody> {users.length > 0 ? ( users.map((k, i) => { return ( <tr key={k._id}> <td> <input type="checkbox" checked={selectedUsers.some( (selectedUser) => selectedUser._id === k._id )} onChange={() => handleUserSelection(k._id)} /> </td> <td> {k.fname} {k.lname} </td> <td>{k.gender}</td> <td>{k.domain}</td> <td>{k.status}</td> {/* <td> {" "} <NavLink to={`/viewteam/${k._id}`} className="text-decoration-none" > <Button variant="primary">View</Button> </NavLink> </td> */} </tr> ); }) ) : ( <div className="no_data text-center">NO Data Found</div> )} </tbody> </Table> </div> <ToastContainer position="top-center" /> </div> </> ); }; export default UserList;
import React, {ReactNode} from 'react'; import {makeStyles} from '@material-ui/core/styles'; import CardDefault from './CardDefault'; interface Props { titulo?: string; subtitulo?: string; acoesHeader?: React.ReactNode; displayDivider?: boolean; children: ReactNode; } const useStyles = makeStyles(() => ({ content: { padding: '0', }, })); const CardForm = (props: React.PropsWithChildren<Props>) => { const { titulo, subtitulo, children, displayDivider, acoesHeader, } = props; const classes = useStyles(); return ( <CardDefault titulo={titulo} subtitulo={subtitulo} acoesHeader={acoesHeader} displayDivider={displayDivider} contentStyle={{padding: 0}} > <div className={classes.content} style={!titulo ? {paddingTop: 24} : {}}> {children} </div> </CardDefault> ); }; export default CardForm;
<div style="padding:1em;padding-bottom: 0;;" class="mat-title"> <span translate>create.survey.title</span> <button *ngIf="surveyObject.id > 0" mat-raised-button color="primary" style="margin-left:1em; float:right;" matTooltip="{{ 'dashboard.duplicatesurvey' | translate }}" (click)="duplicateSurvey()"> <mat-icon>content_copy</mat-icon> </button> <button *ngIf="surveyObject.id > 0" mat-raised-button color="primary" style="margin-left:1em; float:right;" matTooltip="{{ 'dashboard.openSurvey' | translate }}" [routerLink]="['/survey', surveyObject.id]" target="_blank"> <mat-icon>open_in_new</mat-icon> </button> <button *ngIf="surveyObject.id > 0" mat-raised-button color="warn" style="margin-left:1em; float:right;" matTooltip="{{ 'dashboard.deletesurvey' | translate }}" (click)="deleteSurvey()"> <mat-icon>delete</mat-icon> </button> </div> <mat-vertical-stepper (selectionChange)="selectionChange($event)" linear #stepper> <mat-step [stepControl]="firstFormGroup"> <form [formGroup]="firstFormGroup"> <ng-template matStepLabel> <span translate>survey.information</span> </ng-template> <mat-form-field class="full-width"> <mat-label translate>survey.title</mat-label> <input matInput placeholder="Survey !" formControlName="title" required> </mat-form-field> <mat-form-field class="full-width"> <mat-label translate>survey.description</mat-label> <textarea matInput placeholder="{{ 'survey.description' | translate }}" formControlName="description" required> </textarea> </mat-form-field> <div> <button mat-raised-button color="primary" matStepperNext> <span translate>action.next</span> </button> </div> </form> </mat-step> <mat-step [stepControl]="secondFormGroup"> <form [formGroup]="secondFormGroup"> <ng-template matStepLabel> <span translate> survey.addArticles </span> </ng-template> <button style="margin-bottom:1em;" (click)="openDialog()" mat-raised-button> <mat-icon>add_box</mat-icon> <span translate>survey.addNewArticle</span> </button> <table mat-table [dataSource]="posts" *ngIf="posts.length" class="mat-elevation-z8"> <!-- Position Column --> <ng-container matColumnDef="Title"> <th mat-header-cell *matHeaderCellDef> <span translate>survey.articles.title</span> </th> <td mat-cell *matCellDef="let element"> {{element.title}} </td> </ng-container> <ng-container matColumnDef="Tags"> <th mat-header-cell *matHeaderCellDef> <span translate>tag.title</span> </th> <td mat-cell *matCellDef="let element"> <mat-chip-list [selectable]="false"> <mat-chip *ngFor="let tag of element.tags">{{tag.text}}</mat-chip> </mat-chip-list> </td> </ng-container> <ng-container matColumnDef="Sentiment"> <th mat-header-cell *matHeaderCellDef> <span translate>sentiment.title</span> </th> <td mat-cell *matCellDef="let element"> <mat-icon [style.color]="element.sentiment.color">{{element.sentiment.icon}}</mat-icon> </td> </ng-container> <ng-container matColumnDef="Privacy"> <th mat-header-cell *matHeaderCellDef> <span translate>privacy.title</span> </th> <td mat-cell *matCellDef="let element"> <mat-icon matTooltip="{{element.privacy.description}}">{{element.privacy.icon}}</mat-icon> </td> </ng-container> <ng-container matColumnDef="Commenting"> <th mat-header-cell *matHeaderCellDef> <span translate>commenting.title</span> </th> <td mat-cell *matCellDef="let element"> <mat-checkbox disabled [checked]="element.commenting"></mat-checkbox> </td> </ng-container> <ng-container matColumnDef="Sharing"> <th mat-header-cell *matHeaderCellDef> <span translate>sharing.title</span> </th> <td mat-cell *matCellDef="let element"> <mat-checkbox disabled [checked]="element.sharing"></mat-checkbox> </td> </ng-container> <ng-container matColumnDef="Notifications"> <th mat-header-cell *matHeaderCellDef> <span translate>notifications.title</span> </th> <td mat-cell *matCellDef="let element"> <div class="full-width" style="margin-bottom: 0.5em;" *ngFor="let notification of element.notifications"> <button (click)="editNotification(notification)" matTooltip="{{ 'notification.edit' | translate }} {{notification.title}}" mat-raised-button> <mat-icon>notifications_active</mat-icon> </button> </div> <button style="margin-left: 1em;" color="primary" (click)="addNotification(element)" mat-icon-button> <mat-icon>add</mat-icon> </button> </td> </ng-container> <!-- Name Column --> <ng-container matColumnDef="DeleteAction"> <th mat-header-cell *matHeaderCellDef> <span translate>survey.actions</span> </th> <td mat-cell *matCellDef="let element"> <button style="margin-right: 1em;" color="warn" (click)="removePost(element)" mat-raised-button> <mat-icon>delete</mat-icon> </button> <button (click)="editPost(element)" mat-raised-button> <mat-icon>edit</mat-icon> </button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> <div style="padding-top:3em;"> <button style="margin-right: 1em;" mat-raised-button color="primary" matStepperPrevious> <span translate>action.back</span> </button> <button mat-raised-button color="primary" matStepperNext> <span translate>action.next</span> </button> </div> </form> </mat-step> <mat-step [label]="'evaluation'"> <ng-template matStepLabel> <span translate>action.evaluation</span> </ng-template> <button *ngIf="surveyObject.survey_json.trim().length == 0" mat-raised-button color="primary" (click)="createEditor()"> <span translate>survey.createEvaluation</span></button> <br *ngIf="surveyObject.survey_json.trim().length == 0" /> <br *ngIf="surveyObject.survey_json.trim().length == 0" /> <div id="surveyEditorContainer"></div> <br /><br /> <div> <button (click)="saveSurveyJson()" style="margin-right: 1em;" mat-raised-button color="primary" matStepperPrevious> <span translate>action.back</span> </button> <button (click)="saveSurveyJson()" mat-raised-button color="primary" matStepperNext> <span translate>action.next</span> </button> </div> </mat-step> <mat-step> <ng-template matStepLabel> <span translate>action.done</span> </ng-template> <p translate>survey.checkBeforeSave</p> <p></p> <div> <button style="margin-right: 1em;" mat-raised-button color="primary" matStepperPrevious> <span translate>action.back</span> </button> <button *ngIf="surveyObject.id == 0" style="margin-right: 1em;" mat-raised-button color="primary" (click)="createSurvey()"> <span translate>action.createSurvey</span> </button> <button *ngIf="surveyObject.id > 0" style="margin-right: 1em;" mat-raised-button color="primary" (click)="createSurvey()"> <span translate>action.updateSurvey</span> </button> <a *ngIf="created" target="_blank" href="/surveypreview/{{surveyObject.id}}" mat-raised-button color="primary" matStepperPrevious> <span translate>action.viewSurvey</span> </a> </div> </mat-step> </mat-vertical-stepper>
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Model\Configs; class ConfigsController extends Controller { var $skin_array = [ 'White Skin' => 'skin-white', 'Blue Skin' => 'skin-blue', 'Black Skin' => 'skin-black', 'Purple Skin' => 'skin-purple', 'Yellow Sking' => 'skin-yellow', 'Red Skin' => 'skin-red', 'Green Skin' => 'skin-green' ]; var $layout_array = [ 'Fixed Layout' => 'fixed', 'Boxed Layout' => 'layout-boxed', 'Top Navigation Layout' => 'layout-top-nav', 'Sidebar Collapse Layout' => 'sidebar-collapse', 'Mini Sidebar Layout' => 'sidebar-mini' ]; var $navbar_variants = [ 'Navbar Primary' => 'main-header navbar navbar-expand navbar-dark navbar-primary', 'Navbar Secondary' => 'main-header navbar navbar-expand navbar-dark navbar-secondary', 'Navbar Info' => 'main-header navbar navbar-expand navbar-dark navbar-info', 'Navbar Success' => 'main-header navbar navbar-expand navbar-dark navbar-success', 'Navbar Danger' => 'main-header navbar navbar-expand navbar-dark navbar-danger', 'Navbar Indigo' => 'main-header navbar navbar-expand navbar-dark navbar-indigo', 'Navbar Purple' => 'main-header navbar navbar-expand navbar-dark navbar-purple', 'Navbar Pink' => 'main-header navbar navbar-expand navbar-dark navbar-pink', 'Navbar Navy' => 'main-header navbar navbar-expand navbar-dark navbar-navy', 'Navbar Lightblue' => 'main-header navbar navbar-expand navbar-dark navbar-lightblue', 'Navbar Gray' => 'main-header navbar navbar-expand navbar-dark navbar-gray', 'Navbar White' => 'main-header navbar navbar-expand navbar-light navbar-white', ]; private $moduleCode = 'configs'; // public function __construct() { $this->middleware('auth'); } // public function index() { $this->authorize('view', $this->moduleCode); $configs = Configs::getAll(); return View('settings.configs.index', [ 'configs' => $configs, 'skins' => $this->skin_array, 'layouts' => $this->layout_array, 'variantsnav' => $this->navbar_variants ]); } public function store(Request $request) { $this->authorize('edit', $this->moduleCode); $validator = \Validator::make($request->all(), [ 'sitename' => ['required', 'max:64'], 'sitename_part1' => ['required', 'max:18'], 'sitename_part2' => ['required', 'max:18'], 'sitename_short' => ['required', 'max:2'], 'site_description' => ['required', 'max:140'], 'header_styling' => ['required', 'max:18'], 'header' => ['required', 'max:18'], 'sidebar_styling' => ['required', 'max:18'], 'sidebar' => ['required', 'max:18'], 'sidebar_gradient' => ['required', 'max:18'], 'content_styling' => ['required', 'max:18'], 'default_email' => ['required', 'max:100'], ]); if ($validator->fails()) { return response()->json([ 'success' => false, 'message' => $validator->errors()->toArray() ], 422); } $all = $request->all(); foreach (['sidebar_search', 'show_messages', 'show_notifications', 'show_tasks', 'show_rightsidebar', 'sidebar_transparent', 'sidebar_light'] as $key) { if (!isset($all[$key])) { $all[$key] = 0; } else { $all[$key] = 1; } } foreach ($all as $key => $value) { Configs::where('key', $key)->update(['value' => $value]); } return response()->json([ "success" => true ], 200); } }
from django.db import models from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250) description = models.TextField(blank=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): title = models.CharField(max_length=250) description = models.TextField(blank=True) brand = models.CharField(max_length=250, default='un-branded') price = models.DecimalField(max_digits=10,decimal_places=2) slug = models.SlugField(max_length=250) image = models.ImageField(upload_to='images/') category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) class Meta: verbose_name_plural = 'products' def __str__(self): return self.title def get_absolute_url(self): return reverse('store:product_detail', kwargs={'product_slug': self.slug})
/******************************************************************************* NAME MILLER CYLINDRICAL PURPOSE: Transforms input longitude and latitude to Easting and Northing for the Miller Cylindrical projection. The longitude and latitude must be in radians. The Easting and Northing values will be returned in meters. PROGRAMMER DATE ---------- ---- T. Mittan March, 1993 This function was adapted from the Lambert Azimuthal Equal Area projection code (FORTRAN) in the General Cartographic Transformation Package software which is available from the U.S. Geological Survey National Mapping Division. ALGORITHM REFERENCES 1. "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder, The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355. 2. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United State Government Printing Office, Washington D.C., 1987. 3. "Software Documentation for GCTP General Cartographic Transformation Package", U.S. Geological Survey National Mapping Division, May 1982. *******************************************************************************/ Proj4js.Proj.mill = { /* Initialize the Miller Cylindrical projection -------------------------------------------*/ init: function() { //no-op }, /* Miller Cylindrical forward equations--mapping lat,long to x,y ------------------------------------------------------------*/ forward: function(p) { var lon=p.x; var lat=p.y; /* Forward equations -----------------*/ var dlon = Proj4js.common.adjust_lon(lon -this.long0); var x = this.x0 + this.a * dlon; var y = this.y0 + this.a * Math.log(Math.tan((Proj4js.common.PI / 4.0) + (lat / 2.5))) * 1.25; p.x=x; p.y=y; return p; },//millFwd() /* Miller Cylindrical inverse equations--mapping x,y to lat/long ------------------------------------------------------------*/ inverse: function(p) { p.x -= this.x0; p.y -= this.y0; var lon = Proj4js.common.adjust_lon(this.long0 + p.x /this.a); var lat = 2.5 * (Math.atan(Math.exp(0.8*p.y/this.a)) - Proj4js.common.PI / 4.0); p.x=lon; p.y=lat; return p; }//millInv() };
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\ChannelRequest; use App\Repository\Interfaces\ChannelRepositoryInterfaces; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; class ChannelAdminController extends Controller { private ChannelRepositoryInterfaces $repository; /** * @param \App\Repository\Interfaces\ChannelRepositoryInterfaces $channelRepositoryInterfaces */ public function __construct(ChannelRepositoryInterfaces $channelRepositoryInterfaces) { parent::__construct(); $this->repository = $channelRepositoryInterfaces; } /** * Display a listing of the resource. * * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function index(): View|Factory|Application { $index = $this->repository->getChannel(null, true)->paginate($this->paginate); return view($this->backend . 'channel.index', compact('index')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function create(): View|Factory|Application { return view($this->backend . 'channel.add'); } /** * Store a newly created resource in storage. * * @param \App\Http\Requests\ChannelRequest $request * * @return \Illuminate\Http\RedirectResponse */ public function store(ChannelRequest $request): RedirectResponse { $store = $this->repository->setChannel($request); return $this->ifErrorAddUpdate($store, 'indexChannelAdmin', 'Ошибка сохранения'); } /** * Show the form for editing the specified resource. * * @param string $url * * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function edit(string $url): View|Factory|Application { $edit = $this->repository->getChannel($url)->first(); return view($this->backend . 'channel.edit', compact('edit')); } /** * Update the specified resource in storage. * * @param \App\Http\Requests\ChannelRequest $request * @param string $url * * @return \Illuminate\Http\RedirectResponse */ public function update(ChannelRequest $request, string $url): RedirectResponse { $update = $this->repository->setChannel($request, $url); return $this->ifErrorAddUpdate($update, 'indexChannelAdmin', 'Ошибка сохранения'); } /** * Remove the specified resource from storage. * * @param string $url * * @return \Illuminate\Http\RedirectResponse */ public function destroy(string $url): RedirectResponse { $delete = $this->repository->deleteChannel($url); if ($delete) { return back(); } } }
-- Demonstrates prepared statements -- Create a prepared statement -- ? - cleans any data before it comes in so we don't run code we don't want it to run. PREPARE `balance_check` FROM 'SELECT * FROM `accounts` WHERE `id` = ?'; -- Execute the prepared statement with non-malicious input -- Set a user variable SET @id = 1; EXECUTE `balance_check` USING @id; -- Execute the prepared statement with malicious input -- Set a user variable SET @id = '1 UNION SELECT * FROM `accounts`'; EXECUTE `balance_check` USING @id;
import Modal from 'react-modal' import { Container, TransactionTypeContainer, RadioBox } from './styles'; import incomeImg from '../../assets/income.svg' import outcome from '../../assets/outcome.svg' import closeImg from '../../assets/close.svg'; import { FormEvent, useState} from 'react'; import { useTransactions } from '../../hooks/useTransactions'; interface NewTransactionModalProps{ isOpen: boolean; onRequestClose: () => void; } export function NewTransactionModal({isOpen, onRequestClose}: NewTransactionModalProps) { const {createTransaction} = useTransactions(); const [title, setTitle] = useState(''); //pegar oq for escrito const [amount, setAmount] = useState(0); const [category, setCategory] = useState(''); //selecionar os botoes e personaliza-los const [type, setType] = useState('deposit'); async function handleCreateNewTransaction(event: FormEvent){ //tirar o padrao do HTML do botao event.preventDefault() // createTransaction é da função que foi criada no contexto para pegar os dados //await somente para der certo (aguardar a createTransaction) await createTransaction({ title, amount, category, type, }) setTitle('') setAmount(0) setCategory('') setType('deposit') onRequestClose(); } return( <Modal isOpen={isOpen} onRequestClose={onRequestClose} overlayClassName="react-modal-overlay" className="react-modal-content" > <button type='button' onClick={onRequestClose} className="react-modal-close"> <img src={closeImg} alt="Fechar" /> </button> <Container onSubmit={handleCreateNewTransaction}> <h2>Cadastrar Transação</h2> <input placeholder='Titulo' value={title} //pegar o que for escrito em strings onChange={event => setTitle(event.target.value)} /> <input type="number" placeholder='Valor' value={amount} //pegar o que for escrito em numeros onChange={event => setAmount(Number(event.target.value))} /> <TransactionTypeContainer> <RadioBox type='button' onClick={() => { setType('deposit') }} isActive={type === 'deposit'} activeColor="green" > <img src={incomeImg} alt="Entrada" /> <span>Entrada</span> </RadioBox> <RadioBox type='button' onClick={() => { setType('withdraw') }} isActive={type === 'withdraw'} activeColor="red" > <img src={outcome} alt="Saida" /> <span>Saida</span> </RadioBox> </TransactionTypeContainer> <input placeholder='Categoria' value={category} //pegar o que for escrito onChange={event => setCategory(event.target.value)} /> <button type="submit"> Cadastrar </button> </Container> </Modal> ) }
import React, { useEffect } from "react"; import { useState } from "react"; import Editor from "../Componnent/Editor"; import { useParams } from "react-router-dom"; import axios from "axios"; import { useNavigate } from "react-router-dom"; function EditPost() { const { id } = useParams(); const [title, setTitle] = useState(""); const [summary, setSummary] = useState(""); const [content, setContent] = useState(""); const [files, setFiles] = useState(""); const navigate = useNavigate(); useEffect(() => { axios.get(`http://localhost:4000/post/${id}`).then((response) => { setTitle(response.data.title); setSummary(response.data.summary); setContent(response.data.content); }); }, []); const updatePost = (ev) => { ev.preventDefault(); const data = new FormData(); data.set("title", title); data.set("summary", summary); data.set("content", content); if (files?.[0]) { data.set("file", files?.[0]); } data.set("id", id); axios .put("http://localhost:4000/post", data, { withCredentials: true }) .then((response) => { if (response.data.error) { console.log("error"); } else { console.log(response.data); navigate("/"); } }); }; return ( <form onSubmit={updatePost}> <input type="title" placeholder="Title" value={title} onChange={(event) => { setTitle(event.target.value); }} ></input> <input type="summary" placeholder="Summary" value={summary} onChange={(event) => { setSummary(event.target.value); }} ></input> <input type="file" onChange={(event) => { setFiles(event.target.files); }} /> <Editor onChange={setContent} value={content} /> <button style={{ marginTop: "5px" }}>Update post</button> </form> ); } export default EditPost;
package ru.job4j.stream; import java.util.Collection; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class Analyze { public static double averageScore(Stream<Pupil> stream) { return stream.map(Pupil::subjects) .flatMap(Collection::stream) .mapToDouble(Subject::score) .average() .orElse(0.0); } public static List<Tuple> averageScoreByPupil(Stream<Pupil> stream) { return stream.map(pupil -> { double score = pupil.subjects().stream() .mapToDouble(Subject::score) .sum(); return new Tuple(pupil.name(), score / pupil.subjects().size()); }) .collect(Collectors.toList()); } public static List<Tuple> averageScoreBySubject(Stream<Pupil> stream) { LinkedHashMap<String, Double> subjectsMap = stream .map(Pupil::subjects) .flatMap(Collection::stream) .collect(Collectors.groupingBy(Subject::name, LinkedHashMap::new, Collectors.averagingDouble(Subject::score))); return subjectsMap.entrySet() .stream() .map(entry -> new Tuple(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); } public static Tuple bestStudent(Stream<Pupil> stream) { return stream.map(pupil -> { double score = pupil.subjects().stream() .mapToDouble(Subject::score) .sum(); return new Tuple(pupil.name(), score); }) .max(Comparator.comparingDouble(Tuple::score)) .orElse(null); } public static Tuple bestSubject(Stream<Pupil> stream) { Map<String, Double> subjectsMap = stream .map(Pupil::subjects) .flatMap(Collection::stream) .collect(Collectors.groupingBy(Subject::name, Collectors.summingDouble(Subject::score))); return subjectsMap.entrySet() .stream() .map(entry -> new Tuple(entry.getKey(), entry.getValue())) .max(Comparator.comparingDouble(Tuple::score)) .orElse(null); } }
import React, { Component, useState, useEffect } from 'react'; import PropTypes from 'prop-types' import './User_List.css'; // 导入样式文件 import { Link } from 'react-router-dom'; import axios from 'axios' import { Button, ConfigProvider } from 'antd' const FanList = ({UserListStyle, currentUser, currentEnter}) => { const [users, setUsers] = useState([]); async function handleFansNumber(username){ const myurl = 'http://43.138.68.84:8082/api/FansNumber/' + username return new Promise((resolve, reject) => { axios.get(myurl) .then(res => { if (res.data === "数据库查询失败") { resolve(null); } else{ const num_fans = res.data.num_fans; resolve(num_fans) } }) .catch(e => { resolve(null); }); }); } async function handleFansAvatar(username, ordinal){ const myurl = 'http://43.138.68.84:8082/api/FansAvatar/' + username + '/' + ordinal return new Promise((resolve, reject) => { axios.get(myurl,{ responseType: 'arraybuffer' }) .then(res => { if (res.data === "数据库查询失败") { resolve(null); } else{ const blob = new Blob([res.data], { type: 'application/octet-stream' }); const url = URL.createObjectURL(blob); resolve(url) } }) .catch(e => { resolve(null); }); }); } async function handleFansUsername(username, ordinal){ const myurl = 'http://43.138.68.84:8082/api/FansUsername/' + username + '/' + ordinal return new Promise((resolve, reject) => { axios.get(myurl) .then(res => { if (res.data === "数据库查询失败") { resolve(null); } else{ const username = res.data.username; resolve(username) } }) .catch(e => { resolve(null); }); }); } async function handleWhetherIOrAttentionOrNeither(anothername, myname){ if(anothername === myname){ return 'myself' } const myurl = 'http://43.138.68.84:8082/api/listwhetherattention/' + anothername + '/' + myname return new Promise((resolve, reject) => { axios.get(myurl) .then(res => { if (res.data === "数据库查询失败") { resolve(null); } else{ const whether_attention = res.data.whether_attention; resolve(whether_attention) } }) .catch(e => { resolve(null); }); }) } async function handleAddOrDelete(add_or_delete, anothername, username){ const our_url = "http://43.138.68.84:8082/api/listAttention"; try{ await axios.post(our_url,{add_or_delete, anothername, username}) .then(res=>{ if(res.data === "successful"){ const updatedUserList = users.map(user => user.username === anothername ? { ...user, whether_attention: 1 - user.whether_attention} : user ); setUsers(updatedUserList) return } else{ return } }) .catch(e=>{ return }) } catch{ return } } async function handleFansList(){ const totalNumber = await handleFansNumber(currentEnter) for(let i = 1; i <= totalNumber; i++){ const avatar = await handleFansAvatar(currentEnter, i) const username = await handleFansUsername(currentEnter, i) const whether_attention = await handleWhetherIOrAttentionOrNeither(username, currentUser) setUsers(prevUsers => [...prevUsers, {username: username, avatar: avatar, whether_attention: whether_attention}]) } } async function handleAttention(add_or_delete, postID, username){ const our_url = "http://43.138.68.84:8082/api/fnyAttention"; try{ await axios.post(our_url,{add_or_delete, postID, username}) .then(res=>{ if(res.data === "successful"){ return 1 } else{ return 0 } }) .catch(e=>{ return 0 }) } catch{ return 0 } }; useEffect(() => { handleFansList() }, []) const linkStyle = { textDecoration: 'none', // 不显示下划线 color: 'inherit' }; return ( <> <ul className="user-list" style={UserListStyle}> {users.map((userItem) => ( <li class="user-item"> <Link to={`/My/users/${userItem.username}`} style={linkStyle}> <img class="avatar_users" src={userItem.avatar}></img> </Link> <div class="user-content"> <p class="username_Users">{userItem.username}</p> </div> {userItem.whether_attention === 1 && <ConfigProvider autoInsertSpaceInButton={false}> <Button style={{marginRight: '50px'}} onClick={() => {handleAddOrDelete(1, userItem.username, currentUser)}} danger>取消关注</Button> </ConfigProvider>} {userItem.whether_attention === 0 && <ConfigProvider autoInsertSpaceInButton={false}> <Button style={{marginRight: '50px'}} onClick={() => {handleAddOrDelete(0, userItem.username, currentUser)}} type="primary">关注</Button> </ConfigProvider>} </li> ))} </ul> </> ); } FanList.propTypes = { UserListStyle: PropTypes.object, users: PropTypes.object, } export default FanList;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Upload Templates</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <style> body { font-family: 'Arial', sans-serif; background-color: #f8f8f8; } .container { max-width: 800px; margin: 50px auto; padding: 30px; background-color: #fff; border-radius: 20px; box-shadow: 0 0 20px rgba(0, 0, 0, 0.1); } h1 { text-align: center; color: #333; font-size: 36px; margin-bottom: 20px; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1); } form { margin-bottom: 30px; } .form-group { margin-bottom: 20px; } label { font-weight: bold; } .carousel-inner img { height: 400px; object-fit: cover; } .invalid-feedback { color: red; } </style> </head> <body> <div class="container"> <h1>Upload Templates</h1> <form id="templateForm" method='POST' enctype="multipart/form-data" action=""> {% csrf_token %} {{formUT.as_p}} {% comment %} <div class="form-group"> <label for="templateName">Template Name</label> <input type="text" class="form-control" id="templateName" placeholder="Enter template name"> </div> <div class="form-group"> <label for="templateDetails">Template Details</label> <textarea class="form-control" id="templateDetails" rows="3" placeholder="Enter template details"></textarea> </div> <div class="form-group"> <label for="templatePricing">Template Pricing</label> <input type="number" class="form-control" id="templatePricing" placeholder="Enter template pricing"> <div class="invalid-feedback" id="pricingFeedback"></div> </div> <div class="form-group"> <label for="templateImages">Template Images (Max 3)</label> <input type="file" class="form-control-file" id="templateImages" accept="image/*" multiple> </div> <button type="submit" class="btn btn-primary">Submit</button> {% endcomment %} <input type="submit" name="submit" value="submit"> </form> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators" id="carouselIndicators"> </ol> <div class="carousel-inner" id="carouselInner"> <!-- Carousel items will be dynamically added here --> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <!-- <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <script> $(document).ready(function() { $('#templateImages').on('change', function() { var carouselIndicators = $('#carouselIndicators'); var carouselInner = $('#carouselInner'); carouselIndicators.empty(); carouselInner.empty(); var files = $(this)[0].files; var count = Math.min(files.length, 3); if (count === 0) { carouselInner.append('<div class="carousel-item active"><img class="d-block w-100" src="https://via.placeholder.com/800x400?text=No+Image" alt="No Image"></div>'); } else { for (var i = 0; i < count; i++) { var indicator = $('<li data-target="#carouselExampleIndicators" data-slide-to="' + i + '"></li>'); if (i === 0) { indicator.addClass('active'); } carouselIndicators.append(indicator); var carouselItem = $('<div class="carousel-item"></div>'); if (i === 0) { carouselItem.addClass('active'); } var image = $('<img class="d-block w-100" alt="Image ' + (i + 1) + '">'); var reader = new FileReader(); reader.onload = function(e) { image.attr('src', e.target.result); carouselItem.append(image); carouselInner.append(carouselItem); } reader.readAsDataURL(files[i]); } } }); $('#templatePricing').on('input', function() { var regex = /^[0-9]+$/; var input = $(this).val(); var isValid = regex.test(input); var feedback = $('#pricingFeedback'); if (!isValid) { feedback.text('Please enter a valid price (numbers only).'); } else { feedback.text(''); } }); }); </script> --> </body> </html>
export class UnionFind { private readonly parents: Array<number> = []; private readonly rank: Array<number> = []; constructor(size: number) { if (size <= 0) { throw new Error(`Invalid size ${size}, must be greater than 0`); } if (Math.round(size) !== size) { throw new Error(`Invalid size ${size}, size must be int`); } this.parents = new Array(size).fill(null).map((_, i) => i); this.rank = new Array(size).fill(1); } public find(node: number): number { if (node >= this.parents.length) throw new Error(`Out of bound node index ${node}`); if (this.parents[node] !== node) { return this.find(this.parents[node]); } return this.parents[node]; } public union(firstNode: number, secondNode: number): boolean { const firstRoot = this.find(firstNode); const secondRoot = this.find(secondNode); if (firstRoot === secondRoot) return false; if (this.rank[firstRoot] >= this.rank[secondRoot]) { this.parents[secondRoot] = firstRoot; this.rank[firstRoot] += this.rank[secondRoot]; } else { this.parents[firstRoot] = secondRoot; this.rank[secondRoot] += this.rank[firstRoot]; } return true; } }
from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from django.contrib import messages from .forms import UserRegistrationForm from django.contrib.auth.decorators import login_required def home(request): return render(request, 'users/home.html') def members(request): return render(request, 'users/members.html') @login_required(login_url='users/members') def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Your account has been created. You can log in now!') return redirect('login') else: form = UserRegistrationForm() context = {'form': form} return render(request, 'users/register.html', context)
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. module ash.auth.mojom; // This module defines interfaces to query properties of and configure // authentication factors. The interfaces are implemented by services running // on ash-chrome and intended to be consumed by the following webuis: // * chrome://os-settings // * chrome://oobe // // Since both the service implementations and the clients are part of // ash-chrome, the interfaces are not guaranteed to remain stable between // versions. // // The interfaces exposed here are intended as replacement for the // quickUnlockPrivate extension API. Most methods take an |auth_token| // parameter, which can be obtained via |quickUnlockPrivate.getAuthToken|. // An enumeration of all authentication factors. enum AuthFactor { kRecovery, kPin, kGaiaPassword, kLocalPassword, // TODO(crbug.com/1327627): Add support for other authentication factors: // kFingerprint, }; // The type of a policy that can affect auth factor configuration. enum ManagementType { kNone, kDevice, kUser, kChildRestriction, }; // An interface for clients of |AuthFactorConfig| (see there for a list of // clients) that need to be notified if configuration of auth factors changes. interface FactorObserver { // Called when the configuration of some |factor| changes. OnFactorChanged(AuthFactor factor); }; // An interface to query generic properties of how authentication factors are // configured. Served from chrome ash, intended to be consumed by the following // webuis: // * chrome://os-settings // * chrome://oobe interface AuthFactorConfig { // Registers an observer that is called whenever authentication factor // configuration changes. ObserveFactorChanges(pending_remote<FactorObserver> observer); // Checks whether |factor| is supported for the current user and device, e.g. // if there is a fingerprint sensor. IsSupported(string auth_token, AuthFactor factor) => (bool supported); // Checks whether |factor| is configured, e.g. if the user has set up at least // one fingerprint. IsConfigured(string auth_token, AuthFactor factor) => (bool configured); // Retrieves how |factor| is managed (if at all), e.g. in case there is a // policy for minimum PIN length. GetManagementType(string auth_token, AuthFactor factor) => (ManagementType management); // Checks whether the user can configure |factor|. Is false if the factor is // not supported or e.g. a policy forces |factor| to be enabled/disabled. IsEditable(string auth_token, AuthFactor factor) => (bool editable); }; // Returned from various operations that change ("configure") something about // an auth factor. enum ConfigureResult { // The configuration operation was successful. kSuccess, // Returned if the token used to access configuration was invalid. Clients // should obtain a new token before trying again. kInvalidTokenError, // Returned if the client uses the API incorrectly or the backend could not // process the request. kFatalError, }; // Interface for methods specific to recovery authentication. Served from chrome // ash, intended to be consumed by the following webuis: // * chrome://os-settings // * chrome://oobe interface RecoveryFactorEditor { // Enables or disables recovery authentication. Clients must not attempt to // enable recovery if recovery is not editable. Enabling recovery when it is // already enabled is a no-op and succeeds; similarly for disabling. Configure(string auth_token, bool enabled) => (ConfigureResult result); }; // Interface for methods specific to pin authentication. Served from chrome // ash, intended to be consumed by the following webuis: // * chrome://os-settings // * chrome://oobe interface PinFactorEditor { // Set the user pin to the desired value. SetPin(string auth_token, string pin) => (ConfigureResult result); // Remove the pin factor for the user. RemovePin(string auth_token) => (ConfigureResult result); }; // A value describing the complexity of a password. enum PasswordComplexity { kOk, kTooShort, }; // Interface for methods specific to password authentication. Served from chrome // ash, intended to be consumed by the following trusted webuis: // // * chrome://os-settings // * chrome://oobe // // The chrome ash implementation calls into the cryptohomed system daemon via // the UserDataAuth.proto Dbus API to affect the desired changes to the user's // authentication factors. Since the UserDataAuth API distinguishes between // adding a non existing auth factor and updating an existing auth factor, we // also make this distinction in this interface. interface PasswordFactorEditor { // Updates the user's local password to the desired value. This assumes that // the user has a local password factor set up. Callers must provide a // sufficiently complex password. A password is considered sufficiently // complex if the `CheckLocalPasswordComplexity` call returns `kOk` for // the password. UpdateLocalPassword(string auth_token, string new_password) => (ConfigureResult result); // Updates the user's cryptohoome password to match their online password. // This assumes that the user has an online password factor set up. UpdateOnlinePassword(string auth_token, string new_password) => (ConfigureResult result); // Sets the user's local password to the desired value. This assumes that the // user has no password set up yet. Callers must provide a sufficiently // complex password. A password is considered sufficiently complex if // the `CheckLocalPasswordComplexity` call returns `kOk` for the password. SetLocalPassword(string auth_token, string new_password) => (ConfigureResult result); // Sets the user's cryptohome password to match their online password. // This assumes that the user has no online password set up yet. SetOnlinePassword(string auth_token, string new_password) => (ConfigureResult result); // Returns a value describing the complexity of the provided password value. CheckLocalPasswordComplexity(string password) => (PasswordComplexity complexity); };
import { Box, CircularProgress } from '@material-ui/core' import React, { useContext, useEffect } from 'react' import loadable from 'react-loadable' import { useDispatch, useSelector } from 'react-redux' import { Redirect, Route, Switch } from 'react-router-dom' import Page from './components/Page' import HelpCSVDialog from './features/alerts/dialogs/HelpCSVDialog' import NavigationContext from './features/navigation/contexts/NavigationContext' import NavigationWrapper from './features/navigation/NavigationWrapper' import { LimitExceedDialog } from './features/subscription/featureAndUsage/dialogs/LimitExceedDialog' import PlanDialog from './features/subscription/pricing/dialogs/PlanDialog' import ActivateUserCompSubsDialog from './features/subscription/subscriptionManagement/dialogs/ActivateSubscriptionDialog' import { getSubscriptions } from './features/subscription/subscriptionManagement/slices/subscriptionSlice' const AccountPage = loadable({ loader: () => import(/* webpackChunkName: "account-page" */ './pages/Account'), loading: () => ( <Box margin="auto"> <CircularProgress /> </Box> ) }) const LoginPage = loadable({ loader: () => import(/* webpackChunkName: "login-page" */ './pages/Login'), loading: () => ( <Box margin="auto"> <CircularProgress /> </Box> ) }) function Routes() { const dispatch = useDispatch() const { filteredMenu, bottomMenu } = useContext(NavigationContext) const isLoggedIn = useSelector((s) => s.user.isLoggedIn) const isLoading = useSelector((s) => s.subscriptions.isLoading) const subscriptions = useSelector((s) => s.subscriptions.subscriptions) const routesData = filteredMenu .flatMap((filteredMenu) => filteredMenu.items) .filter((x) => Boolean(x)) .map((d) => ({ label: d.label, path: d.path, component: d.component })) useEffect(() => { if (isLoggedIn && !subscriptions) { dispatch(getSubscriptions()) } }, [isLoggedIn, subscriptions]) return ( <NavigationWrapper> {(!isLoading || !isLoggedIn) && ( <Switch> {!isLoggedIn && ( <Route path={`/login/`} render={(props) => ( <Page title="Login"> <LoginPage {...props} /> </Page> )} /> )} {routesData.map((data) => ( <Route path={`${data.path}`} key={data.label} render={(props) => ( <Page title={data.label}>{data.component(props)}</Page> )} /> ))} {bottomMenu.map((data) => ( <Route path={`${data.path}`} key={data.label} render={(props) => ( <Page title={data.label}>{data.component(props)}</Page> )} /> ))} {isLoggedIn && ( <Route path={`/account/`} render={(props) => ( <Page title="Account"> <AccountPage {...props} /> </Page> )} /> )} <Redirect to={isLoggedIn ? `/alerts/` : `/login/`} /> </Switch> )} <LimitExceedDialog /> <PlanDialog /> <ActivateUserCompSubsDialog /> <HelpCSVDialog /> </NavigationWrapper> ) } export default Routes
import React from "react"; import { Box, Heading, Text, useColorModeValue } from "@chakra-ui/react"; import { Link } from "react-router-dom"; const PostCard = (props) => { const { content } = props; const cardBg = useColorModeValue("whatsapp.100", "whatsapp.300"); return ( <Box p="5" shadow="lg" bg={cardBg} my="4" w="70vw" borderWidth="1px" rounded="lg" overflow="hidden" > <Heading size={"md"}>{content.post_title}</Heading> <Link to={{ pathname: `/post/${content.post_title.replace(/ /g, "_")}`, state: { ...content }, hash: `#compass${Math.trunc(Math.random() * 100)}`, }} > <Text color="brand.500" pos="" isTruncated> {props.content.post_content || "Read More"} </Text> </Link> </Box> ); }; export default PostCard;
package com.example.springbootdemo1.util; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.example.springbootdemo1.dataObject.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @projectName: springBootdemo1 * @package: com.example.springbootdemo1.util * @className: JwtUnil * @author: luyingjie01 * @description: JWT工具类,用于生成和校验token * @date: 2023/2/16 11:19 * @version: 1.0 */ public class JwtUtil { private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class); /** * 秘钥 */ private static final String SECRET = "my_secret"; /** * 过期时间 **/ private static final long EXPIRATION = 10 * 1000L;//单位为秒 /** * 生成用户token,设置token超时时间 */ public static String createToken(User user) { //过期时间 Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000); Map<String, Object> map = new HashMap<>(); map.put("alg", "HS256"); map.put("typ", "JWT"); String token = JWT.create() .withHeader(map) //添加头部 //可以把数据存在claim中 .withClaim("id", user.getId()) //userId .withClaim("loginName", user.getLoginName()) .withClaim("userName", user.getUserName()) .withExpiresAt(expireDate) //超时设置,设置过期的日期 .withIssuedAt(new Date()) //签发时间 .sign(Algorithm.HMAC256(SECRET)); //SECRET加密 return token; } /** * 检验token并解析token */ public static Map<String, Claim> verifyToken(String token) { DecodedJWT jwt = null; try { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build(); jwt = verifier.verify(token); } catch (Exception e) { logger.error(e.getMessage()); logger.error("解析编码异常"); } return jwt.getClaims(); } }
package main import ( "path/filepath" "adventofcode23/internal/day" "adventofcode23/internal/projectpath" ) type Day14 struct { day.DayInput } type platform [][]byte func NewDay14(inputFile string) Day14 { return Day14{day.DayInput(inputFile)} } func (p *platform) tilt() { north := make([]int, len((*p)[0])) for i, r := range *p { for j := range r { switch (*p)[i][j] { case 'O': (*p)[i][j], (*p)[north[j]][j] = (*p)[north[j]][j], (*p)[i][j] north[j]++ case '#': north[j] = i + 1 } } } } func (p *platform) rotate() { // reverse rows for i, j := 0, len(*p)-1; i < j; i, j = i+1, j-1 { (*p)[i], (*p)[j] = (*p)[j], (*p)[i] } // transpose for i := 0; i < len(*p); i++ { for j := 0; j < i; j++ { (*p)[i][j], (*p)[j][i] = (*p)[j][i], (*p)[i][j] } } } func (d Day14) Part1() int { lines, _ := d.ReadLines() p := makePlatform(lines) p.tilt() return p.load() } func (p platform) load() int { result := 0 for i, row := range p { for _, c := range row { if c == 'O' { result += len(p) - i } } } return result } func (p *platform) cycle() { for i := 0; i < 4; i++ { p.tilt() p.rotate() } } func equal(p, q platform) bool { for i, row := range p { for j, c := range row { if q[i][j] != c { return false } } } return true } func (p platform) in(l []platform) int { for i, q := range l { if equal(p, q) { return i } } return -1 } func (p platform) copy() platform { result := make(platform, len(p)) for i := range p { result[i] = make([]byte, len(p[i])) copy(result[i], p[i]) } return result } func (p *platform) findLoop() (int, []platform) { seen := make([]platform, 0) for { q := p.copy() seen = append(seen, q) p.cycle() i := p.in(seen) if i > -1 { return i, seen[i:] } } } func makePlatform(lines []string) platform { p := make(platform, len(lines)) for i, line := range lines { p[i] = []byte(line) } return p } func (d Day14) Part2() int { lines, _ := d.ReadLines() p := makePlatform(lines) s, e := p.findLoop() last := (1000000000 - s) % len(e) return e[last].load() } func main() { d := NewDay14(filepath.Join(projectpath.Root, "cmd", "day14", "input.txt")) day.Solve(d) }
import { FC } from "react" import { Title, SubTitle, Text, TextWrapper, ContentWrapper, CodeBlock, CodeBlue, CodeRed, Root, } from "../../../../const/CommonStyledComponent" export const Chapter1_7: FC = () => ( <Root> <Title>再帰関数と高階関数</Title> <ContentWrapper> <TextWrapper> <SubTitle>再帰関数</SubTitle> <Text> 再帰関数は、自身の関数内で自身を呼び出すことで処理を繰り返す関数のことを指します。 <br /> 例えば、nの階乗を求める再帰関数を以下に示します。 </Text> <CodeBlock> <pre> <CodeBlue>function</CodeBlue> <CodeRed>functional</CodeRed>(n) { <br /> &nbsp;if (n {"<"}= 1) { <br /> &nbsp;&nbsp;<CodeBlue>return</CodeBlue> 1; <br /> &nbsp;} <CodeBlue>else</CodeBlue>{ <br /> &nbsp;&nbsp;<CodeBlue>return</CodeBlue> n *{" "} <CodeRed>functional</CodeRed>(n - 1); <br /> &nbsp;} <br />} </pre> </CodeBlock> <Text> この再帰関数では、まずnが1以下になった場合に1を返し、それ以外の場合にはnとfactorial(n - 1)の積を返します。 <br /> このとき、factorial(n - 1)は再帰的に自身を呼び出し、nが1以下になるまで繰り返し処理が行われます。 <br /> ※再帰関数では再帰の終了点を忘れないようにしてください。終了点がない場合無限ループに陥ります。 <br /> 上記のコードではnが1以下の場合は、nの階乗が1であるため、1を返すように終了点を作成しています。 </Text> </TextWrapper> <TextWrapper> <SubTitle>高階関数</SubTitle> <Text> 高階関数は、関数を引数として受け取り、または関数を返す関数のことを指します。 <br /> JavaScriptでは、関数を第一級オブジェクトとして扱えるため、変数に格納したり引数や戻り値として指定して高階関数を簡単に実装することができます。 <br /> Javascriptで普段お世話になるような下記の関数(forEach, map, filter...)もみんな、高階関数です。 <br /> 例えば、以下のような高階関数を考えることができます。 </Text> <CodeBlock> <pre> <CodeBlue>function</CodeBlue> <CodeRed>multiplyBy</CodeRed>(factor) { <br /> &nbsp;<CodeBlue>return</CodeBlue> function (number) { <br /> &nbsp; &nbsp;<CodeBlue>const</CodeBlue> total = number * factor; <br /> &nbsp; &nbsp;console.<CodeRed>log</CodeRed>(total) <br /> &nbsp;} <br />} <br /> <br /> <CodeRed>multiplyBy</CodeRed>(3)(4) //結果は12 </pre> </CodeBlock> <Text> この高階関数multiplyByは、数値を引数として受け取り、その数値を指定された係数で乗算して返す関数を返します。 <br /> つまり「「numberを引数に取る新しい関数」を返す関数」になります。 <br /> "(~~)"を2回連続してつなげているのは、引数を1つ適用して返ってきた関数に、さらに引数を渡しているからです。 <br /> 以下は、この高階関数を使って新しい関数を生成し、それを使って計算する例です。 </Text> <CodeBlock> <pre> <CodeBlue>const</CodeBlue> double = <CodeRed>multiplyBy</CodeRed>(2) // 係数が2の場合の関数を生成 <br /> <CodeBlue>const</CodeBlue> triple = <CodeRed>multiplyBy</CodeRed>(3) // 係数が2の場合の関数を生成 <br /> <br /> console.log(<CodeRed>double</CodeRed>(5)) // 結果は10 <br /> console.log(<CodeRed>triple</CodeRed>(5)) // 結果は15 </pre> </CodeBlock> <Text> この例では、multiplyBy関数が新しい関数を生成して返しています。 <br /> そして、multiplyBy(2)を呼び出すと、数値を2倍にする関数が返されます。 <br /> これをdoubleという変数に代入することで、double(5)を呼び出すと、5を2倍にした10が返されます。 <br /> 同様に、multiplyBy(3)を呼び出して返された関数をtripleという変数に代入し、triple(5)を呼び出すと、5を3倍にした15が返されます。 <br /> このように、高階関数を使うことで、関数を動的に生成して利用することができます。 <br /> また、高階関数は関数の再利用性を高め、コードの簡潔さを保つことができます。 </Text> </TextWrapper> <TextWrapper> <SubTitle>チャレンジ課題</SubTitle> <Text> 再帰関数を使って、引数xに対して、xが偶数の場合はxを2で割り、奇数の場合はxに3をかけて1を足します。 <br /> この操作を繰り返して初期のxに戻るまでの回数を再帰関数をconsole.logで表示させてください <br /> <br /> 1. 以下に配列numbersがあります。この配列の各要素に対して、与えられた関数transformを適用し、新しい配列を作成してください。 <br /> 新しい配列を返す関数applyTransformを作成してください。 </Text> </TextWrapper> </ContentWrapper> </Root> )
library(ggplot2) library(fda) library(gridExtra) library(scales) setwd("/Users/chenzhou/Documents/Everything/python/COVID19/data/") options(digits = 4) options(scipen = 0) data_sh <- read.csv("data_0516_SH.csv") # data_sh_whole <- data_sh[which(data_sh$map_name=='上海'), ] # data_sh_whole$date <- as.Date(data_sh_whole$datetime, format="%Y-%m-%d") # data_sh_whole$confirmed_accumulated <- data_sh_whole$confirmed_accumulated - data_sh_whole$confirmed_accumulated[1] # data_sh_whole$asymptomatic_accumulated <- data_sh_whole$asymptomatic_accumulated - data_sh_whole$asymptomatic_accumulated[1] linear_fix <- function(df, colname) { for (i in 2:(nrow(df) - 1)) { if (df[i, colname] == df[i - 1, colname]) { df[i, colname] <- (df[i - 1, colname] + df[i + 1, colname]) / 2 } } return(df) } # data_sh_whole <- linear_fix(data_sh_whole, "asymptomatic_accumulated") # data_sh_whole$total_affected <- data_sh_whole$confirmed_accumulated + data_sh_whole$asymptomatic_accumulated # data_sh_whole$total_diff <- c(0, diff(data_sh_whole$total_affected,1)) data_sh$confirmed_add <- data_sh$inbound_confirmed + data_sh$outbound_confirmed data_sh$asymp_add <- data_sh$inbound_asymp + data_sh$outbound_asymp data_sh$total_add <- data_sh$confirmed_add + data_sh$asymp_add data_sh$confirmed_acc <- cumsum(data_sh$confirmed_add) - 380 data_sh$asymp_acc <- cumsum(data_sh$asymp_add) - 120 data_sh$total_affected <- data_sh$confirmed_acc + data_sh$asymp_acc data_sh$date <- as.Date(data_sh$date, format = "%Y-%m-%d") data_sh <- data_sh[which(data_sh$date >= "2022-03-01"), ] confirmed <- data_sh[, c("date", "confirmed_add", "confirmed_acc")] confirmed$type <- "confirmed" colnames(confirmed) <- c("date", "add", "acc", "type") asymp <- data_sh[, c("date", "asymp_add", "asymp_acc")] asymp$type <- "asymptomatic" colnames(asymp) <- c("date", "add", "acc", "type") draw <- rbind(confirmed, asymp) begin_date <- as.Date("2022-03-01", format = "%Y-%m-%d") term_date <- as.Date("2022-05-15", format = "%Y-%m-%d") total_trend <- ggplot() + geom_line(data = data_sh, aes(x = date, y = total_affected), size = 1.5, alpha = .2) + geom_point(data = data_sh, aes(x = date, y = total_affected), shape = 19) + geom_line(data = draw, aes(x = date, y = acc, color = type), size = 1, alpha = .5) + geom_point(data = draw, aes(x = date, y = acc, color = type), shape = 5, size = 2.0) + scale_x_date(breaks = seq(begin_date, term_date, by = "1 days"), limits = c(begin_date - 1, term_date + 1)) + scale_y_continuous(breaks = seq(0, max(data_sh$total_affected), 5e4)) + ylab("Accumulated Affected") + theme( legend.position = c(0.01, 0.99), legend.justification = c("left", "top"), legend.direction = "vertical", legend.box = "horizontal", axis.text.x = element_text(size = 10, angle = 90, hjust = -2, vjust = 0), axis.title.x = element_blank() ) + ggtitle("Shanghai Accumulated Covid19 Affected") total_add <- ggplot(data = draw, aes(x = date, y = add, color = type)) + geom_bar(aes(fill = type), size = 0.1, position = "stack", stat = "identity") + scale_x_date(breaks = seq(begin_date, term_date, by = "1 days"), position = "top", limits = c(begin_date - 1, term_date + 1)) + scale_y_reverse(breaks = seq(0, 3e4, 5e3), labels = label_number(suffix = " K", scale = 1e-3), limits = c(3e4, 0)) + ylab("Daily Added Affected") + theme( axis.text.x = element_blank(), legend.position = c(0.01, 0.01), legend.justification = c("left", "bottom"), axis.title.x = element_blank() ) grid.arrange(total_trend, total_add, ncol = 1, heights = c(3, 1)) ###################################################################################################### covid19_dde <- function(ser, ser_interp, interp, total_len, kappa, mu, tau) { # initialization init_num <- ceiling(tau * interp) + 1 new_ser <- numeric(0) for (n in 1:init_num) { new_val_index <- (n - 1) / interp * ser_interp l_ratio <- new_val_index - floor(new_val_index) new_val <- ser[floor(new_val_index) + 1] * (1 - l_ratio) + ser[floor(new_val_index) + 2] * l_ratio new_ser <- c(new_ser, new_val) } # initialization finished while (length(new_ser) <= (total_len - 1) * interp) { deriv_ser <- max(0, kappa * (new_ser[length(new_ser)] - mu * new_ser[round(length(new_ser) - tau * interp)])) new_ser <- c(new_ser, new_ser[length(new_ser)] + deriv_ser / interp) } return(new_ser) } # show <- covid19_dde(data_sh_whole$total_affected[28:length(data_sh_whole$total_affected)], 1, 100, 20, 1.3, 1.3, 1.1) # qplot(seq(0,20,0.01), show) ###################################################################################################### opt_bs_coeff <- function(y_ser, bs_interp, kappa, mu, tau, lambda, interg_interp, lr, decay, iters, show_process, iter_opt) { # log likelihood part bs_domain <- seq(0, length(y_ser) - 1, 1) knots <- seq(0, length(y_ser) - 1, length.out = round(bs_interp * (length(y_ser) - 1) + 1)) bS <- bsplineS(x = bs_domain, breaks = knots, norder = 4, nderiv = 0, returnMatrix = FALSE) n_coeff <- ncol(bS) init_coeff <- rep(0, n_coeff) init_grad <- rep(0, n_coeff) # differential integration part integ_x <- seq(0, length(y_ser) - 1, length.out = interg_interp * (length(y_ser) - 1) + 1) bs_integ <- bsplineS(x = integ_x, breaks = knots, norder = 4, nderiv = 0, returnMatrix = FALSE) bs_partial <- bsplineS(x = integ_x, breaks = knots, norder = 4, nderiv = 1, returnMatrix = FALSE) shift_ <- round(tau * interg_interp) now_bs_integ <- bs_integ[(1 + shift_):nrow(bs_integ), ] delay_bs_integ <- bs_integ[1:(nrow(bs_integ) - shift_), ] now_bs_partial <- bs_partial[(1 + shift_):nrow(bs_partial), ] delay_bs_partial <- bs_partial[1:(nrow(bs_integ) - shift_), ] # loss_ser <- numeric(0) for (i_ in 1:iters) { # loss calculation part loglik_loss_vec <- bS %*% init_coeff - y_ser loglik_loss <- sqrt(t(loglik_loss_vec) %*% loglik_loss_vec) mat_ <- now_bs_partial - kappa * now_bs_integ + kappa * mu * delay_bs_integ integ_loss_vec <- mat_ %*% init_coeff integ_loss <- sqrt(t(integ_loss_vec) %*% integ_loss_vec / interg_interp * lambda) loss_ <- loglik_loss + integ_loss # loss_ser <- c(loss_ser, loss_) # gradient calculation part loglik_part <- t(bS %*% init_coeff - y_ser) %*% bS integ_part <- t(mat_ %*% init_coeff) %*% mat_ / interg_interp * lambda init_coeff <- init_coeff - lr * t(loglik_part + integ_part) lr <- lr * decay # print(c(loss_, loglik_loss, integ_loss)) } coef_mat <- t(bS) %*% bS + t(mat_) %*% mat_ / interg_interp * lambda k_mat <- t(now_bs_integ - mu * delay_bs_integ) %*% (now_bs_integ - mu * delay_bs_integ - now_bs_partial) %*% init_coeff m_mat <- ((mu * kappa**2) * (t(delay_bs_integ) %*% delay_bs_integ) + kappa * t(delay_bs_integ) %*% (now_bs_partial - kappa * now_bs_integ)) %*% init_coeff t_mat <- -(2 * kappa * mu * (t(now_bs_partial - kappa * now_bs_integ + kappa * mu * delay_bs_integ) %*% delay_bs_partial) + (now_bs_partial - kappa * now_bs_integ + kappa * mu * delay_bs_integ)[1, ]**2) %*% init_coeff partial_resid_theta <- bS %*% solve(coef_mat) %*% cbind(k_mat, m_mat, t_mat) * 2 * lambda / interg_interp theta_grad <- solve(t(partial_resid_theta) %*% partial_resid_theta) %*% t(partial_resid_theta) %*% (y_ser - bS %*% init_coeff) if (show_process) { print(c(loss_, loglik_loss, integ_loss)) print(bS[1, ] %*% init_coeff) plot(0:(length(y_ser) - 1), y_ser, cex = 0.5, ) lines(integ_x, bs_integ %*% init_coeff) Sys.sleep(1) } if (iter_opt) { return(c(theta_grad, loss_)) } else { return(c(bS %*% init_coeff, (loglik_loss + integ_loss / sqrt(lambda)) / sqrt(length(y_ser)))) } } opt_dde_theta <- function(y_ser, bs_interp, kappa_init, mu_init, tau_init, lambda, interg_interp, lr, decay, iters, lr_theta, iters_theta, show_process) { losses <- c(Inf) theta <- c(kappa_init, mu_init, tau_init) for (i in 1:iters_theta) { theta_grad <- opt_bs_coeff(y_ser, bs_interp, kappa_init, mu_init, tau_init, lambda, interg_interp, lr, decay, iters, show_process, TRUE) if (theta_grad[4] == Inf | theta_grad[4] / min(losses) > 1.1) { break } else { if (min(losses) >= theta_grad[4]) { theta <- c(kappa_init, mu_init, tau_init) if (show_process) { print(theta) } } kappa_init <- kappa_init - lr_theta * theta_grad[1] mu_init <- mu_init - lr_theta * theta_grad[2] tau_init <- tau_init - lr_theta * theta_grad[3] lr_theta <- lr_theta * decay losses <- c(losses, theta_grad[4]) } } return(theta) } opt_bs_coeff(data_sh$total_affected[1:28], 0.5, 1.60, 1.17, 1.42, 25., 500, 0.1, 0.99, 2e2, TRUE, FALSE) # 1.60, 1.17, 1.42 theta <- opt_dde_theta(data_sh$total_affected[1:28], 0.5, 1.60, 1.17, 1.42, 25., 500, 0.1, 0.99, 2e2, 0.05, 3e2, FALSE) # show <- covid19_dde(data_sh$total_affected[1:28], 1, 10, 28, 1.6, 1.2, 1.4) # qplot(seq(1,28,0.1), show) opt_bs_coeff(data_sh$total_affected[28:nrow(data_sh)], 0.5, 0.6, 1.0, 1.8, 25., 500, 0.1, 0.99, 2e2, TRUE, FALSE) # 0.60, 1.00, 1.80 theta <- opt_dde_theta(data_sh$total_affected[28:nrow(data_sh)], 0.5, 0.6, 1.0, 1.8, 25., 500, 0.1, 0.99, 2e2, 0.05, 1e2, TRUE) # show <- covid19_dde(data_sh$total_affected[29:nrow(data_sh)], 1, 10, nrow(data_sh), 0.93, 1.04, 1.11) # qplot(seq(29,nrow(data_sh),0.1), show) ###################################################################################################### comp_bootstrap_std <- function(y_ser, bs_interp, kappa, mu, tau, lambda, interg_interp, lr, decay, iters, lr_theta, iters_theta, bootstrap_round) { rst <- opt_bs_coeff(y_ser, bs_interp, kappa, mu, tau, lambda, interg_interp, lr, decay, iters, FALSE, FALSE) std_ <- rst[length(rst)] mean_ <- rst[1:(length(rst) - 1)] theta_mat <- t(matrix(c(kappa, mu, tau))) for (br in 1:bootstrap_round) { y_ser_turb <- mean_ + rnorm(length(mean_), 0, std_) theta <- opt_dde_theta(y_ser_turb, bs_interp, kappa, mu, tau, lambda, interg_interp, lr, decay, iters, lr_theta, iters_theta, FALSE) theta_mat <- rbind(theta_mat, t(matrix(theta))) print(br) } return(theta_mat) } theta_mat_prev <- comp_bootstrap_std(data_sh$total_affected[1:28], 0.5, 1.60, 1.17, 1.42, 25., 500, 0.1, 0.99, 2e2, 0.05, 1e1, 100) theta_mat_lockdown <- comp_bootstrap_std(data_sh$total_affected[28:nrow(data_sh)], 0.5, 0.60, 1.00, 1.80, 25., 500, 0.1, 0.99, 2e2, 0.05, 1e1, 100) ###################################################################################################### covid19_dde_predict <- function(ser, interp, total_len, kappa, mu, tau, sd_maxifier, err_maxifier) { # initialization init_num <- floor((length(ser) - 1) * interp) init_ser <- c(ser[length(ser)]) for (n in 1:(init_num - 1)) { tail_left_index <- length(ser) - n / interp l_ratio <- tail_left_index - floor(tail_left_index) inter_val <- ser[floor(tail_left_index)] * (1 - l_ratio) + ser[ceiling(tail_left_index)] * l_ratio init_ser <- c(inter_val, init_ser) } minus_steps <- round(tau * interp) lift_bias <- numeric(0) for (j in 1:(init_num - minus_steps)) { lift_bias <- c(lift_bias, (init_ser[j + minus_steps] - init_ser[j + minus_steps - 1]) * interp - kappa * (init_ser[j + minus_steps] - mu * init_ser[j])) } fit <- smooth.spline(1:length(lift_bias), lift_bias, df = 3) # plot(fit) # initialization finished while (length(init_ser) - init_num < total_len * interp) { if (length(init_ser) - init_num < 14 * interp) { deriv_ser <- max(0, sd_maxifier * sd(fit$y - fit$yin) + err_maxifier * predict(fit, length(init_ser) - minus_steps + 1)$y + kappa * (init_ser[length(init_ser)] - mu * init_ser[length(init_ser) - minus_steps])) init_ser <- c(init_ser, init_ser[length(init_ser)] + deriv_ser / interp) } else { mult_ <- exp((14 * interp + init_num - length(init_ser)) / (total_len * interp) * 5) deriv_ser <- max(0, mult_ * sd_maxifier * sd(fit$y - fit$yin) + mult_ * err_maxifier * predict(fit, length(init_ser) - minus_steps + 1)$y + kappa * (init_ser[length(init_ser)] - mu * init_ser[length(init_ser) - minus_steps])) init_ser <- c(init_ser, init_ser[length(init_ser)] + deriv_ser / interp) } } return(init_ser[init_num:length(init_ser)]) } gen_covid19_dde_cis <- function(ser, interp, total_len, theta_mat, end_date, sd_maxifier, err_maxifier) { pred_cis <- matrix(nrow = 0, ncol = total_len * interp + 1) for (r in 1:nrow(theta_mat)) { pred_ser <- covid19_dde_predict(ser, interp, total_len, theta_mat[r, 1], theta_mat[r, 2], theta_mat[r, 3], 0, err_maxifier) pred_cis <- rbind(pred_cis, t(matrix(pred_ser))) pred_ser <- covid19_dde_predict(ser, interp, total_len, theta_mat[r, 1], theta_mat[r, 2], theta_mat[r, 3], sd_maxifier, err_maxifier) pred_cis <- rbind(pred_cis, t(matrix(pred_ser))) } pred_ci_min <- apply(pred_cis, 2, min)[seq(1, interp * total_len + 1, interp)] pred_ci_max <- apply(pred_cis, 2, max)[seq(1, interp * total_len + 1, interp)] # pred_ci_avg <- apply(pred_cis,2,mean)[seq(1,interp*total_len+1,interp)] # pred_ci_avg <- pred_cis[1,][seq(1,interp*total_len+1,interp)]\ pred_ci_avg <- numeric(0) qt_ser <- seq(0.8, 0.8, length.out = ncol(pred_cis)) for (c in 1:ncol(pred_cis)) { cand <- quantile(pred_cis[, c], c(qt_ser[c])) cand <- max(cand, pred_ci_avg[length(pred_ci_avg)]) pred_ci_avg <- c(pred_ci_avg, cand) } pred_ci_avg <- pred_ci_avg[seq(1, interp * total_len + 1, interp)] return(data.frame(date = seq(end_date, end_date + total_len, 1), ci_min = pred_ci_min, ci_max = pred_ci_max, pred = pred_ci_avg)) } prev_df <- data_sh[1:28, c("date", "total_add", "total_affected")] prev_df$period <- "before lockdown" prev_pred <- opt_bs_coeff(data_sh$total_affected[1:28], 0.5, 1.60, 1.17, 1.42, 25., 500, 0.1, 0.99, 2e2, FALSE, FALSE) prev_df$pred <- prev_pred[1:(length(prev_pred) - 1)] prev_df$total_add[nrow(prev_df)] <- 0 lock_df <- data_sh[28:nrow(data_sh), c("date", "total_add", "total_affected")] lock_df$period <- "after lockdown" lock_pred <- opt_bs_coeff(data_sh$total_affected[28:nrow(data_sh)], 0.5, 0.60, 1.00, 1.80, 25., 500, 0.1, 0.99, 2e2, FALSE, FALSE) lock_df$pred <- lock_pred[1:(length(lock_pred) - 1)] fit_len <- 7 lock_tail_fit <- smooth.spline(1:fit_len, seq(0, 1, length.out = fit_len) * (lock_df$total_affected - lock_df$pred)[(nrow(lock_df) - fit_len + 1):nrow(lock_df)], df = 3) lock_df$pred[(nrow(lock_df) - fit_len + 1):nrow(lock_df)] <- lock_df$pred[(nrow(lock_df) - fit_len + 1):nrow(lock_df)] + lock_tail_fit$y clip <- function(x, vmin, vmax) { return(min(vmax, max(vmin, x))) } pred_cis <- gen_covid19_dde_cis(lock_df$pred, 10, 14, theta_mat_lockdown, data_sh$date[nrow(data_sh)], 0.0, 0.0) pred_std <- lock_pred[length(lock_pred)] * c(0, exp(seq(-1, -1, length.out = 14)), exp(seq(-1, -0.5, length.out = nrow(pred_cis) - 15))) pred_cis$total_add <- c(NaN, diff(pred_cis$pred)) pred_cis$period <- "forecasted" pred_cis$total_affected <- NaN pred_cis$ci_min <- sapply(pred_cis$ci_min - pred_std / 2, clip, vmin = 0, vmax = Inf) pred_cis$ci_max <- pred_cis$ci_max + pred_std / 2 pred_cis$add_min <- sapply(c(NaN, diff(pred_cis$ci_min)) - pred_std / 2, clip, vmin = 0, vmax = Inf) pred_cis$add_max <- c(NaN, diff(pred_cis$ci_max)) + pred_std / 2 final_df <- rbind(prev_df, lock_df) final_df$ci_min <- final_df$total_affected final_df$ci_max <- final_df$total_affected final_df$add_min <- NaN final_df$add_max <- NaN final_df <- rbind(final_df, pred_cis) base_plot <- ggplot(data = final_df, aes(x = date, y = total_affected, color = period, linetype = period, shape = period, alpha = period, size = period)) + scale_size_manual(values = c("before lockdown" = 2, "after lockdown" = 2, "forecasted" = 0)) + scale_alpha_manual(values = c("before lockdown" = 1, "after lockdown" = 1, "forecasted" = 1)) + scale_shape_manual(values = c("before lockdown" = 16, "after lockdown" = 16, "forecasted" = 4)) + scale_color_manual(values = c("before lockdown" = "gold3", "after lockdown" = "red3", "forecasted" = "blue3")) + scale_fill_manual(values = c("before lockdown" = "gold3", "after lockdown" = "red3", "forecasted" = "blue3")) + scale_linetype_manual(values = c("before lockdown" = "solid", "after lockdown" = "solid", "forecasted" = "dashed")) + theme( legend.direction = "vertical", legend.box = "horizontal", axis.title.x = element_blank(), ) start_date <- as.Date("2022-03-01", format = "%Y-%m-%d") end_date <- as.Date("2022-05-30", format = "%Y-%m-%d") trend <- base_plot + geom_line(aes(y = pred), size = 1, alpha = 0.3) + geom_point() + geom_ribbon(aes(ymin = ci_min, ymax = ci_max), linetype = 3, alpha = 0.2, size = 0) + scale_x_date(breaks = seq(start_date, end_date, by = "2 days"), limits = c(start_date - 1, end_date + 1)) + scale_y_continuous(breaks = seq(0, 6e5, 5e4), labels = label_number(suffix = " W", scale = 1e-4)) + ylab("Accumulated Confirmed Affected") + theme( axis.text.x = element_text(size = 10, angle = 90, hjust = -2, vjust = 0), legend.position = c(0.01, 0.99), legend.justification = c("left", "top") ) growth <- base_plot + geom_bar(aes(y = total_add, fill = period), size = 0.2, position = "stack", stat = "identity") + geom_errorbar(aes(ymin = add_min, ymax = add_max), width = .4, alpha = 0.5, size = .4, linetype = "solid") + scale_x_date(breaks = seq(start_date, end_date, by = "2 days"), position = "top", limits = c(start_date - 1, end_date + 1)) + scale_y_reverse(breaks = seq(0, 3e4, 5e3), labels = label_number(suffix = " K", scale = 1e-3), limits = c(3e4, 0)) + scale_alpha_manual(values = c("before lockdown" = .5, "after lockdown" = .5, "forecasted" = .2)) + ylab("Daily Added Confirmed") + theme( axis.text.x = element_blank(), legend.position = c(0.01, 0.01), legend.justification = c("left", "bottom"), ) grid.arrange(trend, growth, ncol = 1, heights = c(3, 1)) pred_df <- final_df[which(final_df$period == "forecasted"), c("date", "pred", "ci_min", "ci_max", "total_add", "add_min", "add_max")] for (r_ in 2:nrow(pred_df)) { print(pred_df[r_, "ci_max"] - pred_df[r_ - 1, "ci_min"] - pred_df[r_, "add_max"]) } write.table(pred_df[2:nrow(pred_df), ], "covid19_forecasted_0517_0530_SH_Whale.csv", row.names = FALSE, col.names = TRUE, sep = ",") ###################################################################################################### data_sh_prev_pred <- read.csv("covid19_forecasted_0517_0530_SH_Whale.csv") data_sh_prev_pred$date <- as.Date(data_sh_prev_pred$date, format = "%Y-%m-%d") data_valid_pred <- data_sh[, c("date", "total_add")] data_valid_pred$method <- "truth" data_valid_pred$add_min <- NaN data_valid_pred$add_max <- NaN cmpst_data <- data_valid_pred[which(data_valid_pred$date == min(data_sh_prev_pred$date) - 1), "total_add"] data_tmp <- data_sh_prev_pred[, c("date", "total_add", "add_min", "add_max")] cmpst_df <- data.frame(date = c(min(data_tmp$date) - 1), total_add = c(cmpst_data), add_min = c(cmpst_data), add_max = c(cmpst_data)) data_tmp <- rbind(cmpst_df, data_tmp) data_tmp$method <- "predicted" data_valid_pred <- rbind(data_valid_pred, data_tmp) ggplot(data = data_valid_pred, aes(x = date, y = total_add, color = method, linetype = method, shape = method, alpha = method, size = method)) + scale_size_manual(values = c("truth" = 0.8, "predicted" = 0.8)) + scale_alpha_manual(values = c("truth" = 0.8, "predicted" = 0.8)) + scale_shape_manual(values = c("truth" = 16, "predicted" = 4)) + scale_color_manual(values = c("truth" = "gold3", "predicted" = "blue3")) + scale_fill_manual(values = c("truth" = "gold3", "predicted" = "blue3")) + scale_linetype_manual(values = c("truth" = "solid", "predicted" = "dashed")) + theme( legend.direction = "vertical", legend.box = "horizontal", axis.title.x = element_blank(), ) + geom_line(aes(y = total_add)) + geom_point(aes(y = total_add), size = 1.5) + geom_ribbon(aes(ymin = add_min, ymax = add_max), linetype = 3, alpha = 0.2, size = 0) + scale_x_date(breaks = seq(min(data_valid_pred$date), max(data_valid_pred$date), by = "2 days")) + scale_y_continuous(breaks = seq(0, 3e4, 5e3), labels = label_number(suffix = " K", scale = 1e-3)) + ylab("Daily Confirmed Incremental") + theme( axis.text.x = element_text(size = 10, angle = 90, hjust = -2, vjust = 0), legend.position = c(0.01, 0.99), legend.justification = c("left", "top") ) ###################################################################################################### base_plot <- ggplot(data = final_df[which(final_df$period != "before lockdown"), ], aes(x = date, y = total_affected, color = period, linetype = period, shape = period, alpha = period, size = period)) + scale_size_manual(values = c("after lockdown" = 2, "forecasted" = 0)) + scale_alpha_manual(values = c("after lockdown" = 1, "forecasted" = 1)) + scale_shape_manual(values = c("after lockdown" = 16, "forecasted" = 4)) + scale_color_manual(values = c("after lockdown" = "red3", "forecasted" = "blue3")) + scale_fill_manual(values = c("after lockdown" = "red3", "forecasted" = "blue3")) + scale_linetype_manual(values = c("after lockdown" = "solid", "forecasted" = "dashed")) + theme( legend.direction = "vertical", legend.box = "horizontal", axis.title.x = element_blank(), ) start_date <- as.Date("2022-03-28", format = "%Y-%m-%d") end_date <- as.Date("2022-05-07", format = "%Y-%m-%d") trend <- base_plot + geom_line(aes(y = pred), size = 1, alpha = 0.3) + geom_point() + geom_ribbon(aes(ymin = ci_min, ymax = ci_max), linetype = 3, alpha = 0.2, size = 0) + scale_x_date(breaks = seq(start_date, end_date, by = "1 days"), limits = c(start_date - 1, end_date + 1)) + scale_y_continuous(breaks = seq(0, 6e5, 5e4), labels = label_number(suffix = " W", scale = 1e-4)) + ylab("Accumulated Confirmed Affected") + theme( axis.text.x = element_text(size = 10, angle = 90, hjust = -2, vjust = 0), legend.position = c(0.01, 0.99), legend.justification = c("left", "top") ) growth <- base_plot + geom_bar(aes(y = total_add, fill = period), size = 0.2, position = "stack", stat = "identity") + geom_errorbar(aes(ymin = add_min, ymax = add_max), width = .4, alpha = 0.5, size = .4, linetype = "solid") + scale_x_date(breaks = seq(start_date, end_date, by = "1 days"), position = "top", limits = c(start_date - 1, end_date + 1)) + scale_y_reverse(breaks = seq(0, 3e4, 5e3), labels = label_number(suffix = " K", scale = 1e-3), limits = c(3e4, 0)) + scale_alpha_manual(values = c("after lockdown" = .5, "forecasted" = .2)) + ylab("Daily Added Confirmed") + theme( axis.text.x = element_blank(), legend.position = c(0.01, 0.01), legend.justification = c("left", "bottom"), ) grid.arrange(trend, growth, ncol = 1, heights = c(3, 1)) library(scatterplot3d) source("addgrids3d.r") theta_df <- data.frame(theta_mat_lockdown) colnames(theta_df) <- c("kappa", "mu", "tau") scatterplot3d(theta_df, type = "h", pch = 1, color = "darkgreen", grid = FALSE, box = FALSE) addgrids3d(theta_df, grid = c("xy", "xz", "yz"))
# brain-teaser ![License](https://img.shields.io/badge/License-MIT-blue.svg) Race against the clock and put your coding knowledge to the test with our thrilling quiz game. Designed with newcomers in mind, Brain Teaser offers an exciting way to learn about coding. Take the quiz, track your scores, and aim for the top of the leaderboard! ## Table of Contents - [Installation](#installation) - [Features](#features) - [Usage](#usage) - [Testing](#testing) - [License](#license) - [Link](#link) - [Contact Me](#contact-me) ## Installation Follow these instructions to set up and run the brain teaser quiz game: **Requirements:** - A web browser (e.g., Chrome, Firefox) **Using a Deployment Link:** 1. **Access the Deployment Link:** Below in the Link Section, there is a deployment link. 2. **Open the Game:** Click on the provided deployment link to open the quiz game in your web browser. 3. **Start Playing:** Once the game loads in your browser, click the "Start Quiz" button to begin the quiz. 4. **Submit Your Score:** After completing the quiz, you can submit your score and initials by clicking the "Submit Score" button. 5. **View the Leaderboard:** To view the leaderboard and see where you rank, click the "View Leaderboard" button. ## Features - **Quiz Questions:** The game offers a series of challenging coding-related questions that test the player's knowledge and problem-solving skills. - **Timer:** A countdown timer adds excitement and pressure, challenging players to answer questions quickly and accurately. - **Scoring:** The game keeps track of the player's score, motivating them to strive for a higher score with each playthrough. - **Leaderboard:** The leaderboard feature allows players to compete with others and see where they rank, adding a competitive and social aspect to the game. - **LocalStorage:** Player scores and initials are stored locally, enabling them to track their progress and compete against themselves and others over time. ![Full Page Image](/assets/images/landing-page.jpeg) ![Full Page Image](/assets/images/view-leaderboard.jpeg) ## Usage The coding quiz game can be used for various purposes, both educational and recreational: - Educational Tool - Self-Assessment - Interview Preparation - Casual Entertainment - Skill Development ## Testing Here are the steps to test the quiz: **Cloning the GitHub Repository:** 1. **Open your CLI:** Open your terminal or command prompt on your local machine. 2. **Navigate to the Desired Directory:** Use the below command to navigate to the directory where you want to store the project: ```sh cd coding/learning_tools/games/github ``` 3. **Clone the Repository:** Use the below command to clone the GitHub repository: ```sh git clone https://github.com:Clkwong3/brain-teaser.git ``` 4. **Navigate to the Project Directory:** Change to the newly created project directory: ```sh cd brain-teaser ``` 5. **Open in Code Editor:** Open the project folder in your preferred code editor (e.g., Visual Studio Code). 6. **Launch in Browser:** You can open the index.html file in your web browser to start playing the quiz game locally. Right-click the index.html file and select "Open with" to choose your browser. ##### You now have the quiz game code on your local machine to modify and test the game locally. ## License All rights reserved. Licensed under the MIT license. ## Link Here is the deployment link: [brain-teaser](https://clkwong3.github.io/brain-teaser/) ## Contact Me If you encounter any issues, please report them on the project's [GitHub repository](https://github.com/Clkwong3/brain-teaser). You can also connect with me on [GitHub](https://github.com/Clkwong3).
IP协议头部结构 版本号 头部长度 服务类型 总长 标识标志 片偏移量 生存时间 协议 头部校验和 源IP地址和目标IP地址 TCP协议头部结构 源端口号 目标端口号 序列号 确认号 头部长度 保留位 标志位 窗口大小 校验和 紧急指针 UDP协议头部结构 源端口号 目标端口号 总长度 校验和 HTTP请求分为4个部分:请求行,请求头、空行、请求正文 请求行分为:请求方法、URL、版本号 请求头包含很多信息,都是键值对形式,包括cookie,语言、压缩方式等 HTTP响应同样是4个部分:响应行、响应头、空行、响应正文 响应行:版本号、状态码、状态码的描述 响应头同样也是键值对,内容类型,日期等 TCP和UDP区别: TCP面向连接,UDP不需要连接 TCP一对一,UDP支持一对一、一对多、多对多 TCP保证可靠性,UDP不保证可靠性 TCP拥有拥塞控制和流量控制,UDP没有 TCP头部较大,UDP较小且固定长度 TCP保证可靠性的方法: 随机序列 确认应答 (ACK) 超时重传 连接管理 (三次握手四次挥手) 流量控制 (根据接收端的处理能力,来决定发送端的发送速度) 滑动窗口 (接收数据段使用的窗口大小,用来告知发送端接收端的缓存大小,以此控制发送端发送数据的大小,达到流量控制的目的) 拥塞控制 (慢开始,拥塞避免,快重传,快回复) UDP如何实现可靠传输: 参考TCP,在应用层实现确认机制,重传机制,窗口确认机制 HTTP的状态码 1XX:信息类,100,正在处理请求 2XX:成功类,200 OK 成功处理请求 3XX:重定向类,301永久移动,302临时移动 4XX:请求错误,400请求语法错误,404未找到,405请求方式不支持 5XX:服务器错误 500服务器内部错误 502网关错误,网关从上游服务器中接受到的响应是无效的,是指上游服务器自己执行超时或者没有按照协议约定来返回数据 503服务不可用(服务器停机维护或者超载,暂时状态) 504网关超时,是指超过了网关自己的时间,没有建立与服务器之间的联系 HTTPS SSL/TCL公钥私钥交换过程: 服务器把自己的公钥登录至CA CA将服务器的公钥使用散列技术生成哈希值,生成一个摘要 CA使用自己的私钥加密这个摘要生成数字签名附在证书下面,发送给服务器 服务器将这个证书发送给客户端 客户端拿到证书后,使用CA的公钥,解密数字签名,获得CA生成的摘要 客户端对证书内的数据,也就是服务器的公钥,做相同的散列处理,得到摘要,与之前签名中解码得到的摘要对比来验证身份 验证通过后,客户端使用服务器的公钥对数据加密后发送 服务器使用私钥进行解密 HTTP1.0是短连接,在一次http连接完成后就会断开,需要重复建立连接十分耗费时间和资源 1.1是长连接,完成一次连接后tcp连接还会保留一段时间,如果需要进行新的http连接直接连接即可,可以复用 HTTP的长连接和短连接本质上就是tcp的长连接和短连接 HTTP2.0加入了多路复用技术,可以一个连接发送多个请求,头部压缩,服务器推送,可以对一个客户端请求发送多个响应,加快了响应速度 HTTP3.0基于UDP协议 TCP的保活机制是由一个保活计时器实现的,当计时器被激发,会发送一个保活检测报文,另一端接收报文后会响应一个ACK 如果收到响应就重置计时器,没有收到,则经过一个时间间隔后再次发送,依次类推直到达到保活探测数,此时,中断连接 IP地址可以分为 1.五类IP (IP地址一共32位,分别以1/2,1/4,1/8, 1/16分段) A类:0.0.0.0 - 127.255.255.255 B类:128.0.0.0 - 191.255.255.255 C类:192.0.0.0 - 223.255.255.255 D类:224.0.0.0 - 239.255.255.255 E类:240.0.0.0 - 255.255.255.255 2.特殊用途IP,特殊源、换回、广播 3.私有IP websocket websocket能够实现全双工通信,基于tcp, http是单向的且每次发送数据时要包含大量头信息 websocket通过第一次建立tcp连接之后,不需要发送header就可以交换数据 用户态和内核态之间的切换 1.系统调用,是用户态程序主动向系统申请切换 2.异常,在执行用户态的程序时,发生了某些不可知的异常,这时会切换到处理此异常的内核态程序,完成了切换 3.中断,外围设备向CPU发送中断信号,这时CPU会停止执行下一条指令而去执行处理中断信号的程序,如果之前执行的用户态程序,这样就自然完成了用户态到内核态的转换 32位地址空间高位的是内核空间,低位的是用户空间 五种IO模型 同步阻塞IO 同步非阻塞IO IO多路复用,(select poll epoll 监视文件描述符(fd)) 异步IO,指异步非阻塞IO 信号驱动IO IO多路复用 select,用一个集合将所有的fd全部拷贝,然后进行轮询,且集合大小有限 poll,将select的集合替换为链表,因此大小没有限制 epoll,事件驱动,采用回调机制,避免了不断复制的问题,且支持很高的同时连接数,支持水平触发和边缘触发 水平触发:只要一个文件描述符就绪,就会触发通知,会重触发 边缘触发:当描述符从未就绪到就绪会通知一次,后续就不会再通知,效率更高,减少了被冲触发的次数 操作系统IO的过程: 1.IO中断,外部存储设备通过IO中断通知CPU,CPU将数据拷贝到内核缓冲区,然后拷贝到用户缓冲区,每次都有上下文切换开销及CPU拷贝的时间 2.通过DMA(Direct Memory Access),CPU通知DMA控制器拷贝外部存储设备数据到内核缓冲区,完成后再通知CPU拷贝到用户缓冲区减轻了CPU的负担 数据库的MVCC主要在RR级别和RC级别下实现(RU级别没有解决任何一个问题,串行化直接加表锁) 主要是实现非锁定读,核心思想是对每个连接数据库的用户,查询操作读到的都是快照,写入操作在事务提交之前对于其他用户来说都是不可见的 通过数据库的隐藏字段, DATA_TRX_ID:标记最近更新这条记录的事务id DATA_ROLL_PTR:指向该条记录的undo log记录 DB_ROW_ID:如果没有建立索引,则有默认索引 DELETE_BIT:标识该条数据有没有被删除 每次事务修改数据时:update时候是当前读 使用排它锁锁定该行 记录redo log 将修改前的值拷贝到undo log 修改当前行的值,填写事务编号,让回滚指针指向undo log中修改前的行 在RC级别下,读事务每次都读取距离undo log最近的那个版本 在RR级别下,每次都读取指定的版本 在RR级别下,快照读ReadView在第一次执行普通select查询时生成,可重复读实际上就是ReadView的重复使用,也就解决了幻读的问题 在RC级别下,每次读时都会产生一个ReadView 每次读取操作时,只能读取到select事务版本之前创建的行,也就是创建版本号小于当前事务版本号的行 以及在当前事务之后删除的行,也就是删除版本号大于当前事务版本号的行 MySQL锁的分类: 基于属性:共享锁、排它锁 基于粒度:表锁、行锁(记录锁、间隙锁) 基于状态:意向共享锁、意向排它锁 共享锁就是读锁,也叫S锁,一个事物对数据加上S锁之后,其他事物只能对该数据加读锁 排它锁就是写锁,也叫X锁,当一个事物对数据加上X锁后,其他事物不能对该数据添加任何锁 表锁粒度大,对整张表加锁,行锁粒度小,并发度更高 间隙锁可以解决幻读问题 数据库四大特性ACID分别使用什么方法实现? A原子性,通过undo log,主要能实现事务回滚 I隔离性,主要通过锁和mvcc D持久性,主要通过redo log,当数据库服务器意外崩溃或者宕机后,保证已经提交的事务,持久化到磁盘中 C一致性,一致性是目的,AID是手段 MySQL的索引: 主键索引、唯一索引、普通索引、全文索引 索引为什么要用B+树实现 1.提升查询效率,尽可能少的从磁盘读取数据 2.保证读取的数据足够有效所以要分块读取 3.磁盘和内存进行交互以页为单位,一般读取页的整数倍,innoDB默认读取16kb 4.二叉树等有个致命缺点就是节点只有2个,插入多个数据时会导致变深,查询效率下降 5.因此要使用多叉树,同时因为数据都是有序的,因此考虑B树和B+树 6.B树不能保证查询每个数据效率都一致,并且每个块都会存储索引和实际数据,实际数据占用空间,造成树的分支减少,也就会增加树的深度 自增主键的优点: 1.自动编号,速度快,按顺序存放,对于检索十分有利 2.数字型,空间小,易于排序,传递也方便 3.不担心主键重复 缺点: 1.因为自增,在手动要插入指定ID的记录时会十分麻烦,当有多个系统需要数据导入时,很难保证原系统与新系统的id不发生冲突 2.如果经常合并表,就可能出现主键重复的情况 数据库三大范式 1.无重复的列 2.属性完全依赖于主键 3.属性不依赖于其他非主属性 Java泛型的实现原理:类型擦除,使用Object等来替代泛型,在实现具体类型方法或者成员变量时使用强转保证多态特性 解决java中传统非线程安全的容器可以使用Collections.synchronized + 容器类型(Map, Set, List)方法 Java虚拟机运行时的数据区: 线程隔离的数据区:虚拟机栈,本地方法栈,程序计数器 线程共享的数据区:方法区,堆 JDK1.8,静态变量和字符串常量池存放在堆中,运行时常量池存放在方法区中 Java中的引用: 1.强引用,平常使用的都是强引用,可以直接访问目标对象,在任何时候都不会被回收 2.软引用,比强引用弱一些的引用,只有当堆空间不足时,会回收这个对象,使用场景:回收 3.弱引用,比软引用弱一些,只要发现弱引用,不管空间是否足够,都会在下次回收时回收,使用场景:回收 4.虚引用,最弱的,和没有引用几乎是一样的,随时都可以被垃圾回收器回收,使用场景:对象回收的跟踪 Java类加载过程: 1.加载:通过全限定名获取二进制字节流,将这个类的静态存储结构转化为方法去的运行时数据结构,在内存中生成一个代表这个类的对象 2.验证:确保字节流中的信息不回危害到虚拟机 3.准备:为类的静态变量分配内存,并初始化为默认值(注意区分这里的默认值是说这类型的默认值,并不是用户指定的) 4.解析:将常量池内的符号引用替换为直接引用 5.初始化:将主导权移交给应用程序,包括静态字段赋值的操作
import { createContext, ReactNode, useEffect, useState } from 'react'; import { Product } from './products.types'; import productsJSON from '../products.json'; type Props = { children: ReactNode; } export const ProductsInterfaceContext = createContext({ products: [] as Product[], categories: [] as string[], fetchProducts: (selectedCategories: string[]) => {}, loading: false }); /* Mock data promise start */ const fetchProductsPromise = (selectedCategories: string[]) => { return new Promise<Product[]>(res => { setTimeout(() => { const products = productsJSON as Product[]; res( selectedCategories.length === 0 ? products : products.filter(product => selectedCategories.includes(product.category)) ); }, 400); }) } const fetchCategoriesPromise = () => { return new Promise<string[]>(res => { setTimeout(() => { const products = productsJSON as Product[]; const categories: string[] = []; products.forEach(product => { if(!categories.includes(product.category) && product.category) { categories.push(product.category) } }) res(categories); }, 50); }); } /* Mock data promise end */ const ProductsInterface = (props: Props) => { const [ products, setProducts ] = useState<Product[]>([]); const [ categories, setCategories ] = useState<string[]>([]); const [ loading, setLoading ] = useState(false); const fetchProducts = async (selectedCategories: string[]) => { setLoading(true); const response = await fetchProductsPromise(selectedCategories); setProducts(response); setLoading(false); } useEffect(() => { async function fetchCategories() { const response = await fetchCategoriesPromise(); setCategories(response); } fetchCategories(); }, []); return ( <ProductsInterfaceContext.Provider value={{ fetchProducts, products, categories, loading, }}> {props.children} </ProductsInterfaceContext.Provider> ) } export default ProductsInterface;
import wollok.game.* const ancho = 20 const alto = 15 const alturaAgua = 8 const fondoIniciar = new Visual( image = "assets/fondoInicio.jpg", position = game.at(0,0) ) const fondoCerrar1 = new Visual ( image = "assets/fondoCierre.jpg", position = game.at(0,0) ) const fondoCerrar2 = new Visual ( image = "assets/fondoCierre2.jpg", position = game.at(0,0) ) object pantalla{ method pantallaInicio() { game.title("Pesca en el Hielo") game.width(ancho) game.height(alto) game.addVisual(fondoIniciar) game.boardGround("assets/fondo1.png") keyboard.enter().onPressDo{self.iniciar()} const musica = game.sound("assets/cancionFondo.mp3") musica.shouldLoop(true) game.schedule(500,{musica.play() musica.volume(0.5)}) keyboard.m().onPressDo{musica.volume(0)} keyboard.u().onPressDo{musica.volume(0.5)} keyboard.d().onPressDo{musica.volume(0.1)} } method iniciar(){ game.clear() game.height(alto) game.width(ancho) game.boardGround("assets/fondo1.png") game.addVisual(heladeraConPeces) game.addVisual(contadorVida) game.onTick(5000,"se crea pez", {const pez = new Pez() game.addVisual(pez) pez.movete() }) game.onTick(7000,"se crea basura", {const basura = new Basura() game.addVisual(basura) basura.movete() }) game.onTick(10000,"se crea medusa", {const medusa = new Medusa() game.addVisual(medusa) medusa.movete() }) game.onTick(30000,"se crea tiburon", {const tiburon = new Tiburon() game.addVisual(tiburon) tiburon.movete() }) game.onTick(50000,"se crea lata de gusanos", {const lataGusanos = new Gusano() game.addVisual(lataGusanos) lataGusanos.movete() }) game.onTick(10000,"se crea pulpo", {const pulpo = new Pulpo() game.addVisual(pulpo) pulpo.movete() }) game.onTick(20000,"se crea quita manchas", {const quitaManchas = new QuitaManchas() game.addVisual(quitaManchas) quitaManchas.movete() }) game.onTick(10000,"se crea cangrejo", {const cangrejo = new Cangrejo() game.addVisual(cangrejo) cangrejo.movete() }) game.addVisual(persona) game.addVisual(ansu) keyboard.up().onPressDo({ansu.moverseArriba()}) keyboard.down().onPressDo({ansu.moverseAbajo()}) game.onCollideDo(ansu,{algo => algo.ansuPesco() algo.fuePescado()}) } } object persona { var property estaParalizado = false var property estaManchado = false var property position = game.at(8.15,10.99999455) var property image = "assets/pinguino.png" method cambiarImagen() { image = "assets/pinguinoElectrocutado2.png" } method volverNormalidad() { image = "assets/pinguino.png" } method cambiarImagenTinta(){ image= "assets/pinguinoConTinta.png" } method electrucutado() { if (estaParalizado) { estaParalizado = false } else { estaParalizado = true } } method perdio() { return contadorVida.vidas() <= 0 } method mancharConTinta() { estaManchado = true self.cambiarImagenTinta() game.say(self, "Tengo que encontrar el limpia manchas") } method limpiar() { self.volverNormalidad() estaManchado = false } } object contadorVida { var property vidas = 3 var property image = "assets/contVidas3.png" var property position = game.at(1,13.5) method sacarVida(cant) { vidas = vidas - cant image = "assets/contVidas"+ vidas + ".png" if (persona.perdio()){ game.clear() game.addVisual(fondoCerrar1) game.schedule(1000,{heladeraConPeces.agregarFinal()}) } } method agregarVida() { if (vidas < 3){ vidas = vidas + 1 image = "assets/contVidas"+ vidas + ".png" } } } object heladeraConPeces { var property position = game.at(3,11) var property capacidad = 0 method image() { return "assets/pez" + self.capacidad() + ".png" } method aumentarCantidad() { capacidad += 1 } method agregarFinal() { position = game.at(12,1) game.addVisual(self) } } class ObjetosFlotantes { var property sePesco = false const vertical = (0..(alturaAgua-1)).anyOne() const horizontal = [21,-2].anyOne() const posicionInicial = game.at(horizontal,vertical) var property estaDerecha = !(horizontal == -2) var property position = posicionInicial method fuePescado() { sePesco = true } method movete() { if (position.x() == -3 or position.x() == 22){ if (!sePesco) {game.removeVisual(self)} } else { self.moverPosicion() game.schedule(self.velocidadMov(),{self.movete()}) } } method moverPosicion() { if (estaDerecha){ position = position.left(1) } else { position = position.right(1) } } method velocidadMov() = 1000 } class Pez inherits ObjetosFlotantes { method image() { return if (estaDerecha) "assets/pezDer.png" else "assets/pezIzq.png" } method ansuPesco() { ansu.cambiarImagen("Pez") game.removeVisual(self) } } class Basura inherits ObjetosFlotantes { const basuras = ["zapato","barril","zapato2"] const objeto = basuras.anyOne() method image() { return "assets/" + objeto + ".png"} method ansuPesco() { game.removeVisual(self) contadorVida.sacarVida(1) } override method velocidadMov() = 1500 } class Medusa inherits ObjetosFlotantes { const cantidadParalizar = 1500 method image() {return if (estaDerecha) "assets/meduzaDer.png" else "assets/meduzaIzq.png"} method ansuPesco(){ contadorVida.sacarVida(1) persona.cambiarImagen() ansu.cambiarImagen("cañaElectrocutada") persona.electrucutado() game.removeVisual(self) game.schedule(cantidadParalizar,{ansu.sacarElec() persona.volverNormalidad() persona.electrucutado() }) } override method velocidadMov() = 500 } class Gusano inherits ObjetosFlotantes { var property image = "assets/lataDeGusanos.png" method ansuPesco() { game.removeVisual(self) contadorVida.agregarVida() } override method velocidadMov() = 250 } class Tiburon inherits ObjetosFlotantes { method image() { return if (estaDerecha) "assets/tiburonIzq.png" else "assets/tiburonDer.png" } method ansuPesco() { game.removeVisual(self) contadorVida.sacarVida(3) } override method velocidadMov() = 500 } class Pulpo inherits ObjetosFlotantes { method image() { return if (estaDerecha) "assets/pulpoDER.png" else "assets/pulpoIZQ.png" } method ansuPesco() { game.removeVisual(self) self.mancharConTinta() contadorVida.sacarVida(1) } method mancharConTinta(){ persona.mancharConTinta() game.addVisual(mancha) } } class QuitaManchas inherits ObjetosFlotantes { var property image = "assets/limpiaManchas.png" method ansuPesco() { game.removeVisual(self) persona.limpiar() mancha.limpiar() } override method velocidadMov() = 800 } class Cangrejo inherits ObjetosFlotantes{ method image() { return if (estaDerecha) "assets/cangrejoDer.png" else "assets/cangrejoIzq.png" } method ansuPesco(){ game.clear() game.addVisual(fondoCerrar2) game.schedule(1000,{heladeraConPeces.agregarFinal()}) } } object mancha{ var property position = game.at(1,-1) method image() { return "assets/mancha.png" } method limpiar() { game.removeVisual(self) } } object ansu { var property position = game.at(9,alturaAgua+1) var property caniaElec = false var property image = "assets/ansu.png" var property cont = 0 method arribaMaximo() { return cont < 0 } method moverseArriba() { if (!persona.estaParalizado()) { if ( self.arribaMaximo() ) { position = position.up(1) cont += 1 } else { self.hayUnPescado() } } } method moverseAbajo() { if (!persona.estaParalizado()) { position = position.down(1) const nuevo = new Hilo(position = position.up(1)) game.addVisual(nuevo) cont -= 1 } } method hayUnPescado() { if (self.image() == "assets/ansuConPez.png") { image = "assets/ansu.png" heladeraConPeces.aumentarCantidad() } } method cambiarImagen(cosa) { if (cosa == "cañaElectrocutada") { caniaElec = true } else { image = "assets/ansuCon" + cosa + ".png" } } method sacarElec() { caniaElec = false } method posicionAbajo() { return position.up() } } class Hilo { var property position var image = "assets/hilo.png" method image() { if (ansu.caniaElec()){ image = "assets/canaElectrocutada.png" } else { image = "assets/hilo.png" } return image } method ansuPesco() { game.removeVisual(self) } method fuePescado () {} } class Visual { var property image var property position = game.origin() }
/* * bst.h * * Created on: 9/10/2023 * Author: Jesús Alejandro Cedillo Zertuche */ #ifndef BST_H_ #define BST_H_ #include <string> #include <sstream> using namespace std; // Header para el friend template <class T> class BST; /* El nodo es el circulito. Tiene el valor, y los apuntadores de sus hijos en la derecha y en la izquierda */ template <class T> class TreeNode { private: T value; TreeNode *left, *right; public: // Constructor TreeNode(T); // Funciones simples implementadas en clase void add(T); bool find(T, int&); // Funciones auxiliares de funciones creadas int whatlevelamI(T val, int& count); int height(int& count, TreeNode<T>* root); void ancestors_exist(stringstream&, T val); void ancestors_recursion(stringstream &aux, T val); int count_elements(int& count); void print_level(stringstream &aux, TreeNode<T>* root, int level, int elements, int& element_num); // Funciones distintas para imprimir el árbol void preorder(stringstream&) const; void inorder(stringstream&) const; void postorder(stringstream&) const; void level_by_level(stringstream&, TreeNode<T>* root); friend class BST<T>; }; // Creas el nodo donde insertar el valor template <class T> TreeNode<T>::TreeNode(T val): value(val), left(0), right(0) {} // Función de agregar template <class T> void TreeNode<T>::add(T val) { // Comparas el valor a insertar contra el valor del nodo if (val < value){ // Si no es nulo, se vuelve a llamar la función con recursión. if (left != 0){ // Aquí el left es el hijo, y se llama la función para que haga la comparación left -> add(val); } // Si es Nulo, ahí se agrega y crea el objeto else { left = new TreeNode<T>(val); } } // Si no, se inserta a la derecha y se hace lo mismo, donde se inserta hasta que llege a nulo else { if (right != 0){ right -> add(val); } else { right = new TreeNode<T>(val); } } } // Función de buscar template <class T> bool TreeNode<T>::find(T val, int &count) { // El caso base donde si lo encontró if (val == value){ return true; } // Si es menor recorre hacia la izquierda else if (val < value){ // Si es nulo, llegó al final y no lo encontró if (left == 0){ return false; } // Si no es nulo, vas a left y llamas a la recursión con ese nodo else { count++; return left -> find(val, count); } } // Si es mayor reocorre hacia la derecha else if (val > value){ // Si es nulo, es caso base y no lo encontró if (right == 0){ return false; } // Si no es nulo, vas al hijo de right y llamas a la recursión con ese nodo else { count++; return right -> find(val, count); } } // Regresar -1 que no lo encontró y para que no tenga warning else { return -1; } } template <class T> int TreeNode<T>::whatlevelamI(T val, int& count){ // Si en el find encuentra el valor regresar el counter if (find(val, count) == true){ return count; } // Si no lo encontró entonces regresar -1 que no existe else { return -1; } } // Pasas el level donde se guarda, y el root, para que al revisar el nivel lo haga de la raíz template <class T> int TreeNode<T>::height(int& level, TreeNode<T>* root){ // Creas variable para guardar int level_count; // Inicializas el count en 1 int count = 1; // Si existe árbol en left if (left != 0){ // Buscas el nivel de left y lo guardas level_count = root -> whatlevelamI(left -> value, count); // Como whatlevelamI usa paso por referencia, sobreescribes a 1 para siguiente nivel recursión count = 1; // Comparas el nivel a ver si es uno más alto. Si es lo guardas en level if (level_count > level){ level = level_count; } // Llamas la recursión pasando al nodo de abajo y pasando la raíz left -> height(level, root); } // Si existe árbol en right if (right != 0){ // Buscas el nivel de right y lo guardas level_count = root -> whatlevelamI(right -> value, count); // Como whatlevelamI usa paso por referencia, sobreescribes a 1 count = 1; // Comparas el nivel a ver si es uno más alto. Si es lo guardas en level if (level_count > level){ level = level_count; } // Llamas la recursión pasando al nodo de abajo y pasando la raíz right -> height(level, root); } // Después de que haya acabado regresas level return level; } template <class T> void TreeNode<T>::ancestors_exist(stringstream &aux, T val){ // Para poder usar el valor de find int count = 1; // Asegurar que el valor exista if (find(val, count) == true){ ancestors_recursion(aux, val); } } template <class T> void TreeNode<T>::ancestors_recursion(stringstream &aux, T val){ // Caso base para que la recursión pare if (value == val){ return; } // Guardas el al string aux << value; // Esta función toma como raíz el nodo, y ve en que nivel esta comparado con ese nodo int count_space = 1; whatlevelamI(val, count_space); /* Ahora, como no se esta imprimiendo el valor, si no sus ancestors cuando sea el último ancestor (nodo padre del valor que se está buscando) no se quiere que tenga un espacio, por lo que se asegura que si es igual a 2 (penúltimo nodo) no se agregue. De igual forma, como el caso base está arriba tampoco llega al 1. */ if (count_space != 2){ aux << " "; } // Ves hacia donde tienes que recorrer y recorres hacia (left) if (val < value){ left -> ancestors_recursion(aux, val); } // Ves hacia donde tienes que recorrer y recorres hacia (right) if (val > value) { right -> ancestors_recursion(aux, val); } } template <class T> int TreeNode<T>::count_elements(int& count){ // Recorres el árbol incrementando el contador hasta que no haya nada if (left != 0){ left -> count_elements(count); count++; } if (right != 0){ right -> count_elements(count); count++; } return count; } // Como es preorder lo junta antes de ir recorriendo template <class T> void TreeNode<T>::preorder(stringstream &aux) const { // Se imprime al principio aux << value; if (left != 0) { aux << " "; left->preorder(aux); } if (right != 0) { aux << " "; right->preorder(aux); } } // Como es inorder lo junta a la mitad (entre left y right) template <class T> void TreeNode<T>::inorder(stringstream &aux) const { if (left != 0) { left->inorder(aux); } if (aux.tellp() != 1) { aux << " "; } // Se imprime a la mitad aux << value; if (right != 0) { right->inorder(aux); } } // Como es postorder lo junta después de recorrer (hojas) template <class T> void TreeNode<T>::postorder(stringstream &aux) const { // Si hay elemento llamas la recursión if (left != 0) { left->postorder(aux); aux << " "; } if (right != 0) { right->postorder(aux); aux << " "; } // Se imprime al final aux << value; } template <class T> void TreeNode<T>::print_level(stringstream &aux, TreeNode<T>* root, int level, int total_elements, int& element_num){ // Sacas el nivel del current node int level_num = 1; // Sacar el nivel del valor root -> whatlevelamI(value, level_num); // Si el nivel sacado, es igual al nivel del for loop entonces lo agregas if (level_num == level){ aux << value; // Incrementas el número de elementos para saber en cual no poner espacio element_num++; // Si el número de elementos imprimidos es distinto al total poner un espacio if (total_elements != element_num){ aux << " "; } } else { // Aseguras que exista left if (left != 0){ // Llamas la recursión left -> print_level(aux, root, level, total_elements, element_num); } // Aseguras que exista right if (right != 0){ // Llamas la recursión right -> print_level(aux, root, level, total_elements, element_num); } } } template <class T> void TreeNode<T>::level_by_level(stringstream &aux, TreeNode<T>* root) { // Sacas el height del árbol para saber cuántos niveles hay que imprimir int height_num = 1; height(height_num, root); // Sacas el número de elementos para saber donde poner el espacio int elements = 1; root -> count_elements(elements); int element_num = 0; // Haces un for loop que corra las veces del height for (int count = 1; count <= height_num; count++){ print_level(aux, root, count, elements, element_num); } } // Este es el árbol completo que tiene el apuntador a la raíz template <class T> class BST { private: TreeNode<T> *root; public: // Constructor BST(); // Funciones simples implementadas en clase bool empty() const; void add(T); // Funciones pedidas a implementar string visit(); int height(); string ancestors(T val); int whatlevelamI(T val); // Funciones distintas para imprimir el árbol string preorder() const; string inorder() const; string postorder() const; string level_by_level() const; }; // Creas el arbol donde inicias la raíz a 0 template <class T> BST<T>::BST() : root(0) {} // Si la raíz es 0, el árbol está vacío template <class T> bool BST<T>::empty() const { return (root == 0); } // Función de agregar template<class T> void BST<T>::add(T val) { // Si el root está vacío y existe el árbol int count = 1; if (root != 0){ // Buscas el objeto para ver si ya está el valor if (!root -> find(val, count)){ // Si no, se agrega el valor. // Esto llama a la función de add de Node, (en este caso root) root -> add(val); } } // Si apenas empieza el árbol entonces creas el primer árbol else { root = new TreeNode<T>(val); } } // Funciones a implementar template <class T> string BST<T>::visit(){ // Creas la variable en donde guardar los datos string preorder_text, inorder_text, postorder_text, level_by_level_text; // Guardas el texto llamando cada función preorder_text = preorder(); inorder_text = inorder(); postorder_text = postorder(); level_by_level_text = level_by_level(); // Creas la variable a regresar donde se suma todo string final; final = preorder_text + "\n" + inorder_text + "\n" + postorder_text + "\n" + level_by_level_text; return final; } template <class T> int BST<T>::height(){ // Iniciar la altura en 1 si existe raíz // Asegurar que exista un árbol int count = 1; if (root != 0){ return root -> height(count, root); } // Si no regresar 0 else { return 0; } } template <class T> string BST<T>::ancestors(T val){ stringstream aux; // Para que se imprima en cualquier caso aux << "["; if (root != 0){ // Llamas a mandar la función auxiliar root -> ancestors_exist(aux, val); } aux << "]"; return aux.str(); } template <class T> int BST<T>::whatlevelamI(T val){ // Si no es nulo llamas al find whatlevelamI int count = 1; if (root != 0){ return root -> whatlevelamI(val, count); } else { return 0; } } // Imprimir el árbol de distintas formas template <class T> string BST<T>::preorder() const { stringstream aux; aux << "["; if (!empty()) { root->preorder(aux); } aux << "]"; return aux.str(); } template <class T> string BST<T>::inorder() const { stringstream aux; aux << "["; if (!empty()) { root->inorder(aux); } aux << "]"; return aux.str(); } template <class T> string BST<T>::postorder() const { stringstream aux; aux << "["; if (!empty()) { root->postorder(aux); } aux << "]"; return aux.str(); } template <class T> string BST<T>::level_by_level() const { stringstream aux; aux << "["; if (!empty()) { root->level_by_level(aux, root); } aux << "]"; return aux.str(); } #endif /* BST_H_ */
// // ProductCardView.swift // funiture-store-swiftui // // Created by Gideon Okoroafor on 4/18/24. // import SwiftUI struct ProductCardView: View { @EnvironmentObject var cartManager: CartManager var product: Product var body: some View { ZStack{ Color("kSecondary") ZStack(alignment: .bottomTrailing){ VStack(alignment: .leading){ Image(product.image) .resizable() .frame(width: 175, height: 160) .cornerRadius(12) Text(product.name) .foregroundColor(.black) .font(.headline) .padding(.vertical, 1) Text(product.supplier) .foregroundColor(.gray) .font(.caption) .padding(.vertical, 0.5) Text("$ \(product.price)") .foregroundColor(.black) .bold() } Button{ cartManager.addToCart(product: product) } label: { Image(systemName: "plus.circle.fill") .resizable() .foregroundColor(Color("kPrimary")) .frame(width: 35, height: 35) .padding(.trailing) } } } .frame(width: 185, height: 260) .cornerRadius(15) } } #Preview { ProductCardView(product: productList[0]) .environmentObject(CartManager()) }
# Technical challenge ## Objective The goal of the challenge is to run Backstage locally, understand the basic parts, extend it with plugins and enhance both the backend and frontend part. You are kindly requested to read the following document, follow the directions to complete the challenge and prepare answer any questions, noted as `Q*`, example `Q1`. The answers should be short and to the point. Challenge the questions and highlight any missing points. > The time spent on the challenge should be limited to **4 hours**. > > Joke disclaimer: Don't count `yarn install` in the duration! ### What is Backstage? Backstage is an open platform for building developer portals. Powered by a centralized software catalog, Backstage brings order to our microservices and infrastructure and enables the product teams to ship high-quality code quickly — without compromising autonomy. Backstage unifies all our infrastructure tooling, services, apis and documentation to create a streamlined development environment from end to end. ### Why is Backstage part of the technical challenge? In Developer Experience team of Celonis, we have invested heavily on Backstage and delivered impactful features that our team of developers uses every day. We have planned to extend further this platform and we invite you to demonstrate your skills in order to become part of this effort. ## Challenge Contribute to an existing project, using Typescript and ReactJS, and understand the provided documentation. Also, put in use your git skills to publish your deliverables; be thorough on your commits and related messages to showcase your git practices. When you finish your challenge, reply to the email you received and send the url to the private repo along with the answers to the questions. ### Run the app locally > Note: You can run the challenge with your preferred setup, but we're also providing a `.devcontainer` folder configuration in case you want to use it with VSCODE. **Steps:** - Create a new private repository using this repository as a template and give access to the following handles: `georgeyord`, `LauraMoraB` and `mariosant`. ![Github repo template](gh-repo-template.png) - Read [Backstage’s docs](https://backstage.io/docs/getting-started/#create-your-backstage-app) to initialize Backstage locally - Use SQlite as *persistent* database by adding to the `app-config.local.yaml`: ```yaml backend: database: client: better-sqlite3 connection: directory: ../../challenge-data/sqlite ``` - At this point, you should have a working Backstage instance running locally. Verify it and continue to the next section. **Questions** - **Q1.** When Backstage service is up and running, how many apps are running? - **Q2.** How many ports are used on the hosting machine? - **Q3.** Why do we have 3 `package.json` files? - **Q4.** In which `package.json` file would you put a new dependency and why? - **Q5.** Why changes on `app-config.local.yaml` are not commited by default on git? Is this a good or bad practice and why? - **Q6.** Would you use the existing `app-config.production.yaml` to configure the database credentials for your production database and commit the changes in git? - **Q7.** Can you describe why we configure `backend.cors` values in `app-config.yaml`? What is CORS? Why is it important on modern browsers? ### Extend Backstage Now that you've successfully set up Backstage locally and confirmed its functionality, let's delve into understanding its plugin system. #### 1. Installing the Shortcuts Plugin Begin by integrating an open-source plugin into your Backstage instance. We'll install the [Shortcuts plugin](https://github.com/backstage/community-plugins/blob/main/workspaces/shortcuts/plugins/shortcuts/README.md). This plugin enhances Backstage by adding a new section to the sidebar. Follow the instructions outlined in its README file to integrate it with your Backstage application. Once the Shortcuts plugin is integrated and operational, we'd like to implement a few modifications: - **Adding a Shortcut**: Incorporate a direct shortcut to the URL `https://www.celonis.com/` within the Shortcuts section; external url is used *on purpose*. - **Changing the Sidebar Icon**: Adjust the icon displayed on the sidebar to reflect a ChatIcon for improved visual representation. #### 2. Modifying Route Names As part of our customization process, we aim to alter the route name for the `Create...` section from `/create` to `/innovate`. **Questions** - **Q8:** Where it needs to be changed and why? - **Q9:** Which page is loaded first `Root.tsx` or `App.tsx` and why? ### Creating a Custom Backstage Plugin: Display Users Now that we've successfully installed an open-source plugin, it's time to work on custom features to display a list of Users in Backstage. To accomplish this, we'll divide the work between enhancing an existing Backend plugin and creating from scratch a Frontend one. #### 1. Extend a Backstage Backend plugin Let's begin with the Backend aspect of our feature. We provide an existing plugin located at the root of this repository, under `sample-backend`. This plugin comes with two default endpoints: `health` and `users`. ##### **Initial Setup and Verification** - Add the `sample-backend` plugin to your Backstage application. [https://backstage.io/docs/plugins/integrating-plugin-into-software-catalog#import-your-plugin-and-embed-in-the-entities-page](plugin integration) - Run Bakcstage and verify the functionality by accessing the provided endpoints (`/api/sample/health` and `/api/sample/users`). **Questions** - **Q10:** Can you explain how did you verify the plugin worked? > Please, note that the plugin as we're providing it should work, *though some of the tests may be failing*. ##### **Modifications** 1. We ultimetly want to add a feature for displaying a list of items on a webpage. The list can potentially contain a large number of items, and we want to ensure smooth performance and user experience. Implement a function or method that takes in a list of items and returns a subset of items, limited to five items per page. 2. For verification purposes, modify the API to also return the MD5 hash of each user's email. #### 2. Create a Backstage Frontend plugin - With our Backend setup in place, let's move on to developing the UI. Follow [this guide](https://backstage.io/docs/plugins/create-a-plugin/) to initialize a Frontend Plugin. - Run Backstage and verify that the Frontend plugin is visible in the UI. ##### 1. Integration with Backend The sample plugin has already a functinality similar to our goal. The issue is that the user list is static. Enhance the Frontend plugin to consume the API provided by `sample-backend`. This doc on [Consuming APIs](https://backstage.io/docs/frontend-system/utility-apis/consuming/) is at you disposal. ##### 2. UI Implementation Display the list of users using a tile view, as described in the [Tile View documentation](https://backstage.io/storybook/?path=/story/layout-item-cards--default). ##### 3. Verification of Email Integrity Implement a status icon to visually indicate the validity of each user's email. Verify that the email value has not been tampered with and is authentic. **Questions** - **Q11:** How did this hash related to the email upgraded the validity of our data? - **Q12:** How does nd5 work, where should it be used and where not? Give some examples. ### Notes - Backstage is currenlty migrating the backend to a new system. Since it's still in alpha, we won't be using it in this challenge. Beware that some packages may appear as deprecated (like `useHotMemoize`), please ignore these warnings and proceed with your development as usual. - When running `yarn install` for the first time, please be aware that it may take a significant amount of time to complete. This delay is expected due to the installation of necessary dependencies and configurations.
import React from "react"; import { Accordion } from "react-bootstrap"; const Blogs = () => { return ( <div className="container"> <Accordion defaultActiveKey="0"> <Accordion.Item eventKey="0"> <Accordion.Header> What are the different ways to manage a state in a React application? </Accordion.Header> <Accordion.Body> <h2>Communication State:</h2> <p> Communication state forms the backbone of your React Native app without you even knowing about it. Remember when you had requested a call back to an HTTP request? That’s when you introduced the communication system in your app. </p> <p> Communication plays a crucial role in storing information in different states. It covers essential aspects of an application such as loading spinners, error messages, pop-ups, and many others which showcases that a communication link has been formed. Communication state is the “loading phase” of the transactions between different states. It stores the following information when used in a React app: </p> <p> 1. The error messages, given that the request failed or the transaction was not completed. </p> <p> 2. The type, selector, and expected change of operations requested. </p> <p>3. The type of data requested to access or expect to receive.</p> <br /> <br /> <h2>Data State</h2> <p> Data state covers information that your React application stores temporarily for various business functions. Supposedly, you are building a project management app. The information stored in the data state will include the following things – project names, contacts, details about the clients, etc. </p> <h2>Control State</h2> <p> Contrary to the state mentioned above in a React app, the control state does not represent the application’s environment. Instead, it refers to the state which the user has input into the app. For example, form inputs, selected items, etc. Control state is known to be more diverse and versatile when it comes to storing information. </p> <br /> <br /> <h2>Session State</h2> <p> Session state contains information about the user of the application such as user id, permissions, passwords, etc. It may also include information on how the application should work according to a particular user’s preferences. </p> <p> While Session state can store similar patterned components like Control state, there is a thick difference between both the information stored. For example, you may have a part of a Control state information that represents parts of a tree view, you can find kind of similar data in the Session state, but it will definitely be different from the Control state. </p> <p> Session states can only be read when a component is mounted, which means that you store a copy of the information already present in the Control state. It stores personal preferences based on the user’s choices to depict the data. </p> <br /> <br /> <h2>Location State</h2> <p> Location state is the UTF-8 display that appears in your URL bar. In fact, the L in URL stands for Locator! One of the most interesting facts about Location state is that you can give directions to a user to parts of the application that do not have unique URLs associated with them. Also, the HTML5 History API allows you to store states separately from the specific URL. </p> <p> Unlike Data and Communication state, which follow a particular pattern or a shape to store information, location state instead stores information in a simple string like structure. However, one of the most interesting things about location states is that it typically stores URLs in the forms of string-like structures even when they don’t actually represent strings. </p> </Accordion.Body> </Accordion.Item> <Accordion.Item eventKey="1"> <Accordion.Header> How does prototypical inheritance work? </Accordion.Header> <Accordion.Body> <p> Every object with its methods and properties contains an internal and hidden property known as [[Prototype]]. The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object.getPrototypeOf and Object.setPrototypeOf. Nowadays, in modern language, it is being set using __proto__. </p> </Accordion.Body> </Accordion.Item> <Accordion.Item eventKey="2"> <Accordion.Header> What is a unit test? Why should we write unit tests? </Accordion.Header> <Accordion.Body> <h2>What is Unit test ?</h2> <p> Unit testing is a type of software testing where individual units or software components are tested. Its purpose is to validate that each unit of code performs as expected. A unit can be anything you want it to be — a line of code, a method, or a class.{" "} </p> <h2>Why Should we use Unit test ?</h2> <p> Unit tests save time and money. Usually, we tend to test the happy path more than the unhappy path. If you release such an app without thorough testing, you would have to keep fixing issues raised by your potential users. The time to fix these issues could’ve been used to build new features or optimize the existing system. Bear in mind that fixing bugs without running tests could also introduce new bugs into the system. </p> <p> Well-written unit tests act as documentation for your code. Any developer can quickly look at your tests and know the purpose of your functions. </p> <p>It simplifies the debugging process</p> <p> Unit testing is an integral part of extreme programming. Extreme programming is basically a “test-everything-that-can-possibly-break” programming strategy. </p> <p> Unit testing improves code coverage. A debatable topic is to have 100% code coverage across your application. </p> </Accordion.Body> </Accordion.Item> <Accordion.Item eventKey="3"> <Accordion.Header>React vs. Angular vs. Vue?</Accordion.Header> <Accordion.Body> <h2>React JS</h2> <p> React, interestingly, combines the UI and behavior of components. For instance, here is the code to create a hello world component in React. In React, the same part of the code is responsible for creating a UI element and dictating its behavior. </p> <p> React offers a Getting Started guide that should help one set up React in about an hour. The documentation is thorough and complete, with solutions to common issues already present on Stack Overflow. React is not a complete framework and advanced features require the use of third-party libraries. This makes the learning curve of the core framework not so steep but depends on the path you take with additional functionality. However, learning to use React does not necessarily mean that you are using the best practices. </p> <h2>Angular JS</h2> <p> Angular has a steep learning curve, considering it is a complete solution, and mastering Angular requires you to learn associated concepts like TypeScript and MVC. Even though it takes time to learn Angular, the investment pays dividends in terms of understanding how the front end works. </p> <p> In Angular, components are referred to as directives. Directives are just markers on DOM elements, which Angular can track and attach specific behavior too. Therefore, Angular separates the UI part of components as attributes of HTML tags, and their behaviors in the form of JavaScript code. This is what sets it apart when looking at Angular vs React. </p> <h2>Vue JS</h2> <p> When looking into Vue vs React, in Vue, UI and behavior are also a part of components, which makes things more intuitive. Also, Vue is highly customizable, which allows you to combine the UI and behavior of components from within a script. Further, you can also use pre-processors in Vue rather than CSS, which is a great functionality. Vue is great when it comes to integration with other libraries, like Bootstrap. </p> <p> Vue provides higher customizability and hence is easier to learn than Angular or React. Further, Vue has an overlap with Angular and React with respect to their functionality like the use of components. Hence, the transition to Vue from either of the two is an easy option. However, simplicity and flexibility of Vue is a double-edged sword — it allows poor code, making it difficult to debug and test. </p> <h5> Although Angular, React and Vue have a significant learning curve, their uses upon mastery are limitless. For instance, you can integrate Angular and React with WordPress and WooCommerce to create progressive web apps. </h5> </Accordion.Body> </Accordion.Item> </Accordion> </div> ); }; export default Blogs;
/** @module String */ import { isStr } from './isStr' /** * Converts a string to train case, I.E. marginTop => margin-top. * @function * @param {String} string to be converted * @return {String} - string in train case format */ export const trainCase = <T extends string = string>(str: string): T => ((isStr(str) && str .split(/(?=[A-Z])|[\s_-]/gm) .join('-') .toLowerCase()) as T) || (str as T)
import "package:dio/dio.dart"; import 'package:ente_auth/core/configuration.dart'; import "package:ente_auth/core/errors.dart"; import "package:ente_auth/l10n/l10n.dart"; import "package:ente_auth/models/api/user/srp.dart"; import "package:ente_auth/services/user_service.dart"; import "package:ente_auth/theme/ente_theme.dart"; import 'package:ente_auth/ui/common/dynamic_fab.dart'; import "package:ente_auth/ui/components/buttons/button_widget.dart"; import "package:ente_auth/utils/dialog_util.dart"; import "package:ente_auth/utils/email_util.dart"; import 'package:flutter/material.dart'; import "package:logging/logging.dart"; // LoginPasswordVerificationPage is a page that allows the user to enter their password to verify their identity. // If the password is correct, then the user is either directed to // PasswordReentryPage (if the user has not yet set up 2FA) or TwoFactorAuthenticationPage (if the user has set up 2FA). // In the PasswordReentryPage, the password is auto-filled based on the // volatile password. class LoginPasswordVerificationPage extends StatefulWidget { final SrpAttributes srpAttributes; const LoginPasswordVerificationPage({Key? key, required this.srpAttributes}) : super(key: key); @override State<LoginPasswordVerificationPage> createState() => _LoginPasswordVerificationPageState(); } class _LoginPasswordVerificationPageState extends State<LoginPasswordVerificationPage> { final _logger = Logger((_LoginPasswordVerificationPageState).toString()); final _passwordController = TextEditingController(); final FocusNode _passwordFocusNode = FocusNode(); String? email; bool _passwordInFocus = false; bool _passwordVisible = false; @override void initState() { super.initState(); email = Configuration.instance.getEmail(); _passwordFocusNode.addListener(() { setState(() { _passwordInFocus = _passwordFocusNode.hasFocus; }); }); } @override Widget build(BuildContext context) { final isKeypadOpen = MediaQuery.of(context).viewInsets.bottom > 100; FloatingActionButtonLocation? fabLocation() { if (isKeypadOpen) { return null; } else { return FloatingActionButtonLocation.centerFloat; } } return Scaffold( resizeToAvoidBottomInset: isKeypadOpen, appBar: AppBar( elevation: 0, leading: IconButton( icon: const Icon(Icons.arrow_back), color: Theme.of(context).iconTheme.color, onPressed: () { Navigator.of(context).pop(); }, ), ), body: _getBody(), floatingActionButton: DynamicFAB( key: const ValueKey("verifyPasswordButton"), isKeypadOpen: isKeypadOpen, isFormValid: _passwordController.text.isNotEmpty, buttonText: context.l10n.logInLabel, onPressedFunction: () async { FocusScope.of(context).unfocus(); await verifyPassword(context, _passwordController.text); }, ), floatingActionButtonLocation: fabLocation(), floatingActionButtonAnimator: NoScalingAnimation(), ); } Future<void> verifyPassword(BuildContext context, String password) async { final dialog = createProgressDialog( context, context.l10n.pleaseWait, isDismissible: true, ); await dialog.show(); try { await UserService.instance.verifyEmailViaPassword( context, widget.srpAttributes, password, dialog, ); } on DioError catch (e, s) { await dialog.hide(); if (e.response != null && e.response!.statusCode == 401) { _logger.severe('server reject, failed verify SRP login', e, s); await _showContactSupportDialog( context, context.l10n.incorrectPasswordTitle, context.l10n.pleaseTryAgain, ); } else { _logger.severe('API failure during SRP login', e, s); if (e.type == DioErrorType.other) { await _showContactSupportDialog( context, context.l10n.noInternetConnection, context.l10n.pleaseCheckYourInternetConnectionAndTryAgain, ); } else { await _showContactSupportDialog( context, context.l10n.oops, context.l10n.verificationFailedPleaseTryAgain, ); } } } catch (e, s) { _logger.info('error during loginViaPassword', e); await dialog.hide(); if (e is LoginKeyDerivationError) { _logger.severe('loginKey derivation error', e, s); // LoginKey err, perform regular login via ott verification await UserService.instance.sendOtt( context, email!, isCreateAccountScreen: true, ); return; } else if (e is KeyDerivationError) { // device is not powerful enough to perform derive key final dialogChoice = await showChoiceDialog( context, title: context.l10n.recreatePasswordTitle, body: context.l10n.recreatePasswordBody, firstButtonLabel: context.l10n.useRecoveryKey, ); if (dialogChoice!.action == ButtonAction.first) { await UserService.instance.sendOtt( context, email!, isResetPasswordScreen: true, ); } return; } else { _logger.severe('unexpected error while verifying password', e, s); await _showContactSupportDialog( context, context.l10n.oops, context.l10n.verificationFailedPleaseTryAgain, ); } } } Future<void> _showContactSupportDialog( BuildContext context, String title, String message, ) async { final dialogChoice = await showChoiceDialog( context, title: title, body: message, firstButtonLabel: context.l10n.contactSupport, secondButtonLabel: context.l10n.ok, ); if (dialogChoice!.action == ButtonAction.first) { await sendLogs( context, context.l10n.contactSupport, "auth@ente.io", postShare: () {}, ); } } Widget _getBody() { return Column( children: [ Expanded( child: AutofillGroup( child: ListView( children: [ Padding( padding: const EdgeInsets.only(top: 30, left: 20, right: 20), child: Text( context.l10n.enterPassword, style: Theme.of(context).textTheme.headlineMedium, ), ), Padding( padding: const EdgeInsets.only( bottom: 30, left: 22, right: 20, ), child: Text( email ?? '', style: getEnteTextTheme(context).smallMuted, ), ), Visibility( // hidden textForm for suggesting auto-fill service for saving // password visible: false, child: TextFormField( autofillHints: const [ AutofillHints.email, ], autocorrect: false, keyboardType: TextInputType.emailAddress, initialValue: email, textInputAction: TextInputAction.next, ), ), Padding( padding: const EdgeInsets.fromLTRB(20, 24, 20, 0), child: TextFormField( key: const ValueKey("passwordInputField"), autofillHints: const [AutofillHints.password], decoration: InputDecoration( hintText: context.l10n.enterYourPasswordHint, filled: true, contentPadding: const EdgeInsets.all(20), border: UnderlineInputBorder( borderSide: BorderSide.none, borderRadius: BorderRadius.circular(6), ), suffixIcon: _passwordInFocus ? IconButton( icon: Icon( _passwordVisible ? Icons.visibility : Icons.visibility_off, color: Theme.of(context).iconTheme.color, size: 20, ), onPressed: () { setState(() { _passwordVisible = !_passwordVisible; }); }, ) : null, ), style: const TextStyle( fontSize: 14, ), controller: _passwordController, autofocus: true, autocorrect: false, obscureText: !_passwordVisible, keyboardType: TextInputType.visiblePassword, focusNode: _passwordFocusNode, onChanged: (_) { setState(() {}); }, ), ), const Padding( padding: EdgeInsets.symmetric(vertical: 18), child: Divider( thickness: 1, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ GestureDetector( behavior: HitTestBehavior.opaque, onTap: () async { await UserService.instance.sendOtt( context, email!, isResetPasswordScreen: true, ); }, child: Center( child: Text( context.l10n.forgotPassword, style: Theme.of(context) .textTheme .titleMedium! .copyWith( fontSize: 14, decoration: TextDecoration.underline, ), ), ), ), GestureDetector( behavior: HitTestBehavior.opaque, onTap: () async { final dialog = createProgressDialog( context, context.l10n.pleaseWait, ); await dialog.show(); await Configuration.instance.logout(); await dialog.hide(); Navigator.of(context) .popUntil((route) => route.isFirst); }, child: Center( child: Text( context.l10n.changeEmail, style: Theme.of(context) .textTheme .titleMedium! .copyWith( fontSize: 14, decoration: TextDecoration.underline, ), ), ), ), ], ), ), ], ), ), ), ], ); } }
<?php namespace App\Entity; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\GraphQl\DeleteMutation; use ApiPlatform\Metadata\GraphQl\Mutation; use ApiPlatform\Metadata\GraphQl\Query; use ApiPlatform\Metadata\GraphQl\QueryCollection; use App\Entity\Traits\BlameableTrait; use App\Entity\Traits\TimestampableTrait; use App\Enum\EmployeeStatusEnum; use App\Repository\EmployeeRepository; use App\State\EmployeeProcessor; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; use Symfony\Bridge\Doctrine\IdGenerator\UuidGenerator; use Symfony\Bridge\Doctrine\Types\UuidType; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Uid\Uuid; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Context\ExecutionContextInterface; #[ORM\Entity(repositoryClass: EmployeeRepository::class)] #[ApiResource( security: 'is_granted("ROLE_USER")', operations: [], processor: EmployeeProcessor::class, graphQlOperations: [ new Query( normalizationContext: [ 'groups' => [self::READ, self::READ_PUBLIC], ], security: 'is_granted("READ_PUBLIC", object)', ), new QueryCollection( normalizationContext: [ 'groups' => [self::READ, self::READ_PUBLIC], ] ), new Mutation( name: 'create', denormalizationContext: [ 'groups' => [self::CREATE], ], normalizationContext: [ 'groups' => [self::READ], ], validationContext: [ 'groups' => [self::CREATE], ], securityPostDenormalize: 'is_granted("CREATE", object)', ), new Mutation( name: 'validate', denormalizationContext: [ 'groups' => [self::VALIDATE], ], normalizationContext: [ 'groups' => [self::READ], ], validationContext: [ 'groups' => [self::VALIDATE], ], security: 'is_granted("VALIDATE", object)', ), new Mutation( name: 'update', denormalizationContext: [ 'groups' => [self::UPDATE], ], normalizationContext: [ 'groups' => [self::READ], ], validationContext: [ 'groups' => [self::VALIDATE], ], security: 'is_granted("UPDATE", object)', ), new DeleteMutation( name: 'delete', security: 'is_granted("DELETE", object)', ), ] )] #[UniqueEntity( fields: ['codeName', 'establishment'], message: 'employee.code_name.unique', errorPath: 'codeName', groups: [self::VALIDATE], )] class Employee { use BlameableTrait; use TimestampableTrait; public const READ = 'employee:read'; public const READ_PUBLIC = 'employee:read:public'; public const CREATE = 'employee:create'; public const VALIDATE = 'employee:validate'; public const UPDATE = 'employee:update'; public const DAY_MONDAY = 'monday'; public const DAY_TUESDAY = 'tuesday'; public const DAY_WEDNESDAY = 'wednesday'; public const DAY_THURSDAY = 'thursday'; public const DAY_FRIDAY = 'friday'; public const DAY_SATURDAY = 'saturday'; public const DAY_SUNDAY = 'sunday'; public const DAYS = [ self::DAY_MONDAY, self::DAY_TUESDAY, self::DAY_WEDNESDAY, self::DAY_THURSDAY, self::DAY_FRIDAY, self::DAY_SATURDAY, self::DAY_SUNDAY, ]; #[ORM\Id] #[ORM\Column(type: UuidType::NAME, unique: true)] #[ORM\GeneratedValue(strategy: 'CUSTOM')] #[ORM\CustomIdGenerator(class: UuidGenerator::class)] #[ApiProperty(identifier: true)] private ?Uuid $id = null; /** * @var array<string, array<int, array<string, string>>> */ #[ORM\Column(type: Types::JSON)] #[ApiProperty(security: '')] #[Groups([self::READ, User::READ, self::CREATE])] private array $weeklySchedule = []; #[ORM\Column(length: 100, nullable: true)] #[Groups([self::READ, self::READ_PUBLIC, User::READ, User::READ_PUBLIC, self::VALIDATE])] #[Assert\When( expression: 'this.getStatus() == enum("App\\\Enum\\\EmployeeStatusEnum::Active")', constraints: [ new Assert\NotBlank( message: 'employee.code_name.not_blank', groups: [self::VALIDATE] ), ], groups: [self::VALIDATE] )] #[Assert\Length( max: 50, maxMessage: 'employee.code_name.max_length', groups: [self::VALIDATE] )] private ?string $codeName = null; #[ORM\OneToOne(mappedBy: 'employee', targetEntity: User::class)] #[Groups([self::READ])] private ?User $user = null; /** @var ArrayCollection<int, EmployeeTimeOff> */ #[ORM\OneToMany(mappedBy: 'employee', targetEntity: EmployeeTimeOff::class, orphanRemoval: true)] private Collection $timeOffs; #[ORM\ManyToOne(inversedBy: 'employees', targetEntity: Establishment::class)] #[ORM\JoinColumn(nullable: false)] #[Groups([self::READ, self::READ_PUBLIC, self::CREATE])] #[Assert\NotNull( message: 'employee.establishment.not_null', groups: [self::CREATE] )] private ?Establishment $establishment = null; #[ORM\Column(length: 50, enumType: EmployeeStatusEnum::class)] #[ApiProperty(security: '')] #[Groups([self::READ, User::READ, self::VALIDATE])] #[Assert\Choice( choices: [EmployeeStatusEnum::Active, EmployeeStatusEnum::Rejected], message: 'employee.status.either_active_or_rejected', groups: [self::VALIDATE] )] private EmployeeStatusEnum $status = EmployeeStatusEnum::Pending; #[ORM\Column(type: Types::TEXT, nullable: true)] #[ApiProperty(security: '')] #[Groups([self::READ, self::CREATE])] #[Assert\NotBlank( message: 'employee.motivation.not_blank', groups: [self::CREATE] )] #[Assert\Length( min: 10, max: 1000, minMessage: 'employee.motivation.min_length', maxMessage: 'employee.motivation.max_length', groups: [self::CREATE] )] private ?string $motivation = null; #[ORM\Column(type: Types::TEXT, nullable: true)] #[Groups([self::READ, self::READ_PUBLIC, self::UPDATE])] #[Assert\Length( max: 1000, maxMessage: 'employee.description.max_length', groups: [self::UPDATE] )] private ?string $description = null; /** @var ArrayCollection<int, Heist> */ #[ORM\ManyToMany(targetEntity: Heist::class, mappedBy: 'allowedEmployees')] private Collection $allowedHeists; /** @var ArrayCollection<int, Heist> */ #[ORM\OneToMany(mappedBy: 'employee', targetEntity: Heist::class)] private Collection $heists; public function __construct() { $this->timeOffs = new ArrayCollection(); $this->allowedHeists = new ArrayCollection(); $this->heists = new ArrayCollection(); } public function getId(): ?Uuid { return $this->id; } /** * @return array<string, array<int, array<string, string>>> */ public function getWeeklySchedule(): array { return $this->weeklySchedule; } /** * @param array<string, array<int, array<string, string>>> $weeklySchedule */ public function setWeeklySchedule(array $weeklySchedule): static { $this->weeklySchedule = $weeklySchedule; return $this; } public function getCodeName(): ?string { return $this->codeName; } public function setCodeName(?string $codeName): static { $this->codeName = $codeName; return $this; } public function getUser(): ?User { return $this->user; } public function setUser(?User $user): static { // unset the owning side of the relation if necessary if (null === $user && null !== $this->user) { $this->user->setEmployee(null); } // set the owning side of the relation if necessary if (null !== $user && $user->getEmployee() !== $this) { $user->setEmployee($this); } $this->user = $user; return $this; } /** * @return Collection<int, EmployeeTimeOff> */ public function getTimeOffs(): Collection { return $this->timeOffs; } public function addTimeOff(EmployeeTimeOff $timeOff): static { if (!$this->timeOffs->contains($timeOff)) { $this->timeOffs->add($timeOff); $timeOff->setEmployee($this); } return $this; } public function removeTimeOff(EmployeeTimeOff $timeOff): static { if ($this->timeOffs->removeElement($timeOff)) { // set the owning side to null (unless already changed) if ($timeOff->getEmployee() === $this) { $timeOff->setEmployee(null); } } return $this; } public function getEstablishment(): ?Establishment { return $this->establishment; } public function setEstablishment(?Establishment $establishment): static { $this->establishment = $establishment; return $this; } public function getStatus(): EmployeeStatusEnum { return $this->status; } public function setStatus(EmployeeStatusEnum $status): static { $this->status = $status; return $this; } public function getMotivation(): ?string { return $this->motivation; } public function setMotivation(?string $motivation): static { $this->motivation = $motivation; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(?string $description): static { $this->description = $description; return $this; } /** * @return Collection<int, Heist> */ public function getAllowedHeists(): Collection { return $this->allowedHeists; } public function addAllowedHeist(Heist $allowedHeist): static { if (!$this->allowedHeists->contains($allowedHeist)) { $this->allowedHeists->add($allowedHeist); $allowedHeist->addAllowedEmployee($this); } return $this; } public function removeAllowedHeist(Heist $allowedHeist): static { if ($this->allowedHeists->removeElement($allowedHeist)) { $allowedHeist->removeAllowedEmployee($this); } return $this; } /** * @return Collection<int, Heist> */ public function getHeists(): Collection { return $this->heists; } public function addHeist(Heist $heist): static { if (!$this->heists->contains($heist)) { $this->heists->add($heist); $heist->setEmployee($this); } return $this; } public function removeHeist(Heist $heist): static { if ($this->heists->removeElement($heist)) { // set the owning side to null (unless already changed) if ($heist->getEmployee() === $this) { $heist->setEmployee(null); } } return $this; } public function hasContractor(User $user): bool { return $this->establishment?->getContractor() === $user; } /** * Validates the weekly schedule. */ #[Assert\Callback(groups: [self::CREATE])] public function validateWeeklySchedule(ExecutionContextInterface $context): void { /** * @var array<string, array<int, array<string, string>>|string> */ $weeklySchedule = $this->getWeeklySchedule(); $totalHours = 0; foreach (self::DAYS as $day) { // Validate if all days are present if (!isset($weeklySchedule[$day]) || !\is_array($weeklySchedule[$day])) { $context->buildViolation('employee.weekly_schedule.missing_day') ->atPath('weeklySchedule') ->setParameter('{{ day }}', $day) ->addViolation() ; continue; } $daySchedule = $weeklySchedule[$day]; $schedulesForDay = []; $i = 0; foreach ($daySchedule as $schedule) { ++$i; $entry = (string) $i; // Validate if all required fields are present if (!isset($schedule['startAt']) || !isset($schedule['endAt'])) { $context->buildViolation('employee.weekly_schedule.missing_start_at_or_end_at') ->atPath('weeklySchedule') ->setParameter('{{ day }}', $day) ->setParameter('{{ entry }}', $entry) ->addViolation() ; continue; } $startAt = $schedule['startAt']; $startAtNumbers = explode(':', $startAt); $endAt = $schedule['endAt']; $endAtNumbers = explode(':', $endAt); // Validate if both have 2 numbers if (2 !== \count($startAtNumbers) || 2 !== \count($endAtNumbers)) { $context->buildViolation('employee.weekly_schedule.invalid_start_at_or_end_at') ->atPath('weeklySchedule') ->setParameter('{{ day }}', $day) ->setParameter('{{ entry }}', $entry) ->addViolation() ; continue; } // Validate if both are valid hours (e.g. 00:00 - 23:59) if ($startAtNumbers[0] < 0 || $startAtNumbers[0] > 23 || $startAtNumbers[1] < 0 || $startAtNumbers[1] > 59) { $context->buildViolation('employee.weekly_schedule.invalid_start_at_or_end_at') ->atPath('weeklySchedule') ->setParameter('{{ day }}', $day) ->setParameter('{{ entry }}', $entry) ->addViolation() ; continue; } if ($endAtNumbers[0] < 0 || $endAtNumbers[0] > 23 || $endAtNumbers[1] < 0 || $endAtNumbers[1] > 59) { $context->buildViolation('employee.weekly_schedule.invalid_start_at_or_end_at') ->atPath('weeklySchedule') ->setParameter('{{ day }}', $day) ->setParameter('{{ entry }}', $entry) ->addViolation() ; continue; } $startAtDate = new \DateTimeImmutable($startAt); $endAtDate = new \DateTimeImmutable($endAt); // Validate if startAt is before endAt if ($startAtDate >= $endAtDate) { $context->buildViolation('employee.weekly_schedule.start_at_after_end_at') ->atPath('weeklySchedule') ->setParameter('{{ day }}', $day) ->setParameter('{{ entry }}', $entry) ->addViolation() ; continue; } $hasOverlap = false; // Validate if there are no overlaps (e.g. 00:00 - 01:00 and 00:30 - 01:30) foreach ($schedulesForDay as $scheduleForDay) { $scheduleForDayStartAt = new \DateTimeImmutable($scheduleForDay['startAt']); $scheduleForDayEndAt = new \DateTimeImmutable($scheduleForDay['endAt']); if (($startAtDate >= $scheduleForDayStartAt && $startAtDate < $scheduleForDayEndAt) || ($endAtDate > $scheduleForDayStartAt && $endAtDate <= $scheduleForDayEndAt) ) { $hasOverlap = true; $context->buildViolation('employee.weekly_schedule.overlap') ->atPath('weeklySchedule') ->setParameter('{{ day }}', $day) ->setParameter('{{ entry }}', $entry) ->setParameter('{{ startAt }}', $startAt) ->setParameter('{{ endAt }}', $endAt) ->setParameter('{{ scheduleForDayStartAt }}', $scheduleForDay['startAt']) ->setParameter('{{ scheduleForDayEndAt }}', $scheduleForDay['endAt']) ->addViolation() ; } } if ($hasOverlap) { continue; } $schedulesForDay[] = $schedule; $totalHours += $endAtDate->diff($startAtDate)->h; } } // Validate if total hours is more than minimum if ($totalHours < $this->getEstablishment()?->getMinimumWorkTimePerWeek()) { $context->buildViolation('employee.weekly_schedule.total_hours_less_than_minimum') ->atPath('weeklySchedule') ->setParameter('{{ totalHours }}', (string) $totalHours) ->setParameter('{{ minimumWorkTimePerWeek }}', (string) $this->getEstablishment()?->getMinimumWorkTimePerWeek()) ->addViolation() ; } } }
import {User} from "../../../userModule/user.model"; import {Action, Selector, State, StateContext} from "@ngxs/store"; import {Injectable} from "@angular/core"; import { UsersService } from "src/Services/users.service"; import { AddUser, DeleteUser, UpdateUser, getUser } from "../Action/employee.action"; import { Observable, tap } from "rxjs"; export class userStateModel{ users:User[] userLoaded:boolean } @State<userStateModel>({ name:'Users', defaults:{ users:[], userLoaded:false } }) @Injectable() export class UsersState { constructor(private userService:UsersService){} @Selector() static getUserlist(state:userStateModel){ return state.users } // Get loaded employee info @Selector() static isuserloaded(state:userStateModel){ return state.userLoaded; } @Action(getUser) getUsers({ getState, setState }: StateContext<userStateModel>) { return this.userService.getData().pipe( tap((res:any) => { const state = getState(); setState({ ...state, users: res, userLoaded: true }); }) ); } @Action(AddUser) addUser({ getState, patchState }: StateContext<userStateModel>, { payload }: AddUser): Observable<any> { return this.userService.addUser(payload).pipe( tap((res: any) => { const state = getState(); if (res && res._id && res.firstName && res.lastName && res.email) { patchState({ users: [...state.users, res as User], }); } else { console.log('Something went wrong:', res); } }) ); } @Action(DeleteUser) deleteUser({setState,getState}:StateContext<userStateModel>,{id}:DeleteUser){ return this.userService.deleteUser(id).pipe(tap((res:User)=>{ const state = getState(); const filteredEmployees = state.users.filter(user=>user._id !== id) // Getting Data of Remaining Employees setState({ ...state, users:filteredEmployees }) })) } @Action(UpdateUser) updateUser({getState,patchState}:StateContext<userStateModel>,{id,payload}:UpdateUser){ return this.userService.updateUser(id as string,payload).pipe(tap((res)=>{ const state = getState(); const userlist = state.users; const Index = userlist.findIndex(emp => emp._id == id) // using id we can fetch index userlist[Index] = res; patchState({ users:userlist }) })) } }
import random class Carta: def __init__(self, valor, naipe): self.valor = valor self.naipe = naipe def __str__(self): return f"{self.valor} de {self.naipe}" def calcular_valor(self): if self.valor == 'A': return 0 elif self.valor == 'J': return 11 elif self.valor == 'Q': return 12 elif self.valor == 'K': return 13 else: return int(self.valor) class Baralho: def __init__(self): valores = [str(i) for i in range(2,11)] + list('JQKA') naipes = ["espadas", "paus", "ouro", "copas"] self.cartas = [Carta(valor, naipe) for valor in valores for naipe in naipes] def embaralhar(self): random.shuffle(self.cartas) def esta_vazio(self): return len(self.cartas) == 0 def retirar_carta(self): if len(self.cartas) == 0: return None else: return self.cartas.pop() class Jogador: def __init__(self, nome): self.nome = nome self.cartas = [] self.pontuacao = 0 def adicionar_carta(self, carta): self.cartas.append(carta) self.calcular_pontuacao() def calcular_pontuacao(self): self.pontuacao = sum([carta.calcular_valor() for carta in self.cartas]) def mostrar_cartas(self): print("Cartas do jogador", self.nome) for carta in self.cartas: print(carta) def __str__(self): return f"Nome = {self.nome}, Pontuação = {self.pontuacao}" class Partida: def __init__(self, jogadores): assert len(jogadores) > 1 and len(jogadores) <= 4, "Jogo inválido" self.jogadores = jogadores self.baralho = Baralho() self.baralho.embaralhar() def distribuir_cartas(self): while not self.baralho.esta_vazio(): for jogador in self.jogadores: carta_retirada = self.baralho.retirar_carta() if carta_retirada is not None: jogador.adicionar_carta(carta_retirada) def imprimir_ranking(self): self.jogadores.sort(reverse=True, key=lambda j: j.pontuacao) for jogador in self.jogadores: print(jogador) print(f"Jogador vencedor foi {jogadores[0].nome}!!!") pontuacao_vencedora = jogadores[0].pontuacao vencedores = [jogadores[0]] for i in range(1, len(self.jogadores)): if jogadores[i] == pontuacao_vencedora: vencedores.append(jogadores[i]) if len(vencedores) > 1: print("Houve empate entre os jogadores: ") print(vencedores) jogador1 = Jogador("Rodolpho") jogador2 = Jogador("William") jogador3 = Jogador("Diego") jogadores = [jogador1, jogador2, jogador3] partida = Partida(jogadores) partida.distribuir_cartas() partida.imprimir_ranking()
using System; using Develop05; class Program { /*EXCEEDS REQUIREMENTS 1. I added a new type of goal called Expire goal. In this new goal type, the user needs to specify an expiration date and the goal must be completed before that day. If not, the goal is closed 2. I used the factory pattern to recreate the Goals objects based on the data stored in the file */ private enum TypeOfGoals { SimpleGoal = 1, EternalGoal, ChecklistGoal, ExpireGoal } private static List<Goal> _goals = new List<Goal>(); private static Develop05.File _file = new Develop05.File(); private static int _points = 0; static void Main(string[] args) { string option = string.Empty; Console.Clear(); while (option != "6") { Console.WriteLine($"You have {_points} points\n"); Console.WriteLine("Menu Options:\n"); Console.WriteLine("1. Create New Goal"); Console.WriteLine("2. List Goals"); Console.WriteLine("3. Save Goals"); Console.WriteLine("4. Load Goals"); Console.WriteLine("5. Record Event"); Console.WriteLine("6. Quit\n"); Console.Write("Please, select a choice from the menu: "); option = Console.ReadLine(); switch (option) { case "1": CreateGoal(); break; case "2": ListGoals(); break; case "3": SaveGoals(); break; case "4": LoadGoals(); break; case "5": RecordEvent(); break; case "6"://Quit Console.WriteLine("have a good day !!!\n"); break; } } } private static void CreateGoal() { Console.WriteLine("The types of goals are:"); Console.WriteLine("1. Simple Goal"); Console.WriteLine("2. Eternal Goal"); Console.WriteLine("3. Checklist Goal"); Console.WriteLine("4. Expire Goal\n"); Console.Write("Which type of goal would you like to create? "); var typeOfGoal = Enum.Parse(typeof(TypeOfGoals), Console.ReadLine()); if (typeOfGoal.Equals(TypeOfGoals.SimpleGoal)) { SimpleGoal simpleGoal = new SimpleGoal(); simpleGoal.AddGoalData(); _goals.Add(simpleGoal); } else if (typeOfGoal.Equals(TypeOfGoals.EternalGoal)) { EternalGoal eternalGoal = new EternalGoal(); eternalGoal.AddGoalData(); _goals.Add(eternalGoal); } else if (typeOfGoal.Equals(TypeOfGoals.ChecklistGoal)) { ChecklistGoal checklistGoal = new ChecklistGoal(); checklistGoal.AddGoalData(); _goals.Add(checklistGoal); } else if (typeOfGoal.Equals(TypeOfGoals.ExpireGoal)) { ExpireGoal expireGoal = new ExpireGoal(); expireGoal.AddGoalData(); _goals.Add(expireGoal); } Console.Clear(); } private static void ListGoals() { Console.Clear(); Console.WriteLine("The Goals are:"); for (int i = 0; i < _goals.Count; i++) { Console.WriteLine($"{i + 1}. {_goals[i].DisplayFullGoalDescription()}"); } Console.WriteLine(); } private static void SaveGoals() { Console.Write($"What is the file name for the goal file? "); _file.SaveToFile(Console.ReadLine(), _goals, _points); Console.Clear(); } private static void LoadGoals() { Console.Write($"What is the file name for the goal file? "); var data = _file.LoadFromFile(Console.ReadLine()); _points = data.Item1; _goals.Clear(); _goals = data.Item2; Console.Clear(); } private static void RecordEvent() { Console.Clear(); Console.WriteLine("The goals are:"); for (int i = 0; i < _goals.Count; i++) { string completedText = _goals[i].CheckIfCompleted() ? " (already completed or expired)" : ""; Console.WriteLine($"{i + 1}. {_goals[i].GetName()} {completedText}"); } Console.Write("Which goal did you accomplish? "); int goalSelected = int.Parse(Console.ReadLine()); var goal = _goals[goalSelected - 1]; if (goal.CheckIfCompleted()) { Console.WriteLine("\nThis goal is already completed or expired. You need to choose another goal"); } else { _points += goal.RecordEvent(); } Console.WriteLine(); } }
import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_sharing_intent/flutter_sharing_intent.dart'; import 'package:flutter_sharing_intent/model/sharing_file.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', home: Scaffold( appBar: AppBar( title: const Text("Zdieľanie súborov"), ), body: const BottomSheetModal(), ), ); } } class BottomSheetModal extends StatefulWidget { const BottomSheetModal({Key? key}) : super(key: key); @override State<BottomSheetModal> createState() => _BottomSheetModalState(); } class _BottomSheetModalState extends State<BottomSheetModal> { late StreamSubscription _intentDataStreamSubscription; List<SharedFile>? list; List<FileInfo>? fileInfoList = []; @override void initState() { initSharingListener(); super.initState(); } initSharingListener() { // For sharing images coming from outside the app while the app is in the memory _intentDataStreamSubscription = FlutterSharingIntent.instance .getMediaStream() .listen((List<SharedFile> value) { setState(() { list = value; }); for (var file in value) { printFileDetails(file.value ?? ""); } print("Shared: getMediaStream ${value.map((f) => f.value).join(",")}"); }, onError: (err) { print("Shared: getIntentDataStream error: $err"); }); // For sharing images coming from outside the app while the app is closed FlutterSharingIntent.instance .getInitialSharing() .then((List<SharedFile> value) { print( "Shared: getInitialMedia => ${value.map((f) => f.value).join(",")}"); setState(() { list = value; }); for (var file in value) { printFileDetails(file.value ?? ""); } }); } Future<String?> getFileSize(String? filePath) async { try { if (filePath == null) { return null; } File file = File(filePath); int sizeInBytes = await file.length(); if (sizeInBytes > 1000000) { return "${(sizeInBytes / 1000000)} MB"; } else { return "${(sizeInBytes / 1000)} KB"; } } catch (e) { print("Error getting file size: $e"); return null; } } String? getFileName(String? filePath) { if (filePath == null) { return null; } List<String> pathSegments = filePath.split('/'); return pathSegments.isNotEmpty ? pathSegments.last : null; } void printFileDetails(String filePath) async { String fileName = getFileName(filePath) ?? ''; String? fileSize = await getFileSize(filePath); setState(() { fileInfoList = [ ...?fileInfoList, FileInfo(filePath, fileName, fileSize), ]; }); } @override Widget build(BuildContext context) { return Center( child: ElevatedButton( child: const Text('Otvoriť modál'), onPressed: () { showModalBottomSheet( isDismissible: true, isScrollControlled: true, context: context, builder: (BuildContext context) { return _buildBottomSheetContent(context); }, ); }, ), ); } Widget _buildBottomSheetContent(BuildContext context) { return Container( height: MediaQuery.of(context).size.height * 0.9, color: Colors.white, child: Padding( padding: const EdgeInsets.symmetric(vertical: 20), child: Column( children: [ Padding( padding: const EdgeInsets.only(bottom: 10), child: _buildTopRow(), ), const Divider( color: Colors.black, thickness: 1, ), Column( children: [ const SizedBox( height: 14, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 14), child: _buildSection("Workspace", "OP"), ), const Divider( color: Colors.black, thickness: 1, ), const SizedBox(height: 14), Padding( padding: const EdgeInsets.symmetric(horizontal: 14), child: _buildSection("Destination", "..."), ), const Divider( color: Colors.black, thickness: 1, ), Padding( padding: const EdgeInsets.all(14), child: _buildFileSection(), ), ], ), Expanded( child: Align( alignment: Alignment.bottomRight, child: MaterialButton( onPressed: () {}, color: Colors.blue, textColor: Colors.white, padding: const EdgeInsets.all(16), shape: const CircleBorder(), child: const Icon( Icons.arrow_forward_ios, size: 24, ), )), ), ], ), ), ); } Widget _buildTopRow() { return const Row( mainAxisAlignment: MainAxisAlignment.center, children: [ /* IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.close), color: Colors.black, ), */ Text( "Zdieľajte v spokostave", style: TextStyle( color: Colors.black, fontSize: 22, fontWeight: FontWeight.bold, ), ), ], ); } Widget _buildSection(String title, String value) { // Tu bude v spoku použitý náš multiselect return Column( children: [ _buildSectionTitle(title), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( value, style: const TextStyle( color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold, ), ), IconButton( onPressed: () {}, icon: const Icon(Icons.arrow_forward_ios), color: Colors.black, ), ], ), ], ); } Widget _buildSectionTitle(String title) { return Align( alignment: Alignment.centerLeft, child: Text( title, style: const TextStyle( color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold, ), ), ); } Widget _buildFileSection() { // Tu bude názov zdieľaného súboru return Column(children: [ const Align( alignment: Alignment.centerLeft, child: Text( "Názov súboru: ", style: TextStyle( color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold, ), )), const SizedBox( height: 14, ), for (var fileInfo in fileInfoList!) Align( alignment: Alignment.centerLeft, child: Text( '${fileInfo.fileName ?? ''}, ${fileInfo.fileSize ?? ''}', style: const TextStyle(fontSize: 20), )), ]); } @override void dispose() { _intentDataStreamSubscription.cancel(); super.dispose(); } } class FileInfo { final String filePath; final String? fileName; final String? fileSize; FileInfo(this.filePath, this.fileName, this.fileSize); }
# Взаимодействие с кодом Python ## Подключение Python Язык программирования Python обладает большими возможностями, имеет богатый функционал и библиотеки, написание которых на языке Си может занять продолжительное время, особенно это касается сферы машинного обучения. И было бы неплохо просто взять готовую функциональность на Python и инкорпорировать в программу на C. И Python позволяет это сделать, предоставляя такую функциональность, как Embedded Python (встраиваемый Python). То есть мы можем встроить в программу на C интерпретатор Python и выполнять в программе на C код на языке Python. Рассмотрим, как это сделать. Для работы на ОС Windows прежде всего нам нужно узнать путь к установленному интерпретатору Python. Например, в моем случае это путь C:\Users\eugen\AppData\Local\Programs\Python\Python311. Для упрощения работу установим в переменных среды переменную PYTHONHOME. Она должна указывать на путь к каталогу, где установлен Python. Эта переменная будет использоваться для поиска нужных библиотек: Определим файл app.c со следующей программой на языке C: ``` #include <Python.h> int main() { Py_Initialize(); PyRun_SimpleString("print('Hello METANIT.COM')"); Py_Finalize(); return 0; } ``` Прежде всего, чтобы встроить Python в программу, подключаем заголовочный файл Python.h. Этот файл устанавливается вместе с другими файлами интерпретатора Python по умолчанию. Мы его можем найти в папке интерпретатора Python в каталоге include В программе сначала вызываем функцию Py_Initialize(). Эта функция инициализирует интерпретатор Python, таблицу модулей и устанавливает путь к модулям. Чтобы выполнить некоторый код Python, применяется функция PyRun_SimpleString(), в которую передается код Python ``` PyRun_SimpleString("print('Hello METANIT.COM')"); ``` Здесь код Python представляет вывод строки на консоль с помощью функции print() После выполнения кода Python вызываем функцию Py_Finalize(), которая освобождает память, выделенную для интерпретатора Python. Для компиляции в Windows используем компилятор gcc. Выполним команду ``` gcc -Wall -I %PYTHONHOME%\include -L %PYTHONHOME%\libs -o app.exe app.c -lpython311 & app ``` При компиляции с помощью опции -I нам надо передать пусть к заголовочным файлам, а это папка %PYTHONHOME%\include. Чтобы не писать полный путь, заменяем его часть содержимым ранее установленной переменной PYTHONHOME Кроме того, с помощью опции -L надо установить путь к библиотеке python. А это путь %PYTHONHOME%\libs Поскольку в моем случае используется версия python 3.11, то указывается параметр -lpython311 В итоге при выполнении программы будет выполняться код Python, который выведет на консоль строку: ``` c:\C>gcc -Wall -I %PYTHONHOME%\include -L %PYTHONHOME%\libs -o app app.c -lpython311 & app Hello METANIT.COM c:\C> ``` При этом в программе могут быть и другие инструкции на языке C: ``` #include <stdio.h> #include <Python.h> int main() { printf("Python program starts\n"); Py_Initialize(); PyRun_SimpleString("print('Hello METANIT.COM')"); Py_Finalize(); printf("Python program ends\n"); return 0; } ``` Компиляция на Linux несколько отличается. Для компиляции на Ubuntu применяется следующая команда: ``` gcc -Wall $(python3-config --cflags) -o app app.c $(python3-config --embed --ldflags) ``` Подобным образом можно использовать более сложный код Python. В том числе с использованием сторонних библиотек Python. Например, нарисуем произвольный график с помощью библиотек numpy и matplotlib. Соответственно нам надо вначале установить данные библиотеки с помощью пакетного менеджера pip: ``` pip install numpy pip install matplotlib ``` Для создания графика определим на С следующую программу: ``` #include <Python.h> int main() { Py_Initialize(); PyRun_SimpleString( "import numpy as np\n" "import matplotlib.pyplot as plt\n" "x = np.array(range(0, 8))\n" "y = eval('2 * x + 1')\n" "plt.title('y = 2x + 1')\n" "plt.xlabel('x')\n" "plt.ylabel('y')\n" "plt.plot(x,y)\n" "plt.show()"); Py_Finalize(); return 0; } ``` В данном случае сначала подключаем функционал библиотек numpy и matplotlib. ``` import numpy as np import matplotlib.pyplot as plt ``` Далее генерируем значения, которые отображаются по оси X: ``` x = np.array(range(0, 8)) ``` Для генерации применяется функция np.array() библиотеки Numpy, которая создает набор чисел от 0 до 7. Далее по значениям X получаем значения Y по определенной формуле. Здесь мы рисуем график функцииy = 2x + 1. И для вычисления значений Y применяем встроенную функцию eval(), которая есть в языке Python и которая вычисляет произвольное выражение. ``` y = eval('2 * x + 1') ``` Затем устанавливаем заголовок графика ``` plt.title('y = 2x + 1') ``` Устанавливаем текстовые метки для осей X и Y: ``` plt.xlabel('x') plt.ylabel('y') ``` И в конце отрисовываем график и отображаем его на экране: ``` plt.plot(x,y) plt.show() ``` Если инструкций на Python много, то их проще определить в отдельный файл. Затем в программе на языке С этот файл можно выполнить с помощью функции PyRun_SimpleFile(), которая имеет следующее определение: ``` int PyRun_SimpleFile(FILE *fp, const char *filename) ``` В качестве первого параметра передается дескриптор файла, а в качестве второго - имя файла. Например, определим в одной папке с программой файл main.py со следующим кодом на языке Python: ``` print("Hello Python in C") ``` Здесь код просто выводит строку на консоль. В главном файле программы на C (допустим, он называется app.c) выполним этот скрипт Python: ``` #include <Python.h> int main() { char filename[] = "main.py"; Py_Initialize(); FILE* fp = fopen(filename, "rb"); // открываем файл и if(fp) PyRun_SimpleFile(fp, filename); // выполняем программу python Py_Finalize(); return 0; } ``` Здесь сначала открываем файл в бинарном режиме для чтения и получаем указатель на файл с помощью функции fopen(), затем выполняем файл с кодом Python. В итоге консоль должна вывести ``` Hello Python in C
import { useEffect, useState } from "react"; import { Editar } from "./Editar"; export const Listado = ({ listadoState, setListadoState }) => { // const [listadoState, setListadoState] = useState([]); const [editar, setEditar] = useState(0); useEffect(() => { console.log("componentes de listado de peliculas cargado!!"); conseguirPeliculas(); }, []); const conseguirPeliculas = () => { let peliculas = JSON.parse(localStorage.getItem("pelis")); setListadoState(peliculas); return peliculas; }; const borrarPeli = (id) => { // Conseguir peliculas almacenadas const pelis_almacenadas = conseguirPeliculas(); // Filtrar esas peliculas para que elimine del array lo que no quiero let nuevo_array_peli = pelis_almacenadas.filter( (peli) => peli.id !== parseInt(id) ); // Actualizar estado del listado setListadoState(nuevo_array_peli); // Actualizar los datos del localstorage localStorage.setItem("pelis", JSON.stringify(nuevo_array_peli)); }; return ( <> {listadoState != null ? ( listadoState.map((peli) => { return ( <article key={peli.id} className="peli-item"> <h3 className="title">{peli.titulo}</h3> <p className="description">{peli.descripcion}</p> <button className="edit" onClick={() => { setEditar(peli.id); }} > Editar </button> <button className="delete" onClick={() => borrarPeli(peli.id)}> Borrar </button> {/* Aparece un formulario de editar */} {editar === peli.id && ( <> <h1>Formulario</h1> <Editar peli={peli} conseguirPeliculas= {conseguirPeliculas} setEditar={setEditar} setListadoState= {setListadoState} /> </> )} </article> ); }) ) : ( <h2>No hay peliculas para Mostrar</h2> )} </> ); };
import { decodeTyson } from './decode' import { encodeTyson } from './encode' import { AnnaClientConstruct, AnnaDbUri, Decode, InsertType, Query, Result, ScalarVectorMap, } from './types' import zmq from 'zeromq' class AnnaClient { private uri: AnnaDbUri = 'annadb://playground.annadb.dev' private port = 10001 private socket: zmq.Socket | undefined constructor(options: AnnaClientConstruct = {}) { this.uri = options?.uri ?? this.uri this.port = options?.port ?? this.port } public connect = () => { if (this.socket !== undefined) { console.warn(`AnnaClient: socket already connected`) } else { const host = new URL(this.uri).hostname this.socket = zmq.socket('req').connect(`tcp://${host}:${this.port}`) } } public close = () => { if (this.socket === undefined) { return } this.socket?.close() } public queryTySON = async (TySON: string, autoClose = true) => { if (this.socket === undefined) this.connect() // decode Tyson to check for errors in string try { this.decode(TySON) } catch (err) { console.log(`Error decoding Tyson: ${err}`) throw err } if (this.socket === undefined) { throw new Error('No socket open') } this.socket.send(TySON) const res = await new Promise<string>((res, rej) => { let data: string | undefined this.socket?.once('message', (raw: Buffer) => { data = raw.toString() if (autoClose) this.socket?.close() res(data as string) }) this.socket?.on('error', (err) => { this.socket?.close() rej(err) }) }) return res } public query = async < I extends InsertType = InsertType, R extends ScalarVectorMap = ScalarVectorMap >( query: Query<I> ) => { const TySON = encodeTyson(query) const res = await this.queryTySON(TySON) let decoded = this.decode(res) if (!Array.isArray(decoded)) decoded = [decoded] return decoded as Result<R>[] } public decode: Decode = (tyson) => { const [rTyson, res] = decodeTyson(tyson) if (rTyson.length > 0) throw new Error( `TySON result was not fully parsed. Remaining TySON: ${rTyson}` ) return res } public encode = encodeTyson } export default AnnaClient
# 角度性能:与维修工人一起预加工 > 原文:<https://dev.to/angular/angular-performance-precaching-with-the-service-worker-4lg5> *本帖最初发布于[https://justir . com/blog/2019/08/ng perf-pre caching-service worker](https://juristr.com/blog/2019/08/ngperf-precaching-serviceworker)。前往[juristr.com/blog](https://juristr.com/blog)了解更多内容* * * * 这篇文章是我的“Angular Performance Week”系列的一部分,在这个系列中,我每天都会发布一个新的视频,该视频基于《今日 web.dev/angular.》上的性能文章。我们正在深入研究服务工人 API,具体来说就是利用 Angular 的集成服务工人包。 > 注:这篇文章和所附的书呆子视频课是基于[明科·格切夫](https://twitter.com/mgechev)和[斯蒂芬·弗鲁恩](https://twitter.com/stephenfluin)关于[web.dev/angular](https://web.dev/angular)的文章。完全归功于他们👍 ## 角度性能系列 1. [路由级代码拆分](https://juristr.com/blog/2019/08/ngperf-route-level-code-splitting/) 2. [预载角度懒惰路线](https://juristr.com/blog/2019/08/ngperf-preloading-lazy-routes) 3. [使用 Angular CLI 的性能预算](https://juristr.com/blog/2019/08/ngperf-setting-performance-budgets) 4. [优化角度变化检测](https://juristr.com/blog/2019/08/ngperf-optimize-change-detection) 5. [使用 CDK 虚拟滚动大列表](https://juristr.com/blog/2019/08/ngperf-virtual-scrolling-cdk) 6. **与角度维修工人一起进行预加工** 订阅我的简讯,不要错过其他视频[。](https://juristr.com/newsletter) ## 用 Angular 的服务工作者包缓存 为了进一步加快我们的应用程序,并在不稳定的网络条件下提供更愉快的体验,我们可能希望使用一个允许我们应用预缓存机制的服务人员。幸运的是,Angular 团队已经提供了一个与框架很好集成的服务工作者模块。让我们看看如何将它应用到我们的应用程序中。 [https://www.youtube.com/embed/2-SoCdPo4l8](https://www.youtube.com/embed/2-SoCdPo4l8) ### 原创 web.dev 文章 想阅读 web.dev 的原始文章吗?点击这里查看!。
"use client"; import { FooterCatch, GradOutline } from "../components"; import { PageWrapper } from "../components"; import { motion } from "framer-motion"; interface MessageBoxProps { message: string; blind: string; index: number; } function MessageBox({ message, blind, index }: MessageBoxProps) { const getFlexPos = () => { if (index % 2 == 0) return "self-start"; else return "self-end"; }; return ( <motion.div initial={{ opacity: 0, x: 100 }} animate={{ opacity: 1, x: 0, transition: { delay: 0.1 } }} exit={{ opacity: 0, x: 100 }} className={`max-w-2xl select-none ${getFlexPos()} z-30 p-6 rounded-lg group gsmContainerLight dark:gsmContainerDark hover:ring-1`} > <GradOutline /> <div className="relative z-20 flex flex-col gap-4"> <p>{message}</p> <p className="ml-auto text-xs text-gray-800 dark:text-gray-400"> {blind} </p> </div> </motion.div> ); } const Messages = [ { message: "I'm a final year Data Science student at Mar Athanasius College of Engineering Kothamangalam tredding my way through course work while also dipping my toes in any technology I can find.", blind: "Sometimes you just wish you had a lot less classes", }, { message: "I've been building web apps for around a year and would love to keep on building cooler and much more use web applications.", blind: "It's certainly been a fun ride", }, { message: "I'm on the lookout for amazing opportunities to build freelance projects and also gain exposure through internships.", blind: "Opportunities here I come", }, ]; export default function About() { return ( <PageWrapper> <div className="flex flex-col gap-8"> {Messages.map((content, index) => ( <MessageBox key={index} message={content.message} blind={content.blind} index={index} /> ))} <FooterCatch blind="I'm also super into conversation that make me go whaaa- 😲" /> </div> </PageWrapper> ); }
import numpy as np import json import Fatiga import Secciones import Concentracion_Tensiones import time # st = time.time() ############################################################################################ #Aclaraciones: #Shaft = Arbol #Axle = eje #En general los ejes se realizan de aceros con bajo carbono, SAE 1020 a 1050 # Cuando los efectos de la resistencia resultand dominar la deflexiones se debe eligir un material de mayor resistencia, lo que permite # reducir los tamaños del eje hasta que la deflexion resulte problematica. #Cuando es necesario tratamientos termicos o aceros aleados las opciones comunes son las siguientes: 1340/50 3140/50 4140 5140 8650 #Ejes deformados en frio [cold drawn] se usan comunmnente para diametros menores a 3" = 76 mm #En general es mejor aplicar la carga en el eje en el espacio entre los rodamientos y no cargas en voladizo fuera de los rodamientos #Solo dos rodamientos debe ser usado en la mayoria de los casos, salvo casos de ejes muy largos(tener en cuenta la alineacion de los rodamientos con cuidado) #Por medio del analisis de Von Misses podemos combinar las diferentes tensiones, de flexion y torsion #Saf = Sigma a flexion = Tension alterna de flexion #Smf = Sigma m flexion = Tension media de flexion #Tat = Tao a Torsion = Tension alterna de torsion #Tmt = Tao m Torsion = Tension media de torsion ########################################################################################### #Parametros del problema (Ejemplo 7-1 pag 370) d = 27.94 #Diametro menor [mm] Diametro_mayor = 41.91 #Diametro mayor [mm] r = 2.794 #Radio de empalme [mm] Ma = 22.5010 #Momento alterno de flexion [kg.mm] Mm = 0 #Momento medio de flexion [kg.mm] Ta = 0 #Torsion alterna [kg.mm] Tm = 19.6437 #Torsion media [kg.mm] n = 1 #Coeficiente de seguridad #################################################################################################### #Variables del material with open("materialesSAE.json", "r") as file: materialesSAE = json.load(file) material_name = "Ejemplo" Su = materialesSAE[material_name]["Su"] #Tension ultima Sy = materialesSAE[material_name]["Sy"] #Tension de fluencia Se = Fatiga.tension_fatiga(Su, True, d) #Tension limite de fatiga ##################################################################################################### #Concentracion de tensiones kt, _ = Concentracion_Tensiones.factores_teoricos(1, Diametro_mayor, d, r) #Factor de concentracion de tensiones teorico a flexion _, kts = Concentracion_Tensiones.factores_teoricos(1, Diametro_mayor, d, r) #Factor de concentracion de tensiones teorico a torsion q, _ = Concentracion_Tensiones.sensibilidad_entalla(r, Su) #Sensibilidad a la entalla a flexion/axial _, qs = Concentracion_Tensiones.sensibilidad_entalla(r, Su) #Sensibilidad a la entall a torsion kf, _ = Concentracion_Tensiones.factor_concentracion_tensiones(kt, kts, q, qs) #Factor de concentracion de tensiones a flexion _ , kfs = Concentracion_Tensiones.factor_concentracion_tensiones(kt, kts, q, qs) #Factor de concentracion de tensiones a torsion c = d/2 #Distancia a la fibra superior (en un circulo es el radio) [mm] _ ,I, _ = Secciones.Circle(d) #Momento de inercia 2 orden respecto al eje de flexion, generalmente z [kg.mm4] _, _, J = Secciones.Circle(d) #Momento de inercia 2 orden o polar respecto al eje de torsion, generalmente x [kg.mm4] ######################################################################################################## #Calculo de tensiones actuantes saf_g = kf * (Ma * c / I ) smf_g = kf * (Mm * c / I ) tat_g = kfs * (Ta * c / J) tmt_g = kfs * (Tm * c / J) ###################################################################################################### #Composicion de tensiones sa = ((saf_g**2) + (3 * (tat_g**2)))**(1/2) #Sigma alterno sm = ((smf_g**2) + (3 * (tmt_g**2)))**(1/2) #Sigma medio ########################################################################################################### #Para utilizar las ecuaciones directamente del libro se deben transformar los valores de kg/mm2 a Kpsi, a cada variable anteriormente calculado se lo redefine agregando un 2 d2 = d / 25.4 Se2 = Se * 1.42334 * 1000 Su2 = Su * 1.42334 * 1000 Sy2 = Sy * 1.42334 * 1000 Mm2 = Mm * 55.9974 Ma2 = Ma * 55.9974 Tm2 = Tm * 55.9974 Ta2 = Ta * 55.9974 #Metodo de calculo por Goodman d_goodman = 25.4 * ((((16*n) / np.pi) * ((1/Se2) * (((4 * ((kf * Ma2)**2)) + (3 * ((kfs * Ta2)**2)))**(1/2)) + (1/Su2) * (((4 * ((kf * Mm2)**2)) + (3 * ((kfs * Tm2)**2)))**(1/2))))**(1/3)) #[mm] n_goodman = 1 / ((16/(np.pi * (d2**3))) * (((1/Se2) * (((4 * ((kf * Ma2)**2)) + (3 * ((kfs * Ta2)**2)))**(1/2))) + ((1 / Su2) * (((4 * ((kf * Mm2)**2))+(3 * ((kfs * Tm2)**2)))**(1/2))))) #Metodo de calculo por Gerber A = ((4 * ((kf*Ma2)**2)) + (3 * ((kfs * Ta2)**2)))**(1/2) B = ((4 * ((kf*Mm2)**2)) + (3 * ((kfs * Tm2)**2)))**(1/2) d_gerber = 25.4 * ((((8 * n * A) / (np.pi * Se2)) * (1 + ((1 + (((2 * B * Se2) / (A * Su2))**2))**(1/2))))**(1/3)) # [mm] n_gerber = 1 / (((8 * A) / (np.pi * (d2**3) * Se2)) * (1 + ((1 + (((2 * B * Se2)/(A * Su2))**2))**(1/2)))) #Metodo de calculo ASME-Elliptic d_ASME = 25.4 * ((((16*n)/np.pi) * (((4*(((kf*Ma2) / Se2)**2)) + (3 * (((kfs * Ta2) / Se2)**2)) + (4 * (((kf*Mm2) / Sy2)**2)) + (3 * (((kfs * Tm2) / Sy2)**2)))**(1/2)))**(1/3)) # [mm] n_ASME = 1 / ((16 / (np.pi * (d2**3))) * (((4 * (((kf*Ma2) / Se2)**2)) + (3 * (((kfs * Ta2) / Se2)**2)) + (4 * (((kf * Mm2) / Sy2)**2)) + (3 * (((kfs * Tm2) / Sy2)**2)))**(1/2))) #Metodo de calculo Soderberg d_soderberg = 25.4 * (((16 * n / np.pi) * (((1/Se2) * (((4 * ((kf*Ma2)**2)) + (3 * ((kfs * Ta2)**2)))**(1/2))) + ((1/Sy2) * (((4 * ((kf*Mm2)**2)) + (3 * ((kfs * Tm2)**2)))**(1/2)))))**(1/3)) # [mm] n_soderberg = 1 / ((16 / (np.pi * (d2**3))) * (((1/Se2) * (((4 * ((kf*Ma2)**2)) + (3 * ((kfs * Ta2)**2)))**(1/2))) + ((1/Sy2) * (((4 * ((kf*Mm2)**2)) + (3 * ((kfs * Tm2)**2)))**(1/2))))) #Calculo de tension maxima S_max = (((((32 * kf * (Mm2 + Ma2))/(np.pi * (d2**3)))**2) + (3 * (((16 * kfs * (Ta2 + Tm2))/(np.pi * (d2**3)))**2)))**(1/2)) * 0.000703069 #Tension maxima generada al primer ciclo de carga n_y = Sy / S_max #Coeficiente de seguridad de tension maxima de fluencia def calcular_ejes(): print("Calculo de ejes") print("Parametros del problema: \n","Diametro Menor: ", d, " mm \n", "Diametro Mayor: ", Diametro_mayor, " mm \n","Radio de empalme: ", r, " mm\n" ) print("Caracteristicas del material: \n", "Su: ", Su, round(Su2,3), " kg/mm2 (kpsi)\n", "Sy: ", Sy, round(Sy2,3), " kg/mm2 (kpsi)\n", "Se: ", round(Se, 3), round(Se2, 3), " kg/mm2 (kpsi)\n", sep=" ") print("Cocnentracion de tensiones: \n", "kt y kts: ", kt, kts, sep=" ") print("\n q y qs: ", round(q, 3), round(qs, 3), sep=" ") print("\n kf y kfs: ", round(kf, 3), round(kfs, 3), sep=" ") # print("\n Diametro minimo por Goodman: ", round(d_goodman, 3)) # print("\n Coeficiente de seguridad por Goodman: ", round(n_goodman, 2)) # print("\n Diametro minimo por Gerber: ", round(d_gerber, 3)) # print("\n Coeficiente de seguridad por Gerber: ", round(n_gerber, 2)) # print("\n Diametro minimo por ASME: ", round(d_ASME, 3)) # print("\n Coeficiente de seguridad por ASME: ", round(n_ASME, 2)) # print("\n Diametro minimo por Soderber: ", round(d_soderberg, 3)) # print("\n Coeficiente de seguridad por Soderberg: ", round(n_soderberg, 2)) # print("\n Tension maxima al primer ciclo: ", round(S_max, 3),round(S_max * 1.42334, 3), "kg/mm2 (kpsi)", sep=" ") # print("\n Coeficiente de seguridad de maxima carga: ", round(n_y, 2)) # # et = time.time() # ft = et - st # print("Medicion de tiempo: {:.4f} segundos".format(ft) )
<?php declare(strict_types=1); /** * * This file is part of the FinalWorkSystem project. * (c) Vladimir Danilov * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace Application\EventDispatcher; use App\Application\EventDispatcher\EntityEventDispatcherService; use App\Application\EventDispatcher\GenericEvent\EntityPostFlushGenericEvent; use App\Application\EventSubscriber\Events; use Danilovl\AsyncBundle\Service\AsyncService; use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class EntityEventDispatcherServiceTest extends TestCase { private readonly EventDispatcherInterface $eventDispatcher; private readonly AsyncService $asyncService; private readonly EntityEventDispatcherService $entityEventDispatcherService; protected function setUp(): void { $this->eventDispatcher = $this->createMock(EventDispatcherInterface::class); $this->asyncService = new AsyncService; $this->entityEventDispatcherService = new EntityEventDispatcherService($this->eventDispatcher, $this->asyncService); } public function testOnResetPasswordTokenCreate(): void { $this->eventDispatcher->expects($this->once()) ->method('dispatch') ->with( $this->isInstanceOf(EntityPostFlushGenericEvent::class), Events::ENTITY_POST_PERSIST_FLUSH ); $this->entityEventDispatcherService->onPostPersistFlush(new class {}); $this->asyncService->call(); } }
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const express_1 = __importDefault(require("express")); const body_parser_1 = __importDefault(require("body-parser")); const uuid_1 = require("uuid"); const cors_1 = __importDefault(require("cors")); const app = (0, express_1.default)(); const port = 8080; // default port to listen app.use(body_parser_1.default.urlencoded({ extended: false })); app.use(body_parser_1.default.json()); app.use((0, cors_1.default)()); const posts = [{ id: (0, uuid_1.v4)(), title: 'hi im a title', date: new Date(), content: 'hi im content', user: 1, }]; const users = [ { id: 0, name: 'Donkey Kong', }, { id: 1, name: 'Diddy Kong' } ]; const findPost = (id) => posts.filter(currentPost => currentPost.id === id); app.get('/posts', (req, res) => { return res.status(200).send(posts); }); app.get('/post/:id', (req, res) => { const { id } = req.params; const foundPost = findPost(id); return res.status(200).send({ post: foundPost }); }); app.post('/posts', (req, res) => { const { title, content, user } = req.body; const newPost = { id: (0, uuid_1.v4)(), title, content, user, date: new Date() }; setTimeout(() => { posts.push(newPost); }, 1000); return res.status(202).end(); }); app.get('/users', (req, res) => { return res.status(200).json(users); }); // start the Express server app.listen(port, () => { // console.log( `server started at http://localhost:${ port }` ); }); //# sourceMappingURL=index.js.map
import { AppRouterContextProviderMock } from '@/__mocks__/useRouter'; import '@testing-library/jest-dom'; import { render } from '@testing-library/react'; import PokeCards from '../app/(pokemon-list)/_components/PokeCards'; Object.defineProperty(window, 'matchMedia', { writable: true, value: jest.fn().mockImplementation(query => ({ matches: true, media: query, onchange: null, addListener: jest.fn(), removeListener: jest.fn(), addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(), })), }); describe('PokeCards', () => { it('renders pokemon cards', () => { const push = jest.fn(); const { getByTestId, getAllByTestId } = render( <AppRouterContextProviderMock router={{ push }}> <PokeCards data={mockData} /> </AppRouterContextProviderMock> ) const container = getByTestId('poke-cards-container') const card = getAllByTestId('poke-card') expect(container).toBeInTheDocument() expect(card[0]).toBeInTheDocument() }) }) const mockData = { "pokemon_v2_evolutionchain": [ { "id": 1, "pokemon_v2_pokemonspecies": [ { "id": 1, "order": 1, "pokemon_v2_pokemons": [ { "id": 1, "name": "bulbasaur", "pokemon_species_id": 1, "pokemon_v2_pokemontypes": [ { "pokemon_v2_type": { "name": "grass", "id": 12 } }, { "pokemon_v2_type": { "name": "poison", "id": 4 } } ], "pokemon_v2_pokemonsprites": [ { "sprites": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/1.svg" } ], "pokemon_v2_pokemonspecy": { "pokemon_v2_pokemoncolor": { "id": 5, "name": "green" } } } ] }, { "id": 2, "order": 2, "pokemon_v2_pokemons": [ { "id": 2, "name": "ivysaur", "pokemon_species_id": 2, "pokemon_v2_pokemontypes": [ { "pokemon_v2_type": { "name": "grass", "id": 12 } }, { "pokemon_v2_type": { "name": "poison", "id": 4 } } ], "pokemon_v2_pokemonsprites": [ { "sprites": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/2.svg" } ], "pokemon_v2_pokemonspecy": { "pokemon_v2_pokemoncolor": { "id": 5, "name": "green" } } } ] }, { "id": 3, "order": 3, "pokemon_v2_pokemons": [ { "id": 3, "name": "venusaur", "pokemon_species_id": 3, "pokemon_v2_pokemontypes": [ { "pokemon_v2_type": { "name": "grass", "id": 12 } }, { "pokemon_v2_type": { "name": "poison", "id": 4 } } ], "pokemon_v2_pokemonsprites": [ { "sprites": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/3.svg" } ], "pokemon_v2_pokemonspecy": { "pokemon_v2_pokemoncolor": { "id": 5, "name": "green" } } }, { "id": 10033, "name": "venusaur-mega", "pokemon_species_id": 3, "pokemon_v2_pokemontypes": [ { "pokemon_v2_type": { "name": "grass", "id": 12 } }, { "pokemon_v2_type": { "name": "poison", "id": 4 } } ], "pokemon_v2_pokemonsprites": [ { "sprites": null } ], "pokemon_v2_pokemonspecy": { "pokemon_v2_pokemoncolor": { "id": 5, "name": "green" } } }, { "id": 10195, "name": "venusaur-gmax", "pokemon_species_id": 3, "pokemon_v2_pokemontypes": [ { "pokemon_v2_type": { "name": "grass", "id": 12 } }, { "pokemon_v2_type": { "name": "poison", "id": 4 } } ], "pokemon_v2_pokemonsprites": [ { "sprites": null } ], "pokemon_v2_pokemonspecy": { "pokemon_v2_pokemoncolor": { "id": 5, "name": "green" } } } ] } ] } ] }
//package com.example.demo.api.user; // // //import com.example.demo.CommonOperations; //import com.example.demo.api.user.request.ChangePasswordRequest; //import com.example.demo.api.user.request.ForgotPasswordDto; //import com.ninja_squad.dbsetup.DbSetup; //import com.ninja_squad.dbsetup.DbSetupTracker; //import com.ninja_squad.dbsetup.destination.DataSourceDestination; //import com.ninja_squad.dbsetup.destination.Destination; //import com.ninja_squad.dbsetup.operation.Operation; //import org.junit.jupiter.api.BeforeEach; //import org.junit.jupiter.api.DisplayName; //import org.junit.jupiter.api.Test; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; //import org.springframework.boot.test.context.SpringBootTest; //import org.springframework.http.MediaType; //import org.springframework.test.web.servlet.MockMvc; //import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; // //import javax.sql.DataSource; //import java.time.LocalDateTime; // //import static com.example.demo.CommonOperations.asJsonString; //import static com.ninja_squad.dbsetup.Operations.insertInto; //import static com.ninja_squad.dbsetup.Operations.sequenceOf; //import static org.hamcrest.CoreMatchers.is; //import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; //import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; // //@AutoConfigureMockMvc //@SpringBootTest //public class UserControllerTest { // private static DbSetupTracker dbSetupTracker = new DbSetupTracker(); // @Autowired // MockMvc mockMvc; // @Autowired // DataSource dataSource; // @BeforeEach // void prepare(){ // final Operation insertRole = // insertInto("tbl_role") // .row() // .column("id", 1) // .column("role_name", "ROLE_USER") // .end() // // // .build(); // // final Operation insertUser = // insertInto("tbl_user") // .row() // .column("id", 1) // .column("avatar", "") // .column("email", "test1@gmail.com") // .column("is_active", 1) // .column("name", "test1") // .column("password", "$2a$10$g2LNKcrRhx6aKDp1OELyVeITVsfYe5msrBT1jiVtDPaiAOhanDEuq") // .column("username", "test1") // .end() // // .build(); // // final Operation insertUserRole = // insertInto("tbl_user_role") // .row() // .column("user_id", 1) // .column("role_id", 1) // .end().build(); // final Operation insertConfirmationToken = // insertInto("tbl_confirmation_token") // .row() // .column("id", 1) // .column("user_id", 1) // .column("created_date", LocalDateTime.now()) // .column("expire_date", LocalDateTime.now().plusMinutes(15)) // .column("token", "testtoken") // .end().build(); // Operation operation = sequenceOf( // CommonOperations.DELETE_ALL, // insertRole, // insertUser, // insertUserRole, // insertConfirmationToken // ); // Destination dest = new DataSourceDestination(dataSource); // DbSetup dbSetup = new DbSetup(dest, operation); // dbSetupTracker.launchIfNecessary(dbSetup); // } // // @Test // @DisplayName("Get Email: CASE 1: username valid") // void getEmailWithUsernameCase1() throws Exception { // // ForgotPasswordDto forgotPasswordDto = ForgotPasswordDto.builder() // .usernameOrEmail("test1") // .build(); // // mockMvc.perform(MockMvcRequestBuilders.post("/api/user/forgot-password") // .content(asJsonString(forgotPasswordDto)) // .contentType(MediaType.APPLICATION_JSON) // .accept(MediaType.APPLICATION_JSON)) // .andExpect(status().isOk()) // .andExpect(jsonPath("$.email", is("test1@gmail.com"))); // } // @Test // @DisplayName("Get Email: CASE 2: username invalid") // void getEmailWithUsernameCase2() throws Exception { // // ForgotPasswordDto forgotPasswordDto = ForgotPasswordDto.builder() // .usernameOrEmail("invalidTest1") // .build(); // // mockMvc.perform(MockMvcRequestBuilders.post("/api/user/forgot-password") // .content(asJsonString(forgotPasswordDto)) // .contentType(MediaType.APPLICATION_JSON) // .accept(MediaType.APPLICATION_JSON)) // .andExpect(status().isBadRequest()); // } // // @Test // @DisplayName("Get User from Token: CASE 1: token valid") // void getUserFromTokenCase1() throws Exception { // // mockMvc.perform(MockMvcRequestBuilders.get("/api/user/forgot-password") // .param("token", "testtoken") // .contentType(MediaType.APPLICATION_JSON) // .accept(MediaType.APPLICATION_JSON)) // .andExpect(status().isOk()) // .andExpect(jsonPath("$.username", is("test1"))); // } // @Test // @DisplayName("Get User from Token: CASE 2: token invalid") // void getUserFromTokenCase2() throws Exception { // // mockMvc.perform(MockMvcRequestBuilders.get("/api/user/forgot-password") // .param("token", "invalidtesttoken") // .contentType(MediaType.APPLICATION_JSON) // .accept(MediaType.APPLICATION_JSON)) // .andExpect(status().isBadRequest()); // } // @Test // @DisplayName("Change password (Forgot Password): CASE 1: Username Password Token valid") // void changePasswordCase1() throws Exception { // ChangePasswordRequest changePasswordRequest = ChangePasswordRequest.builder() // .usernameOrEmail("test1") // .password("newTest1") // .token("testtoken") // .build(); // mockMvc.perform(MockMvcRequestBuilders.post("/api/user/change-password") // .content(asJsonString(changePasswordRequest)) // .contentType(MediaType.APPLICATION_JSON) // .accept(MediaType.APPLICATION_JSON)) // .andExpect(status().isOk()); // } // @Test // @DisplayName("Change password (Forgot Password): CASE 2: Username Password Token invalid") // void changePasswordCase2() throws Exception { // ChangePasswordRequest changePasswordRequest = ChangePasswordRequest.builder() // .usernameOrEmail("invalidtest1") // .password("newTest1") // .token("invalidtesttoken") // .build(); // mockMvc.perform(MockMvcRequestBuilders.post("/api/user/change-password") // .content(asJsonString(changePasswordRequest)) // .contentType(MediaType.APPLICATION_JSON) // .accept(MediaType.APPLICATION_JSON)) // .andExpect(status().isBadRequest()); // } // @Test // @DisplayName("Change password (Forgot Password): CASE 3: Username invalid, Password Token valid") // void changePasswordCase3() throws Exception { // ChangePasswordRequest changePasswordRequest = ChangePasswordRequest.builder() // .usernameOrEmail("invalidtest1") // .password("newTest1") // .token("testtoken") // .build(); // mockMvc.perform(MockMvcRequestBuilders.post("/api/user/change-password") // .content(asJsonString(changePasswordRequest)) // .contentType(MediaType.APPLICATION_JSON) // .accept(MediaType.APPLICATION_JSON)) // .andExpect(status().isBadRequest()); // } //}
// SPDX-License-Identifier: GPL-2.0-only /* * PS3 flash memory os area. * * Copyright (C) 2006 Sony Computer Entertainment Inc. * Copyright 2006 Sony Corp. */ #include <linux/kernel.h> #include <linux/io.h> #include <linux/workqueue.h> #include <linux/fs.h> #include <linux/syscalls.h> #include <linux/export.h> #include <linux/ctype.h> #include <linux/memblock.h> #include <linux/of.h> #include <linux/slab.h> #include <asm/prom.h> #include "platform.h" enum { OS_AREA_SEGMENT_SIZE = 0X200, }; enum os_area_ldr_format { HEADER_LDR_FORMAT_RAW = 0, HEADER_LDR_FORMAT_GZIP = 1, }; #define OS_AREA_HEADER_MAGIC_NUM "cell_ext_os_area" /** * struct os_area_header - os area header segment. * @magic_num: Always 'cell_ext_os_area'. * @hdr_version: Header format version number. * @db_area_offset: Starting segment number of other os database area. * @ldr_area_offset: Starting segment number of bootloader image area. * @ldr_format: HEADER_LDR_FORMAT flag. * @ldr_size: Size of bootloader image in bytes. * * Note that the docs refer to area offsets. These are offsets in units of * segments from the start of the os area (top of the header). These are * better thought of as segment numbers. The os area of the os area is * reserved for the os image. */ struct os_area_header { u8 magic_num[16]; u32 hdr_version; u32 db_area_offset; u32 ldr_area_offset; u32 _reserved_1; u32 ldr_format; u32 ldr_size; u32 _reserved_2[6]; }; enum os_area_boot_flag { PARAM_BOOT_FLAG_GAME_OS = 0, PARAM_BOOT_FLAG_OTHER_OS = 1, }; enum os_area_ctrl_button { PARAM_CTRL_BUTTON_O_IS_YES = 0, PARAM_CTRL_BUTTON_X_IS_YES = 1, }; /** * struct os_area_params - os area params segment. * @boot_flag: User preference of operating system, PARAM_BOOT_FLAG flag. * @num_params: Number of params in this (params) segment. * @rtc_diff: Difference in seconds between 1970 and the ps3 rtc value. * @av_multi_out: User preference of AV output, PARAM_AV_MULTI_OUT flag. * @ctrl_button: User preference of controller button config, PARAM_CTRL_BUTTON * flag. * @static_ip_addr: User preference of static IP address. * @network_mask: User preference of static network mask. * @default_gateway: User preference of static default gateway. * @dns_primary: User preference of static primary dns server. * @dns_secondary: User preference of static secondary dns server. * * The ps3 rtc maintains a read-only value that approximates seconds since * 2000-01-01 00:00:00 UTC. * * User preference of zero for static_ip_addr means use dhcp. */ struct os_area_params { u32 boot_flag; u32 _reserved_1[3]; u32 num_params; u32 _reserved_2[3]; /* param 0 */ s64 rtc_diff; u8 av_multi_out; u8 ctrl_button; u8 _reserved_3[6]; /* param 1 */ u8 static_ip_addr[4]; u8 network_mask[4]; u8 default_gateway[4]; u8 _reserved_4[4]; /* param 2 */ u8 dns_primary[4]; u8 dns_secondary[4]; u8 _reserved_5[8]; }; #define OS_AREA_DB_MAGIC_NUM "-db-" /** * struct os_area_db - Shared flash memory database. * @magic_num: Always '-db-'. * @version: os_area_db format version number. * @index_64: byte offset of the database id index for 64 bit variables. * @count_64: number of usable 64 bit index entries * @index_32: byte offset of the database id index for 32 bit variables. * @count_32: number of usable 32 bit index entries * @index_16: byte offset of the database id index for 16 bit variables. * @count_16: number of usable 16 bit index entries * * Flash rom storage for exclusive use by guests running in the other os lpar. * The current system configuration allocates 1K (two segments) for other os * use. */ struct os_area_db { u8 magic_num[4]; u16 version; u16 _reserved_1; u16 index_64; u16 count_64; u16 index_32; u16 count_32; u16 index_16; u16 count_16; u32 _reserved_2; u8 _db_data[1000]; }; /** * enum os_area_db_owner - Data owners. */ enum os_area_db_owner { OS_AREA_DB_OWNER_ANY = -1, OS_AREA_DB_OWNER_NONE = 0, OS_AREA_DB_OWNER_PROTOTYPE = 1, OS_AREA_DB_OWNER_LINUX = 2, OS_AREA_DB_OWNER_PETITBOOT = 3, OS_AREA_DB_OWNER_MAX = 32, }; enum os_area_db_key { OS_AREA_DB_KEY_ANY = -1, OS_AREA_DB_KEY_NONE = 0, OS_AREA_DB_KEY_RTC_DIFF = 1, OS_AREA_DB_KEY_VIDEO_MODE = 2, OS_AREA_DB_KEY_MAX = 8, }; struct os_area_db_id { int owner; int key; }; static const struct os_area_db_id os_area_db_id_empty = { .owner = OS_AREA_DB_OWNER_NONE, .key = OS_AREA_DB_KEY_NONE }; static const struct os_area_db_id os_area_db_id_any = { .owner = OS_AREA_DB_OWNER_ANY, .key = OS_AREA_DB_KEY_ANY }; static const struct os_area_db_id os_area_db_id_rtc_diff = { .owner = OS_AREA_DB_OWNER_LINUX, .key = OS_AREA_DB_KEY_RTC_DIFF }; #define SECONDS_FROM_1970_TO_2000 946684800LL /** * struct saved_params - Static working copies of data from the PS3 'os area'. * * The order of preference we use for the rtc_diff source: * 1) The database value. * 2) The game os value. * 3) The number of seconds from 1970 to 2000. */ static struct saved_params { unsigned int valid; s64 rtc_diff; unsigned int av_multi_out; } saved_params; static struct property property_rtc_diff = { .name = "linux,rtc_diff", .length = sizeof(saved_params.rtc_diff), .value = &saved_params.rtc_diff, }; static struct property property_av_multi_out = { .name = "linux,av_multi_out", .length = sizeof(saved_params.av_multi_out), .value = &saved_params.av_multi_out, }; static DEFINE_MUTEX(os_area_flash_mutex); static const struct ps3_os_area_flash_ops *os_area_flash_ops; void ps3_os_area_flash_register(const struct ps3_os_area_flash_ops *ops) { mutex_lock(&os_area_flash_mutex); os_area_flash_ops = ops; mutex_unlock(&os_area_flash_mutex); } EXPORT_SYMBOL_GPL(ps3_os_area_flash_register); static ssize_t os_area_flash_read(void *buf, size_t count, loff_t pos) { ssize_t res = -ENODEV; mutex_lock(&os_area_flash_mutex); if (os_area_flash_ops) res = os_area_flash_ops->read(buf, count, pos); mutex_unlock(&os_area_flash_mutex); return res; } static ssize_t os_area_flash_write(const void *buf, size_t count, loff_t pos) { ssize_t res = -ENODEV; mutex_lock(&os_area_flash_mutex); if (os_area_flash_ops) res = os_area_flash_ops->write(buf, count, pos); mutex_unlock(&os_area_flash_mutex); return res; } /** * os_area_set_property - Add or overwrite a saved_params value to the device tree. * * Overwrites an existing property. */ static void os_area_set_property(struct device_node *node, struct property *prop) { int result; struct property *tmp = of_find_property(node, prop->name, NULL); if (tmp) { pr_debug("%s:%d found %s\n", __func__, __LINE__, prop->name); of_remove_property(node, tmp); } result = of_add_property(node, prop); if (result) pr_debug("%s:%d of_set_property failed\n", __func__, __LINE__); } /** * os_area_get_property - Get a saved_params value from the device tree. * */ static void __init os_area_get_property(struct device_node *node, struct property *prop) { const struct property *tmp = of_find_property(node, prop->name, NULL); if (tmp) { BUG_ON(prop->length != tmp->length); memcpy(prop->value, tmp->value, prop->length); } else pr_debug("%s:%d not found %s\n", __func__, __LINE__, prop->name); } static void dump_field(char *s, const u8 *field, int size_of_field) { #if defined(DEBUG) int i; for (i = 0; i < size_of_field; i++) s[i] = isprint(field[i]) ? field[i] : '.'; s[i] = 0; #endif } #define dump_header(_a) _dump_header(_a, __func__, __LINE__) static void _dump_header(const struct os_area_header *h, const char *func, int line) { char str[sizeof(h->magic_num) + 1]; dump_field(str, h->magic_num, sizeof(h->magic_num)); pr_debug("%s:%d: h.magic_num: '%s'\n", func, line, str); pr_debug("%s:%d: h.hdr_version: %u\n", func, line, h->hdr_version); pr_debug("%s:%d: h.db_area_offset: %u\n", func, line, h->db_area_offset); pr_debug("%s:%d: h.ldr_area_offset: %u\n", func, line, h->ldr_area_offset); pr_debug("%s:%d: h.ldr_format: %u\n", func, line, h->ldr_format); pr_debug("%s:%d: h.ldr_size: %xh\n", func, line, h->ldr_size); } #define dump_params(_a) _dump_params(_a, __func__, __LINE__) static void _dump_params(const struct os_area_params *p, const char *func, int line) { pr_debug("%s:%d: p.boot_flag: %u\n", func, line, p->boot_flag); pr_debug("%s:%d: p.num_params: %u\n", func, line, p->num_params); pr_debug("%s:%d: p.rtc_diff %lld\n", func, line, p->rtc_diff); pr_debug("%s:%d: p.av_multi_out %u\n", func, line, p->av_multi_out); pr_debug("%s:%d: p.ctrl_button: %u\n", func, line, p->ctrl_button); pr_debug("%s:%d: p.static_ip_addr: %u.%u.%u.%u\n", func, line, p->static_ip_addr[0], p->static_ip_addr[1], p->static_ip_addr[2], p->static_ip_addr[3]); pr_debug("%s:%d: p.network_mask: %u.%u.%u.%u\n", func, line, p->network_mask[0], p->network_mask[1], p->network_mask[2], p->network_mask[3]); pr_debug("%s:%d: p.default_gateway: %u.%u.%u.%u\n", func, line, p->default_gateway[0], p->default_gateway[1], p->default_gateway[2], p->default_gateway[3]); pr_debug("%s:%d: p.dns_primary: %u.%u.%u.%u\n", func, line, p->dns_primary[0], p->dns_primary[1], p->dns_primary[2], p->dns_primary[3]); pr_debug("%s:%d: p.dns_secondary: %u.%u.%u.%u\n", func, line, p->dns_secondary[0], p->dns_secondary[1], p->dns_secondary[2], p->dns_secondary[3]); } static int verify_header(const struct os_area_header *header) { if (memcmp(header->magic_num, OS_AREA_HEADER_MAGIC_NUM, sizeof(header->magic_num))) { pr_debug("%s:%d magic_num failed\n", __func__, __LINE__); return -1; } if (header->hdr_version < 1) { pr_debug("%s:%d hdr_version failed\n", __func__, __LINE__); return -1; } if (header->db_area_offset > header->ldr_area_offset) { pr_debug("%s:%d offsets failed\n", __func__, __LINE__); return -1; } return 0; } static int db_verify(const struct os_area_db *db) { if (memcmp(db->magic_num, OS_AREA_DB_MAGIC_NUM, sizeof(db->magic_num))) { pr_debug("%s:%d magic_num failed\n", __func__, __LINE__); return -EINVAL; } if (db->version != 1) { pr_debug("%s:%d version failed\n", __func__, __LINE__); return -EINVAL; } return 0; } struct db_index { uint8_t owner:5; uint8_t key:3; }; struct db_iterator { const struct os_area_db *db; struct os_area_db_id match_id; struct db_index *idx; struct db_index *last_idx; union { uint64_t *value_64; uint32_t *value_32; uint16_t *value_16; }; }; static unsigned int db_align_up(unsigned int val, unsigned int size) { return (val + (size - 1)) & (~(size - 1)); } /** * db_for_each_64 - Iterator for 64 bit entries. * * A NULL value for id can be used to match all entries. * OS_AREA_DB_OWNER_ANY and OS_AREA_DB_KEY_ANY can be used to match all. */ static int db_for_each_64(const struct os_area_db *db, const struct os_area_db_id *match_id, struct db_iterator *i) { next: if (!i->db) { i->db = db; i->match_id = match_id ? *match_id : os_area_db_id_any; i->idx = (void *)db + db->index_64; i->last_idx = i->idx + db->count_64; i->value_64 = (void *)db + db->index_64 + db_align_up(db->count_64, 8); } else { i->idx++; i->value_64++; } if (i->idx >= i->last_idx) { pr_debug("%s:%d: reached end\n", __func__, __LINE__); return 0; } if (i->match_id.owner != OS_AREA_DB_OWNER_ANY && i->match_id.owner != (int)i->idx->owner) goto next; if (i->match_id.key != OS_AREA_DB_KEY_ANY && i->match_id.key != (int)i->idx->key) goto next; return 1; } static int db_delete_64(struct os_area_db *db, const struct os_area_db_id *id) { struct db_iterator i; for (i.db = NULL; db_for_each_64(db, id, &i); ) { pr_debug("%s:%d: got (%d:%d) %llxh\n", __func__, __LINE__, i.idx->owner, i.idx->key, (unsigned long long)*i.value_64); i.idx->owner = 0; i.idx->key = 0; *i.value_64 = 0; } return 0; } static int db_set_64(struct os_area_db *db, const struct os_area_db_id *id, uint64_t value) { struct db_iterator i; pr_debug("%s:%d: (%d:%d) <= %llxh\n", __func__, __LINE__, id->owner, id->key, (unsigned long long)value); if (!id->owner || id->owner == OS_AREA_DB_OWNER_ANY || id->key == OS_AREA_DB_KEY_ANY) { pr_debug("%s:%d: bad id: (%d:%d)\n", __func__, __LINE__, id->owner, id->key); return -1; } db_delete_64(db, id); i.db = NULL; if (db_for_each_64(db, &os_area_db_id_empty, &i)) { pr_debug("%s:%d: got (%d:%d) %llxh\n", __func__, __LINE__, i.idx->owner, i.idx->key, (unsigned long long)*i.value_64); i.idx->owner = id->owner; i.idx->key = id->key; *i.value_64 = value; pr_debug("%s:%d: set (%d:%d) <= %llxh\n", __func__, __LINE__, i.idx->owner, i.idx->key, (unsigned long long)*i.value_64); return 0; } pr_debug("%s:%d: database full.\n", __func__, __LINE__); return -1; } static int db_get_64(const struct os_area_db *db, const struct os_area_db_id *id, uint64_t *value) { struct db_iterator i; i.db = NULL; if (db_for_each_64(db, id, &i)) { *value = *i.value_64; pr_debug("%s:%d: found %lld\n", __func__, __LINE__, (long long int)*i.value_64); return 0; } pr_debug("%s:%d: not found\n", __func__, __LINE__); return -1; } static int db_get_rtc_diff(const struct os_area_db *db, int64_t *rtc_diff) { return db_get_64(db, &os_area_db_id_rtc_diff, (uint64_t*)rtc_diff); } #define dump_db(a) _dump_db(a, __func__, __LINE__) static void _dump_db(const struct os_area_db *db, const char *func, int line) { char str[sizeof(db->magic_num) + 1]; dump_field(str, db->magic_num, sizeof(db->magic_num)); pr_debug("%s:%d: db.magic_num: '%s'\n", func, line, str); pr_debug("%s:%d: db.version: %u\n", func, line, db->version); pr_debug("%s:%d: db.index_64: %u\n", func, line, db->index_64); pr_debug("%s:%d: db.count_64: %u\n", func, line, db->count_64); pr_debug("%s:%d: db.index_32: %u\n", func, line, db->index_32); pr_debug("%s:%d: db.count_32: %u\n", func, line, db->count_32); pr_debug("%s:%d: db.index_16: %u\n", func, line, db->index_16); pr_debug("%s:%d: db.count_16: %u\n", func, line, db->count_16); } static void os_area_db_init(struct os_area_db *db) { enum { HEADER_SIZE = offsetof(struct os_area_db, _db_data), INDEX_64_COUNT = 64, VALUES_64_COUNT = 57, INDEX_32_COUNT = 64, VALUES_32_COUNT = 57, INDEX_16_COUNT = 64, VALUES_16_COUNT = 57, }; memset(db, 0, sizeof(struct os_area_db)); memcpy(db->magic_num, OS_AREA_DB_MAGIC_NUM, sizeof(db->magic_num)); db->version = 1; db->index_64 = HEADER_SIZE; db->count_64 = VALUES_64_COUNT; db->index_32 = HEADER_SIZE + INDEX_64_COUNT * sizeof(struct db_index) + VALUES_64_COUNT * sizeof(u64); db->count_32 = VALUES_32_COUNT; db->index_16 = HEADER_SIZE + INDEX_64_COUNT * sizeof(struct db_index) + VALUES_64_COUNT * sizeof(u64) + INDEX_32_COUNT * sizeof(struct db_index) + VALUES_32_COUNT * sizeof(u32); db->count_16 = VALUES_16_COUNT; /* Rules to check db layout. */ BUILD_BUG_ON(sizeof(struct db_index) != 1); BUILD_BUG_ON(sizeof(struct os_area_db) != 2 * OS_AREA_SEGMENT_SIZE); BUILD_BUG_ON(INDEX_64_COUNT & 0x7); BUILD_BUG_ON(VALUES_64_COUNT > INDEX_64_COUNT); BUILD_BUG_ON(INDEX_32_COUNT & 0x7); BUILD_BUG_ON(VALUES_32_COUNT > INDEX_32_COUNT); BUILD_BUG_ON(INDEX_16_COUNT & 0x7); BUILD_BUG_ON(VALUES_16_COUNT > INDEX_16_COUNT); BUILD_BUG_ON(HEADER_SIZE + INDEX_64_COUNT * sizeof(struct db_index) + VALUES_64_COUNT * sizeof(u64) + INDEX_32_COUNT * sizeof(struct db_index) + VALUES_32_COUNT * sizeof(u32) + INDEX_16_COUNT * sizeof(struct db_index) + VALUES_16_COUNT * sizeof(u16) > sizeof(struct os_area_db)); } /** * update_flash_db - Helper for os_area_queue_work_handler. * */ static int update_flash_db(void) { const unsigned int buf_len = 8 * OS_AREA_SEGMENT_SIZE; struct os_area_header *header; ssize_t count; int error; loff_t pos; struct os_area_db* db; /* Read in header and db from flash. */ header = kmalloc(buf_len, GFP_KERNEL); if (!header) return -ENOMEM; count = os_area_flash_read(header, buf_len, 0); if (count < 0) { pr_debug("%s: os_area_flash_read failed %zd\n", __func__, count); error = count; goto fail; } pos = header->db_area_offset * OS_AREA_SEGMENT_SIZE; if (count < OS_AREA_SEGMENT_SIZE || verify_header(header) || count < pos) { pr_debug("%s: verify_header failed\n", __func__); dump_header(header); error = -EINVAL; goto fail; } /* Now got a good db offset and some maybe good db data. */ db = (void *)header + pos; error = db_verify(db); if (error) { pr_notice("%s: Verify of flash database failed, formatting.\n", __func__); dump_db(db); os_area_db_init(db); } /* Now got good db data. */ db_set_64(db, &os_area_db_id_rtc_diff, saved_params.rtc_diff); count = os_area_flash_write(db, sizeof(struct os_area_db), pos); if (count < 0 || count < sizeof(struct os_area_db)) { pr_debug("%s: os_area_flash_write failed %zd\n", __func__, count); error = count < 0 ? count : -EIO; } fail: kfree(header); return error; } /** * os_area_queue_work_handler - Asynchronous write handler. * * An asynchronous write for flash memory and the device tree. Do not * call directly, use os_area_queue_work(). */ static void os_area_queue_work_handler(struct work_struct *work) { struct device_node *node; int error; pr_debug(" -> %s:%d\n", __func__, __LINE__); node = of_find_node_by_path("/"); if (node) { os_area_set_property(node, &property_rtc_diff); of_node_put(node); } else pr_debug("%s:%d of_find_node_by_path failed\n", __func__, __LINE__); error = update_flash_db(); if (error) pr_warn("%s: Could not update FLASH ROM\n", __func__); pr_debug(" <- %s:%d\n", __func__, __LINE__); } static void os_area_queue_work(void) { static DECLARE_WORK(q, os_area_queue_work_handler); wmb(); schedule_work(&q); } /** * ps3_os_area_save_params - Copy data from os area mirror to @saved_params. * * For the convenience of the guest the HV makes a copy of the os area in * flash to a high address in the boot memory region and then puts that RAM * address and the byte count into the repository for retrieval by the guest. * We copy the data we want into a static variable and allow the memory setup * by the HV to be claimed by the memblock manager. * * The os area mirror will not be available to a second stage kernel, and * the header verify will fail. In this case, the saved_params values will * be set from flash memory or the passed in device tree in ps3_os_area_init(). */ void __init ps3_os_area_save_params(void) { int result; u64 lpar_addr; unsigned int size; struct os_area_header *header; struct os_area_params *params; struct os_area_db *db; pr_debug(" -> %s:%d\n", __func__, __LINE__); result = ps3_repository_read_boot_dat_info(&lpar_addr, &size); if (result) { pr_debug("%s:%d ps3_repository_read_boot_dat_info failed\n", __func__, __LINE__); return; } header = (struct os_area_header *)__va(lpar_addr); params = (struct os_area_params *)__va(lpar_addr + OS_AREA_SEGMENT_SIZE); result = verify_header(header); if (result) { /* Second stage kernels exit here. */ pr_debug("%s:%d verify_header failed\n", __func__, __LINE__); dump_header(header); return; } db = (struct os_area_db *)__va(lpar_addr + header->db_area_offset * OS_AREA_SEGMENT_SIZE); dump_header(header); dump_params(params); dump_db(db); result = db_verify(db) || db_get_rtc_diff(db, &saved_params.rtc_diff); if (result) saved_params.rtc_diff = params->rtc_diff ? params->rtc_diff : SECONDS_FROM_1970_TO_2000; saved_params.av_multi_out = params->av_multi_out; saved_params.valid = 1; memset(header, 0, sizeof(*header)); pr_debug(" <- %s:%d\n", __func__, __LINE__); } /** * ps3_os_area_init - Setup os area device tree properties as needed. */ void __init ps3_os_area_init(void) { struct device_node *node; pr_debug(" -> %s:%d\n", __func__, __LINE__); node = of_find_node_by_path("/"); if (!saved_params.valid && node) { /* Second stage kernels should have a dt entry. */ os_area_get_property(node, &property_rtc_diff); os_area_get_property(node, &property_av_multi_out); } if(!saved_params.rtc_diff) saved_params.rtc_diff = SECONDS_FROM_1970_TO_2000; if (node) { os_area_set_property(node, &property_rtc_diff); os_area_set_property(node, &property_av_multi_out); of_node_put(node); } else pr_debug("%s:%d of_find_node_by_path failed\n", __func__, __LINE__); pr_debug(" <- %s:%d\n", __func__, __LINE__); } /** * ps3_os_area_get_rtc_diff - Returns the rtc diff value. */ u64 ps3_os_area_get_rtc_diff(void) { return saved_params.rtc_diff; } EXPORT_SYMBOL_GPL(ps3_os_area_get_rtc_diff); /** * ps3_os_area_set_rtc_diff - Set the rtc diff value. * * An asynchronous write is needed to support writing updates from * the timer interrupt context. */ void ps3_os_area_set_rtc_diff(u64 rtc_diff) { if (saved_params.rtc_diff != rtc_diff) { saved_params.rtc_diff = rtc_diff; os_area_queue_work(); } } EXPORT_SYMBOL_GPL(ps3_os_area_set_rtc_diff); /** * ps3_os_area_get_av_multi_out - Returns the default video mode. */ enum ps3_param_av_multi_out ps3_os_area_get_av_multi_out(void) { return saved_params.av_multi_out; } EXPORT_SYMBOL_GPL(ps3_os_area_get_av_multi_out);
import { useEffect, useState } from 'react'; let timeInterval = null; const App = () => { const [count, setCount] = useState(0); const [lock, setLock] = useState(false); const [timeCount, setTimeCount] = useState(5); useEffect(() => { if (count == 5) { setLock(true); } return () => {}; }, [count]); /** * 1. create an interval for timeCount * 2. set count to 0, set lock to false and time count to 5 */ useEffect(() => { if (lock && timeInterval === null) { timeInterval = setInterval(() => { setTimeCount((prev) => prev - 1); }, 1000); } }, [lock]); useEffect(() => { if (timeCount === 0) { clearInterval(timeInterval); setCount(0); setLock(false); setTimeCount(5); } }, [timeCount]); return ( <div> <h1 id='test'>{count}</h1> <button id='btn' disabled={lock} onClick={() => setCount(count + 1)} > ADD {lock && `(locked - ${timeCount}s)`} </button> </div> ); }; export default App;
using System; using R5T.T0178; using R5T.T0180; namespace R5T.T0190 { /// <summary> /// Strongly-types a string as a network directory path. /// <para> /// Network directory paths point to locations on network drives. /// </para> /// Network drives may or may not be available since they are not physically located on the currently running machine. /// </summary> /// <remarks> /// The <see cref="ILocalDirectoryPath"/>, <see cref="INetworkDirectoryPath"/> and <see cref="IRemoteDirectoryPath"/> types are all siblings. /// </remarks> [StrongTypeMarker] public interface INetworkDirectoryPath : IStrongTypeMarker, IDirectoryPath { } }
import * as fs from 'fs'; import * as path from 'path'; // noinspection JSUnusedGlobalSymbols export class Utils { /** * @param {object} config * @return {{enabled: boolean, protectedTags: string[], selectorHomeBtn: string, selectorPacmanBtn: string}} */ static validateConfig(config) { config = typeof config === "object" ? config : {}; const fields = [ "enabled", "protectedTags", "selectorHomeBtn", "selectorPacmanBtn", "injectMode", "pageSize", ]; Object.keys(config).forEach((k) => !fields.includes(k) && delete config[k]); config.pageSize = ~~config.pageSize; typeof config.enabled !== "boolean" && delete config.enabled; !Array.isArray(config.protectedTags) && delete config.protectedTags; typeof config.selectorHomeBtn !== "string" && delete config.selectorHomeBtn; typeof config.selectorPacmanBtn !== "string" && delete config.selectorPacmanBtn; !["append", "prepend"].includes(config.injectMode) && delete config.injectMode; ![5, 10, 15, 25, 50, 100].includes(config.pageSize) && delete config.pageSize; return config; } /** * @param {{getPackage: function}} storage * @param {string} module * @return {Promise<{name: string, versions: object, tags: object, time: object}>} */ static getPackage(storage, module) { return new Promise((ok, nok) => { storage.getPackage({ name: module, callback: (err, metaData) => { if (err) { return nok(err); } const { name, versions, time, "dist-tags": tags } = metaData; ok({ name, versions, time, "dist-tags": tags }); }, }); }); } /** * @param {{getLocalDatabase: function}} storage * @return {Promise<{name: string, version: string}[]>} */ static getLocalDatabase(storage) { return new Promise((ok, nok) => storage.getLocalDatabase((err, packages) => err ? nok(err) : ok(packages) ) ); } /** * @param {{changePackage: function}} storage * @param {string} module * @param {object} meta * @return {Promise} */ static changePackage(storage, module, meta) { return new Promise((ok, nok) => storage.changePackage(module, meta, "", (err) => (err ? nok(err) : ok())) ); } /** * @param {*} args * @param {function} callback * @param {number} errorCode * @return {function(*=, *): Promise<void>} */ static buildRoute(args, callback, errorCode = 500) { return async (req, res) => { const { storage, ...params } = args; try { const { package: pkg='', scope='' } = req.params || {}, module = [].concat(scope || [], [pkg as never]).join("/"), meta = module && storage ? await Utils.getPackage(storage, module) : null; const data = await callback(module, meta, req, params); data ? res.send(data) : res.sendStatus(200); } catch (err) { res.sendStatus(errorCode); } }; } /** * @param {object} meta * @param {string} version * @return {*} */ static getTagsOfVersion(meta, version) { return Object.entries(meta["dist-tags"]).reduce( (p, [tag, ver]) => (ver === version ? p.concat(tag as never) : p), [] ); } /** * @param {string[]} tags * @param {object} meta * @param {string} version * @param {{protectedTags: []}} opts * @return {boolean} */ static protectedTagsPreserved(tags, meta, version, opts) { const { protectedTags } = opts, before = Utils.getTagsOfVersion(meta, version); return before .filter((t) => protectedTags.includes(t)) .every((t) => tags.includes(t)); } }
/* Copyright 2012 Perttu Luukko * This file is part of itp2d. * itp2d 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. * itp2d 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 * itp2d. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SIMPLEOPERATORS_HPP_ #define _SIMPLEOPERATORS_HPP_ #include "operators.hpp" // Simple operators mainly used to test the logic of OperatorSum and // OperatorProduct in unit testing. // A simple null operator class class NullOperator : public virtual Operator { public: void operate(__attribute__((unused)) State& state, __attribute__((unused))StateArray& workspace) const {}; inline size_t required_workspace() const { return 0; } std::ostream& print(std::ostream& out) const; }; // A simple zero operator class class ZeroOperator : public virtual Operator { public: void operate(State& state, __attribute__((unused))StateArray& workspace) const { state.zero(); } inline size_t required_workspace() const { return 0; } std::ostream& print(std::ostream& out) const; }; // A simple constant operator class class ConstantOperator : public virtual Operator { public: ConstantOperator(comp c); void operate(State& state, __attribute__((unused))StateArray& workspace) const { state *= multiplier; }; inline size_t required_workspace() const { return 0; } inline comp const& get_multiplier() const { return multiplier; } std::ostream& print(std::ostream& out) const; private: comp multiplier; }; #endif // _SIMPLEOPERATORS_HPP_
As the use of AI-based systems becomes more widespread in smart water management, it is important to consider the ethical implications of this technology. In this chapter, we will explore the ethical issues associated with the use of AI in smart water management, as well as best practices for ensuring ethical and responsible AI in this context. We will also discuss future directions and challenges for the ethical development and use of AI in smart water management. Ethical Issues Associated with the Use of AI in Smart Water Management ---------------------------------------------------------------------- There are a number of ethical issues associated with the use of AI in smart water management, including: ### Bias and Discrimination AI-based systems can be biased and discriminatory if they are developed and operated using incomplete or biased data. This can lead to unfair treatment and impact marginalized communities disproportionately. ### Privacy The use of AI-based systems in smart water management raises concerns about privacy. Personal information collected by these systems must be protected and used only for the purpose it was intended for. ### Transparency and Explainability Transparent decision-making is essential to build trust in AI-based systems. Smart water management systems should provide clear explanations of how decisions are made and ensure that individuals are aware of how their data is being used. ### Human Oversight While AI-based systems can improve the efficiency and accuracy of water management processes, it is important to emphasize human oversight in their development and operation. Humans should have the ability to override system decisions if needed. Best Practices for Ensuring Ethical and Responsible AI in Smart Water Management -------------------------------------------------------------------------------- To ensure ethical and responsible AI in smart water management, the following best practices should be followed: ### Develop Clear Ethical Guidelines Water utilities should establish clear ethical guidelines for the development and operation of AI-based systems in smart water management. These guidelines should prioritize the protection of privacy, fairness, transparency, accountability, and human oversight. ### Ensure Diverse and Representative Data To avoid bias and discrimination, it is essential to ensure that the data used to train AI-based systems is diverse and representative of the population. This can be achieved by collecting data from a variety of sources and using techniques such as anomaly detection to identify bias in the data. ### Prioritize Transparency and Explainability To build trust in AI-based systems, it is important to prioritize transparency and explainability in their operation. This includes providing clear explanations of how decisions are made and ensuring that individuals are aware of how their data is being used. ### Emphasize Human Oversight Humans should be involved in the training and development of AI-based systems, and should have the ability to override system decisions when necessary. ### Monitor and Evaluate System Performance Water utilities should monitor and evaluate the performance of AI-based systems on an ongoing basis. This includes assessing their impact on water management processes, evaluating their accuracy and effectiveness, and identifying and addressing any ethical concerns that arise. Future Directions and Challenges -------------------------------- As the use of AI in smart water management continues to grow, there will be new challenges and opportunities in ensuring ethical and responsible use. Future directions may include developing more sophisticated algorithms and incorporating new types of data into decision-making processes. Challenges will continue to include the need to build trust in these systems among stakeholders and maintaining a focus on ethical principles and human oversight. Ultimately, a commitment to ethics and responsibility in the development and use of AI in smart water management will be essential to ensure that access to safe and clean water is guaranteed for all.
<?php require_once('../../config.php'); use block_design_ideas\ai_call; // CHECK And PREPARE DATA global $CFG, $DB, $COURSE, $USER, $OUTPUT; require_once($CFG->libdir . '/questionlib.php'); require_once($CFG->dirroot . '/question/format.php'); require_once($CFG->dirroot . '/question/format/gift/format.php'); $userid = $USER->id; // Get the raw POST data $data = file_get_contents("php://input"); // Decode the JSON data $json_data = json_decode($data, true); // Get question data $question_data = $json_data['questions']; $numofquestions = count($question_data); //Convert questions into GIFT format; $gift = ''; foreach ($question_data as $qd) { $gift .= $qd['question'] . ' {' . "\n"; if ($qd['correct_answer'] == 'answer1') { $gift .= '=' . $qd['answer1'] . "\n"; } else { $gift .= '~' . $qd['answer1'] . "\n"; } if ($qd['correct_answer'] == 'answer2') { $gift .= '=' . $qd['answer2'] . "\n"; } else { $gift .= '~' . $qd['answer2'] . "\n"; } if ($qd['correct_answer'] == 'answer3') { $gift .= '=' . $qd['answer3'] . "\n"; } else { $gift .= '~' . $qd['answer3'] . "\n"; } if ($qd['correct_answer'] == 'answer4') { $gift .= '=' . $qd['answer4'] . "\n"; } else { $gift .= '~' . $qd['answer4'] . "\n"; } $gift .= "}\n\n"; } $course_id = $json_data['course_id']; require_login($course_id, false); // User must have capability to edit course if (!has_capability('moodle/course:update', context_course::instance($course_id))) { $status = [ 'status' => 'error', 'message' => 'You do not have permission to edit this course' ]; echo json_encode($status); die(); } $qformat = new \qformat_gift(); $coursecontext = \context_course::instance($course_id); // Use existing questions category for quiz or create the defaults. $contexts = new core_question\local\bank\question_edit_contexts($coursecontext); if (!$category = $DB->get_record('question_categories', ['contextid' => $coursecontext->id, 'sortorder' => 999])) { $category = question_make_default_categories($contexts->all()); } // Split questions based on blank lines. // Then loop through each question and create it. $questions = explode("\n\n", $gift); unset($questions[4]); if (count($questions) != $numofquestions) { return false; } $createdquestions = []; // Array of objects of created questions. foreach ($questions as $question) { $singlequestion = explode("\n", $question); // Manipulating question text manually for question text field. $questiontext = explode('{', $singlequestion[0]); $questiontext = trim(str_replace('::', '', $questiontext[0])); $qtype = 'multichoice'; $q = $qformat->readquestion($singlequestion); // Check if question is valid. if (!$q) { return false; } $q->category = $category->id; $q->createdby = $userid; $q->modifiedby = $userid; $q->timecreated = time(); $q->timemodified = time(); $q->questiontext = ['text' => "<p>" . $questiontext . "</p>"]; $q->questiontextformat = 1; $created = question_bank::get_qtype($qtype)->save_question($q, $q); $createdquestions[] = $created; } $data = new stdClass(); if ($created) { $data->status = 'success'; } else { $data->status = 'error'; $data->message = 'Error creating questions'; } echo json_encode($data); //} function clean_message($message) { // Remove <html> and <body> tags $message = str_replace('<html>', '', $message); $message = str_replace('</html>', '', $message); $message = str_replace('<body>', '', $message); $message = str_replace('</body>', '', $message); // Remove <p>Essay written by Professor AI Bot</p> $message = preg_replace('/<p>Essay written by Professor AI Bot<\/p>/', '', $message); $message = preg_replace('/<p>Written by Professor AI Bot<\/p>/', '', $message); $message = str_replace('CLASS NOTES: ', '', $message); $message = str_replace('Class Notes: ', '', $message); $message = preg_replace('/<style>.*?<\/style>/', '', $message); // Remove <head...></head> tags and remove all content inbetween them $message = preg_replace('/<head>.*?<\/head>/', '', $message); return $message; }
"use client"; import { fetchUserTokensById, generateChatResponse, subtractTokens, } from "@/utils/action"; import { useAuth } from "@clerk/nextjs"; import { useMutation } from "@tanstack/react-query"; import React, { useState } from "react"; import toast from "react-hot-toast"; import { fadeIn } from "@/variants"; import { motion } from "framer-motion"; const Chat = () => { const { userId } = useAuth(); const [text, setText] = useState(""); const [messages, setMessages] = useState([]); const { mutate, isPending } = useMutation({ mutationFn: async (query) => { const currentTokens = await fetchUserTokensById(userId); if (currentTokens < 100) { toast.error("Token balance too low...."); return; } const response = await generateChatResponse([...messages, query]); if (!response) { toast.error("Something went wrong..."); return; } setMessages((prev) => [...prev, response.message]); const newTokens = await subtractTokens(userId, response.tokens); toast.success(`${newTokens} tokens remaining...`); }, }); const handleSubmit = (e) => { e.preventDefault(); const query = { role: "user", content: text }; mutate(query); setMessages((prev) => [...prev, query]); setText(""); }; return ( <div className="min-h-[calc(100vh-6rem)] grid grid-rows-[1fr,auto]"> <div> {messages.map(({ role, content }, index) => { const avatar = role == "user" ? "👤" : "🤖"; const bcg = role === "user" ? "bg-base-200" : "bg-base-100"; return ( <div key={index} className={`${bcg} flex py-6 -mx-8 px-8 text-xl leading-loose border-b border-base-300`} > <span className="mr-4">{avatar}</span> <p className="max-w-3xl">{content}</p> </div> ); })} {isPending ? <span className="loading"></span> : null} </div> <motion.form variants={fadeIn("up", 0.4)} initial="hidden" animate="show" exit="hidden" onSubmit={handleSubmit} className="max-w-4xl pt-12" > <div className="join w-full"> <input type="text" placeholder="Message MaToursGPT" className="placeholder:text-sm pl-2 md:input input-bordered join-item w-full md:placeholder:text-lg " value={text} required onChange={(e) => setText(e.target.value)} /> <button className=" sm:text-sm btn btn-primary join-item text-md " type="submit" disabled={isPending} > {isPending ? "Please Wait..." : "Ask Question"} </button> </div> </motion.form> </div> ); }; export default Chat;
// login.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { AuthService } from '../../services/auth.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm: FormGroup; constructor(private fb: FormBuilder, private authService: AuthService, private router: Router) { this.loginForm = this.fb.group({ email: ['', [Validators.required, Validators.email]], password: ['', Validators.required] }); } ngOnInit(): void { } onSubmit() : void{ const { email, password } = this.loginForm.value; this.authService.login(email, password).subscribe( () => { this.router.navigate(['/main-page']); }, (error) => { console.error(error); alert('Failed to login'); } ) } }
// App.js import React, { useEffect, useState } from 'react'; import './reg.css' import { Stepper, Step } from 'react-form-stepper'; import Step1 from './Step1'; import Step2 from './Step2'; import Step3 from './Step3'; import Step4 from './Step4'; import Step5 from './Step5'; import { Form, Button, Container, Row, Col } from 'react-bootstrap'; function KeySellerRegistration() { const [step, setStep] = useState(0); const [userData, setUserData] = useState(); const reg_userdata = JSON.parse(localStorage.getItem('seller-registration')) console.log({ reg_userdata }) useEffect(() => { if (!reg_userdata?.Shop_Details_Info && reg_userdata?.password) { setStep(1) } else if (reg_userdata?.Shop_Details_Info && !reg_userdata?.doc_details) { setStep(2) } else if (reg_userdata?.doc_details && !reg_userdata?.bank_details) { setStep(3) } else if (reg_userdata?.bank_details && !reg_userdata?.interest_details) { setStep(4) } }, []) // useEffect(()=>{ // // if (!reg_userdata?.Shop_Details_Info){ // // setStep(1) // // } else if (!reg_userdata?.doc_details && reg_userdata?.Shop_Details_Info && reg_userdata?.password){ // // setStep(2) // // } // if (reg_userdata?.password && !reg_userdata?.Shop_Details_Info){ // console.log('call') // setStep(1) // } else if (reg_userdata?.password && reg_userdata?.Shop_Details_Info ){ // setStep(2) // } // },[]) const nextStep = () => { setStep(step + 1); }; const prevStep = () => { setStep(step - 1); }; const getUserdata = (data) => { console.log(data) setUserData(data) } return ( <div className="App"> <Container> <Row> <Col xs={12}> <Stepper activeStep={step} styleConfig={{ activeBgColor: '#1ec7d6', activeTextColor: '#fff', activeTitleColor: '#820300', inactiveBgColor: '#F5F7F8', inactiveTextColor: '#BFC2C6', completedBgColor: '#236162', completedTextColor: '#fff', size: '2em' }}> <Step label="Seller Information" /> <Step label="Shop Details" /> <Step label="Documentation" /> <Step label="Banking Details" /> <Step label="Categoey & Comissions" /> </Stepper> </Col> </Row> </Container> <Container> <Row className='mt-2 ml-4 p-4'> <Col xs={12}> {step === 0 && <Step1 nextStep={nextStep} getUserdata={getUserdata} />} {step === 1 && <Step2 nextStep={nextStep} prevStep={prevStep} reg_userdata={reg_userdata} getUserdata={getUserdata} />} {step === 2 && <Step3 nextStep={nextStep} prevStep={prevStep} reg_userdata={reg_userdata} getUserdata={getUserdata} />} {step === 3 && <Step4 nextStep={nextStep} prevStep={prevStep} reg_userdata={reg_userdata} getUserdata={getUserdata} />} {step === 4 && <Step5 prevStep={prevStep} reg_userdata={reg_userdata} getUserdata={getUserdata} />} </Col> </Row> </Container> </div> ); } export default KeySellerRegistration;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Change the below title and description according to your brand or website name. --> <title>Startup - Blog</title> <meta name="description" content="Add description here."> <!---------- CSS Files ----------> <link rel="stylesheet" type="text/css" href="../styles.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap" rel="stylesheet"> </head> <body> <!---------- Navbar ----------> <nav data-aos="fade-down" data-aos-duration="1500" class="navbar fixed-top navbar-expand-lg"> <div class="container-fluid"> <!-- Text Logo --> <a class="navbar-brand text-logo" href="../index.html">Vivid AI</a> <!-- Image Logo --> <!-- <a class="navbar-brand image-logo" href="#"> <img class="image-logo" src="./images/logo" alt="logo"> </a> --> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item navbar-item"> <a class="nav-link navbar-link" href="../index.html">Home</a> </li> <li class="nav-item navbar-item"> <a class="nav-link navbar-link" href="#features">Features</a> </li> <li class="nav-item navbar-item"> <a class="nav-link navbar-link" href="#partners">Partners</a> </li> <li class="nav-item navbar-item"> <a class="nav-link navbar-link" href="../blog.html">Blog</a> </li> <li class="nav-item navbar-item"> <a class="nav-link navbar-link" href="#faq">FAQ</a> </li> </ul> <a href="../contact.html"><button class="btn btn-dark btn-sm rounded-pill top-contact-button"> CONTACT </button></a> </div> </div> </nav> <!---------- Article Content ----------> <section class="article"> <div class="article-content"> <!-- Article Title --> <p class="article-title">How to build your first project</p> <!-- Artcle Description --> <p class="article-description">Beginner guide to create first project</p> <!-- Article Info --> <div class="article-info"> <p class="article-date">Published on 6th January 2024</p> <p class="article-author">By Vivid Marketing</p> <p class="article-label">Marketing</p><p class="article-label">Product</p> </div> <!-- Article Image --> <img class="article-image" src="https://images.unsplash.com/photo-1618556450994-a6a128ef0d9d?q=80&w=3164&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="article-image" loading="lazy"> <!-- Article Body --> <div class="article-body"> <p class="article-text"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> <p class="article-text"> It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). </p> <p class="article-text"> There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc. </p> </div> </div> </section> <!-- Footer Content --> <section class="footer"> <div class="footer-content"> <div class="footer-content-left"> <p class="footer-content-left-description"> Vivid Newton™ is part of Vivid Themes Inc.</p> <p class="footer-content-left-copyright"> © 2024 Vivid Themes. All Right Reserved.</p> </div> <div class="footer-content-right"> <div class="footer-content-right-column"> <p class="footer-content-right-column-title">Useful Links</p> <p class="footer-content-right-column-link">Features</p> <p class="footer-content-right-column-link">Pricing</p> <p class="footer-content-right-column-link">Privacy Policy</p> <p class="footer-content-right-column-link">Terms & Conditions</p> </div> <div class="footer_content_right_column"> <p class="footer-content-right-column-title">Help</p> <p class="footer-content-right-column-link">Getting Started</p> <p class="footer-content-right-column-link">User Guide</p> <p class="footer-content-right-column-link">FAQ</p> <p class="footer-content-right-column-link">Feedback</p> </div> <div class="footer_content_right_column"> <p class="footer-content-right-column-title">About</p> <p class="footer-content-right-column-link">News</p> <p class="footer-content-right-column-link">Careers</p> <p class="footer-content-right-column-link">Investors</p> <p class="footer-content-right-column-link">Sustainability</p> </div> </div> </div> </section> <!---------- JavaScript File ----------> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script> <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script> <script src="../script.js"></script> </body> </html>