text
stringlengths
184
4.48M
use std::error::Error; use std::fmt::{Display, Formatter}; use std::mem::size_of; use std::rc::Rc; //RC fn takes_a_string(string: String) { println!("{}", string); } fn takes_a_string_again(string: String) { println!("{}", string); } fn takes_string() { let s = "I am a string".to_string(); takes_a_string(s); // takes_a_string_again(s); // s is not available } #[derive(Debug)] struct City1 { name: String, population: u32, city_history: String, } #[derive(Debug)] struct CityData1 { names: Vec<String>, histories: Vec<String>, } pub fn rc_demo1() { let calgary = City1 { name: "Calgary".to_string(), population: 1_200_000, // Pretend that this string is very very long city_history: "Calgary began as a fort called Fort Calgary that...".to_string(), }; let canada_cities = CityData1 { names: vec![calgary.name], // This is using calgary.name, which is short histories: vec![calgary.city_history], // But this String is very long }; // println!("{} {}", calgary.city_history,calgary.name); } // use rc #[derive(Debug)] struct City { name: String, population: u32, city_history: Rc<String>, } #[derive(Debug)] struct CityData { names: Vec<String>, histories: Vec<Rc<String>>, } pub fn rc_demo2() { let calgary = City { name: "Calgary".to_string(), population: 1_200_000, // Pretend that this string is very very long city_history: Rc::from("Calgary began as a fort called Fort Calgary that...".to_string()), }; let canada_cities = CityData { names: vec![calgary.name], // This is using calgary.name, which is short histories: vec![calgary.city_history.clone()], // But this String is very long }; println!("Calgary's history is: {}", calgary.city_history); println!("{}", Rc::strong_count(&calgary.city_history)); let new_owner = calgary.city_history.clone(); println!("{}", Rc::strong_count(&calgary.city_history)); } // finally, the Box struct MyStruct { name: String, age: u32, height: u32, } #[derive(Debug)] enum MyEnum { Variable1, Variable2, } pub fn box_at_heap() { let my_struct = Box::new(MyStruct { name: "John".to_string(), age: 30, height: 180, }); let my_enum = Box::new(MyEnum::Variable1); //access fields of my_struct println!("Name: {}", my_struct.name); //access fields of my_enum println!("Value: {:?}", my_enum); } struct List { item: Option<Box<List>>, } impl List { fn new() -> Self { List { item: Some(Box::new(List { item: None })), //could be infinite size } } } trait JustATrait {} enum EnumOfNumbers { I8(i8), AnotherI8(i8), OneMoreI8(i8), } impl JustATrait for EnumOfNumbers {} struct StructOfNumbers { an_i8: i8, another_i8: i8, one_more_i8: i8, } impl JustATrait for StructOfNumbers {} enum EnumOfOtherTypes { I8(i8), AnotherI8(i8), Collection(Vec<String>), } impl JustATrait for EnumOfOtherTypes {} struct StructOfOtherTypes { an_i8: i8, another_i8: i8, a_collection: Vec<String>, } impl JustATrait for StructOfOtherTypes {} struct ArrayAndI8 { array: [i8; 1000], // This one will be very large an_i8: i8, in_u8: u8, } impl JustATrait for ArrayAndI8 {} pub fn print_size_of_types() { println!( "{} {} {} {} {}", size_of::<EnumOfNumbers>(), size_of::<StructOfNumbers>(), size_of::<EnumOfOtherTypes>(), size_of::<StructOfOtherTypes>(), size_of::<ArrayAndI8>(), ); } fn returns_just_a_trait() -> Box<dyn JustATrait> { // sized which have a size same as raw pointers let some_enum = EnumOfNumbers::I8(1); Box::new(some_enum) } #[derive(Debug)] struct ErrorOne; impl Display for ErrorOne { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "ErrorOne") } } impl Error for ErrorOne {} #[derive(Debug)] // Do the same thing with ErrorTwo struct ErrorTwo; impl Error for ErrorTwo {} impl Display for ErrorTwo { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "You got the second error!") } } // Make a function that just returns a String or an error pub fn returns_error(input: u8) -> Result<String, Box<dyn Error>> { // compile time aware size // if input is 0, return an ErrorOne // if input is 1 ,return an ErrorTwo // if input is another thing, return a String if input == 0 { return Err(Box::new(ErrorOne)); } if input == 1 { return Err(Box::new(ErrorTwo)); } Ok("Hello".to_string()) }
#ifndef POLYNOMIAL #define POLYNOMIAL #include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::istream; using std::ostream; using std::string; struct Item { double coef; int exp; //in order to inplement quick sort, //-we need the double direction Item* next; Item *last; }; //finding the index of of the base number *lowPtr Item *get_index(Item *lowPtr, Item *highPtr); // an auxiliary function to polish each item in a mathematical format. string printItem(bool isFirst, double coef, int exp); class Polynomial { public: //in this case, I store the nothing in head. Item *head; //in order to make the quicksort quicker, // I set a tail ptr to avoid traversing the whole list. Item *tail; int itemNum; int maxExp; public: //default constructor Polynomial(); void create_Polynomial(); void quick_sort(Item *lowPtr, Item *highPtr); int get_itemNum() const { return itemNum; } int get_maxExp() const { return maxExp; } //friend istream &operator>>(istream &in, const Polynomial &pl); friend ostream &operator<<(ostream &out, const Polynomial &pl); Polynomial &operator=(const Polynomial &pl); Polynomial operator+( const Polynomial &anotherPoly); Polynomial operator-(const Polynomial &anotherPoly); Polynomial operator*(const Polynomial &pl); ~Polynomial() { Item* tempPtr = head; while( tempPtr->next != nullptr ) { tempPtr = tempPtr->next; delete tempPtr->last; } delete tempPtr; } }; #endif
import { paramCase } from 'change-case'; import { Link as RouterLink } from 'react-router-dom'; // @mui import { Box, Card, Link, Typography, Stack, IconButton, Button, Grid } from '@mui/material'; // routes import { PATH_DASHBOARD } from '../../../../routes/paths'; // utils import { fCurrency } from '../../../../utils/formatNumber'; // @types import { Product } from '../../../../@types/product'; // components import Label from '../../../../components/Label'; import Image from '../../../../components/Image'; import { ColorPreview } from '../../../../components/color-utils'; import Iconify from 'src/components/Iconify'; import { useState } from 'react'; // ---------------------------------------------------------------------- type Props = { product: Product; index: number; }; export default function ShopProductCard({ product, index }: Props) { const { name, cover, price, colors, status, priceSale } = product; const images = [ 'https://images.unsplash.com/photo-1565299624946-b28f40a0ae38', 'https://images.unsplash.com/photo-1567620905732-2d1ec7ab7445', 'https://images.unsplash.com/photo-1482049016688-2d3e1b311543', 'https://images.unsplash.com/photo-1540189549336-e6e99c3679fe', 'https://images.unsplash.com/photo-1467003909585-2f8a72700288', 'https://images.unsplash.com/photo-1484723091739-30a097e8f929', 'https://images.unsplash.com/photo-1473093295043-cdd812d0e601', 'https://images.unsplash.com/photo-1467003909585-2f8a72700288', 'https://static.toiimg.com/photo/55976415.cms', 'https://www.indianhealthyrecipes.com/wp-content/uploads/2022/02/hyderabadi-biryani-recipe-chicken.jpg', 'https://img.buzzfeed.com/buzzfeed-static/static/2014-06/23/15/campaign_images/webdr07/26-traditional-indian-foods-that-will-change-your-1-7312-1403550756-15_big.jpg', ]; return ( <Card> <Box sx={{ position: 'relative' }}> {status && ( <Label variant="filled" color={(status === 'sale' && 'error') || 'info'} sx={{ top: 16, right: 16, zIndex: 9, position: 'absolute', textTransform: 'uppercase', }} > {status} </Label> )} <Image alt={name} src={images[index]} ratio="1/1" /> </Box> <Grid container justifyContent="space-between" alignItems="flex-end" spacing={0} sx={{ px: 1, py: 3 }} > <Grid item xs={8}> <Grid container direction={'column'}> <Typography variant="subtitle2">{name}</Typography> <Stack direction="row" spacing={0.5}> {priceSale && ( <Typography component="span" sx={{ color: 'text.disabled', textDecoration: 'line-through' }} > {fCurrency(priceSale)} </Typography> )} <Typography variant="subtitle1">{fCurrency(price)}</Typography> </Stack> </Grid> </Grid> <Grid item> <Incrementer /> </Grid> </Grid> </Card> ); } function Incrementer() { const [quantity, setQuantity] = useState<number>(0); if (quantity < 1) { return ( <Button fullWidth size="large" color="warning" variant="contained" startIcon={<Iconify icon={'ic:round-add-shopping-cart'} />} onClick={() => { setQuantity(quantity + 1); }} sx={{ whiteSpace: 'nowrap', width: 80, height: 36 }} > ADD </Button> ); } return ( <Box sx={{ py: 0.5, px: 0.75, border: 1, lineHeight: 0, borderRadius: 1, display: 'flex', alignItems: 'center', borderColor: 'grey.50032', }} > <IconButton size="small" color="inherit" disabled={quantity <= 1} onClick={() => { quantity && setQuantity(quantity - 1); }} > <Iconify icon={'eva:minus-fill'} width={14} height={14} /> </IconButton> <Typography variant="body2" component="span" sx={{ width: 40, textAlign: 'center' }}> {quantity} </Typography> <IconButton size="small" color="inherit" onClick={() => { setQuantity(quantity + 1); }} > <Iconify icon={'eva:plus-fill'} width={14} height={14} /> </IconButton> </Box> ); }
package THEiAirlineBeans; import THEiAirlineEntity.PaymentRecord; import THEiAirlineEntity.Trips; import THEiAirlineEntity.Passenger; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; @Named(value = "paymentManager") @SessionScoped public class PaymentManager implements Serializable { private EntityManagerFactory emf; private String paymentType; public PaymentManager() { emf = Persistence.createEntityManagerFactory("my_persistence_unit"); } public String getPaymentType() { return paymentType; } public void setPaymentType(String paymentType) { this.paymentType = paymentType; } public PaymentRecord createPayment(double amountPaid, String paymentType, Trips trip, Passenger passenger) { EntityManager em = emf.createEntityManager(); PaymentRecord paymentRecord = new PaymentRecord(); try { em.getTransaction().begin(); paymentRecord.setPaymentDate(new Date()); // Automatically set the current date paymentRecord.setAmountPaid(amountPaid); paymentRecord.setPaymentType(paymentType); paymentRecord.setTrip(trip); paymentRecord.setPassenger(passenger); em.persist(paymentRecord); em.getTransaction().commit(); } finally { em.close(); } return paymentRecord; } public void updatePaymentRecord(PaymentRecord paymentRecord) { EntityManager em = emf.createEntityManager(); try { em.getTransaction().begin(); em.merge(paymentRecord); em.getTransaction().commit(); } finally { em.close(); } } public void deletePaymentRecord(Long paymentRecordId) { EntityManager em = emf.createEntityManager(); try { em.getTransaction().begin(); PaymentRecord paymentRecord = em.find(PaymentRecord.class, paymentRecordId); if (paymentRecord != null) { em.remove(paymentRecord); } em.getTransaction().commit(); } finally { em.close(); } } public PaymentRecord getPaymentRecordById(Long paymentRecordId) { EntityManager em = emf.createEntityManager(); PaymentRecord paymentRecord = null; try { paymentRecord = em.find(PaymentRecord.class, paymentRecordId); } finally { em.close(); } return paymentRecord; } public List<PaymentRecord> getAllPaymentRecords() { EntityManager em = emf.createEntityManager(); List<PaymentRecord> paymentRecords = null; try { paymentRecords = em.createQuery("SELECT pr FROM PaymentRecord pr", PaymentRecord.class).getResultList(); } finally { em.close(); } return paymentRecords; } }
{% extends 'layout.html' %} {% block body %} <h1>Order Starters - Table {{table_id}}</h1> <hr> <div id="Tablestarters"> <div class="row-fluid" id="main"> {% for starter in starters %} {% if loop.index0 % 3 == 0 %} <div class="row"> {% endif %} <div class="col-sm-4"> {% if starter.stock == 0 %} <button type="button" class="btn-lg btn-block btn-danger" data-toggle="modal" data-target="#orderModal{{starter.product_id}}" disabled="true">{{starter.name}} ({{starter.stock}})</button> {% elif starter.stock <= 30 %} <button type="button" class="btn-lg btn-block btn-warning" data-toggle="modal" data-target="#orderModal{{starter.product_id}}">{{starter.name}} ({{starter.stock}})</button> {% else %} <button type="button" class="btn-lg btn-block btn-success" data-toggle="modal" data-target="#orderModal{{starter.product_id}}">{{starter.name}} ({{starter.stock}})</button> {% endif %} </div> {% if loop.index0 % 3 == 2 or loop.last %} </div> {% endif %} <br> {% endfor %} </div> </div> <hr> {% for starter in starters %} <!-- Modal --> <div class="modal fade" id="orderModal{{ starter.product_id}}" role="dialog"> <div class="modal-dialog modal-lg"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <h3>{{starter.name}}</h3> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <table id="Tablestarter" class="table"> <th>Price</th> <th>Message</th> <th>Stock</th> <th>Quantity</th> <th></th> <th></th> </tr> <form id="Formstarter" action="/tables/{{table_id}}/add_to_order/{{order_id}}/{{starter.product_id}}/{{starter.price}}/" method="POST"> <td>£{{starter.price}}</td> <td><textarea name="message{{starter.product_id}}" id="message{{starter.product_id}}"></textarea></td> <td>{{starter.stock}}</td> <td><input type="button" id='SubButton{{starter.product_id}}' value="-"> <input type="number" min="0" name="quantity{{starter.product_id}}" style="width: 50px;" id="quantity{{starter.product_id}}" value=1> <input type="button" id='AddButton{{starter.product_id}}' value="+"> <script> $('#SubButton{{starter.product_id}}').on('click', function () { var input = $('#quantity{{starter.product_id}}'); if (parseInt(input.val()) != 0) { input.val(parseInt(input.val()) - 1); } }) </script> <script> $('#AddButton{{starter.product_id}}').on('click', function () { var input = $('#quantity{{starter.product_id}}'); if (parseInt(input.val()) < '{{starter.stock}}') { input.val(parseInt(input.val()) + 1); } }) </script> </td> <td><input class="btn btn-success" type="Submit" value="Add to Order"></input></td> <td><button type="" class="btn btn-primary" data-dismiss="modal">Cancel</button></td> </tr> </form> </table> </div> </div> </div> </div> {% endfor %} {% endblock %}
import {NgModule} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; import {AuthGuard} from '@shared/guards/auth.guard'; const routes: Routes = [ { path: 'auth', loadChildren: () => import('./pages/auth/auth.module').then(m => m.AuthModule) }, { path: '', canActivate: [AuthGuard], loadChildren: () => import('./workspaces/admin/admin.module').then(m => m.AdminModule) }, { path: '**', redirectTo: 'auth', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import { Command } from 'commander' import inquirer from 'inquirer' import { initConfig, addConfigOptions } from '../lib/config' import * as gitCrypt from '../lib/git-crypt' import { errors } from '../lib/errors' /** * Unlocks the repository. */ const command = new Command() .name('unlock') .description('Unlocks the repository.') .option('-k, --encoded-key <key>', 'The base64 encoded key') .action(async () => { const config = initConfig(command.optsWithGlobals()) // Ensure we are at "locked" status. await gitCrypt.invariantStatus(config, { empty: errors.notConfigured, ready: errors.unlocked, }) let encodedKey = process.env.SHH_KEY || config.encodedKey // Let use input on first usage on new clone. if (!encodedKey && config.logLevel === 'log') { encodedKey = ( await inquirer.prompt([ { name: 'key', type: 'input', message: 'Provide the shh key (run `shh export-key` to get one):', validate: gitCrypt.isValidKey, }, ]) ).key as string } await gitCrypt.unlock(encodedKey) }) addConfigOptions(command) export { command }
import React, { Component } from "react"; /* eslint no-eval: 0 */ import { Display } from "../components/miniComponents/Display/Display"; import { Title } from "../components/miniComponents/Titles/Title"; import { ContainerButtons } from "../components/medioComponents/ContainerButtons/ContainerButtons"; import "./Calculadora.scss"; interface calcProps { displayValue: string; clearDisplay: boolean; operation: null; values: Array<number>; current: number; } const initialState: calcProps = { displayValue: "0", clearDisplay: false, operation: null, values: [0, 0], current: 0, }; export default class Calculadora extends Component { state = { ...initialState, }; clearMemory = () => { this.setState({ ...initialState }); }; setOperation = (operation: string) => { if (this.state.current === 0) { this.setState({ operation, current: 1, clearDisplay: true, }); } else { const equals = operation === "="; const currentOperation = this.state.operation; const values = [...this.state.values]; try { values[0] = eval(`${values[0]} ${currentOperation} ${values[1]}`); } catch (e) { values[0] = this.state.values[0]; } values[1] = 0; this.setState({ displayValue: values[0], operation: equals ? null : operation, current: equals ? 0 : 1, clearDisplay: !equals, values, }); } }; addDigito = (n: string) => { if (n === "." && this.state.displayValue.includes(".")) { return; } const clearDisplay = this.state.displayValue === "0" || this.state.clearDisplay; const currentValue = clearDisplay ? "" : this.state.displayValue; const displayValue = currentValue + n; this.setState({ displayValue, clearDisplay: false }); if (n !== ".") { const i = this.state.current; const newValue = parseFloat(displayValue); const values = [...this.state.values]; values[i] = newValue; this.setState({ values }); } }; render() { const addDigito = (n: string) => this.addDigito(n); const setOperation = (op: string) => this.setOperation(op); return ( <> <Title text="Calculadora"></Title> <section className="calculator__3d"> <div className="calculator"> <Display estilo="display" value={this.state.displayValue} /> <ContainerButtons clear={() => this.clearMemory()} setOperation={setOperation} addDigito={addDigito} /> </div> </section> </> ); } }
<!Doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="css/detalle.css"> <link rel="stylesheet" href="node_modules/open-iconic/font/css/open-iconic-bootstrap.min.css"> <script src="https://kit.fontawesome.com/9534f42a55.js" crossorigin="anonymous"></script> <title>Practica Bootstrapt</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">Bootstrapt</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarNavDropdown" 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 mr-auto"> <li class="nav-item"><a class="nav-link" href="index.html">Home</a></li> <li class="nav-item"><a class="nav-link" href="#" data-toggle="modal" data-target="#register">Registrarse</a></li> <li class="nav-item"><a class="nav-link" href="#" data-toggle="modal" data-target="#login">Login</a> </li> <li class="nav-item"><a class="nav-link" href="consultas.html">Administración de Usuarios</a></li> </ul> </div> </nav> <!-- INICIO LOGIN--> <div class="modal" tabindex="-1" role="dialog" id="login"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">LOGIN</h5> </div> <div class="modal-body"> <form class="px-4 py-3"> <div class="form-group"> <label>Correo</label> <div class="input-group flex-nowrap"> <div class="input-group-prepend"> <span class="input-group-text" id="addon-wrapping"><i class="fas fa-user-alt"></i></span> </div> <input type="email" class="form-control" id="email" placeholder="[email protected]"> </div> </div> <div class="form-group"> <label>Password</label> <div class="input-group flex-nowrap"> <div class="input-group-prepend"> <span class="input-group-text" id="addon-wrapping"><i class="fas fa-key"></i></span> </div> <input type="password" class="form-control" id="password" placeholder="Password"> </div> </div> <button type="button" class="btn btn-success" data-dismiss="modal">Login</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <hr class="my-4"> <a class="dropdown-item" href="#" data-toggle="modal" data-target="#register" data-dismiss="modal">No tienes cuenta! Registrate aqui</a> </form> </div> </div> </div> </div> <!-- FIN DEL LOGIN--> <!-- INICIO REGISTER--> <div class="modal" tabindex="-1" role="dialog" id="register"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">REGISTER</h5> </div> <div class="modal-body"> <form> <div class="form-row"> <div class="form-group col-6"> <input type="text" class="form-control" id="nombres" placeholder="Nombre o Nombres"> </div> <div class="form-group col-6"> <input type="email" class="form-control" id="correo" placeholder="Tu correo"> </div> </div> <div class="form-group"> <input type="password" class="form-control" id="contraseña" placeholder="Contraseña"> </div> <div class="form-group"> <input type="password" class="form-control" id="confcontraseña" placeholder="Confirmar Contraseña"> </div> <div class="form-group"> <input type="date" class="form-control" id="fecha" placeholder="01/01/200"> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios1" value="option1" checked> <label class="form-check-label" for="exampleRadios1"> Mujer </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios2" value="option2"> <label class="form-check-label" for="exampleRadios2"> Hombre </label> </div> <div class="form-group"> <input type="url" class="form-control" id="url" placeholder="Url de Imagen de Perfil"> </div> <button type="submit" class="btn btn-success">Registrarse</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </form> </div> </div> </div> </div> <!-- FIN DEL REGISTER--> <!--INICIO DETALLES DE USUARIO--> <div class="modify"> <div class="modal-body"> <img src="https://randomuser.me/api/portraits/men/1.jpg" class="rounded-circle"> <a href="#" class="btn btn-primary btn-lg active rounded-circle" role="button" aria-pressed="true" data-toggle="modal" data-target="#borrar3"><i class="fas fa-camera"></i></a> <div class="media-body "> <h5 class="mt-0 mb-1">Jhon Doe</h5> <p>Correo: [email protected]</p> <p>Fecha de Nacimiento: 1/12/2005</p> <p>Sexo: Hombre</p> </div> </div> <div class="modal-body"> <img src="https://randomuser.me/api/portraits/women/40.jpg" class="rounded-circle"> <a href="#" class="btn btn-primary btn-lg active rounded-circle" role="button" aria-pressed="true" data-toggle="modal" data-target="#borrar3"><i class="fas fa-camera"></i></a> <div class="media-body "> <h5 class="mt-0 mb-1">Maria Espinoza</h5> <p>Correo: [email protected]</p> <p>Fecha de Nacimiento: 05/11/2000</p> <p>Sexo: Mujer</p> </div> </div> <div class="modal-body"> <img src="https://randomuser.me/api/portraits/women/82.jpg" class="rounded-circle"> <a href="#" class="btn btn-primary btn-lg active rounded-circle" role="button" aria-pressed="true" data-toggle="modal" data-target="#borrar3"><i class="fas fa-camera"></i></a> <div class="media-body "> <h5 class="mt-0 mb-1">Fernanda Espinoza</h5> <p>Correo: [email protected]</p> <p>Fecha de Nacimiento: 05/06/2007</p> <p>Sexo: Mujer</p> </div> </div> </div> <!--FIN DETALLES DE USUARIO--> <footer> <div class="row"> <div class="col-sm-4 d-flex flex-column" id="redes"> <a href="http://www.facebook.com">Facebook</a> <a href="http://www.youtube.com">Youtube</a> <a href="http://www.instagram.com">Instagram</a> <a href="https://github.com">Github</a> </div> <div class="col-sm-4 d-flex flex-column align-items-end"> <address> <h3>Informacion</h3> <p> Loja, Universidad Nacional de Loja, Ecuador</p> <p> +593993194949</p> <p> [email protected]</p> </address> </div> </div> </footer> <script src="node_modules/jquery/dist/jquery.min.js"></script> <script src="node_modules/popper.js/dist/umd/popper.min.js"></script> <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script> </body> </html>
## --- Day 19: Monster Messages --- You land in an airport surrounded by dense forest. As you walk to your high-speed train, the Elves at the <span title="This is a purely fictional organization. Any resemblance to actual organizations, past or present, is purely coincidental.">Mythical Information Bureau</span> contact you again. They think their satellite has collected an image of a _sea monster_! Unfortunately, the connection to the satellite is having problems, and many of the messages sent back from the satellite have been corrupted. They sent you a list of _the rules valid messages should obey_ and a list of _received messages_ they've collected so far (your puzzle input). The _rules for valid messages_ (the top part of your puzzle input) are numbered and build upon each other. For example: 0: 1 2 1: "a" 2: 1 3 | 3 1 3: "b" Some rules, like `` 3: "b" ``, simply match a single character (in this case, `` b ``). The remaining rules list the sub-rules that must be followed; for example, the rule `` 0: 1 2 `` means that to match rule `` 0 ``, the text being checked must match rule `` 1 ``, and the text after the part that matched rule `` 1 `` must then match rule `` 2 ``. Some of the rules have multiple lists of sub-rules separated by a pipe (`` | ``). This means that _at least one_ list of sub-rules must match. (The ones that match might be different each time the rule is encountered.) For example, the rule `` 2: 1 3 | 3 1 `` means that to match rule `` 2 ``, the text being checked must match rule `` 1 `` followed by rule `` 3 `` _or_ it must match rule `` 3 `` followed by rule `` 1 ``. Fortunately, there are no loops in the rules, so the list of possible matches will be finite. Since rule `` 1 `` matches `` a `` and rule `` 3 `` matches `` b ``, rule `` 2 `` matches either `` ab `` or `` ba ``. Therefore, rule `` 0 `` matches `` aab `` or `` aba ``. Here's a more interesting example: 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" Here, because rule `` 4 `` matches `` a `` and rule `` 5 `` matches `` b ``, rule `` 2 `` matches two letters that are the same (`` aa `` or `` bb ``), and rule `` 3 `` matches two letters that are different (`` ab `` or `` ba ``). Since rule `` 1 `` matches rules `` 2 `` and `` 3 `` once each in either order, it must match two pairs of letters, one pair with matching letters and one pair with different letters. This leaves eight possibilities: `` aaab ``, `` aaba ``, `` bbab ``, `` bbba ``, `` abaa ``, `` abbb ``, `` baaa ``, or `` babb ``. Rule `` 0 ``, therefore, matches `` a `` (rule `` 4 ``), then any of the eight options from rule `` 1 ``, then `` b `` (rule `` 5 ``): `` aaaabb ``, `` aaabab ``, `` abbabb ``, `` abbbab ``, `` aabaab ``, `` aabbbb ``, `` abaaab ``, or `` ababbb ``. The _received messages_ (the bottom part of your puzzle input) need to be checked against the rules so you can determine which are valid and which are corrupted. Including the rules and the messages together, this might look like: 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" ababbb bababa abbbab aaabbb aaaabbb Your goal is to determine _the number of messages that completely match rule `` 0 ``_. In the above example, `` ababbb `` and `` abbbab `` match, but `` bababa ``, `` aaabbb ``, and `` aaaabbb `` do not, producing the answer _`` 2 ``_. The whole message must match all of rule `` 0 ``; there can't be extra unmatched characters in the message. (For example, `` aaaabbb `` might appear to match rule `` 0 `` above, but it has an extra unmatched `` b `` on the end.) _How many messages completely match rule `` 0 ``?_ ## --- Part Two --- As you look over the list of messages, you realize your matching rules aren't quite right. To fix them, completely replace rules `` 8: 42 `` and `` 11: 42 31 `` with the following: 8: 42 | 42 8 11: 42 31 | 42 11 31 This small change has a big impact: now, the rules _do_ contain loops, and the list of messages they could hypothetically match is infinite. You'll need to determine how these changes affect which messages are valid. Fortunately, many of the rules are unaffected by this change; it might help to start by looking at which rules always match the same set of values and how _those_ rules (especially rules `` 42 `` and `` 31 ``) are used by the new versions of rules `` 8 `` and `` 11 ``. (Remember, _you only need to handle the rules you have_; building a solution that could handle any hypothetical combination of rules would be <a href="https://en.wikipedia.org/wiki/Formal_grammar" target="_blank">significantly more difficult</a>.) For example: 42: 9 14 | 10 1 9: 14 27 | 1 26 10: 23 14 | 28 1 1: "a" 11: 42 31 5: 1 14 | 15 1 19: 14 1 | 14 14 12: 24 14 | 19 1 16: 15 1 | 14 14 31: 14 17 | 1 13 6: 14 14 | 1 14 2: 1 24 | 14 4 0: 8 11 13: 14 3 | 1 12 15: 1 | 14 17: 14 2 | 1 7 23: 25 1 | 22 14 28: 16 1 4: 1 1 20: 14 14 | 1 15 3: 5 14 | 16 1 27: 1 6 | 14 18 14: "b" 21: 14 1 | 1 14 25: 1 1 | 1 14 22: 14 14 8: 42 26: 14 22 | 1 20 18: 15 15 7: 14 5 | 1 21 24: 14 1 abbbbbabbbaaaababbaabbbbabababbbabbbbbbabaaaa bbabbbbaabaabba babbbbaabbbbbabbbbbbaabaaabaaa aaabbbbbbaaaabaababaabababbabaaabbababababaaa bbbbbbbaaaabbbbaaabbabaaa bbbababbbbaaaaaaaabbababaaababaabab ababaaaaaabaaab ababaaaaabbbaba baabbaaaabbaaaababbaababb abbbbabbbbaaaababbbbbbaaaababb aaaaabbaabaaaaababaa aaaabbaaaabbaaa aaaabbaabbaaaaaaabbbabbbaaabbaabaaa babaaabbbaaabaababbaabababaaab aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba Without updating rules `` 8 `` and `` 11 ``, these rules only match three messages: `` bbabbbbaabaabba ``, `` ababaaaaaabaaab ``, and `` ababaaaaabbbaba ``. However, after updating rules `` 8 `` and `` 11 ``, a total of _`` 12 ``_ messages match: * `` bbabbbbaabaabba `` * `` babbbbaabbbbbabbbbbbaabaaabaaa `` * `` aaabbbbbbaaaabaababaabababbabaaabbababababaaa `` * `` bbbbbbbaaaabbbbaaabbabaaa `` * `` bbbababbbbaaaaaaaabbababaaababaabab `` * `` ababaaaaaabaaab `` * `` ababaaaaabbbaba `` * `` baabbaaaabbaaaababbaababb `` * `` abbbbabbbbaaaababbbbbbaaaababb `` * `` aaaaabbaabaaaaababaa `` * `` aaaabbaabbaaaaaaabbbabbbaaabbaabaaa `` * `` aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba `` _After updating rules `` 8 `` and `` 11 ``, how many messages completely match rule `` 0 ``?_
import { useState } from 'react'; const initialFriends = [ { id: 118836, name: 'Clark', image: 'https://i.pravatar.cc/48?u=118836', balance: -7, }, { id: 933372, name: 'Sarah', image: 'https://i.pravatar.cc/48?u=933372', balance: 20, }, { id: 499476, name: 'Anthony', image: 'https://i.pravatar.cc/48?u=499476', balance: 0, }, ]; function App() { const [showAddFriend, setShowAddFriend] = useState(false); const [friends, setFriends] = useState(initialFriends); const [selectedFriend, setSelectedFriend] = useState(null); function handleShowAddFriend() { setShowAddFriend((show) => !show); } function handleFormAddFriends(newFriend) { setFriends((friends) => [...friends, newFriend]); setShowAddFriend(false); } function handleSelection(friend) { setSelectedFriend((curr) => (curr?.id == friend.id ? null : friend)); setShowAddFriend(false); } function handleSplitBill(value) { setFriends((friends) => friends.map((friend) => friend.id == selectedFriend.id ? { ...friend, balance: friend.balance + value } : friend ) ); setSelectedFriend(null); } return ( <div className='app'> <div className='sidebar'> <FriendsList friends={friends} selectedFriend={selectedFriend} onSelection={handleSelection} /> {showAddFriend && ( <FormAddFriend onHandleFriend={handleFormAddFriends} /> )} <Button onClick={handleShowAddFriend}> {showAddFriend ? 'Close' : 'Add Friend'} </Button> </div> {selectedFriend && ( <FormSplitBill selectedFriend={selectedFriend} onSplitBill={handleSplitBill} /> )} </div> ); } function FriendsList({ friends, selectedFriend, onSelection }) { return ( <ul> {friends.map((friend) => { return ( <Friend key={friend.id} friend={friend} selectedFriend={selectedFriend} onSelection={onSelection} /> ); })} </ul> ); } function Friend({ friend, selectedFriend, onSelection }) { const { id, name, image, balance } = friend; const isSelected = selectedFriend?.id == id; return ( <li className={`${isSelected ? 'selected' : ''}`}> <img src={image} alt='name' /> <h3>{name}</h3> {balance < 0 && ( <p className='red'> You Owe {name} {balance}$ </p> )} {balance > 0 && ( <p className='green'> {name} owes you {balance} $ </p> )} {balance == 0 && <p>You and {name} are even</p>} <Button onClick={() => onSelection(friend)}> {isSelected ? 'Close' : 'Select'} </Button> </li> ); } function Button({ children, onClick }) { return ( <button onClick={onClick} className='button'> {children} </button> ); } function FormAddFriend({ onHandleFriend }) { const [image, setImage] = useState('https://i.pravatar.cc/48'); const [name, setName] = useState(''); function handleFriendName(e) { setName(e.target.value); } function handleImageURL(e) { setImage(e.target.value); } function onSubmitHandler(e) { e.preventDefault(); if (!name || !image) { return; } const id = crypto.randomUUID(); const newItem = { id, image: `${image}?=${id}`, name, balance: 0, }; onHandleFriend(newItem); setName(''); setImage('https://i.pravatar.cc/48'); } return ( <form onSubmit={onSubmitHandler} action='' className='form-add-friend'> <label htmlFor=''>👯‍♀️Friend Name</label> <input type='text' value={name} onChange={handleFriendName} /> <label htmlFor=''>📷 Image URL</label> <input type='text' value={image} onChange={handleImageURL} /> <Button>Add</Button> </form> ); } function FormSplitBill({ selectedFriend, onSplitBill }) { const { name } = selectedFriend; const [bill, setBill] = useState(''); const [paidByUser, setPaidByUser] = useState(''); const paidByFrnd = bill ? bill - paidByUser : ''; const [whoIsPaying, setWhoIsPaying] = useState('user'); function handleBill(e) { setBill(Number(e.target.value)); } function handleMyExpense(e) { setPaidByUser( Number(e.target.value) > bill ? paidByUser : Number(e.target.value) ); } function onSubmitHandler(e) { e.preventDefault(); if (!bill | !paidByUser) return; onSplitBill(whoIsPaying == 'user' ? paidByFrnd : -paidByUser); } return ( <form className='form-split-bill' onSubmit={onSubmitHandler}> <h2>Split bill with {name}</h2> <label htmlFor=''>💲Bill Value</label> <input type='text' value={bill} onChange={handleBill} /> <label htmlFor=''>🎅 Your Expense</label> <input type='text' value={paidByUser} onChange={handleMyExpense} /> <label htmlFor=''>👯‍♀️{name}'s Expense</label> <input type='text' disabled value={paidByFrnd} /> <label htmlFor=''>🤑 Who's paying the bill</label> <select name='' id='' value={whoIsPaying} onChange={(e) => setWhoIsPaying(e.target.value)} > <option value='user'>You</option> <option value='friend'>{name}</option> </select> <Button>Split Bill</Button> </form> ); } export default App;
--- title: 'Introspecting Conduit v0.13' dateString: 'June 21, 2022' mainImageUrl: '/blogIcons/conduit_logo.png' excerpt: 'Unlimited config power' publisher: 'kon14' publisherPosition: 'Backend Developer' publisherIcon: 'https://avatars.githubusercontent.com/u/1786609?v=4' tags: ['Updates', 'Development','Open source', 'Release'] --- <BlogHeaderComponent title={title} dateString={dateString} mainImageUrl={mainImageUrl} publisher={publisher} publisherIcon={publisherIcon} publisherPosition={publisherPosition} /> Tldr; We added support for database introspection and API client library generation, built a CLI, revamped service discovery, implemented the [gRPC health check protocol](https://github.com/grpc/grpc/blob/master/doc/health-checking.md), introduced new configuration options, pimped up the admin panel and fixed a lot of bugs among other things. <br></br> <SectionItemComponent topic='Database Introspection'/> <p> This release introduces database introspection across both MongoDB and PostgreSQL databases </p> <p> Got an existing project you wish to migrate over? All you gotta do is have Conduit connect to your existing database, bring up the administration panel, head to the Database section and let Conduit take care of it. </p> <br></br> <SectionItemComponent topic='We got a CLI'/> <p> We built a <a href="https://github.com/ConduitPlatform/CLI">cli utility</a> to help people interested in using, or even developing, Conduit stay efficient. </p> <p> We intend to natively package and release it on multiple repos down the line, but for the time being you can <a href="https://www.npmjs.com/package/@conduitplatform/cli">grab it from npm</a> or <a href="https://github.com/ConduitPlatform/CLI">build it yourself</a>. </p> <br></br> <br></br> <SectionItemComponent topic="Module Communication"/> <p> We took a first step towards revamping our service discovery for modules. This is just a the beginning, with way more stability improvements already in queue for upcoming versions. </p> <p> All modules may now be started in any random order and they'll just work as long as their dependencies are eventually brought up. </p> <p> There's now an additional layer of protection available for administrative requests performed through gRPC, where a common private key string is required for said requests to go through. gRPC request protection is entirely optional. To enable it, provide a private key using the`GRPC_KEY` env var value across all of your modules. </p> <p> We also implemented better checks for module availability so that optional features depending on unavailable modules are simply turned off, until their dependencies are online and serving, instead of blocking the entire module from starting. </p> <br></br> <br></br> <SectionItemComponent topic='API Clients & Documentation'/> <p> This release introduces REST/GraphQL API client library generation through the CLI. </p> <p> Swagger route documentation generation for REST APIs has been greatly improved. </p> <br></br> <br></br> <SectionItemComponent topic='Security Changes'/> <p> Security client id/secret pair validation is now optional and disabled out of the box. </p> <p> We still recommend turning this on for production environments, but having it off by default should allow for smoother experimentation. </p> <p> Security clients may now also include aliases and notes. </p> <p> Domain origins are now properly validated for web client types. </p> <br/> <br/> <SectionItemComponent topic='Moar Features'/> <p> We implemented the <a href="https://github.com/grpc/grpc/blob/master/doc/health-checking.md">gRPC health check protocol</a>, meaning you may now find out a module's serving status and even subscribe to updates regarding its health state. </p> <p> Alibaba Cloud (Aliyun) is now supported as a storage provider. Cookie support has been added so that you can authenticate without Authorization headers. </p> <p> Chat invitation notifications have been added, with email and push-notifications support so that users are no longer automatically added to rooms against their will </p> <p> You may now specify on the Authentication module if a user can have multiple active sessions either in general or per client. </p> <p> CRUD operations for custom schemas may now be enabled and configured individually. </p> <p> Admin panel is now approximately 404% sleeker 😎. </p> <br/> Got this far? Well then, YOU are awesome!<br /> Feel free to let us know if there's anything you love or hate about Conduit.<br /> Either way, thanks for sticking around. - 🌟 Give us a star here: https://github.com/ConduitPlatform/Conduit - 👀 See our cool Development roadmap here: https://getconduit.dev/roadmap - 📚 Read the docs here: https://getconduit.dev/docs - 👋 Wanna say hi? Drop a mail here: [email protected] - ✨ Join our discord: https://discord.gg/fBqUQ23M7g
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Codec { static final String NULL_STRING = "null"; // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuilder serializedDataBuilder = new StringBuilder(); if (root == null) { return NULL_STRING; } appendNode(serializedDataBuilder, root); return serializedDataBuilder.toString(); } public String appendNode(StringBuilder result, TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node == null) { result.append("null"); result.append(","); } else { result.append(Integer.valueOf(node.val)); result.append(","); queue.add(node.left); queue.add(node.right); } } int endIndex = 0; for(int i =result.length()-1; i >= 0; i--){ if(result.charAt(i) >= '0' && result.charAt(i) <= '9'){ endIndex = i+1; break; } } String r = result.substring(0, endIndex).toString(); return r; } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data == null || data.length() == 0) return null; String[] dataSplit = data.split(","); TreeNode root = deserializeData(dataSplit); return root; } public TreeNode deserializeData(String[] data) { List<TreeNode> nodesList = new ArrayList<TreeNode>(); TreeNode root = null; int index = 0; while (index <= (data.length - 1) / 2) { TreeNode node = null; TreeNode left = null; TreeNode right = null; if (index < nodesList.size()) { node = nodesList.get(index); } else { if (!data[index].equals(NULL_STRING)) { node = new TreeNode(Integer.parseInt(data[index])); } nodesList.add(node); } if (((2 * index) + 1) < nodesList.size()) { left = nodesList.get((2 * index) + 1); } else { if (((2 * index) + 1 < data.length)) { if (!data[(2 * index) + 1].equals(NULL_STRING)) { left = new TreeNode(Integer.parseInt(data[(2 * index) + 1])); nodesList.add(left); } } } if ((2 * index) + 2 < nodesList.size()) { right = nodesList.get((2 * index) + 2); } else { if (((2 * index) + 2 < data.length)) { if (!data[(2 * index) + 2].equals(NULL_STRING)) { right = new TreeNode(Integer.parseInt(data[(2 * index) + 2])); nodesList.add(right); } } } if (root == null) { root = node; } if (node != null) { node.left = left; node.right = right; } index++; } return root; } }
<p align="center"> <img src="https://miro.medium.com/v2/resize:fit:4800/format:webp/1*yYAypHYu_kEGbc-BreWzkw.png" alt="Firedancer Node Visual Guide"> </p> # Firedancer Node Deployment Guide **Firedancer is early stage software and should only be deployed on testnet / devnet now. Please do not deploy on mainnet yet.** ## Overview This guide provides instructions for deploying Firedancer nodes using Ansible. Ansible is an open-source automation tool that can be used for configuration management and application deployment. ## Pre-requisites Before running the playbook, ensure you have the following: - Ansible installed on your system. - A static public IP address. - Ports 8000 to 8020 available and open for communication on your network firewall and router. ## Running the Playbook ### Deployment on a Remote Host To deploy the Firedancer node on a remote host, use the following command, replacing `<ip-address>` with the IP address of your target machine: ```shell ansible-playbook master.yml -i '<ip-address>,' -u ubuntu -K ``` ### Deployment on Localhost If you're deploying on the same machine where Ansible is installed, use `localhost`: ```shell ansible-playbook master.yml -i 'localhost,' -u ubuntu -K ``` ## Customizing the Playbook The `master.yml` playbook includes several tasks that can be enabled or disabled according to your needs. By default, some of these tasks are commented out to prevent execution. You can uncomment any task to enable it or comment it out to skip it during the run. Here is a brief overview of the tasks within `master-playbook.yml`: ### Available Tasks - **System Update and Upgrade**: (Commented out by default) Ensures your system is up to date. - **Disk Setup**: (Commented out by default) Configures disk partitioning. - **Deploy Firedancer**: Deploys the Firedancer application. - **Install Solana CLI**: Installs the Solana Command Line Interface tools. - **Keys and Airdrop**: (Commented out by default) Manages Solana keys and performs an airdrop. ### Customizing Tasks To enable or disable a task, simply comment or uncomment the relevant lines in the `master.yml` file. For instance, to disable the Disk Setup task, ensure it is commented out as follows: ```yaml #- name: Set up Disks # import_playbook: ./playbooks/disk-setup.yml ``` To enable it, remove the `#`: ```yaml - name: Set up Disks import_playbook: ./playbooks/disk-setup.yml ``` Repeat this process for any other tasks you wish to customize. Please note that disk partitioning is specific to our hardware configuration; review and edit as necessary to suit your environment. ## Support For assistance or to report issues with the playbook, please reach out to the support team or open an issue.
package com.bupt.hospital.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.format.annotation.NumberFormat; import org.springframework.lang.Nullable; import javax.validation.constraints.NotNull; /** * * @author zyq * @TableName t_patient */ @TableName(value ="t_patient") @Data @NoArgsConstructor public class Patient implements Serializable, User { @TableId(type = IdType.AUTO) @Nullable private Integer userId; @NotNull(message = "用户名不能为空!") private String userName; @NotNull(message = "密码不能为空!") private String password; @NotNull(message = "身份证不能为空!") private String idNumber; @NotNull(message = "姓名不能为空!") private String name; @NotNull(message = "年龄不能为空!") private Integer age; @NotNull(message = "性别不能为空!") private String gender; @NotNull(message = "居住地址不能为空!") private String address; @NotNull(message = "联系方式不能为空!") private String contact; @Nullable private String medicalRecord; @Nullable private int authorized; @TableField(exist = false) private static final long serialVersionUID = 1L; }
const AppError = require("./appError"); const httpStatus = require("http-status"); /** * An error that occurred when executing a database * query isn't successful. */ class DatabaseError extends AppError { /** * Constructor. * @param {string | undefined} message Error message. * @param {boolean} isFatal Indicates whether the application should terminate * if this error is thrown. */ constructor(message, isFatal) { super(httpStatus.INTERNAL_SERVER_ERROR, message, isFatal); this.name = this.constructor.name; } } module.exports = DatabaseError;
import sys from typing import List, Optional if sys.version_info >= (3, 8): from typing import TypedDict else: from typing_extensions import TypedDict from localstack.aws.api import RequestContext, ServiceException, ServiceRequest, handler MaxResults = int NextToken = str PageSize = int Qos = int Retain = bool ShadowName = str ThingName = str Topic = str errorMessage = str class ConflictException(ServiceException): """The specified version does not match the version of the document.""" message: Optional[errorMessage] class InternalFailureException(ServiceException): """An unexpected error has occurred.""" message: Optional[errorMessage] class InvalidRequestException(ServiceException): """The request is not valid.""" message: Optional[errorMessage] class MethodNotAllowedException(ServiceException): """The specified combination of HTTP verb and URI is not supported.""" message: Optional[errorMessage] class RequestEntityTooLargeException(ServiceException): """The payload exceeds the maximum size allowed.""" message: Optional[errorMessage] class ResourceNotFoundException(ServiceException): """The specified resource does not exist.""" message: Optional[errorMessage] class ServiceUnavailableException(ServiceException): """The service is temporarily unavailable.""" message: Optional[errorMessage] class ThrottlingException(ServiceException): """The rate exceeds the limit.""" message: Optional[errorMessage] class UnauthorizedException(ServiceException): """You are not authorized to perform this operation.""" message: Optional[errorMessage] class UnsupportedDocumentEncodingException(ServiceException): """The document encoding is not supported.""" message: Optional[errorMessage] class DeleteThingShadowRequest(ServiceRequest): """The input for the DeleteThingShadow operation.""" thingName: ThingName shadowName: Optional[ShadowName] JsonDocument = bytes class DeleteThingShadowResponse(TypedDict, total=False): """The output from the DeleteThingShadow operation.""" payload: JsonDocument class GetRetainedMessageRequest(ServiceRequest): """The input for the GetRetainedMessage operation.""" topic: Topic Timestamp = int Payload = bytes class GetRetainedMessageResponse(TypedDict, total=False): """The output from the GetRetainedMessage operation.""" topic: Optional[Topic] payload: Optional[Payload] qos: Optional[Qos] lastModifiedTime: Optional[Timestamp] class GetThingShadowRequest(ServiceRequest): """The input for the GetThingShadow operation.""" thingName: ThingName shadowName: Optional[ShadowName] class GetThingShadowResponse(TypedDict, total=False): """The output from the GetThingShadow operation.""" payload: Optional[JsonDocument] class ListNamedShadowsForThingRequest(ServiceRequest): thingName: ThingName nextToken: Optional[NextToken] pageSize: Optional[PageSize] NamedShadowList = List[ShadowName] class ListNamedShadowsForThingResponse(TypedDict, total=False): results: Optional[NamedShadowList] nextToken: Optional[NextToken] timestamp: Optional[Timestamp] class ListRetainedMessagesRequest(ServiceRequest): nextToken: Optional[NextToken] maxResults: Optional[MaxResults] PayloadSize = int class RetainedMessageSummary(TypedDict, total=False): """Information about a single retained message.""" topic: Optional[Topic] payloadSize: Optional[PayloadSize] qos: Optional[Qos] lastModifiedTime: Optional[Timestamp] RetainedMessageList = List[RetainedMessageSummary] class ListRetainedMessagesResponse(TypedDict, total=False): retainedTopics: Optional[RetainedMessageList] nextToken: Optional[NextToken] class PublishRequest(ServiceRequest): """The input for the Publish operation.""" topic: Topic qos: Optional[Qos] retain: Optional[Retain] payload: Optional[Payload] class UpdateThingShadowRequest(ServiceRequest): """The input for the UpdateThingShadow operation.""" thingName: ThingName shadowName: Optional[ShadowName] payload: JsonDocument class UpdateThingShadowResponse(TypedDict, total=False): """The output from the UpdateThingShadow operation.""" payload: Optional[JsonDocument] class IotDataApi: service = "iot-data" version = "2015-05-28" @handler("DeleteThingShadow") def delete_thing_shadow( self, context: RequestContext, thing_name: ThingName, shadow_name: ShadowName = None ) -> DeleteThingShadowResponse: """Deletes the shadow for the specified thing. Requires permission to access the `DeleteThingShadow <https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions>`__ action. For more information, see `DeleteThingShadow <http://docs.aws.amazon.com/iot/latest/developerguide/API_DeleteThingShadow.html>`__ in the IoT Developer Guide. :param thing_name: The name of the thing. :param shadow_name: The name of the shadow. :returns: DeleteThingShadowResponse :raises ResourceNotFoundException: :raises InvalidRequestException: :raises ThrottlingException: :raises UnauthorizedException: :raises ServiceUnavailableException: :raises InternalFailureException: :raises MethodNotAllowedException: :raises UnsupportedDocumentEncodingException: """ raise NotImplementedError @handler("GetRetainedMessage") def get_retained_message( self, context: RequestContext, topic: Topic ) -> GetRetainedMessageResponse: """Gets the details of a single retained message for the specified topic. This action returns the message payload of the retained message, which can incur messaging costs. To list only the topic names of the retained messages, call `ListRetainedMessages </iot/latest/developerguide/API_iotdata_ListRetainedMessages.html>`__. Requires permission to access the `GetRetainedMessage <https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiotfleethubfordevicemanagement.html#awsiotfleethubfordevicemanagement-actions-as-permissions>`__ action. For more information about messaging costs, see `Amazon Web Services IoT Core pricing - Messaging <http://aws.amazon.com/iot-core/pricing/#Messaging>`__. :param topic: The topic name of the retained message to retrieve. :returns: GetRetainedMessageResponse :raises InvalidRequestException: :raises ResourceNotFoundException: :raises ThrottlingException: :raises UnauthorizedException: :raises ServiceUnavailableException: :raises InternalFailureException: :raises MethodNotAllowedException: """ raise NotImplementedError @handler("GetThingShadow") def get_thing_shadow( self, context: RequestContext, thing_name: ThingName, shadow_name: ShadowName = None ) -> GetThingShadowResponse: """Gets the shadow for the specified thing. Requires permission to access the `GetThingShadow <https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions>`__ action. For more information, see `GetThingShadow <http://docs.aws.amazon.com/iot/latest/developerguide/API_GetThingShadow.html>`__ in the IoT Developer Guide. :param thing_name: The name of the thing. :param shadow_name: The name of the shadow. :returns: GetThingShadowResponse :raises InvalidRequestException: :raises ResourceNotFoundException: :raises ThrottlingException: :raises UnauthorizedException: :raises ServiceUnavailableException: :raises InternalFailureException: :raises MethodNotAllowedException: :raises UnsupportedDocumentEncodingException: """ raise NotImplementedError @handler("ListNamedShadowsForThing") def list_named_shadows_for_thing( self, context: RequestContext, thing_name: ThingName, next_token: NextToken = None, page_size: PageSize = None, ) -> ListNamedShadowsForThingResponse: """Lists the shadows for the specified thing. Requires permission to access the `ListNamedShadowsForThing <https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions>`__ action. :param thing_name: The name of the thing. :param next_token: The token to retrieve the next set of results. :param page_size: The result page size. :returns: ListNamedShadowsForThingResponse :raises ResourceNotFoundException: :raises InvalidRequestException: :raises ThrottlingException: :raises UnauthorizedException: :raises ServiceUnavailableException: :raises InternalFailureException: :raises MethodNotAllowedException: """ raise NotImplementedError @handler("ListRetainedMessages") def list_retained_messages( self, context: RequestContext, next_token: NextToken = None, max_results: MaxResults = None ) -> ListRetainedMessagesResponse: """Lists summary information about the retained messages stored for the account. This action returns only the topic names of the retained messages. It doesn't return any message payloads. Although this action doesn't return a message payload, it can still incur messaging costs. To get the message payload of a retained message, call `GetRetainedMessage <https://docs.aws.amazon.com/iot/latest/developerguide/API_iotdata_GetRetainedMessage.html>`__ with the topic name of the retained message. Requires permission to access the `ListRetainedMessages <https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiotfleethubfordevicemanagement.html#awsiotfleethubfordevicemanagement-actions-as-permissions>`__ action. For more information about messaging costs, see `Amazon Web Services IoT Core pricing - Messaging <http://aws.amazon.com/iot-core/pricing/#Messaging>`__. :param next_token: To retrieve the next set of results, the ``nextToken`` value from a previous response; otherwise **null** to receive the first set of results. :param max_results: The maximum number of results to return at one time. :returns: ListRetainedMessagesResponse :raises InvalidRequestException: :raises ThrottlingException: :raises UnauthorizedException: :raises ServiceUnavailableException: :raises InternalFailureException: :raises MethodNotAllowedException: """ raise NotImplementedError @handler("Publish") def publish( self, context: RequestContext, topic: Topic, qos: Qos = None, retain: Retain = None, payload: Payload = None, ) -> None: """Publishes an MQTT message. Requires permission to access the `Publish <https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions>`__ action. For more information about MQTT messages, see `MQTT Protocol <http://docs.aws.amazon.com/iot/latest/developerguide/mqtt.html>`__ in the IoT Developer Guide. For more information about messaging costs, see `Amazon Web Services IoT Core pricing - Messaging <http://aws.amazon.com/iot-core/pricing/#Messaging>`__. :param topic: The name of the MQTT topic. :param qos: The Quality of Service (QoS) level. :param retain: A Boolean value that determines whether to set the RETAIN flag when the message is published. :param payload: The message body. :raises InternalFailureException: :raises InvalidRequestException: :raises UnauthorizedException: :raises MethodNotAllowedException: """ raise NotImplementedError @handler("UpdateThingShadow") def update_thing_shadow( self, context: RequestContext, thing_name: ThingName, payload: JsonDocument, shadow_name: ShadowName = None, ) -> UpdateThingShadowResponse: """Updates the shadow for the specified thing. Requires permission to access the `UpdateThingShadow <https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions>`__ action. For more information, see `UpdateThingShadow <http://docs.aws.amazon.com/iot/latest/developerguide/API_UpdateThingShadow.html>`__ in the IoT Developer Guide. :param thing_name: The name of the thing. :param payload: The state information, in JSON format. :param shadow_name: The name of the shadow. :returns: UpdateThingShadowResponse :raises ConflictException: :raises RequestEntityTooLargeException: :raises InvalidRequestException: :raises ThrottlingException: :raises UnauthorizedException: :raises ServiceUnavailableException: :raises InternalFailureException: :raises MethodNotAllowedException: :raises UnsupportedDocumentEncodingException: """ raise NotImplementedError
<?php namespace App\Http\Requests; use App\Models\File; use App\Models\User; use Illuminate\Foundation\Http\FormRequest; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class AccessRightsRequest extends ApiFormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { $file = File::where(['id' => $this->route('id')])->first() ?? throw new NotFoundHttpException(); /** @var User $user */ $user = $this->user(); return $user->id == $file->user_id; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ 'email' => 'required|email|exists:App\Models\User,email' ]; } }
import { TestBed } from '@angular/core/testing'; import { provideRouter, withComponentInputBinding } from '@angular/router'; import { RouterTestingHarness, RouterTestingModule } from '@angular/router/testing'; import { of } from 'rxjs'; import { LocalisationDetailComponent } from './localisation-detail.component'; describe('Localisation Management Detail Component', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [LocalisationDetailComponent, RouterTestingModule.withRoutes([], { bindToComponentInputs: true })], providers: [ provideRouter( [ { path: '**', component: LocalisationDetailComponent, resolve: { localisation: () => of({ id: 'ABC' }) }, }, ], withComponentInputBinding() ), ], }) .overrideTemplate(LocalisationDetailComponent, '') .compileComponents(); }); describe('OnInit', () => { it('Should load localisation on init', async () => { const harness = await RouterTestingHarness.create(); const instance = await harness.navigateByUrl('/', LocalisationDetailComponent); // THEN expect(instance.localisation).toEqual(expect.objectContaining({ id: 'ABC' })); }); }); });
import '../custom.css'; import { Link } from 'react-router-dom'; import React, { useState, useEffect } from 'react'; // import { useHistory } from 'react-router-dom'; const entry = { id: "", firstName: "", lastName: "", department: "", className: "", gender: "", age: "", graduated: "" } export default function Edit (props) { const[data, setData] = useState({}); const[graduated, setGender] = useState(0); const[gender, setGraduated] = useState(false); const[age, setAge] = useState(18); const[id, setId] = useState(); const editStudent = () => { console.log("The Edited Student Is: ", entry) fetch("api/student/"+id, { method: "PUT", body:JSON.stringify(entry), headers:{ "content-type": "application/json" } }).then(r=>{ console.log("Response from backend for editting new student", r) window.location = "/" }).catch(e=>console.log("Error Editing new student: ", e)) } const editedData = (e) => { const name = e.target.name; let val = e.target.value if(name === "gender"){ val = Number(val) setGender(val) } if(name === "age"){ val = Number(val) setAge(val) } if(name === "graduated"){ val = val === "1" //if 1 then true setGraduated(val) } entry[name] = val console.log("The Edited Student Is:", entry) } const ageOptions = []; for (let age = 17; age <= 120; age++) { ageOptions.push(<option value={age}>{age}</option>); } useEffect(()=>{ let id_val = window.location.search if (id_val){ id_val = id_val.split("=")[1] setId(id_val) fetch("api/student/"+id_val) .then(r => r.json()) .then(d => { setData(d); setGender(d.gender); setGraduated(d.graduated); setAge(d.age); console.log("the students are: ", d); }) .catch(e => console.log("the error getting student to update: ", e)) } }) return ( <section className="m-20"> <h1>Edit Student</h1> <div> <label htmlFor="fn">First Name</label> <input type="text" name="firstName" id="fn" defaultValue={data.firstName} onChange={editedData}/> </div> <div> <label htmlFor="ln">Last Name</label> <input type="text" name="lastName" id="ln" defaultValue={data.lastName} onChange={editedData}/> </div> <div> <label htmlFor="dp">Department</label> <input type="text" name="department" id="dp" defaultValue={data.department} onChange={editedData}/> </div> <div> <label htmlFor="cn">Class Name</label> <input type="text" name="className" id="cn" defaultValue={data.className} onChange={editedData}/> </div> <div> <label htmlFor="gender">Gender</label> <select name="gender" id="gender" defaultValue={gender} onChange={editedData}> <option value={1}>Male</option> <option value={0}>Female</option> </select> </div> <div> <label htmlFor="age">Age</label> <select type="text" name="age" id="age" defaultValue={age} onChange={editedData}> {ageOptions} </select> </div> <div> <label htmlFor="graduated">Graduated</label> <select name="graduated" id="graduated" defaultValue={graduated} onChange={editedData}> <option value={true}>Yed</option> <option value={false}>No</option> </select> </div> <div className='add-cencel-new-btn'> <Link to="/" className="cancel-btn">Cancel</Link> <button className="add-btn" onClick={editStudent}>Edit Student</button> </div> </section> ) }
/* * Copyright 2015 Persinity Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.persinity.ndt.etlmodule.relational.migrate; import static com.persinity.common.StringUtils.format; import static com.persinity.common.invariant.Invariant.assertArg; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.junit.After; import org.junit.Before; import com.persinity.common.Config; import com.persinity.common.Resource; import com.persinity.common.db.RelDb; import com.persinity.ndt.db.RelDbPoolFactory; import com.persinity.ndt.etlmodule.relational.common.TestDm; /** * Base migrate integration test. * * @author Ivan Dachev */ public abstract class BaseMigrateIT { @Before public void setUp() { relDbPoolFactory = new RelDbPoolFactory(ETL_IT_PROPERTIES); // init test bed schemas resource.accessAndClose(new Resource.Accessor<RelDb, Void>(relDbPoolFactory.appBridge().src().get(), null) { @Override public Void access(final RelDb resource) throws Exception { resource.executeScript("testapp-init.sql"); return null; } }); resource.accessAndClose(new Resource.Accessor<RelDb, Void>(relDbPoolFactory.appBridge().dst().get(), null) { @Override public Void access(final RelDb resource) throws Exception { resource.executeScript("testapp-init.sql"); return null; } }); windowSize = Integer.parseInt(Config.loadPropsFrom(ETL_IT_PROPERTIES).getProperty("window.size")); assertArg(windowSize > 0); testMigrate = new TestMigrate(relDbPoolFactory, windowSize); } @After public void tearDown() { testMigrate.close(); relDbPoolFactory.close(); } /** * Tests one ETL transfer over accumulated data of two transactions, using small set of parallel ETL Instructions */ public void testOnceWithTwoTrans() { final List<String> sqlBatch1 = new LinkedList<>(); sqlBatch1.add("INSERT INTO dept (id, name) VALUES (1, 'Eng')"); sqlBatch1.add("INSERT INTO emp (id, bin_id, name, dept_id) VALUES (1, utl_raw.cast_to_raw('Ivan'), 'Ivan', 1)"); sqlBatch1 .add("INSERT INTO emp (id, bin_id, name, dept_id) VALUES (2, utl_raw.cast_to_raw('Doichin'), 'Doichin', 1)"); sqlBatch1.add("INSERT INTO emp (id, name, dept_id) VALUES (3, 'Rosen', 1)"); sqlBatch1.add("INSERT INTO emp (id, name, dept_id) VALUES (4, 'Ivo Yanakiev', 1)"); sqlBatch1.add("UPDATE dept SET mngr_id = 1 WHERE id = 1"); sqlBatch1.add("INSERT INTO dept (id, name) VALUES (2, 'FreeLancer')"); sqlBatch1.add("INSERT INTO emp (id, name, dept_id) VALUES (5, 'Bozhidar', 2)"); sqlBatch1.add("INSERT INTO emp (id, name, dept_id) VALUES (6, 'Ralitza', 2)"); sqlBatch1.add("UPDATE dept SET mngr_id = 5 WHERE id = 2"); sqlBatch1.add("INSERT INTO kid (id, sid, name, emp_id) VALUES (1, 's4', 'DoichinKid', 2)"); sqlBatch1.add("INSERT INTO kid (id, sid, name, emp_id) VALUES (1, 's6', 'IvoKids6', 4)"); sqlBatch1.add("INSERT INTO kid (id, sid, name, emp_id) VALUES (1, 's3', 'IvoKids2', 4)"); final List<String> sqlBatch2 = new LinkedList<>(); sqlBatch2.add("UPDATE dept SET mngr_id = NULL WHERE mngr_id = 5"); sqlBatch2.add("DELETE FROM emp WHERE id = 5"); sqlBatch2.add("DELETE FROM emp WHERE id = 6"); sqlBatch2.add("DELETE FROM dept WHERE id = 2"); sqlBatch2.add("UPDATE emp SET name = 'Ivan Dachev', bin_id = utl_raw.cast_to_raw('Ivan Dachev') WHERE id = 1"); sqlBatch2 .add("UPDATE emp SET name = 'Doichin Yordanov', bin_id = utl_raw.cast_to_raw('Doichin Yordanov') WHERE id = 2"); sqlBatch2.add("UPDATE kid SET name = 'Mia Yordanova' WHERE id = 1 AND sid = 's4'"); sqlBatch2.add("UPDATE dept SET mngr_id = 4 WHERE id = 1"); sqlBatch2.add("DELETE FROM emp WHERE id = 3"); sqlBatch2.add("INSERT INTO dept (id, name) VALUES (3, 'Sales')"); sqlBatch2.add("INSERT INTO emp (id, name, dept_id) VALUES (10, 'Vladi Goranov', 3)"); sqlBatch2.add("INSERT INTO emp (id, name, dept_id) VALUES (11, 'Boyko Asenov', 3)"); sqlBatch2.add("INSERT INTO kid (id, sid, name, emp_id) VALUES (2, 's54', 'VladiKid', 10)"); sqlBatch2.add("INSERT INTO kid (id, sid, name, emp_id) VALUES (4, 's54', 'BoykoKid', 11)"); sqlBatch2.add("DELETE FROM kid WHERE (id = 1) AND (sid = 's6')"); execute(getSrcPopulateSqlBatches(), getInitialTransferSqlBatches(), getPreConsSqlBatches(), Arrays.asList(sqlBatch1, sqlBatch2), 2); } /** * Tests one ETL transfer over accumulated data of two transactions, using bulk ETL Instruction to transfer changes * for all records at once. */ public void testOnceWithTwoTransBigEtlInstr() { final List<String> sqlBatch1 = new LinkedList<>(); sqlBatch1.add("INSERT INTO dept (id, name) VALUES (1, 'SW')"); sqlBatch1.add("INSERT INTO emp (id, name, dept_id) VALUES (1, 'Ivan', 1)"); sqlBatch1.add("INSERT INTO emp (id, name, dept_id) VALUES (2, 'Doichin', 1)"); sqlBatch1.add("INSERT INTO emp (id, name, dept_id) VALUES (3, 'Rosen', 1)"); final List<String> sqlBatch2 = new LinkedList<>(); sqlBatch2.add("UPDATE emp SET name = 'Ivan Dachev' WHERE id = 1"); sqlBatch2.add("UPDATE emp SET name = 'Doichin Yordanov' WHERE id = 2"); sqlBatch2.add("DELETE FROM emp WHERE id = 3"); execute(getSrcPopulateSqlBatches(), getInitialTransferSqlBatches(), getPreConsSqlBatches(), Arrays.asList(sqlBatch1, sqlBatch2), 10); } /** * Tests one ETL transfer over accumulated data of several windows. */ public void testOnceWithSeveralWindowsBigEtlInstr() { final List<String> sqlBatch1 = new LinkedList<>(); sqlBatch1.add("INSERT INTO dept (id, name) VALUES (1, 'SW')"); sqlBatch1.add("INSERT INTO emp (id, name, dept_id) VALUES (1, 'Ivan', 1)"); sqlBatch1.add("INSERT INTO emp (id, name, dept_id) VALUES (2, 'Doichin', 1)"); sqlBatch1.add("INSERT INTO emp (id, name, dept_id) VALUES (3, 'Rosen', 1)"); final List<String> sqlBatch2 = new LinkedList<>(); sqlBatch2.add("UPDATE emp SET name = 'Ivan Dachev' WHERE id = 1"); sqlBatch2.add("UPDATE emp SET name = 'Doichin Yordanov' WHERE id = 2"); sqlBatch2.add("DELETE FROM emp WHERE id = 3"); sqlBatch2.add("INSERT INTO kid (id, sid, name, emp_id) VALUES (1, 's7', 'IvanKid', 1)"); ArrayList<List<String>> sqlBatches = new ArrayList<>(); sqlBatches.add(sqlBatch1); sqlBatches.add(sqlBatch2); int j = 0; for (int i = 0; i < windowSize * 3; i++) { final List<String> sqlBatch = new LinkedList<>(); if (j == 1) { sqlBatch.add("INSERT INTO emp (id, name, dept_id) VALUES (4, 'Petkan', 1)"); sqlBatch.add("INSERT INTO kid (id, sid, name, emp_id) VALUES (2, 's7', 'IvanKid', 1)"); } else if (j == 2) { sqlBatch.add("DELETE FROM emp WHERE id = 4"); sqlBatch.add("DELETE FROM kid WHERE (id = 2) AND (sid = 's7')"); } else if (j == 3) { j = 0; } j++; sqlBatch.add(format("UPDATE emp SET name = 'Ivan Dachev {}' WHERE id = 1", i)); sqlBatch.add(format("UPDATE emp SET name = 'Doichin Yordanov {}' WHERE id = 2", i)); sqlBatch.add(format("UPDATE kid SET name = 'IvanKid {}' WHERE (id = 1) AND (sid = 's7')", i)); sqlBatches.add(sqlBatch); } execute(getSrcPopulateSqlBatches(), getInitialTransferSqlBatches(), getPreConsSqlBatches(), sqlBatches, 10); } /** * Tests one ETL transfer over no accumulated data */ public void testOnceWithZeroTrans() { final List<String> sqlEmptyBatch = Collections.emptyList(); execute(getSrcPopulateSqlBatches(), getSrcPopulateSqlBatches(), Collections.singletonList(sqlEmptyBatch), Collections.singletonList(sqlEmptyBatch), 2); } /** * @param srcPopulateSqlBatches * @param initialSqlBatches * for initial transfer * @param preConsistentSqlBatches * changes accumulated during initial transfer * @param deltaSqlBatches * deltas * @param etlInstructionSize * ETL instruction size to be used */ public abstract void execute(final List<List<String>> srcPopulateSqlBatches, final List<List<String>> initialSqlBatches, final List<List<String>> preConsistentSqlBatches, final List<List<String>> deltaSqlBatches, final int etlInstructionSize); public RelDbPoolFactory getRelDbPoolFactory() { return relDbPoolFactory; } public TestMigrate getTestMigrate() { return testMigrate; } public TestDm getTestDm() { return testMigrate.getTestDm(); } public int getWindowSize() { return windowSize; } private List<List<String>> getSrcPopulateSqlBatches() { final String srcPopulateSql1 = "INSERT INTO dept (id, name) VALUES (100, 'Initial Dpt')"; final List<String> srcPopulateSqlBatch = Arrays.asList(srcPopulateSql1); final List<List<String>> srcPopulateSqlBatches = Arrays.asList(srcPopulateSqlBatch); return srcPopulateSqlBatches; } /** * @return Inconsistent batch changes recorded during initial transfer that * contradict the end state of the initial transfer when applied after it */ private List<List<String>> getPreConsSqlBatches() { // Note that the initial sql batch ends with no dept 100, hence the contradiction final String preConsSql1 = "INSERT INTO emp (id, name, dept_id) VALUES (101, 'Initial emp1', 100)"; final String preConsSql2 = "INSERT INTO emp (id, name, dept_id) VALUES (102, 'Initial emp2', 100)"; final List<String> preConsSqlBatch1 = Arrays.asList(preConsSql1, preConsSql2); final String preConsSql3 = "DELETE FROM emp WHERE id = 101"; final String preConsSql4 = "DELETE FROM emp WHERE id = 102"; final String preConsSql5 = "DELETE FROM dept WHERE id = 100"; final List<String> preConsSqlBatch2 = Arrays.asList(preConsSql3, preConsSql4, preConsSql5); final List<List<String>> preConsSqlBatches = Arrays.asList(preConsSqlBatch1, preConsSqlBatch2); return preConsSqlBatches; } /** * @return Batch of consistent changes exported during initial transfer */ private List<List<String>> getInitialTransferSqlBatches() { final List<List<String>> result = new LinkedList<>(getSrcPopulateSqlBatches()); result.addAll(getPreConsSqlBatches()); return result; } public static final String ETL_IT_PROPERTIES = "etl-it.properties"; protected TestMigrate testMigrate; private int windowSize; private RelDbPoolFactory relDbPoolFactory; private final Resource resource = new Resource(); }
import React, { useState } from 'react' import { useNavigate } from 'react-router-dom' import './paginaCadastro.css' import { Box, Button, FormControl, IconButton, InputAdornment, InputLabel, OutlinedInput, TextField, Typography, } from '@mui/material' import NewUserModal from './Modal' import { Visibility, VisibilityOff } from '@mui/icons-material' import { createUser } from '../../services/backend' const PaginaCadastro = () => { const navigate = useNavigate() const [showPassword, setShowPassword] = useState(false) const [confimShowPassword, setConfirmShowPassword] = useState(false) const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [confirmPassword, setConfirmPassword] = useState('') const [userModal, setUserModal] = useState(false) const newUser = { email, password, confirmPassword } const newRegister = async () => { const response = await createUser(newUser) if (response.status === 201) { setUserModal(true) } } const handleClickShowPassword = () => setShowPassword((show) => !show) const handleClickConfirmShowPassword = () => setConfirmShowPassword((show) => !show) const handleMouseDownPassword = (event) => { event.preventDefault() } const handleSubmit = (e) => { e.preventDefault() setEmail('') setPassword('') setConfirmPassword('') } return ( <> <Box sx={{ background: 'linear-gradient(rgb(76, 168, 255), rgb(18, 1, 173))', }} display={'flex'} justifyContent="center" width={'100%'} height={'100vh'} component={'form'} onSubmit={handleSubmit} > <Box bgcolor={'#fff'} borderRadius={'8px'} width={'400px'} height={'500px'} border={'2px solid blue'} display={'flex'} flexDirection={'column'} alignItems={'center'} padding={'20px'} marginTop={'40px'} > <Typography fontSize={'2em'} fontFamily={'sans-serif'}> Cadastre-se </Typography> <Box height={'300px'} width={'100%'} display={'flex'} flexDirection={'column'} justifyContent={'space-around'} > <FormControl fullWidth variant="outlined"> <TextField value={email} onChange={(e) => setEmail(e.target.value)} id="outlined-basic" label="Email" variant="outlined" /> </FormControl> <FormControl fullWidth variant="outlined"> <InputLabel htmlFor="outlined-basic">Senha</InputLabel> <OutlinedInput value={password} onChange={(e) => setPassword(e.target.value)} name="outlined-basic" id="outlined-adornment-password" type={showPassword ? 'text' : 'password'} endAdornment={ <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleClickShowPassword} onMouseDown={handleMouseDownPassword} edge="end" > {showPassword ? <VisibilityOff /> : <Visibility />} </IconButton> </InputAdornment> } label="Password" /> </FormControl> <FormControl fullWidth variant="outlined"> <InputLabel htmlFor="outlined-basic"> Confirme sua senha </InputLabel> <OutlinedInput value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} name="outlined-basic" id="confirm-outlined-adornment-password" type={confimShowPassword ? 'text' : 'password'} endAdornment={ <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleClickConfirmShowPassword} onMouseDown={handleMouseDownPassword} edge="end" > {confimShowPassword ? <VisibilityOff /> : <Visibility />} </IconButton> </InputAdornment> } label="Password" /> </FormControl> <Button onClick={newRegister} type="submit" variant="contained"> Cadastrar </Button> </Box> </Box> </Box> <NewUserModal open={userModal} setUserModal={setUserModal} /> </> ) } export default PaginaCadastro
#include <assert.h> #include <ctype.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char* readline(); char* ltrim(char*); char* rtrim(char*); int parse_int(char*); /* * Complete the 'timeInWords' function below. * * The function is expected to return a STRING. * The function accepts following parameters: * 1. INTEGER h * 2. INTEGER m */ /* * To return the string from the function, you should either do static allocation or dynamic allocation * * For example, * char* return_string_using_static_allocation() { * static char s[] = "static allocation of string"; * * return s; * } * * char* return_string_using_dynamic_allocation() { * char* s = malloc(100 * sizeof(char)); * * s = "dynamic allocation of string"; * * return s; * } * */ char* timeInWords(int h, int m) { char *str = calloc(100, 1); char numbers[31][20] = {"emphty","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","quarter","sixteen","seventeen","eighteen","nineteen","twenty","twenty one","twenty two","twenty three","twenty four","twenty five","twenty six","twenty seven","twenty eight","twenty nine","half"}; char utils[5][10] = {"past","to","o' clock", "minutes", "minute"}; if (m == 0) { strcpy(str, numbers[h]); strcat(str, " "); strcat(str, utils[2]); return str; } else { if (m <= 30) { strcpy(str, numbers[m]); strcat(str, " "); if (m != 30 && m != 15 && m != 45) { if (m == 1) strcat(str, utils[4]); else strcat(str, utils[3]); strcat(str, " "); } strcat(str, utils[0]); strcat(str, " "); strcat(str, numbers[h]); } else { strcpy(str, numbers[60 - m]); strcat(str, " "); if (m != 30 && m != 15 && m != 45) { if (m == 1) strcat(str, utils[4]); else strcat(str, utils[3]); strcat(str, " "); } strcat(str, utils[1]); strcat(str, " "); strcat(str, numbers[h + 1]); } } return str; } int main() { FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); int h = parse_int(ltrim(rtrim(readline()))); int m = parse_int(ltrim(rtrim(readline()))); char* result = timeInWords(h, m); fprintf(fptr, "%s\n", result); fclose(fptr); return 0; } char* readline() { size_t alloc_length = 1024; size_t data_length = 0; char* data = malloc(alloc_length); while (true) { char* cursor = data + data_length; char* line = fgets(cursor, alloc_length - data_length, stdin); if (!line) { break; } data_length += strlen(cursor); if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } alloc_length <<= 1; data = realloc(data, alloc_length); if (!data) { data = '\0'; break; } } if (data[data_length - 1] == '\n') { data[data_length - 1] = '\0'; data = realloc(data, data_length); if (!data) { data = '\0'; } } else { data = realloc(data, data_length + 1); if (!data) { data = '\0'; } else { data[data_length] = '\0'; } } return data; } char* ltrim(char* str) { if (!str) { return '\0'; } if (!*str) { return str; } while (*str != '\0' && isspace(*str)) { str++; } return str; } char* rtrim(char* str) { if (!str) { return '\0'; } if (!*str) { return str; } char* end = str + strlen(str) - 1; while (end >= str && isspace(*end)) { end--; } *(end + 1) = '\0'; return str; } int parse_int(char* str) { char* endptr; int value = strtol(str, &endptr, 10); if (endptr == str || *endptr != '\0') { exit(EXIT_FAILURE); } return value; }
package ru.savrey; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; import java.util.Calendar; import java.util.Iterator; import java.util.LinkedList; import org.mockito.*; import static org.mockito.Mockito.*; public class MainTest { public static void main(String[] args) { LinkedList mockedList = mock(LinkedList.class); when(mockedList.get(0)).thenReturn("nullValue"); when(mockedList.get(1)).thenThrow(new RuntimeException()); //mockedList.add("one"); //mockedList.clear(); verify(mockedList).get(0); verify(mockedList, times(2)).add("twice"); verify(mockedList, never()).add("never happened"); verify(mockedList, timeout(100)); } @Mock private Calendar calendar; /** * 4.1. Создать мок-объект Iterator, настроить поведение так, * чтобы за два вызова next() Iterator вернул два слова “Hello World”, * и проверить это поведение с помощью утверждений */ @Test public void iteratorWillReturnHelloWorld() { // Arrange Iterator iteratorMock = mock(Iterator.class); when(iteratorMock.next()).thenReturn("Hello", "World"); // Act String result = iteratorMock.next() + " " + iteratorMock.next(); // Assert assertEquals("Hello World", result); } }
import React from "react"; import { Box, Typography, List, ListItem, ListItemText, FormControlLabel, Checkbox, } from "@mui/material"; import { formatDate } from "@fullcalendar/core"; const SidebarEvent = ({ event }) => ( <ListItem sx={{ display: "flex", flexDirection: "column", alignItems: "start", padding: "0.5em", marginBottom: "0.5em", border: "1px solid rgba(0,0,0,0.12)", borderRadius: "4px", }} > <ListItemText primary={formatDate(event.start, { year: "numeric", month: "short", day: "numeric", })} secondary={event.title} primaryTypographyProps={{ fontWeight: "bold", marginBottom: "0.3em" }} secondaryTypographyProps={{ fontStyle: "italic" }} /> </ListItem> ); const Sidebar = ({ weekendsVisible, handleWeekendsToggle, currentEvents }) => ( <Box sx={{ padding: "20px", border: "1px solid rgba(0, 0, 0, 0.12)", borderRadius: "5px", display: "flex", flexDirection: "column", maxHeight: "calc(70vh - 100px)", overflow: "auto", // Makes the sidebar scrollable when content overflows }} > <Box sx={{ marginBottom: "20px" }}> <Typography variant="h6">Instructions</Typography> <List> <ListItem> Select dates and you will be prompted to create a new event </ListItem> <ListItem>Drag, drop, and resize events</ListItem> <ListItem>Click an event to delete it</ListItem> </List> </Box> <Box sx={{ marginBottom: "20px" }}> <FormControlLabel control={ <Checkbox checked={weekendsVisible} onChange={handleWeekendsToggle} /> } label="Toggle weekends" /> </Box> <Box sx={{ flex: "1", // Makes this box fill the remaining space overflowY: "auto", // Makes the event list scrollable (thank god) }} > <Typography variant="h6">All Events ({currentEvents.length})</Typography> <List> {currentEvents.map((event) => ( <SidebarEvent key={event.id} event={event} /> ))} </List> </Box> </Box> ); export default Sidebar;
import React, { useState } from 'react'; import ReactDOM from 'react-dom'; import TotoContext from './TotoContext'; import Child from './Child'; import Enfant from './Enfant'; import DumbElement1 from './DumbElement1'; import DumbElement2 from './DumbElement2'; import DumbElement3 from './DumbElement3'; import './style.css'; import { DumbContext } from './Helper/Context'; const App = () => { const [color, setColor] = useState('lightgray') const myFunction = () => { if (color === "lightgray") setColor("darkgray") else if (color === "darkgray") setColor("lightgray") } return ( <div className="app"> <Enfant myFunction={myFunction} /> <DumbContext.Provider value={{ color, setColor }}> <DumbElement1 /> <DumbElement2 /> <DumbElement3 /> </DumbContext.Provider> </div> ) } ReactDOM.render(<App />, document.getElementById('root'));
import type { ICType } from '@kiltprotocol/sdk-js'; import AddBoxOutlinedIcon from '@mui/icons-material/AddBoxOutlined'; import { Box, Button, Paper, Stack, SvgIcon, Typography } from '@mui/material'; import React from 'react'; import { Link } from 'react-router-dom'; import { LogoCircleIcon } from '@credential/app-config/icons'; import { ellipsisMixin } from '@credential/react-components/utils'; import { DidName } from '@credential/react-dids'; const CTypes: React.FC<{ list: ICType[] }> = ({ list }) => { return ( <Box> <Box sx={{ textAlign: 'right', mb: 3 }}> <Button component={Link} startIcon={<AddBoxOutlinedIcon />} to="/attester/ctypes/create" variant="contained" > Create ctype </Button> </Box> <Stack spacing={3}> {list.map((cType) => ( <Paper key={cType.hash} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingY: 2.5, paddingX: 4.5, boxShadow: '0px 3px 6px rgba(153, 155, 168, 0.1)' }} variant="outlined" > <Stack alignItems="center" direction="row" spacing={2} sx={({ breakpoints }) => ({ width: '20%', [breakpoints.down('lg')]: { width: '40%' }, [breakpoints.down('md')]: { width: '100%' } })} > <SvgIcon component={LogoCircleIcon} sx={{ width: 35, height: 35 }} viewBox="0 0 60 60" /> <Typography fontWeight={500}>{cType.schema.title}</Typography> </Stack> <Stack spacing={0.5} sx={({ breakpoints }) => ({ width: '40%', [breakpoints.down('lg')]: { display: 'none' } })} > <Typography fontWeight={300} sx={({ palette }) => ({ color: palette.grey[500] })} variant="inherit" > Created by </Typography> <Typography sx={{ ...ellipsisMixin() }} variant="inherit"> <DidName shorten={false} value={cType.owner} /> </Typography> </Stack> <Stack spacing={0.5} sx={({ breakpoints }) => ({ width: '40%', [breakpoints.down('md')]: { display: 'none' } })} > <Typography fontWeight={300} sx={({ palette }) => ({ color: palette.grey[500] })} variant="inherit" > CType Hash </Typography> <Typography sx={{ ...ellipsisMixin() }} variant="inherit"> {cType.hash} </Typography> </Stack> </Paper> ))} </Stack> </Box> ); }; export default CTypes;
# using recursion: def is_palindrome(s): s = ''.join(char.lower() for char in s if char.isalnum()) if len(s) <= 1: return True if s[0].lower() == s[-1].lower(): return is_palindrome(s[1:-1]) return False # however recursion method fails for too long string as it may exceed maximum recursion limit def is_palindrome_two_pointers(s): # Normalize the string: remove non-alphanumeric characters and convert to lowercase s = ''.join(char.lower() for char in s if char.isalnum()) # Use two-pointer technique to check for palindrome left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <a href="/ejercicios/">Go back</a> <p><em>Abre la consola</em></p> <script> /* (function() { let color = 'green'; function printColor() { console.log(color); } printColor(); })(); function makeColorPrinter(color) { let colorMessage = `the color is ${color}`; return function() { console.log(colorMessage) } } let greenColorPrinter = makeColorPrinter('green'); console.log(greenColorPrinter()); const counter = { count: 3, }; console.log(counter.count); */ //funciones privadas function makeCounter(n) { let count = n; return { increase: function() { count = count + 1; }, decrease: function() { count = count - 1; }, getCount: function() { return count; }, }; } let counter = makeCounter(7); console.log('the count is:', counter.getCount()); counter.increase(); console.log('the count is:', counter.getCount()); counter.decrease(); counter.decrease(); counter.decrease(); counter.decrease(); console.log('the count is:', counter.getCount()); </script> </body> </html>
import initialState from './initialState'; //Import Utils. import { calculateTime } from '../../utils/functions'; const reducer = (state = initialState, action = {}) => { switch (action.type) { case "SET_NOTIFICATION_MESSAGE": state = { ...state, objNotification: action.objNotification }; break; case "USER_SIGNIN_REQUESTED": state = { ...state, isFullScreenLoader: true, }; break; case "USER_SIGNIN_SUCCEEDED": state = { ...state, isFirstTimeSignin: false, isOfflineSignin: false, objUser: action.objUser }; break; case "APP_CONFIG_SUCCEEDED": state = { ...state, isFullScreenLoader: false, arrAppConfigs: action.arrAppConfigs }; break; case "USER_SIGNIN_FAILED": case "APP_CONFIG_FAILED": state = { ...state, isFullScreenLoader: false, objNotification: action.objNotification }; break; case "PROJECT_LIST_SUCCEEDED": state = { ...state, arrUserProjects: action.arrUserProjects }; break; case "USER_OFFLINE_SIGNIN_REQUESTED": state = { ...state, isFirstTimeSignin: false, isOfflineSignin: true, objUser: action.objUser, arrUserProjects: action.arrUserProjects ? action.arrUserProjects : initialState.arrUserProjects, arrAppConfigs: action.arrAppConfigs ? action.arrAppConfigs : initialState.arrAppConfigs }; break; case "USER_SIGNOUT_POPUP_REQUESTED": state = { ...state, strUserSignoutPopup: action.strUserSignoutPopup }; break; case "USER_SIGNOUT_REQUESTED": state = { ...state, isFullScreenLoader: true, strUserSignoutPopup: "hide" } break; case "USER_SIGNOUT_SUCCEEDED": state = { ...state, objUser: {}, isFullScreenLoader: false, inActivityID: null, inActivityStartTime: null, strActivityRunTime: '00:00:00', strActivityName: 'Default Activity', inSelectedProjectID: null, inLastRowDataSync: initialState.inLastRowDataSync, isTodayTimeSummaryExist : initialState.isTodayTimeSummaryExist, inTodayTimeSummaryRowDataID: initialState.inTodayTimeSummaryRowDataID, inDayStartTime : initialState.inDayStartTime, inTotalActiveTime: initialState.inTotalActiveTime, }; break; case "UPDATE_INTERNET_STATUS": state = { ...state, isSystemOnline: action.payload }; break; case "START_TRACKER": state = { ...state, isTrackerStart: true, inActivityID: action.payload.inActivityID, inActivityStartTime: action.payload.inActivityStartTime }; break; case "STOP_TRACKER": state = { ...state, isTrackerStart: false, strActivityRunTime: calculateTime(state.inActivityStartTime) }; break; case "ACTIVITY_NAME_POPUP": state = { ...state, strActivityNamePopup: action.payload.strActivityNamePopup, strActivityName: action.payload.strActivityName || initialState.strActivityName }; break; case "UPDATE_ACTIVITY_ROW_DATA_ID": state = { ...state, inActivityRowDataID: action.payload }; break; case "UPDATE_SELECTED_PROJECT_ID": state = { ...state, inSelectedProjectID: action.payload }; break; case "SINGLE_ROW_DATA_SYNC_SERVER_REQUESTED": state = { ...state, isSingleRowDataSyncing: true }; break; case "SINGLE_ROW_DATA_SYNC_SERVER_COMPLETED": state = { ...state, isSingleRowDataSyncing: false, inLastRowDataSync : new Date().getTime() }; break; case "BULK_ROW_DATA_SYNC_SERVER_REQUESTED": state = { ...state, isBulkRowDataSyncing: true }; break; case "BULK_ROW_DATA_SYNC_SERVER_COMPLETED": state = { ...state, isBulkRowDataSyncing: false, inLastRowDataSync : new Date().getTime() }; break; case "BULK_IMAGES_DATA_SYNC_SERVER_REQUESTED": state = { ...state, isBulkImagesDataSyncing: true }; break; case "BULK_IMAGES_DATA_SYNC_SERVER_COMPLETED": state = { ...state, isBulkImagesDataSyncing: false }; break; case "START_FULL_SCREEN_LOADER": state = { ...state, isFullScreenLoader: true }; break; case "ERROR_HANDLER_POPUP_REQUESTED": state = { ...state, strErrorHandlerPopup: action.payload.strErrorHandlerPopup, objErrorHandler: action.payload.objErrorHandler }; break; case "SEND_ERROR_REPORT_To_SERVER_REQUESTED": state = { ...state, strErrorHandlerPopup: "hide", objErrorHandler: initialState.objErrorHandler }; break; case "UPDATE_TODAY_TIME_SUMMARY_DATA": state = { ...state, isTodayTimeSummaryExist: true, inTodayTimeSummaryRowDataID: action.payload.todayTimeSummaryRowDataID, inDayStartTime: action.payload.dayStartTime, inTotalActiveTime: action.payload.totalActiveTime }; break; case "UPDATE_TOTAL_ACTIVE_TIME": state = { ...state, inTotalActiveTime: action.payload.totalActiveTime }; break; default: } return state; }; export default reducer;
// создайте класс User со свойствами name и age и методом sayHi который выводит в консоль фразу 'Привет' // и создать экземпляр класса // 1. class User { constructor(name, age) { (this.name = name), (this.age = age); } sayHi() { console.log(`Hello ${this.name} your age is ${this.age}`); } } const user_1 = new User("Bogdan", 32); const user_2 = new User("Alona", 33); user_1.sayHi(); // Hello Bogdan your age is 32 user_2.sayHi(); // Hello Alona your age is 33 // 2. // добавили новый метод .change_name() который меняет имя class User { constructor(name, age) { (this.name = name), (this.age = age); } sayHi() { console.log(`Hello ${this.name} your age is ${this.age}`); } change_name(new_name) { this.name = new_name; } } const user_1 = new User("Bogdan", 32); const user_2 = new User("Alona", 33); console.log(user_1); // User { name: 'Bogdan', age: 32 } console.log(user_2); // User { name: 'Alona', age: 33 } console.log(user_1.name); // Bogdan console.log(user_1.age); // 32 user_1.change_name("Igor"); // Hello Igor your age is 32 console.log(user_1.name); // Igor user_1.change_name("Goga"); // Hello Goga your age is 32 console.log(user_1.name); // Goga user_1.sayHi(); // Hello Bogdan your age is 32 user_2.sayHi(); // Hello Alona your age is 33 // 3. // Добавьте метод birthday который увеличивает возрост на единицу и выводит в консоль class User { constructor(name, age) { (this.name = name), (this.age = age); } sayHi() { console.log(`Hello ${this.name} your age is ${this.age}`); } birthday() { this.age++; console.log("Всегда оставайся таким веселым!"); } } const user_1 = new User("Bogdan", 32); const user_2 = new User("Alona", 33); user_1.sayHi(); // Hello Bogdan your age is 32 user_2.sayHi(); // Hello Alona your age is 33 user_1.birthday(); // Всегда оставайся таким веселым! console.log(user_1); // User { name: 'Bogdan', age: 33 } // --------------------------------------------------------------------------------- // 4. // роли: root, admin, manager, user // Провести указанную роль и если она входит в список допустимых указать ее пользователю // в ином случае в свойство role указать undefined // --------------------------------------------------------------------------------- // .includes() - Method позволяет проверить если задданное значение в массиве let a = [12, 4, 3, 5]; console.log(a.includes(12)); // true console.log(a.includes(44)); // false // --------------------------------------------------------------------------------- class User { constructor(name, age, role) { (this.name = name), (this.age = age); if (["root", "admin", "manager", "user"].includes(role)) { this.role = role; } else { this.role = undefined; } } } const user_3 = new User("Bogdan", 32, "admin"); const user_4 = new User("Alona", 33, "student"); console.log(user_3); // User { name: 'Bogdan', age: 32, role: 'admin' } console.log(user_4); // User { name: 'Alona', age: 33, role: undefined } // 5 // Добавить метод изменения роли, который получает в качестве аргумента новую роль // и изменяет свойство role в случае, если роль указана верно // если роль неверна, то в свойство role указать undefined class User { constructor(name, age, role) { (this.name = name), (this.age = age); if (["root", "admin", "manager", "user"].includes(role)) { this.role = role; } else { this.role = undefined; } } change_role(new_role) { if (["root", "admin", "manager", "user"].includes(new_role)) { this.role = new_role; } else { this.role = undefined; } } } const user_5 = new User("Bogdan", 32, "admin"); const user_6 = new User("Alona", 33, "student"); console.log(user_5); // User { name: 'Bogdan', age: 32, role: 'admin' } console.log(user_5.change_role("student")); // undefined console.log(user_5); // User { name: 'Bogdan', age: 32, role: undefined } console.log(user_5.change_role("manager")); // undefined console.log(user_5); // User { name: 'Bogdan', age: 32, role: 'manager' } // 6. переписали код class User { constructor(name, age, roles) { (this.name = name), (this.age = age), (this.roles = ["root", "admin", "manager", "user"]); if (this.roles.includes(roles)) { this.roles = roles; } else { this.roles = undefined; } } change_role(new_role) { if (this.roles.includes(new_role)) { this.roles = new_role; } else { this.roles = undefined; } } } const user_7 = new User("Bogdan", 32, "manager"); const user_8 = new User("Alona", 33, "student"); console.log(user_7); // User { name: 'Bogdan', age: 32, role: 'manager' } user_7.change_role("student"); console.log(user_7); // User { name: 'Bogdan', age: 32, role: 'undefined' } console.log(user_7.roles); // manager // user_7.roles.push("babka"); // user_7.roles.append("gdgdgd"); user_7.change_role("manager"); console.log(user_7);
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Clip</title> <script src="https://cdn.tailwindcss.com?plugins=forms"></script> </head> <body> <div class="container mx-auto mt-16" id="app"> <div> <label for="content" class="flex text-md font-medium text-gray-700 items-center justify-between"> <span> Clipboard content [ characters: <b class="text-gray-900">{{ content.length }}</b>, words: <b class="text-gray-900">{{ content.length ? content.replace(/\s+/gi, ' ').split(' ').length : 0 }}</b> ] </span> <span> <button type="button" @click="content = ''" class="inline-flex items-center rounded border border-transparent bg-indigo-100 px-2.5 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"> Clear all </button> </span> </label> <div class="mt-1"> <textarea rows="6" v-model="content" id="content" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"></textarea> </div> </div> <div class="mt-4"> <div class="mt-1 flex rounded-md shadow-sm"> <span class="inline-flex items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-50 px-3 text-gray-500 sm:text-sm">number of chars</span> <input type="number" v-model="chars" step="1" class="block w-full min-w-0 flex-1 rounded-none rounded-r-md border-gray-300 px-3 py-2 focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"> </div> </div> <div class="relative my-4"> <div class="absolute inset-0 flex items-center" aria-hidden="true"> <div class="w-full border-t border-gray-300"></div> </div> <div class="relative flex justify-center"> <span class="bg-white px-2 text-sm text-gray-500">split</span> </div> </div> <div> <div class="mt-1 flex rounded-md shadow-sm"> <span class="inline-flex items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-50 px-3 text-gray-500 sm:text-sm">Prefix:</span> <input type="text" id="prefix" v-model="prefix" class="block w-full min-w-0 flex-1 rounded-none rounded-r-md border-gray-300 px-3 py-2 focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"> </div> </div> <div class="border-b border-gray-200 pb-5 mt-5"> <h3 class="text-lg font-medium leading-6 text-gray-900"> Split - <b>[ Copied: {{ copied.length }} / {{ split.length }}]</b> </h3> </div> <div class="my-4" v-for="(split, index) in split" :key="index"> <div class="flex mb-1"> <div class="text-gray-700 text-2xl p-2">{{ index+1 }}</div> <textarea rows="6" readonly class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">{{ split }}</textarea> </div> <div class="flex text-md font-medium text-gray-700 items-center justify-center"> <button type="button" @click="copy(index)" :class="{'border-gray-300 text-gray-700 bg-white': copied.includes(index), 'border-transparent text-white bg-indigo-600 hover:bg-indigo-700': !copied.includes(index)}" class="inline-flex items-center rounded border px-2.5 py-1.5 text-xs font-medium shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"> Copy </button> </div> </div> </div> <script type="module"> import {createApp} from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js' createApp({ data() { return { content: '', chars: 2000, prefix: 'Reply with continue and nothing else:', copied: [] } }, computed: { split: { get() { if (this.content.length === 0) { return [] } let charLimit = this.chars if (charLimit > this.prefix.length) { charLimit = charLimit - this.prefix.length } return this.wrapText(this.content, charLimit) } } }, methods: { async copy(row) { await navigator.clipboard.writeText(this.prefix + ' ' + this.split[row]); if( !this.copied.includes(row) ) { this.copied.push(row) } }, wrapText(text, charLimit) { const words = text.split(" ") let lines = [] let line = "" for (let i = 0; i < words.length; i++) { let word = words[i] if (line.length + word.length + 1 <= charLimit) { line += " " + word } else { lines.push(line.trim()) line = word } } lines.push(line.trim()) return lines } } }).mount('#app') </script> </body> </html>
import 'dart:convert'; import 'package:get/get.dart'; import 'package:get/get_connect/http/src/utils/utils.dart'; import 'package:http/http.dart' as http; import 'package:musicapp/rout.dart'; import '../env.dart'; import '../models/persons.dart'; import '../models/tokenModel.dart'; class AuthBACKEND { final String baseUrl = AppEnvironment.baseApiUrl; Future<UserModel> checkEmail(String email) async { final response = await http.post( Uri.parse('$baseUrl/login/checkEmail'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'email': email, }), ); if (response.statusCode == 200) { final Map<String, dynamic> data = jsonDecode(response.body); final List<dynamic> existingEmailList = data['result']['existingEmail']; final Map<String, dynamic> existingEmail = existingEmailList.isNotEmpty ? existingEmailList.first : {}; if (existingEmail.isNotEmpty) { // If email is valid, return the user information return UserModel.fromMap(existingEmail); } else { throw Exception('No user found with this email'); } } else if (response.statusCode == 500) { final Map<String, dynamic> data = jsonDecode(response.body); Get.toNamed(RouteGenerator.registerPager); print(data); // If email is not valid, you can navigate to the new password page throw Exception('Invalid email. Navigate to new password page.'); } else { // If the server did not return a 200 OK response, throw an exception. throw Exception('Failed to check email'); } } Future checkPass(int userID, String pass) async { final response = await http.post( Uri.parse('$baseUrl/login/checkPassword'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{'userID': '$userID', 'password': pass}), ); if (response.statusCode == 200) { final Map<String, dynamic> responseBody = json.decode(response.body); print(responseBody); return TokenModel.fromMap(responseBody); } else { print("go to signup"); } } Future<void> createUser( String email, String password, String userName) async { final response = await http.post( Uri.parse('$baseUrl/signUp/createUser'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'email': email, 'password': password, 'userName': userName, }), ); if (response.statusCode == 200) { print("success"); } else { print("go to signup"); } } Future<void> editUser( int userID, String userName, String firstName, String lastName) async { final response = await http.patch( Uri.parse('$baseUrl/user/updateUser'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'userID': "$userID", 'userName': userName, 'firstname': firstName, 'lastname': lastName, }), ); if (response.statusCode == 200) { print("success"); } else { print("go to signup"); } } }
import { useEffect, useRef, useState } from 'react'; export const useLoopPolicyStatus = () => { const time = useRef(); const [loopRequesting, setLoopRequesting] = useState(false); useEffect(() => { return () => { clearTimeout(time.current); setLoopRequesting(false); }; }, []); const check = ({ list, loopFn }) => { const hasPendingItem = !!(list || []).find( it => it.policyStatus === 'pending', ); // 有检测中的数据需要轮询 if (hasPendingItem) { clearTimeout(time.current); time.current = setTimeout(() => { setLoopRequesting(true); loopFn() .then(() => { setLoopRequesting(false); }) .catch(() => { setLoopRequesting(false); }); }, 5000); } else { clearTimeout(time.current); } }; return { check, loopRequesting }; };
```This is a run anywhere example. After this search is an example which has more comments explaining how it works.```` | makeresults | eval foo=split("test,test2", ","), bar=split("27,33", ",") | mvexpand foo | mvexpand bar | stats sum(bar) AS count BY foo | append [| makeresults | eval foo="test4", count=0 ] | stats sum(count) AS amount BY foo ```This is a typical way to prove a negative. Splunk does not know about things which do not exist, so if you need to show a value for items which are going to return nothing you have to account for it by proving a negative.``` | stats count by somefield Time | fields - count | sort - Time | appendpipe [ stats count | eval Time="No Records Found" | eval somefield="No Records Found" | where count==0 | fields - count] ```An alternative method for proving a negative is to populate data with append and makeresults, then using stats to sum everything``` | stats count by field1, field2 ```You need to know every possible value for field1 and field2``` | append [| makeresults | eval field1="Something", field2="Something", count=0] | append [| makeresults | eval field1="Something2", field2="Something2", count=0] | stats sum(count) BY field1, field2 ```This is another way to prove a negative, however this time it does so over a 14 day window of time with gentimes.``` | append [| gentimes start=-14 end=0 increment=1d | eval _time=starttime, value=0, field="STRING", field2="STRING", field3="STRING" | fields _time, value, field, field2, field3] ``` THIS IS UNDOCUMENTED DO NOT USE IT JUST LEAVING IT HERE ``` ``` | multireport [| eval value=0, field="STRING", field2="STRING", field3="STRING", _time=relative_time(now(), "-1d@d")] [| eval value=0, field="STRING", field2="STRING", field3="STRING", _time=relative_time(now(), "-2d@d")] [| eval value=0, field="STRING", field2="STRING", field3="STRING", _time=relative_time(now(), "-3d@d")] ```
import React from 'react' import styled from '@emotion/styled' const ContenedorFrase = styled.div` padding: 2rem; border-radius: 0.5rem; background-color: white; max-width: 800px; @media (min-width: 992px) { margin-top: 10rem; } h1{ font-family: Arial, Helvetica, sans-serif; text-align: center; position: relative; padding-left: 4rem; font-size: 2rem; &::before{ content: open-quote; font-size: 6rem; color: black; position: absolute; left: -1rem; top: -2rem; } } p{ font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 1rem; text-align: right; color: #666; margin-top: 2rem; font-weight: bold; } `; const Frase = ({ frase }) => { const { quote, author } = frase; return ( <ContenedorFrase> <h1>{ quote }</h1> <p>- { author }</p> </ContenedorFrase> ); } export default Frase;
import { Link } from "react-router-dom"; import { useState, useEffect } from "react"; import { updateVote } from "../api"; import { fetchArticle } from "../api"; export default function ArticleCard({ article }) { const [voteCountFromApi, setVoteCountFromApi] = useState(); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [voteStatus, setVoteStatus] = useState(0); const updateVotesLocally = (voteIncrement) => { setVoteCountFromApi(voteIncrement + voteCountFromApi); }; useEffect(() => { fetchArticle(Number(article.article_id)) .then((articleFromApi) => { setIsLoading(false); setVoteCountFromApi(articleFromApi.votes); }) .catch( ({ response: { data: { msg }, status, }, }) => { setIsLoading(false); setError({ msg, status }); } ); }, [article.article_id]); if (isLoading) return <p>Loading...</p>; if (error) return ( <h2> {error.status}: {error.msg} </h2> ); return ( <div className="front-page-body"> <div className="vote"> <button className={`green-arrow green-arrow-${voteStatus} `} onClick={() => { if (voteStatus === 0) { updateVote(article.article_id, 1); updateVotesLocally(1); setVoteStatus(1); } else if (voteStatus === -1) { updateVote(article.article_id, 1); updateVotesLocally(1); setVoteStatus(0); } }} > &#8679; </button> {voteCountFromApi}{" "} <button className={`red-arrow red-arrow-${voteStatus}`} onClick={() => { if (voteStatus === 0) { setVoteStatus(-1); updateVote(article.article_id, -1); updateVotesLocally(-1); } else if (voteStatus === 1) { setVoteStatus(0); updateVote(article.article_id, -1); updateVotesLocally(-1); } }} > &#8681; </button> </div> <div className="front-page-article-card"> <div className="front-page-article-card-header"> <div className={`front-page-article-card-header-logo-${article.topic}`} > "." </div> <Link className="front-page-article-card-header-topic" to={`/topics/${article.topic}`} > <b>topics/{article.topic}</b> </Link> <div className="front-page-article-card-header-author"> &#183; Posted by {article.author} &#183;{" "} {article.created_at.slice(0, 10)} </div> </div> <div className="front-page-article-card-body-title"> <Link className="front-page-article-card-body-title-link" to={`/articles/${article.article_id}`} > {article.title} </Link> </div> <div className="front-page-article-card-body"> <Link className="front-page-article-card-body-link" to={`/articles/${article.article_id}`} > {article.body} </Link> </div> <div className="front-page-article-card-footer"> <Link className="front-page-article-card-footer-comment-logo" to={`/articles/${article.article_id}`} > &#9993;{" "} </Link> <div> <Link className="front-page-article-card-footer-comment" to={`/articles/${article.article_id}`} > {article.comment_count} comments </Link> </div> </div> </div> </div> ); }
import NavBar from "@/components/NavBar"; import "../globals.css"; import type { Metadata } from "next"; import Footer from "@/components/Footer"; import { Toaster } from "react-hot-toast"; import StateProvider from "@/context/StateContext"; export const metadata: Metadata = { title: "MBA Ecommerce", description: "Generated by create next app", }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <StateProvider> <body className="p-3"> <header> <NavBar /> </header> <main className="main-container"> <Toaster></Toaster> {children} </main> <footer> <Footer /> </footer> </body> </StateProvider> </html> ); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Uebung 9</title> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <style> header{width:100%; background-color: #888888; text-align:center; height: 80px } h1{color:white; padding: 10px} footer{position: absolute; bottom:0px;background-color:#888888; width:100%; text-align:center } footer>a, footer>a:visited, footer>a:hover, footer>a:link{ text-decoration:none; color:white; text:bold} #butt{background-color:#0082D1; color: white; border-radius: 5px; padding: 5px; margin: 5px} #in {width:80%; padding: 5px; margin: 5px} @media screen and (max-width: 768px){ #weg{display: none}} #main1 {margin-left:5px} #main2 {display:none} #zuege {background-color:#0082D1; color:white; text-align:center; height:80px; margin-top:5px;margin-left:10px; width:100%; justify-content:center } #wuerfel {background-color:#0082D1; height:200px; width:200px; margin:10px; line-height: 200px; color: white;font-size: xx-large ; font-weight:bold; text-align: center } #wurfliste {margin-left: 50px} </style> </head> <body onload="controller()"> <div class="container-fluid"> <header> <h1 id="h1">Ein Spiel</h1> </header> <div class="row" id="main1"> <div id="playerlist" class="col-12 col-md-3 list-group" > <h3>Auswahl Spielerin</h3> </div> <div id="weg" class="col-12 col-md-2" > <h3> oder</h3> </div> <div id="formular" class="col-12 col-md-6" > <h3>Neue Spielerin anlegen</h3> <form method="get"> <input type="text" id="in" class="form-control" name="name" placeholder="Name"> <button type="submit" id="butt" class="btn btn-primary" >Neue Spielerin anlegen</button> </form> </div> </div> <div id="main2"> <div class="row"> <h2 id="zuege">Anzahl Zuege: 0</h2> </div> <div class="row"> <div id="wuerfel" class="col-2" onclick="wuerfel()"> </div> <div id="wurfliste" class="col-8"> <h5>Liste der Würfe</h5> <ul id="wurf" class="list-group"> </ul> </div> </div> </div> </div> <footer> <a href="http://webtech.f4.htw-berlin.de/~s0569853/WebTech19/Uebung/">Nyco C. Bischoff</a> </footer> </div> </body> <script> function controller() { var urlParams = new URLSearchParams(window.location.search); if (!urlParams.has('name')) { var player = [{"name": "Susan", "moves": 12}, {"name": "Catherine", "moves": 13}, {"name": "Anne", "moves": 11}, {"name": "Bonnie", "moves": 16}, {"name": "Rebecca", "moves": 10}, {"name": "Margaret", "moves": 17}, {"name": "Deborah", "moves": 15}]; createList(player); } else { document.getElementById("main1").style.display = 'none'; document.getElementById("main2").style.display = 'block'; let name = urlParams.get('name'); document.getElementById('h1').innerText = name + " spielt"; } } function createList(player){ var playerList= document.getElementById('playerlist'); for(let i=0; i<player.length; i++){ let a= document.createElement('a'); a.classList.add('list-group-item','list-group-item-action'); a.href = 'index.html?name=' + player[i].name; a.innerText= player[i].name+ " ("+player[i].moves+ ")"; playerList.appendChild(a); } } /* function newPlayer(){ Das: onclick="newPlayer() bracuhe ich gar nicht, wenn ich als form-method "get" habe und nicht (wie eigentlich in der AUfgabe) post, weil mit "get" auch der Name angehängt wird und dann schickt mich der controller auch in main2 var playerList= document.getElementById('playerlist'); let input= document.getElementById('in').value; document.createElement('a'); a.classList.add('list-group-item','list-group-item-action'); a.href = 'index.html?name=' +input; a.innerText= input+ " ( )"; playerList.appendChild(a); document.getElementById('h1').innerHTML= input+" spielt"; }*/ var anzZuege=0; function wuerfel(){ if ( document.getElementById('wuerfel').innerText != 6) { let zufWurf = Math.floor((Math.random() * 6) + 1); anzZuege++; document.getElementById('wuerfel').innerText= zufWurf; document.getElementById('zuege').innerText = 'Anzahl Zuege : ' + anzZuege; let li = document.createElement('li'); li.classList.add('list-group-item', 'list-group-item-action'); if (zufWurf != 6){ li.innerText = anzZuege + '. Wurf : ' + zufWurf; } else{ li.innerHTML = '<a href="index.html" style= "color:red; font-weight: bold">'+ anzZuege + '. Wurf : 6 -->Ende (Startseite) </a>' } document.getElementById('wurf').appendChild(li); } } </script> </html>
import clsx from 'clsx' import type { FC, ReactNode } from 'react' import React from 'react' type Props = { children: ReactNode className?: string variant?: 'warning' | 'danger' | 'success' } const Alert: FC<Props> = ({ children, variant = 'warning', className }) => { return ( <div className={clsx('flex items-center rounded-xl border p-4', className, { 'border-yellow-500 border-opacity-50': variant === 'warning', 'border-red-500 border-opacity-50': variant === 'danger', 'border-green-500 border-opacity-50': variant === 'success' })} > {children} </div> ) } export default Alert
<?php namespace App\Http\Controllers; use App\Models\Aviso; use Illuminate\Http\Request; class AvisoController extends Controller { public function __construct() { $this->middleware('auth'); $this->middleware('admin'); } /** * Display a listing of the resource. */ public function index() { $data = [ 'titulo' => 'Avisos', 'subtitulo' => 'Gerenciando Avisos', ]; return view('avisos.index', $data); } public function listar_avisos() { $avisos = Aviso::all(); $data = []; foreach ($avisos as $aviso) { $data[] = [ 'titulo' => '<a href="' . route('avisos.show', $aviso->id) . '">' . $aviso->titulo . '</a>', 'grupo' => $aviso->grupo, 'created_at' => date('d/m/Y', strtotime($aviso->created_at)), 'acoes' => '<a class="btn btn-primary text-danger ml-2" href="' . route('avisos.destroy', $aviso->id) . '" onclick="event.preventDefault(); document.getElementById(\'logout-form\').submit();"> <i class="fa fa-trash"></i> Deletar</a> <form id="logout-form" action="' . route('avisos.destroy', $aviso->id) . '" method="POST" class="d-none"> @csrf @method("DELETE") </form>', ]; } $retorno = [ 'data' => $data, ]; return response()->json($retorno); } /** * Show the form for creating a new resource. */ public function create() { $data = [ 'titulo' => 'Criar Aviso', 'subtitulo' => 'Cadastrar novo aviso no sistema', ]; return view('avisos.create', $data); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $request->validate([ 'grupo' => ['required', 'string'], 'icone' => ['required', 'string'], 'titulo' => ['required', 'string'], 'descricao' => ['nullable', 'string'], 'imagem' => ['nullable', 'image'], ]); $aviso = new Aviso(); $aviso->grupo = $request->input('grupo'); $aviso->icone = $request->input('icone'); $aviso->titulo = $request->input('titulo'); $aviso->descricao = $request->input('descricao'); if ($request->hasFile('imagem') && $request->file('imagem')->isValid()) { $imagemPath = $request->file('imagem')->store('avisos'); $aviso->imagem = $imagemPath; } $aviso->save(); return redirect()->route('avisos.index')->with('success', 'Aviso criado com sucesso.'); } /** * Display the specified resource. */ public function show(string $id) { $aviso = Aviso::find($id); $data = [ 'titulo' => 'Criaar Aviso', 'subtitulo' => 'Cadastrar novo aviso no sistema', 'aviso' => $aviso, ]; return view('avisos.create', $data); } /** * Show the form for editing the specified resource. */ public function edit(string $id) { // } /** * Update the specified resource in storage. */ public function update(Request $request, string $id) { // } /** * Remove the specified resource from storage. */ public function destroy(string $id) { Aviso::destroy($id); return redirect()->route('avisos.index')->with('success', 'Aviso deletado com sucesso.'); } }
/* * Copyright Fluidware srl * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Request, Response, NextFunction } from 'express'; import { DbClient } from '@fluidware-it/mysql2-client'; import { ensureError, getAsyncLocalStorageProp, getLogger, setAsyncLocalStorageProp } from '@fluidware-it/saddlebag'; import { ConnectionOptions } from 'mysql2'; export const StoreSymbols = { DB_CLIENT: Symbol('fw.mysql-client'), DB_KEEP_CONNECTION: Symbol('fw.mysql-keep-connection') }; export interface MiddlewareOptions { httpMethods?: string[]; connectionOptions?: ConnectionOptions | string; exitOnConnectionFailure: boolean; } export const defaultMiddlewareOptions: MiddlewareOptions = { httpMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], connectionOptions: '', exitOnConnectionFailure: false }; export function getMysql2Middleware(middlewareOptions?: MiddlewareOptions) { const _middlewareOptions = Object.assign({}, defaultMiddlewareOptions, middlewareOptions || {}); return async function mysqlMiddleware(req: Request, res: Response, next: NextFunction): Promise<void> { if (_middlewareOptions.httpMethods?.includes(req.method)) { try { const client = new DbClient(_middlewareOptions.connectionOptions); await client.open(); setAsyncLocalStorageProp<DbClient>(StoreSymbols.DB_CLIENT, client); setAsyncLocalStorageProp<boolean>(StoreSymbols.DB_KEEP_CONNECTION, false); res.on('close', () => { if (!getAsyncLocalStorageProp<boolean>(StoreSymbols.DB_KEEP_CONNECTION)) { client.close().catch(err => { const e = ensureError(err); getLogger().error({ error_code: err.code, error_message: e.message }, 'Failed to close connection'); }); } }); } catch (err) { res.status(500).json({ status: 500, reason: 'A problem occurred, please retry' }); if (_middlewareOptions.exitOnConnectionFailure) { if (err.code === 'ECONNREFUSED') { getLogger().error('Failed to establish db connection. Network error. Exiting'); process.kill(process.pid, 'SIGTERM'); return; } if (err.code === 'ER_ACCESS_DENIED_ERROR') { getLogger().error('Failed to open db connection. Credentials error. Exiting'); process.kill(process.pid, 'SIGTERM'); return; } if (err.code === 'ER_CON_COUNT_ERROR') { getLogger().error('Failed to open db connection. Too many connections. Exiting'); process.kill(process.pid, 'SIGTERM'); return; } } const e = ensureError(err); getLogger().error({ error_code: err.code, error_message: e.message }, 'Failed to establish db connection'); return; } } setImmediate(next); }; }
import { useTranslation } from "react-i18next"; import HeadPage from "../../components/headPage/HeadPage"; import { useEffect, useState } from "react"; import apiAxios from "../../utils/apiAxios"; import Loader from "../../components/loader/Loader"; import { useParams } from "react-router-dom"; import { formateDate } from "../../utils/formatDate"; import useFetch from "../../hooks/useFetch"; const ReportsDetails = () => { const { t } = useTranslation(); const { id } = useParams(); const { data: report, loading } = useFetch(`/report/${id}`, {}); return ( <div className="reports_details"> <HeadPage title={t("Report details")} /> {!loading ? ( <div className="container"> <h5 className="text-[22px] font-semibold mb-2"> {report.name && report.name} </h5> <div className="top flex items-center justify-between gap-3 mb-2"> <h5 className="text-[16px] font-semibold"> {t("Type Device")}:{" "} <span className="text-gray-500"> {report.device_type && report.device_type} </span>{" "} </h5> <span className="date text-gray-500 font-semibold"> {report.created_at && formateDate(report.created_at)} </span> </div> <h5 className="text-[16px] font-semibold"> {t("Phone")}:{" "} <span className="text-gray-500"> {report.phone1 && report.phone1} </span>{" "} </h5> <div className="desc mt-3"> <p className="text-gray-500 mb-2"> {report.description && report.description} </p> </div> </div> ) : ( <Loader /> )} </div> ); }; export default ReportsDetails;
#ifndef MANAGER_UTILS_TEXT_H_ #define MANAGER_UTILS_TEXT_H_ // System headers #include <cstdint> // Other libraries headers #include "utils/drawing/Color.h" // Own components headers #include "manager_utils/drawing/Widget.h" // Forward Declarations class Text : public Widget { public: Text(); ~Text() noexcept; Text(Text&& movedOther); Text& operator=(Text&& movedOther); /** @brief used to create resource. This function must be called * in order to operate will be resource. The Text itself only * handles draw specific data, not the actual Surface/Texture * This function does not return error code for performance reasons * * @param const fontId - unique resource ID * @param const char * - text content we want to create as Text image * @param const Color & - color we want to create the Text with * @param const Point - the position we want the Text to be created * */ void create(const uint64_t fontId, const char* text, const Color& color, const Point& pos = Points::ZERO); /** @brief used to destroy Text texture. In order to use the text * texture again - it needs to be re-created. * (Invoking of .create() method) * */ void destroy(); /** @brief used to set new content of Text texture. * If new text content differs from the current one * internally the old Text surface/texture is destroyed and * new one is created with input text content. * * @param const char * - new text content to be displayed * */ void setText(const char* text); /** @brief used to set color for Text texture. * Internally the old Text surface/texture is destroyed and * new one is created with input new text color. * * @param const Color & - new color of the text * */ void setColor(const Color& color); /** @brief combination of ::setText() and ::setColor() * * NOTE: if you need to change both of them at the same time * it is better to use this method instead of the listed * two, because each of them destroys the text and * creates new one. * * @param const char * - new text content to be displayed * @param const Color & - new color of the text * */ void setTextAndColor(const char* text, const Color& color); /** @brief used to get C-style char array to the _textContent * currently being hold by the Text instance * * @returns const char* - text content of the Text instance * */ const char* getText() const { return _textContent; } private: void resetInternals(); /** @brief used to make a deep copy of the input text * */ void copyTextContent(const char* text); /** Since Text header will be included a lot -> try not to * include std::string. This will heavily influence the compile time * for every file that includes the Text header. * */ const char* _textContent; // Holds the font id correcposnding to the current text uint64_t _fontId; // The color of the text Color _color; /* used in order to check if resource was destroyed -> * not to destroy it twice */ bool _isDestroyed; }; #endif /* MANAGER_UTILS_TEXT_H_ */
<template> <div class="field"> <div class="title"> <label :for="name" class="label"> {{ label }} </label> <div class="helper" @click="$emit('helper')"> {{ helper }} </div> </div> <input class="input" :id="name" :type=type :name="name" :placeholder="placeholder" :disabled="disabled" v-model="valueRef" /> </div> </template> <style lang="scss" scoped> .field { display: flex; flex-direction: column; justify-content: flex-start; align-items: flex-start; width: 100%; margin-bottom: 20px; } .title { display: flex; flex-direction: row; justify-content: space-between; align-items: center; width: 100%; margin-bottom: 8px; } label { font-weight: 500; } .helper { font-size: 0.75rem; font-weight: 300; text-decoration: none; color: $blue; &:hover { color: darken($blue, 10); cursor: pointer; } } input { width: 100%; padding: 8px 0 8px 12px; border: 1px rgba(white, 0.3) solid; border-radius: 5px; font-size: 1rem; background-color: rgba(black, 0.1); color: white; &::placeholder { color: lighten($gray5, 0); } &:disabled { border-color: rgba(white, 0.1); background-color: rgba(black, 0.05); color: lighten($gray5, 25); } } </style> <script setup> const props = defineProps({ label: String, helper: String, type: String, name: String, placeholder: String, disabled: Boolean, value: String }) const valueRef = ref(props.value) const emit = defineEmits(['helper']) </script>
import React, { useRef } from 'react'; import EpisodeComponent from './EpisodeComponent'; import { Episode } from './types'; import { useState } from 'react'; import { AiOutlineLeft, AiOutlineRight } from 'react-icons/ai'; interface Props { title: string; episodes: Episode[]; } const EpisodeSection: React.FC<Props> = ({ title, episodes }) => { const containerRef = useRef<HTMLDivElement>(null); const [scrollPosition, setScrollPosition] = useState(0); const handleScroll = (amount: number) => { if (containerRef.current) { const newPosition = scrollPosition + amount; setScrollPosition(newPosition); containerRef.current.scrollTo({ left: newPosition, behavior: 'smooth', }); } }; const scrollLeft = () => handleScroll(-containerRef.current!.clientWidth); const scrollRight = () => handleScroll(containerRef.current!.clientWidth); return ( <div className="flex flex-col"> <h2 className="mb-4 text-2xl font-bold">{title}</h2> <div className="relative"> <button className="flex items-center justify-center absolute -left-[16px] bottom-1/2 w-[32px] h-[32px] bg-gray-200 rounded-full hover:bg-gray-300" disabled={scrollPosition === 0} onClick={scrollLeft} > <AiOutlineLeft color={'black'} /> </button> <div className="flex flex-grow overflow-x-auto" ref={containerRef} onScroll={() => setScrollPosition(containerRef.current?.scrollLeft ?? 0)} > {episodes.map((episode) => ( <div className="flex-none" key={episode.name}> <EpisodeComponent episode={episode} /> </div> ))} </div> <button className="flex items-center justify-center absolute -right-[16px] bottom-1/2 w-[32px] h-[32px] bg-gray-200 rounded-full hover:bg-gray-300" disabled={ (containerRef.current && containerRef.current.clientWidth + scrollPosition >= containerRef.current.scrollWidth) ?? undefined } onClick={scrollRight} > <AiOutlineRight color={'black'} /> </button> </div> </div> ); }; export default EpisodeSection;
// // ErrorView.swift // Tournament // // Created by Øyvind Hauge on 26/04/2024. // import SwiftUI struct ErrorView: View { var error: Error var action: (() -> Void)? init(_ error: Error, action: (() -> Void)? = nil) { self.error = error self.action = action } var body: some View { VStack { Spacer() HStack { Spacer() Image(systemName: "flame") .renderingMode(.template) .font(Font.system(size: 56)) Spacer() } .padding(.top, 16) .padding(.bottom, 8) Text("Oops! There was an error...") .font(Font.system(size: 20, weight: .bold)) .frame(maxWidth: .infinity, alignment: .center) .multilineTextAlignment(.center) .foregroundStyle(Color.Text.normal) .padding(.horizontal, 16) .padding(.bottom, 2) Text(error.localizedDescription) .font(Font.system(size: 17, weight: .medium)) .frame(maxWidth: .infinity, alignment: .center) .multilineTextAlignment(.center) .foregroundStyle(Color.Text.subtitle) .padding(.horizontal, 16) .padding(.bottom, 16) if let action = action { Button(action: action) { Text("Retry") .frame(maxWidth: .infinity) } .buttonStyle(SecondaryButtonStyle()) } Spacer() } .padding(.horizontal, 16) .background(.white) .clipShape(RoundedRectangle(cornerRadius: 8)) } }
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\siswaRequest; use App\Http\Requests\siswaUpdateRequest; use App\Models\kelas; use App\Models\siswa; use App\Models\spp; use App\Models\User; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; class siswaController extends Controller { public function __construct() { $this->middleware(['admin', 'auth']); } public function index() { $siswa = siswa::with(['kelas', 'spp'])->orderBy('created_at', 'desc')->get(); $spp = spp::all(); $kelas = kelas::all(); return view('admin.siswa', compact('siswa', 'spp', 'kelas')); } /** * Show the form for creating a new resource. */ public function create() { } /** * Store a newly created resource in storage. */ public function store(siswaRequest $request) { try { $request->validated(); $spp = spp::where('code', $request->id_spp)->firstOrFail(); $kelas = kelas::where('code', $request->id_kelas)->firstOrFail(); if ($request->hasFile('image')) { $image = $request->file('image')->store('images/profile', 'public'); } siswa::create([ 'code' => Str::uuid(), 'nisn' => $request->nisn, 'nis' => $request->nis, 'name' => $request->name, 'alamat' => $request->alamat, 'telp' => $request->telp, 'image' => $image, 'id_kelas' => $kelas->id, 'id_spp' => $spp->id, ]); $siswa = siswa::where('nisn', $request->nisn)->first(); User::create([ 'code' => Str::uuid(), 'username' => $request->nisn, 'password' => bcrypt($request->nis), 'siswa_id' => $siswa->id, 'role_id' => 3, ]); } catch (\Throwable $th) { return redirect()->back()->with('error', 'siswa gagal di buat!'); } return redirect()->back()->with('success', 'siswa berhasil di buat!'); } /** * Display the specified resource. */ public function show(string $id) { // } /** * Show the form for editing the specified resource. */ public function edit(string $id) { // } /** * Update the specified resource in storage. */ public function update(siswaUpdateRequest $request) { try { $data = siswa::where('code', $request->id)->firstOrFail(); if ($request->hasFile('image')) { if ($request->image && Storage::disk('public')->exists($data->image)) { Storage::disk('public')->delete($data->image); } $newImage = $request->file('image')->store('images/profile', 'public'); } $data->update([ 'nisn' => $request->nisn ?? $data->nisn, 'nis' => $request->nis ?? $data->nis, 'name' => $request->name ?? $data->name, 'alamat' => $request->alamat ?? $data->alamat, 'telp' => $request->telp ?? $data->telp, 'id_kelas' => $request->id_kelas ?? $data->id_kelas, 'id_spp' => $request->id_spp ?? $data->id_spp, 'image' => $newImage ?? $data->image, 'update_at' => Carbon::now() ]); User::where('siswa_id', $data->id)->first()->update([ 'username' => ($request->nisn == null) ? $data->nisn : $request->nisn, 'password' => ($request->nis == null) ? bcrypt($data->nis) : bcrypt($request->nis), ]); } catch (\Throwable $th) { return redirect()->back()->with('error', 'siswa gagal di update!'); } return redirect()->back()->with('success', 'siswa berhasil di update!'); } /** * Remove the specified resource from storage. */ public function destroy(string $id) { try { $data = siswa::where('code', $id)->firstOrFail(); if ($data->image && Storage::disk('public')->exists($data->image)) { Storage::disk('public')->delete($data->image); } $data->delete(); } catch (\Throwable $th) { return redirect()->back()->with('error', 'siswa gagal di hapus!'); } return redirect()->back()->with('success', 'siswa berhasil di hapus!'); } }
using PDDL, SymbolicPlanners """ ActionCommand A sequence of one or more actions to be executed, with optional predicate modifiers for action arguments. """ struct ActionCommand "Actions to be executed." actions::Vector{Term} "Predicate modifiers for action arguments." predicates::Vector{Term} "Free variables in lifted actions." vars::Vector{Var} "Types of free variables." vtypes::Vector{Symbol} end ActionCommand(actions, predicates) = ActionCommand(actions, predicates, Var[], Symbol[]) Base.hash(cmd::ActionCommand, h::UInt) = hash(cmd.vtypes, hash(cmd.vars, hash(cmd.predicates, hash(cmd.actions, h)))) Base.:(==)(cmd1::ActionCommand, cmd2::ActionCommand) = cmd1.actions == cmd2.actions && cmd1.predicates == cmd2.predicates && cmd1.vars == cmd2.vars && cmd1.vtypes == cmd2.vtypes Base.issetequal(cmd1::ActionCommand, cmd2::ActionCommand) = issetequal(cmd1.actions, cmd2.actions) && issetequal(cmd1.predicates, cmd2.predicates) && length(cmd1.vars) == length(cmd2.vars) && Dict(zip(cmd1.vars, cmd1.vtypes)) == Dict(zip(cmd2.vars, cmd2.vtypes)) Base.issubset(cmd1::ActionCommand, cmd2::ActionCommand) = issubset(cmd1.actions, cmd2.actions) && issubset(cmd1.predicates, cmd2.predicates) && issubset(Dict(zip(cmd1.vars, cmd1.vtypes)), Dict(zip(cmd2.vars, cmd2.vtypes))) function Base.merge(cmd1::ActionCommand, cmd2::ActionCommand) actions = unique!(vcat(cmd1.actions, cmd2.actions)) predicates = unique!(vcat(cmd1.predicates, cmd2.predicates)) vdict1 = Dict(zip(cmd1.vars, cmd1.vtypes)) vdict2 = Dict(zip(cmd2.vars, cmd2.vtypes)) vdict = merge(vdict1, vdict2) vars = collect(keys(vdict)) vtypes = collect(values(vdict)) return ActionCommand(actions, predicates, vars, vtypes) end function Base.show(io::IO, ::MIME"text/plain", command::ActionCommand) action_str = join(write_pddl.(command.actions), " ") print(io, action_str) if !isempty(command.predicates) print(io, " where ") pred_str = join(write_pddl.(command.predicates), " ") print(io, pred_str) end end function Base.show(io::IO, ::MIME"text/llm", command::ActionCommand) command = type_to_itemtype(drop_unpredicated_vars(command)) action_str = join(write_pddl.(command.actions), " ") action_str = filter(!=('?'), action_str) print(io, action_str) if !isempty(command.predicates) print(io, " where ") pred_str = join(write_pddl.(command.predicates), " ") pred_str = filter(!=('?'), pred_str) print(io, pred_str) end end "Replace arguments in an action command with variables." function lift_command(command::ActionCommand, state::State; ignore = [pddl"(me)", pddl"(you)"], type_name_fn = (s, o) -> string(get_item_type(s, o))) args_to_vars = Dict{Const, Var}() name_count = Dict{String, Int}() vars = Var[] vtypes = Symbol[] actions = map(command.actions) do act args = map(act.args) do arg arg in ignore && return arg arg isa Const || return arg var = get!(args_to_vars, arg) do type = PDDL.get_objtype(state, arg) name = type_name_fn(state, arg) count = get(name_count, name, 0) + 1 name_count[name] = count name = Symbol(uppercasefirst(name), count) v = Var(name) push!(vars, v) push!(vtypes, type) return v end return var end return Compound(act.name, args) end predicates = map(command.predicates) do pred pred isa Compound || return pred args = map(pred.args) do arg arg isa Const || return arg return get(args_to_vars, arg, arg) end return Compound(pred.name, args) end return ActionCommand(actions, predicates, vars, vtypes) end "Grounds a lifted action command into a set of ground action commands." function ground_command(command::ActionCommand, domain::Domain, state::State) vars = command.vars types = command.vtypes # Return original command if it has no variables length(vars) == 0 && return [command] # Find all possible groundings typeconds = Term[Compound(ty, Term[var]) for (ty, var) in zip(types, vars)] neqconds = Term[Compound(:not, [Compound(:(==), Term[vars[i], vars[j]])]) for i in eachindex(vars) for j in 1:i-1] conds = [command.predicates; neqconds; typeconds] substs = satisfiers(domain, state, conds) g_commands = ActionCommand[] for s in substs actions = map(act -> PDDL.substitute(act, s), command.actions) predicates = map(pred -> PDDL.substitute(pred, s), command.predicates) push!(g_commands, ActionCommand(actions, predicates)) end # Remove duplicate groundings according to set equality unique_g_commands = ActionCommand[] for g_cmd in g_commands if !any(issetequal(g_cmd, ug_cmd) for ug_cmd in unique_g_commands) push!(unique_g_commands, g_cmd) end end return unique_g_commands end "Converts object types in a command to item types." function type_to_itemtype(command::ActionCommand) vars = Var[] vtypes = Symbol[] predicates = Term[] for pred in command.predicates if pred.name == :itemtype push!(vars, pred.args[1]) push!(vtypes, pred.args[2].name) else push!(predicates, pred) end end for (var, ty) in zip(command.vars, command.vtypes) var in vars && continue push!(vars, var) push!(vtypes, ty) end return ActionCommand(command.actions, predicates, vars, vtypes) end "Drop variables from an action command that are not predicated." function drop_unpredicated_vars(command::ActionCommand) predicated = Var[] for pred in command.predicates for arg in pred.args arg isa Var || continue push!(predicated, arg) end end unpredicated = setdiff(command.vars, predicated) actions = map(command.actions) do act args = filter(!in(unpredicated), act.args) return Compound(act.name, args) end vars = Var[] types = Symbol[] for (var, ty) in zip(command.vars, command.vtypes) var in unpredicated && continue push!(types, ty) end return ActionCommand(actions, command.predicates, vars, types) end "Statically check if a ground action command is possible in a domain and state." function is_command_possible( command::ActionCommand, domain::Domain, state::State; speaker = pddl"(actor)", listener = pddl"(helper)", statics = PDDL.infer_static_fluents(domain) ) possible = true command = pronouns_to_names(command; speaker, listener) for act in command.actions # Substitute and simplify precondition precond = PDDL.get_precond(domain, act) # Append predicates preconds = append!(PDDL.flatten_conjs(precond), command.predicates) precond = Compound(:and, preconds) # Simplify static terms precond = PDDL.dequantify(precond, domain, state) precond = PDDL.simplify_statics(precond, domain, state, statics) possible = precond.name != false end return possible end "Convert an action command to one or more goal formulas." function command_to_goals( command::ActionCommand; speaker = pddl"(actor)", listener = pddl"(helper)", act_goal_map = Dict( :grab => act -> begin item = act.args[2] if item isa Var item = Const(Symbol(lowercase(string(item.name)))) end return Compound(:placed, Term[item, pddl"(table1)"]) end ) ) vars = command.vars types = command.vtypes # Convert each action to goal goals = map(command.actions) do action action = pronouns_to_names(action; speaker, listener) goal = act_goal_map[action.name](action) return PDDL.flatten_conjs(goal) end goals = reduce(vcat, goals) # Convert to existential quantifier if variables are present if !all(PDDL.is_ground.(goals)) && !isempty(vars) # Find predicate constraints which include some variables constraints = filter(pred -> any(arg in vars for arg in pred.args), command.predicates) # Construct type constraints typeconds = Term[Compound(ty, Term[v]) for (ty, v) in zip(types, vars)] typecond = length(typeconds) > 1 ? Compound(:and, typeconds) : typeconds[1] neqconds = Term[Compound(:not, [Compound(:(==), Term[vars[i], vars[j]])]) for i in eachindex(vars) for j in 1:i-1] # Construct existential quantifier body = Compound(:and, append!(goals, neqconds, constraints)) goals = [Compound(:exists, Term[typecond, body])] end return goals end "Replace speaker and listener names with pronouns." function names_to_pronouns( command::ActionCommand; speaker = pddl"(actor)", listener = pddl"(helper)" ) actions = map(command.actions) do act names_to_pronouns(act; speaker, listener) end predicates = map(command.predicates) do pred names_to_pronouns(pred; speaker, listener) end return ActionCommand(actions, predicates, command.vars, command.vtypes) end function names_to_pronouns( term::Compound; speaker = pddl"(actor)", listener = pddl"(helper)" ) new_args = map(term.args) do arg if arg == speaker pddl"(me)" elseif arg == listener pddl"(you)" else names_to_pronouns(arg; speaker, listener) end end return Compound(term.name, new_args) end names_to_pronouns(term::Var; kwargs...) = term names_to_pronouns(term::Const; kwargs...) = term "Replace pronouns with speaker and listener names." function pronouns_to_names( command::ActionCommand; speaker = pddl"(actor)", listener = pddl"(helper)" ) actions = map(command.actions) do act pronouns_to_names(act; speaker, listener) end predicates = map(command.predicates) do pred pronouns_to_names(pred; speaker, listener) end return ActionCommand(actions, predicates, command.vars, command.vtypes) end function pronouns_to_names( term::Compound; speaker = pddl"(actor)", listener = pddl"(helper)" ) new_args = map(term.args) do arg if arg == pddl"(me)" speaker elseif arg == pddl"(you)" listener else pronouns_to_names(arg; speaker, listener) end end return Compound(term.name, new_args) end pronouns_to_names(term::Var; kwargs...) = term pronouns_to_names(term::Const; kwargs...) = term "Extract focal objects from an action command or plan." function extract_focal_objects( command::ActionCommand; obj_arg_idxs = Dict(:pickup => 2, :handover => 3, :unlock => 3) ) objects = Term[] for act in command.actions act.name in keys(obj_arg_idxs) || continue idx = obj_arg_idxs[act.name] obj = act.args[idx] push!(objects, obj) end return unique!(objects) end function extract_focal_objects( plan::AbstractVector{<:Term}; obj_arg_idxs = Dict(:grab => 2), listener = pddl"(helper)" ) focal_objs = Term[] for act in plan act.args[1] == listener || continue act.name in keys(obj_arg_idxs) || continue idx = obj_arg_idxs[act.name] obj = act.args[idx] push!(focal_objs, obj) end return unique!(focal_objs) end "Extract focal objects from a plan that matches a lifted action command." function extract_focal_objects_from_plan( command::ActionCommand, plan::AbstractVector{<:Term}; obj_arg_idxs = Dict(:grab => 2), speaker = pddl"(actor)", listener = pddl"(helper)" ) focal_vars = extract_focal_objects(command; obj_arg_idxs) focal_objs = Term[] command = pronouns_to_names(command; speaker, listener) for cmd_act in command.actions for act in plan unifiers = PDDL.unify(cmd_act, act) isnothing(unifiers) && continue for var in focal_vars if haskey(unifiers, var) push!(focal_objs, unifiers[var]) end end end end return unique!(focal_objs) end
# Enphase Envoy legacy support [![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg?style=for-the-badge)](https://github.com/hacs/integration#readme) This is a HACS custom integration providing an Envoy Legacy HTML production data extension to the [Home Assistant Core Enphase Envoy integration](https://www.home-assistant.io/integrations/enphase_envoy) for [enphase envoys/IQ Gateways](https://enphase.com/en-us/products-and-services/envoy-and-combiner). This custom integration is NOT a replacement for the HA Enphase Envoy integration. You still need to configure the HA Enphase Envoy integration to communicate with any Envoy type. This custom integration registers a custom updater for [pyenphase](https://github.com/pyenphase/pyenphase), which is the communication module used by HA Enphase Envoy. Once this updater is registered, Envoy production data for legacy Envoy can be collected by the HA Core Enphase Envoy integration from the HTML pages used by Envoy firmware's < 3.9 You should only deploy this custom integration when running an Enphase Envoy legacy model with firmware before 3.9, either stand-alone or in a mixed environment with newer models. The registered updater is only used for communication to the legacy Envoy, not for communication to the newer models. Only use with Home Assistant 2023.12 or newer. ## Installation 1. Make appropriate backups of you Home Assistant installation and data. 2. Install [HACS](https://hacs.xyz/) if you haven't already 3. Add this GITHUB repository as a [custom integration repository](https://hacs.xyz/docs/faq/custom_repositories) in HACS 4. Restart Home Assistant 5. Go to the HACS Integrations page in HA, select this custom repository and download the `Enphase Envoy legacy support` custom integration 6. After download restart Home Assistant. 7. Add the custom integration using the home assistant configuration flow and select the `Enphase Envoy Legacy Support' integration If you decide to install this manually without the use of HACS, then make sure to only place the files in custom_components/enphase_envoy_legacy_support from this repository into the folder /config/custom_components/enphase_envoy_legacy_support on your Home Assistant system. ## Usage Once the custom integration is added, no further configuration is needed for this custom integration. All setup of the Envoy is to be done in the HA Core Enphase Envoy integration. This custom integration or the HA Core Enphase Envoy integration can be added in any order, but as long as this custom integration is not added, HA Core Enphase Envoy can not successfully communicate with the legacy Envoy. With a fresh Home Assistant installation that needs to communicate with a legacy Envoy best first add this custom integration to enable successful adding of the legacy Envoy next. For Home Assistant installations that went through upgrades and now show the legacy Envoy failing, installation of this custom integration will solve the issues as soon as installed. For Home Assistant installation currently using another custom integration enabling the legacy Envoy and plan to switch to the HA Core Enphase Envoy, first install this custom integration to prepare for such a switch. As this custom integration registers with pyenphase there's no interaction with other custom integrations. How to migrate from other custom integrations to the HA Core one is not in the scope of this document. ## Add the integration Once the custom integration is added to your system using HACS, configure it as described in [Adding Integrations](https://www.home-assistant.io/getting-started/integration/). Search for `enphase` and select `Enphase Envoy Legacy Support` ![picture of Search for Enphase integrations](docs/Add_Enphase_Legacy_Integration.PNG "Search for Enphase integrations") There is no further configuration information needed and the integration is created. ![picture of Custom integration configured](docs/Add_Enphase_Legacy_Integration+done.PNG "Custom integration configured") The newly added custom integrations shows in the integrations dashboard ![picture of configured custom integration in integrations dashboard](docs/Added_Enphase_Legacy_Integration.PNG "configured custom integration in integrations dashboard") In the integration details it shows as a service. The `add service` button will not add any more services. Only 1 can be added and is sufficient. ![picture of Integration details](docs/Added_Enphase_Legacy_Integration_Service.PNG "Integration details") ## Legacy Envoy data A legacy Envoy only provides production data. ![picture of Envoy Legacy entities](docs/Added_Enphase_Legacy_Integration_Entities.PNG "Envoy Legacy entities")
import { useEffect, useState, memo } from "react"; import { ToastContainer, toast } from "react-toastify"; import 'react-toastify/dist/ReactToastify.css'; import './Card.css'; function Card({item, setCart, cart}) { const [imageURL, setImageURL] = useState(""); const [disabled, setDisabled] = useState(false); useEffect(() => { import(`../assets/images/${item._id}.jpg`).then((module) => { setImageURL(module.default); }); }, [item._id]); // Add item._id as a dependency to refresh the image when item changes function addToCart() { if (!disabled) { setCart((prevCart) => { const existingItemIndex = prevCart.findIndex(i => i._id === item._id); if (existingItemIndex !== -1) { // Item is already in the cart toast.warning('Item is already in the cart.', { position: "top-center", autoClose: 3000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); return prevCart; } else { // Item is not in the cart toast.success('🤤 Booking the table for you!', { position: "top-center", autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); return [...prevCart, { ...item, quantity: 1 }]; } }); // Disable the button after adding the item setDisabled(true); } } return ( <div className="Card"> <div className="Card-inner"> <div className="Card-inner-left"> <img src={imageURL} alt={item.name} /> </div> <div className="Card-inner-right"> <div> <div className="title">{item.name}</div> <div className="desc">Savor the flavors!</div> </div> <div> <div className="price">Rs. {item.price}</div> <button onClick={addToCart} disabled={disabled}>Book now</button> </div> </div> </div> <ToastContainer /> </div> ); } export default memo(Card);
package com.jgeun.pokedex.core.network.api import com.jgeun.pokedex.core.model.common.NetworkResult import com.jgeun.pokedex.core.network.model.dto.PokemonInfoDto import com.jgeun.pokedex.core.network.model.response.PokemonResponse import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface PokedexService { @GET("pokemon") suspend fun fetchPokemonList( @Query("limit") limit: Int = 20, @Query("offset") offset: Int = 0 ): NetworkResult<PokemonResponse> @GET("pokemon/{name}") suspend fun fetchPokemonInfo( @Path("name") name: String ): NetworkResult<PokemonInfoDto> }
import { createContext, useReducer } from "react"; import { CalculateNutritions } from "../meal-editor/utils/calculate-nutritions"; const stateStack = []; const initialState = { ingredientList: {}, nutritionList: {}, foodProperties: { uniqueFoodID: "", foodName: "", foodWeight: 100, foodUnit: "g", foodImage: "", foodImageChanged: false }, changed: false, lisIsEmpty: false, back: false, refetch: { reFetchID: "", reFetchNewID: "", needReFetch: false, } }; const ingredientContext = createContext(); const addIngredientHandler = (state, action) => { let tempState = { ...state }; if (action.payload) { let isDuplicate = false; for (const ingredient in state.ingredientList) { if (action.payload.item._id === ingredient.id) { isDuplicate = true; break; } } if (isDuplicate) return state; tempState.ingredientList[action.payload.item._id] = { item: { ...action.payload.item }, types: action.payload.type ? action.payload.type : Object.keys(action.payload.item.types)[0], weight: action.payload.weight ? parseFloat(action.payload.weight) : 100, unit: action.payload.unit ? action.payload.unit : "g", }; } tempState.changed = true; return tempState; }; const removeIngredientHandler = (state, action) => { let tempState = { ...state }; delete tempState.nutritionList[action.payload]; delete tempState.ingredientList[action.payload]; tempState.changed = true; return tempState; }; const ingredientChangeHandler = (state, action) => { let tempState = { ...state }; tempState.ingredientList[action.payload.id][action.payload.type] = action.payload.value; let nutritions = CalculateNutritions( tempState.ingredientList[action.payload.id] ); tempState.nutritionList[action.payload.id] = nutritions; tempState.changed = true; return tempState; }; const setUniqueFoodID = (state, payload) => { let tempState = { ...state }; tempState.foodProperties.uniqueFoodID = payload; return tempState; }; const setChangedToFalse = (state) => { const tempState = { ...state }; tempState.changed = false; return tempState; }; const popState = (state) => { let tempState = stateStack.pop(); if (stateStack.length <= 0) { tempState.back = false; } if (state.refetch) { tempState.refetch.needReFetch = true; tempState.refetch.reFetchID = state.refetch.reFetchID; tempState.refetch.reFetchNewID = state.foodProperties.uniqueFoodID; } return tempState; }; const updateItemData = (state, payload) => { let tempState = { ...state }; tempState.refetch.needReFetch = false; delete tempState.nutritionList[state.refetch.reFetchID]; delete tempState.ingredientList[state.refetch.reFetchID]; let newItem = payload.food; tempState.ingredientList[newItem._id] = { item: { ...newItem }, types: payload.type ? payload.type : Object.keys(newItem.types)[0], weight: payload.weight ? parseFloat(payload.weight) : 100, unit: payload.unit ? payload.unit : "g", }; let nutritions = CalculateNutritions( tempState.ingredientList[newItem._id] ); tempState.nutritionList[newItem._id] = nutritions; tempState.changed = true; return tempState; }; const pushState = (state, payload) => { let tempState; if (payload.emptyPush) { if (!state.back) { let emptyState = { ingredientList: {}, nutritionList: {}, foodProperties: { uniqueFoodID: "", foodName: "", foodWeight: "", }, changed: false, lisIsEmpty: false, back: false, refetch: { reFetchID: "", reFetchNewID: "", needReFetch: false } }; stateStack.push({ ...emptyState }) tempState = { ...state }; tempState.uniqueFoodID = payload.uniqueFoodID; tempState.back = true; return tempState; } else { return state; } } else { stateStack.push({ ...state }); tempState = { ingredientList: {}, nutritionList: {}, foodProperties: { uniqueFoodID: payload.uniqueFoodID, foodName: "", }, changed: false, lisIsEmpty: false, back: true, refetch: { reFetchID: payload.uniqueFoodID, reFetchNewID: "", needReFetch: false } }; } return tempState; }; const changeFoodProperties = (state, payload) => { let tempState = { ...state }; if (payload.foodName) tempState.foodProperties.foodName = payload.foodName; if (payload.foodWeight) tempState.foodProperties.foodWeight = payload.foodWeight; if (payload.foodUnit) tempState.foodProperties.foodUnit = payload.foodUnit; if (payload.foodImage) tempState.foodProperties.foodImage = payload.foodImage; if (payload.foodImageChanged !== undefined) { tempState.foodProperties.foodImageChanged = payload.foodImageChanged; } return tempState; } const rootReducer = (state, action) => { switch (action.type) { case "addIngredient": return addIngredientHandler(state, action); case "removeIngredient": return removeIngredientHandler(state, action); case "changeIngredient": return ingredientChangeHandler(state, action); case "setUniqueFoodID": return setUniqueFoodID(state, action.payload); case "setChangedToFalse": return setChangedToFalse(state); case "pushState": return pushState(state, action.payload); case "popState": return popState(state); case "updateItemData": return updateItemData(state, action.payload); case "changeFoodProperties": return changeFoodProperties(state, action.payload); default: return state; } }; const IngredientProvider = ({ children, testValue }) => { const [state, dispatch] = useReducer(rootReducer, initialState); // console.log('stack',stateStack); // console.log('state',state); return ( <ingredientContext.Provider value={testValue ? {...testValue} : { state, dispatch }}> {children} </ingredientContext.Provider> ); }; export { ingredientContext, IngredientProvider };
// lib/screens/home_screen.dart import 'package:expense_tracker_provider/screens/add_expense_screen.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:expense_tracker_provider/providers/expense_provider.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); @override Widget build(BuildContext context) { final expenseProvider = Provider.of<ExpenseProvider>(context); return Scaffold( appBar: AppBar( title:const Text('Expense Tracker'), ), body: ListView.builder( itemCount: expenseProvider.expenses.length, itemBuilder: (context, index) { final expense = expenseProvider.expenses[index]; return ListTile( title: Text(expense.title), subtitle: Text('\$${expense.amount.toStringAsFixed(2)}'), trailing: IconButton( icon:const Icon(Icons.delete), onPressed: () { expenseProvider.removeExpense(expense.id); }, ), ); }, ), floatingActionButton: FloatingActionButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) =>const AddExpenseScreen(), ), ); // Navigate to a screen to add a new expense (not implemented yet) }, child: const Icon(Icons.add), ), ); } }
// // NFTListViewController.swift // DinzWeb3 // // Created by Dino Bozic on 03.03.2024.. // import Foundation import UIKit import Combine class NFTListViewController: UIViewController { var viewModel: NFTListViewModeling //MARK: - Views lazy var contentView: NFTListContentView = { let view = NFTListContentView() view.tableView.dataSource = self view.tableView.delegate = self return view }() //MARK: - Properties private var cancellables = Set<AnyCancellable>() init(viewModel: NFTListViewModeling) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) view.backgroundColor = UIStyle.Color.Background.primary } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() addSubviews() setConstraints() observe() viewModel.onViewDidLoad() } private func addSubviews() { view.addSubview(contentView) } private func setConstraints() { contentView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ contentView.topAnchor.constraint(equalTo: view.topAnchor), contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor), contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } private func observe() { viewModel.reloadTablePublisher .receive(on: DispatchQueue.main) .sink { [weak self] _ in guard let self else { return } self.contentView.tableView.reloadData() }.store(in: &cancellables) } } extension NFTListViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { viewModel.dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch viewModel.dataSource[indexPath.row] { case .nft(let cellViewModel): let cell: NFTListItemTableViewCell = tableView.dequeueCellAtIndexPath(indexPath: indexPath) cell.setup(cellViewModel) return cell } } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { viewModel.willDisplay(at: indexPath.row) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch viewModel.dataSource[indexPath.row] { case .nft(let cellViewModel): viewModel.routeToNFTDetails(nft: cellViewModel.nft) } } }
import styles from "./Tasks.module.css"; import { crosLight, filterLightLogo, plusLogo, sortLightLogo, } from "../../assets/index.js"; import Task from "./Task.jsx"; import NewTask from "./NewTask.jsx"; import { useEffect, useState } from "react"; import { TasksFilterCard } from "../UI/FunctionCard.jsx"; import EditTask from "./EditTask.jsx"; import { taskAction } from "../../store/tasks.js"; import { useDispatch, useSelector } from "react-redux"; import Message from "../UI/Message..jsx"; import { uiAction } from "../../store/ui.js"; const URL = import.meta.env.VITE_SERVER_URL; const Tasks = () => { const dispatch = useDispatch(); const [isNewTask, setIsNewTask] = useState(false); const [isEditTask, setEditTask] = useState(false); const [isFilterShow, setIsFilterShow] = useState(false); const [isShortShow, setIsShortShow] = useState(false); const [sortBy, setSortBy] = useState("Default"); const [filterBy, setFilterBy] = useState("All"); const [singleTask, setSingleTask] = useState(""); const searchData = useSelector((state) => state.task.searchData); const isMessage = useSelector((state) => state.ui.isMessage); const message = useSelector((state) => state.ui.message); const messageType = useSelector((state) => state.ui.messageType); const newTaskHandler = () => { if (!isEditTask) { setIsNewTask((pre) => !pre); } setEditTask(false); }; const filterHandler = (value, e, data) => { e.stopPropagation(); setIsFilterShow(value); setIsShortShow(false); setFilterBy(data); }; const shorterHandler = (value, e, data) => { e.stopPropagation(); setIsShortShow(value); setIsFilterShow(false); setSortBy(data); }; const editTaskHandler = (data) => { setEditTask(true); setIsNewTask(false); window.scrollTo(0, 0); const url = URL + `singletask?taskId=${data}`; fetch(url, { method: "GET", credentials: "include", headers: { "Content-Type": "application/json", }, }) .then((response) => { if (!response.ok) { throw new Error("task delete issue"); } return response.json(); }) .then((data) => { setSingleTask(data.data); }) .catch((err) => { console.log(err); dispatch( uiAction.errorMessageHandler({ message: "Something went wrong!" }), ); }); }; const getTasks = () => { if (sortBy && filterBy) { const url = URL + `task?sorts=${sortBy === "Default" ? "" : sortBy}&filter=${filterBy === "All" ? "" : filterBy}&search=${searchData}`; fetch(url, { method: "GET", credentials: "include" }) .then((response) => { if (!response.ok) { throw new Error("task get issue"); } return response.json(); }) .then((data) => { dispatch(taskAction.replaceTask({ tasks: data.data })); }) .catch((err) => { console.log(err); dispatch( uiAction.errorMessageHandler({ message: "Something went wrong!" }), ); }); } }; useEffect(() => { getTasks(); }, [filterBy, sortBy, searchData]); const closeMessage = () => { dispatch(uiAction.closeMessageHandler()); }; useEffect(() => { const messageHideHandler = setTimeout(() => { dispatch(uiAction.closeMessageHandler()); }, 5000); return () => { clearTimeout(messageHideHandler); }; }, [isMessage, message]); return ( <div className={styles["tasks-container"]}> {isMessage && ( <Message message={message} type={messageType} closeHandler={closeMessage} /> )} <div className={styles["task-header"]}> <p>Task Board</p> <div className={styles["task-header-options"]}> <div onClick={newTaskHandler} className={`${styles["create-task"]} ${isNewTask ? styles["close-task"] : ""} ${isEditTask ? styles["close-task"] : ""}`} > <div className={styles["create-task-logo"]}> <img src={isNewTask ? crosLight : isEditTask ? crosLight : plusLogo} alt={"plusLogo"} /> </div> {isNewTask && <p>Close New</p>}{" "} {!isEditTask && !isNewTask && <p>Add New</p>}{" "} {isEditTask && <p>Close Edit</p>} </div> <div className={styles["filter"]} onClick={(e) => filterHandler(true, e)} > <img onClick={(e) => filterHandler(true, e)} src={filterLightLogo} alt={"filter"} /> {isFilterShow && ( <TasksFilterCard optionHandlder={filterHandler} options={["All", "Completed", "Pending"]} /> )} </div> <div className={styles["sort"]} onClick={(e) => shorterHandler(true, e)} > <img src={sortLightLogo} alt={"sort"} /> {isShortShow && ( <TasksFilterCard options={["Default", "Date", "Priority"]} optionHandlder={shorterHandler} /> )} </div> </div> </div> {isNewTask && <NewTask />} {isEditTask && <EditTask singleTask={singleTask} />} <Task editTaskHandler={editTaskHandler} /> </div> ); }; export default Tasks;
import Image from "next/image"; import { useTable, useExpanded, useSortBy } from "react-table"; export default function Table(props: any) { const { id, data, columns, actions } = props; const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({ columns, data }, useSortBy, useExpanded); return ( <div className="table-container"> <table id={id} {...getTableProps()} className="dashboard-table"> <thead> {headerGroups.map((headerGroup: any, x: number) => ( <tr {...headerGroup.getHeaderGroupProps()} key={x}> {headerGroup.headers.map((column: any, y: number) => { const { id } = column; const className = id .split("") .map((letter: any, idx: any) => { return letter.toUpperCase() === letter ? `${idx !== 0 ? "-" : ""}${letter.toLowerCase()}` : letter; }) .join(""); return ( <th className={className} {...column.getHeaderProps(column.getSortByToggleProps())} key={y} > {column.render("Header")} {/*{console.log({ test: column })}*/} {column?.isSorted ? ( <Image src="/svg/up-down.svg" alt="Arrow Down" width={10} height={10} key={y} /> ) : ( <span className="sort" key={y} /> )} </th> ); })} </tr> ))} </thead> <tbody {...getTableBodyProps()}> {rows.map((row: any, i: number) => { prepareRow(row); return ( <tr {...row.getRowProps()} onClick={ actions && actions.clickRow ? () => actions.clickRow(row.original) : null } key={i} > {row.cells.map((cell: any, q: number) => { const string = cell.column.Header.toLowerCase(); const className = string.split(" ").join("-"); const cellProps = { ...cell.getCellProps() }; const activeCol = string === "active"; return ( <td {...cellProps} className={className} onClick={ activeCol ? null : actions && actions.clickCell ? () => actions.clickCell(row.original) : null } key={q} > {cell.render("Cell")} </td> ); })} </tr> ); })} </tbody> </table> </div> ); }
using CarControl.Models; using MahApps.Metro.Controls; using Npgsql; using System; using System.Collections.Generic; using System.Globalization; using System.Windows; using System.Windows.Controls; namespace CarControl.Windows { /// <summary> /// Lógica interna para NovoRecebimentoWindow.xaml /// </summary> public partial class NovoRecebimentoWindow : MetroWindow { NpgsqlConnection conn = new(); List<Recebimento> recebimentoList = new(); public NovoRecebimentoWindow(NpgsqlConnection connection) { conn = connection; InitializeComponent(); MostrarRecebimentos(); } private void MostrarRecebimentos() { dg.ItemsSource = null; recebimentoList.Clear(); string sql = ($"SELECT idrecebimento, nome_cliente, valororiginal, valorrecebido, recebimento_dia_previsto, dhrecebimento, em_aberto FROM vw_recebimento WHERE em_aberto = TRUE ORDER BY idrecebimento;"); NpgsqlCommand cmd = new NpgsqlCommand(sql, conn); using (NpgsqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { #region lendo alugueis Recebimento recebimento = new( reader.GetInt32(0), reader.GetString(1), reader.GetDouble(2), reader.IsDBNull(3) ? null : reader.GetDouble(3), DateOnly.FromDateTime(reader.GetDateTime(4)), reader.IsDBNull(5) ? null : reader.GetDateTime(5), reader.GetBoolean(6) ); #endregion recebimentoList.Add(recebimento); } reader.Close(); dg.ItemsSource = recebimentoList; } } private void MostrarDetalhes(int idRecebimento) { LimpaLabels(); string sql = ($"SELECT * FROM vw_recebimento WHERE idrecebimento = {idRecebimento};"); NpgsqlCommand cmd = new NpgsqlCommand(sql, conn); using (NpgsqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { idRecebimentoLabel.Content = idRecebimentoLabel.Content + reader.GetInt32(0).ToString(); idAluguelLabel.Content = idAluguelLabel.Content + reader.GetInt32(1).ToString(); dhAluguelLabel.Content = dhAluguelLabel.Content + reader.GetDateTime(2).ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture); idDevolucaoLabel.Content = idDevolucaoLabel.Content + (reader.IsDBNull(3) ? null : reader.GetInt32(3).ToString()); dhDevolucaoLabel.Content = dhDevolucaoLabel.Content + (reader.IsDBNull(3) ? null : reader.GetDateTime(4).ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)); idClienteLabel.Content = idClienteLabel.Content + reader.GetInt32(5).ToString(); nomeClienteLabel.Content = nomeClienteLabel.Content + reader.GetString(6); idModeloLabel.Content = idModeloLabel.Content + reader.GetInt32(7).ToString(); nomeModeloLabel.Content = nomeModeloLabel.Content + reader.GetString(8); valorOriginalLabel.Content = valorOriginalLabel.Content + reader.GetDouble(9).ToString("C"); valorRecebidoLabel.Content = valorRecebidoLabel.Content + (reader.IsDBNull(10) ? null : reader.GetDouble(10).ToString("C")); dhRecebimentoLabel.Content = dhRecebimentoLabel.Content + (reader.IsDBNull(11) ? null : reader.GetDateTime(11).ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)); if (reader.GetBoolean(12)) emAbertoLabel.Content = emAbertoLabel.Content + "Sim"; else emAbertoLabel.Content = emAbertoLabel.Content + "Não"; diaPrevistoRecebimentoLabel.Content = diaPrevistoRecebimentoLabel.Content + reader.GetDateTime(13).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); } reader.Close(); } } private void DataGridRow_GotFocus(object sender, RoutedEventArgs e) { if (sender is DataGridRow row && row.Item is Recebimento selectedItem) MostrarDetalhes(selectedItem.IdRecebimento); } private void LimpaLabels() { idRecebimentoLabel.Content = "Id Recebimento: "; idAluguelLabel.Content = "Id Aluguel: "; dhAluguelLabel.Content = "Data do Aluguel: "; idDevolucaoLabel.Content = "Id Devolução: "; dhDevolucaoLabel.Content = "Data da Devolução: "; idClienteLabel.Content = "Id Cliente: "; nomeClienteLabel.Content = "Cliente: "; idModeloLabel.Content = "Id Modelo: "; nomeModeloLabel.Content = "Modelo: "; emAbertoLabel.Content = "Em Aberto: "; valorOriginalLabel.Content = "Valor original: "; valorRecebidoLabel.Content = "Valor recebido: "; dhRecebimentoLabel.Content = "Data do recebimento: "; diaPrevistoRecebimentoLabel.Content = "Data prevista: "; } private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == System.Windows.Input.Key.Escape) Close(); } private void FecharRecebimentoWindowBtn_Click(object sender, RoutedEventArgs e) { Close(); } private void ReceberBtn_Click(object sender, RoutedEventArgs e) { Recebimento r = dg.SelectedItem as Recebimento; if (r is not null) { MessageBoxResult messageBoxResult = MessageBox.Show("Deseja confirmar recebimento?", "Confirmar recebimento", MessageBoxButton.YesNo); if (messageBoxResult == MessageBoxResult.Yes) { double valorRecebido = r.ValorOriginal; int idrecebimento = r.IdRecebimento; var dhRecebimento = DateTime.Now; string sql = $"UPDATE recebimento SET valorrecebido = {valorRecebido}, dhrecebimento = '{dhRecebimento.ToString("dd-MM-yyyy HH:mm:ss")}', em_aberto = FALSE WHERE idrecebimento = {idrecebimento};"; NpgsqlCommand cmd = new NpgsqlCommand(sql, conn); cmd.ExecuteNonQuery(); MessageBox.Show("Recebimento efetuado com sucesso!", "Recebimento concluído"); Close(); } else Close(); } } } }
import { render, fireEvent, waitFor } from '@testing-library/react'; import React from 'react'; import useFocusEvents from '../useFocusEvents'; describe('useFocusEvents', () => { test('returns hasFocus as false when no element within the ref has focus', () => { const TestHook: React.FC = () => { const focusRef = React.useRef<HTMLDivElement>(null); const { hasFocus } = useFocusEvents(focusRef); return ( <div ref={focusRef}> <div data-testid="has-focus">{hasFocus.toString()}</div> </div> ); }; const { getByTestId } = render(<TestHook />); expect(getByTestId('has-focus').textContent).toBe('false'); }); test('returns hasFocus as true when an element within the ref has focus', async () => { const TestHook: React.FC = () => { const focusRef = React.useRef<HTMLDivElement>(null); const { hasFocus } = useFocusEvents(focusRef); return ( <div ref={focusRef}> <input data-testid="input" type="text" /> <div data-testid="has-focus">{hasFocus.toString()}</div> </div> ); }; const { getByTestId } = render(<TestHook />); const input = getByTestId('input'); fireEvent.focus(input); expect(getByTestId('has-focus').textContent).toBe('true'); }); test('calls onFocusIn when an element within the ref receives focus', () => { const onFocusIn = jest.fn(); const TestHook: React.FC = () => { const focusRef = React.useRef<HTMLDivElement>(null); useFocusEvents(focusRef, onFocusIn); return ( <div ref={focusRef}> <input data-testid="input" type="text" /> </div> ); }; const { getByTestId } = render(<TestHook />); const input = getByTestId('input'); fireEvent.focus(input); expect(onFocusIn).toHaveBeenCalled(); }); test('calls onFocusOut when an element within the ref loses focus', () => { const onFocusOut = jest.fn(); const TestHook: React.FC = () => { const focusRef = React.useRef<HTMLDivElement>(null); useFocusEvents(focusRef, null, onFocusOut); return ( <div ref={focusRef}> <input data-testid="input" type="text" /> </div> ); }; const { getByTestId } = render(<TestHook />); const input = getByTestId('input'); fireEvent.focus(input); expect(onFocusOut).not.toHaveBeenCalled(); fireEvent.blur(input); expect(onFocusOut).toHaveBeenCalled(); }); });
import React from 'react'; import Header from './Header'; import './DonorNot.css'; import { Navigate } from 'react-router-dom'; import EtaSection from './EtaSection'; const DonorNot = () => { const [notifications, setNotifications] = React.useState([ { id: 1, title: 'Pickup Request accepted', description: `A driver is on the way to pick up your donation id 1. Please hand over the donation to the driver when he/she arrives`, TimeToMeet: '2024-05-31T23:59:59.999Z', }, { id: 2, title: 'Driver Arrived!', description: `The driver has arriced to pick up your dontion id 2 at the specified location. Please hand over the donation to the driver. `, }, { id: 3, title: 'Driver Arrived!', description: `The driver has arriced to pick up your dontion id 2 at the specified location. Please hand over the donation to the driver. `, }, ]); const handleView = () => { console.log("View is clicked"); } const handleDelete = (id) => { const newNotifications = notifications.filter(notification => notification.id !== id); setNotifications(newNotifications); } return ( <div className="DonorNot"> <Header loggedIn={true} role="Donor"/> <h2 className='DonorNot-title'>Notifications</h2> <div className='DonorNot-notifications'> {notifications.map(notification => ( <div className="donation-preview" key={notification.id} > <h2 className='DonorNot-notifications-title'>{ notification.title }</h2> <div className="DonorNot-notifications-details"> <br/> <p> {notification.description} </p> <br/> </div> <div className="DonorNot-notifications-buttons"> <button className="DonorNot-notifications-delete-button" onClick={() => handleDelete(notification.id)}>Delete</button> </div> {notification.id === 1 && <EtaSection timeToMeet={notification.TimeToMeet}></EtaSection>} </div> ))} {notifications.length === 0 && <h2 className='DonorNot-notifications-title'>No Notifications</h2>} </div> </div> ); }; export default DonorNot;
import {ToastrService} from "ngx-toastr"; import {Injectable} from "@angular/core"; import {IsMobileService} from "./is-mobile.service"; @Injectable({ providedIn: 'root' }) export class NotifierService { get positionClass() { return this.isMobileService.isMobile ? 'toast-top-full-width' : 'toast-top-right'; } constructor(private toastr: ToastrService, private isMobileService: IsMobileService) { } public error(message: string, title?: string | undefined) { this.toastr.error(message, title, { timeOut: 3000, positionClass: this.positionClass, }); } public success(message: string, title?: string | undefined) { this.toastr.success(message, title, { positionClass: this.positionClass, }); } public info(message: string, title?: string | undefined) { this.toastr.info(message, title, { timeOut: 5000, positionClass: this.positionClass, }); } public warning(message: string, title?: string | undefined) { this.toastr.warning(message, title, { positionClass: this.positionClass, }); } public showTamplate(tamplate: string, title?: string | undefined) { this.toastr.info(tamplate, title, { enableHtml: true, disableTimeOut: true, closeButton: true }); } }
import pytest import common @pytest.mark.pgsql('maas', files=['subscriptions.sql']) async def test_ok(taxi_maas, load_json, mockserver): @mockserver.json_handler('/persuggest/internal/persuggest/v2/stops_nearby') def _stops_nearby(request): return mockserver.make_response( json=load_json('stops_nearby_response.json'), ) await taxi_maas.invalidate_caches() response = await taxi_maas.post( '/internal/maas/v1/check-trip-requirements', headers={ 'X-Yandex-Uid': 'user_uid', 'X-YaTaxi-UserId': 'user_id', 'X-YaTaxi-PhoneId': 'active_phone_id', }, json={ 'waypoints': [[37.5, 55.5], [37.467, 55.736]], 'coupon': 'maas30000002', }, ) assert response.status_code == 200 response_body = response.json() assert response_body['valid'] assert 'failed_check_id' not in response_body @pytest.mark.pgsql('maas', files=['subscriptions.sql']) @pytest.mark.parametrize( 'waypoints, coupon, phone_id, expected_response', [ pytest.param( [[37.5, 55.5], [37.467, 55.736]], 'maas30000002', 'active_phone_id', {'valid': True}, id='valid', ), pytest.param( [[37.5, 55.5]], 'maas30000002', 'active_phone_id', {'valid': False, 'failed_check_id': 'route_without_point_b'}, id='route_without_point_b', ), pytest.param( None, 'maas30000002', 'active_phone_id', {'valid': False, 'failed_check_id': 'no_route'}, id='no_route', ), pytest.param( [[37.5, 55.5], [37.51, 55.52], [37.52, 55.53]], 'maas30000002', 'active_phone_id', { 'valid': False, 'failed_check_id': 'route_with_intermediate_stop', }, id='route_with_intermediate_stop', ), pytest.param( [[37.467, 55.736], [38, 56]], 'maas30000002', 'active_phone_id', {'valid': True}, id='valid_from_metro', # we don't check route length ), pytest.param( [[38, 56], [37.467, 55.736]], 'maas30000002', 'active_phone_id', {'valid': True}, id='valid_to_metro', # we don't check route length ), pytest.param( [[38, 56], [38, 56]], 'maas30000002', 'active_phone_id', { 'valid': False, 'failed_check_id': 'route_points_too_far_from_metro', }, id='route_points_too_far_from_metro', ), pytest.param( [[37.5, 55.5], [37.467, 55.736]], 'invalid_coupon', 'active_phone_id', {'valid': False, 'failed_check_id': 'subscription_unavailable'}, id='coupon_in_subscription_!=_coupon_in_request', ), pytest.param( [[37.5, 55.5]], 'invalid_coupon', 'active_phone_id', {'valid': False, 'failed_check_id': 'subscription_unavailable'}, id='route_without_point_b_and_invalid_coupon', ), pytest.param( [[37.5, 55.5], [37.467, 55.736]], 'maas30000002', 'active_phone_id_no_coupon', {'valid': False, 'failed_check_id': 'subscription_unavailable'}, id='subscription_without_coupon', ), pytest.param( [[37.5, 55.5], [37.467, 55.736]], 'maas30000002', 'some_phone_id', {'valid': False, 'failed_check_id': 'subscription_unavailable'}, id='user_without_subscription', ), pytest.param( [[37.5, 55.5], [37.467, 55.736]], 'maas30000001', 'reserved_phone_id', {'valid': False, 'failed_check_id': 'subscription_unavailable'}, id='user_with_inactive_subscription', ), ], ) async def test_checks( taxi_maas, load_json, mockserver, waypoints, coupon, phone_id, expected_response, ): @mockserver.json_handler('/persuggest/internal/persuggest/v2/stops_nearby') def _stops_nearby(request): response_file = 'stops_nearby_response.json' return mockserver.make_response(json=load_json(response_file)) await taxi_maas.invalidate_caches() response = await taxi_maas.post( '/internal/maas/v1/check-trip-requirements', headers={ 'X-Yandex-Uid': 'user_uid', 'X-YaTaxi-UserId': 'user_id', 'X-YaTaxi-PhoneId': phone_id, }, json={'waypoints': waypoints, 'coupon': coupon}, ) assert response.status_code == 200 assert response.json() == expected_response @pytest.mark.pgsql('maas', files=['subscriptions.sql']) async def test_geo_checks_disabled(taxi_maas, taxi_config, load_json): taxi_config.set( MAAS_GEO_HELPER_SETTINGS={ 'geo_client_qos': { 'validate_route': {'timeout-ms': 50, 'attempts': 1}, }, 'route_validation_settings': { 'enable_geo_checks': False, 'ignore_geo_errors': False, }, 'geo_settings': load_json('geo_settings.json'), }, ) await taxi_maas.invalidate_caches() response = await taxi_maas.post( '/internal/maas/v1/check-trip-requirements', headers={ 'X-Yandex-Uid': 'user_uid', 'X-YaTaxi-UserId': 'user_id', 'X-YaTaxi-PhoneId': 'active_phone_id', }, json={ 'waypoints': [[37.5, 55.5], [37.51, 55.52]], 'coupon': 'maas30000002', }, ) assert response.status_code == 200 response_body = response.json() assert response_body['valid'] assert 'failed_check_id' not in response_body @pytest.mark.pgsql('maas', files=['subscriptions.sql']) @pytest.mark.parametrize( 'waypoints, expected_response', [ pytest.param( [[37.5, 55.5], [37.467, 55.736]], {'valid': True}, id='valid_metro', ), pytest.param( [[37.5, 55.5], [37.472, 55.730]], {'valid': True}, id='valid_railway', ), pytest.param( [[38, 56], [37.48, 55.75]], { 'valid': False, 'failed_check_id': 'route_points_too_far_from_metro', }, id='route_points_too_far_from_metro', ), pytest.param( [[37.449, 55.726], [38, 56]], { 'valid': False, 'failed_check_id': 'route_points_too_far_from_metro', }, id='route_points_too_far_from_railway', ), ], ) async def test_checks_with_railway( taxi_maas, load_json, mockserver, taxi_config, waypoints, expected_response, ): taxi_config.set( MAAS_GEO_HELPER_SETTINGS={ 'geo_client_qos': {}, 'route_validation_settings': { 'enable_geo_checks': True, 'ignore_geo_errors': False, }, 'geo_settings': load_json('geo_settings_with_railway.json'), }, ) @mockserver.json_handler('/persuggest/internal/persuggest/v2/stops_nearby') def _stops_nearby(request): request_json = request.json assert len(request_json['transport_types']) == 1 assert request_json['transport_types'][0] in {'underground', 'railway'} assert request_json == common.create_stops_nearby_request( position=[37.62, 55.75], distance_meters=30000, pickup_points_type='identical', transfer_type='from_mt', routers={'bee': {'type': 'bee_line'}}, transport_types=request_json['transport_types'], fetch_lines=False, ) response_file = 'stops_nearby_response.json' if request_json['transport_types'] == ['railway']: response_file = 'stops_nearby_railway_response.json' return mockserver.make_response(json=load_json(response_file)) await taxi_maas.invalidate_caches() assert _stops_nearby.times_called == 2 response = await taxi_maas.post( '/internal/maas/v1/check-trip-requirements', headers={ 'X-Yandex-Uid': 'user_uid', 'X-YaTaxi-UserId': 'user_id', 'X-YaTaxi-PhoneId': 'active_phone_id', }, json={'waypoints': waypoints, 'coupon': 'maas30000002'}, ) assert response.status_code == 200 assert response.json() == expected_response @pytest.mark.pgsql('maas', files=['subscriptions.sql']) async def test_ok_with_cache_with_no_successfull_updates( taxi_maas, load_json, mockserver, ): response = await taxi_maas.post( '/internal/maas/v1/check-trip-requirements', headers={ 'X-Yandex-Uid': 'user_uid', 'X-YaTaxi-UserId': 'user_id', 'X-YaTaxi-PhoneId': 'active_phone_id', }, json={ 'waypoints': [[37.5, 55.5], [37.467, 55.736]], 'coupon': 'maas30000002', }, ) assert response.status_code == 200 response_body = response.json() assert response_body['valid'] assert 'failed_check_id' not in response_body @pytest.mark.pgsql('maas', files=['subscriptions.sql']) async def test_ok_with_empty_cache(taxi_maas, load_json, mockserver): @mockserver.json_handler('/persuggest/internal/persuggest/v2/stops_nearby') def _stops_nearby(request): return mockserver.make_response( json=load_json('stops_nearby_empty_response.json'), ) await taxi_maas.invalidate_caches() response = await taxi_maas.post( '/internal/maas/v1/check-trip-requirements', headers={ 'X-Yandex-Uid': 'user_uid', 'X-YaTaxi-UserId': 'user_id', 'X-YaTaxi-PhoneId': 'active_phone_id', }, json={ 'waypoints': [[37.5, 55.5], [37.467, 55.736]], 'coupon': 'maas30000002', }, ) assert response.status_code == 200 response_body = response.json() assert response_body['valid'] assert 'failed_check_id' not in response_body
<?php namespace App\DataFixtures; use App\Entity\Article; use App\Entity\User; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; use Faker\Factory; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; class AppFixtures extends Fixture { public function __construct(UserPasswordHasherInterface $hasher) { $this->hasher = $hasher; } public function load(ObjectManager $manager): void { $faker = Factory::create(); //generating fake users for ($u=0; $u < 10; $u++){ $user = new User(); $passHash = $this->hasher->hashPassword($user,'password'); $user->setEmail($faker->email); $user->setPassword($passHash); $manager->persist($user); } //generating fake articles for ($a=0; $a < random_int(5,15); $a++){ $article = (new Article())->setAuthor($user) ->setContent($faker->text(300)) ->setName($faker->text(50)); $manager->persist($article); } $manager->flush(); } }
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HeroesComponent } from './heroes/heroes.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { HeroDetailComponent } from './hero-detail/hero-detail.component'; // path is a string that matches the URL in the browser bar // '' path is default route: app navigates to dashboard automatically const routes: Routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'heroes', component: HeroesComponent }, { path: 'dashboard', component: DashboardComponent }, { path: 'detail/:id', component: HeroDetailComponent }, ]; // This metadata initializes the router and starts it listening for browser location changes // Exports: so routermodule willl be available throughout app @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class pickup_throw : MonoBehaviour { // Gun Sounds here! private AudioSource audioSource; [SerializeField] public AudioClip drop_weapon_sound; [SerializeField] public AudioClip pickup_weapon_sound; [SerializeField] GameObject Pickup_text; [SerializeField] GameObject Drop_text; [SerializeField] GameObject Hand; GameObject weapon_to_pickup; bool holdingGun; void Drop_weapon_sound() { audioSource.PlayOneShot(drop_weapon_sound); } void Pickup_weapon_sound() { audioSource.PlayOneShot(pickup_weapon_sound); } void Start() { // Get audio source audioSource = gameObject.GetComponent<AudioSource>(); holdingGun = false; } void weaponDisable(Transform weapon_object, bool isDisable) { MonoBehaviour[] allScripts = weapon_object.GetComponents<MonoBehaviour>(); foreach (MonoBehaviour script in allScripts) { if (script.name == "LaserSight") { // Enable laser sight script.enabled = true; continue; } if (isDisable) { script.enabled = false; } else script.enabled = true; } // Recursively call the function for each child for (int i = 0; i < weapon_object.transform.childCount; i++) { weaponDisable(weapon_object.transform.GetChild(i), isDisable); } } /* This function will be used in conjunction with invoke so that it will take a few seconds to disable/enable text */ IEnumerator disable_text() { yield return new WaitForSeconds(1); Drop_text.SetActive(false); } // Update is called once per frame void Update() { // Ensures that the texts are facing the correct direction (upwards positive y direction) Pickup_text.transform.rotation = Quaternion.Euler(0f, 0f, 0f); Drop_text.transform.rotation = Quaternion.Euler(0f, 0f, 0f); if (Hand.transform.childCount == 1) { float speed_weapon = 6.0f; GameObject item_on_hand = Hand.transform.GetChild(0).gameObject; float distance_gun_hand = Vector3.Distance(item_on_hand.transform.position, Hand.transform.position); Vector3 smoothedPosition = Vector3.Lerp(item_on_hand.transform.position, Hand.transform.position, speed_weapon * Time.deltaTime); item_on_hand.transform.position = smoothedPosition; if (distance_gun_hand > 1) { item_on_hand.transform.position = Hand.transform.position; } // If user presses q (To drop item in hand) if (Input.GetKey("q")) { // Drop weapon sound audioSource.PlayOneShot(drop_weapon_sound); // Disable ammo count text for weapons held by player if (item_on_hand.name == "Pistol" || item_on_hand.name == "M4 Carbine" || item_on_hand.name == "Kar98K" || item_on_hand.name == "Shotgun") { // Disable text object item_on_hand.transform.GetChild(0).gameObject.SetActive(false); } if (item_on_hand.CompareTag("grenade")) { // Unset the hand as the weapon's parent item_on_hand.transform.parent = null; // Change back to dynamic so that grenade do not "Float around" item_on_hand.GetComponent<Rigidbody2D>().isKinematic = false; // Disable grenade scripts weaponDisable(item_on_hand.transform, true); // Change the text Drop_text.GetComponent<TextMesh>().text = item_on_hand.name + " dropped!"; // Enable text Drop_text.SetActive(true); // After a few seconds, disable text StartCoroutine(disable_text()); } if (item_on_hand.GetComponentInChildren<Animator>().GetCurrentAnimatorStateInfo(0).IsName("idle") || item_on_hand.GetComponentInChildren<Animator>().GetCurrentAnimatorStateInfo(0).IsName("empty")) { // Unset the hand as the weapon's parent item_on_hand.transform.parent = null; // Disable weapon rotation / shooting scripts weaponDisable(item_on_hand.transform, true); // Disable sprite animation item_on_hand.GetComponentInChildren<Animator>().enabled = false; // Change the text Drop_text.GetComponent<TextMesh>().text = item_on_hand.name + " dropped!"; // Enable text Drop_text.SetActive(true); // After a few seconds, disable text StartCoroutine(disable_text()); } } } } void OnTriggerStay2D(Collider2D collision) { if ((collision.gameObject.CompareTag("gun")|| collision.gameObject.CompareTag("grabbable") || collision.gameObject.CompareTag("grenade")) && !holdingGun && Hand.transform.childCount < 1) { // Retrieve details for weapon to pickup weapon_to_pickup = collision.gameObject; // Get weapon name string weapon_name = weapon_to_pickup.name; // Change the text Pickup_text.GetComponent<TextMesh>().text = "E - Pick up " + weapon_name; if (Hand.transform.childCount == 0) { Pickup_text.SetActive(true); } else { Pickup_text.SetActive(false); } if (Input.GetKey("e")) { audioSource.PlayOneShot(pickup_weapon_sound); if (weapon_to_pickup.CompareTag("grenade")) { // Change back to dynamic so that grenade do not "Float around" weapon_to_pickup.GetComponent<Rigidbody2D>().isKinematic = true; weapon_to_pickup.GetComponent<BoxCollider2D>().enabled = false; } // If is pistol if (weapon_to_pickup.name == "Pistol" || weapon_to_pickup.name == "M4 Carbine" || weapon_to_pickup.name == "Kar98K" || weapon_to_pickup.name == "Shotgun") { // Enable ammo count for pistol weapon_to_pickup.transform.GetChild(0).gameObject.SetActive(true); } try { // Enable sprite animation weapon_to_pickup.GetComponentInChildren<Animator>().enabled = true; } catch { } if (weapon_to_pickup.name == "Pistol") { // Set weapon position to hand position weapon_to_pickup.transform.rotation = Hand.transform.rotation; } weaponDisable(weapon_to_pickup.transform, false); // Set weapon position to hand position weapon_to_pickup.transform.position = Hand.transform.position; // Set parent of weapon which is going to be picked up to be the hand weapon_to_pickup.transform.parent = Hand.transform; } } } private void OnTriggerExit2D(Collider2D collision) { Pickup_text.SetActive(false); } }
from dataclasses import field from django import forms from .models import Category, Post,Comment class PostForm(forms.ModelForm): status = forms.ChoiceField(choices=Post.OPTIONS) category = forms.ModelChoiceField(queryset=Category.objects.all(),empty_label="Select") class Meta : model = Post fields = ( "title", "content", "image", "category", "status", ) class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ("content",)
<?php class Usuario{ public $nombre; public $clave; public $email; //Constructor public function __construct($nombre, $clave, $email) { $this->nombre = $nombre; $this->clave = $clave; $this->email = $email; } public static function guardarUsuarioCSV($usuario) { $archivo = fopen("usuarios.csv", "a"); if($archivo){ fwrite($archivo, $usuario->nombre . "," . $usuario->clave . "," . $usuario->email . "\n"); echo "<p>Usuario guardado correctamente en el archivo CSV.</p>"; } else{ echo "<p>Error al abrir el archivo CSV.</p>"; } fclose($archivo); } public static function leerUsuarioCSV(){ $archivo = fopen("usuarios.csv", "r"); echo "<ul>"; while(!feof($archivo)){ $linea = fgets($archivo); echo "<li>$linea</li>"; } echo "</ul>"; fclose($archivo); } public static function encontrarUsuario($email, $clave) { $archivo = fopen("usuarios.csv", "r"); $usuarioEncontradoFlag = false; while(!feof($archivo)){ $linea = fgets($archivo); $elementosLinea = explode(",", $linea); if($elementosLinea[2] === $email && $elementosLinea[1] === $clave){ $usuarioEncontradoFlag = true; echo "Verificado"; break; }else if($elementosLinea[2] === $email && $elementosLinea[1] != $clave){ echo "Error en los datos"; break; } } if (!$usuarioEncontradoFlag) { echo "Usuario no registrado"; } fclose($archivo); echo "<br/>"; } }
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * Trait Resolution. See doc.rs. */ use middle::mem_categorization::Typer; use middle::subst; use middle::ty; use middle::typeck::infer::InferCtxt; use std::rc::Rc; use syntax::ast; use syntax::codemap::{Span, DUMMY_SP}; pub use self::fulfill::FulfillmentContext; pub use self::select::SelectionContext; pub use self::select::SelectionCache; pub use self::util::supertraits; pub use self::util::transitive_bounds; pub use self::util::Supertraits; pub use self::util::search_trait_and_supertraits_from_bound; mod coherence; mod fulfill; mod select; mod util; /** * An `Obligation` represents some trait reference (e.g. `int:Eq`) for * which the vtable must be found. The process of finding a vtable is * called "resolving" the `Obligation`. This process consists of * either identifying an `impl` (e.g., `impl Eq for int`) that * provides the required vtable, or else finding a bound that is in * scope. The eventual result is usually a `Selection` (defined below). */ #[deriving(Clone)] pub struct Obligation { pub cause: ObligationCause, pub recursion_depth: uint, pub trait_ref: Rc<ty::TraitRef>, } /** * Why did we incur this obligation? Used for error reporting. */ #[deriving(Clone)] pub struct ObligationCause { pub span: Span, pub code: ObligationCauseCode } #[deriving(Clone)] pub enum ObligationCauseCode { /// Not well classified or should be obvious from span. MiscObligation, /// In an impl of trait X for type Y, type Y must /// also implement all supertraits of X. ItemObligation(ast::DefId), /// Obligation incurred due to an object cast. ObjectCastObligation(/* Object type */ ty::t), /// To implement drop, type must be sendable. DropTrait, /// Various cases where expressions must be sized/copy/etc: AssignmentLhsSized, // L = X implies that L is Sized StructInitializerSized, // S { ... } must be Sized VariableType(ast::NodeId), // Type of each variable must be Sized RepeatVec, // [T,..n] --> T must be Copy // Captures of variable the given id by a closure (span is the // span of the closure) ClosureCapture(ast::NodeId, Span), // Types of fields (other than the last) in a struct must be sized. FieldSized, } // An error has already been reported to the user, so no need to continue checking. #[deriving(Clone,Show)] pub struct ErrorReported; pub type Obligations = subst::VecPerParamSpace<Obligation>; pub type Selection = Vtable<Obligation>; #[deriving(Clone,Show)] pub enum SelectionError { Unimplemented, Overflow, OutputTypeParameterMismatch(Rc<ty::TraitRef>, ty::type_err) } pub struct FulfillmentError { pub obligation: Obligation, pub code: FulfillmentErrorCode } #[deriving(Clone)] pub enum FulfillmentErrorCode { CodeSelectionError(SelectionError), CodeAmbiguity, } /** * When performing resolution, it is typically the case that there * can be one of three outcomes: * * - `Ok(Some(r))`: success occurred with result `r` * - `Ok(None)`: could not definitely determine anything, usually due * to inconclusive type inference. * - `Err(e)`: error `e` occurred */ pub type SelectionResult<T> = Result<Option<T>, SelectionError>; #[deriving(PartialEq,Eq,Show)] pub enum EvaluationResult { EvaluatedToMatch, EvaluatedToAmbiguity, EvaluatedToUnmatch } /** * Given the successful resolution of an obligation, the `Vtable` * indicates where the vtable comes from. Note that while we call this * a "vtable", it does not necessarily indicate dynamic dispatch at * runtime. `Vtable` instances just tell the compiler where to find * methods, but in generic code those methods are typically statically * dispatched -- only when an object is constructed is a `Vtable` * instance reified into an actual vtable. * * For example, the vtable may be tied to a specific impl (case A), * or it may be relative to some bound that is in scope (case B). * * * ``` * impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1 * impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2 * impl Clone for int { ... } // Impl_3 * * fn foo<T:Clone>(concrete: Option<Box<int>>, * param: T, * mixed: Option<T>) { * * // Case A: Vtable points at a specific impl. Only possible when * // type is concretely known. If the impl itself has bounded * // type parameters, Vtable will carry resolutions for those as well: * concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])]) * * // Case B: Vtable must be provided by caller. This applies when * // type is a type parameter. * param.clone(); // VtableParam(Oblig_1) * * // Case C: A mix of cases A and B. * mixed.clone(); // Vtable(Impl_1, [VtableParam(Oblig_1)]) * } * ``` * * ### The type parameter `N` * * See explanation on `VtableImplData`. */ #[deriving(Show,Clone)] pub enum Vtable<N> { /// Vtable identifying a particular impl. VtableImpl(VtableImplData<N>), /// Vtable automatically generated for an unboxed closure. The def /// ID is the ID of the closure expression. This is a `VtableImpl` /// in spirit, but the impl is generated by the compiler and does /// not appear in the source. VtableUnboxedClosure(ast::DefId), /// Successful resolution to an obligation provided by the caller /// for some type parameter. VtableParam(VtableParamData), /// Successful resolution for a builtin trait. VtableBuiltin, } /** * Identifies a particular impl in the source, along with a set of * substitutions from the impl's type/lifetime parameters. The * `nested` vector corresponds to the nested obligations attached to * the impl's type parameters. * * The type parameter `N` indicates the type used for "nested * obligations" that are required by the impl. During type check, this * is `Obligation`, as one might expect. During trans, however, this * is `()`, because trans only requires a shallow resolution of an * impl, and nested obligations are satisfied later. */ #[deriving(Clone)] pub struct VtableImplData<N> { pub impl_def_id: ast::DefId, pub substs: subst::Substs, pub nested: subst::VecPerParamSpace<N> } /** * A vtable provided as a parameter by the caller. For example, in a * function like `fn foo<T:Eq>(...)`, if the `eq()` method is invoked * on an instance of `T`, the vtable would be of type `VtableParam`. */ #[deriving(Clone)] pub struct VtableParamData { // In the above example, this would `Eq` pub bound: Rc<ty::TraitRef>, } pub fn evaluate_obligation<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, param_env: &ty::ParameterEnvironment, obligation: &Obligation, typer: &Typer<'tcx>) -> EvaluationResult { /*! * Attempts to resolve the obligation given. Returns `None` if * we are unable to resolve, either because of ambiguity or * due to insufficient inference. */ let mut selcx = select::SelectionContext::new(infcx, param_env, typer); selcx.evaluate_obligation(obligation) } pub fn evaluate_impl<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, param_env: &ty::ParameterEnvironment, typer: &Typer<'tcx>, cause: ObligationCause, impl_def_id: ast::DefId, self_ty: ty::t) -> EvaluationResult { /*! * Tests whether the impl `impl_def_id` can be applied to the self * type `self_ty`. This is similar to "selection", but simpler: * * - It does not take a full trait-ref as input, so it skips over * the "confirmation" step which would reconcile output type * parameters. * - It returns an `EvaluationResult`, which is a tri-value return * (yes/no/unknown). */ let mut selcx = select::SelectionContext::new(infcx, param_env, typer); selcx.evaluate_impl(impl_def_id, cause, self_ty) } pub fn select_inherent_impl<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, param_env: &ty::ParameterEnvironment, typer: &Typer<'tcx>, cause: ObligationCause, impl_def_id: ast::DefId, self_ty: ty::t) -> SelectionResult<VtableImplData<Obligation>> { /*! * Matches the self type of the inherent impl `impl_def_id` * against `self_ty` and returns the resulting resolution. This * routine may modify the surrounding type context (for example, * it may unify variables). */ // This routine is only suitable for inherent impls. This is // because it does not attempt to unify the output type parameters // from the trait ref against the values from the obligation. // (These things do not apply to inherent impls, for which there // is no trait ref nor obligation.) // // Matching against non-inherent impls should be done with // `try_resolve_obligation()`. assert!(ty::impl_trait_ref(infcx.tcx, impl_def_id).is_none()); let mut selcx = select::SelectionContext::new(infcx, param_env, typer); selcx.select_inherent_impl(impl_def_id, cause, self_ty) } pub fn is_orphan_impl(tcx: &ty::ctxt, impl_def_id: ast::DefId) -> bool { /*! * True if neither the trait nor self type is local. Note that * `impl_def_id` must refer to an impl of a trait, not an inherent * impl. */ !coherence::impl_is_local(tcx, impl_def_id) } pub fn overlapping_impls(infcx: &InferCtxt, impl1_def_id: ast::DefId, impl2_def_id: ast::DefId) -> bool { /*! * True if there exist types that satisfy both of the two given impls. */ coherence::impl_can_satisfy(infcx, impl1_def_id, impl2_def_id) && coherence::impl_can_satisfy(infcx, impl2_def_id, impl1_def_id) } pub fn obligations_for_generics(tcx: &ty::ctxt, cause: ObligationCause, generics: &ty::Generics, substs: &subst::Substs) -> subst::VecPerParamSpace<Obligation> { /*! * Given generics for an impl like: * * impl<A:Foo, B:Bar+Qux> ... * * and a substs vector like `<A=A0, B=B0>`, yields a result like * * [[Foo for A0, Bar for B0, Qux for B0], [], []] */ util::obligations_for_generics(tcx, cause, 0, generics, substs) } pub fn obligation_for_builtin_bound(tcx: &ty::ctxt, cause: ObligationCause, source_ty: ty::t, builtin_bound: ty::BuiltinBound) -> Result<Obligation, ErrorReported> { util::obligation_for_builtin_bound(tcx, cause, builtin_bound, 0, source_ty) } impl Obligation { pub fn new(cause: ObligationCause, trait_ref: Rc<ty::TraitRef>) -> Obligation { Obligation { cause: cause, recursion_depth: 0, trait_ref: trait_ref } } pub fn misc(span: Span, trait_ref: Rc<ty::TraitRef>) -> Obligation { Obligation::new(ObligationCause::misc(span), trait_ref) } pub fn self_ty(&self) -> ty::t { self.trait_ref.self_ty() } } impl ObligationCause { pub fn new(span: Span, code: ObligationCauseCode) -> ObligationCause { ObligationCause { span: span, code: code } } pub fn misc(span: Span) -> ObligationCause { ObligationCause { span: span, code: MiscObligation } } pub fn dummy() -> ObligationCause { ObligationCause { span: DUMMY_SP, code: MiscObligation } } } impl<N> Vtable<N> { pub fn map_nested<M>(&self, op: |&N| -> M) -> Vtable<M> { match *self { VtableImpl(ref i) => VtableImpl(i.map_nested(op)), VtableUnboxedClosure(d) => VtableUnboxedClosure(d), VtableParam(ref p) => VtableParam((*p).clone()), VtableBuiltin => VtableBuiltin, } } pub fn map_move_nested<M>(self, op: |N| -> M) -> Vtable<M> { match self { VtableImpl(i) => VtableImpl(i.map_move_nested(op)), VtableUnboxedClosure(d) => VtableUnboxedClosure(d), VtableParam(p) => VtableParam(p), VtableBuiltin => VtableBuiltin, } } } impl<N> VtableImplData<N> { pub fn map_nested<M>(&self, op: |&N| -> M) -> VtableImplData<M> { VtableImplData { impl_def_id: self.impl_def_id, substs: self.substs.clone(), nested: self.nested.map(op) } } pub fn map_move_nested<M>(self, op: |N| -> M) -> VtableImplData<M> { let VtableImplData { impl_def_id, substs, nested } = self; VtableImplData { impl_def_id: impl_def_id, substs: substs, nested: nested.map_move(op) } } } impl EvaluationResult { pub fn potentially_applicable(&self) -> bool { match *self { EvaluatedToMatch | EvaluatedToAmbiguity => true, EvaluatedToUnmatch => false } } } impl FulfillmentError { fn new(obligation: Obligation, code: FulfillmentErrorCode) -> FulfillmentError { FulfillmentError { obligation: obligation, code: code } } }
<!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> </head> <body> <div id="root"> <div> <button @click="onClickText" class="btn">Hello world, Click me</button> <span>{{ refData.myName }} - {{ msg }} - {{ info.msg2 }}</span> <span>{{ info.age }} - {{ nextYage }}</span> <span>-nextYageFor2: {{ nextYageFor2 }}</span> <div v-if="showDiv"> 被你发现了 </div> <div> <button @click="onIncreaseAge" class="btn">Increase Age</button> <button @click="onChangeAgeSetter" class="btn">ChangeAge Setter</button> </div> </div> </div> <script> new Vue({ el: '#root', data: { msg: '改变我', showDiv: false, refData: { myName: 'Ruo' }, info: { msg2: 'hello', age: 28 } }, computed: { nextYage: function () { return this.info.age + 1; }, nextYageFor2: { get: function () { console.log('1.computed getter...'); return this.info.age * 10; }, set: function (value) { console.log('2.computed setter...', value); } } }, methods: { onClickText: function () { console.log('test:', this); this.msg = '努力'; this.showDiv = !this.showDiv; this.info.msg2 = this.showDiv ? '直接点' : '其他选择'; }, onIncreaseAge: function () { this.info.age = this.info.age + 1; }, onChangeAgeSetter: function () { console.log('this.onChangeAgeSetter', this.nextYageFor2); this.nextYageFor2 = 1; } } }); </script> </body> </html>
// // ErrorTestAlertView.swift // Rawdah // // Created by Sapar Jumabekov on 07.06.2022. // import Foundation import UIKit import Stevia // MARK: - Delegate protocol ErrorTestAlertViewDelegate: AnyObject { func closeTapped() func restartTapped() } // MARK: - Main class ErrorTestAlertView: UIView { // MARK: - Variables weak var delegate: ErrorTestAlertViewDelegate? private let index: (Int, Int) // MARK: - Outlets private lazy var closeButton: UIButton = { let button = UIButton() button.setImage(UIImage(systemName: "xmark"), for: []) button.tintColor = .label button.addTarget(self, action: #selector(closeButtonDidTapped), for: .touchUpInside) return button }() private let imageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "error") return imageView }() let successLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.numberOfLines = 0 label.text = "" return label }() let errorLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.numberOfLines = 0 label.text = "" return label }() private let firstTextLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.numberOfLines = 0 label.text = "test_error_first_text".localized return label }() private lazy var secondTextLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.numberOfLines = 0 label.text = "test_error_second_text".localized return label }() private let originalLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.text = "ان شاء اللهٰ" return label }() private lazy var restartButton: UIButton = { let button = UIButton() button.backgroundColor = .systemBackground button.setTitle("test_error_button".localized, for: []) button.setTitleColor(.systemGreen, for: []) button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .caption2) button.titleLabel?.numberOfLines = 0 button.titleLabel?.textAlignment = .center button.layer.cornerRadius = 12 button.layer.borderColor = UIColor.systemGreen.cgColor button.layer.borderWidth = 1.0 button.clipsToBounds = true button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .body) button.addTarget(self, action: #selector(restartButtonDidTapped), for: .touchUpInside) return button }() // MARK: - Init init(index: (Int, Int)) { self.index = index super.init(frame: .zero) setup() } required init?(coder: NSCoder) { fatalError() } // MARK: - Actions @objc private func restartButtonDidTapped(_ sender: Any) { delegate?.restartTapped() } @objc private func closeButtonDidTapped(_ sender: Any) { delegate?.closeTapped() } // MARK: - Setup private func setup() { guard let customFont = UIFont(name: "ScheherazadeNew-Regular", size: 32) else { fatalError(""" Failed to load the "CustomFont-Light" font. Make sure the font file is included in the project and the font name is spelled correctly. """ ) } originalLabel.font = UIFontMetrics.default.scaledFont(for: customFont) originalLabel.adjustsFontForContentSizeCategory = true setupConstraints() } private func setupConstraints() { subviews(closeButton, imageView, successLabel, errorLabel, firstTextLabel, secondTextLabel, originalLabel, restartButton) closeButton.top(24).right(24).size(34) imageView.Top == safeAreaLayoutGuide.Top + 48 imageView.centerHorizontally().height(30%).heightEqualsWidth() successLabel.Top == imageView.Bottom + 12 successLabel.centerHorizontally() errorLabel.Top == successLabel.Bottom + 12 errorLabel.fillHorizontally(padding: 24) firstTextLabel.Top == errorLabel.Bottom + 12 firstTextLabel.fillHorizontally(padding: 24) secondTextLabel.Top == firstTextLabel.Bottom + 12 secondTextLabel.fillHorizontally(padding: 24) originalLabel.Top == secondTextLabel.Bottom + 12 originalLabel.fillHorizontally(padding: 24) restartButton.height(56).fillHorizontally(padding: 24) restartButton.Bottom == self.Bottom - 24 } }
#' Fits the nominal model #' #' Function estimates the parameters of LMA models where the category scale #' are estimated. The function can be used to estimate the parameters of the #' LMA model corresponding the nominal model (for multi-category items) and #' the 2 parameter logistic model for dichotomous items. The function sets #' up log object(s) and model formula. In the case of unidimensional models, #' the function iterates over item regressions; whereas, for multidimensional #' models, the function iterates between the item and phi regressions. This #' function is called from 'ple.lma', but can be run outside of 'ple.lma'. #' #' @param Master Master data set in long format #' @param Phi.mat Matrix of starting values of the association parameters #' @param starting.sv Matrix starting values category scale values #' @param pq.mat Array used compute rest scores and total scores #' @param tol Value used to determine convergence of algorithm #' @param PersonByItem Same as inData (rows are response patterns) #' @param TraitByTrait Same as inTraitAdj (trait x trait adjacency) #' @param ItemByTrait Same as inItemTraitAdj (item x trait adjacency) #' @param item.by.trait One dimensional array indicating trait item loads on #' @param ItemNames Names of items in inData (i.e. columns names of #' categorical variables) #' @param LambdaNames Lambda names used in the Master and stacked data frames #' @param NuNames Nu names in Master data frame #' @param LambdaName Lambda names in formula for items #' @param NuName Nu names in formula for item regressions #' @param PhiNames Association parameter names for stacked regression #' @param npersons Number of persons #' @param nitems Number of items #' @param ncat Number of categories per item #' @param nless ncat-1 = number unique lambda and unique nus #' @param ntraits Number of traits #' @param Maxnphi Number of association parametets #' #' @return item.log Iteration history of LogLike, lambda, and item parameters #' @return phi.log Iteration history of LogLike, lambdas and phi parameters #' @return criterion Current value of the convergence statistic #' @return estimates Item x parameter matrix: LogLike, lambda and scale values #' @return Phi.mat Estimated conditional correlation matrix #' @return fitem Formula for item data #' @return fstack Formula for stacked data #' @return item.mlogit Summaries from final run of mlogit for item regressions #' @return phi.mlogit Summary from final run of mlogit for stacked regression #' @return mlpl.item Max log pseudo-likelihood function from item regressions #' @return mlpl.phi Maximum of log pseudo-likelihood function from stacked regression #' @return AIC Akaike information criterion for pseudo-likelihood (smaller is better) #' @return BIC Bayesian information criterion for pseudo-likelihood (smaller is better) #' #' @examples #' data(dass) #' inData <- dass[1:250,c("d1", "d2", "d3", "a1","a2","a3","s1","s2","s3")] #' #--- unidimensional #' inTraitAdj <- matrix(1, nrow=1, ncol=1) #' inItemTraitAdj <- matrix(1, nrow=9, ncol=1) #' s <- set.up(inData, model.type='nominal', inTraitAdj, inItemTraitAdj, #' tol=1e-02) #' #' n1 <- fit.nominal(s$Master, s$Phi.mat, s$starting.sv, s$pq.mat, s$tol, #' s$PersonByItem, s$TraitByTrait, s$ItemByTrait, s$item.by.trait, #' s$ItemNames, s$LambdaNames, s$NuNames, s$LambdaName, s$NuName, #' s$PhiNames, s$npersons, s$nitems, s$ncat,s$ nless, s$ntraits, #' s$Maxnphi) #' #' @export ###################################################################################################### fit.nominal <- function(Master, Phi.mat, starting.sv, pq.mat, tol, PersonByItem, TraitByTrait, ItemByTrait, item.by.trait, ItemNames, LambdaNames, NuNames, LambdaName, NuName, PhiNames, npersons, nitems, ncat, nless, ntraits, Maxnphi) { # -- Object to store results from fitting models to items desired_length <- nitems item.log <- vector(mode = "list", length = desired_length) for (item in 1:nitems) { item.log[[item]]<- matrix(0, nrow=1, ncol=(2*nless+2)) } # -- Put starting values first 2 rows (needed if compute in early iterations) for (item in 1:nitems) { lamholder <- seq(1:nless) item.log[[item]] <- c(0 ,0, lamholder, starting.sv[item,2:ncat]) item.log[[item]] <- rbind(item.log[[item]], c(0, 0, lamholder, starting.sv[item,2:ncat]) ) } # --- Object to hold iterations from up-dating the phis if (ntraits>1) { phiholder <- seq(1:Maxnphi) lamholder <- seq(1:(nitems*nless)) phi.log <- matrix(c(0,lamholder,phiholder),nrow=1, ncol=(1 + nitems*nless + Maxnphi)) } else { phi.log <- NULL } # --- Formula for nominal model # up-dating nu x.names <- c(LambdaName,NuName) fitem <- stats::as.formula(paste("y ~", paste(x.names,collapse="+"),"| 0 | 0",sep=" ")) # up-dating phi (if needed) if (ntraits>1) { xstack.names <- c(LambdaNames,PhiNames) fstack <- stats::as.formula(paste("y ~", paste(xstack.names,collapse="+"),"| 0 | 0",sep=" ")) } else { fstack <- NULL } # Fit model # --- for uni-dimensional model --- if (ntraits==1) { criterion <- 10 # Any number greater than tol while (criterion>tol) { ItemLoop.results <- ItemLoop(Master, item.log, Phi.mat=Phi.mat, PersonByItem=PersonByItem, npersons=npersons, nitems=nitems, ntraits=ntraits, ncat=ncat, nless=nless, TraitByTrait=TraitByTrait, pq.mat=pq.mat, LambdaName=LambdaName, NuName=NuName, fitem=fitem) Master <- ItemLoop.results$Master item.log <- ItemLoop.results$item.log converge <- convergence.stats(item.log=item.log, nitems=nitems, nless=nless, LambdaName=LambdaName, NuName=NuName) criterion <- abs(converge$criterion.loglike) if (criterion > tol) { print(paste0(criterion , " > ", tol)) } else { print(paste0("Alogithm has converged: ", criterion," < ",tol)) } } } # --- multidimensional model --- if (ntraits>1) { criterion <- 10 # Any number greater than tol ItemLoop.results <- ItemLoop(Master, item.log, Phi.mat=Phi.mat, PersonByItem=PersonByItem, npersons=npersons, nitems=nitems, ntraits=ntraits, ncat=ncat, nless=nless, TraitByTrait=TraitByTrait, pq.mat=pq.mat, LambdaName=LambdaName, NuName=NuName, fitem=fitem) Master <- ItemLoop.results$Master item.log <- ItemLoop.results$item.log while (criterion>tol) { stack.results <- FitStack(Master, item.log, phi.log, fstack, TraitByTrait, pq.mat, npersons, nitems, ncat, nless, ntraits, Maxnphi, PhiNames, LambdaNames) Phi.mat <- stack.results[[1]] phi.log <- stack.results[[2]] scale.results <-Scale(Master, item.log, Phi.mat, PersonByItem, npersons, nitems, ncat, nless, ntraits, item.by.trait) Master <- scale.results[[1]] Phi.mat <- scale.results[[2]] ItemLoop.results <- ItemLoop(Master, item.log, Phi.mat=Phi.mat, PersonByItem=PersonByItem, npersons=npersons, nitems=nitems, ntraits=ntraits, ncat=ncat, nless=nless, TraitByTrait=TraitByTrait, pq.mat=pq.mat, LambdaName=LambdaName, NuName=NuName, fitem=fitem) Master <- ItemLoop.results$Master item.log <- ItemLoop.results$item.log converge <- convergence.stats(item.log=item.log, nitems=nitems, nless=nless, LambdaName=LambdaName, NuName=NuName) criterion <- abs(converge$criterion.loglike) if (criterion > tol) { print(paste0(criterion , " > ", tol)) } else { print(paste0("Alogithm has converged: ", criterion," < ",tol)) } } } # --- one last set of models to save output from mlogit --- desired_length <- nitems item.mlogit <- vector(mode = "list", length = desired_length) for (item in 1:nitems) { DataForItem <- ItemData(Master, ItemID=item, Phi.mat=Phi.mat, npersons, nitems, ntraits, ncat, nless, TraitByTrait, pq.mat, LambdaName, NuName) item.data <- dfidx::dfidx(DataForItem, choice="y", idx=c("CaseID","alt")) item.mlogit[[item]] <- mlogit::mlogit(fitem, item.data) } if (ntraits > 1) { stacked.data <- StackData(Master, item.log, phi.log, pq.mat, npersons, nitems, ncat, nless, ntraits, Maxnphi, PhiNames, LambdaNames) stacked <- dfidx::dfidx(stacked.data, choice="y", idx=c("CaseID","alt")) phi.mlogit <- mlogit::mlogit(fstack, stacked) } else { phi.mlogit <- NULL } # --- save LogLike and parmeters to file i1 <- item.log[[1]] item.save <- i1[nrow(i1),] for (item in 2:nitems) { i <- item.log[[item]] i <- i[nrow(i),] item.save <- rbind(item.save,i) } rownames(item.save) <- ItemNames if (ncat > 2) { lam1 <- -rowSums(item.save[,3:(1+ncat)]) nu1 <- -rowSums(item.save[,(2+ncat):ncol(item.save)]) estimates <- cbind(item.save[,2],lam1,item.save[,3:(1+ncat)], nu1,item.save[,(2+ncat):ncol(item.save)]) } else { lam1 <- -item.save[,3] nu1 <- -item.save[,4] estimates <- cbind(item.save[,2],lam1,item.save[,3],nu1,item.save[,4]) } lambdaName<- matrix(NA, nrow=1, ncol=ncat) nuName <- matrix(NA,nrow=1,ncol=ncat) for (cat in 1:ncat){ lambdaName[cat] <- paste("lambda", cat, sep="") nuName[cat] <- paste("nu", cat, sep="") } colnames(estimates) <- c("loglike", lambdaName, nuName) # --- Max of ple function to items and phi mlpl.item <- sum(estimates[, 1]) mlpl.phi <- phi.mlogit$logLik #--- Information criteria nparm <- 2*nless*nitems + Maxnphi- ntraits AIC <- -1*mlpl.item - nparm BIC <- -2*mlpl.item - nparm*log(length(unique(Master$PersonID))) # --- output from fit.nominal results <- list(item.log=item.log, phi.log=phi.log, criterion=criterion, estimates=estimates, Phi.mat=Phi.mat, fitem=fitem, fstack=fstack, item.mlogit=item.mlogit, phi.mlogit=phi.mlogit, mlpl.item=mlpl.item, mlpl.phi=mlpl.phi, AIC = AIC[1], BIC = BIC[1]) return(results) }
<?php namespace Srdorado\SiigoClient\Model\Client; use Srdorado\SiigoClient\Exception\Rule\BadRequest; use Srdorado\SiigoClient\Exception\Rule\UrlRuleRequestException; use Srdorado\SiigoClient\Model\EntityInterface; use Srdorado\SiigoClient\Model\Validator\CreditNoteValidator; class ClientCreditNote extends AbstractClient { /** * Construct * * @param string $baseUrl */ public function __construct($baseUrl = '') { $this->baseUrl = $baseUrl; $this->initGuzzleClient(); $this->validator = new CreditNoteValidator(); } public function getHeaders($params = []) { $headers = \Srdorado\SiigoClient\Enum\EndPoint\Customer::HEADER_POST; $headers['Authorization'] = $params['access_token']; return $headers; } /** * Create credit note in siigo * * @param EntityInterface|null $entity * @return array * @throws BadRequest */ public function create($entity = null) { return $this->getBodyGeneric( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::CREATE, $entity ); } /** * @param EntityInterface|null $entity * @param bool $allResponse * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getAll($entity = null, $allResponse = false) { return $this->getListRequest( \Srdorado\SiigoClient\Enum\EndPoint\Voucher::GET_ALL, $entity, $allResponse ); } /** * Get credit note by id * * @param EntityInterface|null $entity * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getById($entity = null) { $response = ''; $this->validator->validate(\Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_ID, $entity); $headers = $this->getHeaders(['access_token' => $this->accessToken]); $url = $this->validator->getUrl(\Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_ID, $entity); $urlRequest = $this->getRequestUrl($url); $result = $this->get($urlRequest, $headers); if ($result['code'] === 200) { $result = json_decode($result['contents'], true); $response = $result; } else { $message = 'response - ' . $result['contents']; throw new \Srdorado\SiigoClient\Exception\Rule\BadRequest($message); } return $response; } /** * @param EntityInterface|null $entity * @param bool $allResponse * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getByCreatedStart($entity = null, $allResponse = false) { return $this->getListRequest( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_CREATED_START, $entity, $allResponse ); } /** * @param EntityInterface|null $entity * @param bool $allResponse * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getByUpdatedStart($entity = null, $allResponse = false) { return $this->getListRequest( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_UPDATED_START, $entity, $allResponse ); } /** * @param EntityInterface|null $entity * @param bool $allResponse * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getByDateStart($entity = null, $allResponse = false) { return $this->getListRequest( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_DATE_START, $entity, $allResponse ); } /** * @param EntityInterface|null $entity * @param bool $allResponse * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getByDateEnd($entity = null, $allResponse = false) { return $this->getListRequest( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_DATE_END, $entity, $allResponse ); } /** * @param EntityInterface|null $entity * @param bool $allResponse * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getByCreatedEnd($entity = null, $allResponse = false) { return $this->getListRequest( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_CREATED_END, $entity, $allResponse ); } /** * @param EntityInterface|null $entity * @param bool $allResponse * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getByUpdatedEnd($entity = null, $allResponse = false) { return $this->getListRequest( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_UPDATED_END, $entity, $allResponse ); } /** * @param EntityInterface|null $entity * @param bool $allResponse * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getByCustomerBranchOffice($entity = null, $allResponse = false) { return $this->getListRequest( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_CUSTOMER_BRANCH_OFFICE, $entity, $allResponse ); } /** * @param EntityInterface|null $entity * @param bool $allResponse * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getByCustomerIdentification($entity = null, $allResponse = false) { return $this->getListRequest( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_CUSTOMER_IDENTIFICATION, $entity, $allResponse ); } /** * @param EntityInterface|null $entity * @param bool $allResponse * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getByDocumentId($entity = null, $allResponse = false) { return $this->getListRequest( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::GET_BY_DOCUMENT_ID, $entity, $allResponse ); } /** * @param EntityInterface|null $entity * @return array * @throws BadRequest * @throws UrlRuleRequestException */ public function getPDF($entity = null) { return $this->getUrlGenericList( \Srdorado\SiigoClient\Enum\EndPoint\CreditNote::PDF, $entity ); } }
#include<iostream> class bad_hmean { private: double v1; double v2; public: bad_hmean(double a = 0, double b = 0) :v1(a), v2(b) {}; void mesg(); }; inline void bad_hmean::mesg() { std::cout << "hmean(" << v1 << "," << v2 << "): " << "invalid arguments:a=-b\n"; } class bad_gmean { public: double v1; double v2; bad_gmean(double a = 0, double b = 0) :v1(a), v2 (b) {}; const char *mesg(); }; inline const char *bad_gmean::mesg() { return "gmean() arguments should be >=0\n"; } #include<iostream> #include<cmath> #include<string> #include"exc_mean.h" class demo { private: std::string word; public: demo(const std::string &str) { word = str; std::cout << "demo " << word << " craeted\n"; } ~demo() { std::cout << "demo " << word << " destroyed\n"; } void show() const { std::cout << "demo " << word << " lives!\n"; } }; double hmean(double a, double b); double gmean(double a, double b); double means(double a, double b); int main() { using std::cout; using std::cin; using std::endl; double x, y, z; { demo d1("found in block in main()"); cout << "Enter two numbers:"; while (cin >> x >> y) { try { z = means(x, y); cout << "The mean mean of " << x << " and " << y << " is " << z << endl; cout << "Enter next pair:"; } catch (bad_hmean &bg) { bg.mesg(); cout << "Try again.\n"; continue; } catch (bad_gmean &hg) { cout << hg.mesg(); cout << "Vslues used: " << hg.v1 << ", " << hg.v2 << endl; cout << "Sorry, you don't get to play any more.\n"; break; } } d1.show(); } cout << "Bye\n"; cin.get(); cin.get(); return 0; } double hmean(double a, double b) { if (a == -b) throw bad_hmean(a, b); return 2.0*a*b / (a + b); } double gmean(double a, double b) { if (a < 0 || b < 0) throw bad_gmean(a, b); return std::sqrt(a*b); } double means(double a, double b) { double am, hm, gm; demo d2("found in means()"); am = (a + b) / 2.0; try { hm = hmean(a, b); gm = gmean(a, b); } catch (bad_hmean &bg) { bg.mesg(); std::cout << "Caught in means() \n"; throw; } d2.show(); return (am + hm + gm) / 3.0; }
import React, {useState,useEffect,useMemo} from 'react'; // import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonInput, IonItem, IonLabel, IonList, IonItemDivider } from '@ionic/react'; import '../css/mainStyles.scss'; import LocalizeComponent from '../localize/LocalizeComponent'; import { useForm } from "react-hook-form"; import { yupResolver } from '@hookform/resolvers/yup'; import * as yup from "yup"; import { withStyles, makeStyles, } from '@material-ui/core/styles'; import TextField from '@material-ui/core/TextField'; import Grid from '@material-ui/core/Grid'; import { connect } from 'react-redux'; import AlertSuccessComponent from '../helperComponents/AlertSuccessComponent'; import AlertDangerComponent from '../helperComponents/AlertDangerComponent'; import GoBack from '../helperComponents/goBackComponent'; import RateService from '../services/RateService'; import StarIcon from '@material-ui/icons/Star'; import GoBackWithCenterComponent from '../helperComponents/goBackAbsoluteComponent'; import config from '../config/config.js'; import { increment, decrement,save_email } from '../actions/actions'; import { Link, useHistory, } from "react-router-dom"; function mapStateToProps(state,ownProps) { return { count: state.count, email:state.email, password:state.password } } //const {regionsList: { data: list = [] } } = props; const mapDispatchToProps = dispatch => ({ increment, decrement, dispatch, save_email }); const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, backgroundColor:'transparent', }, paper: { padding: theme.spacing(2), textAlign: 'center', color: theme.palette.text.secondary, backgroundColor:'transparent', }, })); const CssTextField = withStyles({ root: { '& label.Mui-focused': { color: '#0083ff', }, '& label': { color: '#0083ff', }, '& .MuiInput-underline:after': { borderBottomColor: '#0083ff', }, '& .MuiOutlinedInput-root': { '& fieldset': { borderColor: '#0083ff', }, '&:hover fieldset': { borderColor: 'yellow', }, '&.Mui-focused fieldset': { borderColor: '#0083ff', }, '& input:valid + fieldset': { borderColor: '#0083ff', }, '& input:invalid + fieldset': { borderColor: 'red', }, }, }, })(TextField); const schema = yup.object().shape({ rate: yup.string().required("Required"), }); const MessageComponent = (props) => { return ( <div className="errorBox"> {props.message} </div> ) } const ErrorDiv = (props) => { //console.log(props); const errorMessage = props.message; if(errorMessage != undefined){ return <MessageComponent message={errorMessage}/> }else{ return <div></div> } } const RateComponent = (props) => { var raitingId = useMemo(() => { const locationData = props.location; if(locationData.data){ localStorage.setItem("raitingId",props.location.data); return props.location.data; }else{ return localStorage.getItem("raitingId"); } },[]); //console.log(raitingId); const classes = useStyles(); const { register, handleSubmit, errors,setError } = useForm({ resolver: yupResolver(schema) }); var obj = { email:"" }; const [storageData,setStorageData] = useState(obj); const [cancelDoubleEvent,setCancelDoubleEvent] = useState(0); const [closeDialog,setCloseDialog] = useState(false); const [rateindex,setRateIndex] = useState(0); const [sucessState,setSucessState] = useState(false); const [dangerState,setDangerState] = useState(false); const [ratetext,setRateText] = useState(''); const [alertText,setAlertText] = useState("Success action Thanks!"); var rateObject = { status:0, class:"usualColorStatus" } var rateArray = new Array(); const [rateArrayStatus,setRateArrayStatus] = useState([ { id:0, status:0, class:"usualColorStatus" }, { id:1, status:0, class:"usualColorStatus" }, { id:2, status:0, class:"usualColorStatus" }, { id:3, status:0, class:"usualColorStatus" }, { id:4, status:0, class:"usualColorStatus" }, ]); const onSubmit = ((data) => { var raiteMessage = data.rate; //console.log(data); //rateindex //console.log(rateindex); if((rateindex == 0) || (raiteMessage.length < 1)){ setAlertText(LocalizeComponent.rateAction); setDangerState(true); hideAlert(); }else{ var sendData = { rate:rateindex, userId:raitingId, text:raiteMessage } RateService.setRate(sendData); } }); const rateEvent = ((rate) => { var newratecount = rate; setSucessState(false); const newrateArrayStatus = [...rateArrayStatus]; for(var i = 0;i < newrateArrayStatus.length;i++){ if(i < newratecount){ newrateArrayStatus[i].class = "yellowColorStatus"; }else{ newrateArrayStatus[i].class = "usualColorStatus"; } } setRateArrayStatus(newrateArrayStatus); setRateIndex(rate); }); const setRateInputValue = ((event) => { var value = event.target.value; setRateText(value); //setRateText }); const hideAlert = () => { setTimeout(function(){ setSucessState(false); setDangerState(false); },3000); } useEffect(() => { const listenRateService = RateService.listenRate().subscribe(data => { //console.log(data); if(data.status == "ok"){ setRateText("");//clean input setAlertText(LocalizeComponent.successAction);//setText in Alert setSucessState(true);//show alert hideAlert();//hide alert through 2 sec }else if(data.status = "exist_user"){ setAlertText(LocalizeComponent.cantRate); setDangerState(true); hideAlert(); } }); //unsubscribe return () => { listenRateService.unsubscribe(); } //unsubscribe }, []); useEffect(() => { //initiase functions var sendData = { rate:5, userId:raitingId, text:"" } //RateService.setRate(sendData); config.checkUserAuthorization(2); }, []); return ( <div className={classes.root}> <Grid container > <GoBackWithCenterComponent center={LocalizeComponent.rate}/> <GoBack/> <div className="StarDiv"> <div onClick={(e) => rateEvent(1)} ><StarIcon className={"firstStar " + rateArrayStatus[0].class} /></div> <div onClick={(e) => rateEvent(2)} ><StarIcon className={"secondStar " + rateArrayStatus[1].class} /></div> <div onClick={(e) => rateEvent(3)} ><StarIcon className={"secondStar " + rateArrayStatus[2].class} /></div> <div onClick={(e) => rateEvent(4)} ><StarIcon className={"secondStar " + rateArrayStatus[3].class} /></div> <div onClick={(e) => rateEvent(5)} ><StarIcon className={"secondStar " + rateArrayStatus[4].class} /></div> </div> <div className="commentBox"> <form onSubmit={handleSubmit(onSubmit)} className={classes.margin}> <CssTextField inputRef={register} name="rate" className="textArea" onChange={setRateInputValue} id="rate" type="text" multiline value={ratetext} helperText={errors.rate?.message} variant="outlined" placeholder={LocalizeComponent.rateDescribe} label={LocalizeComponent.rate} /> <div className="buttonDiv buttonMargin"> <input className="buttonStyle center-button" type="submit" value={LocalizeComponent.rate}/> </div> </form> </div> <AlertSuccessComponent state={sucessState} text={alertText}/> <AlertDangerComponent state={dangerState} text={alertText}/> </Grid> </div> ); }; export default connect(mapStateToProps,mapDispatchToProps)(RateComponent);
import { Table, Model, Column, DataType, ForeignKey, BelongsTo, BeforeValidate, } from "sequelize-typescript"; import { PredefinedMessageSchema } from "./PredefinedMessageSchema"; import { DropdownValueSchema } from "./DropdownValueSchema"; @Table({ timestamps: true, tableName: "predefined_message_relation", }) export class PredefinedMessageRelationSchema extends Model { @ForeignKey(() => PredefinedMessageSchema) @Column({ type: DataType.INTEGER, allowNull: true, }) predefinedMessageAId!: number; @ForeignKey(() => DropdownValueSchema) @Column({ type: DataType.INTEGER, allowNull: true, onDelete: 'CASCADE', }) predefinedDropdownValueAId!: number; @ForeignKey(() => PredefinedMessageSchema) @Column({ type: DataType.INTEGER, allowNull: false, onDelete: 'CASCADE', }) predefinedMessageBId!: number; @ForeignKey(() => PredefinedMessageSchema) @Column({ type: DataType.INTEGER, allowNull: true, onDelete: 'CASCADE', }) predefinedMessageBIdOnCancel!: number; @BelongsTo(() => PredefinedMessageSchema, "predefinedMessageAId") predefinedMessageA!: PredefinedMessageSchema; @BelongsTo(() => PredefinedMessageSchema, "predefinedMessageBId") predefinedMessageB!: PredefinedMessageSchema; @BelongsTo(() => PredefinedMessageSchema, "predefinedMessageBIdOnCancel") predefinedMessageBOnCancel!: PredefinedMessageSchema; @BelongsTo(() => DropdownValueSchema) dropdownValue!: DropdownValueSchema; @BeforeValidate static validateColumns(instance: PredefinedMessageRelationSchema) { if ( instance.predefinedMessageAId === null && instance.predefinedDropdownValueAId !== null ) { throw new Error( "If predefinedMessageAId is null, predefinedDropdownValueAId cannot be null." ); } } }
import { Component, OnInit, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { CookieService } from 'ngx-cookie-service'; import { GooglePlaceDirective } from 'ngx-google-places-autocomplete'; import { Address } from 'ngx-google-places-autocomplete/objects/address'; import { ToastrService } from 'ngx-toastr'; import { AddServiceComponent } from 'src/app/components/modal/add-service/add-service.component'; import { ApiService } from 'src/app/services/api.service'; @Component({ selector: 'app-edit-saloon-profile', templateUrl: './edit-saloon-profile.component.html', styleUrls: ['./edit-saloon-profile.component.scss'] }) export class EditSaloonProfileComponent implements OnInit { editProfileForm!: FormGroup; scarletData; model: any = {}; serviceData: any; videoData: any; Aminities: any; saloon_detail: any; data: any; public myProfileData: any; options = { types: [] }; lat: any; lng: any; public handleAddressChange(address: Address) { let location: any = address.geometry.location.toJSON(); this.lat = location.lat; this.lng = location.lng; } @ViewChild("placesRef") placesRef!: GooglePlaceDirective; constructor(private api: ApiService, private cookie: CookieService, private formBuilder: FormBuilder, private toast: ToastrService, public modal :NgbModal,) { this.scarletData = JSON.parse(this.cookie.get("scarlet_website")); } async ngOnInit() { await this.getSaloonDetail(); await this.getProfile(); await this.getService(); await this.getVideos(); await this.getAminitys(); } async addServicePopup(){ this.modal.open(AddServiceComponent,{size :'lg',centered:true}) } async getProfile() { try { let data = await this.api.get(`users/get_profile/${this.scarletData.user_id}`); if (data.status == 1) { this.myProfileData = data.data.profile; this.model.firstname = this.myProfileData.firstname; this.model.company_name = this.myProfileData.company_name; this.model.user_phone = this.myProfileData.user_phone; this.model.user_email = this.myProfileData.user_email; this.model.state = this.myProfileData.state; this.model.city = this.myProfileData.city; this.model.country_code = this.myProfileData.country_code; this.model.pincode = this.myProfileData.pincode; this.model.busi_address = this.myProfileData.busi_address; this.model.busi_description = this.myProfileData.busi_description; } } catch (error) { console.error(error); } } async saloonProfileUpdate() { try { this.model.busi_lat = this.myProfileData.busi_lat; this.model.busi_lng = this.myProfileData.busi_lng; this.model.type = 2; let data = await this.api.post("users/profile_update", this.model); if (data.status == 1) { this.toast.success(data.message); this.getProfile(); } else { this.toast.error(data.message); } } catch (error) { console.error(error); } } async getService() { try { let data = await this.api.post("saloon/service_get", { "page_no": 0, "user_id": this.scarletData.user_id }); if (data.status == 1) { this.serviceData = data.data.service_get.service } } catch (error) { console.error(error); } } async getVideos() { try { let data = await this.api.post("saloon/assets_get", { "page_no": 0, "type": "Video", "user_id": this.scarletData.user_id }); if (data.status == 1) { this.videoData = data.data.assets_get.assets } } catch (error) { console.error(error); } } async getAminitys() { try { let data = await this.api.post("saloon/aminities", { "page_no": 0 }); if (data.status == 1) { this.Aminities = data.data.aminities.aminities } } catch (error) { console.error(error); } } removeImage(video: any) { this.data = video; this.removeAssets(); } async removeAssets(){ try { let data = await this.api.post("saloon/assets_remove",{ id: this.data.id }); if(data.status == 1){ this.toast.success(data.message); this.getVideos(); }else{ this.toast.error(data.message); } } catch (error) { console.error(error); } } url: any; format: any; onSelectFile(event: any) { const file = event.target.files && event.target.files[0]; if (file) { var reader = new FileReader(); reader.readAsDataURL(file); if(file.type.indexOf('image')> -1){ this.format = 'image'; } else if(file.type.indexOf('video')> -1){ this.format = 'video'; } reader.onload = (event) => { this.url = (<FileReader>event.target).result; this.addImages(); } } } async addImages(){ try { const formdata: FormData = new FormData(); formdata.append('type', 'Video'); formdata.append('user_id', this.scarletData.user_id) if (this.url) { formdata.append('asset_url', this.url); } let data = await this.api.post("saloon/assets_add",formdata); if(data.status == 1){ this.toast.success(data.message); }else{ this.toast.error(data.message); } } catch (error) { console.error(error); } } async getSaloonDetail(){ try { let data = await this.api.post("users/saloon_detail",{ "user_id": this.scarletData.user_id }); if(data.status == 1){ this.saloon_detail = data.data.saloon_detail; }else{ } } catch (error) { console.error(error); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clases; /** * * @author jquevedo3 */ public class Fraccionario { private int numerador; private int denominador; /** * @param args the command line arguments */ public Fraccionario(int numerador, int denominador) throws DenominadorCeroException { this.numerador=numerador; this.denominador=denominador; if (denominador ==0 ){ throw new DenominadorCeroException(); } } public int getNumerador() { return numerador; } public void setNumerador(int numerador) { this.numerador = numerador; } public int getDenominador() { return denominador; } public void setDenominador(int denominador) { this.denominador = denominador; } public Fraccionario sumar(Fraccionario f2) throws DenominadorCeroException{ Fraccionario f; int num, den; num = this.numerador * f2.denominador+this.denominador*f2.numerador; den = this.denominador*f2.denominador; f = new Fraccionario (num, den); return f; } public Fraccionario restar(Fraccionario f2) throws DenominadorCeroException{ Fraccionario f; int num, den; num = this.numerador * f2.denominador-this.denominador*f2.numerador; den = this.denominador*f2.denominador; f = new Fraccionario (num, den); return f; } public Fraccionario Multiplicacion (Fraccionario f2) throws DenominadorCeroException{ Fraccionario f; int num, den; num = this.numerador * f2.denominador*this.denominador*f2.numerador; den = this.denominador*f2.denominador; f = new Fraccionario (num, den); return f; } }
<!DOCTYPE html> <html> <head> <title>ToDo</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet"> <style type="text/css"> body{ background: rgb(54,217,182); background: linear-gradient(90deg, rgba(54,217,182,1) 0%, rgba(32,152,126,1) 43%, rgba(0,212,255,1) 100%); } h1, h2, h3, h4, h5, p, span, strike{ font-family: 'Montserrat', sans-serif; } #task-container{ max-width:600px; margin:0 auto; box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22); background-color: #fff; margin-top:100px; margin-bottom:100px; justify-content: space-around; align-items: flex-start; } #form-wrapper{ position: -webkit-sticky; position: sticky; top: 0rem; border-bottom: 1px solid #e9e9e9; background-color: #fff; box-shadow: 0 3px 8px rgba(0,0,0,0.25); padding:40px; } #submit{ background-color: #36d9b6; border-radius: 0; border:0; color: #fff; } .flex-wrapper{ display: flex; } .task-wrapper{ margin:5px; padding: 5px; padding:20px; cursor: pointer; border-bottom: 1px solid #e9e9e9; color: #686868; } </style> </head> <body> <div class="container"> <div id="task-container"> <div id="form-wrapper"> <form id="form"> <div class="flex-wrapper"> <div style="flex: 6"> <input id="title" class="form-control" type="text" name="title" placeholder="Add task"> </div> <div style="flex: 1"> <input id="submit" class="btn" type="submit" > </div> </div> </form> </div> <div id="list-wrapper"> </div> </div> </div> <script type="text/javascript"> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); let activeItem = null; let list_snapshot = []; buildList() function buildList() { let wrapper = document.getElementById('list-wrapper') // wrapper.innerHTML = ''; let url = 'http://127.0.0.1:8000/api/task-list/'; fetch(url) .then((response) => response.json()) .then(function(data){ console.log('Data:', data) let list = data for (let i in list) { try{ document.getElementById(`data-row-${i}`).remove() }catch(err){ } let title = `<span class="title">${list[i].title}</span>` if (list[i].completed == true) { title = `<strike class="title">${list[i].title}</strike>` } let item = ` <div id="data-row-${i}" class="task-wrapper flex-wrapper"> <div style="flex:7"> ${title} </div> <div style="flex:1"> <button class="btn btn-sm btn-outline-info edit">Edit </button> </div> <div style="flex:1"> <button class="btn btn-sm btn-outline-dark delete">-</button> </div> </div> ` wrapper.innerHTML += item; } if (list_snapshot.length > list.length){ for (var i = list.length; i < list_snapshot.length; i++){ document.getElementById(`data-row-${i}`).remove() } } list_snapshot = list for (let i in list) { let editBtn = document.getElementsByClassName('edit')[i]; let deleteBtn = document.getElementsByClassName('delete')[i]; let title = document.getElementsByClassName('title')[i]; editBtn.addEventListener('click', function() { editItem(list[i]); }) deleteBtn.addEventListener('click', function() { deleteItem(list[i]); }) title.addEventListener('click', function() { strikeUnstrike(list[i]); }) } }) } let form = document.getElementById('form-wrapper') form.addEventListener('submit', function(e){ e.preventDefault() console.log('Form subbmited') let url = 'http://127.0.0.1:8000/api/task-create/'; console.log('item is ',activeItem); if (activeItem) { url = `http://127.0.0.1:8000/api/task-update/${activeItem.id}/`; activeItem = null; } console.log('current url:',url); let title = document.getElementById('title').value fetch(url, { method: 'POST', headers: { 'Content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'title':title}) } ).then(function(response){ buildList(); document.getElementById('form').reset(); }) }) function editItem(item) { console.log('Item Clicked:', item); activeItem = item; document.getElementById('title').value = activeItem.title; } function deleteItem(item) { console.log('Delete Clicked'); fetch(`http://127.0.0.1:8000/api/task-delete/${item.id}/`, { method: 'DELETE', headers: { 'Content-type': 'application/json', 'X-CSRFToken': csrftoken, } }) .then((response) => { buildList(); }) } function strikeUnstrike(item) { console.log('Strike clicked'); item.completed = !item.completed; fetch(`http://127.0.0.1:8000/api/task-update/${item.id}/`, { method: 'POST', headers: { 'Content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'title':item.title, 'completed': item.completed}) }) .then((response) => { buildList(); }) } </script> </body> </html>
import { PieceLetters } from "./Tetriminos"; import seedrandom from "seedrandom"; export class PieceGenerator { private _shuffledPieces: string[] = []; private _currentIndex: number = 0; private rng; constructor(seed: number) { this.rng = seedrandom(seed.toString()); } private shufflePieces(): void { this._shuffledPieces = [...PieceLetters]; for (let i = this._shuffledPieces.length - 1; i > 0; i--) { const randomIndex = Math.floor(this.rng() * (i + 1)); [this._shuffledPieces[i], this._shuffledPieces[randomIndex]] = [ this._shuffledPieces[randomIndex], this._shuffledPieces[i], ]; } this._currentIndex = 0; } public getNextPiece(): string { if (this._currentIndex >= this._shuffledPieces.length) { this.shufflePieces(); } const nextPiece = this._shuffledPieces[this._currentIndex]; this._currentIndex++; return nextPiece; } }
import { Route, Routes, useNavigate } from "react-router-dom"; import Home from "./components/Home"; import SignIn from "./components/SignIn"; import SignUp from "./components/Signup"; import ContactHistory from "./components/HistoryCard"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import "./App.css"; import FormContext from "./FormContext"; import { useEffect, useState } from "react"; export default function App() { const BASE_URL = "http://localhost:8000"; const [user, setUser] = useState(null); const [mailDetails, setMailDetails] = useState([]); const navigate = useNavigate(); const Login = (email, password) => { fetch(`${BASE_URL}/auth/login`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email, password }), }) .then((res) => res.json()) .then((data) => { if (data.success == false) { toast.error(data.message ); } else { setUser(data); toast.success("Logged in successfully"); localStorage.setItem("contactformUsers", JSON.stringify(data)); navigate("/Home"); } }); }; const SignUpUser = (name ,email ,password) =>{ fetch(`${BASE_URL}/auth/signup`,{ method:"POST", headers:{ "Content-Type":"application/json", }, body:JSON.stringify({name,email,password}) }) .then((res)=>res.json()) .then((data)=>{ if(data.success == false){ toast.error(data.message) }else{ toast.success(data.message) navigate("/") } }) } const fetchMails = () =>{ fetch(`${BASE_URL}/form-data/fetch-mails`,{ method:"GET", headers:{ "Content-Type":"application/json", Authorization:user.token, }, }) .then((res)=>res.json()) .then((data)=>{ if(data.success == false){ console.log("mails not found " + data.message) }else{ setMailDetails(data.mailDetails) } }) } const sendMail = (receiverEmail, mailSubject ,mailMessage)=>{ fetch(`${BASE_URL}/form-data/send-mail`,{ method:"POST", headers:{ "Content-Type":"application/json", Authorization:user.token, }, body:JSON.stringify({ receiverEmail, mailSubject, mailMessage }) }) .then((res)=>res.json()) .then((data)=>{ if(data.success ==false){ toast.error("error while send mail " + data.message) }else{ toast.success("Mail Sent Successfully") fetchMails(); } }) } useEffect(()=>{ if(localStorage.getItem("contactformUsers")){ setUser(JSON.parse(localStorage.getItem("contactformUsers"))); navigate("/Home") } },[]) const Logout =()=>{ setUser(null) localStorage.clear("contactformUsers") navigate("/") } return ( <div> <FormContext.Provider value={{ Login,SignUpUser , user , Logout ,fetchMails ,mailDetails ,sendMail}}> <ToastContainer /> <Routes> <Route path="/" element={<SignIn />} /> <Route path="/SignUp" element={<SignUp />} /> <Route path="/Home" element={<Home />} /> <Route path="/Contact-History" element={<ContactHistory />} /> </Routes> </FormContext.Provider> </div> ); }
<?php namespace App\Http\Controllers; use App\Models\Hotel; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class HotelController extends Controller { public function index() { $hotels = Hotel::all(); return response()->json($hotels); } public function findById($id) { $hotel = Hotel::find($id); if (!$hotel) { return response()->json(['error' => 'Hotel not found'], 404); } return response()->json($hotel); } public function store(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|string', 'description' => 'nullable|string', 'image' => 'nullable|string', 'contact_email' => 'nullable|email', 'city' => 'nullable|string', 'contact_phone' => 'nullable|string', 'promotion' => 'nullable|string', 'price' => 'required|numeric', 'review' => ['required', 'regex:/^\d+(\.\d{1})?$/'], 'starnumber'=>'nullable|string', 'category_hotel_id' => 'required|exists:category_hotels,id', 'region_id' => 'required|exists:regions,id', ]); if ($validator->fails()) { return response()->json(['error' => $validator->errors()], 400); } $hotel = Hotel::create($validator->validated()); return response()->json($hotel, 201); } public function show(Hotel $hotel) { return response()->json($hotel); } public function update(Request $request, Hotel $hotel) { $validator = Validator::make($request->all(), [ 'name' => 'string', 'description' => 'nullable|string', 'image' => 'nullable|string', 'contact_email' => 'nullable|email', 'city' => 'nullable|string', 'contact_phone' => 'nullable|string', 'promotion' => 'nullable|string', 'price' => 'nullable|numeric', 'review' => ['required', 'regex:/^\d+(\.\d{1})?$/'], 'starnumber'=>'nullable|string', 'category_hotel_id' => 'exists:category_hotels,id', 'region_id' => 'exists:regions,id', ]); if ($validator->fails()) { return response()->json(['error' => $validator->errors()], 400); } $hotel->update($validator->validated()); return response()->json($hotel, 200); } public function destroy(Hotel $hotel) { $hotel->delete(); return response()->json(null, 204); } public function filterByStarNumber(Request $request) { $starNumber = $request->input('star_number'); $hotels = Hotel::whereHas('category', function ($query) use ($starNumber) { $query->where('starnumber', $starNumber); })->get(); return response()->json($hotels); } }
/// <reference types="react" /> import PropTypes from 'prop-types'; import { AnyObjectSchema } from 'yup'; import { FormProps } from './Form'; export interface NestedFormProps<TSchema extends AnyObjectSchema> extends Omit<FormProps<TSchema>, 'onError' | 'onChange' | 'value' | 'defaultValue' | 'defaultErrors'> { name: string; } /** * A `Form` component that takes a `name` prop. Functions exactly like a normal * Form, except that when a `name` is present it will defer errors up to the parent `<Form>`, * functioning like a `<Form.Field>`. * * This is useful for encapsulating complex input groups into self-contained * forms without having to worry about `"very.long[1].paths[4].to.fields"` for names. */ declare function NestedForm<T extends AnyObjectSchema>({ name, schema, errors, ...props }: NestedFormProps<T>): JSX.Element; declare namespace NestedForm { var propTypes: { name: PropTypes.Validator<string>; schema: PropTypes.Requireable<object>; errors: PropTypes.Requireable<object>; context: PropTypes.Requireable<object>; meta: PropTypes.Requireable<PropTypes.InferProps<{ errors: PropTypes.Validator<object>; onError: PropTypes.Validator<(...args: any[]) => any>; }>>; }; } export default NestedForm;
@extends('admin.layouts.app') @section('panel') <div class="row"> <div class="col-lg-12 col-md-12 mb-30"> <div class="card"> <div class="card-body p-0"> <div class="table-responsive--sm table-responsive"> <table class="table table--light style--two"> <thead> <tr> <th>@lang('User')</th> <th>@lang('Type')</th> <th>@lang('Payment Method')</th> <th>@lang('Margin')</th> <th>@lang('Rate')</th> <th>@lang('Payment Window')</th> <th>@lang('Status')</th> <th>@lang('Action')</th> </tr> </thead> <tbody> @forelse ($advertisements as $item) <tr> <td data-label="@lang('User')"> <span class="font-weight-bold d-block">{{$item->user->fullname}}</span> <span class="small"> <a href="{{ route('admin.users.detail', $item->user->id) }}"><span>@</span>{{ $item->user->username }}</a> </span> </td> <td data-label="@lang('Type')"> @if ($item->type == 1) <span class="badge badge--primary">@lang('Buy')</span> @else <span class="badge badge--success">@lang('Sell')</span> @endif </td> <td data-label="@lang('Payment Method')"> {{__($item->fiatGateway->name)}} <span class="d-block font-weight-bold">{{__($item->fiat->code)}}</span> </td> <td data-label="@lang('Margin')">{{ getAmount($item->margin) }}%</td> <td data-label="@lang('Rate')"> <span class="font-weight-bold">{{showAmount(rate($item->type, $item->crypto->rate, $item->fiat->rate, $item->margin))}} {{__($item->fiat->code)}}</span> <span class="small d-block">/ {{__($item->crypto->code)}}</span> </td> <td data-label="@lang('Payment Window')">{{$item->window}} @lang('Minutes')</td> <td data-label="@lang('Status')"> @if ($item->status == 1) <span class="badge badge--primary">@lang('Active')</span> @else <span class="badge badge--danger">@lang('Deactive')</span> @endif </td> <td data-label="@lang('Action')"> <a href="{{route('admin.ad.view',$item->id)}}" class="icon-btn"><i class="las la-eye"></i></a> </td> </tr> @empty <tr> <td class="text-muted text-center" colspan="100%">{{ __($emptyMessage) }}</td> </tr> @endforelse </tbody> </table> </div> </div> @if($advertisements->hasPages()) <div class="card-footer py-4"> {{ $advertisements->links('admin.partials.paginate') }} </div> @endif </div> </div> </div> @push('breadcrumb-plugins') <form action="{{ route('admin.ad.search') }}" method="GET" class="form-inline float-sm-right bg--white mt-2"> <div class="input-group has_append"> <input type="text" name="search" class="form-control" placeholder="@lang('Username')" value="{{ request()->search??null }}"> <div class="input-group-append"> <button class="btn btn--primary" type="submit"><i class="fa fa-search"></i></button> </div> </div> </form> @endpush @endsection
@extends('layout.template') @section('content') <div class="row" style="height:95%; padding:20px; background-image:url('public/images/secciones/login/loginimg.jpg'); background-size:cover;"> <div class="col-md-4"> <div class="container"> <div class="row justify-content-center"> <div class="col-md-12"> <div class="card" style="text-align:center; padding:15px;"> <img src="public/images/logo/logo.png" class="logotp" style="margin:0 auto;" /> <div class="card-body"> <form method="POST" action="{{ route('register') }}"> @csrf <div class="row mb-3"> <label for="name" class="col-md-4 col-form-label text-md-end">Nombre</label><br /> <div class="col-md-6"> <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="<?php if(isset($_REQUEST['name']) ){ echo $_REQUEST['name']; }?>" <?php if(isset($_REQUEST['name']) and $_REQUEST['name']!=NULL){ echo "readonly";} ?> required autocomplete="name" autofocus> @error('name') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="row mb-3"> <label for="email" class="col-md-4 col-form-label text-md-end">Correo</label><br /> <div class="col-md-6"> <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="<?php if(isset($_REQUEST['name']) ){ echo $_REQUEST['email']; } ?>" <?php if(isset($_REQUEST['email']) and $_REQUEST['email']!=NULL){ echo "readonly";} ?> required autocomplete="email"> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="row mb-3"> <label for="password" class="col-md-4 col-form-label text-md-end">Contraseña</label><br /> <div class="col-md-6"> <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="new-password"> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="row mb-3"> <label for="password-confirm" class="col-md-4 col-form-label text-md-end">Confirmar Contraseña</label><br /> <div class="col-md-6"> <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password"> </div> </div> <div class="row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-secondary" style="color:#fff;"> {{ __('Register') }} </button> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> @endsection
--- title: "PEP681 - Data Class Transformsって何のためにあるの?" emoji: "🤔" type: "tech" # tech: 技術記事 / idea: アイデア topics: ["Python"] published: true --- この記事は[Mapbox Japan Advent Calendar 2022](https://qiita.com/advent-calendar/2022/mapbox-japan) 8日目の記事です。 ## PEP681が追加された背景 [PEP681 - Data Class Transforms](https://peps.python.org/pep-0681/)は`typing`モジュールに`@dataclass_transform`というデコレータを追加する変更で[pydantic](https://github.com/pydantic/pydantic)や[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy)、[pyserde](https://github.com/yukinarit/pyserde)等のdataclassをベースにしたライブラリの型チェックし易くするために提案されました。 例えば、`@dataclass`を追加するだけの超シンプルなデコレータ`@add_dataclass`があるとします。 ```python from dataclasses import dataclass from typing import Type, TypeVar def add_dataclass(cls: Type[T]) -> Type[T]: """ @dataclassを追加するだけのデコレータ """ dataclass(cls) return cls @add_dataclass class A: v: int a = A(10) print(a) ``` このコードを実行すると意図した通りに動いてくれるんですが、  ``` $ python a.py A(v=10) ``` mypyで型チェックをすると、以下のようにエラーが出てしまいます。 ``` $ mypy a.py a.py:15: error: Too many arguments for "A" ``` なんでmypyが正しくチェックしてくれないかというと、タイプチェッカーはdataclassを解釈して型アノテーションに基づいてコンストラクタ等のメソッドの型チェックをしてくれるんですが、実際にPythonコードを実行している訳ではないので`add_dataclass`の内部でdataclassが呼ばれようが型チェックをしてくれません。タイプチェッカー的にはdataclassデコレータは付いてないことになるので上記の型エラーが出力されるわけです。 ## PEP681ができる前まではどうしてた? じゃあ、PEP681ができる前まではどうしていたかというと、 ##### 1. 必ず`@dataclass`デコレータを付けるようにする ```python @add_dataclass @dataclass class A: v: int ``` この例だとdataclassを付けるだけのデコレータにさらに`@dataclass`付けているので意味がなくなってしまいますが、タイプチェッカーのエラーはなくなります。 [pyserde](https://github.com/yukinarit/pyserde)はこのアプローチをとっていて、本来`@dataclass`がなくても機能しますが、付けることが推奨されています。 ```python @serde @dataclass # <= 必須ではないが推奨 class Foo: ... ``` ##### 2. `typing.TYPE_CHECKING`でタイプチェッカーを騙す `typing.TYPE_CHECKING`という型結チェック時だけ`True`になる変数があるので、以下のように`add_dataclass`が`dataclass`であるかのようにエイリアスを作るとタイプチェッカーを騙すことができます。 ```python if TYPE_CHECKING: from dataclasses import dataclass as add_dataclass else: def add_dataclass(cls: Type[T]) -> Type[T]: dataclass(cls) return cls ``` これでエラーが出なくなりました。 ``` $ mypy a.py Success: no issues found in 1 source file ``` 確かpydanticもこのアプローチだったと思います。 ## PEP681 Python 3.11で追加された`typing.datalass_transform`を使えば、もっと簡単に解決できるようになります。 `@typing.dataclass_transform()`をデコレータ関数に付けるだけ。 ```python from typing import Type, TypeVar, dataclass_transform @dataclass_transform() def add_dataclass(cls: Type[T]) -> Type[T]: """ @dataclassを追加するだけのデコレータ """ dataclass(cls) return cls ``` Python 3.7~3.10の場合は、`type_extensions>=4.1.0`にバックポートがあるのでそちらを使いましょう。 ## タイプチェッカーのPEP681サポート状況 が、残念ながら実はmypyは2022年11月11日現在で[PEP681をサポートしていません](https://github.com/python/mypy/issues/12840) 🥹 主なタイプチェッカーのPEP681サポート状況は以下の通り | mypy 0.990 | pyright 1.1279 | pytype 2022.11.10 | pyre 0.9.17 | |------------|----------------|-------------------|-------------| | 未対応 | 対応 | 未対応 | 未対応 | 唯一対応しているpyrightで型チェックをするとエラーは何も出なくなりました 🎉 ``` $ pyright a.py 0 errors, 0 warnings, 0 informations ``` ## 宣伝 `dataclass`に`serde`デコレータを付けるだけで、Toml,Yaml,JSON,MsgPack等の様々なフォーマットに(de)serializeできるライブラリ`pyserde`を開発しています。よかったら使ってみてください 🙏 https://github.com/yukinarit/pyserde また、`pyserde`でPEP681に対応した時のPRは[こちら](https://github.com/yukinarit/pyserde/pull/271)になります。参考にしてください。
/* Blink Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/gpio.h" #include "esp_log.h" #include "led_strip.h" #include "sdkconfig.h" //#include "esp_rom_sys.h" static const char *TAG = "func_blink"; /* Use project configuration menu (idf.py menuconfig) to choose the GPIO to blink, or you can edit the following line and set a number here. */ #define BLINK_GPIO CONFIG_BLINK_GPIO static uint8_t s_led_state = 0; // #ifdef CONFIG_BLINK_LED_RMT static led_strip_handle_t led_strip; void turnOn_led(int color) { if (s_led_state) { switch(color) { /* Set the LED pixel using RGB from 0 (0%) to 255 (100%) for each color */ //led_strip_set_pixel(led_strip, 0, 128, 4, 4); /* Refresh the strip to send data */ case 1: led_strip_set_pixel(led_strip, 0, 128, 4, 4);//red break; case 2: led_strip_set_pixel(led_strip, 0, 4, 128, 4);//green break; case 3: led_strip_set_pixel(led_strip, 0, 4, 4, 128);//blue break; default:led_strip_set_pixel(led_strip, 0, 16, 16, 16);//white } led_strip_refresh(led_strip); } else{ led_strip_clear(led_strip); } } void blink_led(int mode,int color){ if (mode == 1){ int i; for(i=0 ; i<4 ; i++) { turnOn_led(color); s_led_state = !s_led_state; vTaskDelay(CONFIG_BLINK_PERIOD / portTICK_PERIOD_MS); //esp_rom_delay_us(us); } } else{ turnOn_led(color); } } void configure_led(void) { ESP_LOGI(TAG, "Example configured to blink addressable LED!"); /* LED strip initialization with the GPIO and pixels number*/ led_strip_config_t strip_config = { .strip_gpio_num = BLINK_GPIO, .max_leds = 1, // at least one LED on board }; led_strip_rmt_config_t rmt_config = { .resolution_hz = 10 * 1000 * 1000, // 10MHz }; ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip_config, &rmt_config, &led_strip)); /* Set all LED off to clear all pixels */ led_strip_clear(led_strip); } // #endif void led_on(int mode,int color){ s_led_state=1; blink_led(mode,color); // while (1) // { // ESP_LOGI(TAG, "Turning the LED %s!", s_led_state == true ? "ON" : "OFF"); // blink_led(); // /* Toggle the LED state */ // s_led_state = !s_led_state; // vTaskDelay(CONFIG_BLINK_PERIOD / portTICK_PERIOD_MS); // } } void led_off(){ s_led_state=0 ; ESP_ERROR_CHECK(led_strip_clear(led_strip)); }
import {Scene} from "phaser"; import {PlayerData} from "./type"; import {getHeroModelSet} from "../../assets/hero"; import {Player, IPlayer} from "./player"; export interface INonPlayableCharacter extends IPlayer { Update: () => void; GetPlayerData: () => PlayerData; IsDestroyed: () => boolean; } export class NonPlayablePlayer extends Player implements INonPlayableCharacter { private nextX: number; private nextY: number; private isDestroyed: boolean; private playerSocket: WebSocket; constructor(scene: Scene, playerData: PlayerData) { super(scene, playerData.playerName, playerData.x, playerData.y, playerData.modelId); this.nextX = playerData.x; this.nextY = playerData.y; this.isDestroyed = false; } Destroy = () => { this.sprite.removeFromDisplayList(); this.sprite.destroy(true); this.isDestroyed = true; } Create(): void { this.sprite = this.scene.physics.add.sprite(this.startX, this.startY, getHeroModelSet(this.modelId).StartSprite); this.sprite.setData("type", "other_player"); this.sprite.anims.play(getHeroModelSet(this.modelId).Idle, true); this.sprite.setOrigin(0.5, 0.5); this.sprite.setCollideWorldBounds(true); this.sprite.body.setSize(22, 32, true); this.playerSocket = new WebSocket(`ws://localhost:3000/ws/player/${this.playerName}`); this.playerSocket.onopen = () => { this.playerSocket.onmessage = (ev) => { const playerData = JSON.parse(ev.data) as PlayerData; this.onPlayerUpdate(playerData) } } } GetName = (): string => { return this.playerName; } Update = () => { const x = this.sprite.x; const y = this.sprite.y; if ((x == this.nextX) && (y == this.nextY)) { this.sprite.anims.play(getHeroModelSet(this.modelId).Idle, true); this.sprite.setVelocityX(0); this.sprite.setVelocityY(0); return } this.move(); } GetPlayerData = (): PlayerData => { return { playerName: this.playerName, x: this.nextX, y: this.nextY, modelId: this.modelId, } } IsDestroyed = (): boolean => this.isDestroyed; onPlayerUpdate = (playerData: PlayerData) => { const x = this.sprite.x; const y = this.sprite.y; if (playerData.x != x || playerData.y != y) { this.setPosition(playerData.x, playerData.y); } } move = () => { this.sprite.anims.play(getHeroModelSet(this.modelId).Idle, true); const x = this.sprite.x; const y = this.sprite.y; console.log("friend move", x, y, "to", this.nextX, this.nextY); this.handleFlip(x, this.nextX); this.sprite.setPosition(this.nextX, this.nextY); } handleFlip = (x: number, nextX: number) => { if (x > nextX) { this.sprite.flipX = true; } if (x < nextX) { this.sprite.flipX = false; } } setPosition = (x: number, y: number) => { this.nextX = x; this.nextY = y; } }
/** * WordPress dependencies */ import { __ } from '@wordpress/i18n'; import { addFilter } from '@wordpress/hooks'; import { InspectorControls, withColors, __experimentalColorGradientSettingsDropdown as ColorGradientSettingsDropdown, // eslint-disable-line __experimentalUseGradient, // eslint-disable-line __experimentalUseMultipleOriginColorsAndGradients as useMultipleOriginColorsAndGradients, // eslint-disable-line } from '@wordpress/block-editor'; import { PanelBody, RangeControl } from '@wordpress/components'; import { compose } from '@wordpress/compose'; /** * Add the attribute needed for reversing column direction on mobile. * * @since 0.1.0 * @param {Object} settings */ function addAttributes( settings ) { if ( 'core/image' !== settings.name ) { return settings; } // Add the attribute. const imageZoomAttributes = { margin: { type: 'number', default: 0, }, scrollOffset: { type: 'number', default: 0, }, background: { type: 'string', default: '#fff', }, }; const newSettings = { ...settings, attributes: { ...settings.attributes, ...imageZoomAttributes, }, }; return newSettings; } addFilter( 'blocks.registerBlockType', 'crowdify/image-zoom', addAttributes ); /** * Determines if the active variation is this one * * @param {*} props * @return {boolean} Is this the correct variation? */ const isImageZoom = ( props ) => { const { attributes: { className }, } = props; return className?.includes( 'image-zoom' ); }; /** * Filter the BlockEdit object and add icon inspector controls to button blocks. * * @since 0.1.0 * @param {Object} BlockEdit */ function withControls( BlockEdit ) { return compose( [ withColors( { backgroundColor: 'background-color' } ) ] )( ( props ) => { const { clientId, attributes, setAttributes, backgroundColor, setBackgroundColor, } = props; const { margin, scrollOffset, background } = attributes; if ( ! isImageZoom( props ) && props.name !== 'core/image' ) { return <BlockEdit { ...props } />; } const { gradientValue, setGradient } = __experimentalUseGradient(); const colorGradientSettings = useMultipleOriginColorsAndGradients(); return ( <> <InspectorControls> <PanelBody title={ __( 'General' ) }> <RangeControl label={ __( 'Margin', 'crowdify-blocks' ) } help={ __( 'The space outside the zoomed image', 'crowdify-blocks' ) } value={ margin } onChange={ ( value ) => setAttributes( { margin: value } ) } step={ 1 } max={ 1000 } /> <RangeControl label={ __( 'Scroll Offset', 'crowdify-blocks' ) } help={ __( 'The number of pixels to scroll to close the zoom', 'crowdify-blocks' ) } value={ scrollOffset } onChange={ ( value ) => setAttributes( { scrollOffset: value } ) } step={ 1 } max={ 1000 } /> </PanelBody> </InspectorControls> { colorGradientSettings.hasColorsOrGradients && ( <InspectorControls group="color"> <ColorGradientSettingsDropdown __experimentalIsRenderedInSidebar settings={ [ { colorValue: backgroundColor.color || background, gradientValue, label: __( 'Background Zoom' ), onColorChange: ( colorValue ) => { setBackgroundColor( colorValue ); setAttributes( { background: colorValue, } ); }, onGradientChange: setGradient, isShownByDefault: true, resetAllFilter: () => { setBackgroundColor( undefined ); setAttributes( { background: undefined, } ); }, }, ] } panelId={ clientId } { ...colorGradientSettings } /> </InspectorControls> ) } <BlockEdit { ...props } /> </> ); } ); } addFilter( 'editor.BlockEdit', 'crowdify/image-zoom', withControls );
--- title: "Key length determination in Polyalphabetic Ciphers" date: 2023-11-24 draft: false --- Polyalphabetic [ciphers](/ciphers) are considerably more difficult to break than monoalphabetic ones. Giovan Battista Bellaso devised an elegant implementation of a polyalphabetic cipher based on the Tabula Recta that today is known as the Vigenère cipher. ## Classic Vigenère cipher - [Modular arithmetic](/modular-arithmetic) sums up Vigenère cipher. - Assign each of the N letters an integer from 0 to N - 1. - To encrypt: C = (P + K) mod N - To decrypt: P = (C - K) mod N - Where C is ciphertext, P is plaintext, K is key, and N is the number of letters. - Vigenère cipher can be a [one-time pad](/vernam-cipher) if the key is: - same length as plaintext - chosen randomly - never reused ### Vigenère Cipher encryption pseudocode ``` # Inputs # plaintext: string of English alphabet letters to be encrypted # key: string of English letters used as encryption key # Output # ciphertext: string of encrypted English letters # Function to convert a letter to its corresponding numerical value # (A=0, B=1, ..., Z=25) # ord function returns ASCII value of a character function letter_to_number(letter) return ord(letter) - ord('A') # Function to convert a numerical value to its corresponding letter # (0=A, 1=B, ..., 25=Z) # chr function returns a character from ASCII value function number_to_letter(number) return chr((number mod 26) + ord('A')) # Main encryption function function vigenere_encrypt(plaintext, key) # Ensure the key has at least one character if length(key) == 0 return "Error: Key must have at least one character." # Initialize ciphertext as empty string ciphertext = "" # Iterate over each character in the plaintext for i from 0 to length(plaintext) - 1 # if the character is a letter, encrypt it if is_letter(plaintext[i]) # convert the plaintext letter and key letter to numbers plaintext_number = letter_to_number(plaintext[i]) key_number = letter_to_number(key[i mod length(key)]) # perform the shift for Vigenère cipher encrypted_number = (plaintext_number + key_number) mod 26 # convert the number back to a letter an append to ciphertext encrypted_letter = number_to_letter(encrypted_number) ciphertext = ciphertext + encrypted_letter else # non-letter characters are added to the ciphertext unchanged ciphertext = ciphertext + plaintext[i] # Return the ciphertext result return ciphertext ``` The `vigenere_encrypt` function iterates over each character in plaintext using [modular arithmetic](/modular-arithmetic) (via `mod` modulo operator) to wrap around the key if the plaintext is longer than the key. The `ord` function is assumed to return the ASCII value of a character, and `chr` function is assumed to return a character from an ASCII value. ## Breaking the Vigenère cipher To break, one can use coincidence analysis to determine key length. Given key length (say L), ciphertext can be split into [monoalphabetic sets](/monoalphabetic-ciphers). - Every Lth letter uses same key, then the Vigenère is a simple Caesar Shift, and frequecy analysis applies. - Ciphertext could, by trial and error, be split into sets that have expected frequency distribution. - Coincidences, a powerful tool, determine key length. - If the ciphertext characters appear uniformly and seemingly at random, frequency analysis is rendered very ineffective.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="stylesheet" href="style.css"> <title>Hello, world!</title> </head> <body> <div class="container"> <h1 id="title">Welcome to Survey Form</h1> <p id="description">Help us to build your portfolio</p> <form id="survey-form"> <div class="mb-3"> <label for="name" class="form-label" id="name-label">Name</label> <input type="text" class="form-control" id="name" placeholder="Enter your name" required> </div> <div class="mb-3"> <label for="email" class="form-label" id="email-label">Email address</label> <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter valid Email-Address" required> </div> <div class="mb-3"> <label for="number" class="form-label" id="number-label">Age</label> <input type="number" class="form-control" min="18" max="60" id="number" placeholder="Enter age"> </div> <div class="mb-3"> <label for="" class="form-label" id="dropd">Choose your Profession</label> <select class="form-select" aria-label="Default select example" id="dropdown"> <option selected>None</option> <option value="softwareEngineer">Software Engineer</option> <option value="accountant">Accountant</option> <option value="devops">Devops Engineer</option> </select> </div> <label for="" class="form-label">Would you recommend this Survey form to a friend?</label> <div class="form-check"> <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1" value="yes"> <label class="form-check-label" for="flexRadioDefault1"> Yes </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault2" value="no"> <label class="form-check-label" for="flexRadioDefault2"> No </label> </div> <label for="" class="form-label"> What would you like to see improved? (Check all that apply) </label> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1" value="1"> <label class="form-check-label" for="exampleCheck1">Front-End</label> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1" value="1"> <label class="form-check-label" for="exampleCheck1">Back-end</label> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1" value="1"> <label class="form-check-label" for="exampleCheck1">MVC</label> </div> <div class="mb-3"> <label for="exampleFormControlTextarea1" class="form-label">Anything Else</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary" id="submit">Submit</button> </form> </div> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html>
import { CustomerDetails, CustomerQuery } from '@app/model/api.model'; import { CustomersApiService } from '@app/services/api/customers.api.service'; import { SearchRequest, SearchResponse } from '@app/model/common.model'; import { Injectable } from '@angular/core'; import { Subject, Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; @Injectable() export class CustomersService { private customerSearchRequest: SearchRequest<CustomerQuery> = new SearchRequest<CustomerQuery>(); private customersSearchResponse: Subject<SearchResponse<CustomerDetails>> = new Subject<SearchResponse<CustomerDetails>>(); customersSearchResponse$ = this.customersSearchResponse.asObservable(); constructor(private customersApiService: CustomersApiService) { } async setCurrentPage(page: number) { this.customerSearchRequest.pageNumber = page; await this.searchCustomers(); } setSearchQuery(searchTerm: string) { this.customerSearchRequest.query = new CustomerQuery(); this.customerSearchRequest.query.name = searchTerm; return this.searchCustomers(); } private searchCustomers() { return this.customersApiService.searchCustomers(this.customerSearchRequest).pipe( tap(response => this.customersSearchResponse.next(response)) ); } }
/******************************************************************************\ empowerd - empowers the offline smart home Copyright (C) 2019 - 2022 Max Maisel This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. \******************************************************************************/ use super::SourceBase; use crate::models::Weather; use crate::task_group::TaskResult; use bresser6in1_usb::{Client as BresserClient, PID, VID}; use slog::{debug, error, warn}; use std::time::Duration; pub struct Bresser6in1Source { base: SourceBase, //bresser_client: BresserClient, } impl Bresser6in1Source { pub fn new(base: SourceBase) -> Self { Self { base } } pub async fn run(&mut self) -> TaskResult { let timing = match self.base.sleep_aligned().await { Ok(x) => x, Err(e) => return e, }; let logger2 = self.base.logger.clone(); let weather_data = match tokio::task::spawn_blocking(move || { // TODO: move bresser client (allocated buffers, ...) back to Miner struct let mut bresser_client = BresserClient::new(Some(logger2.clone())); let mut weather_data = bresser_client.read_data(); for i in 1..4u8 { if let Err(e) = weather_data { if i == 2 { match usb_reset::reset_vid_pid(VID, PID) { Ok(()) => { warn!( logger2, "Reset device {:X}:{:X}", VID, PID ); std::thread::sleep(Duration::from_secs(5)); } Err(e) => { error!( logger2, "Reset device {:X}:{:X} failed: {}", VID, PID, e ); } } } debug!( logger2, "Get weather data failed, {}, retrying...", e ); weather_data = bresser_client.read_data(); } else { break; } } return weather_data; }) .await { Ok(x) => x, Err(e) => { error!( self.base.logger, "Joining blocking Bresser USB task failed: {}", e ); return TaskResult::Running; } }; let mut weather_data = match weather_data { Ok(x) => x, Err(e) => { error!( self.base.logger, "Get weather data failed, {}, giving up!", e ); return TaskResult::Running; } }; weather_data.timestamp = timing.now as u32; let record = Weather::new(weather_data); self.base.notify_processors(&record); let _: Result<(), ()> = self.base.save_record(record).await; TaskResult::Running } }
import { useLazyQuery } from '@apollo/client'; import { isEqual } from 'lodash'; import React, { useCallback } from 'react'; import { ListRenderItemInfo } from 'react-native'; import { FlatList } from 'react-native-gesture-handler'; import Animated, { runOnJS, useAnimatedReaction, useDerivedValue } from 'react-native-reanimated'; import theme from '@assets/theme/theme'; import { Box, MemoizedProductTileVertical, ShadowBox, Text } from '@components'; import { CollectionDataSection, useLocalizedData, useOrderLines } from '@contexts'; import { GET_COLLECTION_REMAINING_CONTENTS } from '@graphqlDocuments'; import { GetCollectionContentsQuery, GetCollectionContentsQueryVariables, ProductVariant } from '@types'; interface Props { collectionSection: CollectionDataSection; activeIndices: Animated.SharedValue<true[]>; index: number; } export const CollectionSection: React.FC<Props> = (props) => { const { collectionSection, index, activeIndices } = props; const { strings } = useLocalizedData(); const { getCount } = useOrderLines(); const isActive = useDerivedValue(() => { return activeIndices.value[index] ?? false; }, [index]); const [getCollectionContent, { data: extendedCollectionData }] = useLazyQuery< GetCollectionContentsQuery, GetCollectionContentsQueryVariables >(GET_COLLECTION_REMAINING_CONTENTS); const fetchData = useCallback(async () => { if (collectionSection.id) { await getCollectionContent({ variables: { id: collectionSection.id ?? '' } }); } }, [collectionSection.id]); useAnimatedReaction( () => isActive.value, (value) => { if (value) { runOnJS(fetchData)(); } }, [] ); const windowSize = collectionSection.data.length > 50 ? collectionSection.data.length / 4 : 21; const keyExtractor = (item: ProductVariant) => `collection-product-${item.id}`; const NoItem = () => { return ( <Box marginRight="s3" marginBottom="s3"> <ShadowBox backgroundColor="white" borderRadius={theme.radii.xl} padding="s6"> <Text textAlign="center" variant="text-sm" color="textColorPlaceholder" lineBreakMode="middle" textBreakStrategy="balanced" > {strings.dashboard.nothingOnShelf} </Text> </ShadowBox> </Box> ); }; const renderProductVariant = ({ item: productVariant }: ListRenderItemInfo<ProductVariant>) => { const newData = extendedCollectionData?.collection?.productVariants?.items?.find( (item) => item.id === productVariant.id ); const item = newData ? { ...(newData as ProductVariant), ...productVariant } : productVariant; const count = getCount(item); return ( <Box flex={1} marginBottom="s5" paddingRight="s3" maxWidth="33.33%"> <MemoizedProductTileVertical orderedQuantity={count} item={item} /> </Box> ); }; return ( <> <Text variant="heading-sm" marginVertical="s5" style={{ backgroundColor: theme.colors.background }}> {collectionSection.title} </Text> {collectionSection.data.length > 0 ? ( <FlatList data={collectionSection.data} renderItem={renderProductVariant} numColumns={3} windowSize={windowSize} initialNumToRender={windowSize} maxToRenderPerBatch={windowSize} updateCellsBatchingPeriod={windowSize} keyExtractor={keyExtractor} showsVerticalScrollIndicator={false} scrollEnabled={false} /> ) : ( <NoItem /> )} </> ); }; export const MemoizedCollectionSection = React.memo(CollectionSection, (prevProps, nextProps) => isEqual(prevProps.collectionSection.data, nextProps.collectionSection.data) );
import React from "react"; import Form from "./common/form"; import Datepicker from "./common/datepicker"; import axios from "axios"; import BaseJoi from "joi-browser"; import JoiDateExtensions from "joi-date-extensions"; import DatePicker, { registerLocale } from "react-datepicker"; import enGB from "date-fns/locale/en-GB"; import moment from "moment"; import "react-datepicker/dist/react-datepicker.css"; const Joi = BaseJoi.extend(JoiDateExtensions); registerLocale("en-GB", enGB); class TripForm extends Form { state = { data: { date: moment(new Date()).format("YYYY-MM-DD"), deviatingRoute: "file", endKms: "", endNumber: "", endZipcode: "", privateDetourKms: "", startKms: "", startNumber: "", startZipcode: "", type: "" }, date: new Date(), errors: {}, types: ["zakelijk", "prive"], id: "" }; schema = { date: Joi.date(), startZipcode: Joi.string() .required() .label("Start - Zipcode"), startNumber: Joi.string() .required() .label("Start - Number"), startKms: Joi.number() .required() .label("Start - Kms") .min(0), endZipcode: Joi.string() .required() .label("End - Zipcode"), endNumber: Joi.string() .required() .label("End - Number"), endKms: Joi.number() .required() .label("End - Kms") .min(0), type: Joi.string() .required() .label("Type"), privateDetourKms: Joi.number() .required() .label("Private detour kms") .min(0), deviatingRoute: Joi.string() .required() .label("Deviating route") }; async populateForm() { try { if (this.props.tripId) { await fetch(`/api/trip?_id=${this.props.tripId}`) .then(data => data.json()) .then(res => { console.log('date collected:', res.data); this.setState({ id: res.data._id }) delete res.data._id; delete res.data.__v; console.log('id removed', res.data); res.data.date = res.data.date.slice(0, 10); this.setState({ data: res.data, date: new Date(res.data.date) }) }); } } catch (ex) { if (ex.response && ex.response.status === 404) console.log('Whoops, can\'t find it buddy'); } } async componentDidMount() { await this.populateForm(); console.log('props', this.props) } handleDateChange = date => { const data = { ...this.state.data }; data["date"] = moment(date).format("YYYY-MM-DD"); this.setState({ data, date: date }); }; doSubmit = () => { if (this.state.id) { axios.put(`/api/trip?id=${this.state.id}`, this.state.data) .then(res => { this.props.refreshData(); res.status === 200 ? this.props.toggleForm() : alert("Something went wrong!"); }); } else { axios.post("/api/trip", this.state.data).then(res => { this.props.refreshData(); res.status === 200 ? this.props.toggleForm() : alert("Something went wrong!"); }); } }; render() { return ( <React.Fragment> <DatePicker customInput={<Datepicker />} selected={this.state.date} onChange={this.handleDateChange} dateFormat="d MMM YYYY" locale="en-GB" /> <form onSubmit={this.handleSubmit}> <div> <div> <h4>Vertrek</h4> {this.renderInput("startZipcode", "Postcode")} {this.renderInput("startNumber", "Huisnummer")} {this.renderInput("startKms", "Kilometerstand", "number")} </div> <div> <h4>Aankomst</h4> {this.renderInput("endZipcode", "Postcode")} {this.renderInput("endNumber", "Huisnummer")} {this.renderInput("endKms", "Kilometerstand", "number")} </div> <div> <h4>Overige</h4> {this.renderSelect("type", "Soort rit", this.state.types)} {this.renderInput( "privateDetourKms", "Privé-omrijkilometers", "number" )} {this.renderInput("deviatingRoute", "Afwijkende route")} </div> </div> {this.renderButton(`${this.state.id ? "Rit aanpassen" : "Rit toevoegen"}`)} </form> </React.Fragment> ); } } export default TripForm;
// // TransactUserBlockVM.swift // Spasibka // // Created by Aleksandr Solovyev on 13.02.2023. // import StackNinja final class TransactUserBlockVM<Design: DSP>: StackModel { private lazy var userAvatar = WrappedY(ImageViewModel() .image(Design.icon.newAvatar) .contentMode(.scaleAspectFill) .cornerCurve(.continuous).cornerRadius(70 / 2) .size(.square(70)) ) private lazy var transactionOwnerLabel = LabelModel() .set(Design.state.label.regular14) .numberOfLines(0) .alignment(.center) private lazy var dateLabel = LabelModel() .textColor(Design.color.textSecondary) private lazy var amountLabel = LabelModel() private lazy var currencyLabel = CurrencyLabelDT<Design>() .setAll { label, _, image in label .height(Grid.x32.value) .set(Design.state.label.bold32) .textColor(Design.color.success) image .width(Grid.x26.value) .height(Grid.x26.value) .imageTintColor(Design.color.success) } .height(40) // MARK: - Funcs override func start() { super.start() padding(.init(top: 16, left: 16, bottom: 16, right: 16)) distribution(.fill) alignment(.center) spacing(8) arrangedModels([ userAvatar, Spacer(maxSize: 32), dateLabel, transactionOwnerLabel, amountLabel, currencyLabel, ]) } } extension TransactUserBlockVM: StateMachine { func setState(_ state: TransactDetailsState) { var input: Transaction switch state { case let .sentTransaction(value): input = value currencyLabel.models.main.textColor(Design.color.textError) currencyLabel.models.right2.imageTintColor(Design.color.textError) currencyLabel.label .text(input.amount.unwrap) let recipientFullName = HistoryPresenters<Design>.getDisplayNameForRecipient(transaction: input) // let recipientFullName = (input.recipient?.recipientFirstName ?? "") + " " + // (input.recipient?.recipientSurname ?? "") transactionOwnerLabel .set(.text("\(Design.text.youSent) \(recipientFullName)")) if let urlSuffix = input.recipient?.recipientPhoto { let urlString = SpasibkaEndpoints.urlBase + urlSuffix userAvatar.subModel.url(urlString) } else { var userIconText = "" if let nameFirstLetter = input.recipient?.recipientFirstName?.first, let surnameFirstLetter = input.recipient?.recipientSurname?.first { userIconText = String(nameFirstLetter) + String(surnameFirstLetter) } let tempImage = userIconText.drawImage(backColor: Design.color.backgroundBrand) userAvatar.subModel .image(tempImage) .backColor(Design.color.backgroundBrand) } if let challName = input.sender?.challengeName { transactionOwnerLabel .set(.text(Design.text.sentForChallenge + challName)) userAvatar.subModel.image(Design.icon.challengeAvatar) } case let .recievedTransaction(value): input = value currencyLabel.label .text("+" + input.amount.unwrap) let senderFullName = HistoryPresenters<Design>.getDisplayNameForSender(transaction: input) // let senderFullName = (input.sender?.senderFirstName ?? "") + " " + // (input.sender?.senderSurname ?? "") transactionOwnerLabel .set(.text("\(Design.text.youReceivedFrom) \(senderFullName)")) if let urlSuffix = input.sender?.senderPhoto { let urlString = SpasibkaEndpoints.urlBase + urlSuffix userAvatar.subModel.url(urlString) } else { var userIconText = "" if let nameFirstLetter = input.sender?.senderFirstName?.first, let surnameFirstLetter = input.sender?.senderSurname?.first { userIconText = String(nameFirstLetter) + String(surnameFirstLetter) } let tempImage = userIconText.drawImage(backColor: Design.color.backgroundBrand) userAvatar.subModel .image(tempImage) .backColor(Design.color.backgroundBrand) } if input.isAnonymous == true { userAvatar.subModel .image(Design.icon.smallSpasibkaLogo.insetted(16)).imageTintColor(Design.color.iconBrand) .backColor(Design.color.backgroundBrandSecondary) } } let amount = input.amount ?? "" let amountText = Design.text.pluralCurrencyWithValue(amount, case: .genitive) amountLabel .set(.text(amountText)) var textColor = Design.color.text switch input.transactionStatus?.id { case "A": textColor = Design.color.textSuccess case "D": textColor = Design.color.boundaryError transactionOwnerLabel.text(Design.text.youWantedToSend + (input.recipient?.recipientFirstName ?? "") + " " + (input.recipient?.recipientSurname ?? "")) case "W": textColor = Design.color.textWarning default: textColor = Design.color.text } amountLabel.set(.textColor(textColor)) guard let convertedDate = (input.createdAt ?? "").dateFormatted() else { return } dateLabel.set(.text(convertedDate)) } }
import { render, screen } from '@testing-library/vue' import { vi } from 'vitest' import { mockPostMyAddress } from './fetchers/mock' import RegisterAddress from './RegisterAddress.vue' import { clickSubmit, inputContactNumber, inputDeliveryAddress } from './testingUtils' vi.mock('./fetchers') async function fillValuesAndSubmit() { const contactNumber = await inputContactNumber() const deliveryAddress = await inputDeliveryAddress() const submitValues = { ...contactNumber, ...deliveryAddress } await clickSubmit() return submitValues } async function fillInvalidValuesAndSubmit() { const contactNumber = await inputContactNumber({ name: '田中 太郎', phoneNumber: 'abc-defg-hijkl' }) const deliveryAddress = await inputDeliveryAddress() const submitValues = { ...contactNumber, ...deliveryAddress } await clickSubmit() return submitValues } beforeEach(() => { vi.resetAllMocks() }) test('成功時「登録しました」が表示される', async () => { const mockFn = mockPostMyAddress() render(RegisterAddress) const submitValues = await fillValuesAndSubmit() expect(mockFn).toHaveBeenCalledWith(expect.objectContaining(submitValues)) expect(screen.getByText('登録しました')).toBeInTheDocument() }) test('失敗時「登録に失敗しました」が表示される', async () => { const mockFn = mockPostMyAddress(500) render(RegisterAddress) const submitValues = await fillValuesAndSubmit() expect(mockFn).toHaveBeenCalledWith(expect.objectContaining(submitValues)) expect(screen.getByText('登録に失敗しました')).toBeInTheDocument() }) test('バリデーションエラー時「不正な入力値が含まれています」が表示される', async () => { render(RegisterAddress) await fillInvalidValuesAndSubmit() expect(screen.getByText('不正な入力値が含まれています')).toBeInTheDocument() }) test('不明なエラー時「不明なエラーが発生しました」が表示される', async () => { render(RegisterAddress) await fillValuesAndSubmit() expect(screen.getByText('不明なエラーが発生しました')).toBeInTheDocument() }) test('Snapshot: 登録フォームが表示される', async () => { mockPostMyAddress() const { container } = render(RegisterAddress) expect(container).toMatchSnapshot() })
import React from "react"; import "./Auth.scss"; import Logo from "../../img/newlogo.png"; import { useState, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { logIn } from "../../actions/AuthActions"; import { signUp } from "../../actions/AuthActions"; const Auth = () => { const dispatch = useDispatch(); const loading = useSelector((state) => state.authReducer?.loading); const [isSignUp, setSignUp] = useState(true); console.log(loading); const [data, setData] = useState({ firstname: "", lastname: "", username: "", password: "", confirmpass: "", }); const [confirmpass, setConfirmPass] = useState(true); const handleChange = (e) => { setData({ ...data, [e.target.name]: e.target.value }); }; const handleSubmit = (e) => { e.preventDefault(); if (isSignUp) { data.password === data.confirmpass ? dispatch(signUp(data)) : setConfirmPass(false); } else { dispatch(logIn(data)); } }; const resetForm = () => { setConfirmPass(true); setData({ firstname: "", lastname: "", username: "", password: "", confirmpass: "", }); }; return ( <div className="Auth"> {/* Left side */} <div className="a-left"> <img src={Logo} alt="" /> <div className="Webname"> <h1>CoTweet</h1> <h6>Explore the world</h6> </div> </div> {/* right Side */} <div className="a-right"> <form className="infoForm authForm" onSubmit={handleSubmit}> <h3>{isSignUp ? "Sign up" : "Log In"}</h3> {isSignUp && ( <div> <input type="text" placeholder="First Name" className="infoInput" name="firstname" onChange={handleChange} value={data.firstname} /> <input type="text" placeholder="Last Name" className="infoInput" name="lastname" onChange={handleChange} value={data.lastname} /> </div> )} <div> <input type="text" placeholder="User Name" className="infoInput" name="username" onChange={handleChange} value={data.username} /> </div> <div> <input type="password" placeholder="Password" className="infoInput" name="password" onChange={handleChange} value={data.password} /> {isSignUp && ( <input type="password" placeholder="Confirm Password" className="infoInput" name="confirmpass" onChange={handleChange} value={data.confirmpass} /> )} </div> <span style={{ display: confirmpass ? "none" : "block", color: "red", fontSize: "12px", alignSelf: "flex-end", marginRight: "5px", }} > *Password is not Same </span> <div> <span style={{ fontSize: "12px", cursor: "pointer" }} onClick={() => { setSignUp((prev) => !prev); resetForm(); }} > {isSignUp ? "Already have an account. Login" : "Dont have an account? Sign Up "} </span> </div> <button className="button infoButton" type="submit" disabled={loading} > {loading ? "loading..." : isSignUp ? "Signup" : "Login"} </button> </form> </div> </div> ); }; // function Login() { // const initialValue = { // password: "", // email: "", // }; // const [formValues, setformValues] = useState(initialValue); // const [formError, setformError] = useState({}); // const [isSubmit, setIsSubmit] = useState(false); // const handleChange = (e) => { // const { name, value } = e.target; // setformValues({ ...formValues, [name]: value }); // }; // const handleSubmit = (e) => { // e.preventDefault(); // setformError(validate(formValues)); // setIsSubmit(true); // }; // useEffect( // (formValues) => { // console.log(formError); // if (Object.keys(formError).length === 0 && isSubmit) { // } // }, // [formError] // ); // const validate = (formValues) => { // const errors = {}; // const regex = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$"; // if (!formValues.email) { // errors.email = "email is required"; // } else if (!regex.test(formValues.email)) { // errors.email = "This is not valid"; // } // if (!formValues.password) { // errors.password = "password is required"; // } else if (formValues.password.length < 4) { // errors.password = "Password minimum 4 char"; // } else if (formValues.password.length > 8) { // errors.password = "Password maximum 8 char"; // } // return errors; // }; // return ( // <div className="a-right"> // <form className="infoForm authForm" onSubmit={handleSubmit}> // <h1>Log In</h1> // <div> // <input // type="email" // placeholder="email" // className="infoInput" // name="email" // value={formValues.email} // onChange={handleChange} // /> // </div> // <> // {formError.email ? ( // <div className="error">{formError.email}</div> // ) : null} // </> // <div> // <input // type="password" // placeholder="password" // className="infoInput" // name="password" // value={formValues.password} // onChange={handleChange} // /> // </div> // <> // {formError.password ? ( // <div className="error">{formError.password}</div> // ) : null} // </> // <div> // <span style={{ fontSize: "12px" }}> // Don't have an account. Sign up // </span> // <button className="button infoButton">Login</button> // </div> // </form> // </div> // ); // } // function SignUp() { // const initialValues = { // firstname: "", // lastname: "", // username: "", // password: "", // confirmpass: "", // email: "", // gender: "", // phone: "", // }; // const [formValues, setformValues] = useState(initialValues); // const [formError, setformError] = useState({}); // const [isSubmit, setIsSubmit] = useState(false); // const handleChange = (e) => { // const { name, value } = e.target; // setformValues({ ...formValues, [name]: value }); // }; // const handleSubmit = (e) => { // e.preventDefault(); // setformError(validate(formValues)); // setIsSubmit(true); // }; // useEffect( // (formValues) => { // console.log(formError); // if (Object.keys(formError).length === 0 && isSubmit) { // } // }, // [formError] // ); // const validate = (formValues) => { // const errors = {}; // const regex = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$"; // if (!formValues.firstname) { // errors.firstname = "Firstname is required "; // } else if (formValues.firstname.length < 4) { // errors.firstname = "Firstname minimum 4 char"; // } // if (!formValues.lastname) { // errors.lastname = "Lastname is required"; // } else if (formValues.lastname.length < 4) { // errors.lastname = "Lastname minimum 4 char"; // } // if (!formValues.username) { // errors.username = "username is required"; // } else if (formValues.username.length < 4) { // errors.username = "username minimum 4 char"; // } // if (!formValues.password) { // errors.password = "password is required"; // } else if (formValues.password.length < 4) { // errors.password = "Password minimum 4 char"; // } else if (formValues.password.length > 8) { // errors.password = "Password maximum 8 char"; // } // console.log(formValues.confirmpass); // console.log(formValues.password); // if (!formValues.confirmpass) { // errors.confirmpass = "confirm password is required"; // } else if (formValues.password !== formValues.confirmpass) { // errors.confirmpass = "Enter the same Password"; // } // if (!formValues.email) { // errors.email = "email is required"; // } else if (!regex.test(formValues.email)) { // errors.email = "This is not valid"; // } // if (!formValues.gender) { // errors.gender = "gender is required"; // } // if (!formValues.phone) { // errors.phone = "Number is required"; // } else if (formValues.phone.length !== 10) { // errors.phone = "Number ten char required"; // } // return errors; // }; // return ( // <div className="a-right"> // <form className="infoForm authForm" onSubmit={handleSubmit}> // <h3>Sign up</h3> // <div> // <input // type="text" // placeholder="First Name" // className="infoInput" // name="firstname" // value={formValues.firstname} // onChange={handleChange} // /> // <input // type="text" // placeholder="Last Name" // className="infoInput" // name="lastname" // value={formValues.lastname} // onChange={handleChange} // /> // </div> // <> // {formError.firstname ? ( // <div className="error">{formError.firstname}</div> // ) : null} // </> // <> // {formError.lastname ? ( // <div className="error">{formError.lastname}</div> // ) : null} // </> // <div> // <input // type="text" // placeholder="User Name" // className="infoInput" // name="username" // value={formValues.username} // onChange={handleChange} // /> // </div> // <> // {formError.username ? ( // <div className="error">{formError.username}</div> // ) : null} // </> // <div> // <input // type="Number" // placeholder="Number" // className="infoInput" // name="phone" // value={formValues.phone} // onChange={handleChange} // /> // </div> // <> // {formError.phone ? ( // <div className="error">{formError.phone}</div> // ) : null} // </> // <div> // <input // type="password" // placeholder="Password" // className="infoInput" // name="password" // value={formValues.password} // onChange={handleChange} // /> // <input // type="password" // placeholder="Confirm Password" // className="infoInput" // name="confirmpass" // value={formValues.confirmpass} // onChange={handleChange} // /> // </div> // <> // {formError.password ? ( // <div className="error">{formError.password}</div> // ) : null} // </> // <> // {formError.confirmpass ? ( // <div className="error">{formError.confirmpass}</div> // ) : null} // </> // <div> // <input // type="email" // placeholder="Email" // className="infoInput" // name="email" // value={formValues.email} // onChange={handleChange} // /> // </div> // <> // {formError.email ? ( // <div className="error">{formError.email}</div> // ) : null} // </> // <div> // <h4>Gender</h4> // <div> // <input // type="radio" // className="infoInput" // name="gender" // value={formValues.gender} // onChange={handleChange} // /> // Male // </div> // <div> // <input // type="radio" // className="infoInput" // name="gender" // value={formValues.gender} // onChange={handleChange} // /> // Female // </div> // <> // {formError.gender ? ( // <div className="error">{formError.gender}</div> // ) : null} // </> // </div> // <div> // <span style={{ fontSize: "12px" }}> // Already have an account. Login // </span> // </div> // <button className="button infoButton" type="submit"> // Signup // </button> // </form> // </div> // ); // } export default Auth;
<?php namespace App\Http\Requests\PersonCompany; use Illuminate\Foundation\Http\FormRequest; class PersonCompanyAddRequest extends FormRequest { /** * Prepare the data for validation. * * @return void */ protected function prepareForValidation() { $this->merge([ 'person_code' => $this->person_code, ]); } /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'person_code' => 'required|string|size:32', 'company_code' => 'required|string|size:32', 'start_work_date' => 'required|date', 'end_work_date' => 'nullable|date', 'suggest_salary' => 'required|numeric', 'daily_income' => 'required|numeric', 'position' => 'required|string', ]; } }
<template> <el-form ref="form" :rules="rules" :model="form" label-width="120px" label-position="left"> <el-form-item label="用户名" prop="username"> <el-col :span="7"> <el-input v-model="form.username" /> </el-col> </el-form-item> <el-form-item label="邮箱" prop="email"> <el-col :span="20"> <el-input v-model="form.email" /> </el-col> </el-form-item> <el-form-item label="密码" prop="password"> <el-col :span="20"> <el-input v-model="form.password" /> </el-col> </el-form-item> <el-form-item label="角色权限" prop="roles"> <el-col :span="20"> <el-input v-model="form.roles" /> </el-col> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit">立即创建</el-button> <el-button @click="onCancel">取消</el-button> </el-form-item> </el-form> </template> <script> import { addUser } from '@/api/admin/users' export default { data() { return { policyTypes: [], form: { username: '', email: '', password: '', roles: '' }, rules: { username: [{ required: true, message: '请输入用户名', trigger: 'blur' }], email: [{ required: true, message: '请输入用户邮箱', trigger: 'blur' }], password: [{ required: true, message: '请输入密码', trigger: 'blur' }], roles: [{ required: true, message: '请输入role(s),使用,分割', trigger: 'blur' }] } } }, methods: { onSubmit() { this.$refs['form'].validate((valid) => { if (valid) { addUser(this.form).then(res => { this.$message.success(res['msg']) this.$emit('success') }) } else { return false } }) }, onCancel() { this.$emit('cancel') } } } </script> <style scoped> </style>
/** 1. 유저 프로파일 페이지 (1) 유저 프로파일 페이지 구독하기, 구독취소 (2) 구독자 정보 모달 보기 (3) 구독자 정보 모달에서 구독하기, 구독취소 (4) 유저 프로필 사진 변경 (5) 사용자 정보 메뉴 열기 닫기 (6) 사용자 정보(회원정보, 로그아웃, 닫기) 모달 (7) 사용자 프로파일 이미지 메뉴(사진업로드, 취소) 모달 (8) 구독자 정보 모달 닫기 */ // (1) 유저 프로파일 페이지 구독하기, 구독취소 function toggleSubscribe(toUserId, obj) { if ($(obj).text() === "구독취소") { $.ajax({ type: "delete", url: `/api/subscribe/${toUserId}`, dataType: "json" }).done(response => { $(obj).text("구독하기"); $(obj).toggleClass("blue"); }).fail(error => { console.log("구독취소 실패"); }); } else { $.ajax({ type: "post", url: `/api/subscribe/${toUserId}`, dataType: "json" }).done(response => { $(obj).text("구독취소"); $(obj).toggleClass("blue"); }).fail(error => { console.log("구독하기 실패"); }); } } // (2) 구독자 정보 모달 보기 function subscribeInfoModalOpen(pageUserId) { $(".modal-subscribe").css("display", "flex"); $.ajax({ type: "get", url: `/api/user/${pageUserId}/subscribe`, dataType: "json" }).done(response => { response.data.forEach((u) => { let item = getSubscribeModalItem(u); $("#subscribeModalList").append(item); // 구독정보를 감싸고있는 div 태그 }); }).fail(error => { console.log("실패!", error); }); } // 구독정보 데이터를 받아줄 메서드 function getSubscribeModalItem(u) { let item = ` <div class="subscribe__item" id="subscribeModalItem-${u.id}}"> <div class="subscribe__img"> <img src="/upload/${u.profileImageUrl}" onerror="this.src='/images/person.jpeg'"/> </div> <div class="subscribe__text"> <h2>${u.username}</h2> </div> <div class="subscribe__btn">`; if (!u.equalUserState) { if (u.subscribeState) { item += `<button class="cta blue" onclick="toggleSubscribe(${u.id}, this)">구독취소</button>`; } else { item += `<button class="cta" onclick="toggleSubscribe(${u.id}, this)">구독하기</button>`; } } // 백틱으로 구분해서 if 사용 item += ` </div> </div>`; return item; } // (3) 구독자 정보 모달에서 구독하기, 구독취소 function toggleSubscribeModal(obj) { if ($(obj).text() === "구독취소") { $(obj).text("구독하기"); $(obj).toggleClass("blue"); } else { $(obj).text("구독취소"); $(obj).toggleClass("blue"); } } // (4) 유저 프로파일 사진 변경 (완) function profileImageUpload(pageUserId, principalId) { if (pageUserId != principalId) { alert("수정 권한이 없습니다."); return; } $("#userProfileImageInput").click(); $("#userProfileImageInput").on("change", (e) => { let f = e.target.files[0]; if (!f.type.match("image.*")) { alert("이미지 파일을 등록해주세요."); return; } // 서버에 이미지 전송 let profileImageForm = $("#userProfileImageForm")[0]; // Ajax로 form 데이터를 보낼 때는 FormData 오브젝트를 사용해야 한다. let formData = new FormData(profileImageForm); // Ajax 요청 $.ajax({ type: "put", url: `/api/user/${principalId}/profileImageUrl`, data: formData, contentType: false, // Default가 true이고, 이는 x-www-from-urlencoded로 파싱됨. false로 해서 multipart/from-data로 받아야함 processData: false, // multipart/form-data로 보낼 때, 같이 false로 변경 enctype: "multipart/form-data", dataType: "json" }).done(response => { let reader = new FileReader(); // 사진 전송이 성공되면 유저 이미지의 src를 변경 reader.onload = (e) => { $("#userProfileImage").attr("src", e.target.result) } reader.readAsDataURL(f); // 자동으로 reader.onload()가 실행되는 코드 alert("프로필 이미지 변경이 완료되었습니다."); }).fail(error => { console.log("오류", error); }); }) } // (5) 사용자 정보 메뉴 열기 닫기 function popup(obj) { $(obj).css("display", "flex"); } function closePopup(obj) { $(obj).css("display", "none"); } // (6) 사용자 정보(회원정보, 로그아웃, 닫기) 모달 function modalInfo() { $(".modal-info").css("display", "none"); } // (7) 사용자 프로파일 이미지 메뉴(사진업로드, 취소) 모달 function modalImage() { $(".modal-image").css("display", "none"); } // (8) 구독자 정보 모달 닫기 function modalClose() { $(".modal-subscribe").css("display", "none"); location.reload(); }