text
stringlengths
184
4.48M
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Auctions{% endblock %}</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="{% static 'auctions/layout.css' %}" rel="stylesheet"> <link href="{% static 'auctions/listing.css' %}" rel="stylesheet"> <link href="{% static 'auctions/category.css' %}" rel="stylesheet"> </head> <body> <div class="signed-in"> {% if user.is_authenticated %} Signed in as <strong>{{ user.username }}</strong>. {% else %} Not signed in. {% endif %} </div> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Active Listings</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'categories' %}">Categories</a> </li> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'watchlist' %}">Watchlist</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'create' %}">Create Listing</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}">Log Out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Register</a> </li> {%endif%} </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-light" type="submit">Search <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-search" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M10.442 10.442a1 1 0 0 1 1.415 0l3.85 3.85a1 1 0 0 1-1.414 1.415l-3.85-3.85a1 1 0 0 1 0-1.415z"/> <path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11zM13 6.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0z"/> </svg></button> </form> </div> </nav> {% block body %} {% endblock %} </body> </html>
import pandas as pd from sklearn.model_selection import train_test_split from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences # Assuming you have a CSV with text data (e.g., reviews) and their corresponding labels (sentiment) file_path = r"C:\Users\pvans\Downloads\spotify-2023.csv" # Load data (considering 'text' column for text and 'sentiment' column for labels) data = pd.read_csv(file_path,encoding='ISO_8859-1') # Separate the text and labels texts = data['track_name'] labels = data['artist_count'] # Tokenize the text tokenizer = Tokenizer() tokenizer.fit_on_texts(texts) word_index = tokenizer.word_index # Convert text data to sequences sequences = tokenizer.texts_to_sequences(texts) padded_sequences = pad_sequences(sequences, maxlen=100) # Adjust maxlen as needed # Split the data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(padded_sequences, labels, test_size=0.2, random_state=42) # Define the model (simple neural network for text classification) model = keras.Sequential([ layers.Embedding(len(word_index) + 1, 32, input_length=100), # Embedding layer layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(1, activation='sigmoid') ]) # Compile the model model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Train the model model.fit(X_train, y_train, epochs=5, batch_size=32, validation_split=0.1) # Evaluate the model test_loss, test_acc = model.evaluate(X_test, y_test) print(f'Test accuracy: {test_acc}') # Predict on test data y_pred = model.predict(X_test) print("Predicted values:", y_pred)
import React, { useState } from "react"; import { CustomLink } from "../CustomLink/CustomLink"; const Header = () => { const [isOpen, setIsOpen] = useState(false); return ( <div> <nav className="bg-gray-800"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center"> <div className="flex items-center text-center justify-center h-16"> <div className="flex items-center justify-center text-center"> <div className="flex-shrink-0"></div> <div className="md:block justify-center items-center"> <div className="flex items-center justify-center space-x-4"> <CustomLink to="/home" className=" hover:bg-gray-700 text-gray-300 px-3 py-2 rounded-md text-sm font-medium" > Home </CustomLink> <CustomLink to="/reviews" className="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium" > Reviews </CustomLink> <CustomLink to="/dashboard" className="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium" > Dashboard </CustomLink> <CustomLink to="/blogs" className="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium" > Blogs </CustomLink> <CustomLink to="/about" className="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium" > About </CustomLink> </div> </div> </div> </div> </div> </nav> </div> ); }; export default Header;
<?php namespace App\Entity; use App\Repository\ArticleRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: ArticleRepository::class)] class Article { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column()] private ?int $id = null; #[ORM\Column(length: 180)] private ?string $title = null; #[ORM\Column(length: 100)] private ?string $author = null; #[ORM\Column(length: 255)] private ?string $description = null; #[ORM\Column(type: Types::TEXT)] private ?string $content = null; #[ORM\Column(length: 255)] private ?string $image = null; #[ORM\Column] private ?bool $is_published = null; #[ORM\ManyToOne(inversedBy: 'articles')] #[ORM\JoinColumn(nullable: false)] private ?Category $category = null; #[ORM\OneToMany(mappedBy: 'article', targetEntity: Comment::class)] private Collection $comments; public function __construct() { $this->comments = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getTitle(): ?string { return $this->title; } public function setTitle(string $title): self { $this->title = $title; return $this; } public function getAuthor(): ?string { return $this->author; } public function setAuthor(string $author): self { $this->author = $author; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getContent(): ?string { return $this->content; } public function setContent(string $content): self { $this->content = $content; return $this; } public function getImage(): ?string { return $this->image; } public function setImage(string $image):self { $this->image = $image; return $this; } public function isIsPublished(): ?bool { return $this->is_published; } public function setIsPublished(bool $is_published): self { $this->is_published = $is_published; return $this; } public function getCategory(): ?Category { return $this->category; } public function setCategory(?Category $category): self { $this->category = $category; return $this; } /** * @return Collection<int, Comment> */ public function getComments(): Collection { return $this->comments; } public function addComment(Comment $comment): self { if (!$this->comments->contains($comment)) { $this->comments->add($comment); $comment->setArticle($this); } return $this; } public function removeComment(Comment $comment): self { if ($this->comments->removeElement($comment)) { // set the owning side to null (unless already changed) if ($comment->getArticle() === $this) { $comment->setArticle(null); } } return $this; } }
import { useState } from 'react'; import { submitFormData } from '../utils/api'; export default function EventsPage() { const [createForm, setCreateForm] = useState({ name: '', date: '', location: '', duration: '', description: '', startTime: '', organizationId: '' }); const [deleteForm, setDeleteForm] = useState({ id: '' }); const [updateForm, setUpdateForm] = useState({ id: '', name: '', date: '', location: '', duration: '', description: '', startTime: '', organizationId: '' }); const [getByIdForm, setGetByIdForm] = useState({ id: '' }); const [getAttendeesForm, setGetAttendeesForm] = useState({ eventId: '' }); const getFormDataAndAction = (form) => { switch (form) { case 'create': return { formData: createForm, endpoint: '/events', method: 'POST', }; case 'delete': return { formData: deleteForm, endpoint: `/events/${deleteForm.id}`, method: 'DELETE', }; case 'update': return { formData: updateForm, endpoint: `/events/${updateForm.id}`, method: 'PUT', }; case 'getById': return { formData: getByIdForm, endpoint: `/events/${getByIdForm.id}`, method: 'GET', }; case 'getAttendees': return { formData: getAttendeesForm, endpoint: `/events/${getAttendeesForm.eventId}/attendees`, method: 'GET', }; default: return {}; } }; const handleSubmit = (form) => async (event) => { event.preventDefault(); const { formData, endpoint, method } = getFormDataAndAction(form); console.log('Submitting form data:', formData); try { const responseData = await submitFormData(formData, endpoint, method); console.log('Response from API:', responseData); } catch (error) { console.error('Error submitting form data:', error); } }; return ( <div style={{ textAlign: 'center' }}> <h1>Events</h1> <form onSubmit={handleSubmit('create')} style={formStyle}> <h2>Create Event</h2> <div> <label>Name:</label> <input type="text" value={createForm.name} onChange={(e) => setCreateForm({ ...createForm, name: e.target.value })} style={inputStyle} /> </div> <div> <label>Date:</label> <input type="date" value={createForm.date} onChange={(e) => setCreateForm({ ...createForm, date: e.target.value })} style={inputStyle} /> </div> <div> <label>Location:</label> <input type="text" value={createForm.location} onChange={(e) => setCreateForm({ ...createForm, location: e.target.value })} style={inputStyle} /> </div> <div> <label>Duration:</label> <input type="text" value={createForm.duration} onChange={(e) => setCreateForm({ ...createForm, duration: e.target.value })} style={inputStyle} /> </div> <div> <label>Description:</label> <textarea value={createForm.description} onChange={(e) => setCreateForm({ ...createForm, description: e.target.value })} style={inputStyle} /> </div> <div> <label>Start Time:</label> <input type="time" value={createForm.startTime} onChange={(e) => setCreateForm({ ...createForm, startTime: e.target.value })} style={inputStyle} /> </div> <div> <label>Organization ID:</label> <input type="text" value={createForm.organizationId} onChange={(e) => setCreateForm({ ...createForm, organizationId: e.target.value })} style={inputStyle} /> </div> <button type="submit" style={buttonStyle}>Submit</button> </form> <form onSubmit={handleSubmit('delete')} style={formStyle}> <h2>Delete Event</h2> <div> <label>Event ID:</label> <input type="text" value={deleteForm.id} onChange={(e) => setDeleteForm({ ...deleteForm, id: e.target.value })} style={inputStyle} /> </div> <button type="submit" style={buttonStyle}>Submit</button> </form> <form onSubmit={handleSubmit('update')} style={formStyle}> <h2>Update Event</h2> <div> <label>Event ID:</label> <input type="text" value={updateForm.id} onChange={(e) => setUpdateForm({ ...updateForm, id: e.target.value })} style={inputStyle} /> </div> <div> <label>Name:</label> <input type="text" value={updateForm.name} onChange={(e) => setUpdateForm({ ...updateForm, name: e.target.value })} style={inputStyle} /> </div> <div> <label>Date:</label> <input type="date" value={updateForm.date} onChange={(e) => setUpdateForm({ ...updateForm, date: e.target.value })} style={inputStyle} /> </div> <div> <label>Location:</label> <input type="text" value={updateForm.location} onChange={(e) => setUpdateForm({ ...updateForm, location: e.target.value })} style={inputStyle} /> </div> <div> <label>Duration:</label> <input type="text" value={updateForm.duration} onChange={(e) => setUpdateForm({ ...updateForm, duration: e.target.value })} style={inputStyle} /> </div> <div> <label>Description:</label> <textarea value={updateForm.description} onChange={(e) => setUpdateForm({ ...updateForm, description: e.target.value })} style={inputStyle} /> </div> <div> <label>Start Time:</label> <input type="time" value={updateForm.startTime} onChange={(e) => setUpdateForm({ ...updateForm, startTime: e.target.value })} style={inputStyle} /> </div> <div> <label>Organization ID:</label> <input type="text" value={updateForm.organizationId} onChange={(e) => setUpdateForm({ ...updateForm, organizationId: e.target.value })} style={inputStyle} /> </div> <button type="submit" style={buttonStyle}>Submit</button> </form> <form onSubmit={handleSubmit('getById')} style={formStyle}> <h2>Get Event by ID</h2> <div> <label>Event ID:</label> <input type="text" value={getByIdForm.id} onChange={(e) => setGetByIdForm({ ...getByIdForm, id: e.target.value })} style={inputStyle} /> </div> <button type="submit" style={buttonStyle}>Submit</button> </form> <form onSubmit={handleSubmit('getAttendees')} style={formStyle}> <h2>Get Attendees for Event</h2> <div> <label>Event ID:</label> <input type="text" value={getAttendeesForm.eventId} onChange={(e) => setGetAttendeesForm({ ...getAttendeesForm, eventId: e.target.value })} style={inputStyle} /> </div> <button type="submit" style={buttonStyle}>Submit</button> </form> <a href="/"> <h3>Return Home</h3> </a> </div> ); } const formStyle = { marginBottom: '20px', padding: '20px', backgroundColor: '#f9f9f9', borderRadius: '8px', width: '100%', maxWidth: '600px', margin: '0 auto', }; const inputStyle = { width: '100%', padding: '10px', marginBottom: '15px', border: '1px solid #ccc', borderRadius: '4px', boxSizing: 'border-box', fontFamily: 'Arial, sans-serif', }; const buttonStyle = { padding: '10px 20px', backgroundColor: '#007bff', color: '#fff', border: 'none', borderRadius: '4px', cursor: 'pointer', };
from fastapi import FastAPI, UploadFile, File import whisper from transformers import MarianMTModel, MarianTokenizer, pipeline, AutoTokenizer, AutoModelForSequenceClassification import uvicorn import numpy as np import pandas as pd import torch import os app = FastAPI() # Cargar el modelo y el tokenizador output_dir = os.path.join(os.path.dirname(__file__), "model_save") loaded_tokenizer = AutoTokenizer.from_pretrained(output_dir) loaded_model = AutoModelForSequenceClassification.from_pretrained(output_dir) # Cargar los modelos preentrenados whisper_model = whisper.load_model("small") translation_model = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-es-en") translation_tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-es-en") #sentiment_analysis = pipeline('sentiment-analysis', model='distilbert-base-uncased-finetuned-sst-2-english') @app.post("/analyze/") async def transcribe_translate(file: UploadFile = File(...)): # Guardar el archivo subido with open("temp_audio_file.mp3", "wb") as buffer: buffer.write(file.file.read()) # Transcribir el audio en español result_es = whisper_model.transcribe("temp_audio_file.mp3", language='es') transcription_es = result_es['text'] # Traducir el texto al inglés translated = translation_model.generate(**translation_tokenizer(transcription_es, return_tensors="pt", padding=True)) translation_en = [translation_tokenizer.decode(t, skip_special_tokens=True) for t in translated] # Tokenizar la frase de prueba test_phrases = [translation_en[0]] inputs = loaded_tokenizer(test_phrases, padding=True, truncation=True, return_tensors="pt") # Mover los inputs al dispositivo adecuado device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") loaded_model.to(device) inputs = {k: v.to(device) for k, v in inputs.items()} # Hacer predicciones with torch.no_grad(): outputs = loaded_model(**inputs) predictions = outputs.logits.argmax(dim=-1) # Mapeo de los índices de las etiquetas a las clases de sentimiento label_map = {0: "Negativa", 1: "Algo negativa", 2: "Neutral", 3: "Algo positiva", 4: "Positiva"} sentiment_label = label_map[predictions.item()] #return {"transcription_es": transcription_es, "translation_en": translation_en[0]} # Analizar el sentimiento del texto traducido #sentiment_result = sentiment_analysis(translation_en)[0] return { "transcription_es": transcription_es, # "translation_en": translation_en, "sentiment": sentiment_label } if __name__ == "__main__": uvicorn.run(app, host="localhost", port=4000)
import { For, Show, Suspense, createEffect, createResource, createSignal } from "solid-js" import { fetch_structured_full_trabajadores } from "../functions/fetch"; import Spinner from "./Spinner"; export default function Caratula() { const [trabajador, setTrabajador] = createSignal<number>(); const [currTrabajador, setCurrTrabajador] = createSignal<Record<string, any>>(); const [trabajadores] = createResource<Record<string, any>[number]>(fetch_structured_full_trabajadores); createEffect(() => { if (trabajador()) { setCurrTrabajador(trabajadores()[trabajador()!]) } console.log(currTrabajador()); }); return <Suspense fallback={<div>Cargando informacion</div>}> <Show when={trabajadores.error}> <div class="flex flex-row items-center gap-4 text-xl font-bold"> <Spinner size={"lg"} /> <p>Cargando información...</p> </div> </Show> <Show when={trabajadores.error}> Error </Show> <Show when={trabajadores.state === "ready"}> <article class="mx-8"> <div class="flex w-full justify-end gap-4"> <Show when={!trabajador()}> Trabajador no seleccionado </Show> <Show when={trabajador()}> Trabajador seleccionado: </Show> {/* @ts-ignore */} <select value={trabajador()} onChange={(e) => setTrabajador(e.currentTarget.value)}> <For each={trabajadores()}>{ (trabajador, id) => <option value={id()} > {trabajador.Nombres} {trabajador.APaterno} </option> }</For> </select> </div> <Show when={trabajador() && currTrabajador()}> <div class="w-full flex flex-row flex-wrap my-4 justify-center"> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">idTrabajador:</h5> <p class="w-1/3 border border-black rounded-sm bg-gray-200 text-center">{currTrabajador()!.idTrabajador}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Nombre completo:</h5> <p class="w-1/3 border border-black rounded-sm bg-gray-200 text-center">{`${currTrabajador()!.Nombres} ${currTrabajador()!.APaterno} ${currTrabajador()!.AMaterno}`}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Foto:</h5> <img loading="lazy" alt="Foto de trabajador" src={currTrabajador()!.Foto} /> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">idSexo:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.idSexo ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.idSexo ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">idSangre:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.idSangre ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.idSangre ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Fecha nacimiento:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.FecNacimiento ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.FecNacimiento ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Fecha alta:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.FecAlta ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.FecAlta ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Sueldo:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.SBC ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.SBC ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">NSS:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.Nss ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.Nss ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">CURP:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.CURP ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.CURP ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">RFC:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.Rfc ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.Rfc ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">INE:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.Ife ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.Ife ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Domicilio:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center`}> {`${currTrabajador()!.DomCalle}, ${currTrabajador()!.DomNumExt},${currTrabajador()!.DomNumInt ? currTrabajador()!.DomNumInt + "," : ""} ${currTrabajador()!.DomColonia}, ${currTrabajador()!.DomCp}, ${currTrabajador()!.DomCiudad}, ${currTrabajador()!.DomEstado}`} </p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Celular:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.Cel ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.Cel ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">idBanco:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.idBanco ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.idBanco ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Número de cuenta:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.CtaNum ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.CtaNum ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">CLABE:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.CtaClabe ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.CtaClabe ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Calzado Medida:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.CalzMedida ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.CalzMedida ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Calzado Medida:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.CalzCasquillo ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.CalzCasquillo ? "Si" : "No"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Calzado Medida:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.Contacto ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.Contacto ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Teléfono del contacto:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.TelContacto ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.TelContacto ?? "X"}</p> </div> <div class="w-1/2 flex flex-row justify-start items-center"> <h5 class="font-bold tracking-wide w-2/3">Beneficiario:</h5> <p class={`w-1/3 border border-black rounded-sm bg-gray-200 text-center ${currTrabajador()!.Beneficiario ? "bg-gray-200" : "bg-red-400"}`}>{currTrabajador()!.Beneficiario ?? "X"}</p> </div> </div> </Show> </article> </Show> </Suspense> }
var todoList = []; let keyRef = 0; function AddTodo() { const value = document.getElementById("add-todo").value; if (value) { let temp = { value: value, isRead: false, isRemoved: false } todoList.push(temp) AddElementToHTML(); document.getElementById("add-todo").value = null; updateLocalStorage(); ToggleNoTodo() } else { alert('Please enter a todo'); } } function AddElementToHTML(todo = null) { const p = document.createElement("p"); // creating a html element as <p> tag p.id = `todo-name-${keyRef}` const container = document.createElement("div"); // creating a html element as <p> tag container.className = `todo` // setting the <p> with a classname as 'todo' container.id = `${keyRef}` const removeBtn = document.createElement("button"); removeBtn.textContent = 'X'; removeBtn.addEventListener('click', () => RemoveTodo(container.id)) const node = document.createTextNode(todo?.value ?? todoList[todoList.length - 1].value); // creating a text p.appendChild(node); // adding the text to the <p> container.appendChild(p); container.appendChild(removeBtn); // adding the text to the <p> container.addEventListener('dblclick', () => MarkReadToggler(container.id)); const element = document.getElementById("list-container"); // getting where to insert the <p> tag element.append(container);// appending p tag as child to the "list-container" id. keyRef++; } function RemoveTodo(id) { let tag = document.getElementById(id); var todo = todoList.filter(todo => todo.value === tag.getElementsByTagName('p')[0].innerText) if (todo[0].isRead) { todoList = todoList.filter(todo => todo.value !== tag.getElementsByTagName('p')[0].innerText) tag.style.display = 'none'; tag.remove(); updateLocalStorage(); ToggleNoTodo(); } else { alert("Please finish the task to remove...") } } function ToggleNoTodo() { const todo = document.getElementById("empty-todo") if (todoList.length === 0) { todo.style.display = 'block' } else { todo.style.display = 'none' } } function MarkReadToggler(id) { let tag = document.getElementById(id); let todo = todoList.filter(todo => todo.value === tag.getElementsByTagName('p')[0].innerText) todo[0].isRead = !todo[0].isRead; if (todo[0].isRead) { document.getElementById(`todo-name-${id}`).style.textDecoration = 'line-through' } else { document.getElementById(`todo-name-${id}`).style.textDecoration = 'none' } } function GetListFromLocalStorage() { const data = localStorage.getItem('todoList'); if (data) { todoList = JSON.parse(data); for (let todo of todoList) { AddElementToHTML(todo); } ToggleNoTodo(); } else { console.log('no data found') } } function updateLocalStorage() { localStorage.setItem('todoList', JSON.stringify(todoList)) }
import WebSocket from 'ws'; import { EventEmitter } from 'node:events'; import Alert from './Alert.js'; export default class TzevaAdom extends EventEmitter { constructor() { super(); this.#fetchGeographicData().then(data => { this._AllAreas = data.areas; this._AllCities = data.cities }); this.#wsConnect().then(); } async #wsConnect() { this._ws = this.#createWebSocket(); let isReconnecting = false; const handleReconnect = () => { // handle the reconnection this._ws.close(); if (isReconnecting) return; isReconnecting = true; setTimeout(this.#wsConnect.bind(this), 5000); // Bind 'this' to the function }; this._ws.onopen = () => {}; // log the connection this._ws.onclose = () => handleReconnect(); // reconnect if the connection is closed this._ws.onerror = (e) => { console.error(e.error); handleReconnect(); } this._ws.onmessage = async (m) => { this.#handelMessage(m); } } #createWebSocket() { const WEBSOCKET_URL = "wss://ws.tzevaadom.co.il:8443/socket?platform=WEB"; // the websocket url return new WebSocket(WEBSOCKET_URL, { headers: { origin: "https://www.tzevaadom.co.il", }, }); } #handelMessage(message){ if (typeof message.data !== "string") return null; const ALERT = new Alert(message, this._AllCities, this._AllAreas); if (ALERT.isAlert()) { this.emit("onAlert", ALERT); } } async #fetchGeographicData() { const versionR = await fetch("https://api.tzevaadom.co.il/lists-versions"); const versionJson = await versionR.json(); const version = versionJson.cities; let response = await fetch( "https://www.tzevaadom.co.il/static/cities.json?v=" + version ); response = await response.json(); return {cities: response.cities, areas: response.areas}; } }
var margin = {top: 20, right: 20, bottom: 30, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom, centered, animation; var projection = d3.geo.albersUsa().scale(width); var path = d3.geo.path() .projection(projection); var svg = d3.select("#map").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.json("us.json", function(error, us) { var state_features = topojson.feature(us, us.objects.states).features; var feature_domain = [0, state_features.length-1]; // setup x var xScale = d3.scale.linear().range([0, width]).domain(feature_domain), // value -> display xAxis = d3.svg.axis().scale(xScale).orient("bottom"); // setup y var yScale = d3.scale.linear().range([height, 0]).domain(feature_domain), // value -> display yAxis = d3.svg.axis().scale(yScale).orient("left"); // x-axis var x_axis_g = svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + (height) + ")") .call(xAxis).style('opacity', 0); x_axis_g.append("text") .attr("class", "label") .attr("x", width) .attr("y", -6) .style("text-anchor", "end") .text("Random X variable"); // y-axis var y_axis_g = svg.append("g") .attr("class", "y axis") .call(yAxis) .style('opacity', 0); y_axis_g.append("text") .attr("class", "label") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Random Y variable"); var g = svg.append("g"); var scale = d3.scale.linear() .domain(feature_domain) .range([0, Math.PI*2]); var states = g.append("g") .attr("id", "states") .selectAll("path") .data(state_features) .enter().append("path") .attr("d", path); var default_size = function(d, i) { return 40; }; var exploder = d3.geo.exploder() .projection(projection) .size(default_size); function addButton(text, callback) { d3.select("#buttons").append('button') .text(text) .on('click', function() { // clear running animation animation = clearTimeout(animation); // hide axis x_axis_g.transition().duration(500).style('opacity', 0); y_axis_g.transition().duration(500).style('opacity', 0); // reset to default size exploder.size(default_size); callback.call(this); }) } // -------------------------- // // randomly ordered grid // // -------------------------- addButton('random grid', function() { var rand = d3.shuffle(d3.range(state_features.length)); states.transition() .duration(500) .call( exploder.position(function(d, index) { var i = rand[index]; var px = Math.max(0, width - 9*60)/2 return [px + (i%10)*60, 70 + Math.floor(i/10)*60]; }) ); }); // -------------------------- // // Circle Plot // // -------------------------- function circle(d, i) { var t = scale(i); var r = (height/2)*.8; var x = width/2 + r*Math.cos(t); var y = height/2 + r*Math.sin(t); return [x, y]; } addButton('circle', function(d, i) { states.transition() .duration(500) .call(exploder.position(circle)); }); // -------------------------- // // Figure 8 plot // // -------------------------- function figure8(d, i) { var t = scale(i); var r = (height/2)*.8; var d = (1 + Math.pow(Math.sin(t), 2)); var x = width/2 + (r*Math.cos(t)) / d; var y = height/2 + (r*Math.sin(t)*Math.cos(t)) / d; return [x, y]; } addButton('figure 8 animated', function() { var advance = 1; function tick() { states .transition() .duration(500) .call(exploder.position(function(d, i) { return figure8(d, i + advance++); })); } animation = setInterval(tick, 550) tick(); }); // -------------------------- // // spiral Plot // // -------------------------- var spiral_scale = d3.scale.linear() .domain(feature_domain) .range([0, 50000]); var size_scale = d3.scale.linear() .domain(feature_domain) .range([10, 100]); function spiral(d, i) { var t = spiral_scale(i); var x = width/2 + Math.pow(t, 1/2)*Math.cos(t); var y = height/2 + Math.pow(t, 1/2)*Math.sin(t); return [x, y]; } addButton('spiral', function(d, i) { states.transition() .duration(500) .call( exploder .position(spiral) .size(function(d, i) { return size_scale(i); }) ); }); // -------------------------- // // Scatter Plot // // -------------------------- addButton('scatter', function(d, i) { // hide axis x_axis_g.transition().duration(500).style('opacity', 1); y_axis_g.transition().duration(500).style('opacity', 1); states.transition() .duration(500) .call( exploder.position(function(d, i) { var x = xScale(i) + (-0.5 + Math.random())*70; var y = yScale(i) + (-0.5 + Math.random())*70; return [x, y]; }) ); }); // -------------------------- // // realign map // // -------------------------- addButton('reset', function() { states.transition() .duration(500) .attr("d", path) .attr("transform", "translate(0,0)"); }); });
import {BaseComponent} from "../../../../type/BaseComponent"; import {LgPopLayer} from "@/components/popLayer"; import {connect, MapDispatchToProps, MapStateToProps} from "react-redux"; import "./rechargeLayer.scss" import {FunctionProperties, NonFunctionProperties} from "../../../../type/util"; import {RootState} from "../../../../redux/rootReducer"; import {bindActionCreators, Dispatch} from "redux"; import {WiseBoardAction} from "../../../../type/wiseBoard/WiseBoardAction"; import {RechargeLayerActionType} from "../../../../type/wiseBoard/rechargeLayer/rechargeLayerActionType"; import {FlexFillViewFrame} from "@/components/flexFillViewFrame"; import {WiseBoardTableData} from "../../../../type/wiseBoard/WiseBoardTableData"; import {CommonInput} from "@/components/CommonInput"; import {LgButton} from "@/components/button"; import {FormEvent} from "react"; import { BaseProps } from "../../../../type/BaseProps"; import {CommonTextarea} from "@/components/CommonTextarea"; import {recharge} from "../../../../redux/wiseBoard/rechargeLayer/rechargeLayerAction"; export interface RechargeLayerProps { isOpen: boolean onClose(): void rechargeSchool: WiseBoardTableData | null rechargeTime: number rechargeTimeChange(rechargeTime: number): void rechargeRemark: string rechargeRemarkChange(rechargeRemark: string): void onSubmit(): void } const quickInputs: { name: string, value: number }[] = [ { name: "5万分钟", value: 50000 }, { name: "10万分钟", value: 100000 }, { name: "30万分钟", value: 300000 }, { name: "50万分钟", value: 500000 }, ] export class RechargeLayer extends BaseComponent<RechargeLayerProps> { constructor(props: RechargeLayerProps & BaseProps) { super(props); this.handleQuickInput = this.handleQuickInput.bind(this) this.handleRechargeTimeChange = this.handleRechargeTimeChange.bind(this) this.handleRemarkInput = this.handleRemarkInput.bind(this) } render() { return ( <LgPopLayer width={600} height={480} isShowBottom={false} title="充值" isOpen={this.props.isOpen} onShowLayer={this.props.onClose} className={this.rootClass()}> <FlexFillViewFrame flexStart={this.renderTips()} orientation="vertical"> {this.renderForm()} </FlexFillViewFrame> </LgPopLayer> ) } renderTips() { return ( <div className={this.class("tips")}> {this.renderSchoolInfo()} {this.renderRemainTime()} </div> ) } renderSchoolInfo() { return ( <div className={this.class("school-info")}> <div className={this.class("school-info-name")}>当前学校:</div> <div className={this.class("school-info-value")}>{this.props.rechargeSchool?.schoolName}</div> </div> ) } renderRemainTime() { return ( <div className={this.class("remain-time")}> <div className={this.class("remain-time-name")}>剩余时间:</div> <div className={this.class("remain-time-value")}> {this.props.rechargeSchool?.restCallTime} <div className={this.class("remain-time-value-subtitle")}>分钟</div> </div> </div> ) } handleRechargeTimeChange(e: FormEvent<HTMLInputElement>){ let newVal = 0 if(e.currentTarget.value){ newVal = Number(e.currentTarget.value) } if(newVal > 10000000){ newVal = 10000000 } this.props.rechargeTimeChange(newVal) } handleQuickInput(item: {name: string, value: number}){ if(item.value !== this.props.rechargeTime){ this.props.rechargeTimeChange(item.value) } } handleRemarkInput(e: FormEvent<HTMLTextAreaElement>){ this.props.rechargeRemarkChange(e.currentTarget.value) } renderForm() { return ( <div className={this.class("form")}> <div className={this.class("form-item")}> <div className={this.class("form-item-name")}> 充值时长: </div> <div className={this.class("form-item-content")}> <CommonInput value={this.props.rechargeTime === 0? "" :this.props.rechargeTime.toString()} onInput={this.handleRechargeTimeChange} className={this.class("inner-input")} type="number" inputFilter="numberOnly" min={1} max={10000000} maxLength={9}/> </div> <div className={this.class("form-item-tail")}>分钟</div> </div> <div className={this.class("form-item")}> <div className={this.class("form-item-name")}/> <div className={this.class("form-item-content")}> <div className={this.class("quick-input-list")}> { quickInputs.map(item => <div key={item.value} onClick={() => this.handleQuickInput(item)} className={this.class("quick-input", {"selected": item.value === this.props.rechargeTime})}>{item.name}</div>) } </div> </div> </div> <div className={this.class("form-item")}> <div className={this.class("form-item-name")}>备注:</div> <div className={this.class("form-item-content")}> <CommonTextarea value={this.props.rechargeRemark} onInput={this.handleRemarkInput} maxLength={50} /> </div> </div> <div className={this.class("form-operation")}> <LgButton className={this.class("submit-button")} onClick={this.props.onSubmit} value={"充值"} type="info" radius gradient /> </div> </div> ) } getClassNamePrefix(): string { return "RechargeLayer"; } } const mapStateToProps: MapStateToProps<NonFunctionProperties<RechargeLayerProps>, RechargeLayerProps, RootState> = (state) => { return { isOpen: state.wiseBoardState.rechargeLayerState.showRechargeLayer, rechargeSchool: state.wiseBoardState.rechargeLayerState.rechargeSchool, rechargeTime: state.wiseBoardState.rechargeLayerState.rechargeTime, rechargeRemark: state.wiseBoardState.rechargeLayerState.rechargeRemark } } const mapDispatchToProps: MapDispatchToProps<FunctionProperties<RechargeLayerProps>, any> = (dispatch: Dispatch<WiseBoardAction>) => { return { onClose: () => dispatch({type: RechargeLayerActionType.CLOSE_RECHARGE_LAYER}), rechargeTimeChange: (rechargeTime) => dispatch({type: RechargeLayerActionType.RECHARGE_LAYER_RECHARGE_TIME_CHANGE, rechargeTime}), rechargeRemarkChange: (rechargeRemark) => dispatch({type: RechargeLayerActionType.RECHARGE_LAYER_RECHARGE_REMARK_CHANGE, rechargeRemark}), ...bindActionCreators({onSubmit: recharge}, dispatch) } } export const RechargeLayerComponent = connect(mapStateToProps, mapDispatchToProps)(RechargeLayer)
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:frederic/backend/sets/frederic_set_list_data.dart'; import 'package:frederic/backend/sets/frederic_set_manager.dart'; import 'package:frederic/backend/workouts/frederic_workout_activity.dart'; import 'package:frederic/widgets/standard_elements/shadow_list_view.dart'; import 'package:frederic/widgets/workout_player_screen/activity_player_view.dart'; import 'package:frederic/widgets/workout_player_screen/short_set_card.dart'; import 'package:provider/provider.dart'; class ActivityPlayerSetSegment extends StatelessWidget { const ActivityPlayerSetSegment(this.activity, {required this.controller, Key? key}) : super(key: key); final FredericWorkoutActivity activity; final ScrollController controller; @override Widget build(BuildContext context) { return BlocBuilder<FredericSetManager, FredericSetListData>( buildWhen: (current, next) => next.changedActivities.contains(activity.activity.id), builder: (context, setListData) { double itemExtent = 60; var todaysSets = setListData[activity.activity.id].getTodaysSets(); int numberOfSetsTODO = activity.sets; int numberOfSetsDone = todaysSets.length; int numberOfSetsTODOToDisplay = numberOfSetsTODO - numberOfSetsDone; if (numberOfSetsTODOToDisplay < 0) numberOfSetsTODOToDisplay = 0; int numberOfSetsTotal = numberOfSetsDone + numberOfSetsTODOToDisplay; int indexCurrentSet = numberOfSetsDone; bool everythingComplete = numberOfSetsDone >= numberOfSetsTODO; WidgetsBinding.instance.addPostFrameCallback((timeStamp) { controller.jumpTo(0); jumpTo(indexCurrentSet * itemExtent); }); Future(() { Provider.of<BooleanChangeNotifier>(context, listen: false).value = everythingComplete; }); //int currentFirstItem = widget.controller.offset ~/ itemExtent; //print(currentFirstItem); return LayoutBuilder(builder: (context, constraints) { double availableHeight = constraints.maxHeight; int itemCount = availableHeight ~/ itemExtent; double listHeight = itemCount * itemExtent; return Column( children: [ Container( height: listHeight, child: GestureDetector( onVerticalDragUpdate: (details) { if (details.delta.dy.abs() >= 1) { if (details.delta.dy < 0) { jumpTo(controller.offset + itemExtent); } else { jumpTo(controller.offset - itemExtent); } } }, child: NotificationListener<OverscrollIndicatorNotification>( onNotification: (overscroll) { overscroll.disallowIndicator(); return true; }, child: ShadowListView( blurPadding: const EdgeInsets.only(left: 24), controller: controller, shadowWidth: 12, prototypeItem: ShortSetCard(), itemCount: numberOfSetsTotal + 1, scrollDirection: Axis.vertical, physics: NeverScrollableScrollPhysics(), itemBuilder: (context, index) { if (index >= numberOfSetsTotal) { return ShortSetCard( finished: everythingComplete, disabled: !everythingComplete, last: true, ); } else if (index > indexCurrentSet) { // sets still to do: return ShortSetCard( reps: activity.reps, disabled: true, ); } else if (index == indexCurrentSet) { // current set: return ShortSetCard( reps: activity.reps, ); } else { // sets already done: int reps = activity.reps; if (index < todaysSets.length) reps = todaysSets[index].reps; return ShortSetCard( reps: reps, finished: true, ); } }, ), ), ), ), //Expanded(child: Container()), ], ); }); }); } void jumpTo(double offset) { controller.animateTo(offset, duration: const Duration(milliseconds: 200), curve: Curves.easeInOut); } }
import { ActionReducerMapBuilder, CaseReducer, createAction, createReducer, PayloadAction } from "@reduxjs/toolkit"; import { IProduct } from "../../Models/Product"; import { ReducerWithInitialState } from "@reduxjs/toolkit/dist/createReducer"; //State export type IProductWithAmount = IProduct & {amount: number} export interface ProductState{ products:Array<IProductWithAmount>; } const initState:ProductState = { products: [] } /* +-------------------+ | 1) DEFINE ACTIONS | +-------------------+ */ export enum ProductsActionNames { ADD_UNIT_TO_CART = "products/ADD_UNIT_TO_CART", REMOVE_UNIT_FROM_CART = "products/REMOVE_UNIT_FROM_CART" }; //Define Redux Action creators to set <TPayload,TAction> for each action: export const ADD_UNIT_TO_CART = createAction<IProduct,string>(ProductsActionNames.ADD_UNIT_TO_CART); export const REMOVE_UNIT_FROM_CART = createAction<IProduct,string>(ProductsActionNames.REMOVE_UNIT_FROM_CART); /* +------------------------------------------+ | 1) DEFINE A CASE REDUCER FOR EACH ACTION | +------------------------------------------+ */ //ADD_ARTICLE const addUnitToCart:CaseReducer<ProductState, PayloadAction<IProduct,string>> = (state:ProductState, action:PayloadAction<IProduct,string>) => { const entry = state.products.find(product => product.id === action.payload.id); if(entry === undefined){ state.products.push({...action.payload, amount: 1}) } else { entry.amount+=1; } return state; }; //REMOVE_ARTICLE const removeUnitFromCart:CaseReducer<ProductState, PayloadAction<IProduct,string>> = (state:ProductState, action:PayloadAction<IProduct,string>) => { const entry = state.products.find(product => product.id === action.payload.id); if(entry === undefined){ return state; } if(entry.amount===1){ state.products = state.products.filter(product => product !== entry); return state; } entry.amount-=1; return state; }; /* +-----------------------------------------+ | 3) MAP ACTION TYPES WITH CASE REDUCERS | +-----------------------------------------+ */ const reducerBuilder = (builder:ActionReducerMapBuilder<ProductState>) => { builder.addCase(ADD_UNIT_TO_CART, addUnitToCart); builder.addCase(REMOVE_UNIT_FROM_CART, removeUnitFromCart); }; /* +-----------------------+ | 4) BUILD THE REDUCER | +-----------------------+ */ export const ProductReducer: ReducerWithInitialState<ProductState> = createReducer<ProductState>(initState,reducerBuilder);
import { proxyObject } from './utils'; import { isNotBoolean } from './types'; export type Key = { win?: string; mac?: string; macSymbol?: string; alias?: string; symbol?: string; }; type NormalizeKey = string; /** * https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values */ export function normalizeKey(code: string): NormalizeKey { const s = code.toLowerCase(); if (s.startsWith('control')) return 'ctrl'; if (s.startsWith('meta') || s === 'command' || s.startsWith('os')) return 'meta'; if (s.startsWith('shift')) return 'shift'; if (s.startsWith('alt') || s === 'option') return 'alt'; return s.replace(/^(digit|key|numpad)/, ''); } function appendToMap(keys: Record<NormalizeKey, Key>) { Object.entries(keys).forEach(([named, key]) => { Object.entries(key).forEach(([_, k]) => { map[k] = named; }); }); } const keys: Record<NormalizeKey, Key> = { ctrl: { alias: 'control', macSymbol: '⌃', }, meta: { win: 'win', mac: 'command', macSymbol: '⌘', }, shift: { symbol: '⇧', }, alt: { mac: 'option', macSymbol: '⌥', }, escape: { alias: 'esc', }, backspace: { symbol: '⌫', }, enter: { alias: 'return', symbol: '↵', }, space: { symbol: '␣', }, capsLock: { symbol: '⇪', }, arrowdown: { alias: 'down', symbol: '↓', }, arrowup: { alias: 'up', symbol: '↑', }, arrowleft: { alias: 'left', symbol: '←', }, arrowright: { alias: 'right', symbol: '→', }, minus: { symbol: '-', }, equal: { symbol: '=', }, period: { symbol: '.', }, comma: { symbol: ',', }, slash: { symbol: '/', }, backslash: { symbol: '|', }, bracketleft: { symbol: '[', }, bracketright: { symbol: ']', }, semicolon: { symbol: ';', }, quote: { symbol: "'", }, backquote: { symbol: '`', }, }; const map: Record<string, NormalizeKey> = proxyObject({}); appendToMap(keys); export const isMac = navigator.platform.includes('Mac'); export function getDisplayKey(code: string, type?: keyof Key) { const key = normalizeKey(code); const keyObj = keys[key]; let result: string | undefined = undefined; if (!keyObj) { result = key; } else if (type) { result = keyObj[type]; } if (!result) { result = (isMac ? keyObj['macSymbol'] || keyObj['mac'] : keyObj['win']) || keyObj['symbol'] || key; } return result.replace(/^(.)/, (_substr, $1: string) => $1.toUpperCase()); } // custom key map export function setKeys(keysRecord: Record<NormalizeKey, Key>) { Object.assign(keys, keysRecord); appendToMap(keysRecord); } const hotkeySplitter = /,(?!,)/; // https://bugs.webkit.org/show_bug.cgi?id=174931 // const keySplitter = /(?<!\+)\+/; const keySplitter = /\+/; export function matchHotKey(evt: KeyboardEvent, hotkey: string) { const keys = hotkey.split(keySplitter).map((k) => map[k]); const targetKeyEvent = { ctrl: false, meta: false, shift: false, alt: false, namedKey: '' }; keys.forEach((named) => { switch (named) { case 'ctrl': return (targetKeyEvent.ctrl = true); case 'meta': return (targetKeyEvent.meta = true); case 'shift': return (targetKeyEvent.shift = true); case 'alt': return (targetKeyEvent.alt = true); default: return (targetKeyEvent.namedKey = named); } }); let nextKey = ''; if (targetKeyEvent.namedKey.length > 2 && targetKeyEvent.namedKey.includes('-')) { // not support `a--`, `--a`, `a--b`, only allow `a-b` [targetKeyEvent.namedKey, nextKey] = [...targetKeyEvent.namedKey.split('-')]; } const match = evt.ctrlKey === targetKeyEvent.ctrl && evt.metaKey === targetKeyEvent.meta && evt.shiftKey === targetKeyEvent.shift && evt.altKey === targetKeyEvent.alt && (!targetKeyEvent.namedKey || normalizeKey(evt.code) === targetKeyEvent.namedKey || /** * https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values */ evt.key.toLowerCase() === targetKeyEvent.namedKey); return nextKey ? match && nextKey : match; } export type HotKeyHandles = { onLock?: (evt: KeyboardEvent) => void; onUnlock?: (evt: KeyboardEvent) => void; onUncapture?: (evt: KeyboardEvent) => void; [index: string]: ((evt: KeyboardEvent) => void) | undefined; }; let locked = false; const unlockCallback = new Set<() => void>(); export function unlock() { locked = false; unlockCallback.forEach((callback) => callback()); unlockCallback.clear(); } /** * must have non-control character; * not case sensitive; * support `a-b`, press `a`, hotkeys be locked, wait next `keydown` event, allow call `unlock` */ export function hotkeys(handles: HotKeyHandles) { return function (evt: KeyboardEvent) { if (evt.isComposing) return; if (locked) return; let captured = false; const nextKeyHandleSet = new Map<string, Set<(evt: KeyboardEvent) => void>>(); for (const str in handles) { const handle = handles[str]; if (!handle) break; const shortcuts = str.split(hotkeySplitter).map((e) => e.trim()); const matchResult = shortcuts.map((hotkey) => matchHotKey(evt, hotkey)); if (matchResult.some((r) => r === true)) { captured = true; handle(evt); } matchResult.filter(isNotBoolean).forEach((key) => { const set = nextKeyHandleSet.get(key) || new Set<(evt: KeyboardEvent) => void>(); set.add(handle); nextKeyHandleSet.set(key, set); }); } if (nextKeyHandleSet.size) { captured = true; unlockCallback.clear(); handles.onLock?.(evt); locked = true; const nextKeyHandle = (evt: KeyboardEvent) => { handles.onUnlock?.(evt); locked = false; evt.stopPropagation(); evt.preventDefault(); let nextKeyCaptured = false; nextKeyHandleSet.forEach((handleSet, k) => { if (matchHotKey(evt, k)) { nextKeyCaptured = true; handleSet.forEach((h) => h(evt)); } }); if (!nextKeyCaptured) handles.onUncapture?.(evt); }; unlockCallback.add(() => removeEventListener('keydown', nextKeyHandle, { capture: true })); addEventListener('keydown', nextKeyHandle, { once: true, capture: true }); } if (!captured) handles.onUncapture?.(evt); }; } /** * support space,enter */ export const commonHandle = hotkeys({ 'space,enter': (evt) => { (evt.target as HTMLElement).click(); evt.preventDefault(); }, esc: (evt) => { (evt.target as HTMLElement).blur(); evt.preventDefault(); }, });
<%= form_for(@course) do |f| %> <% if @course.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@course.errors.count, "error") %> prohibited this course from being saved:</h2> <ul> <% @course.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :name %><br> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :description %><br> <%= f.text_area :description %> </div> <div class="field"> <%= f.label :location %><br> <%= f.text_field :location %> </div> <div> <%= f.select(:instructor_id, Instructor.all.collect {|a| [ a.name, a.id ] }, {:include_blank => 'Please select an instructor'}) %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
const connection = require("../model/connection") const adminSchema = require("../model/adminSchema") const jwt = require("jsonwebtoken"); const jwtKey = "e-comm"; class adminController { //signup admin async signup(req, resp) { const { name, email, mobileNo, password } = req.body; try { const existsMail = await adminSchema.findOne({ email: email }); if (existsMail) { return resp.status(400).json({ message: "Email already exists", }); } const existsMobileNumber = await adminSchema.findOne({ mobileNo: mobileNo, }); if (existsMobileNumber) { return resp.status(400).json({ message: "Mobile number already exists", }); } const result = await adminSchema.create({ name, email, mobileNo, password, }); if (result) { return resp.status(201).json({ status: 201, message: "Signup successfully", data: result, }); } } catch (error) { return resp.status(500).json({ status: 500, message: "Internal server error", data: ["Error during signup:", error], }); } } //login Admin async login(req, resp) { try { const check = await adminSchema.findOne({ email: req.body.email }); if (!check) { return resp.status(401).send({ status: 401, Message: "User not found", }); } if (check.password === req.body.password) { jwt.sign( { adminSchema : check }, jwtKey, { expiresIn: "24h" }, (error, token) => { if (error) { resp.status(500).json({ status: 500, Message: "Token creation failed", }); } else { resp.status(200).json({ user: check, auth: token, status: 200, Message: "Welcome, you are logged in", data: check, }); } } ); } else { resp.status(401).json({ status: 401, Message: "Wrong password", }); } } catch (error) { resp.status(500).json({ status: 500, Message: "Server error", error: error.message, }); } } } module.exports = new adminController();
<div bsModal #createOrEditModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="createOrEditModal" aria-hidden="true" [config]="{ backdrop: 'static' }" > <div class="modal-dialog modal-lg"> <div class="modal-content"> <form *ngIf="active" #leadContactForm="ngForm" novalidate (ngSubmit)="save()" autocomplete="off"> <div class="modal-header"> <h4 class="modal-title"> <span *ngIf="leadContact.id">{{ l('EditLeadContact') }}</span> <span *ngIf="!leadContact.id">{{ l('CreateNewLeadContact') }}</span> </h4> <button type="button" class="btn-close" (click)="close()" aria-label="Close" [disabled]="saving" ></button> </div> <div class="modal-body"> <div class="my-3"> <label class="form-label" for="LeadTitle">{{ l('Lead') }}</label> <div class="input-group"> <input class="form-control" id="LeadTitle" name="leadTitle" [(ngModel)]="leadTitle" type="text" disabled /> <button class="btn btn-primary blue" (click)="openSelectLeadModal()" type="button"> <i class="fa fa-search"></i> {{ l('Pick') }} </button> <button class="btn btn-danger btn-icon" type="button" (click)="setLeadIdNull()"> <i class="fa fa-times"></i> </button> </div> </div> <input class="form-control" name="leadContact.leadId" [(ngModel)]="leadContact.leadId" type="text" required hidden /> <div class="my-3"> <label class="form-label" for="ContactFullName">{{ l('Contact') }}</label> <div class="input-group"> <input class="form-control" id="ContactFullName" name="contactFullName" [(ngModel)]="contactFullName" type="text" disabled /> <button class="btn btn-primary blue" (click)="openSelectContactModal()" type="button"> <i class="fa fa-search"></i> {{ l('Pick') }} </button> <button class="btn btn-danger btn-icon" type="button" (click)="setContactIdNull()"> <i class="fa fa-times"></i> </button> </div> </div> <input class="form-control" name="leadContact.contactId" [(ngModel)]="leadContact.contactId" type="text" required hidden /> <div class="my-3"> <label class="form-label" for="LeadContact_Notes">{{ l('Notes') }}</label> <input type="text" #LeadContact_Notes="ngModel" id="LeadContact_Notes" class="form-control" [(ngModel)]="leadContact.notes" name="Notes" /> <validation-messages [formCtrl]="LeadContact_Notes"></validation-messages> </div> <div class="my5"> <label class="form-label" for="LeadContact_InfluenceScore">{{ l('InfluenceScore') }}</label> <input type="number" #LeadContact_InfluenceScore="ngModel" id="LeadContact_InfluenceScore" class="form-control" [(ngModel)]="leadContact.influenceScore" name="InfluenceScore" /> <validation-messages [formCtrl]="LeadContact_InfluenceScore"></validation-messages> </div> </div> <div class="modal-footer"> <button [disabled]="saving" type="button" class="btn btn-default" (click)="close()"> {{ l('Cancel') }} </button> <button type="submit" class="btn btn-primary blue" [disabled]="!leadContactForm.form.valid" [buttonBusy]="saving" [busyText]="l('SavingWithThreeDot')" > <i class="fa fa-save"></i> <span>{{ l('Save') }}</span> </button> </div> </form> </div> </div> <leadContactLeadLookupTableModal #leadContactLeadLookupTableModal (modalSave)="getNewLeadId()" ></leadContactLeadLookupTableModal> <leadContactContactLookupTableModal #leadContactContactLookupTableModal (modalSave)="getNewContactId()" ></leadContactContactLookupTableModal> </div>
// // IndividualEventsView.swift // AlzhApp // // Created by lorena.cruz on 7/6/24. // // import SwiftUI struct IndividualEventsView: View { let patientID: Int? @EnvironmentObject var carerViewModel: CarerViewModel var body: some View { GeometryReader { proxy in ScrollView { VStack { if carerViewModel.isLoading { ProgressView("Cargando eventos...") .progressViewStyle(CircularProgressViewStyle(tint: .white)) .foregroundColor(.white) } else if let errorText = carerViewModel.errorText { Image(systemName: "exclamationmark.triangle") .resizable() .frame(width: 30, height: 30) .foregroundColor(.red) Text(errorText) .foregroundColor(.red) Button(action: { Task { carerViewModel.errorText = nil } }, label: { Text("Reintentar") .foregroundColor(.white) .padding() }) .background( Capsule() .fill(Color.red) ) } else if carerViewModel.events.isEmpty { Text("No se encontraron eventos.") .foregroundColor(.white) } else { VStack(spacing: 0) { ForEach(carerViewModel.events, id: \.id) { event in EventRowView(event: event) .frame(maxWidth: .infinity) .padding(.vertical, 15) .background(Color.white) .cornerRadius(8) .shadow(radius: 2) .padding(.horizontal) } } } } .navigationBarTitle("Eventos de paciente") .frame(maxWidth: .infinity, minHeight: proxy.size.height) } .background(LinearGradient(colors: AppColors.gradientBackground, startPoint: .top, endPoint: .bottom)) .onAppear { Task { if let patientID = patientID { await carerViewModel.getEventsByPatient(patientID: patientID) } } } } } } struct EventRowView: View { let event: Event var body: some View { VStack(alignment: .leading) { HStack { Image(systemName: event.status == "Por hacer" ? "exclamationmark.triangle.fill" : "checkmark.circle.fill") .resizable() .frame(width: 20,height: 20) .foregroundStyle(event.status == "Por hacer" ? AppColors.pink : AppColors.lilac) VStack{ HStack { Text("\(event.name ?? "Unknown") -" ) .font(.headline) .foregroundColor(.black) Text(event.type ?? "Unknown") .font(.headline) .foregroundColor(.black) .underline() } Text(event.description ?? "No description") .font(.subheadline) .foregroundColor(.black) if let initialDate = event.initialDate, let finalDate = event.finalDate { Text("Fecha: \(initialDate, formatter: Event.dateFormatter) - \(finalDate, formatter: Event.dateFormatter)") .font(.footnote) .foregroundColor(.gray) } if let initialHour = event.initialHour, let finalHour = event.finalHour { Text("Hora: \(initialHour, formatter: Event.timeFormatter) - \(finalHour, formatter: Event.timeFormatter)") .font(.footnote) .foregroundColor(.gray) } } } } .padding(10) } }
import { useEffect, useRef, useState } from "react"; import TabularCard from "./TabularCard/TabularCard"; import DynamicTitle from "../DynamicTitle/DynamicTitle"; import { useSetTitle } from "../../hooks/useSetTitle"; const AllToys = () => { useSetTitle("All Toys") const query = useRef(); const [searchQuery, setSearchQuery] = useState(""); const [allToys, setAllToys] = useState([]); const searchHandler = () => { let searchedData = query.current.value; setSearchQuery(searchedData); query.current.value = ""; }; useEffect(() => { if(searchQuery){ fetch(`https://lego-land-seven.vercel.app/search?name=${searchQuery}`) .then(res=>res.json()) .then(data=>setAllToys(data)) } fetch(`https://lego-land-seven.vercel.app/search`) .then(res=>res.json()) .then(data=>setAllToys(data)) } ,[searchQuery]) return ( <div className="px-10"> <DynamicTitle head={'All Toys'}></DynamicTitle> <div className="text-center"> <input type="text" placeholder="Type here" ref={query} className="input input-bordered w-full max-w-xs" /> <button onClick={searchHandler} className="btn btn-primary ml-8">Search</button> </div> <div> {allToys.map(toys => <TabularCard key={toys._id} toys={toys}/> )} </div> </div> ); }; export default AllToys;
class TodoModel { List<TodoModel>? todos; int? userId; int? id; String? title; bool? completed; TodoModel({this.todos, this.userId, this.id, this.title, this.completed}); TodoModel.fromJson(Map<String, dynamic> json) { userId = json['userId']; id = json['id']; title = json['title']; completed = json['completed']; // Parse the "todos" array and create a list of TodoModel objects if (json['todos'] is List) { todos = (json['todos'] as List<dynamic>) .map((todoJson) => TodoModel.fromJson(todoJson)) .toList(); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['userId'] = this.userId; data['id'] = this.id; data['title'] = this.title; data['completed'] = this.completed; // Serialize the "todos" list if it's not null if (this.todos != null) { data['todos'] = this.todos!.map((todo) => todo.toJson()).toList(); } return data; } }
/* * JPPF. * Copyright (C) 2005-2019 JPPF Team. * http://www.jppf.org * * 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 org.jppf.node.connection; import org.jppf.comm.discovery.*; import org.jppf.utils.*; import org.jppf.utils.configuration.JPPFProperties; import org.slf4j.*; /** * This implementation of {@link DriverConnectionStrategy} is the JPPF default * and produces DriverConnectionInfo instances based solely on the JPPF configuration. * @author Laurent Cohen * @since 4.1 */ public class JPPFDefaultConnectionStrategy implements DriverConnectionStrategy { /** * Logger for this class. */ private static Logger log = LoggerFactory.getLogger(JPPFDefaultConnectionStrategy.class); /** * The node configuration. */ private final TypedProperties config; /** * Create this connection strategy. */ public JPPFDefaultConnectionStrategy() { this(JPPFConfiguration.getProperties()); log.info("created {} with global config", getClass().getSimpleName()); } /** * Create this connection strategy. * @param config the node configuration. */ public JPPFDefaultConnectionStrategy(final TypedProperties config) { this.config = config; } @Override public DriverConnectionInfo nextConnectionInfo(final DriverConnectionInfo currentInfo, final ConnectionContext context) { return config.get(JPPFProperties.DISCOVERY_ENABLED) ? discoverDriver() : connectionFromManualConfiguration(); } /** * Automatically discover the server connection information using a datagram multicast. * Upon receiving the connection information, the JPPF configuration is modified to take into * account the discovered information. If no information could be received, the node relies on * the static information in the configuration file. * @return the discovered connection information. */ private DriverConnectionInfo discoverDriver() { final JPPFMulticastReceiver receiver = new JPPFMulticastReceiver(new IPFilter(config)); final JPPFConnectionInformation info = receiver.receive(); receiver.setStopped(true); if (info == null) { if (log.isDebugEnabled()) log.debug("Could not auto-discover the driver connection information"); return connectionFromManualConfiguration(); } if (log.isDebugEnabled()) log.debug("Discovered driver: " + info); final boolean ssl = config.get(JPPFProperties.SSL_ENABLED); final boolean recovery = config.get(JPPFProperties.RECOVERY_ENABLED); return JPPFDriverConnectionInfo.fromJPPFConnectionInformation(info, ssl, recovery); } /** * Determine the connection information specified manually in the configuration. * @return the configured connection information. */ private DriverConnectionInfo connectionFromManualConfiguration() { final boolean ssl = config.get(JPPFProperties.SSL_ENABLED); final String host = config.get(JPPFProperties.SERVER_HOST); final int port = config.get(ssl ? JPPFProperties.SERVER_SSL_PORT_NODE : JPPFProperties.SERVER_PORT); return new JPPFDriverConnectionInfo(ssl, host, port, config.get(JPPFProperties.RECOVERY_ENABLED)); } }
package es.yeffry.valorantapi.manager.network import com.google.gson.Gson import es.yeffry.valorantapi.manager.network.dto.ErrorBodyDTO import es.yeffry.valorantapi.domain.entities.CustomException import retrofit2.HttpException import retrofit2.Response import java.io.IOException import java.net.SocketTimeoutException import javax.inject.Inject class NetworkManager @Inject constructor() { suspend fun <T> load(call: suspend () -> Response<T>): Result<T?> { var serverResponse = ErrorBodyDTO("") return try { val response = call() if (response.isSuccessful) { Result.success(response.body()) } else { val gson = Gson() val errorBody = response.errorBody() val errorBodyDTO = if (errorBody != null) { gson.fromJson(errorBody.string(), ErrorBodyDTO::class.java) } else { ErrorBodyDTO("") } Result.failure(CustomException(errorBodyDTO.errorMessage)) } } catch (e: Exception) { val errorMessage = when (e) { is HttpException -> { val errorBody = e.response()?.errorBody() if (errorBody != null) { val gson = Gson() val errorBodyDTO = gson.fromJson(errorBody.string(), ErrorBodyDTO::class.java) errorBodyDTO.errorMessage } else { serverResponse.errorMessage } } is SocketTimeoutException -> "Timeout Error" is IOException -> "Thread Error" else -> "Unknown Error" } Result.failure(CustomException(errorMessage)) } } }
const nombre = document.getElementById('nombre'); const email = document.getElementById('email'); const contrasena = document.getElementById('contrasena'); const confirmarContrasena = document.getElementById('confirmarContrasena'); const edad = document.getElementById('edad'); const generoMasculino = document.getElementById('generoMasculino'); const generoFemenino = document.getElementById('generoFemenino'); const terminosCondiciones = document.getElementById('terminosCondiciones'); function mostrarError(idElemento, texto) { document.getElementById(idElemento).textContent = texto; } function limpiarErrores() { const eleFormulario = document.getElementById('registroForm'); let elementosError = Array.from(eleFormulario.getElementsByClassName('error')); elementosError.forEach(e => { e.textContent = ''; }); } document.getElementById('registroForm').addEventListener('submit', function(event) { event.preventDefault(); limpiarErrores(); // Validar nombre if (!nombre.checkValidity()) { mostrarError('errorNombre', "Por favor, ingresa tu nombre."); } // Validar email if (!email.checkValidity()) { mostrarError('errorEmail', "Ingresa una dirección de correo electrónico válida."); } // Validar contraseña if (!contrasena.checkValidity()) { mostrarError('errorContrasena', "La contraseña debe tener al menos 8 caracteres."); } // Confirmar contraseña if (contrasena.value !== confirmarContrasena.value) { mostrarError('errorConfirmarContrasena', "Las contraseñas no coinciden."); } // Validar edad if (!edad.checkValidity()) { mostrarError('errorEdad', "Debes tener al menos 18 años para registrarte."); } // Validar género if (!generoMasculino.checked && !generoFemenino.checked) { mostrarError('errorGenero', "Selecciona tu género."); } // Validar términos y condiciones if (!terminosCondiciones.checked) { mostrarError('errorTerminosCondiciones', "Debes aceptar los términos y condiciones."); } // Si no hay errores, enviamos el formulario if (this.checkValidity() && contrasena.value === confirmarContrasena.value) { alert('Registrado correctamente'); this.submit(); } });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>My Pie</title> <script src="./js/d3.min.js"></script> </head> <body> </body> <script> var width=600; var height=600; var svg=d3.select("body") .append("svg") .attr("width",width) .attr("height",height); // 1.确定初始数据 var dataset=[["小米",60.8],["三星",58.4],["联想",47.3],["苹果",46.6],["华为",41.3],["酷派",40.1],["其他",111.5]] // 2.转换数据 var pie=d3.layout.pie() //默认画一个0-2π的完整的圆,取消下面两句注释则画一个不完整的圆 //.startAngle(Math.PI*0.2) //.endAngle(Math.PI*1.5) .value(function(d){ return d[1]; }); //dataset是初始数据,piedata是转换后的数据 var piedata=pie(dataset); console.log(piedata); // 3.绘制 var outerRadius=width/3; var innerRadius=0;//内半经设为0则中间没有空白 //创建弧生成器 var arc=d3.svg.arc() .innerRadius(innerRadius) .outerRadius(outerRadius); //定义一个颜色比例尺 var color=d3.scale.category20() //在<svg>里添加几个<g>元素,每一个<g>用于包含一段弧 var arcs=svg.selectAll("g") .data(piedata) .enter() .append("g") .attr("transform","translate("+(width/2)+","+(height/2)+")");//平移到SVG画板中心 //上述代码返回一个<g>元素的选择集,<g>的数量与piedata的长度一致,选择集保存在变量arcs中。 //这样一来,只要用arcs.append()就可以同时为所有<g>添加元素 //添加弧的路径元素 arcs.append("path") .attr("fill",function(d,i){ //弧的颜色用颜色比例尺返回 return color(i); }) .attr("d",function(d){ //用前面定义的弧生成器生成路径值 return arc(d); }) //添加弧的文字元素 arcs.append("text") .attr("transform",function(d){ //arc.centroid方法返回弧中心坐标[x,y](注意,x和y的值是以圆心坐标为原点而言的) var x=arc.centroid(d)[0]*1.4;//文字的x坐标 var y= arc.centroid(d)[1]*1.4;//文字的y坐标 return "translate("+x+","+y+")" }) .attr("text-anchor","middle") .text(function(d){ //计算市场份额的百分比 var percent=Number(d.value)/d3.sum(dataset,function(d){return d[1];})*100; return percent.toFixed(1)+"%";//保留1位小数点,末尾加一个百分号返回 }); //添加连接弧外文字的直线元素 arcs.append("line") .attr("stroke","black") .attr("x1",function(d){ //arc.centroid方法返回弧中心坐标[x,y](注意,x和y的值是以圆心坐标为原点而言的) return arc.centroid(d)[0]*2; }) .attr("y1",function(d){ return arc.centroid(d)[1]*2; }) .attr("x2",function(d){ return arc.centroid(d)[0]*2.2; }) .attr("y2",function(d){ return arc.centroid(d)[1]*2.2; }) //添加弧外的文字元素 arcs.append("text") .attr("transform",function(d){ var x=arc.centroid(d)[0]*2.5; var y=arc.centroid(d)[1]*2.5; return "translate("+x+","+y+")"; }) .attr("text-anchor","middle") .text(function(d){ return d.data[0]; }); </script> </html>
import { useEffect, useState } from "react"; import ItemCard from "../itemCard/itemCard"; import styles from "./landingPageTrendingItems.module.css"; function fetchPlantsGallery() { return new Promise((resolve, reject) => { setTimeout(() => { resolve([ { id: 1, name: "A4 Card Stock", price: 1200 }, { id: 2, name: "A3 Card Stock", price: 800 }, { id: 3, name: "Apsara Pencil (pack of 12)", price: 650 }, { id: 4, name: "Camlin Stapler", price: 1450 }, { id: 5, name: "Camel Scented Erasers (Box of 3)", price: 1300 }, { id: 6, name: "A4 Card Stock", price: 1200 }, { id: 7, name: "A3 Card Stock", price: 800 }, { id: 8, name: "Apsara Pencil (pack of 12)", price: 650 }, { id: 9, name: "Camlin Stapler", price: 1450 }, { id: 10, name: "Camel Scented Erasers (Box of 3)", price: 1300 }, ]); }, 1000); }); } export default function TrendingItems() { const [items, setItems] = useState<any>([]); useEffect(() => { fetchPlantsGallery().then((items) => { setItems(items); }); }); return ( <div className={styles.wrapper}> <div className={styles.heading}>Trending items</div> <div className={styles.itemsGrid}> {items.map((item: any) => ( <ItemCard item={item} key={item.id} /> ))} </div> </div> ); }
import { DataImporter } from './DataImporter'; import { ImportHelper } from '../helper/ImportHelper'; import { Constants } from './Constants'; import { RangedParser } from '../parser/weapon/RangedParser'; import { MeleeParser } from '../parser/weapon/MeleeParser'; import { ThrownParser } from '../parser/weapon/ThrownParser'; import { ParserMap } from '../parser/ParserMap'; import { WeaponParserBase } from '../parser/weapon/WeaponParserBase'; import {DefaultValues} from "../../data/DataDefaults"; import WeaponItemData = Shadowrun.WeaponItemData; import {Helpers} from "../../helpers"; export class WeaponImporter extends DataImporter { public categoryTranslations: any; public itemTranslations: any; public files = ['weapons.xml']; CanParse(jsonObject: object): boolean { return jsonObject.hasOwnProperty('weapons') && jsonObject['weapons'].hasOwnProperty('weapon'); } GetDefaultData(): WeaponItemData { return { name: 'Unnamed Item', type: 'weapon', data: { description: { value: '', chat: '', source: '', }, action: DefaultValues.actionData({type: 'varies', attribute: 'agility'}), technology: DefaultValues.technologyData({rating: 1}), ammo: { spare_clips: { value: 0, max: 0, }, current: { value: 0, max: 0, }, }, range: { category: '', ranges: { short: 0, medium: 0, long: 0, extreme: 0, }, rc: { value: 0, base: 0, mod: [], }, modes: { single_shot: false, semi_auto: false, burst_fire: false, full_auto: false, }, }, melee: { reach: 0, }, thrown: { ranges: { short: 0, medium: 0, long: 0, extreme: 0, attribute: '', }, blast: { radius: 0, dropoff: 0, }, }, category: 'range', subcategory: '', }, }; } ExtractTranslation() { if (!DataImporter.jsoni18n) { return; } let jsonWeaponi18n = ImportHelper.ExtractDataFileTranslation(DataImporter.jsoni18n, this.files[0]); this.categoryTranslations = ImportHelper.ExtractCategoriesTranslation(jsonWeaponi18n); this.itemTranslations = ImportHelper.ExtractItemTranslation(jsonWeaponi18n, 'weapons', 'weapon'); } async Parse(jsonObject: object): Promise<Item> { const folders = await ImportHelper.MakeCategoryFolders(jsonObject, 'Weapons', this.categoryTranslations); folders['gear'] = await ImportHelper.GetFolderAtPath(`${Constants.ROOT_IMPORT_FOLDER_NAME}/Weapons/Gear`, true); folders['quality'] = await ImportHelper.GetFolderAtPath(`${Constants.ROOT_IMPORT_FOLDER_NAME}/Weapons/Quality`, true); const parser = new ParserMap<WeaponItemData>(WeaponParserBase.GetWeaponType, [ { key: 'range', value: new RangedParser() }, { key: 'melee', value: new MeleeParser() }, { key: 'thrown', value: new ThrownParser() }, ]); let datas: WeaponItemData[] = []; let jsonDatas = jsonObject['weapons']['weapon']; for (let i = 0; i < jsonDatas.length; i++) { let jsonData = jsonDatas[i]; if (DataImporter.unsupportedEntry(jsonData)) { continue; } let data = parser.Parse(jsonData, this.GetDefaultData(), this.itemTranslations); // @ts-ignore // TODO: Foundry Where is my foundry base data? data.folder = folders[data.data.subcategory].id; Helpers.injectActionTestsIntoChangeData(data.type, data, data); datas.push(data); } // @ts-ignore // TODO: TYPE: This should be removed after typing of SR5Item return await Item.create(datas); } }
package com.kindminds.drs.web.ctrl.amazon; import java.io.IOException; import java.util.List; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.kindminds.drs.api.usecase.report.amazon.ImportAmazonReturnReportUco; import com.kindminds.drs.service.util.SpringAppCtx; import com.kindminds.drs.util.JsonHelper; @Controller @PreAuthorize("hasAnyRole(T(com.kindminds.drs.service.util.AuthorityList).auth('AMAZON_RETURN_REPORT'))") public class AmazonReturnReportController { private ImportAmazonReturnReportUco getUco(){return (ImportAmazonReturnReportUco)(SpringAppCtx.get().getBean("importAmazonReturnReportUcoImpl"));} @RequestMapping(value = "/AmazonReturnReport") public String ListOfAmazonReturnReport(){ return "ListOfAmazonReturnReports"; } @RequestMapping(value="/AmazonReturnReport/uploadFile",method=RequestMethod.POST) public String uploadFile(@RequestParam("file") MultipartFile file,final RedirectAttributes redirectAttributes){ try { String originalFileName = file.getOriginalFilename(); byte[] fileBytes = file.getBytes(); String result = this.getUco().save(originalFileName, fileBytes); redirectAttributes.addFlashAttribute("message", result); } catch (IOException e) { e.printStackTrace(); } return "redirect:/AmazonReturnReport"; } @RequestMapping(value = "/AmazonReturnReport/listUploadedFiles", method = RequestMethod.GET) public @ResponseBody String listUploadedFiles(){ List<String> uploadedFiles = this.getUco().getFileList(); return JsonHelper.toJson(uploadedFiles); } @RequestMapping(value = "/AmazonReturnReport/importFile/{fileName:.*}") public String importUploadedFile(@PathVariable String fileName,final RedirectAttributes redirectAttributes){ String result = this.getUco().importFile(fileName); redirectAttributes.addFlashAttribute("message", result); return "redirect:/AmazonReturnReport"; } @RequestMapping(value = "/AmazonReturnReport/deleteUploadedFile/{fileName:.*}") public String deleteUploadedFile(@PathVariable String fileName,final RedirectAttributes redirectAttributes){ String result = this.getUco().delete(fileName); redirectAttributes.addFlashAttribute("message", result); return "redirect:/AmazonReturnReport"; } }
#!/usr/bin/perl # Copyright (C) 2014-2018 Mikhael Goikhman <[email protected]> use strict; use warnings; use sigtrap qw(die untrapped normal-signals stack-trace any error-signals); use Getopt::Long qw(:config no_ignore_case bundling); use POSIX qw(strftime); use FindBin; use lib "$FindBin::Bin/../lib"; use SMB::Client; my $quiet = 0; my $verbose = 0; my $username = undef; my $force_anon = 0; my $disable_anon = 0; sub show_usage (;$) { my $is_error = shift || 0; my $out = $is_error ? \*STDERR : \*STDOUT; my $usage = qq{ Usage: $0 [OPTIONS] //server/share Start a simple SMB client Options: -h --help show this usage -q --quiet do not show any errors -v --verbose print more messages (multiple) -U --username u[%p] SMB username and password (prompted if absent) -a --force-anon disable user logon even if anonymous logon failed -A --disable-anon disable anonymous logon if no username }; $usage =~ s/^\n//; $usage =~ s/^\t\t?//mg; print $out $usage; exit $is_error; } GetOptions( 'h|help' => sub { show_usage(0) }, 'q|quiet+' => \$quiet, 'v|verbose+' => \$verbose, 'U|username=s' => \$username, 'a|force-anon' => \$force_anon, 'A|disable-anon' => \$disable_anon, ) or show_usage(1); my $share_uri = shift || '//localhost/users'; use Term::ReadLine; my $term = Term::ReadLine->new('smb-client'); $term->MinLine(undef); # no autohistory my $OUT = $term->OUT || \*STDOUT; my $history_filename = '.smb-client-history'; eval { $term->ReadHistory($history_filename) }; END { eval { $term->WriteHistory($history_filename) }; } $Term::ReadLine::Gnu::Attribs{term_set} = [ "\033[1;36m", "\033[m", "\033[1;31m", "\033[m" ] if %Term::ReadLine::Gnu::Attribs; @Term::ReadLine::TermCap::rl_term_set = ("\033[1;36m", "\033[m", "\033[1;31m", "\033[m") if @Term::ReadLine::TermCap::rl_term_set; warn "# Consider to install perl(Term::ReadLine::Gnu) to get history.\n" if $verbose && !%Term::ReadLine::Gnu::Attribs; $SIG{INT} = sub { die "Terminated by user\n"; }; my @args; sub prompt ($;$$) { my $message = shift; my $n_args = shift || 0; my $is_secret = shift; return shift @args if @args; $message .= ': ' unless $message =~ /[:>.]\s*$/; my $answer = $term->readline($message, ''); print $OUT "\n"; return unless defined $answer; $answer =~ s/^\s+|\s+$//g; $answer =~ s/\s+/ /g; $term->addhistory($answer) if $answer ne '' && !$is_secret; my @words = split(' ', $answer); if (@words > 1) { $answer = shift @words; push @args, shift @words while @words && $n_args--; warn "Extraneous words in input (@words) skipped\n" if @words; } return $answer; } my $client = undef; my $password = undef; $password = $1 if defined $username && $username =~ s/%(.*)$//; if ($force_anon || !defined $username && !$disable_anon) { print "Connecting to $share_uri as anonymous user\n"; $client = SMB::Client->new( $share_uri, use_anon => 1, username => $username, password => $password, quiet => $quiet, verbose => $verbose, log_level => SMB::LOG_LEVEL_INFO, ); goto CONNECTED if $client->check_session; die "Anonymous logon failed, skipping normal logon as requested\n" if $force_anon; } $username //= $ENV{USER} || $ENV{LOGNAME} || die "Please specify username to connect\n"; $password //= prompt("Enter password as user '$username'", 0, 1); print "Connecting to $share_uri with user '$username'\n"; $client = SMB::Client->new( $share_uri, username => $username, password => $password, quiet => $quiet, verbose => $verbose, log_level => SMB::LOG_LEVEL_INFO, ); CONNECTED: my $tree = $client->connect_tree or die "Failed to connect to $share_uri, aborting\n"; sub check_tree() { return 1 if $tree; print "No current working tree\n"; return 0; } sub format_cwd () { my $connection = $client->get_curr_connection || return "[not-connected]"; my $addr = $connection->addr; my $path = $tree ? "/" . $tree->share . $tree->cwd : '[no-tree-connected]'; $path = substr($path, 0, 48) . ".." if length($path) > 50; return "$addr$path"; } my %commands = ( status => sub { while (my ($addr, $connection) = each %{$client->connections}) { print "Connection $addr\n"; for my $tree ($connection->tree) { print "\tShare $tree->{share}\n"; } } }, cd => sub { return unless check_tree(); $tree->chdir(prompt("Directory to change to")); }, dir => sub { return unless check_tree(); for my $file (@{$tree->find(@args ? shift @args : '*') || []}) { printf "%-40s %9s %s\n", $file->name, $file->size_string, $file->mtime_string; } }, get => sub { return unless check_tree(); $tree->dnload(prompt("File to download"), shift @args); }, put => sub { return unless check_tree(); $tree->upload(prompt("File to upload"), shift @args); }, del => sub { return unless check_tree(); my $recursive = @args && $args[0] eq '-r' && shift @args && 1; $tree->remove({ recursive => $recursive }, prompt("File to remove")); }, rmdir => sub { return unless check_tree(); my $recursive = @args && $args[0] eq '-r' && shift @args && 1; $tree->remove({ recursive => $recursive }, prompt("Dir to remove"), 1); }, rename => sub { return unless check_tree(); my $force = @args && $args[0] eq '-f' && shift @args && 1; $tree->rename({ force => $force }, prompt("File to rename"), prompt("New file name")); }, copy => sub { return unless check_tree(); $tree->copy(prompt("File to copy"), prompt("New file name")); }, help => sub { my $help = qq{ Operations available: connect ADDR connect to server, ADDR is host[:port] disconnect disconnect from the current server tree-connect connect to share, argument syntax //host[:port]/share tree-disconn disconnect from the current share status show connections and shares switch [IDX] change the current tree or connection (see "status") cd DIR change working directory dir [MASK] list all or matching files get SRC [DST] download remote file SRC from server put SRC [DST] upload local file SRC file to server del [-r] FILE remove file rmdir [-r] D remove dir (use -r to remove recursively) rename F1 F2 rename file (add -f to force) copy F1 F2 copy file quit exit the client (close all connections) }; $help =~ s/^\n//; $help =~ s/^\t{2}\t?//mg; print $help; }, ); my %aliases = ( chdir => 'cd', find => 'dir', download => 'get', upload => 'put', rm => 'del', remove => 'del', mv => 'rename', move => 'rename', cp => 'copy', exit => 'quit', ); print "Connected to $share_uri. Enter 'help' to list commands.\n"; while (1) { my $dir = format_cwd(); my $cmd = prompt("smb:$dir> ", 3) // last; $cmd = $aliases{$cmd} if $aliases{$cmd}; last if $cmd eq 'quit'; my $func = $commands{$cmd}; if ($func) { $func->(); } else { print "Invalid command '$cmd', try 'help'\n"; } @args = (); # forget unconsumed args }
#include "global.h" #include "config.h" #include "recording.h" #include "processing.h" #include "playing.h" #include "base64_wrapper.h" #include "other.h" #include "Google_Wrapper.h" bool initSDCard() { Serial.print("Initializing SD card.......... "); if (!SD.begin(CHIPSELECTPIN)) { return false; } if (SD.exists(samplesRecordedFilePath)) {SD.remove(samplesRecordedFilePath);} if (SD.exists(samplesRecordedFilePath_base64)) {SD.remove(samplesRecordedFilePath_base64);} if (SD.exists(samplesGoogleFilePath)) {SD.remove(samplesGoogleFilePath);} if (SD.exists(samplesGoogleFilePath_base64)) {SD.remove(samplesGoogleFilePath_base64);} if (SD.exists(jsonCallFilePath)) {SD.remove(jsonCallFilePath);} if (SD.exists(jsonResponseFilePath)) {SD.remove(jsonResponseFilePath);} return true; } bool connectToWiFi() { Serial.print("Connecting to Wi-Fi........... "); WiFi.begin(SSID, PASSWORD); unsigned long startTime = millis(); while (WiFi.status() != WL_CONNECTED) { if (millis() - startTime > 20000) { // Timeout after 20 seconds return false; } delay(1000); } return true; } bool i2s_mic_install() { Serial.print("Installing I2S (Mic) ......... "); const i2s_config_t i2s_config = { .mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX), .sample_rate = SAMPLE_RATE * 8, //after averaging and considering processor timing, 64200 I2S sample rate is aprx 8000hz .bits_per_sample = i2s_bits_per_sample_t(16), .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S), .intr_alloc_flags = 0, .dma_buf_count = 128, .dma_buf_len = BUFFERLEN, .use_apll = false }; esp_err_t i2s_install_status = i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL); const i2s_pin_config_t pin_config = { .bck_io_num = I2S_SCK, .ws_io_num = I2S_WS, .data_out_num = -1, .data_in_num = I2S_SD }; esp_err_t i2s_pin_status = i2s_set_pin(I2S_NUM_0, &pin_config); i2s_start(I2S_NUM_0); //moved here, it was outside before if (i2s_install_status == ESP_OK && i2s_pin_status == ESP_OK){ Serial.println("Success!"); return true; } } bool i2s_speaker_install() { Serial.print("Installing I2S (Speaker) ..... "); i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX), .sample_rate = SAMPLE_RATE, .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, // Change to ONLY_LEFT .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB), .intr_alloc_flags = 0, .dma_buf_count = 4, .dma_buf_len = 512, .use_apll = false }; esp_err_t i2s_install_status = i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL); i2s_pin_config_t pin_config = { .bck_io_num = 11,//bclkPin, .ws_io_num = 12,//wclkPin, .data_out_num = 10,//dataPin, .data_in_num = I2S_PIN_NO_CHANGE}; esp_err_t i2s_pin_status = i2s_set_pin(I2S_NUM_0, &pin_config); i2s_set_sample_rates(I2S_NUM_0, SAMPLE_RATE); if (i2s_install_status == ESP_OK && i2s_pin_status == ESP_OK){ Serial.println("Success!"); return true; } } // ------------------------------------------------------- bool start(){ if (!initSDCard()) { Serial.println("Failed. Exiting..."); return false; } Serial.println("Success!"); if (!connectToWiFi()) { Serial.println("Failed. Exiting..."); return false; } Serial.println("Success!"); return true; }
using AutoMapper; using Library.API.Infrastructure; using Library.API.Repositories; using Library.API.Services.Exceptions; // using Library.API.Repositories.Exceptions; namespace Library.API.Services; public class LibraryService : ILibraryService { private ILibraryRepository repository; private ILogger logger; private IMapper mapper; public LibraryService(IMapper mapper, LibraryContext context) { repository = RepositoryFactory.Create().CreateLibraryRepository(context); this.mapper = mapper; using ILoggerFactory factory = LoggerFactory.Create(builder => builder.AddConsole()); logger = factory.CreateLogger("LibraryService"); } public IList<BookEditionDTO> GetAllBooks() { IList<BookEditionDTO>? result = null; try { var bookEditions = repository.GetAllBooks(); result = mapper.Map<List<BookEditionDTO>>(bookEditions); } catch (Exception e) { logger.LogWarning(e.ToString()); throw new LibraryServiceException(e.ToString(), e); } return result; } public IList<BookInstanceDTO> GetAllBookInstances() { IList<BookInstanceDTO>? result = null; try { var bookInstances = repository.GetAllBookInstances(); result = mapper.Map<List<BookInstanceDTO>>(bookInstances); } catch (Exception e) { logger.LogWarning(e.ToString()); throw new LibraryServiceException(e.ToString(), e); } return result; } public async Task<BookInstanceDTO?> GetBookInstanceById(int id) { if (id <= 0) return null; BookInstanceDTO? result; try { var bookInstance = await repository.GetBookInstanceById(id); result = mapper.Map<BookInstanceDTO>(bookInstance); } catch (Exception e) { logger.LogWarning(e.ToString()); throw new LibraryServiceException(e.ToString(), e); } return result; } public async Task<BookEditionDTO?> GetBookByISBN(string isbn) { if (!IsISBNValid(isbn)) return null; BookEditionDTO? result; try { var bookEdition = await repository.GetBookByISBN(isbn); result = mapper.Map<BookEditionDTO>(bookEdition); } catch (Exception e) { logger.LogWarning(e.ToString()); throw new LibraryServiceException($"Error in getting book by ISBN -> {isbn}", e); } return result; } public async Task<LibraryServiceResponse> AddBookEdition(BookEditionDTO bookEditionDTO) { if (!IsISBNValid(bookEditionDTO.ISBN)) return new LibraryServiceResponse("Invalid ISBN", false); var response = new LibraryServiceResponse( $"BookEdition with ISBN {bookEditionDTO.ISBN} added to database", true ); try { var isEditionAlreadyCreated = await GetBookByISBN(bookEditionDTO.ISBN) != null; if (!isEditionAlreadyCreated) { var edition = mapper.Map<BookEdition>(bookEditionDTO); var isAdded = await repository.AddBookEdition(edition); if (!isAdded) { response = new LibraryServiceResponse( $"Unable to add book edition isbn -> {edition.ISBN}", false ); } } else response = new LibraryServiceResponse( $"Book with such ISBN -> {bookEditionDTO.ISBN} already in database", false ); } catch (Exception e) { logger.LogWarning(e.ToString()); throw new LibraryServiceException($"Error while adding book with {bookEditionDTO.ISBN}", e); } return response; } public async Task<LibraryServiceResponse> AddBookInstances(string isbn, int amount) { if (!IsISBNValid(isbn)) return new LibraryServiceResponse("Invalid ISBN", false); if (amount < 0 || amount > 100) return new LibraryServiceResponse("Incorrect amount. Amount is [1, 100]"); var result = new LibraryServiceResponse( $"Added new book instances for {isbn} in {amount} copies", true ); var edition = await repository.GetBookByISBN(isbn); bool isAdded = false; if (edition != null) { var instances = new BookInstance[amount]; for (int i = 0; i < amount; i++) instances[i] = new BookInstance(edition); isAdded = await repository.AddBookInstances(instances); if (!isAdded) { result = new LibraryServiceResponse( $"Unable to add instances for isbn -> {isbn}, check if it exists", false ); } } return result; } public async Task<LibraryServiceResponse> DeleteBookEdition(string isbn) { if (!IsISBNValid(isbn)) return new LibraryServiceResponse("Invalid ISBN", false); try { bool isDeleted = await repository.DeleteBookEdition(isbn); if (!isDeleted) return new LibraryServiceResponse($"Not found edition with isbn -> {isbn}", false); } catch (Exception e) { logger.LogWarning(e.ToString()); throw new LibraryServiceException(e.ToString(), e); } return new LibraryServiceResponse($"Successfull deletion of book edition {isbn}", true); } public async Task<LibraryServiceResponse> DeleteBookInstance(int id) { if (id <= 0) return new LibraryServiceResponse("Id < 0", false); try { bool isDeleted = await repository.DeleteBookInstance(id); if (!isDeleted) return new LibraryServiceResponse($"Instance with id -> {id} not founded", false); } catch (Exception e) { logger.LogWarning(e.ToString()); throw new LibraryServiceException(e.ToString(), e); } return new LibraryServiceResponse($"Successfull deletion of book instance with id {id}", true); } public async Task<LibraryServiceResponse> UpdateBookEdition( string isbn, BookEditionDTO newInfoDTO ) { if (!IsISBNValid(isbn)) return new LibraryServiceResponse($"Invalid ISBN {isbn}", false); if (!IsISBNValid(newInfoDTO.ISBN)) return new LibraryServiceResponse( $"Invalid ISBN of BookEdition update info {newInfoDTO.ISBN}", false ); var response = new LibraryServiceResponse($"Book Edition has been updated", true); try { var newInfo = mapper.Map<BookEdition>(newInfoDTO); bool isUpdated = await repository.UpdateBookEdition(isbn, newInfo); if (!isUpdated) response = new LibraryServiceResponse( $"Book edition {isbn} not found, update impossible", false ); } catch (Exception e) { logger.LogWarning(e.ToString()); throw new LibraryServiceException(e.ToString(), e); } return response; } public async Task<LibraryServiceResponse> UpdateBookInstance(int id, BookInstanceDTO newInfoDTO) { if (id <= 0) return new LibraryServiceResponse("Id < 0", false); if (!IsISBNValid(newInfoDTO.ISBN)) return new LibraryServiceResponse( $"Invalid ISBN of Book instance update info: {newInfoDTO.ISBN}", false ); LibraryServiceResponse response = new LibraryServiceResponse( $"New inforamtion for book instance with id -> {id} successfully loaded", true ); try { var newInfo = mapper.Map<BookInstance>(newInfoDTO); var isUpdated = await repository.UpdateBookInstance(id, newInfo); if (!isUpdated) response = new LibraryServiceResponse( $"Unable to update book with id -> {id}, try to check if this book exists", false ); } catch (Exception e) { logger.LogWarning(e.ToString()); throw new LibraryServiceException(e.ToString(), e); } return response; } private bool IsISBNValid(string isbn) { const string pattern = @"^(?=(?:\D*\d){10}(?:(?:\D*\d){3})?$)[\d-]+$"; return System.Text.RegularExpressions.Regex.IsMatch(isbn, pattern); } }
package com.example.GameStopGradsProject.apiintegrationtest.delete; import com.example.GameStopGradsProject.model.User; import com.example.GameStopGradsProject.repository.UserRepository; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.Optional; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class DeleteUserApiIntegrationTest { @MockBean private UserRepository userRepository; @Autowired private MockMvc mockMvc; @Autowired private DataSource dataSource; @AfterAll public void teardown() throws SQLException { Connection connection = dataSource.getConnection(); connection.close(); } @Test @DisplayName(""" If the following endpoint DELETE /users/deletion/{id} is called and the id exists in the user table, then the HTTP response should be 200 OK. """) @WithMockUser(username = "anything", password = "anything") void Test1() throws Exception { long id = 1; when(userRepository.findUserById(id)).thenReturn(Optional.of(new User())); mockMvc.perform(delete("/users/deletion/" + id)) .andExpect(status().isOk()); } @Test @DisplayName(""" If the following endpoint DELETE /users/deletion/{id} is called and the id does not exist in the user table, then the HTTP response should be 404 NOT FOUND. """) @WithMockUser(username = "anything", password = "anything") void Test2() throws Exception { long id = 1; when(userRepository.findUserById(id)).thenReturn(Optional.empty()); mockMvc.perform(delete("/users/deletion/" + id)) .andExpect(status().isNotFound()); } }
{- | Module : Header Description : Generate or read a header of a command packet Copyright : (c) Frédéric BISSON, 2015 License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : POSIX Generate or read a header of a command packet. -} module Network.NecControl.Header ( Equipment (Monitor, Group, AllEquipment, Controller) , MessageType ( Command, CommandReply, GetParameter, GetParameterReply , SetParameter, SetParameterReply ) , Header (Header, hdrDestination, hdrSource, hdrMsgType, hdrMsgLength) , updateLength ) where import Data.Char (ord, chr) import Data.Word (Word8) import Control.Monad (when) import Network.NecControl.NecProtocol (NecValue, toNec, fromNec) import Network.NecControl.PacketStructure (PacketStructure (StartOfHeader, Reserved0)) {-| An `Equipment` designates a monitor, a group of monitors or a controller. It is used to either specify a receiver or a sender of a command packet. -} data Equipment = Monitor Int | Group Char | AllEquipment | Controller deriving (Eq, Show) instance NecValue Equipment where toNec AllEquipment = [0x2a] toNec (Monitor i) | i < 1 || i > 100 = error "Wrong monitor ID" | otherwise = [0x40 + fromIntegral i] toNec (Group c) | c < 'A' || c > 'J' = error "Wrong group ID" | otherwise = [0x31 + fromIntegral (ord c - ord 'A')] toNec Controller = [0x30] fromNec [0x2a] = Right AllEquipment fromNec [0x30] = Right Controller fromNec [x] | x >= 0x41 && x <= 0xa4 = Right (Monitor (fromIntegral x - 0x41)) | x >= 0x31 && x <= 0x3a = Right (Group (chr (fromIntegral x - 0x31 + ord 'A'))) | otherwise = Left "Invalid equipment" fromNec _ = Left "Invalid equipment" {-| A `MessageType` specifies the type of the `Message` included in a `CommandPacket`. -} data MessageType = Command | CommandReply | GetParameter | GetParameterReply | SetParameter | SetParameterReply deriving (Eq, Show) instance NecValue MessageType where toNec Command = [0x41] toNec CommandReply = [0x42] toNec GetParameter = [0x43] toNec GetParameterReply = [0x44] toNec SetParameter = [0x45] toNec SetParameterReply = [0x46] fromNec [0x41] = Right Command fromNec [0x42] = Right CommandReply fromNec [0x43] = Right GetParameter fromNec [0x44] = Right GetParameterReply fromNec [0x45] = Right SetParameter fromNec [0x46] = Right SetParameterReply fromNec _ = Left "Invalid message type" {-| A `Header` is the first part of a `CommandPacket`. -} data Header = Header { hdrDestination :: Equipment -- ^ Receiver of the packet , hdrSource :: Equipment -- ^ Sender of the packet , hdrMsgType :: MessageType -- ^ Message type , hdrMsgLength :: Word8 -- ^ Message length } deriving (Eq, Show) {-| Update the length of a `Header`. -} updateLength :: Header -> Int -> Header updateLength header lgth = header { hdrMsgLength = fromIntegral lgth } instance NecValue Header where toNec (Header destination source msgType msgLength) = concat [ toNec StartOfHeader , toNec Reserved0 , toNec destination , toNec source , toNec msgType , toNec msgLength ] fromNec [soh, resv0, destination, source, msgType, h1, h0] = do soh' <- fromNec [soh] resv0' <- fromNec [resv0] destination' <- fromNec [destination] source' <- fromNec [source] msgType' <- fromNec [msgType] msgLength <- fromNec [h1, h0] when (soh' /= StartOfHeader) (Left "Invalid start of header") when (resv0' /= Reserved0) (Left "Invalid reserved 0") return $ Header destination' source' msgType' msgLength fromNec _ = Left "Wrong header size"
package com.github.hehecoi222.week5slidesimplstoredata.repository.datasources import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.github.hehecoi222.week5slidesimplstoredata.domain.entities.SimpleEntity import com.github.hehecoi222.week5slidesimplstoredata.domain.repository.SimpleDAO @Database(entities = [SimpleEntity::class], version = 1) abstract class RoomAccessDatabase : RoomDatabase() { abstract fun simpleDAO(): SimpleDAO companion object { @Volatile private var INSTANCE: RoomAccessDatabase? = null fun getDatabase(context: Context): RoomAccessDatabase { return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, RoomAccessDatabase::class.java, "simple_database" ).build() INSTANCE = instance instance } } } }
<template> <div> <page-header :title="`${$metaInfo.title}`" :items="[ {text: $metaInfo.title, active: true}, ]" /> <div class="card"> <div class="card-body"> <div class="d-flex justify-content-end mb-4"> <div> <b-button variant="outline-success" :to="{ name: 'str.create' }"> <b-icon icon="plus"></b-icon> Tambah STR </b-button> </div> </div> <b-row class="my-1"> <b-col sm="6"> <div class="d-flex align-items-center mb-3"> <div class="mr-4 text-nowrap">Cari STR</div> <b-form-input class="w-100" v-model="ctx.filter" placeholder="Masukan Nomor STR"> </b-form-input> </div> </b-col> </b-row> <b-table hover responsive id="str-table" ref="table" :items="itemsProvider" :current-page="ctx.currentPage" :per-page="ctx.perPage" :filter="ctx.filter" :busy="isBusy" :sortBy="ctx.sortBy" :sortDesc="ctx.sortDesc" :fields="fields"> <template #cell(nama_pegawai)="row"> <span>{{ row.item.nama_pegawai || '-' }}</span> </template> <template #cell(nomor_str)="row"> <span>{{ row.item.nomor_str || '-' }}</span> </template> <template #cell(tanggal_kadaluarsa_str)="row"> <span>{{ row.item.tanggal_kadaluarsa_str || '-' }}</span> </template> <template #cell(status)="row"> <span class="badge badge-pill badge-success" v-if="row.item.status === 1">Active</span> <span class="badge badge-pill badge-danger" v-if="row.item.status === 0">Inactive</span> </template> <!-- <template #cell(image)="row"> <span>{{ row.item.image || '-' }}</span> </template> --> <template #cell(actions)="row"> <nuxt-link :to="{ name: 'str.edit', params: { id: row.item.str_id }}" class="mr-2"> <b-button variant="outline-primary"> <b-icon icon="pencil"></b-icon> Edit </b-button> </nuxt-link> <a @click="promptDelete(row.item)" style="cursor: pointer; color: red"> <b-button variant="outline-danger"> <b-icon icon="trash"></b-icon>Delete </b-button> </a> <nuxt-link :to="{ name: 'str.detail', params: { id: row.item.str_id }}" class="mr-2"> <b-button variant="info"> <b-icon icon="zoom-in"></b-icon>Detail </b-button> </nuxt-link> </template> </b-table> <b-row> <b-col sm="6"> <b-pagination v-model="ctx.currentPage" :total-rows="str_count" :per-page="ctx.perPage" aria-controls="str-table"> </b-pagination> </b-col> <b-col sm="6" class="d-flex justify-content-end"> <span class="font-size">Total Data : {{ str_count }}</span> </b-col> </b-row> </div> </div> </div> </template> <script> import axios from 'axios' import Swal from 'sweetalert2' import { buildQueryParams } from '~/plugins/utils' export default { // middleware: ['auth', 'check-permission'], middleware: ['auth'], head() { return { title: 'STR' } }, async asyncData() { if (window.tablectxstr) { var ctx = window.tablectxstr } else { var ctx = { currentPage: 1, perPage: 20, filter: '', sortBy: 'nama_pegawai', sortDesc: false } } let f1resp = (await axios.get('/str?' + buildQueryParams(ctx))).data let str = f1resp.data let str_count = f1resp.count return { str, str_count, ctx, } }, data: () => ({ fields: [ { key: 'nama_pegawai', label: 'Nama Pegawai', sortable: true, sortDirection: 'asc' }, { key: 'nomor_str', label: 'Nomor STR', sortable: false, sortDirection: 'asc' }, { key: 'tanggal_kadaluarsa_str', label: 'Tanggal Kadaluarsa', sortable: false, sortDirection: 'asc' }, // { key: 'image', label: 'Image', sortable: false, sortDirection: 'asc' }, { key: 'status', label: 'Status', sortable: false, sortDirection: 'asc' }, { key: 'actions', label: 'Actions' } ], isTableInit: false, isBusy: false }), created: function () { }, watch: { }, methods: { async itemsProvider(ctx) { if (!this.isTableInit) { this.isTableInit = true return this.str } ctx.params = this.ctx.params this.isBusy = true try { window.tablectxstr = ctx const response = await axios.get('/str?' + buildQueryParams(ctx)) this.isBusy = false this.str_count = response.data.count return response.data.data } catch (error) { this.isBusy = false return [] } }, async promptDelete(item) { Swal.fire({ title: 'Apakah Anda yakin hendak menghapus ' + item.nomor_str + '?', showDenyButton: true, confirmButtonText: `Hapus`, denyButtonText: `Batal`, }).then(async (result) => { /* Read more about isConfirmed, isDenied below */ if (result.isConfirmed) { const response = await axios.delete(`/str/${item.str_id}`) Swal.fire({ icon: 'success', title: 'Berhasil', text: 'Data berhasil dihapus', confirmButtonText: 'Ok', }) this.$refs.table.refresh() } }) }, refreshTable() { this.$refs.table.refresh() } } } </script> <style> .font-size { font-size: 1rem; } </style>
import { join } from "path"; import { Configuration, Inject } from "@tsed/di"; import { PlatformApplication } from "@tsed/common"; import "@tsed/platform-express"; // /!\ keep this import import "@tsed/ajv"; import "@tsed/swagger"; import { config } from "./config/index"; import * as rest from "./controllers/rest/index"; import * as pages from "./controllers/pages/index"; import { Env } from "@tsed/core"; export const rootDir = __dirname; export const isProduction = process.env.NODE_ENV === Env.PROD; @Configuration({ ...config, acceptMimes: ["application/json", "text/html", "text/plain"], httpPort: process.env.PORT || 8083, httpsPort: false, // CHANGE in PROD disableComponentsScan: true, neo: { url: process.env.NEO_URL, username: process.env.NEO_USERNAME, password: process.env.NEO_PASSWORD, }, mount: { "/api": [...Object.values(rest)], "/": [...Object.values(pages)], }, swagger: [ { path: "/doc", specVersion: "3.0.1", outFile: `${rootDir}/out/swagger.json`, // showExplorer: true, // display search bar }, ], middlewares: [ "cors", "cookie-parser", "compression", "method-override", "json-parser", { use: "urlencoded-parser", options: { extended: true } }, ], views: { root: join(`${rootDir}/views`), extensions: { ejs: "ejs", }, }, exclude: ["**/*.spec.ts"], logger: { disableRoutesSummary: isProduction, // remove table with routes summary }, }) export class Server { @Inject() protected app: PlatformApplication; @Configuration() protected settings: Configuration; }
import React, { useState } from 'react'; import { Col, Row, InputGroup, FormControl, Button, Alert } from 'react-bootstrap'; import ToggleButton from 'react-bootstrap/ToggleButton'; function Generator() { const [password, setPassword] = useState(''); const [lowercase, setLowercase] = useState(true); const [uppercase, setUppercase] = useState(true); const [numbers, setNumbers] = useState(true); const [symbols, setSymbols] = useState(true); const [length, setLength] = useState(8); const [copied, setCopied] = useState(false); const generatePassword = () => { let characterList = ''; let generatedPassword = ''; if (lowercase) { characterList += 'abcdefghijklmnopqrstuvwxyz'; } if (uppercase) { characterList += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; } if (numbers) { characterList += '0123456789'; } if (symbols) { characterList += '!@#$%^&*()_+~`|}{[]\:;?><,./-='; } for (let i = 0; i < length; i++) { const characterIndex = Math.round(Math.random() * characterList.length); generatedPassword += characterList.charAt(characterIndex); } setPassword(generatedPassword); }; const handleCopy = () => { navigator.clipboard.writeText(password); setCopied(true); }; return ( <div className="generator"> <Row> <Col> <h1>Password Generator</h1> </Col> </Row> <div className="settings"> <Row> <Col> <label>Password Length</label> <InputGroup> <FormControl type="number" value={length} onChange={(e) => setLength(e.target.value)} /> </InputGroup> </Col> </Row> <Row> <Col> <label>Include Lowercase</label> <ToggleButton className="mb-2" id="toggle-check-lowercase" type="checkbox" variant="outline-primary" checked={lowercase} onChange={() => setLowercase(!lowercase)} > </ToggleButton> </Col> </Row> <Row> <Col> <label>Include Uppercase</label> <ToggleButton className="mb-2" id="toggle-check-uppercase" type="checkbox" variant="outline-primary" checked={uppercase} onChange={() => setUppercase(!uppercase)} > </ToggleButton> </Col> </Row> <Row> <Col> <label>Include Numbers</label> <ToggleButton className="mb-2" id="toggle-check-numbers" type="checkbox" variant="outline-primary" checked={numbers} onChange={() => setNumbers(!numbers)} > </ToggleButton> </Col> </Row> <Row> <Col> <label>Include Symbols</label> <ToggleButton className="mb-2" id="toggle-check-symbols" type="checkbox" variant="outline-primary" checked={symbols} onChange={() => setSymbols(!symbols)} > </ToggleButton> </Col> </Row> <Row> <Col> <Button variant="primary" onClick={generatePassword}> Generate Password </Button> </Col> </Row> <div className="password"> {password && copied && ( <Alert variant="dark" onClose={() => setCopied(false)} dismissible> Password copied </Alert> )} <Row> <Col> <InputGroup> <FormControl type="text" value={password} readOnly/> <Button onClick={handleCopy}>Copy</Button> </InputGroup> </Col> </Row> </div> </div> </div> ); } export default Generator;
import os from google.oauth2 import credentials from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from googleapiclient.discovery import build import asyncio, json, string, re from concurrent.futures import ThreadPoolExecutor import sqlite3 import datetime import email.utils # connect to sqlite database conn = sqlite3.connect('email_db.sqlite') cursor = conn.cursor() # database table structue cursor.execute(''' CREATE TABLE IF NOT EXISTS email_details ( id INTEGER PRIMARY KEY AUTOINCREMENT, emailid VARCHAR, subject TEXT, sender TEXT, receiver TEXT, date TIMESTAMP, message TEXT )''' ) conn.commit() # Gmail Scopes SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.modify', 'https://www.googleapis.com/auth/gmail.labels'] # Creds Json CLIENT_SECRET_FILE = 'credentials.json' # sanitize email for security purpose async def sanitize_emails(content): # removing the ascii and non printables sanitized_content = ''.join(filter(lambda x: x in string.printable, content)) sanitized_content = re.sub(r'[;<>&]', '', sanitized_content) return sanitized_content # save email in to db async def insert_email(email_id, subject, sender, receiver, date, message): try: query = ''' INSERT INTO email_details (emailid, subject, sender, receiver, date, message) VALUES (?, ?, ?, ?, ?, ?) ''' cursor.execute(query, (email_id, subject, sender, receiver, date, message)) conn.commit() except Exception as e: print("error inserting emails", str(e)) # logic for fetching email's async def fetch_emails(msg_id, creds): try: service = build('gmail', 'v1', credentials=creds) def get_email_details(): msg = service.users().messages().get(userId='me', id=msg_id, format='full').execute() headers = msg['payload']['headers'] subject = [header['value'] for header in headers if header['name'] == 'Subject'][0] sender = [header['value'] for header in headers if header['name'] == 'From'][0] receiver = [header['value'] for header in headers if header['name'] == 'To'][0] date = [header['value'] for header in headers if header['name'] == 'Date'][0] formatted_date = email.utils.parsedate_to_datetime(date) email_date = formatted_date.strftime("%Y-%m-%d %H:%M:%S") message_body = msg['snippet'] email_id = msg['id'] respone_json = { "email_id": email_id, "sender": sender, "receiver": receiver, "date": email_date, "subject": subject, "message": message_body } return respone_json with ThreadPoolExecutor() as executor: response = await asyncio.get_event_loop().run_in_executor( executor, get_email_details) sanitized_email = await sanitize_emails(response['message']) email_resp = await insert_email(response['email_id'], response['subject'], response['sender'], response['receiver'], response['date'], sanitized_email) except Exception as e: print(f"Error fetching email details: {str(e)}") async def main(): # Authenticate the Gmail creds = None if os.path.exists('token.json'): creds = credentials.Credentials.from_authorized_user_file('token.json', SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES) creds = flow.run_local_server(port=0) with open('token.json', 'w') as token: token.write(creds.to_json()) # gmail api service service = build('gmail', 'v1', credentials=creds) results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute() messages = results.get('messages', []) if messages: print("*" * 20, "Fetching & Saving Emails", "*" * 20) tasks = [fetch_emails(message['id'], creds) for message in messages] await asyncio.gather(*tasks) # task else: print("No Emails") if __name__ == '__main__': asyncio.run(main()) conn.close() print("*" * 20, "Completed Saving Emails", "*" * 20)
// Reactにおける型 import React from 'react' // typeは型エイリアス // React.React.Nodeはreact要素やコンポーネントなどを指す広範な型 type ContainerProps = { title: string children: React.ReactNode } // JSX.Element型 const Container = (props: ContainerProps): JSX.Element => { const { title, children } = props return ( <div style={{ background: 'red' }}> <span>{title}</span> <div>{children}</div> </div> ) } const Parent = (): JSX.Element => { return ( <Container title="Hello"> <p>ここの部分が背景色で囲まれます</p> </Container> ) } export default Parent
from pyspark.sql.session import SparkSession from pyspark.sql.types import * from pyspark.sql.functions import * from pyspark.sql.window import Window from datetime import date # Create Spark session spark = SparkSession.builder.appName("Transform and Load data into DataWarehouse") \ .config("spark.jars.packages", "com.datastax.spark:spark-cassandra-connector_2.12:3.3.0," "org.apache.spark:spark-sql-kafka-0-10_2.12:3.3.1,org.apache.kafka:kafka-clients:3.3.1") \ .config("spark.jars", "mysql-connector-java-8.0.33.jar").getOrCreate() # Set up Spark Log spark.sparkContext.setLogLevel("ERROR") # Take dataframe from Cassandra def read_from_cassandra(table, keyspace, arg_month): df = spark.read \ .format("org.apache.spark.sql.cassandra") \ .options(table=table, keyspace=keyspace) \ .option("spark.sql.query", f"SELECT * FROM {table} WHERE month = {arg_month}") \ .load().drop("year", "month", "day") print(f"-----------{table}-----------") df.printSchema() df.show(10) return df # Processing dataframes before create new ones def processing_data(inventoryDf, productDf, orderDf, customerDf, addressDf): # Join dataframes into a dataframe print("----------------------------") print("| Start joinning dataframe |") df = inventoryDf.join(productDf.withColumnRenamed("id", "product_id"), inventoryDf.id == productDf.inventory_id, how="inner") \ .join(orderDf, productDf.order_id == orderDf.id, how="inner") \ .join(customerDf, orderDf.customer_id == customerDf.id, how="inner") \ .join(addressDf, orderDf.city_id == addressDf.id.alias("city_id"), how="inner").drop("id") df = df.select("product_id", "product_name", "category", "type", "actual_price", "discount_price", "ratings", "no_of_ratings", "inventory_id", "inv_quantity", "quantity_sold", "link", "image", "customer_id", "customer_name", "gender", "email", "delivery_status", "segment", "city_id", "city", "state", "country", "order_id", "order_date", "ship_date", "timestamp", "timeuuid", "quarter") # Filter and fill Null data with some requirements print("------------------------------") print("| Start filter and fill Null |") print("------------------------------") df = df.filter(col("image").isNotNull()) df = df.filter(col("link").isNotNull()) df = df.filter(col("image").rlike("^https://.")).filter(col("link").rlike("^https://.")) df = df.filter(col("actual_price").isNotNull()).filter(col("actual_price") != 0) df = df.fillna(value=0, subset=["ratings", "no_of_ratings", "discount_price"]) df = df.filter(col("discount_price") < col("actual_price")) df.printSchema() df.show(10) return df # Put processed data into Order table in data warehouse def fact_Order(df): fact_Order = df.select("product_id", "customer_id", "city_id", "timeuuid") windowSpec_id = Window.orderBy("product_id") fact_Order = fact_Order.withColumn("id", row_number().over(windowSpec_id)) fact_Order = fact_Order.select("id", "product_id", "customer_id", "city_id", "timeuuid").distinct() fact_Order.printSchema() fact_Order.show(10) return fact_Order # Put processed data into Product table in data warehouse def dim_Product(df): dim_Product = df.select(col("product_id").alias("id"), "product_name", "category", "type", "actual_price", "discount_price", "ratings", "no_of_ratings", "link", "image", "quantity_sold", "inv_quantity", "delivery_status").distinct() dim_Product.printSchema() dim_Product.show(10) return dim_Product # Put processed data into Customer table in data warehouse def dim_Customer(df): dim_Customer = df.select(col("customer_id").alias("id"), "customer_name", "gender", "email", "segment").distinct() dim_Customer.printSchema() dim_Customer.show(10) return dim_Customer # Put processed data into Dilivery Location table in data warehouse def dim_DiliveryLocation(df): dim_DiliveryLocation = df.select(col("city_id").alias("id"), "city", "state", "country").distinct() dim_DiliveryLocation.printSchema() dim_DiliveryLocation.show(10) return dim_DiliveryLocation # Put processed data into Dilivery Location table in data warehouse def dim_Date(df): quarter_name = concat(lit("Q"), "quarter").alias("quarter_name") month_name = date_format(to_timestamp("ship_date"), "MMMM").alias("month_name") weekday_name = date_format(to_timestamp("ship_date"), "EEEE").alias("weekday_name") dim_Date = df.select("timeuuid", year("ship_date").alias("year"), "quarter", quarter_name, month("ship_date").alias("month"), month_name, dayofmonth("ship_date").alias("day"), weekday_name).distinct().sort("month", "day") dim_Date.printSchema() dim_Date.show(10) return dim_Date def kafkaTopic_to_mysql(df, topic, schema, dbtable, arg_year, arg_month, arg_day): print("---------------------------------") print(f"| Process {dbtable} with Kafka |") print("---------------------------------") # Write data to Kafka topic KAFKA_BOOTSTRAP_SERVER = "localhost:9092" df.selectExpr(f"CAST({df.columns[0]} AS STRING) AS key", "to_json(struct(*)) AS value") \ .write \ .format("kafka") \ .option("kafka.bootstrap.servers", KAFKA_BOOTSTRAP_SERVER) \ .option("topic", topic) \ .save() # Construct a streaming Dataframe that reads from topic lines = spark.read \ .format("kafka") \ .option("kafka.bootstrap.servers", KAFKA_BOOTSTRAP_SERVER) \ .option("subscribe", topic) \ .load() dbtable_data = lines.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)") \ .select(from_json("value", schema).alias("data")).select("data.*") dbtable_data.printSchema() print("--------------------------------------") print(f"| Batching write {dbtable} to mysql |") print("--------------------------------------") # Declare the parameters MySQL HOST = 'localhost' PORT = '3306' USER = "root" PASSWORD = "root" DB_NAME = "datawarehouse" URL = f'jdbc:mysql://{HOST}:{PORT}/{DB_NAME}' dbtable_data.withColumn("year", lit(arg_year)).withColumn("month", lit(arg_month)).withColumn("day", lit(arg_day)) \ .write \ .partitionBy("year", "month", "day") \ .format("jdbc") \ .option("url", URL) \ .option("dbtable", f"{dbtable}") \ .option("user", USER) \ .option("password", PASSWORD) \ .mode("append") \ .save() print(f"| Successfully save {dbtable} table |") print("--------------------------------------") if __name__ == '__main__': print("-------------------------------------") print("| Start reading data from Cassandra |") print("-------------------------------------") # Take the argument and partition them arg = str(date.today()) runTime = arg.split("-") arg_year = runTime[0] arg_month = runTime[1] arg_day = runTime[2] # Declare table names for Cassandra KEYSPACE = "datalake" INVENTORY_TABLE = "inventory" PRODUCT_TABLE = "product" ORDER_TABLE = "orderr" CUSTOMER_TABLE = "customer" ADDRESS_TABLE = "address" inventoryDf = read_from_cassandra(INVENTORY_TABLE, KEYSPACE, arg_month) productDf = read_from_cassandra(PRODUCT_TABLE, KEYSPACE, arg_month) orderDf = read_from_cassandra(ORDER_TABLE, KEYSPACE, arg_month) customerDf = read_from_cassandra(CUSTOMER_TABLE, KEYSPACE, arg_month) addressDf = read_from_cassandra(ADDRESS_TABLE, KEYSPACE, arg_month) print("----------------------") print("| Start process data |") df = processing_data(inventoryDf, productDf, orderDf, customerDf, addressDf) print("-----------------------------------") print("| Start put data into Order table |") print("-----------------------------------") order_table = fact_Order(df) print("-------------------------------------") print("| Start put data into Product table |") print("-------------------------------------") product_table = dim_Product(df) print("--------------------------------------") print("| Start put data into Customer table |") print("--------------------------------------") customer_table = dim_Customer(df) print("-----------------------------------------------") print("| Start put data into Dilivery Location table |") print("-----------------------------------------------") dilivery_location_table = dim_DiliveryLocation(df) print("----------------------------------") print("| Start put data into Date table |") print("----------------------------------") date_table = dim_Date(df) print("----------------------") print("| Start Data Process |") # Define schema for the data orderSchema = StructType([StructField("id", IntegerType(), True), StructField("product_id", IntegerType(), True), StructField("customer_id", IntegerType(), True), StructField("city_id", IntegerType(), True), StructField("timeuuid", StringType(), True)]) productSchema = StructType([StructField("id", IntegerType(), True), StructField("product_name", StringType(), True), StructField("category", StringType(), True), StructField("type", IntegerType(), True), StructField("actual_price", IntegerType(), True), StructField("discount_price", IntegerType(), True), StructField("ratings", DoubleType(), True), StructField("no_of_ratings", DoubleType(), True), StructField("link", StringType(), True), StructField("image", StringType(), True), StructField("quantity_sold", IntegerType(), True), StructField("inv_quantity", IntegerType(), True), StructField("delivery_status", StringType(), True)]) customerSchema = StructType([StructField("id", IntegerType(), True), StructField("customer_name", StringType(), True), StructField("gender", StringType(), True), StructField("email", StringType(), True), StructField("segment", StringType(), True)]) dilivery_locationSchema = StructType([StructField("id", IntegerType(), True), StructField("city", StringType(), True), StructField("state", StringType(), True), StructField("country", StringType(), True)]) dateSchema = StructType([StructField("timeuuid", StringType(), True), StructField("year", IntegerType(), True), StructField("quarter", IntegerType(), True), StructField("quarter_name", StringType(), True), StructField("month", IntegerType(), True), StructField("month_name", StringType(), True), StructField("day", IntegerType(), True), StructField("weekday_name", StringType(), True)]) # Declare table names for MySQL ORDER_TOPIC = "cass-mysql-factOrder" PRODUCT_TOPIC = "cass-mysql-dimProduct" CUSTOMER_TOPIC = "cass-mysql-dimCustomer" DILI_LOCA_TOPIC = "cass-mysql-dimDiliveryLocation" DATE_TOPIC = "cass-mysql-dimDate" ORDER_TABLE = "factOrder" PRODUCT_TABLE = "dimProduct" CUSTOMER_TABLE = "dimCustomer" DILI_LOCA_TABLE = "dimDiliveryLocation" DATA_TABLE = "dimDate" # Start to transform data order_to_mysql = kafkaTopic_to_mysql(order_table, ORDER_TOPIC, orderSchema, ORDER_TABLE, arg_year, arg_month, arg_day) product_to_mysql = kafkaTopic_to_mysql(product_table, PRODUCT_TOPIC, productSchema, PRODUCT_TABLE, arg_year, arg_month, arg_day) customer_to_mysql = kafkaTopic_to_mysql(customer_table, CUSTOMER_TOPIC, customerSchema, CUSTOMER_TABLE, arg_year, arg_month, arg_day) dilivery_location_to_mysql = kafkaTopic_to_mysql(dilivery_location_table, DILI_LOCA_TOPIC, dilivery_locationSchema, DILI_LOCA_TABLE, arg_year, arg_month, arg_day) date_to_mysql = kafkaTopic_to_mysql(date_table, DATE_TOPIC, dateSchema, DATA_TABLE, arg_year, arg_month, arg_day) print("| Successful Processing |") print("-------------------------")
@page @model RegisterModel @{ ViewData["Header"] = "Register Page"; } <div class="container d-flex justify-content-center" > <div class="col-md-4 text-center mb-4"> <form id="registerForm" class="row" asp-route-returnUrl="@Model.ReturnUrl" method="post"> <h2 class="mb-4">Create a new account.</h2> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-floating"> <input asp-for="Input.Email" class="form-control" autocomplete="[email protected]" aria-required="true" /> <label asp-for="Input.Email"></label> <span asp-validation-for="Input.Email" class="text-danger"></span> </div> <div class="form-floating col-md-6"> <input asp-for="Input.Name" class="form-control" autocomplete="name" aria-required="true" /> <label asp-for="Input.Name"></label> <span asp-validation-for="Input.Name" class="text-danger"></span> </div> <div class="form-floating col-md-6"> <input asp-for="Input.Age" class="form-control" autocomplete="age" aria-required="true" /> <label asp-for="Input.Age"></label> <span asp-validation-for="Input.Age" class="text-danger"></span> </div> <div class="form-floating"> <textarea asp-for="Input.AboutMe" class="form-control" aria-required="true" ></textarea> <label asp-for="Input.AboutMe"></label> <span asp-validation-for="Input.AboutMe" class="text-danger"></span> </div> <div class="form-floating"> <input asp-for="Input.Password" class="form-control" autocomplete="new-password" aria-required="true" /> <label asp-for="Input.Password"></label> <span asp-validation-for="Input.Password" class="text-danger"></span> </div> <div class="form-floating"> <input asp-for="Input.ConfirmPassword" class="form-control" autocomplete="new-password" aria-required="true" /> <label asp-for="Input.ConfirmPassword"></label> <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span> </div> <div class="form-floating mb-4"> <select asp-for="Input.Role" asp-items="@Model.Input.RoleList" class="form-select" > <option disabled selected>-Select Role</option> </select> </div> <button id="registerSubmit" type="submit" class="w-100 btn btn-lg btn-primary">Register</button> </form> </div> </div> @section Scripts { <partial name="_ValidationScriptsPartial" /> }
<form id="create-form" enctype="multipart/form-data"> @csrf <div class="form-group"> <label for="name">Category</label> <select name="category_id" id="category_id" class="form-control select2"> <option value="">Select One</option> @if(isset($categories[0])) @foreach($categories as $data) <option value="{{ $data->id }}">{{ $data->name }}</option> @endforeach @endif </select> <span id="category_+id_error" class="text-danger"></span> </div> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="Enter Group Name"> <span id="name_error" class="text-danger"></span> </div> <div class="form-group"> <label for="name">Is Primary Group</label> <input type="radio" id="is_primary" name="is_primary" value="1"> <span>Yes</span> <input type="radio" id="is_primary" name="is_primary" value="0"> <span>No</span> <span id="name_error" class="text-danger"></span> </div> <button type="submit" id="addSubCategoryBtn" class="btn btn-primary"><i class="fa fa-save"></i>&nbsp; Add Group Name</button> </form> <script> $(document).on('click','#addSubCategoryBtn',function (event) { event.preventDefault(); ErrorMessageClear(); var form = $('#create-form')[0]; var formData = new FormData(form); // Set header if need any otherwise remove setup part $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="token"]').attr('value') } }); $.ajax({ url: "{{route('superAdmin.jury_groups.store')}}",// your request url data: formData, processData: false, contentType: false, type: 'POST', success: function (data) { Swal.fire({ position: 'top-end', icon: data.type, title: data.message, showConfirmButton: false, // timer: 1500 }) setTimeout(function() { location.reload(); }, 1000); }, error: function (data) { $.each(data.responseJSON.errors, function(key, value) { ErrorMessage(key, value); }); } }); }); </script>
const NotFoundError = require('../../Commons/exceptions/NotFoundError'); const AddThread = require('../../Domains/threads/entities/AddThread'); const AddedThread = require('../../Domains/threads/entities/AddedThread'); const GetThread = require('../../Domains/threads/entities/GetThread'); const ThreadRepository = require('../../Domains/threads/ThreadRepository'); class ThreadRepositoryPostgres extends ThreadRepository { constructor(pool, idGenerator) { super(); this._pool = pool; this._idGenerator = idGenerator; } async addThread(thread) { const { userId: owner, title, body } = new AddThread(thread); const id = `thread-${this._idGenerator()}`; const date = new Date().toISOString(); const query = { text: 'INSERT INTO threads VALUES ($1, $2, $3, $4, $5) RETURNING id, title, owner', values: [id, title, body, date, owner], }; const result = await this._pool.query(query); return new AddedThread({ ...result.rows[0] }); } async checkAvailabilityThread(threadId) { const query = { text: 'SELECT id FROM threads WHERE id = $1', values: [threadId], }; const result = await this._pool.query(query); if (!result.rowCount) { throw new NotFoundError('thread tidak ditemukan'); } } async getThreadById(threadId) { const query = { text: `SELECT t.id, t.title, t.body, t.date, u.username FROM threads AS t JOIN users AS u ON u.id = t.owner WHERE t.id = $1`, values: [threadId], }; const result = await this._pool.query(query); return new GetThread({ ...result.rows[0], comments: [] }); } } module.exports = ThreadRepositoryPostgres;
<!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>CallBack</title> </head> <body> <button class="clickMe"> ClickMe! </button> <p> <input type="button" value="stop" onClick="stopInterval()" /> </p> <script> const button = document.querySelector ('.clickMe'); function handleClick() {console.log('Great Clicking!')}; // registering the event handler {'handleclick()'} with the event ('click') button.addEventListener('click',handleClick); const handler1 = function() { console.log('Nice Job!!!'); }; button.addEventListener('click',handler1); // timer call back const handler2 = () => { console.log('DONE! time to eat!'); }; setTimeout(handler2, 3000); // the func will be called after the timeoutperiod // const interval = setInterval(handler2, 2000); // setTimeout(clearTimeout(interval),10000); var interval = setInterval(handler2, 2000); function stopInterval() { clearInterval(interval); console.log('stopped!!!!!'); } </script> <!-- publisher - a control or a function that raise an event (signal) subscriber - the code / function thet reaches to the event (signal) signal - event (click, textchange, mouse over...) one to many one event can have many subscribers. --> </body> </html>
--- layout: ../../layouts/MarkdownPostLayout.astro title: "Arch linux手術室" author: "sakakibara" description: "Arch linux小説です。" image: url: "https://cdn.icon-icons.com/icons2/2699/PNG/512/archlinux_logo_icon_167835.png" alt: "Arch linux logo" pubDate: 2024-03-04 tags: ["astro", "公開学習", "コミュニティ"] --- # 手術中 心臓が汗をかく。 部屋は暗いが眼の前のディスプレイがやたら眩しい。 "練習通りにいってくれ。" 汚い字で書かれたメモを見ながら、慎重にパーティションを切り分ける。 1つのタイプミスが命取りになる。 カーソルの点滅に心臓の鼓動が追いつく。 呼吸を殺し、指先に意識を移し、暗闇の中で輝く文字だけを見つめる。 Enterに小指をかけた直前、あの日々を思い出した。 ### UEFI or BIOS ```bash title='UEFI or BIOS' cat /sys/firmware/efi/fw_platform_size ``` linuxがどのように起動するか。 電源を入れると、マザーボードのROMに書き込まれた起動ファームウェアが実行される。 起動ファームウェアは大きく分けて2つ。 BIOSとUEIFだ。 端的に言ってしまえばBIOSの方が古くてUEFIの方が新しい。 なので最近のPCはUEFIを採用している。 自分が使用する起動ファームウェアがどちらを採用しているかによって今後のインストール手順が大きく変わる。 また、linuxのインストールはインストールメディアとインストール先のブロックデバイスが必要になる。 このコマンドを含め、明示されるまでは暗黙のうちにインストールメディアのlinuxのコマンドを入力していることに注意する。 ### Can you use your network ? ```bash title='can you use network?' ip link ping archlinux.jp ``` このあとの工程でインストールメディアから様々なパッケージをダウンロードする。 そのため、インターネットに接続されていることは必須となる。 `ip link` コマンドはlinuxが認識しているネットワークデバイスを表示するコマンドである。 注意することとして、これにeth0のような表示あったからと言って、それはインターネットに接続している確認にはならない。 あくまで接続されているデバイスを表示するだけなのだ。 `ping archlinux.jp`コマンドはarchlinux.jpへデータを送信し、応答を表示するコマンドだ。 `ping`コマンドはICMP(Internet Control Message Protocol: インターネット制御通知プロトコル)というプロトコルのECHO_REQUESTを使用する。これはネットワークの通知のテストに使われる。 ### timedate check ```bash title='timedatectl' timedatectl status ``` 時間をチェックする。 ### separete partition ```bash title='lsblk' lsblk ``` ```bash title='gdisk' gdisk /dev/sda ``` ```bash title='gdisk' > o => Y > n => Enter => Enter => +1G => ef00 > n => Enter => Enter => +4G => 8200 > n => Enter => Enter => Enter => 8e00 > w ``` ### add LVM #### 物理ボリューム: Physical Volume ```bash title='pvcreate' pvcreate /dev/sda3 ``` ```bash title='pvs or pvdisplay' pvs pvdisplay ``` #### ボリュームグループ: Volume Group ```bash title='vgcreate' vgcreate ArchVolGroup /dev/sda3 ``` ```bash title='vgs, vgdisplay' vgs vgdisplay ``` #### 論理ボリューム: Logical Volume ```bash title='lvcreate' lvcreate -L 100G ArchVolGroup -n lvol lvcreate -l 100%FREE ArchVolGroup -n lvolhome ``` ```bash title='lvdisplay, lvremove, lvresize ...' lvdisplay lvremove lvresize ``` ### add file system ```bash title='mkfs' mkfs.fat -F 32 /dev/sda1 mkswap /dev/sda2 mk.ext4 /dev/ArchVolGroup/lvol mk.ext4 /dev/ArchVolGroup/lvolhome ``` ```bash title='lsblk' lsblk --fs ``` ### mount block device ```bash title='mount' mount /dev/ArchVolGroup/lvol /mnt mkdir /mnt/boot mount /dev/sda1 /mnt/boot mkdir /mnt/home mount /dev/ArchVolGroup/lvolhome /mnt/home swapon /dev/sda2 ``` ### chose pacman mirrorlist ```bash title='mount' reflector --sort rate --country jp --latest 10 --save /etc/pacman.d/mirrorlist ``` ### download pacages ```bash title='mount' pacstrap -K /mnt base linux linux-firmware vim sudo man-db man-pages lvm2 ``` ### fstab ```bash title='mount' genfstab -U /mnt >> /mnt/etc/fstab ``` ### setting XDG ```bash title='zsh' export XDG_CONFIG_HOME="$HOME/.config" export XDG_CACHE_HOME="$HOME/.cache" export XDG_DATA_HOME="$HOME/.local/share" export XDG_STATE_HOME="$HOME/.local/state" ``` ### change root ```bash title='mount' arch-chroot /mnt ``` ### setting locale ```bash title='mount' ln -sf /usr/share/zoneinfo/Asia/Tokyo /etc/localtime ``` ```bash title='vim /etc/locale.gen' en_US.UTF-8 //unmount jp_JP.UTF-8 //unmount ``` ```bash title='locale-gen' locale-gen ``` ```bash title='vim /etc/locale.conf' LANG=en_US.UTF-8 ``` ```bash title='vim /etc/hostname' organon ``` ### setting network ```bash title='systemd-networkd' systemctl enable systemd-networkd systemd-resolved ``` ```zsh title='vim /etc/systemd/network/ether.network' [Match] Name = enp03 [Network] DHCP = yes ``` ### setting for LVM ```bash title='vim /etc/mkinitcpio.conf' HOOKS=(base ... block lvm2 filesystem) ``` ### initcpio ```bash title='mkinitcpio' mkinitcpio -P ``` ### user add ### setting grub and microcode ```bash title='grub' pacman -S amd-ucode grub efibootmgr grub-install --target=x86_64-efi --efi-directory=/boot --bootloader-id=GRUB ``` ```bash title='grub' mkdir /boot/EFI/boot cp /boot/EFI/GRUB/grubx64.efi /boot/EFI/boot/bootx64.efi ``` ```bash title='vim /etc/default/grub' GRUB_CMDLINE_LINUX_DEFAULT="root=/dev/ArchVolGroup/lvol" GRUB_PRELOAD_MODULES="... lvm" ``` ```bash title='vim /etc/default/grub' grub-mkconfig -o /boot/grub/grub.cfg ``` ### Arch linux ```bash title='reboot' exit umount -R /mnt reboot ```
import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:share_plus/share_plus.dart'; mixin ShareMixin { void pickAndShareImage(BuildContext context) async { final box = context.findRenderObject() as RenderBox?; final imagePicker = ImagePicker(); final pickedFile = await imagePicker.pickImage( source: ImageSource.gallery, ); if (pickedFile != null) { await Share.shareXFiles([XFile(pickedFile.path)], sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size); } } void shareListOfImages(BuildContext context, List<String> paths) async { final box = context.findRenderObject() as RenderBox?; await Share.shareXFiles(paths.map((e) => XFile(e)).toList(), sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size); } void shareText(BuildContext context, String text) async { final box = context.findRenderObject() as RenderBox?; await Share.share(text, sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size); } }
"use client"; import React from "react"; import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"; import { getAllCourse, getCourseDetails } from "@/app/services/courseService"; const initialState = { courses: [], courseDetails: {}, courseIsError: false, courseIsSuccess: false, courseIsLoading: false, courseMessage: "", }; // Get all courses export const fetchAllCourse = createAsyncThunk( "courses/getAll", async (_, thunkAPI) => { try { return await getAllCourse(); } catch (error) { const courseMessage = (error.response && error.response.data && error.response.data.courseMessage) || error.courseMessage || error.toString(); return thunkAPI.rejectWithValue(courseMessage); } } ); // Get course details export const fetchCourseDetails = createAsyncThunk( "courses/getDetails", async (courseId, thunkAPI) => { try { return await getCourseDetails(courseId); } catch (error) { const courseMessage = (error.response && error.response.data && error.response.data.courseMessage) || error.courseMessage || error.toString(); return thunkAPI.rejectWithValue(courseMessage); } } ); export const courseSlice = createSlice({ name: "course", initialState, reducers: { reset: (state) => initialState, }, extraReducers: (builder) => { builder .addCase(fetchAllCourse.pending, (state) => { state.courseIsLoading = true; }) .addCase(fetchAllCourse.fulfilled, (state, action) => { state.courseIsLoading = false; state.courseIsSuccess = true; state.courses = action.payload; }) .addCase(fetchAllCourse.rejected, (state, action) => { state.courseIsLoading = false; state.courseIsError = true; state.courseMessage = action.payload; }) .addCase(fetchCourseDetails.pending, (state) => { state.courseIsLoading = true; }) .addCase(fetchCourseDetails.fulfilled, (state, action) => { state.courseIsLoading = false; state.courseIsSuccess = true; state.courseDetails = action.payload; }) .addCase(fetchCourseDetails.rejected, (state, action) => { state.courseIsLoading = false; state.courseIsError = true; state.courseMessage = action.payload; }); }, }); export const { reset } = courseSlice.actions; export default courseSlice.reducer;
-module(episode_4). -behaviour(gen_server). % https://github.com/kivra/restclient % Enable restc in erlang_bits.app.src % https://github.com/fedspendingtransparency/usaspending-api/blob/master/usaspending_api/api_contracts/contracts/v2/search/spending_by_category/county.md -export([ start_link/0, init/1, handle_call/3, handle_cast/2 ]). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). -record(state, {api_url = "https://api.usaspending.gov/api/v2/search/spending_by_category/county"}). init([]) -> {ok, #state{}}. handle_call(ping, _From, State) -> {reply, pong, State}; handle_call({county, County}, _From, State = #state{api_url = ApiUrl}) -> Body = #{ filters => #{ % might be better to use unicode:characters_to_binary/1 function here? recipient_search_text => [list_to_binary(County)], time_period => [ #{ start_date => <<"2022-01-01">>, end_date => <<"2022-12-31">> } ] } }, {ok, 200, _Headers, Response} = restc:request( % request method post, % content type json, % request URL, restc:construct_url can be useful for query parameters ApiUrl, % expected status codes [200], % headers as proplist [], % Automatically converted to JSON for us Body, % options [] ), logger:notice(#{response => Response}), Results = proplists:get_value(<<"results">>, Response), logger:notice(#{results => Results}), Amounts = lists:foldr(fun collect_amounts/2, maps:new(), Results), logger:notice(#{amounts => Amounts}), AmountsAsBinary = maps:map(fun(_K, V) -> decimal:to_binary(V) end, Amounts), logger:notice(#{as_binary => AmountsAsBinary}), {reply, Amounts, State}; handle_call(Msg, _From, State) -> logger:notice("Got unknown message ~p~n", [Msg]), {reply, ok, State}. handle_cast(Msg, State) -> logger:notice("Got unknown message ~p~n", [Msg]), {noreply, State}. collect_amounts(Proplist, Map) -> Name = proplists:get_value(<<"name">>, Proplist), Amount = proplists:get_value(<<"amount">>, Proplist), Opts = #{precision => 2, rounding => round_floor}, AmountDecimal = decimal:to_decimal(Amount, Opts), maps:update_with(Name, fun(V) -> decimal:add(V, AmountDecimal) end, AmountDecimal, Map).
import { useEffect, useState } from "react" import { fakeFetch } from "../api/api5" export const Ques5 = () => { const [ bakeryData, setBakeryData] = useState([]); const getData = async(url) => { try { const {status, data} = await fakeFetch(url) // console.log(status,data) if (status === 200){ setBakeryData(data.posts) } // console.log(data) }catch(e){ console.log(e) } } const showBakery = ()=>{ setBakeryData(bakeryData.filter(({category})=> category === "Bakery")) } useEffect(()=>{ getData("https://example.com/api/posts") },[]) return ( <> <ul style={{backGroundColor: "red"}}> { bakeryData.map(({caption,src,views,likes,category},index)=>(<li key={index}><img src={src} alt="" /><figcaption>{caption}</figcaption><p>Likes:{likes}<br />Views:{views}</p></li>)) } </ul> <button onClick={showBakery}>Show Bakery</button> </> ) }
import React, { forwardRef, useImperativeHandle } from 'react'; interface RefComponentProps { style?: React.CSSProperties; } export interface RefComponentRef { afunction: () => void; } function InternalRefComponent(props: RefComponentProps, ref: React.ForwardedRef<RefComponentRef>) { useImperativeHandle( ref, () => { return { afunction() { console.log('afunction'); }, }; }, [], ); return <div style={props?.style}>RefComponent</div>; } const RefComponent = forwardRef(InternalRefComponent); export default RefComponent;
// http.ts import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios' import qs from "qs" import { Toast } from 'vant'; import getSignOptions from './getSignOptions' const service: AxiosInstance = axios.create({ // 联调 // baseURL: process.env.NODE_ENV === 'production' ? `/` : '/api', baseURL: process.env.VUE_APP_BASE_API, // 是否跨站点访问控制请求 withCredentials: true, timeout: 60000, transformRequest: [(data) => { data = JSON.stringify(data) return data }], validateStatus() { // 使用async-await,处理reject情况较为繁琐,所以全部返回resolve,在业务代码中处理异常 return true }, transformResponse: [(data) => { if (typeof data === 'string' && data.startsWith('{')) { data = JSON.parse(data) } return data }] }) // 声明一个 Map 用于存储每个请求的标识 和 取消函数 const pending = new Map() /** * 添加请求 * @param {Object} config */ const addPending = (config: AxiosRequestConfig) => { const url = [ config.method, config.url, qs.stringify(config.params), qs.stringify(config.data) ].join('&') config.cancelToken = config.cancelToken || new axios.CancelToken(cancel => { if (!pending.has(url)) { // 如果 pending 中不存在当前请求,则添加进去 pending.set(url, cancel) } }) } /** * 移除请求 * @param {Object} config */ const removePending = (config: AxiosRequestConfig) => { const url = [ config.method, config.url, qs.stringify(config.params), qs.stringify(config.data) ].join('&') if (pending.has(url)) { // 如果在 pending 中存在当前请求标识,需要取消当前请求,并且移除 const cancel = pending.get(url) cancel(url) pending.delete(url) } } /** * 清空 pending 中的请求(在路由跳转时调用) */ export const clearPending = (): void => { for (const [url, cancel] of pending) { cancel(url) } pending.clear() } // 请求拦截器 service.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => { // console.log(config, "config"); // let token = localStorage.getItem("TOKEN"); // if (token) { // // 判断是否存在token,如果存在的话,则每个http header都加上token // config.headers.common["authorization"] = token; // } removePending(config) // 在请求开始前,对之前的请求做检查取消操作 addPending(config) // 将当前请求添加到 pending 中 config.headers = { ...config.headers, "Content-Type": "application/json;charset=UTF-8", "Dahuange-User-Access-Token": localStorage.getItem("casToken") || "" }; const signOptions = getSignOptions("RECHARGE_CARD_CONSUMER", config); config.headers = { ...config.headers, ...signOptions }; console.log(`%c<-------${config.url}-------->`, 'color: red;font-size: 18px' , config.data || config.params) return config; }, (error) => { // 错误抛到业务代码 Toast({ message: "请求方式错误", duration: 3000 }); return Promise.reject(error); }) // 响应拦截器 service.interceptors.response.use((response: AxiosResponse) => { // const status = response.status removePending(response) // 在请求结束后,移除本次请求 const { code, message } = response.data; if (code == 10002 || code == 10006 || code == 10005 || code == 10034) { // 10002 token已经过期,10006登录状态失效 // resetAllStorage(); return response; } const WHITE_CODES = [83001]; if ( (response && response.data && code < 0) || (code && code !== 200 && code !== 100) ) { // 更改错误码,增加情况,当code不为100,不为200,且code存在的时候 if (!WHITE_CODES.includes(code) && message) { Toast({ message: message, duration: 3000 }); } return Promise.reject(response); } return response; }, (error) => { if (axios.isCancel(error)) { console.log('repeated request: ' + error.message) } else { // handle error code // 错误抛到业务代码 switch (error.response.status) { case 401: console.log("接口返回401!!!!!!!!!!!!!"); return Promise.reject(error.response.data); // 返回接口返回的错误信息 } if (error.response.status !== 400) { Toast({ message: error.message, duration: 3000 }); } } return Promise.reject(error) }) export default service
import {useState, useEffect} from 'react'; import {useDispatch, useSelector} from 'react-redux'; import { signInSuccess, signInError, signOutSuccess, signOutError, } from 'src/redux/actions/auth'; import {AsyncStorage} from 'react-native'; import {clearMessage} from 'src/redux/actions/chat'; import {authorize, refresh, revoke} from 'react-native-app-auth'; import jwt_decode from 'jwt-decode'; import {authConfig} from 'src/constants'; const useAuth = () => { const [isLoading, setLoading] = useState<boolean>(false); const user = useSelector((state: any) => state.authReducers); const dispatch = useDispatch(); console.log(user.isAuth); const handleLogin = async () => { try { setLoading(true); const response = await authorize(authConfig); const {accessToken, refreshToken} = response; await AsyncStorage.multiSet([ ['accessToken', accessToken], ['refreshToken', refreshToken === null ? '' : refreshToken], // Offline Access is not checked ]); const decoded: Object = jwt_decode(accessToken); const randomGen = Math.floor(Math.random() * 6) + 1; dispatch(signInSuccess({...decoded, sub: decoded.sub + randomGen})); setLoading(false); } catch (error) { console.error('error: ', error); dispatch(signInError()); } finally { setLoading(false); } }; const handleLogout = async () => { try { setLoading(true); const accessToken = await AsyncStorage.getItem('accessToken'); console.log('token: ', accessToken); await revoke(authConfig, { tokenToRevoke: accessToken || '', includeBasicAuth: true, sendClientId: true, }); await AsyncStorage.multiSet([ ['accessToken', ''], ['refreshToken', ''], ]); dispatch(signOutSuccess()); dispatch(clearMessage()); setLoading(false); } catch (error) { console.error(error); dispatch(signOutError()); } finally { setLoading(false); } }; const handleRefreshToken = async () => { try { const refreshToken = await AsyncStorage.getItem('refreshToken'); if (refreshToken !== '' && refreshToken !== null) { const response = await refresh(authConfig, {refreshToken}); await AsyncStorage.multiSet([ ['accessToken', response.accessToken], [ 'refreshToken', response.refreshToken === null ? '' : response.refreshToken, ], ]); } } catch (error) { console.error(error); } }; const isLoggedIn = async () => { const accessToken = await AsyncStorage.getItem('accessToken'); return accessToken === null || accessToken === '' ? false : true; }; useEffect(() => { //TODO access to local storage to get user's data }, []); return { isLoading, handleLogin, handleLogout, handleRefreshToken, isLoggedIn, user, }; }; export default useAuth;
<!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> <style> * { margin: 0; width: 80%; box-sizing: border-box; height: auto; padding: 0; } fieldset { padding: 2px; border: none; } section#formulario { margin: 30px auto; padding: 5px; } form { width: 100%; height: auto; padding: 2px; } label { display: block; width: 100%; height: auto; padding: 2px; } </style> </head> <body> <section id="formulario"> <form action="" name="cadastro" method="get"> <fieldset> <legend>Cadastro de Usuário</legend> <label for="nome">Nome</label> <input type="text" name="nome" value="" id="nome" required /> <label for="sobrenome">Sobrenome</label> <input type="text" name="sobrenome" value="" id="sobrenome" /> <label for="nasc">Data de Nascimento</label> <input type="date" name="dataNasc" id="nasc" /> </fieldset> <fieldset> <legend>Gênero</legend> <label>Masculino</label> <input type="radio" name="genero" id="" value="m" /> <label>Feminino</label> <input type="radio" name="genero" id="" value="f" /> </fieldset> <fieldset> <legend>Preferências</legend> <label for="php">PHP</label> <input type="checkbox" name="php" id="php" /> <label for="js">Javascript</label> <input type="checkbox" name="js" id="js" /> <label for="html_css">Html/CSS</label> <input type="checkbox" name="html_css" id="html_css" /> </fieldset> <fieldset> <select name="" id=""> <option value="">Selecione</option> <option value="junior">Junior</option> <option value="pleno">Pleno</option> <option value="senior">Senior</option> </select> </fieldset> <fieldset> <label for="edicao">Escreva Mais sobre você</label> <textarea name="edicao" id="" cols="80" rows="10"></textarea> </fieldset> </form> <input type="submit" name="enviarDados" value="ENVIAR" /> </section> </body> </html>
## A Lite redis-server implementation in golang Inspired from [Coding Challenges - Build Your Own Redis Server ](https://codingchallenges.fyi/challenges/challenge-redis) ## Prerequisites - Go 1.22 or later - redis-cli (for testing this implementation) Installation guide - https://redis.io/docs/install/install-redis/ ## Try out ```bash # Using brew (for mac or linux) brew install omkarph/tap/redis-server-lite redis-server-lite # or # Using a release archive from https://github.com/OmkarPh/redis-server-lite/releases/latest cd ~/Downloads # Go to the Downloads folder of your machine mkdir redis-server-lite tar -xf "release_archive_file" -C redis-server-lite cd redis-server-lite ./redis-server-lite # Test redis-cli set message Hello World redis-cli get message ``` ## Features - Follows RESP protocol (Works with redis-cli & redis-benchmark) - Key expiration (Active & Passive) - Simple & Sharded key-value stores Can be customised in `redis.conf` file as: ``` kv_store sharded shardfactor 32 or kv_store simple ``` ## Supported commands Detailed documentation - https://redis.io/commands/ | Command | Syntax | Example | Description | |----------|------------------------------------------|-----------------------------------------------------------|-------------------------------------------------| | SET | **SET key value** [NX / XX] [GET]<br/>[EX seconds / PX milliseconds<br/> / EXAT unix-time-seconds / PXAT unix-time-milliseconds / KEEPTTL] | redis-cli SET name omkar<br/>redis-cli SET name omkar GET KEEPTTL | Set the string value of a key | | GET | **GET key** | redis-cli GET name | Get the value of a key | | DEL | **DEL key** [key ...] | redis-cli DEL name<br/>redis-cli DEL name age | Delete one or more keys | | INCR | **INCR key** | redis-cli INCR age | Increment the integer value of a key | | DECR | **DECR key** | redis-cli DECR age | Decrement the integer value of a key | | EXISTS | **EXISTS key** [key ...] | redis-cli EXISTS name<br/>redis-cli EXISTS name age | Check if a key exists | | EXPIRE | **EXPIRE key seconds** [NX / XX / GT / LT] | redis-cli EXPIRE name 20<br/>redis-cli EXPIRE name 20 NX | Set a key's time to live in seconds | | PERSIST | **PERSIST key ** | redis-cli PERSIST name | Remove the expiration from a key | | TTL | **TTL key** | redis-cli TTL key | Get the time to live for a key (in seconds) | | TYPE | **TYPE key** | redis-cli TYPE name | Determine the type stored at a key | | PING | **PING** | redis-cli PING | Ping the server | | ECHO | **ECHO message** | redis-cli ECHO "Hello world" | Echo the given string | ## Local setup ```bash # Clone this repository git clone https://github.com/OmkarPh/redis-lite.git cd redis-lite # Install dependencies go get . # Run the server go run . # Build release executible go build -o build/redis-lite-server -v ./build/redis-lite-server ``` ## Benchmarks > [!NOTE] > These are results from Macbook air M1 8gb ```bash redis-benchmark -t SET,GET,INCR -q ``` ### redis-server-lite ![redis-server-lite](assets/benchmarkLite.png) ### Original redis-server ![redis-server](assets/benchmarkOg.png)
package com.scheduler.app.backend.aREST.Models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.scheduler.app.backend.aREST.Models.Base.*; import java.util.*; import java.util.List; import java.util.Objects; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class Devices extends ModelBase{ // device which the board is belong to @JsonManagedReference @JsonIgnore @ManyToOne @JoinColumn(name="board_id", nullable=false) private Board boardId; // name of device @Column private String deviceName; // state which the device is in @Column private String state; // error from device @Column private String warning; // priority for task schedule @Column private int priority=1; // time delay (mins) for task schedule @Column private double timeDelay=10; @OneToMany(fetch = FetchType.LAZY) private Set<Routes> routes=new HashSet<Routes>(); public Devices() { } public Devices(Board boardId, String deviceName, String state, String warning, int priority, double timeDelay, Set<Routes> routes) { this.boardId = boardId; this.deviceName = deviceName; this.state = state; this.warning = warning; this.priority = priority; this.timeDelay = timeDelay; this.routes = routes; } public Board getBoardId() { return this.boardId; } public void setBoardId(Board boardId) { this.boardId = boardId; } public String getDeviceName() { return this.deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public String getState() { return this.state; } public void setState(String state) { this.state = state; } public String getWarning() { return this.warning; } public void setWarning(String warning) { this.warning = warning; } public int getPriority() { return this.priority; } public void setPriority(int priority) { this.priority = priority; } public double getTimeDelay() { return this.timeDelay; } public void setTimeDelay(double timeDelay) { this.timeDelay = timeDelay; } public Set<Routes> getRoutes() { return this.routes; } public void setRoutes(Set<Routes> routes) { this.routes = routes; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Devices)) { return false; } Devices devices = (Devices) o; return Objects.equals(boardId, devices.boardId) && Objects.equals(deviceName, devices.deviceName) && Objects.equals(state, devices.state) && Objects.equals(warning, devices.warning) && priority == devices.priority && timeDelay == devices.timeDelay && Objects.equals(routes, devices.routes); } @Override public int hashCode() { return Objects.hash(boardId, deviceName, state, warning, priority, timeDelay, routes); } }
# This file contains the structural alignment dataset classes import os import csv import numpy as np import json import torch import random from torch.utils import data from transformers import AutoTokenizer import pandas as pd lm_mp = {'roberta': 'roberta-base', 'bert': 'bert-base-uncased', 'distilbert': 'distilbert-base-uncased'} class CADataset(data.Dataset): #copy from BTDataset class """Dataset for pre-training""" def __init__(self, csv_path, max_len=512, size=None, lm='bert', da='all'): self.tokenizer = AutoTokenizer.from_pretrained(lm_mp[lm]) self.instances= [] self.rel_instances = [] self.max_len = max_len self.size = size # dataset size pd_list = [] cur_df = pd.read_csv(csv_path) cur_df = cur_df.dropna() cur_df = cur_df[['text','c_text']] pd_list.append(cur_df) merged_df = pd.concat(pd_list, axis = 0) self.instances = list(merged_df.text.values) self.rel_instances = list(merged_df.c_text.values) #print(self.instances) if size is not None: if size > len(self.instances): N = size // len(self.instances) + 1 self.instances = (self.instances * N)[:size] # over sampling self.rel_instances = (self.rel_instances * N)[:size] else: indices = [i for i in range(len(self.instances))] selected_indices = random.sample(indices, size) out_instances = [] out_rel = [] for index in selected_indices: out_instances.append(self.instances[index]) out_rel.append(self.rel_instances[index]) self.instances = out_instances self.rel_instances = out_rel def __len__(self): """Return the size of the dataset.""" return len(self.instances) def __getitem__(self, idx): """Return a tokenized item of the dataset. Args: idx (int): the index of the item Returns: List of int: token ID's of the 1st entity List of int: token ID's of the 2nd entity List of int: token ID's of the two entities combined int: the label of the pair (0: unmatch, 1: match) """ #print('A') A = self.instances[idx] # combine with the deletion operator #print('B') B = self.rel_instances[idx] # left yA = self.tokenizer.encode(text=A, max_length=self.max_len, truncation=True) yB = self.tokenizer.encode(text=B, max_length=self.max_len, truncation=True) return yA, yB @staticmethod def pad(batch): """Merge a list of dataset items into a train/test batch Args: batch (list of tuple): a list of dataset items Returns: LongTensor: x1 of shape (batch_size, seq_len) LongTensor: x2 of shape (batch_size, seq_len). Elements of x1 and x2 are padded to the same length """ yA, yB = zip(*batch) maxlen = max([len(x) for x in yA]) maxlen = max(maxlen,max([len(x) for x in yB])) yA = [xi + [0]*(maxlen - len(xi)) for xi in yA] yB = [xi + [0]*(maxlen - len(xi)) for xi in yB] return torch.LongTensor(yA), \ torch.LongTensor(yB) class SupCADataset(data.Dataset): """dataset for the evaluation""" def __init__(self, csv_path, max_len=256, size=None, lm='bert', da=None): self.tokenizer = AutoTokenizer.from_pretrained(lm_mp[lm]) self.labels = [] self.instances = [] self.max_len = max_len self.size = size with open('/export/data/ysunbp/CCTA/SimTAB/sato_data/label.json', 'r') as dict_in: self.label_dict = json.load(dict_in) pd_list = [] df = pd.read_csv(csv_path) df = df.dropna() pd_list.append(df) merged_dataset = pd.concat(pd_list, axis = 0) df = merged_dataset[['text','gt']] df = df.values self.instances = df[:,0] for i in range(df.shape[0]): self.labels.append(int(self.label_dict[df[i,1]])) if size is not None: if size > len(self.instances): N = size // len(self.instances) + 1 self.instances = list((self.instances * N)[:size]) self.labels = list((self.labels * N)[:size]) else: indices = [i for i in range(len(self.instances))] selected_indices = random.sample(indices, size) out_instances = [] out_labels = [] for index in selected_indices: out_instances.append(self.instances[index]) out_labels.append(self.labels[index]) self.instances = out_instances self.labels = out_labels def __len__(self): """Return the size of the dataset.""" return len(self.labels) def __getitem__(self, idx): """Return a tokenized item of the dataset. Args: idx (int): the index of the item Returns: List of int: token ID's of the column int: the label of the column """ # idx = random.randint(0, len(self.pairs)-1) col = self.instances[idx] x = self.tokenizer.encode(text=col, max_length=self.max_len, truncation=True) return x, self.labels[idx] @staticmethod def pad(batch): """Merge a list of dataset items into a train/test batch Args: batch (list of tuple): a list of dataset items Returns: LongTensor: x1 of shape (batch_size, seq_len) LongTensor: a batch of labels, (batch_size,) """ # cleaning x1, y = zip(*batch) maxlen = max([len(x) for x in x1]) x1 = [xi + [0]*(maxlen - len(xi)) for xi in x1] return torch.LongTensor(x1), torch.LongTensor(y)
<?php namespace App\Http\Controllers\API; use App\Http\Requests\API\CreateDocumentoAPIRequest; use App\Http\Requests\API\UpdateDocumentoAPIRequest; use App\Models\Documento; use App\Repositories\DocumentoRepository; use Illuminate\Http\Request; use App\Http\Controllers\AppBaseController; use Response; /** * Class DocumentoController * @package App\Http\Controllers\API */ class DocumentoAPIController extends AppBaseController { /** @var DocumentoRepository */ private $documentoRepository; public function __construct(DocumentoRepository $documentoRepo) { $this->documentoRepository = $documentoRepo; } /** * @param Request $request * @return Response * * @OA\Get( * path="/documentos", * summary="getDocumentoList", * tags={"Documento"}, * description="Get all Documentos", * @OA\Response( * response=200, * description="successful operation", * @OA\Schema( * type="object", * @OA\Property( * property="success", * type="boolean" * ), * @OA\Property( * property="data", * type="array", * @OA\Items(ref="#/definitions/Documento") * ), * @OA\Property( * property="message", * type="string" * ) * ) * ) * ) */ public function index(Request $request) { $documentos = $this->documentoRepository->all( $request->except(['skip', 'limit']), $request->get('skip'), $request->get('limit') ); return $this->sendResponse($documentos->toArray(), 'Documentos retrieved successfully'); } /** * @param Request $request * @return Response * * @OA\Post( * path="/documentos", * summary="createDocumento", * tags={"Documento"}, * description="Create Documento", * @OA\RequestBody( * required=true, * @OA\MediaType( * mediaType="application/x-www-form-urlencoded", * @OA\Schema( * type="object", * required={""}, * @OA\Property( * property="name", * description="desc", * type="string" * ) * ) * ) * ), * @OA\Response( * response=200, * description="successful operation", * @OA\Schema( * type="object", * @OA\Property( * property="success", * type="boolean" * ), * @OA\Property( * property="data", * ref="#/definitions/Documento" * ), * @OA\Property( * property="message", * type="string" * ) * ) * ) * ) */ public function store(CreateDocumentoAPIRequest $request) { $input = $request->all(); $documento = $this->documentoRepository->create($input); return $this->sendResponse($documento->toArray(), 'Documento saved successfully'); } /** * @param int $id * @return Response * * @OA\Get( * path="/documentos/{id}", * summary="getDocumentoItem", * tags={"Documento"}, * description="Get Documento", * @OA\Parameter( * name="id", * description="id of Documento", * @OA\Schema( * type="integer" * ), * required=true, * in="path" * ), * @OA\Response( * response=200, * description="successful operation", * @OA\Schema( * type="object", * @OA\Property( * property="success", * type="boolean" * ), * @OA\Property( * property="data", * ref="#/definitions/Documento" * ), * @OA\Property( * property="message", * type="string" * ) * ) * ) * ) */ public function show($id) { /** @var Documento $documento */ $documento = $this->documentoRepository->find($id); if (empty($documento)) { return $this->sendError('Documento not found'); } return $this->sendResponse($documento->toArray(), 'Documento retrieved successfully'); } /** * @param int $id * @param Request $request * @return Response * * @OA\Put( * path="/documentos/{id}", * summary="updateDocumento", * tags={"Documento"}, * description="Update Documento", * @OA\Parameter( * name="id", * description="id of Documento", * @OA\Schema( * type="integer" * ), * required=true, * in="path" * ), * @OA\RequestBody( * required=true, * @OA\MediaType( * mediaType="application/x-www-form-urlencoded", * @OA\Schema( * type="object", * required={""}, * @OA\Property( * property="name", * description="desc", * type="string" * ) * ) * ) * ), * @OA\Response( * response=200, * description="successful operation", * @OA\Schema( * type="object", * @OA\Property( * property="success", * type="boolean" * ), * @OA\Property( * property="data", * ref="#/definitions/Documento" * ), * @OA\Property( * property="message", * type="string" * ) * ) * ) * ) */ public function update($id, UpdateDocumentoAPIRequest $request) { $input = $request->all(); /** @var Documento $documento */ $documento = $this->documentoRepository->find($id); if (empty($documento)) { return $this->sendError('Documento not found'); } $documento = $this->documentoRepository->update($input, $id); return $this->sendResponse($documento->toArray(), 'Documento updated successfully'); } /** * @param int $id * @return Response * * @OA\Delete( * path="/documentos/{id}", * summary="deleteDocumento", * tags={"Documento"}, * description="Delete Documento", * @OA\Parameter( * name="id", * description="id of Documento", * @OA\Schema( * type="integer" * ), * required=true, * in="path" * ), * @OA\Response( * response=200, * description="successful operation", * @OA\Schema( * type="object", * @OA\Property( * property="success", * type="boolean" * ), * @OA\Property( * property="data", * type="string" * ), * @OA\Property( * property="message", * type="string" * ) * ) * ) * ) */ public function destroy($id) { /** @var Documento $documento */ $documento = $this->documentoRepository->find($id); if (empty($documento)) { return $this->sendError('Documento not found'); } $documento->delete(); return $this->sendSuccess('Documento deleted successfully'); } }
package com.etech.controller; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.etech.entity.Tshopuser; import com.etech.service.EtechService; import com.etech.variable.Variables; import com.etech.webutil.Brower; import com.etech.webutil.WebServiceValidCode; import com.etech.webutil.WebServiceValidCodeForFindPassword; @Controller public class ControllerRegisterOne { private static final Log log = LogFactory.getLog(ControllerRegisterOne.class); @Resource private EtechService etechService; @RequestMapping(value="/validatePhoneNumber") public @ResponseBody String validateMobile(String phoneNumber){ log.debug("current register phoneNumber:"+phoneNumber); // 根据手机号查找该用户是否被注册 Tshopuser shopuser = (Tshopuser)etechService.findObject(Tshopuser.class, Variables.username, phoneNumber); // 该手机号被注册 if(!StringUtils.isEmpty(shopuser)){ return "false"; } // 该手机号未被注册 return "true"; } @RequestMapping(value="/validatePhoneNumber2") public @ResponseBody String validateMobile2(String phoneNumber){ log.debug("current register phoneNumber:"+phoneNumber); // 根据手机号查找该用户是否被注册 Tshopuser shopuser = (Tshopuser)etechService.findObject(Tshopuser.class, Variables.username, phoneNumber); // 该手机号被注册 if(!StringUtils.isEmpty(shopuser)){ return "<script>parent.document.getElementById('returnValue_pn').value=false;</script>"; } // 该手机号未被注册 return "<script>parent.document.getElementById('returnValue_pn').value=true;</script>"; } /**Begin Author:wuqiwei Data:2014-07-15 AddReason:获取手机验证码*/ @RequestMapping(value="/generateValidCode") public void generateValidCode(String phoneNumber,HttpSession session,ServletResponse response){ log.debug("current phoneNumber:"+phoneNumber); String validCode = WebServiceValidCode.getCode(phoneNumber); log.debug("validCode:"+validCode); session.setAttribute(Variables.validCode, validCode); Map<String, Object> map=new HashMap<String, Object>(); map.put("returnCode", validCode); Brower.outJson(map, response); } /**End Author:wuqiwei Data:2014-07-15 AddReason:获取手机验证码*/ /** * findPassword * @param phoneNumber * @param session * @param response */ @RequestMapping(value="/generateValidCodeTwo") public void generateValidCode2(String phoneNumber,HttpSession session,ServletResponse response){ log.debug("current phoneNumber:"+phoneNumber); String validCode = WebServiceValidCodeForFindPassword.getCode(phoneNumber); log.debug("validCode:"+validCode); session.setAttribute(Variables.validCode, validCode); Map<String, Object> map=new HashMap<String, Object>(); map.put("returnCode", validCode); Brower.outJson(map, response); } //注册验证码 @RequestMapping(value="/validateNumberCode") public @ResponseBody String validateNumberCode(String numberCode,HttpSession session){ String sessionCode = (String)session.getAttribute(Variables.validCode); //response.addHeader("Access-Control-Allow-Origin","*"); log.debug("input valid code:"+numberCode+" session Valid code:"+sessionCode); // 验证码不匹配 if (sessionCode != null) { if(!sessionCode.equals(numberCode)){ return "false"; } }else { return "false"; } return "true"; } /** * 找回密码验证码 */ /**Begin Author:wuqiwei Data:2014-07-15 AddReason:验证电话验证码是否一致*/ @RequestMapping(value="/validateNumberCode2") public @ResponseBody String validateNumberCode2(String numberCode,HttpSession session){ String sessionCode = (String)session.getAttribute(Variables.validCode); //response.addHeader("Access-Control-Allow-Origin","*"); log.debug("input valid code:"+numberCode+" session Valid code:"+sessionCode); // 验证码不匹配 if (sessionCode != null) { if(!sessionCode.equals(numberCode)){ return "<script>parent.document.getElementById('returnValue').value=false;</script>"; } }else { return "<script>parent.document.getElementById('returnValue').value=false;</script>"; } return "<script>parent.document.getElementById('returnValue').value=true;</script>"; } /**End Author:wuqiwei Data:2014-07-15 AddReason:验证电话验证码是否一致*/ /**Begin Author:wuqiwei Data:2014-07-15 AddReason:表单验证通过后,将该保存到数据库*/ @RequestMapping(value="/dealRegister") public void dealRegister(Tshopuser shopuser,HttpSession session,ServletResponse response){ log.debug("current register phoneNumber:"+shopuser.getPhoneNumber()); shopuser.setUserName(shopuser.getPhoneNumber()); // 密码md5加密 String password=DigestUtils.md5Hex(shopuser.getPassword()); shopuser.setPassword(password); shopuser.setScore(0); shopuser.setGrade((short)1); shopuser.setGender(Variables.man); shopuser.setPhoneNumber(shopuser.getPhoneNumber()); // 创建时间 shopuser.setAddTime(new Timestamp(System.currentTimeMillis())); shopuser.setState((short)Variables.reviewing); shopuser.setLoginCount(1); // 没有注册店铺 shopuser.setDefaultShopId(Variables.unRegister); etechService.saveOrUpdate(shopuser); session.setAttribute(Variables.sessionUser, shopuser); Brower.redirect("/register2.jhtml", response); } @RequestMapping(value="/register") public String registerView(){ return "/WEB-INF/register.jsp"; } }
<h1>正则表达式定义 </h1> <p>正则表达式(regular expression)描述了一种字符串匹配的模式,可以用来检查一个串是否含有某种子串、将匹配的子串做替换或者从某个串中取出符合某个条件的子串等。</p> <p>列目录时, dir *.txt或ls *.txt中的*.txt就不是一个正则表达式,因为这里*与正则式的*的含义是不同的。 <br /> 正则表达式是由普通字符(例如字符 a 到 z)以及特殊字符(称为元字符)组成的文字模式。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配。</p> <p>3.1 普通字符 <br /> 由所有那些未显式指定为元字符的打印和非打印字符组成。这包括所有的大写和小写字母字符,所有数字,所有标点符号以及一些符号。 </p> <p>3.2 非打印字符 字符 含义 <br /> <br /> \S 匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。 <br /> \s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。<br /> \f 匹配一个换页符。等价于 \x0c 和 \cL。 <br /> \n 匹配一个换行符。等价于 \x0a 和 \cJ。 <br /> \r 匹配一个回车符。等价于 \x0d 和 \cM。 <br /> \t 匹配一个制表符。等价于 \x09 和 \cI。 <br /> \v 匹配一个垂直制表符。等价于 \x0b 和 \cK。 <br /> \cx 匹配由x指明的控制字符。例如, \cM 匹配一个 Control-M 或回车符。x 的值必须为 A-Z 或 a-z 之一。否则,将 c 视为一个原义的 'c' 字符。 </p> <p>3.3 特殊字符</p> <p> 所谓特殊字符,就是一些有特殊含义的字符,如上面说的"*.txt"中的*,简单的说就是表示任何字符串的意思。如果要查找文件名中有*的文件,则需要对*进行转义,即在其前加一个\。ls \*.txt。正则表达式有以下特殊字符。 </p> <p> 特别字符 说明 </p> <p> 以下顺序即为操作符的运算优先级。</p> <p> 1、转义符<br /> <特殊的特殊字符‘\’><br /> \ 将下一个字符标记为或特殊字符、或原义字符、或向后引用、或八进制转义符。例如, 'n' 匹配字符 'n'。'\n' 匹配换行符。序列 '\\' 匹配 "\",而 '\(' 则匹配 "("。</p> <p> 2、圆括号和方括号<br /> ( 标记 “子表达式” 的开始和结束位置。子表达式可以获取供以后使用。要匹配这些字符,请使用 \( 和 \)。 <br /> [ 标记 “中括号表达式” 的开始。要匹配 [,请使用 \[。 <br /> <br /> 3、限定符<br /> * 匹配前面的子表达式零次或多次。要匹配 * 字符,请使用 \*。 <br /> + 匹配前面的子表达式一次或多次。要匹配 + 字符,请使用 \+。 <br /> ? 匹配前面的子表达式零次或一次,或指明一个非贪婪限定符。要匹配 ? 字符,请使用 \?。 <br /> { 标记 “限定符表达式” 的开始。要匹配 {,请使用 \{。 </p> <p> 4、位置和顺序 <br /> ^ 匹配输入字符串的开始位置,除非在方括号表达式中使用,此时它表示不接受该字符集合。要匹配 ^ 字符本身,请使用 \^。 <br /> $ 匹配输入字符串的结尾位置。如果设置了 RegExp 对象的 Multiline 属性,则 $ 也匹配 '\n' 或 '\r'。要匹配 $ 字符本身,请使用 \$。 </p> <p> 5、“或”操作<br /> | 指明两项之间的一个选择。要匹配 |,请使用 \|。 </p> <p>   构造正则表达式的方法和创建数学表达式的方法一样。也就是用多种元字符与操作符将小的表达式结合在一起来创建更大的表达式。正则表达式的组件可以是单个的字符、字符集合、字符范围、字符间的选择或者所有这些组件的任意组合。 <br />  </p> <p>3.4 限定符</p> <p>    限定符用来指定正则表达式的一个给定组件必须要出现多少次才能满足匹配。有*或+或?或{n}或{n,}或{n,m}共6种。<br /> *、+和?限定符都是贪婪的,因为它们会尽可能多的匹配文字,只有在它们的后面加上一个?就可以实现非贪婪或最小匹配。<br />    正则表达式的限定符有:<br />   </p> <p> 字符 描述 <br /> * 匹配前面的子表达式零次或多次。例如,zo* 能匹配 "z" 以及 "zoo"。* 等价于{0,}。 <br /> + 匹配前面的子表达式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。 <br /> ? 匹配前面的子表达式零次或一次。例如,"do(es)?" 可以匹配 "do" 或 "does" 中的"do" 。? 等价于 {0,1}。 <br /> {n} n 是一个非负整数。匹配确定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的两个o。<br /> {n,} n 是一个非负整数。至少匹配n 次。例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等价于<br /> 'o+'。'o{0,}' 则等价于 'o*'。 <br /> {n,m} m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。例如,"o{1,3}" 将匹配 "fooooood" 中的前三个 o。'o{0,1}' 等价于 'o?'。请注意在逗号和两个数之间不能有空格。 </p> <p>3.5 定位符</p> <p>  用来描述字符串或单词的边界,^和$分别指字符串的开始与结束,\b描述单词的前或后边界,\B表示非单词边界。不能对定位符使用限定符。 </p> <p>3.6 选择</p> <p> 用圆括号将所有选择项括起来,相邻的选择项之间用|分隔。但用圆括号会有一个副作用,是相关的匹配会被缓存,此时可用?:放在第一个选项前来消除这种副作用。<br /> 其中?:是非捕获元之一,还有两个非捕获元是?=和?!,这两个还有更多的含义,前者为正向预查,在任何开始匹配圆括号内的正则表达式模式的位置来匹配搜索字符串,后者为负向预查,在任何开始不匹配该正则表达式模式的位置来匹配搜索字符串。 </p> <p>3.7 后向引用</p> <p>   对一个正则表达式模式或部分模式两边添加圆括号将导致相关匹配存储到一个临时缓冲区中,所捕获的每个子匹配都按照在正则表达式模式中从左至右所遇到的内容存储。存储子匹配的缓冲区编号从 1 开始,连续编号直至最大 99 个子表达式。每个缓冲区都可以使用 '\n' 访问,其中 n 为一个标识特定缓冲区的一位或两位十进制数。<br />    可以使用非捕获元字符 '?:', '?=', or '?!' 来忽略对相关匹配的保存。 </p>
import { Outlet } from "react-router-dom" import { RootList } from "../../components/RootList" import styled from "styled-components" import { getContacts } from "../../utils/ContactService"; import React, { useEffect, useState } from 'react' import useDebounce from "../../hooks/use-debounce"; const Container = styled.div` width: 100%; display: flex; align-items: flex-start; ` export const Home = ()=>{ const [contacts, setContacts] = useState(getContacts()) const [searchValue, setSearchValue] = useState("") const deb = useDebounce(searchValue, 300) const updateContacts = () => { setContacts(sortList(getContacts())) } useEffect(()=>{ },[contacts]) const concatNames = (first_name, last_name) =>{ return String(first_name).concat(" ", last_name).toLowerCase() } const sortList = (list) =>{ list.sort((current, next)=>{ if(concatNames(current.first_name, current.last_name)> concatNames(next.first_name, next.last_name)){ return 1 } if(concatNames(current.first_name, current.last_name) < concatNames(next.first_name, next.last_name) ){ return -1 } return 0 }) return list } function searchList (){ if(searchValue !== "" && contacts){ return sortList(contacts) .filter(contact => concatNames(contact.first_name, contact.last_name).toLocaleLowerCase().includes(String(deb).toLowerCase())) }else if(contacts){ return sortList(contacts) } } return( <> <Container> <RootList contacts={searchList()} searchValue={searchValue} setSearchValue={setSearchValue}/> <Outlet context={{ searchList, updateContacts }}/> </Container> </> ) }
import React, { useEffect, useState } from 'react'; import { addToDb, getShoppingCart } from '../../utilities/fakedb'; import Cart from '../Cart/Cart'; import Product from '../product/Product'; import './Shop.css' const Shop = () => { let [products, setProducts] = useState([]) let [cart, setCart] = useState([]) useEffect(() => { fetch('products.json') .then(res => res.json()) .then(data => setProducts(data)) }, []) useEffect(() => { const storedCard = getShoppingCart() let savecart = [] for (let id in storedCard) { // console.log('id', id) let saveProducts = products.find(product => product.id === id) console.log(saveProducts) if (saveProducts) { let quantity = storedCard[id] saveProducts.quantity = quantity savecart.push(saveProducts) } setCart(savecart) } // console.log(storedCard) }, [products]) function handelId(product) { // console.log('added item',product, cart) let newCart = [...cart, product] setCart(newCart) addToDb(product.id) } return ( <div className='shop-container'> <div className="products-container"> { products.map(product => <Product key={product.id} product={product} handelId={handelId} ></Product>) } </div> <div className='summary'> <Cart carts={cart}></Cart> </div> </div> ); }; export default Shop;
import React, { useState } from 'react' import { TouchableOpacity } from 'react-native' import { SocialIcon } from 'react-native-elements'; import * as WebBrowser from 'expo-web-browser'; import * as Google from 'expo-auth-session/providers/google'; WebBrowser.maybeCompleteAuthSession(); type GoogleButtonProps = { title: string, loading: boolean, onSucess: Function, onError: Function, onStart: Function onEnd: Function } export function GoogleButton(props : GoogleButtonProps) { const [request, response, promptAsync] = Google.useIdTokenAuthRequest({ expoClientId: '298374665465-8pqbsk0j8taauo015v0otjias4d9bd6r.apps.googleusercontent.com', // iosClientId: 'GOOGLE_GUID.apps.googleusercontent.com', // androidClientId: 'GOOGLE_GUID.apps.googleusercontent.com', webClientId: '298374665465-7a45vnk7rtgluiop788juljjhlqbaqpl.apps.googleusercontent.com', }); const [hasClicked, setClicked] = useState<boolean>(false); React.useEffect(() => { if (response?.type === 'success') { props.onSucess(response.params.id_token) props.onEnd(); } else { if (hasClicked) { props.onError(); props.onEnd(); } } }, [response]); return ( <TouchableOpacity onPress={() => { setClicked(true); props.onStart(); promptAsync(); }}> <SocialIcon title={props.title} type='google' button // light onPress={() => { setClicked(true); props.onStart(); promptAsync(); }} loading={props.loading} disabled={!request} /> </TouchableOpacity> ); }
import { Body, Link, Container, Head, Heading, Hr, Html, Img, Preview, Section, Tailwind, Text, } from "@react-email/components"; import { DUB_LOGO } from "../lib/constants"; export default function DomainDeleted({ domain = "dub.sh", projectName = "Dub", projectSlug = "dub", }: { domain: string; projectName: string; projectSlug: string; }) { return ( <Html> <Head /> <Preview>Domain Deleted</Preview> <Tailwind> <Body className="mx-auto my-auto bg-white font-sans"> <Container className="mx-auto my-10 max-w-[500px] rounded border border-solid border-gray-200 px-10 py-5"> <Section className="mt-8"> <Img src={DUB_LOGO} width="40" height="40" alt="Dub" className="mx-auto my-0" /> </Section> <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black"> Domain Deleted </Heading> <Text className="text-sm leading-6 text-black"> Your domain <code className="text-purple-600">{domain}</code> for your Dub project{" "} <Link href={`https://app.dub.sh/${projectSlug}`} className="font-medium text-blue-600 no-underline" > {projectSlug}↗ </Link>{" "} has been invalid for 30 days. As a result, it has been deleted from Dub. </Text> <Text className="text-sm leading-6 text-black"> If you would like to restore the domain, you can easily create it again on Dub with the link below. </Text> <Section className="my-8 text-center"> <Link className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline" href={`https://app.dub.sh/${projectSlug}/domains`} > Add a domain </Link> </Section> <Text className="text-sm leading-6 text-black"> If you did not want to keep using this domain on Dub anyway, you can simply ignore this email. </Text> <Hr className="mx-0 my-6 w-full border border-gray-200" /> <Text className="text-[12px] leading-6 text-gray-500"> This email was intended for members of the{" "} <span className="text-black">{projectName}</span> project on Dub.If you were not expecting this email, you can ignore this email. If you are concerned about your account's safety, please reply to this email to get in touch with us. </Text> </Container> </Body> </Tailwind> </Html> ); }
import FuelSDK try: debug = False stubObj = FuelSDK.ET_Client(False, debug) NewListName = "PythonSDKList" # Create List print(">>> Create List") postList = FuelSDK.ET_List() postList.auth_stub = stubObj postList.props = { "ListName": NewListName, "Description": "This list was created with the PythonSDK", "Type": "Private", } postResponse = postList.post() print("Post Status: " + str(postResponse.status)) print("Code: " + str(postResponse.code)) print("Message: " + str(postResponse.message)) print("Result Count: " + str(len(postResponse.results))) print("Results: " + str(postResponse.results)) # Make sure the list created correctly and the 1st dict in it has a NewID... if postResponse.status and "NewID" in postResponse.results[0]: newListID = postResponse.results[0]["NewID"] # Retrieve newly created List by ID print(">>> Retrieve newly created List") getList = FuelSDK.ET_List() getList.auth_stub = stubObj getList.props = [ "ID", "PartnerKey", "CreatedDate", "ModifiedDate", "Client.ID", "Client.PartnerClientKey", "ListName", "Description", "Category", "Type", "CustomerKey", "ListClassification", "AutomatedEmail.ID", ] getList.search_filter = { "Property": "ID", "SimpleOperator": "equals", "Value": newListID, } getResponse = getList.get() print("Retrieve Status: " + str(getResponse.status)) print("Code: " + str(getResponse.code)) print("Message: " + str(getResponse.message)) print("MoreResults: " + str(getResponse.more_results)) print("Results Length: " + str(len(getResponse.results))) print("Results: " + str(getResponse.results)) # Update List print(">>> Update List") patchSub = FuelSDK.ET_List() patchSub.auth_stub = stubObj patchSub.props = {"ID": newListID, "Description": "I updated the description"} patchResponse = patchSub.patch() print("Patch Status: " + str(patchResponse.status)) print("Code: " + str(patchResponse.code)) print("Message: " + str(patchResponse.message)) print("Result Count: " + str(len(patchResponse.results))) print("Results: " + str(patchResponse.results)) # Retrieve List that should have description updated print(">>> Retrieve List that should have description updated ") getList = FuelSDK.ET_List() getList.auth_stub = stubObj getList.props = [ "ID", "PartnerKey", "CreatedDate", "ModifiedDate", "Client.ID", "Client.PartnerClientKey", "ListName", "Description", "Category", "Type", "CustomerKey", "ListClassification", "AutomatedEmail.ID", ] getList.search_filter = { "Property": "ID", "SimpleOperator": "equals", "Value": newListID, } getResponse = getList.get() print("Retrieve Status: " + str(getResponse.status)) print("Code: " + str(getResponse.code)) print("Message: " + str(getResponse.message)) print("MoreResults: " + str(getResponse.more_results)) print("Results Length: " + str(len(getResponse.results))) print("Results: " + str(getResponse.results)) # Delete List print(">>> Delete List") deleteSub = FuelSDK.ET_List() deleteSub.auth_stub = stubObj deleteSub.props = {"ID": newListID} deleteResponse = deleteSub.delete() print("Delete Status: " + str(deleteResponse.status)) print("Code: " + str(deleteResponse.code)) print("Message: " + str(deleteResponse.message)) print("Results Length: " + str(len(deleteResponse.results))) print("Results: " + str(deleteResponse.results)) # Retrieve List to confirm deletion print(">>> Retrieve List to confirm deletion") getList = FuelSDK.ET_List() getList.auth_stub = stubObj getList.props = [ "ID", "PartnerKey", "CreatedDate", "ModifiedDate", "Client.ID", "Client.PartnerClientKey", "ListName", "Description", "Category", "Type", "CustomerKey", "ListClassification", "AutomatedEmail.ID", ] getList.search_filter = { "Property": "ID", "SimpleOperator": "equals", "Value": newListID, } getResponse = getList.get() print("Retrieve Status: " + str(getResponse.status)) print("Code: " + str(getResponse.code)) print("Message: " + str(getResponse.message)) print("MoreResults: " + str(getResponse.more_results)) print("Results Length: " + str(len(getResponse.results))) print("Results: " + str(getResponse.results)) except Exception as e: print("Caught exception: " + str(e.message))
import { faCartShopping, faHeart, faSearch } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Link } from 'react-router-dom'; import { useCart } from '../hooks/useCart'; import { useAuthContext } from '../hooks/useAuthContext'; import styled from 'styled-components'; const formatCurrency = require('format-currency'); const ProductInfo = styled.div` position: absolute; bottom: 4px; left: 4px; text-align: start; z-index: 20; `; const Info = styled.div` width: 100%; height: 100%; position: absolute; top: 0; left: 0; background-color: rgba(0, 0, 0, 0.2); z-index: 3; display: flex; align-items: center; justify-content: center; opacity: 0; transition: all ease 0.5s; `; const Container = styled.div` margin: 5px; min-width: 280px; height: 350px; display: flex; align-items: center; justify-content: center; background-color: #f5fbfd; position: relative; &:hover ${Info} { opacity: 1; } `; const Circle = styled.div` width: 200px; height: 200px; border-radius: 50%; background-color: white; position: absolute; `; const Image = styled.img` height: 75%; z-index: 2; `; const Icon = styled.div` width: 40px; height: 40px; border-radius: 50%; background-color: white; display: flex; align-items: center; justify-content: center; margin: 10px; transition: all 0.5s ease; color: black; cursor: pointer; &:hover { background-color: #e9f5f5; transform: scale(1.1); } `; export default function ProductItem({ item }) { const { postCart } = useCart(); const { user } = useAuthContext(); const handleAddCart = async () => { await postCart(user._id, item.name, item._id, item.image[0], item.configuration[0].Size[0].price); console.log('post cart successfully'); }; return ( <Container> <Circle /> <Image src={item.image} /> <Link to={`/detail/${item._id}`}> <ProductInfo> <em style={{ fontWeight: '800' }}>{item.name}</em> <br /> <em style={{ color: '#d0021c', fontWeight: '800' }}> {formatCurrency(item.price)} <i className='fa-solid fa-dollar-sign' style={{ marginLeft: '4px' }}></i> </em> </ProductInfo> </Link> <Info> <Icon> <FontAwesomeIcon icon={faCartShopping} onClick={handleAddCart} /> </Icon> <Icon> <FontAwesomeIcon icon={faSearch} /> </Icon> <Icon> <FontAwesomeIcon icon={faHeart} /> </Icon> </Info> </Container> ); }
import "@testing-library/jest-dom"; import { render, fireEvent } from "@testing-library/react"; import CardProducts from "./CardProducts"; describe("CardProducts component", () => { const mockProps = { urlImage: "/path/to/image.png", name: "Product Name", price: "$10.00", description: "Product Description", onclick: jest.fn(), }; it("renders product details correctly", () => { const { getByText } = render(<CardProducts {...mockProps} />); const nameElement = getByText(mockProps.name); const priceElement = getByText(mockProps.price); const descriptionElement = getByText(mockProps.description); expect(nameElement).toBeInTheDocument(); expect(priceElement).toBeInTheDocument(); expect(descriptionElement).toBeInTheDocument(); }); it("calls onclick function when button is clicked", () => { const { getByText } = render(<CardProducts {...mockProps} />); const button = getByText("COMPRAR"); fireEvent.click(button); expect(mockProps.onclick).toHaveBeenCalled(); }); });
<script setup lang="ts"> import { ArrowDown } from '@element-plus/icons-vue' const props = defineProps<{ isActive?: boolean plain?: boolean name?: string disabled?: boolean click?: MouseEvent }>() const emits = defineEmits<{ click: [ev: MouseEvent] }>() const dropdownVisible = ref(false) const toggleDropdown = () => { dropdownVisible.value = !dropdownVisible.value } const closeDropdown = () => { dropdownVisible.value = false } const dropdownArrowRef = ref<HTMLElement>() const dropdownRef = ref<HTMLElement>() useEventListener('click', (ev) => { if (!dropdownVisible.value) return const path = ev.composedPath() for (const key in path) { const ele = path[key] if (ele === dropdownArrowRef.value || ele === dropdownRef.value) return } closeDropdown() }) const handleClick = (ev: MouseEvent) => { if (props.disabled) return emits('click', ev) } </script> <template> <div class="tool-item" :class="{ 'has-dropdown': Boolean($slots.dropdown), 'is-active': isActive, 'dropdown-open': dropdownVisible, plain, }" > <div class="item-content" @click="handleClick"> <div class="flex-1 w-full grid place-items-center"> <slot name="default" /> </div> <div v-if="name" class="item-name"> {{ name }} </div> </div> <div v-if="$slots.dropdown" ref="dropdownArrowRef" class="item-dropdown-icon" @click="toggleDropdown"> <el-icon class="scale-90 transition-all" :size="12" :class="dropdownVisible ? 'rotate-180' : ''" color="var(--el-text-color-regular)" > <ArrowDown /> </el-icon> </div> <div ref="dropdownRef" class="item-dropdown-content" :class="{ 'is-hidden': !dropdownVisible, }" > <slot name="dropdown" :close="closeDropdown" /> </div> </div> </template> <style scoped> .tool-item { --cursor: auto; --item-bg: transparent; --item-bg--hover: transparent; --item-bg--active: transparent; --radius: 4px; --state-color: unset; --content-radius: var(--radius) var(--radius) var(--radius) var(--radius); height: 32px; display: flex; transition: all ease 150ms; color: var(--el-color-info); user-select: none; line-height: 1; position: relative; overflow: visible; &.is-active { color: var(--el-color-primary); --state-color: var(--el-color-primary); } &.dropdown-open { --item-bg: var(--el-fill-color-darker); } &.has-dropdown { --content-radius: 4px 0 0 4px; } &:not(.plain) { --cursor: pointer; --item-bg--hover: var(--el-fill-color-dark); --item-bg--active: var(--el-fill-color-darker); } } .item-content { cursor: var(--cursor); min-width: 32px; display: flex; flex-direction: column; border-radius: var(--content-radius); &:hover { background: var(--item-bg--hover); color: var(--state-color, var(--el-text-color-regular)); } &:active { background: var(--item-bg--active); } } .item-name { font-size: 12px; scale: 0.8; width: 100%; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .item-dropdown-icon { cursor: pointer; width: 14px; overflow: visible; display: grid; place-items: center; border-radius: 0 var(--radius) var(--radius) 0; background: var(--item-bg); &:hover { background: var(--item-bg--hover); } &:active { background: var(--item-bg--active); } } .item-dropdown-content { position: absolute; left: 0; top: 100%; z-index: 1; background: #FFF; &.is-hidden { content-visibility: hidden; @supports not (content-visibility: hidden) { display: none; } } } </style>
"use client" import * as z from 'zod' import {zodResolver} from "@hookform/resolvers/zod" import { useForm } from 'react-hook-form' import { useState } from 'react' import{toast} from 'react-hot-toast' import { Modal } from "@/components/ui/modal" import { useStoreModal } from "@/hooks/use-store-modal" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../ui/form' import { Input } from '../ui/input' import { Button } from '../ui/button' import axios from 'axios' const formSchema = z.object({ name: z.string().min(1), }) export const StoreModal = () => { const storeModal = useStoreModal(); const [loading, setLoading]= useState(false); const onSubmit = async (values:z.infer<typeof formSchema>)=>{ try { setLoading(true); const response = await axios.post('/api/stores', values); toast.success("Store created.") window.location.assign(`/${response.data.id}`); } catch (error) { toast.error("Something went wrong") } finally { setLoading(false); } } const form = useForm<z.infer <typeof formSchema>>({ resolver: zodResolver(formSchema), defaultValues:{ name: "", }, }); return( <Modal isOpen={storeModal.isOpen} onClose={storeModal.onClose} title="Create store" description="Add a new store to manage products and categories"> <div className=''> <div className=' space-y-4 py-2 pb-4'> <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)}> <FormField control={form.control} name="name" render={({field})=>( <FormItem> <FormLabel>Name</FormLabel> <FormControl> <Input placeholder='E-Commerce' {...field} disabled={loading}/> </FormControl> <FormMessage/> </FormItem> )} /> <div className='pt-6 space-x-2 flex items-center justify-end w-full'> <Button disabled={loading} variant='outline' onClick={storeModal.onClose}> Cancel </Button> <Button type='submit' disabled={loading} > Continue </Button> </div> </form> </Form> </div> </div> </Modal> ) }
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import '../utils/light_theme_colors.dart'; abstract class AppTextStyle { ///Font Size static const double small_font_size = 11.0; static const double xSmall_font_size = 12.0; static const double regular_font_size = 13.0; static const double xRegular_font_size = 14.0; static const double medium_font_size = 16.0; static const double xMedium_font_size = 18.0; static const double large_font_size = 20.0; static const double xLarge_font_size = 32.0; static TextStyle small_red = GoogleFonts.tajawal( textStyle: TextStyle(color: Colors.redAccent, fontSize: small_font_size)); static TextStyle small_white = GoogleFonts.tajawal(textStyle: TextStyle(color: Colors.white, fontSize: 9)); static TextStyle xMediumWhiteStyle = GoogleFonts.tajawal(textStyle: TextStyle(color: Colors.white, fontSize: xMedium_font_size)); static TextStyle xMediumWhiteBoldStyle = GoogleFonts.tajawal(textStyle: TextStyle(color: Colors.white, fontSize: xMedium_font_size, fontWeight: FontWeight.bold)); static TextStyle xLargeWhiteBoldStyle = GoogleFonts.tajawal(textStyle: TextStyle(color: Colors.white, fontSize: xLarge_font_size, fontWeight: FontWeight.bold)); static TextStyle xLargeWhiteBold700Style = GoogleFonts.tajawal(textStyle: TextStyle(color: Colors.white, fontSize: xLarge_font_size, fontWeight: FontWeight.w700)); static TextStyle xMediumGreyStyle = GoogleFonts.tajawal(textStyle: TextStyle(color: Color(0xFF9D9D9D), fontSize: xMedium_font_size)); static TextStyle mediumGreyStyle = GoogleFonts.tajawal(textStyle: TextStyle(color: Color(0xFF9D9D9D), fontSize: medium_font_size)); static TextStyle largeGreyBoldStyle = GoogleFonts.tajawal(textStyle: TextStyle(color: Color(0xFF9D9D9D), fontSize: large_font_size, fontWeight: FontWeight.bold)); static TextStyle mediumDarkWithOpacityStyle = GoogleFonts.tajawal(textStyle: TextStyle( color: LightThemeColors.textDarkColor.withOpacity(0.5), fontSize: 16, fontWeight: FontWeight.bold, )); static TextStyle mediumSecondaryWithoutOpacityStyle = GoogleFonts.tajawal(textStyle: TextStyle( color: LightThemeColors.secondaryHeaderColor, fontSize: 16, fontWeight: FontWeight.bold, )); static TextStyle mediumSecondaryWithoutOpacityStyleWith500Bold = GoogleFonts.tajawal(textStyle: TextStyle( color: LightThemeColors.secondaryHeaderColor, fontSize: 18, fontWeight: FontWeight.w500, )); static TextStyle mediumSecondaryWithOpacityStyle = GoogleFonts.tajawal(textStyle: TextStyle( color: LightThemeColors.secondaryHeaderColor.withOpacity(0.5), fontSize: 16, fontWeight: FontWeight.bold, )); static TextStyle mediumPrimaryWithOpacityStyle = GoogleFonts.tajawal(textStyle: TextStyle( color: LightThemeColors.primaryColor, fontSize: 16, fontWeight: FontWeight.bold, )); static TextStyle largeDarkStyle = GoogleFonts.tajawal(textStyle: TextStyle( color: LightThemeColors.textDarkColor, fontSize: 16, fontWeight: FontWeight.bold, )); static TextStyle largePrimaryWithShadowStyle(context) => GoogleFonts.tajawal(textStyle: TextStyle( color: LightThemeColors.colorBlueText, fontSize: 28, fontWeight: FontWeight.bold, shadows: [Shadow(color: Colors.grey[50]!, offset: Offset(0,2))] )); static TextStyle largeSecondaryWithShadowStyle(context) => GoogleFonts.tajawal(textStyle: TextStyle( color: LightThemeColors.secondaryHeaderColor, fontSize: 28, fontWeight: FontWeight.bold, shadows: [Shadow(color: Colors.grey[50]!, offset: Offset(0,2))] )); static TextStyle largeSecondaryStyle(context) => GoogleFonts.tajawal(textStyle: TextStyle( color: LightThemeColors.secondaryHeaderColor, fontSize: 28, fontWeight: FontWeight.bold, )); static TextStyle largeWhiteStyle(context) => GoogleFonts.tajawal(textStyle: TextStyle( color: Theme.of(context).scaffoldBackgroundColor, fontSize: 28, fontWeight: FontWeight.bold, )); }
import { Card } from 'antd'; import Complaint from '../Complaint'; import './index.css' import { useEffect, useState } from 'react'; import { User } from '../../../interfaces/user'; import { UsersDto } from '../../../interfaces/usersDto'; import { AuthJWT } from '../../../interfaces/auth'; import { accounts } from '../../../lib/accounts'; import { useCookies } from 'react-cookie'; import { complaintsLib } from '../../../lib/complaints'; const { getAllUsers } = accounts(); const { getAllComplaints } = complaintsLib(); export default function AllComplaints() { const [users, setUsers] = useState<UsersDto>(); const [listOfComplaints, setListOfComplaints] = useState<any>(); const [loaded, setLoaded] = useState(false); const [cookies, setCookie] = useCookies(); async function loadComplaints() { const rawComplaints = await getAllComplaints(cookies.token as string); let companiesWithComplaints: any = {}; for (const complaint of rawComplaints) { if (!companiesWithComplaints[complaint.company.name]) { companiesWithComplaints[complaint.company.name] = [] } companiesWithComplaints[complaint.company.name].push(complaint) } console.log(companiesWithComplaints) setListOfComplaints(companiesWithComplaints) } async function loadUsers() { const response = await getAllUsers(cookies.token); setUsers(response); } useEffect(() => { loadUsers(); }, []) useEffect(() => { if (listOfComplaints) { setLoaded(true); } }, [listOfComplaints]) useEffect(() => { loadComplaints(); }, []) useEffect(() => { if (users !== undefined) { setLoaded(true); } }, [users]) return ( <div className='all-accounts'> <Card title={'All Complaints'}> { loaded && listOfComplaints && Object.keys(listOfComplaints).map((company) => <Complaint company={company} children={listOfComplaints[company]} onClose={loadComplaints}/>) } </Card> </div> ) }
import React from 'react'; import s from './formControl.module.css'; interface FormControlProps { children: React.ReactNode; meta: { touched: boolean; error: string; }; } const FormControl = ({ children, meta, ...props }: FormControlProps) => { const hasError = meta.touched && meta.error; return ( <div className={s.formControl + ' ' + (hasError ? s.error : '')}> <div>{children}</div> {hasError && <span>{meta.error}</span>} </div> ); }; interface TextareaProps { input: { value: string; onChange: (event: React.ChangeEvent<HTMLTextAreaElement>) => void; }; meta: { touched: boolean; error: string; }; }; export const Textarea = ({ input, meta, ...props }: TextareaProps) => { return ( <FormControl meta={meta} {...props}> <textarea className={s.error_textarea} {...input} {...props} /> </FormControl> ); }; interface InputProps { input: { value: string; onChange: (event: React.ChangeEvent<HTMLInputElement>) => void; }; meta: { touched: boolean; error: string; }; }; export const Input = ({ input, meta, ...props }: InputProps) => { return ( <FormControl meta={meta} {...props}> <input className={s.error_textarea} {...input} {...props} /> </FormControl> ); }; // export const Textarea = ({ input, meta, ...props }:TextareaProps) => {// достаем деструктуризацией input meta и хотим все оставшиеся штуки оставить в props // const hasError = meta.touched && meta.error // return ( // <div className={s.formControl + ' '+ (hasError? s.error:'')}> // <div><textarea className={s.error_textarea} {...input} {...props} /></div> // { hasError && <span className={s.error_span}>{meta.error}</span>} // </div> // ); // }; // export const Input = ({ input, meta, ...props }:InputProps) => { // const hasError = meta.touched && meta.error // return ( // <div className={s.formControl + ' '+ (hasError? s.error:'')}> // <div><input className={s.error_textarea} {...input} {...props} /></div> // { hasError && <span className={s.error_span}>{meta.error}</span>} // </div> // ); // }
package functional_programming_and_lambda_expressions.practice_problems.assignment02; import java.util.Arrays; import java.util.Scanner; @FunctionalInterface interface Calc2<T> { T compute(Integer[] array); } public class MainEntry2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("*********Menu*************"); System.out.println("What would you like to do?"); System.out.println("1. Add"); System.out.println("2. Subtract"); System.out.println("3. Multiply"); System.out.println("4. Divide"); int choice = scanner.nextInt(); if (choice == 1){ System.out.println("How many numbers do you want to enter"); int arrayLength = scanner.nextInt(); scanner.nextLine(); Integer[] array = new Integer[arrayLength]; for (int i = 0; i < arrayLength; i++){ array[i] = scanner.nextInt(); } Calc2<Integer> calc = numberArray -> Arrays.stream(array).reduce(0, Integer::sum); System.out.println("The sum of your entered numbers is " + calc.compute(array)); } else if (choice == 2){ System.out.println("Please enter only two numbers"); int arrayLength = 2; Integer[] array = new Integer[arrayLength]; for (int i = 0; i < arrayLength; i++){ array[i] = scanner.nextInt(); } Calc2<Integer> calc = numberArray -> Arrays.stream(array).reduce((x, y) -> array[0] - array[1]).orElse(0); System.out.println("The difference of those two numbers is " + calc.compute(array)); } else if (choice == 3){ System.out.println("How many numbers do you want to enter"); int arrayLength = scanner.nextInt(); scanner.nextLine(); Integer[] array = new Integer[arrayLength]; for (int i = 0; i < arrayLength; i++){ array[i] = scanner.nextInt(); } Calc2<Integer> calc = numberArray -> Arrays.stream(array).reduce(1, Math::multiplyExact); System.out.println("The product of your entered numbers is " + calc.compute(array)); } else if (choice == 4) { System.out.println("Please enter only two numbers"); int arrayLength = 2; scanner.nextLine(); Integer[] array = new Integer[arrayLength]; for (int i = 0; i < arrayLength; i++) { array[i] = scanner.nextInt(); } Calc2<Integer> calc = numberArray -> Arrays.stream(array).reduce((x, y) -> array[0] / array[1]).orElseThrow( () -> new ArithmeticException("Cannot divide by zero") ); System.out.println("The quotient of your entered numbers is " + calc.compute(array)); } else { System.out.println("You entered an INVALID choice"); } } }
/* bzflag * Copyright (c) 1993 - 2009 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef __CUSTOMZONE_H__ #define __CUSTOMZONE_H__ /* interface header */ #include "WorldFileLocation.h" /* system headers */ #include <vector> #include <string> #include <map> /* local implementation headers */ //#include "WorldInfo.h" class WorldInfo; class FlagType; typedef std::vector<std::string> QualifierList; typedef std::map<FlagType*, int> ZoneFlagMap; // type, count class CustomZone : public WorldFileLocation { public: CustomZone(); virtual bool read(const char *cmd, std::istream&); virtual void writeToWorld(WorldInfo*) const; virtual bool usesGroupDef() { return false; } // make a safety zone for all team flags (on the ground) void addFlagSafety(float x, float y, WorldInfo* worldInfo); const QualifierList &getQualifiers() const; const ZoneFlagMap& getZoneFlagMap() const; float getArea() const; void getRandomPoint(fvec3& pt) const; float getDistToPoint(const fvec3& pos) const; public: static const std::string& getFlagIdQualifier(int flagId); static int getFlagIdFromQualifier(const std::string&); static const std::string& getFlagTypeQualifier(FlagType* flagType); static FlagType* getFlagTypeFromQualifier(const std::string&); static const std::string& getFlagSafetyQualifier(int team); static int getFlagSafetyFromQualifier(const std::string&); static const std::string& getPlayerTeamQualifier(int team); static int getPlayerTeamFromQualifier(const std::string&); private: void addZoneFlagCount(FlagType* flagType, int count); private: ZoneFlagMap zoneFlagMap; QualifierList qualifiers; }; inline const QualifierList& CustomZone::getQualifiers() const { return qualifiers; } inline const ZoneFlagMap& CustomZone::getZoneFlagMap() const { return zoneFlagMap; } inline float CustomZone::getArea() const { const float x = (size.x >= 1.0f) ? size.x : 1.0f; const float y = (size.y >= 1.0f) ? size.y : 1.0f; const float z = (size.z >= 1.0f) ? size.z : 1.0f; return (x * y * z); } #endif /* __CUSTOMZONE_H__ */ // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
import { Controller, Get, Post, Body, Patch, Param, Delete, UsePipes, HttpCode } from '@nestjs/common'; import { BannerService } from './banner.service'; import { CreateBannerDto } from './dto/create-banner.dto'; import { UpdateBannerDto } from './dto/update-banner.dto'; import { ValidationPipe } from '../../pipe/validation.pipe'; @Controller('banner') export class BannerController { constructor(private readonly bannerService: BannerService) {} @UsePipes(new ValidationPipe()) @HttpCode(200) @Post('add') async create(@Body() CreateBannerDto: CreateBannerDto) { return await this.bannerService.create(CreateBannerDto); } @Get('list') findAll() { return this.bannerService.findAll(); } @Get(':id') findOne(@Param('id') id: string) { return this.bannerService.findOne(+id); } @Patch(':id') update(@Param('id') id: string, @Body() updateBannerDto: UpdateBannerDto) { return this.bannerService.update(+id, updateBannerDto); } @Delete(':id') remove(@Param('id') id: string) { return this.bannerService.remove(+id); } }
// Types import { componentMap, ComponentType } from "@/maps/componentMap"; // Next import Link from "next/link"; // React import { useEffect, useState } from "react"; const ComponentsBar = () => { const [currentPath, setCurrentPath] = useState<string>(""); useEffect(() => { setCurrentPath(window.location.pathname); }, []); return ( <div className="hidden lg:flex dark:border-gray-800 fixed overflow-y-scroll border-r-[1px] h-[92vh] min-w-[20%] w-[20%] dark:bg-black bg-white mx-auto justify-center align-center p-[10px] float-left"> <div className="mt-[40px] absolute right-10 w-[60%] "> <div className="mb-[20px]"> <div className="pb-[10px]"> <p className="font-semibold dark:text-white text-slate-700"> Layout </p> </div> {componentMap .sort((a, b) => a.title.localeCompare(b.title)) .filter((c) => { return c.type === "layout"; }) .map((component: ComponentType) => ( <div className="mb-[10px]" key={component.id}> <div> {!component.disabled ? ( <Link href={component.href} key={component.id} className={`${ currentPath === component.href && "bg-slate-100 dark:bg-gray-800 rounded-md" } p-[5px] pl-[8px] mb-[5px] dark:text-white text-slate-700 hover:underline flex align-center text-sm items-center`} > <p>{component.title}</p> </Link> ) : ( <div key={component.id} className={`dark:text-slate-500 text-sm text-slate-400 cursor-not-allowed p-[5px] pl-[8px] mb-[8px] hover:underline flex align-center items-center`} > <p>{component.title}</p> </div> )} </div> </div> ))} <div className="mt-[30px] pb-[10px]"> <p className="font-semibold dark:text-white text-slate-700"> Components </p> </div> {componentMap .sort((a, b) => a.title.localeCompare(b.title)) .filter((c) => { return c.type === "component"; }) .map((component: ComponentType) => ( <div className="mb-[10px]" key={component.id}> <div> {!component.disabled ? ( <Link href={component.href} key={component.id} className={`${ currentPath === component.href && "bg-slate-100 dark:bg-gray-800 rounded-md" } p-[5px] pl-[8px] mb-[5px] dark:text-white text-slate-700 hover:underline flex align-center text-sm items-center`} > <p>{component.title}</p> </Link> ) : ( <div key={component.id} className={`dark:text-slate-500 text-sm text-slate-400 cursor-not-allowed p-[5px] pl-[8px] mb-[8px] hover:underline flex align-center items-center`} > <p>{component.title}</p> </div> )} </div> </div> ))} <div className="h-[20px]" /> </div> </div> </div> ); }; export default ComponentsBar;
'use client' import { zodResolver } from "@hookform/resolvers/zod" import { useState } from "react" import { useForm } from "react-hook-form" import * as z from "zod" import '../globals.css' import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Toaster } from "@/components/ui/toaster" import { useToast } from "@/components/ui/use-toast" import { useRouter } from "next/navigation" import { createUser, loginUser } from "../supabase-service" import { userStore } from "../userStore" export default function Page() { const [isLogin, setIsLogin] = useState(true); const { isLoggedIn, setLoggedIn, user, setUser} = userStore(); const { toast } = useToast() const router = useRouter() const loginFormSchema = z.object({ username: z.string().min(5, { message: "username must be at least 5 characters." }).max(50), password: z.string().min(8), confirmPass: z.string().optional() }) .superRefine(({ confirmPass, password }, ctx) => { if (!isLogin && confirmPass !== password) { ctx.addIssue({ path: ["confirmPass"], code: "custom", message: "The passwords did not match" }); } }); const form = useForm<z.infer<typeof loginFormSchema>>({ resolver: zodResolver(loginFormSchema), defaultValues: { username: "", password: "", confirmPass: "" } }) async function login(username: string, password: string) { var response: any = await loginUser(username, password) toast({ title: response?.title, description: response?.description, variant: response?.success ? "default" : "destructive" }) if(response.success) { sessionStorage.setItem('loggedInUser', JSON.stringify(response?.data?.user)) setUser(response?.data?.user) setLoggedIn(true) router.push("/profile") } } async function signUp(username: string, password: string) { var response = await createUser(username, password) toast({ title: response?.title, description: response?.description, variant: response?.success ? "default" : "destructive" }) setIsLogin(true) } async function onSubmit(values: z.infer<typeof loginFormSchema>) { if (isLogin) { // if logging in login(values.username, values.password) } else { // if signing up signUp(values.username, values.password) } } function toggleLogin(): void { setIsLogin(!isLogin); form.reset() } return ( <main className="w-screen h-screen gradient-bg flex flex-col items-center justify-center"> <Toaster /> <div className="p-20 rounded-xl shadow-xl flex flex-col items-center justify-center"> <h1 className="text-4xl mb-12">{isLogin ? "login" : "sign-up"}</h1> <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8"> <FormField control={form.control} name="username" render={({ field }) => ( <FormItem> <FormLabel>username</FormLabel> <FormControl> <Input className="w-80" placeholder="example123" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="password" render={({ field }) => ( <FormItem> <FormLabel>password</FormLabel> <FormControl> <Input className="w-80" placeholder="********" type="password" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> {!isLogin && <FormField control={form.control} name="confirmPass" render={({ field }) => ( <FormItem> <FormLabel>confirm password</FormLabel> <FormControl> <Input className="w-80" placeholder="********" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> } <Button type="submit" className="mr-4">{isLogin ? "login" : "sign-up"}</Button> <br/> <Button className="pl-0 pt-0 mt-0" type="button" variant="link" onClick={toggleLogin}>{isLogin ? "new to next-blog? sign-up instead" : "already have an accunt? login instead"}</Button> </form> </Form> </div> </main>) }
import Vue from "vue"; import VueRouter from "vue-router"; import HomePage from "@/views/home/HomePage.vue"; import Tutorials from "@/views/tutorials/Tutorials.vue"; import UserInfo from "@/views/portfolio/user-info/UserInfo.vue"; import CarDetails from "@/views/car/CarDetails"; import VendorLandingPage from "@/views/vendor/VendorLandingPage"; const routes = [ // HomePage { path: "/", name: "Home", component: HomePage }, { path: "/tutorials", name: "Tutorials", component: Tutorials }, { path: "/car/:car_id", name: "CarDetails", component: CarDetails, }, { path: "/vendor", name: "VendorLandingPage", component: VendorLandingPage, }, { path: "/allCars", name: "AllCars", component: () => import("@/views/car/AllCars.vue") }, //Admin page { path: "/portfolio/user-info", name: "UserInfo", component: UserInfo }, { path: "/portfolio/list-users", name: "ListUser", component: () => import("@/views/portfolio/list-user/ListUsers.vue") }, { path: "/portfolio/list-vendors", name: "ListVendor", component: () => import("@/views/portfolio/list-user/ListVendors.vue") }, { path: "/portfolio/list-cars", name: "ListCar", component: () => import("@/views/portfolio/list-car/ListCars.vue") }, { path: "/portfolio/user-list-booking", name: "UserListBooking", component: () => import("@/views/portfolio/list-booking/UserListBooking.vue") }, { path: "/portfolio/vendor-list-booking", name: "VendorListBooking", component: () => import("@/views/portfolio/list-booking/VendorListBooking.vue") }, //Auth { path: "/login", name: "Login", component: () => import("@/views/auth/Login.vue") }, { path: "/register", name: "Register", component: () => import("@/views/auth/Register.vue") }, ]; Vue.use(VueRouter); const router = new VueRouter({ mode: 'history', routes }); export default router;
import styles from "../assets/styles/components/DashboardLevels.module.scss"; import { motion } from "framer-motion"; import { levelVariants } from "../motionVariants/levelVariants"; import { useNavigate } from "react-router-dom"; const DashboardLevels = () => { const english_levels = ["A1", "A2", "B1", "B2", "C1", "C2"]; const navigate = useNavigate(); return ( <div className={styles["english-levels"]}> <h3 className={styles.title}> Discover Your English Proficiency: Journey from Beginner to Advanced </h3> <div className={styles["levels-list"]}> {english_levels.map((item, index) => ( <motion.div key={index} className={styles.level} initial="hidden" whileInView="visible" variants={levelVariants} viewport={{ once: true }} custom={index} onClick={() => navigate(`/vocabulary-list?level=${item}`)} > {item} </motion.div> ))} </div> </div> ); }; export default DashboardLevels;
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSchoolInNumbersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('school_in_numbers', function (Blueprint $table) { $table->id(); $table->string('fr_title')->nullable(); $table->string('en_title')->nullable(); $table->string('ar_title')->nullable(); $table->string('icon')->nullable(); $table->integer('number')->nullable(); $table->boolean('is_active')->default(true)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('school_in_numbers'); } }
# 动态导入 - webpack和vite构建的差别 - vite按需加载,webpack全部打包 - 动态导入和按需加载异曲同工 - 动态导入是es6的新特性 - 动态导入一版用在路由中 ```js <!-- 非动态导入 --> import Home from "./Home" import Login from "./Login" const routes=[{ path:'/home', component:home },{ path:'/Login', component:Login }] ``` ```js <!-- 动态导入 --> const routes=[{ path:'/home', component:import("./home")//返回一个promise },{ path:'/Login', component:import("./login") }] ```
import React from 'react' import { withRouter } from 'react-router-dom' import Text from 'components/CleanUIComponents/Text' import Spacer from 'components/CleanUIComponents/Spacer' import moment from 'moment' import { connect } from 'react-redux' import { Card, Spin, Empty, Button, Form, Table, Icon, Pagination, Row, Col, Tooltip } from 'antd' import lodash from 'lodash' import { amountFormatter, cryptoAmountFormatter, getCompanyName, getName, } from 'utilities/transformer' import { getAccountDetailsById, getFiatBalTransactionsById, updateSelectedPaymentType, // getCryptoBalTransactionsById, updateSelectedTransactionRecordId, } from 'redux/caTransactions/actions' import { twoFAauthorizationModal } from 'redux/auth0/actions' import ManualCredit from '../balanceAdjustment/manualCredit' import ManualDebit from '../balanceAdjustment/manualDebit' import SendCryptoPayment from '../balanceAdjustment/cryptoSendPayment' import styles from './style.module.scss' // import { string } from 'exceljs/dist/exceljs' const mapStateToProps = ({ user, currencyAccounts, caTransactions, general }) => ({ token: user.token, creditDebitLoading: currencyAccounts.creditDebitLoading, selectedAccountDetails: caTransactions.selectedAccountDetails, summaryLoading: caTransactions.summaryLoading, selectedAccountBalSummary: caTransactions.selectedAccountBalSummary, totalBalTxns: caTransactions.totalBalTxns, balTxnLoading: caTransactions.balTxnLoading, paymentType: caTransactions.paymentType, selectedAccount: currencyAccounts.selectedAccount, clients: general.clients, vendors: general.newVendors, companies: general.companies, introducers: general.introducers, }) @withRouter @Form.create() @connect(mapStateToProps) class AccountDetails extends React.Component { state = { unUsedValues: false, expandedRowKeys: [], fromNumber: 1, toNumber: 50, // pageSize: 10, activePage: 1, limit: 50, defaultCurrent: 1, clientAndIntroducers: [], } componentDidMount() { const { dispatch, clients, introducers } = this.props this.getClientId() dispatch(twoFAauthorizationModal(false)) this.setState({ clientAndIntroducers: clients.concat(introducers), }) } getClientId = () => { const { dispatch, token, match } = this.props const { limit } = this.state const ID = match.params.id dispatch(getAccountDetailsById(ID, token)) const value = { limit, activePage: 1, } this.getTransactions(value) // dispatch(getTransactionsListById(ID, token)) } getTransactions = value => { const { dispatch, token, match, selectedAccount } = this.props const ID = match.params.id dispatch( getFiatBalTransactionsById(ID, { ...value, accountType: selectedAccount.accountType }, token), ) } handleRefresh = () => { const { limit } = this.state const value = { limit, activePage: 1, } this.getClientId() this.getTransactions(value) } onClickBack = () => { const { dispatch, history } = this.props dispatch(updateSelectedPaymentType('')) history.push(`/payments-accounts-list`) } handleOnClickCredit = () => { const { dispatch } = this.props dispatch(updateSelectedPaymentType('credit')) // this.setState({ manualCredit: true, manualDebit: false }) } handleOnClickDebit = () => { const { dispatch } = this.props dispatch(updateSelectedPaymentType('debit')) // this.setState({ manualDebit: true, manualCredit: false }) } handleCryptoSend = () => { const { dispatch } = this.props dispatch(updateSelectedPaymentType('cryptoSend')) } onExpand = (expanded, record) => { this.updateExpandedRowKeys({ record }) } updateExpandedRowKeys = ({ record }) => { const { id } = record const { expandedRowKeys } = this.state const isExpanded = expandedRowKeys.find(key => key === id) let expandedRowKey = [] if (isExpanded) { expandedRowKey = expandedRowKeys.reduce((acc, key) => { if (key !== id) acc.push(key) return acc }, []) } else { expandedRowKey.push(id) } this.setState({ expandedRowKeys: expandedRowKey, }) } getClientNameForID = clientId => { const { clients } = this.props const filteredClients = clients.filter(vendor => vendor.id === clientId) return filteredClients.length > 0 ? filteredClients[0].tradingName : '' } handleTableChange = currentPage => { const { limit } = this.state this.setState({ activePage: currentPage, }) const value = { limit, activePage: currentPage, } this.getTransactions(value) this.arrayPaginationCount(limit, currentPage) } arrayPaginationCount = (limit, activePage) => { const skip = (activePage - 1) * limit const fromNumb = skip + 1 const toNumb = skip + limit this.setState({ fromNumber: fromNumb, toNumber: toNumb, }) } handlePageSizeChange = (current, pageSize) => { const { activePage } = this.state const value = { limit: pageSize, activePage: 1, } Promise.resolve( this.setState({ limit: pageSize, activePage: 1, fromNumber: current }), ).then(() => this.getTransactions(value)) this.arrayPaginationCount(pageSize, activePage) } getOwner = (type, ownerEntityId) => { const { companies } = this.props const { clientAndIntroducers } = this.state switch (type) { case 'client': return getName(clientAndIntroducers, ownerEntityId) case 'pl': return getCompanyName(companies, ownerEntityId) case 'vendor_client': return getCompanyName(companies, ownerEntityId) case 'vendor_pl': return getCompanyName(companies, ownerEntityId) case 'suspense': return getCompanyName(companies, ownerEntityId) default: return '' } } getActiveAccountNumber = accountDetails => { const activeRecord = accountDetails.filter(e => e.isActiveAccountIdentification === true) return activeRecord.length > 0 ? activeRecord[0].accountNumber : '--' } navigateToTransactionSummary = reference => { const { history, dispatch, selectedAccountDetails } = this.props dispatch( updateSelectedTransactionRecordId({ id: selectedAccountDetails.id, type: selectedAccountDetails.accountType, }), ) history.push(`/payment-transaction-summary/${reference}`) } getCounterPartyDetails = record => { let value const { payments } = record if (typeof payments !== 'string') { if ( payments.processFlow !== 'manual_debit_adjustment' && payments.processFlow !== 'manual_credit_adjustment' ) { if (payments.isOutbound) { value = payments.creditor ? payments.creditor.creditorName : lodash.startCase(payments.processFlow) } else { value = payments.debtor ? payments.debtor.debtorName : lodash.startCase(payments.processFlow) } } else { value = lodash.startCase(payments.processFlow) } } return value } render() { const { selectedAccountDetails, summaryLoading, form, selectedAccountBalSummary, balTxnLoading, paymentType, totalBalTxns, } = this.props const { amount, displayAmount, unUsedValues, expandedRowKeys, fromNumber, toNumber, defaultCurrent, } = this.state if (unUsedValues) { console.log( 'selectedAccountDetails', selectedAccountDetails, amount, displayAmount, form, expandedRowKeys, ) } const manualButtonVisible = selectedAccountDetails?.currencyType === 'fiat' || selectedAccountDetails?.currencyType === 'crypto' // const sortedBalTxn = // selectedAccountBalSummary.length > 0 // ? lodash.orderBy(selectedAccountBalSummary, ['createdAt'], ['desc']) // : [] const columns = [ { title: 'Date', dataIndex: 'createdAt', key: 'createdAt', align: 'center', render: text => <a>{moment(text, 'YYY-MM-DD').format('DD MMM YY')}</a>, }, { title: 'Counterparty ', key: 'counterParty', dataIndex: 'counterParty', align: 'center', render: (text, record) => ( <>{Object.entries(record).length > 0 ? this.getCounterPartyDetails(record) : undefined}</> ), }, { title: 'Transaction Reference', dataIndex: 'reference', key: 'reference', align: 'center', }, { title: 'Remittance information', dataIndex: 'remarks', key: 'remarks', // align : 'center', render: text => ( <div className="row"> <div className="col-lg-12"> <span>{text}</span> </div> {/* <div className="col-lg-12"> <Button type="link" icon="right" className={styles.moreInfo}> More Info </Button> </div> */} </div> ), }, { title: 'Amount', dataIndex: 'amount', key: 'amount', align: 'center', }, { title: 'Balance', key: 'balance', dataIndex: 'balance', align: 'center', render: text => <span className={styles.balance}>{amountFormatter(text)}</span>, }, { title: 'Status', dataIndex: 'status', key: 'status', align: 'center', render: record => { if (record === 'complete') { return ( <Button type="link" icon="check-circle" size="small" style={{ color: '#3CB371', fontWeight: '600' }} > Completed </Button> ) } if (record === 'pending') { return ( <Button type="link" size="small" icon="info-circle" style={{ color: '#40A0EE', fontWeight: '600' }} > {lodash.capitalize(record)} </Button> ) } if (record === 'cancelled') { return ( <Button type="link" size="small" icon="close-circle" style={{ color: '#ff6e6e', fontWeight: '600' }} > {lodash.capitalize(record)} </Button> ) } return record }, }, ] return ( <div> <div className={styles.summaryHeader}> <Text weight="thin" size="xlarge" className="font-size-15 bold"> <Button type="link" icon="arrow-left" className={styles.backArrowIcon} onClick={this.onClickBack} /> {`${' '} ${'Back To Accounts'}`} </Text> </div> <Spin spinning={summaryLoading}> {Object.entries(selectedAccountDetails).length > 0 ? ( <div> <div className="row"> <div className="col"> {selectedAccountDetails.currencyType === 'crypto' ? ( <Card className={styles.activeCard} bordered> <div className={`row ${styles.closeIcon}`}> <div className="col-lg-12"> <Icon type="close" style={{ float: 'right', color: 'white' }} onClick={this.onClickBack} /> </div> </div> <div className="row"> <div className="col-6 col-lg-6"> <div className={styles.nameBlock}> {selectedAccountDetails.ownerEntityId ? this.getOwner( selectedAccountDetails.accountType, selectedAccountDetails.ownerEntityId, ) : '__'} </div> </div> <div className="col-8 col-lg-5"> <div className={styles.currencyBlock}> {selectedAccountDetails.currency} </div> </div> </div> <div className="row"> <div className="col-8 col-lg-6"> <div className={styles.accountNameBlock}> {selectedAccountDetails.accountName ? selectedAccountDetails.accountName : '--'} </div> </div> <div className="col-8 col-lg-3"> <span className={styles.statusBlock}>Available Balance : </span> </div> <div className="col-8 col-lg-2"> <div className={styles.availablebalanceBlock}> {cryptoAmountFormatter( selectedAccountDetails.balance.availableBalance, 8, )} </div> </div> </div> <div className="row"> <div className="col-8 col-lg-6"> <div className={styles.addressBlock}> {selectedAccountDetails.accountIdentification ? selectedAccountDetails.accountIdentification.accountNumber : '--'} </div> </div> <div className="col-8 col-lg-3"> <span className={styles.statusBlock}>Balance : </span> </div> <div className="col-8 col-lg-2"> <div className={styles.balanceBlock}> {cryptoAmountFormatter(selectedAccountDetails.balance.balance, 8)} </div> </div> </div> <Spacer height="5px" /> <div className="row"> <div className="col-8 col-lg-6"> <div className={styles.typeBlock}> {selectedAccountDetails.currencyType ? lodash.capitalize(selectedAccountDetails.currencyType) : '--'} </div> </div> <div className="col-8 col-lg-5"> <div className={styles.statusBlock}> {lodash.capitalize(selectedAccountDetails.accountStatus)} </div> </div> </div> <div> <img src="resources/images/logo_square-mobile.svg" alt="" className={styles.imageBlock} style={{ position: 'absolute', top: 86, right: -20, opacity: '25%', height: '120px', width: '120px', }} /> </div> </Card> ) : ( <Card className={styles.activeCard} bordered> <div className={`row ${styles.closeIcon}`}> <div className="col-lg-12"> <Icon type="close" style={{ float: 'right', color: 'white' }} onClick={this.onClickBack} /> </div> </div> <div className="row"> <div className="col-6 col-lg-6"> <div className={styles.nameBlock}> {selectedAccountDetails.ownerEntityId ? this.getOwner( selectedAccountDetails.accountType, selectedAccountDetails.ownerEntityId, ) : '__'} </div> </div> <div className="col-8 col-lg-5"> <div className={styles.currencyBlock}> {selectedAccountDetails.currency} </div> </div> </div> <div className="row"> <div className="col-8 col-lg-6"> <div className={styles.accountNameBlock}> {selectedAccountDetails.accountName ? selectedAccountDetails.accountName : '--'} </div> </div> <div className="col-8 col-lg-3"> <span className={styles.statusBlock}>Available Balance : </span> </div> <div className="col-8 col-lg-2"> <div className={styles.availablebalanceBlock}> {amountFormatter(selectedAccountDetails.balance.availableBalance)} </div> </div> </div> <div className="row"> <div className="col-8 col-lg-6"> <div className={styles.addressBlock}> {selectedAccountDetails.accountIdentification ? selectedAccountDetails.accountIdentification.accountNumber : ''} </div> </div> <div className="col-8 col-lg-3"> <span className={styles.statusBlock}>Balance : </span> </div> <div className="col-8 col-lg-2"> <div className={styles.balanceBlock}> {amountFormatter(selectedAccountDetails.balance.balance)} </div> </div> </div> <Spacer height="5px" /> <div className="row"> <div className="col-8 col-lg-6"> <div className={styles.typeBlock}> {selectedAccountDetails.currencyType ? lodash.capitalize(selectedAccountDetails.currencyType) : '--'} </div> </div> <div className="col-8 col-lg-5"> <div className={styles.statusBlock}> {lodash.capitalize(selectedAccountDetails.accountStatus)} </div> </div> </div> <div> <img src="resources/images/logo_square-mobile.svg" alt="" className={styles.imageBlock} style={{ position: 'absolute', top: 86, right: -20, opacity: '25%', height: '120px', width: '120px', }} /> </div> </Card> )} </div> </div> <Spacer height="10px" /> {!paymentType && ( <Card title={ manualButtonVisible ? ( <div className={styles.tableHeader}> <div className="row"> <div className="col-7 col-lg-2"> <Button onClick={this.handleOnClickCredit}> <div className="row"> <div className="col-7 col-lg-7">Manual Credit</div> <div className="col-5 col-lg-5"> <img src="resources/images/initiate-money-transfer.png" alt="" style={{ position: 'absolute', top: -1, right: 15, height: '20px', width: '20px', }} /> </div> </div> </Button> </div> <div className="col-7 col-lg-2"> <Button className={styles.debitBtn} onClick={this.handleOnClickDebit}> <div className="row"> <div className="col-7 col-lg-7">Manual Debit</div> <div className="col-5 col-lg-5"> <img src="resources/images/initiate-money-transfer.png" alt="" style={{ position: 'absolute', top: -1, right: 15, height: '20px', width: '20px', }} /> </div> </div> </Button> </div> <div className={`col-7 col-lg-8 ${styles.refreshBtn}`}> <Tooltip title="Refresh to get new transactions"> <Icon type="reload" onClick={this.handleRefresh} /> </Tooltip> </div> </div> </div> ) : ( '' ) } headStyle={{ padding: '0', border: '1px solid #a8c6fa', borderTopLeftRadius: '10px', borderTopRightRadius: '10px', borderBottom: 'none', }} bodyStyle={{ padding: '0', border: '1px solid #a8c6fa', }} className={styles.mainCard} > <div> <div> <Table columns={columns} dataSource={selectedAccountBalSummary} className={styles.txnTable} loading={balTxnLoading} pagination={false} onRow={record => ({ onClick: () => { this.navigateToTransactionSummary(record.reference) }, })} /> <div className="pl-3 mt-4 mb-3"> <Row> <Col xs={{ span: 12 }} md={{ span: 5 }} lg={{ span: 4 }} className={styles.totalPageBlock} > <span> Show {fromNumber} to <b>{toNumber}</b> of <b>{totalBalTxns}</b>{' '} entries </span> </Col> <Col xs={{ span: 12 }} md={{ span: 19 }} lg={{ span: 20 }}> <Pagination className={styles.paginationTab} onChange={this.handleTableChange} showSizeChanger defaultCurrent={defaultCurrent} defaultPageSize={50} pageSizeOptions={['10', '50', '100']} onShowSizeChange={this.handlePageSizeChange} total={totalBalTxns} loading={balTxnLoading || summaryLoading} /> </Col> </Row> </div> </div> {/* )} */} </div> </Card> )} {paymentType === 'credit' && <ManualCredit />} {paymentType === 'debit' && <ManualDebit />} {paymentType === 'cryptoSend' && <SendCryptoPayment />} </div> ) : ( <Empty /> )} </Spin> </div> ) } } export default AccountDetails
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://spring.io/guides/gs-producing-web-service" targetNamespace="http://spring.io/guides/gs-producing-web-service" elementFormDefault="qualified"> <xs:element name="getBookRequest"> <xs:complexType> <xs:sequence> <xs:element name="isbn" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getBookResponse"> <xs:complexType> <xs:sequence> <xs:element name="book" type="tns:book"/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="book"> <xs:sequence> <xs:element name="isbn" type="xs:string"/> <xs:element name="title" type="xs:string"/> <xs:element name="author" type="tns:author"/> <xs:element name="copies" type="xs:int"/> <xs:element name="language" type="tns:language"/> </xs:sequence> </xs:complexType> <xs:complexType name="author"> <xs:sequence> <xs:element name="firstName" type="xs:string"/> <xs:element name="lastName" type="xs:string"/> <xs:element name="biography" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:simpleType name="language"> <xs:restriction base="xs:string"> <xs:enumeration value="ENG"/> <xs:enumeration value="GER"/> <xs:enumeration value="ESP"/> </xs:restriction> </xs:simpleType> </xs:schema>
// Rem output with px fallback @mixin font-size($sizeValue: 1) { font-size: ($sizeValue * 16) * 1px; font-size: $sizeValue * 1rem; } // Center block @mixin center-block { display: block; margin-left: auto; margin-right: auto; } // Clearfix @mixin clearfix() { content: ""; display: table; table-layout: fixed; } // Clear after (not all clearfix need this also) @mixin clearfix-after() { clear: both; } // Column width with margin @mixin column-width($numberColumns: 3) { width: map-get( $columns, $numberColumns ) - ( ( $columns__margin * ( $numberColumns - 1 ) ) / $numberColumns ); } @mixin breakpoint($breakpoint: $width-sm, $mobilefirst:true) { @if (unit($breakpoint) == 'rem') { $breakpoint: strip-unit($breakpoint) +"em"; // Safari can't handle rem media queries } @if ($mobilefirst) { @media (min-width: #{$breakpoint}) { @content; } } @else { @media (max-width: #{($breakpoint - 1)}) { @content; } } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {ClayoutComponent} from "./clayout/clayout.component"; import {CsettingsComponent} from "./csettings/csettings.component"; import {SpaceComponent} from "./space/space.component"; const routes: Routes = [ { path: '', component : ClayoutComponent, children: [ {path: '', redirectTo: 'profil', pathMatch: 'full'}, { //Comme user est un module il faut le charger avec loadChildren path: 'reservation', loadChildren: () => import('./reservation/reservation.module').then(m => m.ReservationModule) }, { //Comme user est un module il faut le charger avec loadChildren path: 'profil', loadChildren: () => import('./cprofil/cprofil.module').then(m => m.CprofilModule) }, { path: 'settings', component : CsettingsComponent }, { path: 'space', component : SpaceComponent } ] } // { // path: '' , component : MaintenanceComponent // } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class ClientRoutingModule { }
package uk.gov.hmcts.juror.api.bureau.service; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import uk.gov.hmcts.juror.api.bureau.controller.response.BureauBacklogCountData; import uk.gov.hmcts.juror.api.juror.domain.JurorResponseQueries; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; @Slf4j @Service public class BureauBacklogCountServiceImpl implements BureauBacklogCountService { private final JurorDigitalResponseRepositoryMod jurorResponseRepository; @Autowired public BureauBacklogCountServiceImpl( final JurorDigitalResponseRepositoryMod jurorResponseRepository) { Assert.notNull(jurorResponseRepository, "JurorResponseRepository cannot be null"); this.jurorResponseRepository = jurorResponseRepository; } @Override public long getBacklogNonUrgentCount() { return jurorResponseRepository.count(JurorResponseQueries.byUnassignedTodoNonUrgent()); } @Override public long getBacklogUrgentCount() { return jurorResponseRepository.count(JurorResponseQueries.byUnassignedTodoUrgent()); } @Override public long getBacklogAllRepliesCount() { return jurorResponseRepository.count(JurorResponseQueries.byUnassignedTodo()); } @Override public BureauBacklogCountData getBacklogResponseCount() { BureauBacklogCountData dto = new BureauBacklogCountData(); dto.setNonUrgent(getBacklogNonUrgentCount()); dto.setUrgent(getBacklogUrgentCount()); dto.setAllReplies(getBacklogAllRepliesCount()); return dto; } }
import { Box, Grid, Typography,} from "@mui/material"; import { useForm } from "react-hook-form"; import { UsuarioActions } from "../../actions/UsuarioActions"; import { TxtFieldForm } from "../../components/TextField/TxtFieldForm"; import { ButtonGeneric } from "../../components/Button/ButtonGeneric"; import { yupResolver } from "@hookform/resolvers/yup"; import * as yup from 'yup' import { AlertError } from "../../components/helpers/AlertError"; import { useEffect, useState } from "react"; import LOGO_BRANCA from '../../imgs/logo_branca.png' import { useAlertDialog } from "../../components/Dialogs/DialogProviderAlert"; interface CadastroForm { nome: string, email: string, cargo: string, senha: string, senhaConfirm: string } export const Cadastro = () => { const usuarioActions = UsuarioActions() const [hasError, setHasError] = useState<boolean>(false) const [cadastrado, setCadastrado] = useState<boolean>(false) const showDialogConfirmed = useAlertDialog() const validationSchema = yup.object().shape({ nome: yup.string() .required("Campo obrigatório") .min(3, 'Mínimo 3 letras'), email: yup.string() .required("Campo obrigatório") .email('E-mail inválido'), senha: yup.string() .required("Campo obrigatório"), senhaConfirm: yup.string() .required("Campo obrigatório") }) const { setValue, handleSubmit, formState: { errors }, control } = useForm<CadastroForm>({ resolver: yupResolver(validationSchema) }) const onSubmitCadastro = async (data: any) => { console.log("SUBMIT") if (data.senha === data.senhaConfirm) { usuarioActions.usuarioInsert(data).then(async (res: any) => { if (res.status === 200) { await showDialogConfirmed(`Seja bem vindo ${res.data.nome}!`, "success") setCadastrado(true) } else { console.log("ERROS BACK END") } }) } else { setHasError(true) } } useEffect(() => { if(cadastrado) window.location.href = 'http://localhost:3000/' }, [cadastrado]) return ( <div> <form onSubmit={handleSubmit(onSubmitCadastro)}> <Grid container direction='column' alignItems='çenter' justifyItems='center'> <Grid item > <Grid container direction='row'> <Grid item xs={12} md={3.5} lg={3} xl={4}> </Grid> <Grid item xs={12} md={6} lg={5} xl={4}> <Box sx={{ display: 'flex', justifyContent: 'center', alignContent: 'center', marginTop: 3 }}> <img src={LOGO_BRANCA} alt="LOGO" style={{ width: '260px', height: '280px' }} /> </Box> <Box sx={{ margin: 5, marginBottom: 2, backgroundColor: 'transparent', borderRadius: '10px', }}> <Grid container direction={'column'} alignContent='center' justifyContent={'center'}> {hasError && <Grid item sx={{ marginBottom: 4 }}> <AlertError title={"Atenção"} type={'warning'} style={'filled'} msgError="As senhas informadas não condizem!" /> </Grid>} <Grid item sx={{ marginBottom: 3, width: '100%' }}> <TxtFieldForm name={"nome"} control={control} label={"Nome de usuário"} error={errors.nome?.message} /> </Grid> <Grid item sx={{ marginBottom: 3 }}> <TxtFieldForm name={"email"} control={control} label={"E-mail"} error={errors.email?.message} /> </Grid> <Grid item sx={{ marginBottom: 3 }}> <TxtFieldForm name={"cargo"} control={control} label={"Cargo"} error={errors.cargo?.message} /> </Grid> <Grid item sx={{ marginBottom: 3 }}> <TxtFieldForm name={"senha"} control={control} label={"Senha"} type="password" error={errors.senha?.message} /> </Grid> <Grid item sx={{ marginBottom: 3 }}> <TxtFieldForm name={"senhaConfirm"} control={control} label={"Confirmação de senha"} type="password" error={errors.senhaConfirm?.message} /> </Grid> <Grid item sx={{}}> <ButtonGeneric title={"CADASTRAR-SE"} fullWidth /> </Grid> </Grid> </Box> <Box sx={{ textAlign: 'center' }}> <Typography fontFamily={'Kanit, sans-serif;'} fontWeight={'bold'} sx={{ marginBottom: 2 }}>Já se cadastrou?</Typography> </Box> <Box sx={{ display: 'flex', justifyContent: 'center', alignContent: 'center' }}> <ButtonGeneric title={"FAZER LOGIN"} typeIcon="entrar" backgroundColor={"#f5f5f5"} color={"#006666"} backgroundColorHover={'#008584'} colorHover='#f5f5f5' width="300px" onClick={() => { window.location.href = 'http://localhost:3000/' }} type="button" /> </Box> </Grid> <Grid item xs={12} md={3.5} lg={3} xl={4}> </Grid> </Grid> </Grid> </Grid> </form> </div> ) }
--- layout: post title: "Adapter Pattern" category: design pattern --- <aside> 💡 Work as a bridge between two **incompatible interfaces**. </aside> ### Create Adapter Class ```java public class MediaAdapter implements MediaPlayer { AdvancedMediaPlayer advancedMusicPlayer; public MediaAdapter(String audioType){ if(audioType.equalsIgnoreCase("vlc") ){ advancedMusicPlayer = new VlcPlayer(); }else if (audioType.equalsIgnoreCase("mp4")){ advancedMusicPlayer = new Mp4Player(); } } @Override public void play(String audioType, String fileName) { if(audioType.equalsIgnoreCase("vlc")){ advancedMusicPlayer.playVlc(fileName); } else if(audioType.equalsIgnoreCase("mp4")){ advancedMusicPlayer.playMp4(fileName); } } } ``` ### Use the Adapter ```java public class AudioPlayer implements MediaPlayer { MediaAdapter mediaAdapter; @Override public void play(String audioType, String fileName) { //inbuilt support to play mp3 music files if(audioType.equalsIgnoreCase("mp3")){ System.out.println("Playing mp3 file. Name: " + fileName); } //mediaAdapter is providing support to play other file formats else if(audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")){ mediaAdapter = new MediaAdapter(audioType); mediaAdapter.play(audioType, fileName); } else{ System.out.println("Invalid media. " + audioType + " format not supported"); } } } ```
/********************************* * Sensor : LDR (Light Dependant Resistor) * Board : Arduino UNO * Output : Serial (9600) * Analog : A0, A1, A2, A3, A4, A5 * Recommended pin use: A0 *********************************/ const int pin_ldr = A0; // const int pin_ldr = A1; // const int pin_ldr = A2; // const int pin_ldr = A3; // const int pin_ldr = A4; // const int pin_ldr = A5; void setup() { Serial.begin(9600); // Inisialisasi monitor serial } void loop() { int nilai = analogRead(pin_ldr); // Membaca nilai analog dari pin A0 // Mengkonversi nilai analog tegangan menggunakan ADC // ADC memiliki resolusi 10bit, sehingga dapat mewakili 2 ^ 10 = 1024 float tegangan_hasil = 5.0 * nilai / 1024; // Catatan: Ini adalah konversi D-to-A // Mencetak hasil pada monitor serial Serial.print("Vout ="); Serial.print(tegangan_hasil); Serial.println("V"); delay(2000); // jeda selama dua detik }
<?php namespace App\Http\Controllers; use App\Models\Distrito; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Barryvdh\DomPDF\Facade\Pdf; class DistritoController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { $distritos = Distrito::all(); //$distritos=Distrito::where('estado', true)->get(); return view("patologia.distritos.index", [ 'distritos' => $distritos ]); } public function pdf() { $distritos = Distrito::where('estado', true)->orderby('nombre_distrito','asc')->get(); $pdf = Pdf::loadView('patologia.distritos.pdf', compact('distritos')); return $pdf->stream(); //return $pdf->download('invoice.pdf'); --> para descargar pdf } public function create() { return view('patologia.distritos.create'); } public function store(Request $request) { $request->validate( [//'codigo_distrito'=>'required', 'nombre_distrito'=>'required'] ); $user = auth()->user(); $distrito = Distrito::create(array_merge($request->all(), ['creatoruser_id' => $user->id])); return redirect()->route('patologia.distritos.index')->with('mensaje','Se creó exitosamente'); } public function show(Distrito $distrito) { // } public function edit($id) { $distrito=Distrito::find($id); return view('patologia.distritos.edit',compact('distrito')); } public function update(Request $request, $id) { $hoy = date('Y-m-d H:i:s'); $distrito = request()->except(['_token','_method']); $user = auth()->user(); Distrito::where('id', $id)->update(array_merge($distrito, ['updateduser_id' => $user->id],['updated_at' => $hoy])); return redirect()->route('patologia.distritos.index')->with('mensaje', 'Se actualizó exitosamente'); } public function destroy($id) { $hoy = date('Y-m-d H:i:s'); $user = auth()->user(); $distrito = Distrito::find($id); if (!$distrito) { return redirect()->route('patologia.distritos.index')->with('mensaje', 'No se encontró el distrito'); } $distrito->estado = FALSE; // Cambia el estado a inactivo $distrito->save(); return redirect()->route('patologia.distritos.index')->with('mensaje', 'El distrito se marcó como Inactivo'); } public function habilitar($id) { $hoy = date('Y-m-d H:i:s'); $user = auth()->user(); $distrito = Distrito::find($id); if (!$distrito) { return redirect()->route('patologia.distritos.index')->with('mensaje', 'No se encontró el Distrito'); } $distrito->estado = TRUE; // Cambia el estado a ACTIVO $distrito->updateduser_id = $user->id; $distrito->updated_at = $hoy; $distrito->save(); return redirect()->route('patologia.distritos.index')->with('mensaje', 'El distrito se marcó como Activo'); } }
/* * Copyright (c) 2011 Patrick Meyer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.itemanalysis.jmetrik.workspace; import com.itemanalysis.jmetrik.commandbuilder.AbstractCommand; import com.itemanalysis.jmetrik.commandbuilder.OptionValueType; import com.itemanalysis.jmetrik.commandbuilder.FreeOption; import com.itemanalysis.jmetrik.commandbuilder.SelectOneOption; public class CloseDatabaseCommand extends AbstractCommand { public CloseDatabaseCommand()throws IllegalArgumentException{ super("database", "New database command"); try{ FreeOption name = new FreeOption("name", "Database name", true, OptionValueType.STRING); this.addFreeOption(name); FreeOption path = new FreeOption("path", "Path/Host to database", true, OptionValueType.STRING); this.addFreeOption(path); FreeOption username = new FreeOption("username", "User name", true, OptionValueType.STRING); this.addFreeOption(username); FreeOption password = new FreeOption("password", "Password", true, OptionValueType.STRING); this.addFreeOption(password); FreeOption port = new FreeOption("port", "Port", false, OptionValueType.INTEGER); this.addFreeOption(port); SelectOneOption create = new SelectOneOption("action", "Database Action", true); create.addArgument("create", "Create database"); create.addArgument("delete", "Delete database"); this.addSelectOneOption(create); }catch(IllegalArgumentException ex){ throw new IllegalArgumentException(ex); } } }
package com.djt.chap03; import com.djt.entity.ClickLogs; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.Table; import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; /** * Flink SQL查询未注册的表 */ public class FlinkSQLQueryUnregTable { public static void main(String[] args) throws Exception { //1、获取Stream执行环境 StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); //2、创建表执行环境 StreamTableEnvironment tEnv = StreamTableEnvironment.create(env); env.setParallelism(1); //3、读取数据 DataStream<ClickLogs> clickLogs = env.fromElements( "Mary,./home,2022-02-02 12:00:00", "Bob,./cart,2022-02-02 12:00:00", "Mary,./prod?id=1,2022-02-02 12:00:05", "Liz,./home,2022-02-02 12:01:00", "Bob,./prod?id=3,2022-02-02 12:01:30", "Mary,./prod?id=7,2022-02-02 12:01:45" ).map(event -> { String[] props = event.split(","); return ClickLogs .builder() .user(props[0]) .url(props[1]) .cTime(props[2]) .build(); }); //4、流转换为动态表 Table table = tEnv.fromDataStream(clickLogs); //5、SQL查询未注册表(注意table两边得有空格) Table resultTable = tEnv.sqlQuery("select user,count(url) as cnt from " + table + " group by user"); //6、执行并打印 resultTable.execute().print(); } }
//// API endpoints for managing exercises // const router = require('express').Router(); let Exercise = require('../models/exercise.model'); // Your Challenge: Make five routes. Each will use mongojs method // to interact with your mongoDB database, as instructed below. // You will be using express Router and Mongoose // -/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/ // 1. get all exercise logs on record // GET: / router.get('/', async(req,res)=> { try{ const exercise = await Exercise.find({}).exec(); res.json(exercise) } catch (err) { console.log(err) } }); // 2. add a new exercise log // POST: /add router.post('/add',({body},res)=> { Exercise.create(body) .then(dbUser => { res.json(dbUser); }) .catch(err => { res.json(err); }); }); // 3. retrieve a specfic exercise log // GET: /:id router.get('/:id', async(req, res) => { try{ const exercise = await Exercise.findById({_id: req.params.id}); res.send(exercise) } catch(err) { console.log(err); } }); // 4. delete a specfic exercise log // DELETE: /:id router.delete('/:id', async(req, res)=> { try{ const exercise = await Exercise.deleteOne({_id: req.params.id}); res.send(exercise) } catch(err) { console.log(err); } }); // 5. retrieve a specific exercise log and update it // with information sent by client on req body // POST: /update/:id router.post('/update/:id', async (req, res)=> { const updateRecord = await Exercise.updateOne({_id: req.params.id}, { $set: { username: req.body.username, description: req.body.description, duration: req.body.duration, date: Date.now() } }, {new: true} ) res.send(updateRecord) }) module.exports = router;
import { describe, expect, test } from "bun:test"; import { Radix, combineRadix } from "../src"; describe("Radix Tree", () => { describe("insert", () => { test("should insert values correctly", () => { const radix = new Radix<number>(); radix.insert("user/:id", 1); radix.insert("user/:id/profile", 2); radix.insert("user/:id/settings", 3); expect(radix.children).toHaveProperty("user"); expect(radix.children.user.children).toHaveProperty(":"); expect(radix.children.user.children[":"].children).toHaveProperty("profile"); expect(radix.children.user.children[":"].children).toHaveProperty("settings"); expect(radix.children.user.children[":"].children.profile.value).toBe(2); expect(radix.children.user.children[":"].children.settings.value).toBe(3); }); }); describe("match", () => { test("should match values correctly with parameters", () => { const radix = new Radix<number>(); radix.insert("user/:id", 1); radix.insert("user/:id/profile", 2); radix.insert("user/:id/settings", 3); const result = radix.match("user/123/profile"); expect(result?.value).toBe(2); expect(result?.parameters).toHaveProperty("id", "123"); }); test("should return undefined for non-existent keys", () => { const radix = new Radix<number>(); radix.insert("user/:id", 1); radix.insert("user/:id/profile", 2); const result = radix.match("user/456/settings"); expect(result?.value).toBeUndefined(); expect(result?.parameters).toBeUndefined(); }); }); }); describe("combineNodes", () => { test("should combine nodes correctly", () => { const firstNode = new Radix<number>("id"); firstNode.insert("user/:id", 1); firstNode.insert("user/:id/profile", 2); const secondNode = new Radix<number>("name"); secondNode.insert("user/:name", 3); secondNode.insert("user/:name/settings", 4); const node = combineRadix(firstNode, secondNode); expect(node.parameter).toBe("id"); expect(node.children).toHaveProperty("user"); expect(node.children.user.children).toHaveProperty(":"); expect(node.children.user.children[":"].parameter).toBe("id"); expect(node.children.user.children[":"].children).toHaveProperty("profile"); expect(node.children.user.children[":"].children.profile.value).toBe(2); expect(node.children.user.children[":"].children).toHaveProperty("settings"); expect(node.children.user.children[":"].children.settings.value).toBe(4); }); });
<!DOCTYPE html> <html> <head> <title>Тест по физике 9 класс "Механика</title> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="ButtonOptions.css" rel="stylesheet"> </head> <body style="background-color: #805A3B"> <h1 class="countdown-title">Осталось времени:</h1> <div id="countdown" class="countdown"> <div class="countdown-number"> <span class="minutes countdown-time"></span> <span class="countdown-text">Минут</span> </div> <div class="countdown-number"> <span class="seconds countdown-time"></span> <span class="countdown-text">Секунд</span> </div> </div> <style type="text/css"> body { text-align: center; background: #ADD8E6; font-family: sans-serif; font-weight: 500; } .countdown-title { color: #0B0C0F; font-weight: 100; font-size: 40px; } .countdown { font-family: sans-serif; color: #000; display: inline-block; font-weight: 100; text-align: center; font-size: 30px; } .countdown-number { padding: 9px; border-radius: 5px; background: #C9A66B; display: inline-block; } .countdown-time { padding: 14px; border-radius: 70px; background: #F1DCC9; display: inline-block; } .countdown-text { display: block; padding-top: 3px; font-size: 14px; } </style> <script type="text/javascript">jQuery(document).ready(function($) { var quest = 0; var resp = 0; var array = [ ["Кинематика - это", ["Раздел механики, в котором изучается механическое движение тел", "раздел механики, в котором изучается механическое движение с учетом взаимодействия тел", "раздел механики, в котором изучается механическое движение без учета взаимодействия тел"], 2], ["Механическое движение происходит", ["физическая величина", "физический процесс", "свойство тела"], 1], ["Механическое движение происходит", ["мгновенно", "в течении какого-то времени", "в течении минуты"], 1], ["Чему равен вес груза массой m, лежащего на полу лифта, при движении лифта вниз с ускорением а?", ["m(g − а)", "m(g + а)", "m(а − g)"], 0], ["Из письменного стола выдвинули ящик. Движется ли в это время стол относительно ящика?", ["не движется", "однозначного ответа нет", "движется"], 2], ["Тело отсчета - это", ["тело, размерами которого можно пренебречь", "тело, которое не движется", "тело, относительно которого рассматривается изменение положения других тел"], 2], ["Какое тело в механике может быть принято в качестве тела отсчета?", ["только Земля", "любое тело", "тело, размерами которого можно пренебречь"], 1], ["Существуют ли в природе абсолютно неподвижные тела?", ["не существуют", "нельзя сказать точно", "существуют"], 0], ["Может ли тело одновременно совершать механическое движение и покоиться?", ["может относительно разных тел отсчёта", "может", "не может"], 2], ["Система отсчета - это", ["система, состоящая из тела отсчета, системы координат и системы отсчета времени", "cистема всех тел, относительно которых рассматривается движение других тел", "система, в которой можно пренебречь размерами тел"], 0] ]; var fillData = function() { if (quest >= array.length) { alert('Правильных ответов: ' + resp + ' из ' + array.length); } else { $('#quest').text(array[quest][0]); for (var i = 0; i < array[quest][1].length; i++) { $("#a" + (i + 1)) .text(array[quest][1][i]) .data({ resp: i == array[quest][2] }); } } }; $('#test button').click(function() { if ($(this).data('resp')) resp++; quest++; fillData(); }); fillData(); }); function getTimeRemaining(endtime) { var t = Date.parse(endtime) - Date.parse(new Date()); var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 2000 / 60) % 60); var hours = Math.floor((t / (1000 * 60 * 60)) % 24); var days = Math.floor(t / (1000 * 60 * 60 * 24)); return { total: t, days: days, hours: hours, minutes: minutes, seconds: seconds }; } function initializeClock(id, endtime) { var clock = document.getElementById(id); var daysSpan = clock.querySelector(".days"); var hoursSpan = clock.querySelector(".hours"); var minutesSpan = clock.querySelector(".minutes"); var secondsSpan = clock.querySelector(".seconds"); function updateClock() { var t = getTimeRemaining(endtime); if (t.total <= 0) { alert('Правильных ответов: ' + resp + ' из ' + array.length); } minutesSpan.innerHTML = ("0" + t.minutes).slice(-2); secondsSpan.innerHTML = ("0" + t.seconds).slice(-2); } updateClock(); var timeinterval = setInterval(updateClock, 1000); } var deadline = new Date(Date.parse(new Date()) + 1200 * 1000); initializeClock("countdown", deadline); </script> <div id="test" class="div" style="height: 640px; text-align: center; top: 230px;"> <div id="quest" class="hd"></div> <button id="a1" class="BB1" style="font-size: calc( (100vw - 240px)/(1100 - 240) * (20 - 8) + 8px);"></button> <button id="a2" class="BB2" style="font-size: calc( (100vw - 240px)/(1100 - 240) * (20 - 8) + 8px);"></button> <button id="a3" class="BB3" style="font-size: calc( (100vw - 240px)/(1100 - 240) * (20 - 8) + 8px);"></button> </div> </body> </html>
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Lobster&family=Rubik&display=swap" rel="stylesheet"> <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"> <script src="https://kit.fontawesome.com/c26cd2166c.js"></script> <title>Food Shop</title> </head> <body> <nav class="navbar navbar-expand-lg"> <div class="container"> <a class="navbar-brand" href="#">Organic</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"><i class="fas f-hamburger"></i></span> </button> <div class="collapse navbar-collapse" id="navbarScroll"> <ul class="navbar-nav m-auto my-2 my-lg-0"> <li class="nav-item"> <a class="nav-link active" href="#">HOME</a> </li> <li class="nav-item"> <a class="nav-link" href="#">TRENDING</a> </li> <li class="nav-item"> <a class="nav-link" href="#"> STORE </a> </li> <li class="nav-item"> <a class="nav-link" href="#">ORGANIC</a> </li> <li class="nav-item"> <a class="nav-link" href="#">CONTACT</a> </li> </ul> <form class="d-flex"> <input class="px-2 search" type="search" placeholder="Search" aria-label="Search"> <button class="btn0" type="submit">Search</button> </form> </div> </div> </nav> <section class="main"> <div class="container py-5"> <div class="row py-5"> <div class="col-lg-7 pt-5 text-center"> <h1 class="pt-5">Nature Has Always Cared For Us !</h1> <button class="btn1 mt-3"> More Tips</button> </div> </div> </div> </section> <section class="new"> <div class="container py-5"> <div class="row pt-5"> <div class="col-lg-7 m-auto"> <div class="row text-center"> <div class="col-lg-4"> <img src="images/banana-removebg-preview.png" class="MARYAM" alt=""> <h6>NATURAL</h6> </div> <div class="col-lg-4"> <img src="images/grapes purp.png" class="MARYAM1" alt=""> <h6>ORGANIC</h6> </div> <div class="col-lg-4"> <img src="images/sag.png" class="MARYAM2" alt=""> <h6>HEALTH</h6> </div> </div> </div> </div> </div> </div> </section> <section class="product"> <div class="container py-5"> <div class="row py-5"> <div class="col-lg-5 m-auto text-center"> <h1>What's Trending</h1> <h6 style="color:red;">Be Healthy Organic Food</h6> </div> </div> <div class="row"> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/food-removebg-preview.png" class="energy1" alt=""> </div> </div> <h6>Energy Food</h6> <p>$39.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/beans-removebg-preview.png" class="energy2" alt=""> </div> </div> <h6>Green Beans</h6> <p>$49.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/milk-removebg-preview.png" class="energy3" alt=""> </div> </div> <h6>Healthy Milk</h6> <p>$29.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/pack-removebg-preview.png" class="energy4" alt=""> </div> </div> <h6>Refill Pack</h6> <p>$59.99</p> </div> </div> <div class="row"> <div class="col-lg-6 text-center m-auto"> <button class="btn1">Click For More</button> </div> </div> </div> </section> <section class="about"> <div class="container py-5"> <div class="row py-5"> <div class="col-lg-8 m-auto text-center"> <h1>Welcome To Our Organic Food Society</h1> <h6 style="color: red;">Be Healthy Organic Food</h6> </div> </div> <div class="row"> <div class="col-lg-4"> <img src="images/citrus.jpeg" class="images-fluid mb-3" alt=""> <h5>Best Quality product</h5> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque, magnam. Harum dolor veniam nihil tempora obcaecati, esse repellendus, amet nostrum aut consectetur!</p> </div> <div class="col-lg-4"> <img src="images/organic.jpeg" class="images-fluid mb-3" alt=""> <h5>Organic Food</h5> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque, magnam. Harum dolor veniam nihil tempora obcaecati, esse repellendus, amet nostrum aut consectetur!</p> </div> <div class="col-lg-4"> <img src="images/yellow citrus.jpeg" class="images-fluid mb-3" alt=""> <h5>Best Quality product</h5> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque, magnam. Harum dolor veniam nihil tempora obcaecati, esse repellendus, amet nostrum aut consectetur!</p> </div> </div> <div class="row pt-3"> <div class="col-lg-6 text-center m-auto"> <button class="btn1">Shop More</button> </div> </div> </div> </section> <section class="shop"> <div class="container"> <div class="row py-5"> <div class="col-lg-8 m-auto text-center"> <h1>Explore Our Store</h1> <h6 style="color: red;">Pick Your Product From Our Store</h6> </div> </div> <div class="row"> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/food-removebg-preview.png" class="energy1" alt=""> </div> </div> <h6>Energy Food</h6> <p>$39.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/beans-removebg-preview.png" class="energy2" alt=""> </div> </div> <h6>Green Beans</h6> <p>$49.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/milk-removebg-preview.png" class="energy3" alt=""> </div> </div> <h6>Healthy Milk</h6> <p>$29.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/pack-removebg-preview.png" class="energy4" alt=""> </div> </div> <h6>Refill Pack</h6> <p>$59.99</p> </div> <div class="row"> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/food-removebg-preview.png" class="energy1" alt=""> </div> </div> <h6>Energy Food</h6> <p>$39.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/beans-removebg-preview.png" class="energy2" alt=""> </div> </div> <h6>Green Beans</h6> <p>$49.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/milk-removebg-preview.png" class="energy3" alt=""> </div> </div> <h6>Healthy Milk</h6> <p>$29.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/pack-removebg-preview.png" class="energy4" alt=""> </div> </div> <h6>Refill Pack</h6> <p>$59.99</p> </div> </div> <div class="row"> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/food-removebg-preview.png" class="energy1" alt=""> </div> </div> <h6>Energy Food</h6> <p>$39.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/beans-removebg-preview.png" class="energy2" alt=""> </div> </div> <h6>Green Beans</h6> <p>$49.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/milk-removebg-preview.png" class="energy3" alt=""> </div> </div> <h6>Healthy Milk</h6> <p>$29.99</p> </div> <div class="col-lg-3 text-center"> <div class="card border-0 bg-light mb-2"> <div class="card-body"> <img src="images/pack-removebg-preview.png" class="energy4" alt=""> </div> </div> <h6>Refill Pack</h6> <p>$59.99</p> </div> </div> </div> </div> </section> <section class="apple py-5"> <div class="container text-white py-5"> <div class="row py-5"> <div class="col-lg-6"> <h1 class="font-weight-bold py-3">Unlock Your Potential With Good Nutrion</h1> <h6>Be Healthy Organic Food</h6> <button class="btn1 mt-3">More From Us</button> </div> </div> </div> </section> <section class="contact py-5"> <div class="container py-5"> <div class="row"> <div class="col-lg-5 m-auto text-center"> <h1>Contact Us</h1> <h6 style="color: red;">Always Be In Touch With Us</h6> </div> </div> <div class="row py-5"> <div class="col-lg-9 m-auto"> <div class="row"> <div class="col-lg-4"> <h6>LOCATION</h6> <P>New York 0911 First Street DC</P> <h6>PHONE</h6> <p>03444-24359555</p> <h6>EMAIL</h6> <p>[email protected]</p> </div> <div class="col-lg-7"> <div class="row"> <div class="col-lg-6"> <input type="text" class="form-control bg-light" placeholder="First Name"> </div> <div class="col-lg-6"> <input type="text" class="form-control bg-light" placeholder="Last Name"> </div> </div> <div class="row"> <div class="col-lg-12 py-3"> <textarea name="" class="form-control bg-light" placeholder="Enter Your Name" id="" cols="10" rows="5"></textarea> </div> </div> <button class="btn1">Submit</button> </div> </div> </div> </div> </section> <section class="news py-5"> <div class="container py-5"> <div class="row"> <div class="col-lg-9 m-auto text-center"> <h1>Join Our Secret Society</h1> <input type="text" class="px-3" placeholder="Enter Your Email"> <button class="btn2">Submit</button> </div> </div> <div class="row"> <div class="col-lg-11 m-auto"> <div class="row"> <div class="col-lg-3 py-3"> <h5 class="pb-3">CUSTOMER CARE</h5> <p>Regular</p> <p>On Time</p> <p>Always Care</p> </div> <div class="col-lg-3 py-3"> <h5 class="pb-3">FAQ'S</h5> <p>Regular</p> <p>On Time</p> <p>Always Care</p> </div> <div class="col-lg-3 py-3"> <h5 class="pb-3">OUR COMPANT</h5> <p>Regular</p> <p>On Time</p> <p>Always Care</p> </div> <div class="col-lg-3 py-3"> <h5 class="pb-3">SOCIAL MEDIA</h5> <span><i class="fab fa-facebook"></i></span> <span><i class="fab fa-instagram"></i></span> <span><i class="fab fa-twitter"></i></span> <span><i class="fab fa-google-plus"></i></span> </div> </div> </div> </div> <hr> <p class="text-center"> copyright @2021 All right reserved | This template is made with BY ProWeb</p> </div> </section> </body> </html>
import { Entity, PrimaryGeneratedColumn, Column, UpdateDateColumn, CreateDateColumn } from 'typeorm'; export enum CategoryStatus { INACTIVE, ACTIVE, } @Entity() export class Category { @PrimaryGeneratedColumn('uuid') id: number; @Column({ length: 50 }) name: string; @Column({ nullable: true }) description: string; @Column({ nullable: true }) image: string; @Column({ type: 'enum', enum: CategoryStatus, default: CategoryStatus.ACTIVE, }) status: CategoryStatus; @CreateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' }) createdAt: Date; @UpdateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' }) updatedAt: Date; }
import { PayloadAction, createSlice } from "@reduxjs/toolkit"; import { RootState } from "./store"; import { Product } from "../definitions"; export interface CartState { productsInCart: Product[]; } const initialState: CartState = { productsInCart: [], }; export const cartSlice = createSlice({ name: "cart", initialState, reducers: { add: (state, action: PayloadAction<Product>) => { state.productsInCart.push(action.payload); }, remove: (state, action: PayloadAction<Product>) => { let index = state.productsInCart.findIndex(product => product.id == action.payload.id); state.productsInCart.splice(index, 1); }, }, }); export const { add, remove } = cartSlice.actions; export const selectCart = (state: RootState) => state.cart; export default cartSlice.reducer;
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head th:replace="fragments::page_head('Your Account Details')"></head> <body> <div class="container-fluid"> <div th:replace="navigation::menu"></div> <form th:action="@{/account/update}" th:object="${user}" method="post" style="max-width: 700px;margin: 0 auto;" enctype="multipart/form-data"> <input type="hidden" name="" th:field="*{id}"> <div class="text-center"> <h1>Your Account Details </h1> </div> <div th:if="${message!=null}" class="alert alert-success text-center"> [[${message}]] </div> <div class="border border-secondary rounded p-3"> <div class="form-group row"> <label for="" class="col-sm-4 col-form-label">E-mail:</label> <div class="col-sm-8"> <input type="email" class="form-control" th:field="*{email}" readonly> </div> </div> <div class="form-group row mt-2"> <label for="" class="col-sm-4 col-form-label">First Name:</label> <div class="col-sm-8"> <input type="text" class="form-control" th:field="*{firstName}" required minlength="2" maxlength="45"> </div> </div> <div class="form-group row mt-2"> <label for="" class="col-sm-4 col-form-label">Last Name:</label> <div class="col-sm-8"> <input type="text" class="form-control" th:field="*{lastName}" required minlength="2" maxlength="45"> </div> </div> <div class="form-group row mt-2"> <label for="" class="col-sm-4 col-form-label">Password:</label> <div class="col-sm-8"> <input type="password" class="form-control" th:field="*{password}" oninput="checkPasswordMatch(document.getElementById('confirmPassword'))" placeholder="Leave blank if you don't want to change password" minlength="8" maxlength="20"> </div> </div> <div class="form-group row mt-2"> <label for="" class="col-sm-4 col-form-label">Confirm Password:</label> <div class="col-sm-8"> <input type="password" class="form-control" id="confirmPassword" oninput="checkPasswordMatch(this);" minlength="8" maxlength="20"> </div> </div> <div class="form-group row mt-2"> <label for="" class="col-sm-4 col-form-label">Assigned Roles:</label> <div class="col-sm-8"> <span><b>[[${user.roles}]]</b></span> </div> </div> <div class="form-group row mt-2"> <label for="" class="col-sm-4 col-form-label">Enabled:</label> <div class="col-sm-8"> <input type="checkbox" th:field="*{enabled}"> </div> </div> <div class="form-group row mt-2"> <label for="" class="col-sm-4 col-form-label">Photos:</label> <div class="col-sm-8"> <input type="hidden" name="" th:field="*{photo}"> <!-- accept="image/png,image/jpeg" --> <input type="file" id="fileImage" name="image" class="mb-2"> <img th:src="@{${user.photosImagePath}}" width="150" height="200" class="img-fluid" id="thumbnail" alt="Photo preview"> </div> </div> <div class="text-center"> <input type="submit" value="Save" class="btn btn-primary m-3"> <input type="button" value="Cancel" id="buttonCancel" class="btn btn-secondary"> </div> </div> </form> <div class="modal" id="modalDialog" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modalTitle"></h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" id="modalBody"> <p>Modal body text goes here.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> <head th:replace="fragments::footer"></head> </div> <!-- Bootstrap JavaScript Libraries --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous"> </script> <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script> <script th:src="@{/js/common.js}"></script> <script th:src="@{/js/common_form.js}"></script> <script> moduleUrl = "[[@{/}]]" function checkPasswordMatch(confirmPassword) { if (confirmPassword.value != $("#password").val()) { confirmPassword.setCustomValidity("Password do not match"); } else { confirmPassword.setCustomValidity(""); } } </script> </body> </html>
import {NestFactory} from '@nestjs/core'; import {AppModule} from './app.module'; // Importar en TS const cookieParser = require('cookie-parser') // Importar en JS const express = require('express') const session = require('express-session') const FileStore = require('session-file-store')(session) async function bootstrap() { const app = await NestFactory.create(AppModule) as any; // AQUI CONFIGURAR CUALQUIER COSA //app.use(cookieParser()) // app.use(cookieParser('Me gusta el hornado de ibarra')) app.use(cookieParser('DelUnoAlOchoEnLetras')); app.set('view engine' , 'ejs'); app.use(express.static('publico')); app.use( session({ name: 'server-session-id', secret: 'No sera de tomar un traguito', resave: true, saveUninitialized: true, cookie: {secure: false}, store: new FileStore(), }), ); await app.listen(3001); } bootstrap();
<template> <v-data-table :items="trabajadores" :headers="headers" dense :search="search"> <template v-slot:top> <v-toolbar flat> <v-toolbar-title>Trabajadores</v-toolbar-title> <v-divider class="mx-4" inset vertical ></v-divider> <v-text-field v-model="search" label="Busqueda" dense /> <v-divider class="mx-4" inset vertical ></v-divider> </v-toolbar> </template> <template v-slot:item.photo="{ item }"> <v-img :src="getPhoto(item.photo)" max-height="50" max-width="70" ></v-img> </template> <template v-slot:item.acciones="{ item }"> <v-btn small class="success" @click="restore(item)"><v-icon small>{{ "fas fa-trash-restore" }}</v-icon></v-btn> </template> </v-data-table> </template> <script> export default { data(){ return { search:'', trabajadores:[], }; }, computed:{ headers(){ return [ {text:'',value:'photo'}, {text:'DNI',value:'dni'}, {text:'Apellido Paterno',value:'ape_paterno'}, {text:'Apellido Materno',value:'ape_materno'}, {text:'Nombres',value:'nombres'}, {text:'Direccion',value:'direccion'}, {text:'Celular',value:'celular'}, {text:'Estado',value:'estado'}, {text:'',value:'acciones'}, ]; } }, mounted(){ this.getData() }, methods:{ getData(){ axios.get('/trabajadores-trashed').then(response=>{this.trabajadores=response.data}).catch() }, restore(item){ swal({ title: "Restauracion!", text: "De sea restaurar a: "+item.ape_paterno+" "+item.ape_materno+" "+item.nombres+"?", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (!willDelete) return false let formData = new FormData formData.append('id',item.dni) axios.post('/trabajador-restore',formData).then(response =>{ swal("Restauracion del Trabajador exitosa!") location.reload(1000) }).catch(error =>{ var texto=""; for (var property in error.response.data.errors){ texto = texto + error.response.data.errors[property]+'\n'; } const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 2000, timerProgressBar: true, onOpen: (toast) => { toast.addEventListener('mouseenter', Swal.stopTimer) toast.addEventListener('mouseleave', Swal.resumeTimer) } }); Toast.fire({ icon: 'warning', title : texto }) }) }) }, getPhoto(foto){ return "storage/images/trabajadores/"+foto }, }, } </script>
import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common'; import { FailException } from './FailException'; @Catch(FailException) export class FailFilter<T> implements ExceptionFilter { catch(exception: T, host: ArgumentsHost) { console.log('FailFilter', exception, host); // 通过 host.getType() 可以判断当前请求的连接类型 // 根据不同的连接类型,返回不同的响应 if (host.getType() === 'http') { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const request = ctx.getRequest(); response.status(500).json({ statusCode: 500, connectionType: 'http', timestamp: new Date().toISOString(), path: request.url, message: exception['msg'], }); } else if (host.getType() === 'ws') { return { statusCode: 500, connectionType: 'ws', timestamp: new Date().toISOString(), }; } else if (host.getType() === 'rpc') { return { statusCode: 500, connectionType: 'rpc', timestamp: new Date().toISOString(), }; } } }