text
stringlengths
184
4.48M
package com.nnk.springboot.service; import com.nnk.springboot.domain.BidList; import com.nnk.springboot.domain.CurvePoint; import com.nnk.springboot.repositories.CurvePointRepository; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.*; import static org.mockito.Mockito.doNothing; @ExtendWith(MockitoExtension.class) public class CurvePointServiceTest { @Mock CurvePointRepository curvePointRepository; @InjectMocks CurveService service; @Test void findCurveById_OK() { when(curvePointRepository.findById(any())).thenReturn(Optional.of(new CurvePoint())); assertDoesNotThrow(() -> service.findCurveById(1)); } @Test void findAllCurve_OK() { List<CurvePoint> curvePointList = new ArrayList<>(); CurvePoint curvePoint = new CurvePoint(1, 2, 3); curvePointList.add(curvePoint); when(curvePointRepository.findAll()).thenReturn(curvePointList); assertDoesNotThrow(() -> service.findAllCurve()); assertEquals(1, curvePointList.size()); } @Test void saveTrade_OK() { when(curvePointRepository.save(any(CurvePoint.class))).thenReturn(new CurvePoint()); assertDoesNotThrow(() -> service.saveCurve(new CurvePoint())); } @Test void updateTrade_OK() { CurvePoint curvePoint = new CurvePoint(1, 2, 3); when(curvePointRepository.findById(anyInt())).thenReturn(Optional.of(curvePoint)); assertDoesNotThrow(() -> service.updateCurvePoint(1, new CurvePoint(4, 5, 6))); verify(curvePointRepository, times(1)).save(curvePoint); } @Test void deleteTrade_Ok() { doNothing().when(curvePointRepository).deleteById(anyInt()); assertDoesNotThrow(() -> service.deleteCurveById(anyInt())); } }
import java.util.*; class Product { private String name; private double price; private int quantity; public Product(String name, double price, int quantity) { this.name = name; this.price = price; this.quantity = quantity; } public double getTotalPrice() { return price * quantity; } public double getPrice() { return price; } } public class ProductSalesAnalyzer { public static void main(String[] args) { // Create a list of product sales List<Product> sales = new ArrayList<>(); sales.add(new Product("Product 1", 30.0, 5)); sales.add(new Product("Product 2", 75.0, 2)); sales.add(new Product("Product 3", 120.0, 3)); sales.add(new Product("Product 4", 25.0, 8)); // Define price ranges double[] priceRanges = {0.0, 50.0, 100.0, 200.0, Double.MAX_VALUE}; // Initialize variables to store results int[] productCountByRange = new int[priceRanges.length]; double[] revenueByRange = new double[priceRanges.length]; // Iterate through each product sale and categorize it into the appropriate price range for (Product product : sales) { double totalPrice = product.getTotalPrice(); for (int i = 0; i < priceRanges.length - 1; i++) { if (totalPrice >= priceRanges[i] && totalPrice < priceRanges[i + 1]) { productCountByRange[i]++; revenueByRange[i] += totalPrice; break; } } } // Display the results System.out.println("Number of products sold within specific price ranges:"); for (int i = 0; i < priceRanges.length - 1; i++) { System.out.printf("$%.2f - $%.2f: %d products, Total Revenue: $%.2f%n", priceRanges[i], priceRanges[i + 1], productCountByRange[i], revenueByRange[i]); } } }
import React, { useState } from 'react'; import { useNavigate } from "react-router-dom"; import classnames from 'classnames'; interface IProps { title: string active: boolean onClick: () => void } export const MenuOption: React.FC<IProps> = ({ title, active, onClick }) => { const navigate = useNavigate(); const [isHoveredButton, setIsHoveredButton] = useState<boolean>(false); const handleMouseEnterCopy = () => { setIsHoveredButton(true); }; const handleMouseLeaveCopy = () => { setIsHoveredButton(false); }; const copyCodeDivStyle = { cursor: 'default', background: active ? '#E0E8FF' : '#F4F4F5', color: active ? '#6366F1' : '#71717A', borderRadius: '20px', padding: '2px 8px 2px 8px', fontSize: '14px', ...(isHoveredButton && { cursor: 'pointer', }), } as React.CSSProperties; return ( <span onClick={onClick} style={copyCodeDivStyle} onMouseEnter={handleMouseEnterCopy} onMouseLeave={handleMouseLeaveCopy} > {title} </span > ); };
/** * @param {integer} init * @return { increment: Function, decrement: Function, reset: Function } */ var createCounter = function(init) { let temp = init; const increment = function() { temp = temp + 1; return temp } const decrement = function() { temp = temp - 1; return temp; } const reset = function() { temp = init; return temp; } return { increment, decrement, reset }; }; /** * const counter = createCounter(5) * counter.increment(); // 6 * counter.reset(); // 5 * counter.decrement(); // 4 */
# Exercism Python Track ## Lessons ### Using object methods and shifting away from procedural programming Looking up object methods opens new possiblilities for ways of doing things without having to write procedures. My solution to this exercise still appears very procedural compared to other solutions I looked at after completing the exercise. Object methods can make development faster and make code simpler and more readable than following paths of logical procedure. I aim to make a program simple and easy to read. While it is hard to tell looking at a program you very recently wrote, my procedural way of writing code seems harder to read and follow. My goal is to find a balance between procedural and object-oriented programming styles that is as readable as possible. Look at this segment of my solution: ```python if letter in vowels: # 'qu' edge case handling if letter == 'u' and cluster.endswith('q'): cluster += letter text[index] = word.removeprefix(cluster) + cluster + suffix break # 'yt' edge case handling elif letter == 't' and cluster.endswith('y'): cluster = "" text[index] = word + suffix break else: text[index] = word.removeprefix(cluster) + cluster + suffix break else: # 'xr' edge case handling if (letter == 'r' and cluster.endswith('x')): cluster = "" text[index] = word + suffix break # 'yt' edge case handling elif letter == 't' and cluster.endswith('y'): cluster = "" text[index] = word + suffix break cluster += letter ``` The above seqment repeats: ```python text[index] = word.removeprefix(cluster) + cluster + suffix ``` and ```python text[index] = word + suffix ``` The purpose of this is to rotate certain letters from the front of the word to the rear. However in some of the other solutions I reviewed, this logic was replaced with a much simpler function: ```python def rotate(word): return word[1:] + word[0] ``` Using the above function, they rotated the letters of the word until a vowel was found except in the defined edge cases, and thus the solution was simplified.
require 'test_helper' class PasswordResetsTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end def setup ActionMailer::Base.deliveries.clear @user = users(:michael) end test "password resets" do get new_password_reset_url assert_template "password_resets/new" #メールアドレスが無効 post password_resets_path, params: {password_reset: {email:""}} assert_not flash.empty? assert_template "password_resets/new" #メールアドレスが有効 post password_resets_path, params: {password_reset: {email: @user.email}} assert_not_equal @user.reset_digest, @user.reload.reset_digest assert_equal 1, ActionMailer::Base.deliveries.size assert_not flash.empty? assert_redirected_to root_url #パスワードの再設定フォームのテスト user = assigns(:user) #メールアドレスが無効 get edit_password_reset_url(user.reset_token, email:"") assert_redirected_to root_url #無効なユーザー user.toggle!(:activated) get edit_password_reset_path(user.reset_token, email: user.email) assert_redirected_to root_url user.toggle!(:activated) # メールアドレスが有効で、トークンが無効 get edit_password_reset_path('wrong token', email: user.email) assert_redirected_to root_url # メールアドレスもトークンも有効 get edit_password_reset_path(user.reset_token, email: user.email) # assert_template "password_resets/edit" # assert_select "input[name=email][type=hidden][value=?]", user.email # 無効なパスワードとパスワード確認 patch password_reset_path(user.reset_token), params: { email: user.email, user: { password: "foobaz", password_confirmation: "barquux" } } # assert_select 'div#error_explanation' # パスワードが空 patch password_reset_path(user.reset_token), params: { email: user.email, user: { password: "", password_confirmation: "" } } # assert_select 'div#error_explanation' # 有効なパスワードとパスワード確認 patch password_reset_path(user.reset_token), params: { email: user.email, user: { password: "foobaz", password_confirmation: "foobaz" } } # assert is_logged_in? assert_not flash.empty? # assert_redirected_to user end end
/* eslint-disable react/jsx-one-expression-per-line */ /* eslint-disable react/prop-types */ /* eslint-disable quotes */ import axios from "axios"; import React, { useEffect, useState } from "react"; const Mastery = ({ setStudyState, setSession, setNumCards, setDeckLength, clickedDeck, }) => { // create new session const createSession = (deckId) => { axios.post(`/createSession/${deckId}`).then((response) => { setSession(response.data.session.id); }); }; const [percentMastery, setPercentMastery] = useState(0); const listDropDown = [5, 10].map((num) => ( <li key={num} onClick={() => { setNumCards(num); createSession(clickedDeck); setStudyState("study"); axios.get(`/deckLength/${clickedDeck}`).then((response) => { const { length } = response.data; setDeckLength(Math.min(length, num)); }); }} > <span className="dropdown-item">Set of {num}</span> </li> )); let studyButton; if (clickedDeck >= 1) { // create study button studyButton = ( <div className="text-center"> <button className="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false" > Study </button> <ul className="dropdown-menu" aria-labelledby="dropdownMenuButton1"> {listDropDown} </ul> </div> ); } useEffect(() => { if (clickedDeck !== null) { axios.get(`/allSessions/${clickedDeck}`).then((response) => { const mastery = response.data; let count = 0; for (const key in mastery) { if (mastery[key] === 3) { count += 1; } } axios.get(`/deckLength/${clickedDeck}`).then((response2) => { const { length } = response2.data; setPercentMastery(Math.round((count / length) * 100)); }); }); } }); return ( <div> <div className="contain"> <div className="car"> <div className="box"> <div className="percent"> <svg> <circle cx="70" cy="70" r="70" /> <circle style={{ strokeDashoffset: `calc(440 - (440 * ${percentMastery}) / 100)`, }} cx="70" cy="70" r="70" /> </svg> <div className="number"> <h2> {percentMastery} <span>%</span> </h2> </div> </div> <h2 className="text">Mastery</h2> </div> </div> </div> {studyButton} </div> ); }; export default Mastery;
class ListaTareas{ constructor(){ this._lista_tareas = [] if (localStorage.getItem('lista_tareas')) { this._lista_tareas = JSON.parse(localStorage.getItem('lista_tareas')); }else{ localStorage.setItem('lista_tareas', '') } this.crearEventos(); this.Imprimirhtml(); } Imprimirhtml(){ let tareas = document.getElementById("tareas"); let html = "" tareas.innerHTML = ""; this._lista_tareas.forEach((valor, clave) => { let checkbox = valor.checkbox ? "checked" : ""; // Crear el elemento <li> const li = document.createElement("li"); li.className = "tarea"; li.id = `tarea_${clave}`; // Crear el primer <div> const div1 = document.createElement("div"); // Crear el checkbox y establecer su estado const checkboxInput = document.createElement("input"); checkboxInput.type = "checkbox"; checkboxInput.checked = checkbox === "checked"; // Suponiendo que 'checkbox' es una cadena que indica si el checkbox debe estar marcado o no div1.appendChild(checkboxInput); // Agregar el primer <div> al <li> li.appendChild(div1); // Crear el segundo <div> con la clase "texto" const div2 = document.createElement("div"); div2.className = "texto"; // Crear el párrafo y establecer su contenido const parrafo = document.createElement("p"); parrafo.textContent = valor.tarea; parrafo.className = checkbox === "checked" ? checkbox : ""; // Añadir la clase solo si el checkbox está marcado div2.appendChild(parrafo); // Agregar el segundo <div> al <li> li.appendChild(div2); // Crear el tercer <div> const div3 = document.createElement("div"); // Crear el input hidden const hiddenInput = document.createElement("input"); hiddenInput.type = "hidden"; hiddenInput.value = `tarea_${clave}`; div3.appendChild(hiddenInput); // Crear el botón de eliminar const eliminarButton = document.createElement("button"); eliminarButton.className = "eliminar"; eliminarButton.textContent = "X"; div3.appendChild(eliminarButton); // Agregar el tercer <div> al <li> li.appendChild(div3); //Evento al boton eliminar eliminarButton.addEventListener('click', () => { this.eliminartarea(valor.tarea, li); }); checkboxInput.addEventListener('change', a => { if (a.target.checked) { parrafo.classList.add('checked'); this._lista_tareas[clave].checkbox = true; } else { parrafo.classList.remove('checked'); this._lista_tareas[clave].checkbox = false; } this.ActualizarLocalStorage(); }) tareas.appendChild(li); }); } eliminartarea(tarea, elemento){ this._lista_tareas = this._lista_tareas.filter(tarea_lista => tarea_lista.tarea != tarea); this.ActualizarLocalStorage(); elemento.remove(); } crearEventos(){ let btnAgregar = document.getElementById("agrega"); btnAgregar.addEventListener("click", a => { a.preventDefault(); let elementoAgregar = document.getElementById("textoAgregar"); let nueva_tarea = elementoAgregar.value.trim(); let obligatorio = document.querySelector("#agregar > p"); let tarea_repetida = this._lista_tareas.some( tarea => tarea.tarea == elementoAgregar.value); // si no se digito el elemento muestra el mensaje de error if (nueva_tarea === "") { obligatorio.removeAttribute("hidden"); obligatorio.textContent = "* El contenido es obligatorio"; }else if(tarea_repetida){ obligatorio.removeAttribute("hidden"); obligatorio.textContent = "* El contenido ya exite en la lista"; }else{ obligatorio.setAttribute("hidden", true); this.agregarArray(elementoAgregar.value, false); this.Imprimirhtml(); elementoAgregar.value = ""; } }); } agregarArray(texto, checkbox){ this._lista_tareas.push({ 'tarea': texto, 'checkbox': checkbox }); this.ActualizarLocalStorage(); } ActualizarLocalStorage(){ localStorage.setItem('lista_tareas', JSON.stringify(this._lista_tareas)); } } let lista = new ListaTareas();
import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) import argparse import json from tqdm import tqdm import argparse import os import torch from stllm.common.config import Config from stllm.common.registry import registry from stllm.conversation.conversation import Chat, CONV_VIDEO_LLama2, CONV_VIDEO_Vicuna0, \ CONV_VISION_LLama2, CONV_instructblip_Vicuna0 # imports modules for registration from stllm.datasets.builders import * from stllm.models import * from stllm.processors import * from stllm.runners import * from stllm.tasks import * def parse_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser() # Define the command-line arguments parser.add_argument('--video_dir', help='Directory containing video files.', required=True) parser.add_argument('--gt_file', help='Path to the ground truth file containing question.', required=True) parser.add_argument('--output_dir', help='Directory to save the model results JSON.', required=True) parser.add_argument('--output_name', help='Name of the file for storing results JSON.', required=True) parser.add_argument("--cfg-path", required=True, help="path to configuration file.") parser.add_argument("--ckpt-path", required=True, help="path to checkpoint file.") parser.add_argument("--num-frames", type=int, required=False, default=100) parser.add_argument( "--options", nargs="+", help="override some settings in the used config, the key-value pair " "in xxx=yyy format will be merged into config file (deprecate), " "change to --cfg-options instead.", ) parser.add_argument("--gpu-id", type=int, default=0, help="specify the gpu to load the model.") return parser.parse_args() def run_inference(args): """ Run inference on ActivityNet QA DataSet using the Video-ChatGPT model. Args: args: Command-line arguments. """ # Initialize the model conv_dict = {'minigpt4_vicuna0': CONV_VIDEO_Vicuna0, "instructblip_vicuna0": CONV_instructblip_Vicuna0, "instructblip_vicuna0_btadapter": CONV_instructblip_Vicuna0, 'minigpt4_vicuna0_btadapter': CONV_VIDEO_Vicuna0,} print('Initializing Chat') args = parse_args() cfg = Config(args) model_config = cfg.model_cfg model_config.device_8bit = args.gpu_id model_config.ckpt = args.ckpt_path model_cls = registry.get_model_class(model_config.arch) #model_config.eval = True model = model_cls.from_config(model_config).to('cuda:{}'.format(args.gpu_id)) for name, para in model.named_parameters(): para.requires_grad = False model.eval() CONV_VISION = conv_dict[model_config.model_type] model = model.to(torch.float16) chat = Chat(model, device='cuda:{}'.format(args.gpu_id)) # Load both ground truth file containing questions and answers with open(args.gt_file) as file: gt_file = json.load(file) # Create the output directory if it doesn't exist if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) output_list = [] # List to store the output results video_formats = ['.mp4', '.avi', '.mov', '.mkv'] # Iterate over each sample in the ground truth file index = 0 for sample in tqdm(gt_file): video_name = sample['video_name'] if 'video_name' in sample else sample['video'] id = sample['question_id'] if 'question_id' in sample else sample['id'] question = sample['question'] answer = sample['answer'] index += 1 sample_set = {'id': id, 'question': question, 'answer': answer} video_path = os.path.join(args.video_dir, video_name) # Check if the video exists chat_state = CONV_VISION.copy() img_list = [] chat.upload_video(video_path, chat_state, img_list, args.num_frames, question) chat.ask(question, chat_state) llm_message = chat.answer(conv=chat_state, img_list=img_list, num_beams=5, do_sample=False, temperature=1, system=False, max_new_tokens=300, max_length=2000)[0] sample_set['pred'] = llm_message output_list.append(sample_set) # Save the output list to a JSON file with open(os.path.join(args.output_dir, f"{args.output_name}.json"), 'w') as file: json.dump(output_list, file) if __name__ == "__main__": args = parse_args() run_inference(args)
@extends('layouts.app') @section('css') <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet"> @endsection @section('content') <div class="container mw-100"> @if(Session::has('mensaje')) <div class="alert alert-success fade show" role="alert" id="alertMes"> {{ Session::get('mensaje') }} </div> @endif <br> <a href="{{ url('parcelas/crear') }}" class="btn btn-success m-2">Registrar nueva parcela</a> <div class="table-responsive m-2"> <table id="parcelas" class="table table-striped table-bordered shadow-lg" style="width:100%; white-space: nowrap; overflow-x: auto; text-align: center;"> <thead class="bg-primary text-white"> <tr> <th scope="col">Id</th> <th scope="col">Nombre</th> <th scope="col">Propietario</th> <th scope="col">Cultivo</th> <th scope="col">Plantas totales</th> <th scope="col">Faltas</th> <th scope="col">Provincia</th> <th scope="col">Municipio</th> <th scope="col">Agregado</th> <th scope="col">Zona</th> <th scope="col">Polígono</th> <th scope="col">Parcela</th> <th scope="col">Superficie total (ha)</th> <th scope="col">Superficie en uso (ha)</th> <th scope="col">Recinto</th> <th scope="col">Pendiente</th> <th scope="col">Referencia catastral</th> <th scope="col">Acciones</th> </tr> </thead> <tbody> @foreach($parcelas as $parcela) <tr> <th scope="row">{{ $parcela->id }}</th> <td>{{ $parcela->nombre }}</td> <td>{{ $parcela->propietario }}</td> <td>{{ $parcela->cultivo }}</td> <td>{{ $parcela->num_uni_total }}</td> <td>{{ $parcela->num_uni_falta }}</td> <td>{{ $parcela->provincia_id }}</td> <td>{{ $parcela->municipio_id }}</td> <td>{{ $parcela->agregado }}</td> <td>{{ $parcela->zona }}</td> <td>{{ $parcela->poligono }}</td> <td>{{ $parcela->parcela }}</td> <td>{{ $parcela->superficie_total }}</td> <td>{{ $parcela->superficie_uso }}</td> <td>{{ $parcela->recinto }}</td> <td>{{ $parcela->pendiente }}</td> <td>{{ $parcela->referencia_catastral }}</td> <td> <a class="btn btn-warning" href="{{ url('parcelas/editar/'.$parcela->id) }}">Editar</a> <form action="{{ url('/parcelas/'.$parcela->id) }}" method="post" class="d-inline"> @csrf {{ method_field('DELETE') }} <input class="btn btn-danger" type="submit" onclick="return confirm('¿Desea borrar la parcela?')" value="Borrar"> </form> </td> </tr> @endforeach </tbody> </table> @section('js') <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script> <script> $(document).ready(function() { $('#parcelas').DataTable({ "language": { "sProcessing": "Procesando...", "sLengthMenu": "Mostrar _MENU_ parcelas", "sZeroRecords": "No se encontraron resultados", "sEmptyTable": "Ningún dato disponible en esta tabla", "sInfo": "Mostrando parcelas del _START_ al _END_ de un total de _TOTAL_ parcelas", "sInfoEmpty": "Mostrando parcelas del 0 al 0 de un total de 0 parcelas", "sInfoFiltered": "(filtrado de un total de _MAX_ parcelas)", "sInfoPostFix": "", "sSearch": "Buscar:", "sUrl": "", "sInfoThousands": ",", "sLoadingRecords": "Cargando...", "oPaginate": { "sFirst": "Primero", "sLast": "Último", "sNext": "Siguiente", "sPrevious": "Anterior" }, "oAria": { "sSortAscending": ": Activar para ordenar la columna de manera ascendente", "sSortDescending": ": Activar para ordenar la columna de manera descendente" } }, "lengthMenu": [[5, 10, 15, -1], [5, 10, 50, "Todas"]] }); }); </script> @endsection {!! $parcelas->links() !!} </div> </div> <script> // Obten el elemento del alert var alert = document.getElementById('alertMes'); // Desvanecer y ocultar el alert después de 5 segundos setTimeout(function() { alert.classList.remove('show'); }, 5000); </script> @endsection
/* * copyright (c) 2010-2023 belledonne communications sarl. * * This file is part of Liblinphone * (see https://gitlab.linphone.org/BC/public/liblinphone). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "liblinphone_tester.h" #include "local-conference-tester-functions.h" #include "shared_tester_functions.h" namespace LinphoneTest { static void create_simple_ice_conference(void) { create_conference_base(ms_time(NULL), -1, FALSE, LinphoneConferenceParticipantListTypeOpen, FALSE, LinphoneMediaEncryptionNone, TRUE, LinphoneConferenceLayoutGrid, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, LinphoneMediaDirectionRecvOnly, TRUE, LinphoneConferenceSecurityLevelNone, {LinphoneParticipantRoleSpeaker, LinphoneParticipantRoleListener}); } static void create_simple_stun_ice_conference(void) { create_conference_base(ms_time(NULL), -1, FALSE, LinphoneConferenceParticipantListTypeOpen, FALSE, LinphoneMediaEncryptionNone, TRUE, LinphoneConferenceLayoutGrid, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, LinphoneMediaDirectionSendRecv, FALSE, LinphoneConferenceSecurityLevelNone, {LinphoneParticipantRoleSpeaker, LinphoneParticipantRoleListener}); } static void create_simple_ice_srtp_conference(void) { create_conference_base(ms_time(NULL), -1, FALSE, LinphoneConferenceParticipantListTypeOpen, FALSE, LinphoneMediaEncryptionSRTP, TRUE, LinphoneConferenceLayoutGrid, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, LinphoneMediaDirectionSendRecv, FALSE, LinphoneConferenceSecurityLevelNone, {LinphoneParticipantRoleSpeaker, LinphoneParticipantRoleListener}); } static void create_simple_ice_dtls_conference(void) { create_conference_base(ms_time(NULL), -1, FALSE, LinphoneConferenceParticipantListTypeOpen, FALSE, LinphoneMediaEncryptionDTLS, TRUE, LinphoneConferenceLayoutGrid, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, LinphoneMediaDirectionSendRecv, FALSE, LinphoneConferenceSecurityLevelNone, {LinphoneParticipantRoleSpeaker, LinphoneParticipantRoleListener}); } static void create_simple_stun_ice_srtp_conference(void) { create_conference_base( ms_time(NULL), -1, FALSE, LinphoneConferenceParticipantListTypeOpen, FALSE, LinphoneMediaEncryptionSRTP, TRUE, LinphoneConferenceLayoutActiveSpeaker, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, LinphoneMediaDirectionSendRecv, FALSE, LinphoneConferenceSecurityLevelNone, {LinphoneParticipantRoleSpeaker, LinphoneParticipantRoleListener}); } static void create_simple_ice_conference_with_audio_only_participant(void) { create_conference_base(ms_time(NULL), -1, FALSE, LinphoneConferenceParticipantListTypeOpen, FALSE, LinphoneMediaEncryptionNone, TRUE, LinphoneConferenceLayoutGrid, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, LinphoneMediaDirectionRecvOnly, FALSE, LinphoneConferenceSecurityLevelNone, {LinphoneParticipantRoleSpeaker, LinphoneParticipantRoleListener}); } static void create_simple_stun_ice_conference_with_audio_only_participant(void) { create_conference_base(ms_time(NULL), -1, FALSE, LinphoneConferenceParticipantListTypeOpen, FALSE, LinphoneMediaEncryptionNone, TRUE, LinphoneConferenceLayoutGrid, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, LinphoneMediaDirectionSendRecv, FALSE, LinphoneConferenceSecurityLevelNone, {LinphoneParticipantRoleSpeaker, LinphoneParticipantRoleListener}); } static void create_simple_stun_ice_srtp_conference_with_audio_only_participant(void) { create_conference_base(ms_time(NULL), -1, FALSE, LinphoneConferenceParticipantListTypeOpen, FALSE, LinphoneMediaEncryptionSRTP, TRUE, LinphoneConferenceLayoutGrid, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, LinphoneMediaDirectionRecvOnly, FALSE, LinphoneConferenceSecurityLevelNone, {LinphoneParticipantRoleSpeaker, LinphoneParticipantRoleListener}); } static void create_simple_point_to_point_encrypted_ice_conference(void) { create_conference_base( ms_time(NULL), -1, TRUE, LinphoneConferenceParticipantListTypeOpen, FALSE, LinphoneMediaEncryptionNone, TRUE, LinphoneConferenceLayoutGrid, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, LinphoneMediaDirectionRecvOnly, FALSE, LinphoneConferenceSecurityLevelPointToPoint, {LinphoneParticipantRoleSpeaker, LinphoneParticipantRoleListener}); } static void create_simple_ice_conference_merging_calls(void) { create_simple_conference_merging_calls_base(TRUE, LinphoneConferenceLayoutActiveSpeaker, TRUE, FALSE, TRUE, LinphoneConferenceSecurityLevelNone, FALSE); } static void abort_call_to_ice_conference(void) { Focus focus("chloe_rc"); { // to make sure focus is destroyed after clients. ClientConference marie("marie_rc", focus.getConferenceFactoryAddress()); ClientConference pauline("pauline_rc", focus.getConferenceFactoryAddress()); ClientConference laure("laure_tcp_rc", focus.getConferenceFactoryAddress()); focus.registerAsParticipantDevice(marie); focus.registerAsParticipantDevice(pauline); focus.registerAsParticipantDevice(laure); setup_conference_info_cbs(marie.getCMgr()); const LinphoneConferenceLayout layout = LinphoneConferenceLayoutGrid; bctbx_list_t *coresList = NULL; for (auto mgr : {focus.getCMgr(), marie.getCMgr(), pauline.getCMgr(), laure.getCMgr()}) { if (mgr != focus.getCMgr()) { linphone_core_set_default_conference_layout(mgr->lc, layout); } const bctbx_list_t *accounts = linphone_core_get_account_list(mgr->lc); for (const bctbx_list_t *account_it = accounts; account_it != NULL; account_it = account_it->next) { LinphoneAccount *account = (LinphoneAccount *)(bctbx_list_get_data(account_it)); enable_stun_in_account(mgr, account, TRUE, TRUE); } enable_stun_in_mgr(mgr, TRUE, TRUE, TRUE, TRUE); coresList = bctbx_list_append(coresList, mgr->lc); } linphone_core_set_file_transfer_server(marie.getLc(), file_transfer_url); std::list<LinphoneCoreManager *> conferenceMgrs{focus.getCMgr(), marie.getCMgr(), pauline.getCMgr(), laure.getCMgr()}; std::list<LinphoneCoreManager *> participants{pauline.getCMgr(), laure.getCMgr()}; auto members = participants; members.push_back(marie.getCMgr()); time_t start_time = ms_time(NULL); int duration = -1; time_t end_time = (duration <= 0) ? -1 : (start_time + duration * 60); const char *initialSubject = "Test aborted ICE call"; const char *description = "Grenoble"; LinphoneConferenceSecurityLevel security_level = LinphoneConferenceSecurityLevelNone; stats focus_stat = focus.getStats(); bctbx_list_t *participant_infos = NULL; std::map<LinphoneCoreManager *, LinphoneParticipantInfo *> participantList; LinphoneParticipantRole role = LinphoneParticipantRoleSpeaker; for (auto &p : participants) { LinphoneParticipantInfo *participant_info = linphone_participant_info_new(p->identity); linphone_participant_info_set_role(participant_info, role); participant_infos = bctbx_list_append(participant_infos, participant_info); participantList.insert(std::make_pair(p, participant_info)); role = (role == LinphoneParticipantRoleSpeaker) ? LinphoneParticipantRoleListener : LinphoneParticipantRoleSpeaker; } LinphoneAddress *confAddr = create_conference_on_server(focus, marie, participantList, start_time, end_time, initialSubject, description, TRUE, security_level); BC_ASSERT_PTR_NOT_NULL(confAddr); char *confAddrStr = (confAddr) ? linphone_address_as_string(confAddr) : NULL; // Chat room creation to send ICS BC_ASSERT_TRUE(wait_for_list(coresList, &marie.getStats().number_of_LinphoneConferenceStateCreated, 2, liblinphone_tester_sip_timeout)); for (auto mgr : {marie.getCMgr(), pauline.getCMgr(), laure.getCMgr()}) { LinphoneCallParams *new_params = linphone_core_create_call_params(mgr->lc, nullptr); ms_message("%s calls conference %s", linphone_core_get_identity(mgr->lc), confAddrStr); LinphoneCall *call = linphone_core_invite_address_with_params_2(mgr->lc, confAddr, new_params, NULL, nullptr); BC_ASSERT_PTR_NOT_NULL(call); linphone_call_params_unref(new_params); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneCallOutgoingProgress, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneCallStreamsRunning, 1, liblinphone_tester_sip_timeout)); if (call) { linphone_call_terminate(call); } BC_ASSERT_TRUE( wait_for_list(coresList, &mgr->stat.number_of_LinphoneCallEnd, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE( wait_for_list(coresList, &mgr->stat.number_of_LinphoneCallReleased, 1, liblinphone_tester_sip_timeout)); } BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneCallIncomingReceived, 3, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE( wait_for_list(coresList, &focus.getStats().number_of_LinphoneCallEnd, 3, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneCallReleased, 3, liblinphone_tester_sip_timeout)); for (auto mgr : {marie.getCMgr(), pauline.getCMgr(), laure.getCMgr()}) { reset_counters(&mgr->stat); ms_message("%s calls again conference %s", linphone_core_get_identity(mgr->lc), confAddrStr); LinphoneCallParams *new_params = linphone_core_create_call_params(mgr->lc, nullptr); linphone_core_invite_address_with_params_2(mgr->lc, confAddr, new_params, NULL, nullptr); linphone_call_params_unref(new_params); } for (auto mgr : {marie.getCMgr(), pauline.getCMgr(), laure.getCMgr()}) { BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneCallOutgoingProgress, 1, liblinphone_tester_sip_timeout)); int no_streams_running = 2; BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneCallUpdating, (no_streams_running - 1), liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneCallStreamsRunning, no_streams_running, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneConferenceStateCreated, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneSubscriptionOutgoingProgress, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneSubscriptionActive, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_NotifyFullStateReceived, 1, liblinphone_tester_sip_timeout)); } BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneCallIncomingReceived, focus_stat.number_of_LinphoneCallIncomingReceived + 3, liblinphone_tester_sip_timeout)); int focus_no_streams_running = 6; BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneCallUpdatedByRemote, focus_stat.number_of_LinphoneCallUpdatedByRemote + (focus_no_streams_running - 3), liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneCallStreamsRunning, focus_stat.number_of_LinphoneCallStreamsRunning + focus_no_streams_running, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneConferenceStateCreated, focus_stat.number_of_LinphoneConferenceStateCreated + 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneSubscriptionIncomingReceived, focus_stat.number_of_LinphoneSubscriptionIncomingReceived + 3, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneSubscriptionActive, focus_stat.number_of_LinphoneSubscriptionActive + 3, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_participants_added, focus_stat.number_of_participants_added + 3, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_participant_devices_added, focus_stat.number_of_participant_devices_added + 3, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_participant_devices_joined, focus_stat.number_of_participant_devices_joined + 3, liblinphone_tester_sip_timeout)); std::map<LinphoneCoreManager *, LinphoneParticipantInfo *> memberList = fill_memmber_list(members, participantList, marie.getCMgr(), participant_infos); wait_for_conference_streams({focus, marie, pauline, laure}, conferenceMgrs, focus.getCMgr(), memberList, confAddr, FALSE); LinphoneConference *fconference = linphone_core_search_conference_2(focus.getLc(), confAddr); BC_ASSERT_PTR_NOT_NULL(fconference); // wait bit more to detect side effect if any CoreManagerAssert({focus, marie, pauline, laure}).waitUntil(chrono::seconds(2), [] { return false; }); for (auto mgr : {focus.getCMgr(), marie.getCMgr(), pauline.getCMgr(), laure.getCMgr()}) { LinphoneAddress *uri = linphone_address_new(linphone_core_get_identity(mgr->lc)); LinphoneConference *pconference = linphone_core_search_conference_2(mgr->lc, confAddr); linphone_address_unref(uri); BC_ASSERT_PTR_NOT_NULL(pconference); if (pconference) { const LinphoneConferenceParams *conference_params = linphone_conference_get_current_params(pconference); int no_participants = 0; if (start_time >= 0) { BC_ASSERT_EQUAL((long long)linphone_conference_params_get_start_time(conference_params), (long long)start_time, long long, "%lld"); } BC_ASSERT_EQUAL((long long)linphone_conference_params_get_end_time(conference_params), (long long)end_time, long long, "%lld"); BC_ASSERT_EQUAL((int)linphone_conference_params_get_security_level(conference_params), (int)security_level, int, "%0d"); if (mgr == focus.getCMgr()) { no_participants = 3; BC_ASSERT_FALSE(linphone_conference_is_in(pconference)); } else { no_participants = 2; BC_ASSERT_TRUE(linphone_conference_is_in(pconference)); LinphoneCall *current_call = linphone_core_get_current_call(mgr->lc); BC_ASSERT_PTR_NOT_NULL(current_call); if (current_call) { BC_ASSERT_EQUAL((int)linphone_call_get_state(current_call), (int)LinphoneCallStateStreamsRunning, int, "%0d"); } BC_ASSERT_TRUE(check_ice(mgr, focus.getCMgr(), LinphoneIceStateHostConnection)); const LinphoneVideoActivationPolicy *pol = linphone_core_get_video_activation_policy(mgr->lc); bool_t enabled = !!linphone_video_activation_policy_get_automatically_initiate(pol); LinphoneCall *pcall = linphone_core_get_call_by_remote_address2(mgr->lc, confAddr); BC_ASSERT_PTR_NOT_NULL(pcall); if (pcall) { const LinphoneCallParams *call_lparams = linphone_call_get_params(pcall); BC_ASSERT_EQUAL(linphone_call_params_video_enabled(call_lparams), enabled, int, "%0d"); const LinphoneCallParams *call_rparams = linphone_call_get_remote_params(pcall); BC_ASSERT_EQUAL(linphone_call_params_video_enabled(call_rparams), enabled, int, "%0d"); const LinphoneCallParams *call_cparams = linphone_call_get_current_params(pcall); BC_ASSERT_EQUAL(linphone_call_params_video_enabled(call_cparams), enabled, int, "%0d"); } LinphoneCall *ccall = linphone_core_get_call_by_remote_address2(focus.getLc(), mgr->identity); BC_ASSERT_PTR_NOT_NULL(ccall); if (ccall) { const LinphoneCallParams *call_lparams = linphone_call_get_params(ccall); BC_ASSERT_EQUAL(linphone_call_params_video_enabled(call_lparams), enabled, int, "%0d"); const LinphoneCallParams *call_rparams = linphone_call_get_remote_params(ccall); BC_ASSERT_EQUAL(linphone_call_params_video_enabled(call_rparams), enabled, int, "%0d"); const LinphoneCallParams *call_cparams = linphone_call_get_current_params(ccall); BC_ASSERT_EQUAL(linphone_call_params_video_enabled(call_cparams), enabled, int, "%0d"); } } BC_ASSERT_EQUAL(linphone_conference_get_participant_count(pconference), no_participants, int, "%0d"); bctbx_list_t *devices = linphone_conference_get_participant_device_list(pconference); BC_ASSERT_EQUAL(bctbx_list_size(devices), 3, size_t, "%zu"); if (devices) { bctbx_list_free_with_data(devices, (void (*)(void *))linphone_participant_device_unref); } BC_ASSERT_STRING_EQUAL(linphone_conference_get_subject(pconference), initialSubject); LinphoneParticipant *me = linphone_conference_get_me(pconference); BC_ASSERT_TRUE(linphone_participant_is_admin(me) == ((mgr == marie.getCMgr()) || (mgr == focus.getCMgr()))); BC_ASSERT_TRUE(linphone_address_weak_equal(linphone_participant_get_address(me), mgr->identity)); bctbx_list_t *participants = linphone_conference_get_participant_list(pconference); for (bctbx_list_t *itp = participants; itp; itp = bctbx_list_next(itp)) { LinphoneParticipant *p = (LinphoneParticipant *)bctbx_list_get_data(itp); BC_ASSERT_TRUE( linphone_participant_is_admin(p) == linphone_address_weak_equal(linphone_participant_get_address(p), marie.getCMgr()->identity)); } bctbx_list_free_with_data(participants, (void (*)(void *))linphone_participant_unref); if (mgr != focus.getCMgr()) { BC_ASSERT_TRUE(CoreManagerAssert({focus, marie, pauline, laure}) .waitUntil(chrono::seconds(10), [&fconference, &pconference] { return check_conference_ssrc(fconference, pconference); })); } } } // Wait a little bit wait_for_list(coresList, NULL, 0, 3000); std::list<LinphoneCoreManager *> mgrsToRemove{pauline.getCMgr()}; mgrsToRemove.push_back(laure.getCMgr()); stats marie_stat = marie.getStats(); for (auto mgr : mgrsToRemove) { LinphoneCall *call = linphone_core_get_current_call(mgr->lc); BC_ASSERT_PTR_NOT_NULL(call); if (call) { linphone_call_terminate(call); BC_ASSERT_TRUE( wait_for_list(coresList, &mgr->stat.number_of_LinphoneCallEnd, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneCallReleased, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneSubscriptionTerminated, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneConferenceStateTerminationPending, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneConferenceStateTerminated, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &mgr->stat.number_of_LinphoneConferenceStateDeleted, 1, liblinphone_tester_sip_timeout)); LinphoneAddress *uri = linphone_address_new(linphone_core_get_identity(mgr->lc)); LinphoneConference *pconference = linphone_core_search_conference(mgr->lc, NULL, uri, confAddr, NULL); BC_ASSERT_PTR_NULL(pconference); linphone_address_unref(uri); } } BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_participants_removed, focus_stat.number_of_participants_removed + 2, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_participant_devices_removed, focus_stat.number_of_participant_devices_removed + 2, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &marie.getStats().number_of_participants_removed, marie_stat.number_of_participants_removed + 2, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &marie.getStats().number_of_participant_devices_removed, marie_stat.number_of_participant_devices_removed + 2, liblinphone_tester_sip_timeout)); // wait bit more to detect side effect if any CoreManagerAssert({focus, marie, pauline, laure}).waitUntil(chrono::seconds(2), [] { return false; }); BC_ASSERT_EQUAL(marie.getStats().number_of_LinphoneConferenceStateTerminationPending, marie_stat.number_of_LinphoneConferenceStateTerminationPending, int, "%d"); BC_ASSERT_EQUAL(marie.getStats().number_of_LinphoneConferenceStateTerminated, marie_stat.number_of_LinphoneConferenceStateTerminated, int, "%d"); BC_ASSERT_EQUAL(marie.getStats().number_of_LinphoneConferenceStateDeleted, marie_stat.number_of_LinphoneConferenceStateDeleted, int, "%d"); BC_ASSERT_EQUAL(focus.getStats().number_of_LinphoneConferenceStateTerminationPending, focus_stat.number_of_LinphoneConferenceStateTerminationPending, int, "%d"); BC_ASSERT_EQUAL(focus.getStats().number_of_LinphoneConferenceStateTerminated, focus_stat.number_of_LinphoneConferenceStateTerminated, int, "%d"); BC_ASSERT_EQUAL(focus.getStats().number_of_LinphoneConferenceStateDeleted, focus_stat.number_of_LinphoneConferenceStateDeleted, int, "%d"); for (auto mgr : {focus.getCMgr(), marie.getCMgr()}) { LinphoneConference *pconference = linphone_core_search_conference_2(mgr->lc, confAddr); BC_ASSERT_PTR_NOT_NULL(pconference); if (pconference) { BC_ASSERT_EQUAL(linphone_conference_get_participant_count(pconference), ((mgr == focus.getCMgr()) ? 1 : 0), int, "%0d"); bctbx_list_t *devices = linphone_conference_get_participant_device_list(pconference); BC_ASSERT_EQUAL(bctbx_list_size(devices), 1, size_t, "%zu"); if (devices) { bctbx_list_free_with_data(devices, (void (*)(void *))linphone_participant_device_unref); } BC_ASSERT_STRING_EQUAL(linphone_conference_get_subject(pconference), initialSubject); } } const bctbx_list_t *calls = linphone_core_get_calls(marie.getLc()); BC_ASSERT_EQUAL(bctbx_list_size(calls), 1, size_t, "%zu"); LinphoneCall *call = linphone_core_get_call_by_remote_address2(marie.getLc(), focus.getCMgr()->identity); BC_ASSERT_PTR_NOT_NULL(call); if (call) { linphone_call_terminate(call); BC_ASSERT_TRUE(wait_for_list(coresList, &marie.getStats().number_of_LinphoneCallEnd, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &marie.getStats().number_of_LinphoneCallReleased, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &marie.getStats().number_of_LinphoneSubscriptionTerminated, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &marie.getStats().number_of_LinphoneConferenceStateTerminationPending, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &marie.getStats().number_of_LinphoneConferenceStateTerminated, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &marie.getStats().number_of_LinphoneConferenceStateDeleted, 1, liblinphone_tester_sip_timeout)); // Explicitely terminate conference as those on server are static by default LinphoneConference *pconference = linphone_core_search_conference_2(focus.getLc(), confAddr); BC_ASSERT_PTR_NOT_NULL(pconference); if (pconference) { linphone_conference_terminate(pconference); } BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneConferenceStateTerminationPending, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneConferenceStateTerminated, 1, liblinphone_tester_sip_timeout)); BC_ASSERT_TRUE(wait_for_list(coresList, &focus.getStats().number_of_LinphoneConferenceStateDeleted, 1, liblinphone_tester_sip_timeout)); } for (auto mgr : {marie.getCMgr(), pauline.getCMgr(), laure.getCMgr()}) { const bctbx_list_t *call_logs = linphone_core_get_call_logs(mgr->lc); BC_ASSERT_EQUAL((unsigned int)bctbx_list_size(call_logs), 2, unsigned int, "%u"); bctbx_list_t *mgr_focus_call_log = linphone_core_get_call_history_2(mgr->lc, focus.getCMgr()->identity, mgr->identity); BC_ASSERT_PTR_NOT_NULL(mgr_focus_call_log); if (mgr_focus_call_log) { BC_ASSERT_EQUAL((unsigned int)bctbx_list_size(mgr_focus_call_log), 2, unsigned int, "%u"); for (bctbx_list_t *it = mgr_focus_call_log; it; it = bctbx_list_next(it)) { LinphoneCallLog *call_log = (LinphoneCallLog *)it->data; BC_ASSERT_TRUE(linphone_call_log_was_conference(call_log)); } bctbx_list_free_with_data(mgr_focus_call_log, (bctbx_list_free_func)linphone_call_log_unref); } } // wait bit more to detect side effect if any CoreManagerAssert({focus, marie, pauline, laure}).waitUntil(chrono::seconds(2), [] { return false; }); bctbx_list_free_with_data(participant_infos, (bctbx_list_free_func)linphone_participant_info_unref); if (confAddrStr) ms_free(confAddrStr); linphone_address_unref(confAddr); bctbx_list_free(coresList); } } } // namespace LinphoneTest static test_t local_conference_scheduled_ice_conference_tests[] = { TEST_ONE_TAG("Create simple ICE conference", LinphoneTest::create_simple_ice_conference, "ICE"), TEST_ONE_TAG("Create simple STUN+ICE conference", LinphoneTest::create_simple_stun_ice_conference, "ICE"), TEST_ONE_TAG("Create simple ICE SRTP conference", LinphoneTest::create_simple_ice_srtp_conference, "ICE"), TEST_ONE_TAG("Create simple ICE DTLS conference", LinphoneTest::create_simple_ice_dtls_conference, "ICE"), TEST_ONE_TAG("Create simple STUN+ICE SRTP conference", LinphoneTest::create_simple_stun_ice_srtp_conference, "ICE"), TEST_ONE_TAG("Create simple ICE conference with audio only participant", LinphoneTest::create_simple_ice_conference_with_audio_only_participant, "ICE"), TEST_ONE_TAG("Create simple STUN+ICE conference with audio only participant", LinphoneTest::create_simple_stun_ice_conference_with_audio_only_participant, "ICE"), TEST_ONE_TAG("Create simple STUN+ICE SRTP conference with audio only participant", LinphoneTest::create_simple_stun_ice_srtp_conference_with_audio_only_participant, "ICE"), TEST_ONE_TAG("Create simple point-to-point encrypted ICE conference", LinphoneTest::create_simple_point_to_point_encrypted_ice_conference, "ICE"), TEST_ONE_TAG("Create simple ICE conference by merging calls", LinphoneTest::create_simple_ice_conference_merging_calls, "ICE"), /* because of aborted calls*/ TEST_TWO_TAGS("Abort call to ICE conference", LinphoneTest::abort_call_to_ice_conference, "LeaksMemory", "ICE") /* because of aborted calls*/ }; test_suite_t local_conference_test_suite_scheduled_ice_conference = { "Local conference tester (Scheduled ICE Conference)", NULL, NULL, liblinphone_tester_before_each, liblinphone_tester_after_each, sizeof(local_conference_scheduled_ice_conference_tests) / sizeof(local_conference_scheduled_ice_conference_tests[0]), local_conference_scheduled_ice_conference_tests, 0, 4 /*cpu_weight : video conference uses more resources */ };
package com.busik.busik.Passanger.ApiResponse; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Date; public class Passenger implements Comparable<Passenger>{ @SerializedName("id") @Expose private Integer id; @SerializedName("fio") @Expose private String fio; @SerializedName("phone") @Expose private String phone; @SerializedName("email") @Expose private String email; @SerializedName("live_city") @Expose private String liveCity; @SerializedName("live_country") @Expose private String liveCountry; @SerializedName("rating") @Expose private Integer rating; @SerializedName("application") @Expose private Application application; private Date dateSort; public Date getDateSort() { return dateSort; } public void setDateSort(Date dateSort) { this.dateSort = dateSort; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFio() { return fio; } public void setFio(String fio) { this.fio = fio; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLiveCity() { return liveCity; } public void setLiveCity(String liveCity) { this.liveCity = liveCity; } public String getLiveCountry() { return liveCountry; } public void setLiveCountry(String liveCountry) { this.liveCountry = liveCountry; } public Integer getRating() { return rating; } public void setRating(Integer rating) { this.rating = rating; } public Application getApplication() { return application; } public void setApplication(Application application) { this.application = application; } @Override public String toString() { return "Passenger{" + "id=" + id + ", fio='" + fio + '\'' + ", phone='" + phone + '\'' + ", email='" + email + '\'' + ", liveCity='" + liveCity + '\'' + ", liveCountry='" + liveCountry + '\'' + ", rating=" + rating + ", application=" + application + '}'; } @Override public int compareTo(Passenger o) { return getDateSort().compareTo(o.getDateSort()); } }
import React, { useState, useEffect } from "react"; import { auth, db } from "../../firebase/config"; import { getDoc, doc } from "firebase/firestore"; import { useAppContext } from "../../context/AppProvider"; import { useParams, useNavigate } from "react-router-dom"; import { HiOutlineArrowSmLeft, HiOutlineArrowSmRight } from "react-icons/hi"; import { AiOutlineCheckCircle, AiOutlineCloseCircle } from "react-icons/ai"; const Question = ({ currentQuestion, listQuestion }) => { return ( <div className="flex flex-col justify-center items-start ml-8 mt-4"> <div className="text-2xl"> {"Câu" + ` ${currentQuestion}: ` + listQuestion?.question[currentQuestion - 1]?.question} </div> <div className="flex flex-col mt-2"> {listQuestion?.question[currentQuestion - 1]?.answer.map((a, index) => ( <div> <div className="flex items-center"> <div className="my-2" key={index}> <input readOnly type="radio" name="radio-101" value={a} checked={ listQuestion.question[currentQuestion - 1].yourChoice === a } className="radio radio-success" /> <span className="ml-3 text-xl">{a}</span> </div> {a === listQuestion.question[currentQuestion - 1].correctAnswer ? ( <AiOutlineCheckCircle className="ml-10 text-3xl text-green-700" /> ) : ( "" )} {a !== listQuestion.question[currentQuestion - 1].correctAnswer && listQuestion.question[currentQuestion - 1].yourChoice === a ? ( <AiOutlineCloseCircle className="ml-10 text-3xl text-red-500" /> ) : ( "" )} </div> </div> ))} </div> </div> ); }; const FilterQuestion = ({ handleChangeFilter }) => { return ( <select defaultValue={"all"} onChange={(e) => handleChangeFilter(e.target.value)} className="w-[172px] text-center select select-bordered max-w-md select-sm mb-2" > <option value="all" selected> Tất cả </option> <option value="correct">Câu trả lời đúng</option> <option value="incorrect">Câu trả lời sai</option> <option value="uncompleted">Chưa làm</option> </select> ); }; function ExamResult() { const { id } = useParams(); const navigate = useNavigate(); const [listQuestion, setListQuestion] = useState(); const [currentQuestion, setCurrentQuestion] = useState(1); const [filterQuestion, setFilterQuestion] = useState(listQuestion); const [loading, setLoading] = useState(true); const { setNavTitile } = useAppContext(); //Lấy dữ liệu bài kiểm tra tương ứng useEffect(() => { const getListQuestion = async () => { const docRef = doc(db, "histories", `${auth.currentUser.uid}/exams/${id}`); const docSnap = await getDoc(docRef); setListQuestion({ ...docSnap.data() }); }; getListQuestion(); setLoading(false); }, [id]); //Back và Next Question const handleNextQuestion = (e) => { if (currentQuestion >= listQuestion.numberQuestion) { e.preventDefault(); return; } else { setCurrentQuestion(currentQuestion + 1); } }; const handlePrevQuestion = (e) => { if (currentQuestion <= 1) { e.preventDefault(); return; } else { setCurrentQuestion(currentQuestion - 1); } }; //Filter questions const handleChangeFilterQuestion = (filterValue) => { switch (filterValue) { case "all": setFilterQuestion(listQuestion); setCurrentQuestion(listQuestion.question[0].index); break; case "correct": setFilterQuestion({ ...listQuestion, question: listQuestion.question.filter((q) => q.correctAnswer === q.yourChoice), }); setCurrentQuestion( listQuestion.question.filter((q) => q.correctAnswer === q.yourChoice)[0].index ); break; case "incorrect": setFilterQuestion({ ...listQuestion, question: listQuestion.question.filter( (q) => q.correctAnswer !== q.yourChoice && !!q.yourChoice ), }); setCurrentQuestion( listQuestion.question.filter((q) => q.correctAnswer !== q.yourChoice)[0].index ); break; case "uncompleted": setFilterQuestion({ ...listQuestion, question: listQuestion.question.filter((q) => !!!q.yourChoice), }); setCurrentQuestion(listQuestion.question.filter((q) => !!!q.yourChoice)[0].index); break; default: break; } }; return ( <> {loading ? ( <div>loading...</div> ) : ( <div className="w-full h-full overflow-hidden flex justify-end"> {/* Câu hỏi */} <div className="flex-1 "> <Question currentQuestion={currentQuestion} listQuestion={listQuestion} /> {/* Back và Next button */} <div className="flex justify-start items-center"> <div className="flex justify-center items-center mx-4 my-2 px-4 py-2"> <button className={`btn btn-ghost btn-outline text-2xl mx-4 my-2 ${ currentQuestion <= 1 && "btn-disabled" }`} onClick={(e) => handlePrevQuestion(e)} > {/* <span className="pr-3" > Back </span> */} <HiOutlineArrowSmLeft /> </button> </div> <div className="flex justify-center items-center mx-4 my-2 px-4 py-2"> <button className={`btn btn-ghost btn-outline text-2xl mx-4 my-2 ${ currentQuestion >= listQuestion?.question.length && "btn-disabled" }`} onClick={(e) => handleNextQuestion(e)} > <HiOutlineArrowSmRight /> {/* <span className="pl-3" > Next </span> */} </button> </div> </div> </div> {/* right side bar */} <div className="flex flex-col w-[500px] h-screen text-lg shadow-xl"> <div className="flex flex-col justify-center items-center mt-8 pt-8"> <span className="mx-4 block my-4"> Số câu đã làm:{" "} {listQuestion?.question.filter((q) => !!q?.yourChoice).length} /{" "} {listQuestion?.question.length} </span> <span className="mx-4 block my-4">Lọc danh sách</span> <FilterQuestion handleChangeFilter={handleChangeFilterQuestion} /> </div> <div className={`w-[90%] min-h-0 max-h-[300px] mt-5 pt-5 mx-auto flex justify-around flex-wrap font-mono ${ listQuestion?.question.numberQuestion >= 20 ? "overflow-scroll" : "" }`} > {filterQuestion?.question.map((q, i) => ( <div className="mx-2" key={i}> <button className={`btn btn-outline mx-2 my-2 px-2 py-2 w-16 ${q.yourChoice === q.correctAnswer ? "btn-primary" : ""} `} onClick={() => setCurrentQuestion(q.index)} > Câu {q.index}{" "} {q.yourChoice === q.correctAnswer ? ( <div className="text-red-600"> <AiOutlineCheckCircle /> </div> ) : ( <div className="text-black"> <AiOutlineCloseCircle /> </div> )} </button> </div> ))} </div> <div className="mt-10 pt-4 mx-auto shadow-sm"> <button className="btn btn-outline btn-ghost" onClick={() => navigate("/user/exam-history")} > Quay lại </button> </div> </div> </div> )} </> ); } export default ExamResult;
package in.arifalimondal.auth.config; import in.arifalimondal.auth.entity.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class CustomUserDetails implements UserDetails { private String username; private String password; private Set<GrantedAuthority> authorities; public CustomUserDetails(User userCredential) { this.username = userCredential.getName(); this.password = userCredential.getPassword(); authorities = new HashSet<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); if(this.username.equalsIgnoreCase("order")) { authorities.add(new SimpleGrantedAuthority("ROLE_ORDER")); } else if(this.username.equalsIgnoreCase("product")) { authorities.add(new SimpleGrantedAuthority("ROLE_PRODUCT")); } else if(this.username.equalsIgnoreCase("admin")) { authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN")); } } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
(ns fr33m0nk.virtual-threads-demo (:require [clojure.core.async.impl.protocols :as protocols] [clojure.core.async.impl.dispatch :as dispatch] [clojure.core.async :as a] [hato.client :as http]) (:import (java.util.concurrent CyclicBarrier Executors StructuredTaskScope StructuredTaskScope$ShutdownOnFailure StructuredTaskScope$ShutdownOnSuccess StructuredTaskScope$Subtask StructuredTaskScope$Subtask$State) (java.util.function Function))) ;; Virtual threads are a part of JDK 19+ ;; Virtual thread is a JDK construct similar to Coroutines in Kotlin and Go routines in Go ;; JDK schedules Virtual threads on Platform threads using m:n scheduling ;; Virtual threads are scheduled on special ForkJoin worker thread pools ;; Why virtual threads? ;; Virtual are very lightweight is comparison to platform threads ;; Whenever JDK detects a blocking operation: ;; - it parks the blocking virtual threads (by unmounting virtual thread from platform thread) ;; - allows other virtual thread to carry on execution ;; - blocking virtual threads is a cheap operation ;; Earlier craft: ;; - asynchronous programming e.g. CompletableFuture ;; - code rewrite e.g. core.async ;; - Java agent based runtime instrumentation via bytecode rewrite e.g. kilim, quasar ;; Spinning up a 100,000 virtual threads (comment ;;platform threads ;; Below code blows up REPL!! (let [counter (atom 0) barrier (CyclicBarrier. 100000) platform-threads (into [] (map (fn [i] (-> (Thread/ofPlatform) (.unstarted #(try (Thread/sleep (long (rand-int 2000))) (.await barrier) (catch Exception e (throw e))))))) (range 100000))] (doall (pmap #(do (.start %) (swap! counter inc)) platform-threads)) (doall (pmap #(.join %) platform-threads)) (println @counter)) ;;virtual threads (let [counter (atom 0) barrier (CyclicBarrier. 500000) virtual-threads (into [] (map (fn [i] (-> (Thread/ofVirtual) (.unstarted #(try (Thread/sleep (long (rand-int 2000))) (.await barrier) (catch Exception e (throw e))))))) (range 500000))] (doall (pmap #(do (.start %) (swap! counter inc)) virtual-threads)) (doall (pmap #(.join %) virtual-threads)) (println @counter))) ;; Following function takes some time doing IO (defn make-api-request [] (http/get "https://httpbin.org/get")) ;; How to use virtual threads? ;; 1 (defn start-virtual-thread [f] (Thread/startVirtualThread f)) (comment (let [p (promise) vt (start-virtual-thread #(deliver p (select-keys (make-api-request) [:status])))] (.join vt) @p)) ;; 2 ;; JDK ships with a special executor which launch a new virtual thread per task ;; This can be used in place of any Executor service created for IO tasks (def virtual-thread-executor (Executors/newVirtualThreadPerTaskExecutor)) (comment @(.submit virtual-thread-executor #(+ 1 2)) ) ;; replacing core.async's executor service ;; This does not work with a/pipeline operators or a/thread!! as they use different thread pool ;; Rick and Morty example ;; Problem: get character profiles for first two episodes of Rick and Morty ;; Different endpoints for characters per episode and individual character profile (comment (def vt-core-async-executor (-> (Thread/ofVirtual) (.name "core-async-" 0) (.factory) (Executors/newThreadPerTaskExecutor))) (defonce async-virtual-executor (reify protocols/Executor (protocols/exec [_ r] (.execute vt-core-async-executor ^Runnable r)))) (alter-var-root #'dispatch/executor (constantly (delay async-virtual-executor))) (let [episodes [1 2] get-request #(http/get % {:as :json}) rick-morty-episode-cast-api (fn [episode] (get-request (str "https://rickandmortyapi.com/api/episode/" episode))) episode-cast-chan (->> (mapv #(a/go (println "Episode cast thread : " (Thread/currentThread)) (-> (rick-morty-episode-cast-api %) :body :characters)) episodes) (a/merge) (a/transduce (comp (mapcat identity) (distinct)) conj #{})) character-chan (->> (a/<!! episode-cast-chan) (mapv #(a/go (-> (get-request %) :body))) (a/merge) (a/into []))] (a/<!! character-chan))) ;; 3 ;; Structured Task scope (Incubator feature in JDK 19 and 20. Preview feature in JDK 21) ;; Structured concurrency emphasises on writing imperative code and blocking virtual threads as and when needed ;; Structured task scope acts as a supervisor for all the subtasks ;; All subtasks run in their own virtual thread ;; 3.1 StructuredTaskScope class can be used directly ;; the default behaviour can be overridden to support a use case (defn ->structured-scope ^StructuredTaskScope [success-handler error-handler] (proxy [StructuredTaskScope] [] (handleComplete [^StructuredTaskScope$Subtask subtask] (condp = (.state subtask) StructuredTaskScope$Subtask$State/UNAVAILABLE (throw (IllegalArgumentException. "SubTask is unavailable")) StructuredTaskScope$Subtask$State/FAILED (error-handler (.exception subtask)) StructuredTaskScope$Subtask$State/SUCCESS (success-handler (.get subtask)))))) (comment (let [accumulators (repeatedly 2 #(atom [])) ;; create success and error accumulators [success-handler error-handler] (map (fn [acc] (partial swap! acc conj)) accumulators)] (with-open [scope (->structured-scope success-handler error-handler)] (let [api-request (.fork scope #(-> (make-api-request) (select-keys [:status]))) failure (.fork scope #(throw (ex-info "boom" {}))) some-slow-task (.fork scope #(do (Thread/sleep 5000) :some-slow-task))] ; Status of tasks before join: UNAVAILABLE (run! #(printf "\nStatus of tasks before join: %s\n" (.state %)) [api-request failure some-slow-task]) (.join scope) ; Status of tasks after join: Success (run! #(printf "\nStatus of tasks after join: %s\n" (.state %)) [api-request failure some-slow-task]) (->> accumulators (map deref) (zipmap [:success :failure])))))) ;; Two customizations of StructuredTaskScope are offered out of the box ;; 3.2 Shutdown On success (comment (with-open [scope (StructuredTaskScope$ShutdownOnSuccess.)] (let [some-slow-task (.fork scope #(do (println "Sleeping") (Thread/sleep 5000) (println "Awake") :some-slow-task)) api-request (.fork scope #(-> (make-api-request) (select-keys [:status])))] (.join scope) (.result scope)))) ;; 3.3 Shutdown On Failure (comment (with-open [scope (StructuredTaskScope$ShutdownOnFailure.)] (let [some-slow-task (.fork scope #(do (println "Sleeping") (Thread/sleep 5000) (println "Awake") :some-slow-task)) failure (.fork scope #(throw (ex-info "boom" {}))) api-request (.fork scope #(-> (make-api-request) (select-keys [:status])))] (.join scope) (.throwIfFailed scope) [(.get some-slow-task) (.get api-request)]))) ;;; Gotchas ;; Virtual thread would be pinned to Platform thread if: ;; code uses synchronized blocks ;; code does FFI e.g. native code interop using JNI ;;; Platform vs Virtual thread? ;; Use platform threads when doing non-blocking and computationally intensive work ;; Use virtual threads when doing I/O intensive or computationally inexpensive work ;; Rick and Morty example ;; Problem: get character profiles for first two episodes of Rick and Morty ;; Different endpoints for characters per episode and individual character profile (comment (let [get-request #(http/get % {:as :json}) ;get-request (fn [_] (throw (Exception. "BOOM"))) custom-exception-handler (fn [scope] (reify Function (apply [_ ex] (ex-info (str "My exception " (.getMessage ex)) {:error-api scope :stacktrace (.getStackTrace ex)}))))] (with-open [episode-scope (StructuredTaskScope$ShutdownOnFailure.)] (let [episodes [1 2] rick-morty-episode-cast-api (fn [episode] (get-request (str "https://rickandmortyapi.com/api/episode/" episode))) ;; forking tasks inside functions that produce lazy sequence will lead to exceptions episode-tasks (mapv (fn [episode] (.fork episode-scope #(rick-morty-episode-cast-api episode))) episodes)] (.join episode-scope) ;; Also takes a custom exception handler (.throwIfFailed episode-scope (custom-exception-handler :episode-scope)) (let [character-uris (into #{} (mapcat #(-> % .get :body :characters)) episode-tasks)] (with-open [character-scope (StructuredTaskScope$ShutdownOnFailure.)] (let [characters (mapv (fn [uri] (.fork character-scope #(get-request uri))) character-uris)] (.join character-scope) (.throwIfFailed character-scope (custom-exception-handler :character-scope)) (into [] (map #(-> % .get :body)) characters)))))))) ;; The number of platform threads for worker pool is controlled by below parameters: ;; `-Djdk.virtualThreadScheduler.parallelism=1` ;; `-Djdk.virtualThreadScheduler.maxPoolSize=1` ;; `-Djdk.virtualThreadScheduler.minRunnable=1`
import { create } from "zustand"; export type ModelType = | "createChannel" | "visitChannel" | "deleteChannel" | "upgrade" | "settings"|"trending"|"uploadVideo"; export interface ModelSchema { label: ModelType | null; isOpen: boolean; onOpen: (label: ModelType) => void; onClose: () => void; } const UseModel = create<ModelSchema>((set) => ({ label: null, isOpen: false, onOpen: (label) => set({ isOpen: true, label }), onClose: () => set({ label: null, isOpen: false }), })); export default UseModel
import { validate } from '../validate' import { ValidoDecoratorsTestClass } from './decoratros.artifacts' describe('zod with decorators', () => { it('should pass validation for valid data', async () => { const data = { name: 'John', age: 25, tags: ['tag1', 'tag2', 123, 456], role: 'admin', role2: 'user', upperName: ' upper and trimmed ', catchExample: 'catch', fixedLengthString: 'fixed', limitedNumber: 50, fromDate: new Date(2010, 0, 1), toDate: new Date(2022, 0, 1), nullableValue: null, nullishValue: undefined, email: '[email protected]', url: 'https://example.com', emoji: '😀', uuid: '123e4567-e89b-12d3-a456-426655440000', cuid: 'cjb6mdsb90000qw42x6f7xd4r', cuid2: 'ckfgagrk70000z6b9gkz5kblv', ulid: '01FAEMFCNH0WJD3V4W5Z2N1JKK', datetime: '2022-01-01T00:00:00.000Z', ip: '127.0.0.1', uppercase: 'ABC', startsWithHello: 'HelloWorld', endsWithWorld: 'HelloWorld', greaterThanTen: 20, greaterThanOrEqualToTwenty: 30, lessThanThirty: 20, lessThanOrEqualToForty: 40, integer: 10, positiveNumber: 5, nonNegativeNumber: 0, negativeNumber: -5, nonPositiveNumber: -10, multipleOfFive: 15, finiteNumber: 123.45, safeNumber: 987.65, includesWorld: 'Hello world', stringType: 'string', numberType: 123, bigintType: BigInt(123), booleanType: true, dateType: new Date(), symbolType: Symbol('symbol'), undefinedType: undefined, nullType: null, voidType: undefined, anyType: 'any', unknownType: 'unknown', // neverType: 'never', enumType: 'A', nativeEnumType: 'RED', setType: new Set(['value1', 'value2']), mapType: new Map([['key1', 1], ['key2', 2]]), literalType: 'literal', nanType: NaN, recordType: { key1: 1, key2: 2 }, unionType: 'string', discriminatedUnionType: { type: 'A', value: 'string' }, intersectionType: { prop1: 'string', prop2: 123 }, promiseType: Promise.resolve('promise'), preprocessedType: true, customType: 'custom', andType: { prop1: 'str', prop2: 123 }, orType: { prop2: 123 }, } const result = await validate(data, ValidoDecoratorsTestClass, undefined, true) if (!result.success) { console.log(result.error) } expect(result.success).toBe(true) if (result.success) { data.upperName = 'UPPER AND TRIMMED' data.tags = ['tag1', 'tag2', '123', '456'] data.preprocessedType = 'true' as unknown as boolean expect(result.data).toEqual(data) } }) it('should fail validation for invalid data', async () => { const data = { name: 'John', age: '25', // Invalid type tags: 'tag1', // Invalid type role: 'guest', // Invalid value role2: 'admin', // Invalid value upperName: 123, // Invalid type catchExample: 123, // Invalid type fixedLengthString: 'short', // Invalid length limitedNumber: 150, // Exceeds maximum fromDate: '2022-01-01', // Invalid type toDate: '2022-12-31', // Invalid type nullableValue: undefined, // Invalid type nullishValue: false, // Invalid type email: 'test@example', // Invalid format url: 'example.com', // Invalid format emoji: 'invalid', // Invalid format uuid: '123', // Invalid format cuid: 'invalid', // Invalid format cuid2: 'invalid', // Invalid format ulid: 'invalid', // Invalid format datetime: '2022-01-01', // Invalid format ip: 'localhost', // Invalid format uppercase: 'abc', // Invalid format startsWithHello: 'World', // Does not start with "Hello" endsWithWorld: 'Hello', // Does not end with "World" greaterThanTen: 5, // Less than minimum greaterThanOrEqualToTwenty: 15, // Less than minimum lessThanThirty: 40, // Greater than maximum lessThanOrEqualToForty: 50, // Greater than maximum integer: 10.5, // Not an integer positiveNumber: -5, // Not a positive number nonNegativeNumber: -1, // Not a non-negative number negativeNumber: 0, // Not a negative number nonPositiveNumber: 5, // Not a non-positive number multipleOfFive: 12, // Not a multiple of 5 finiteNumber: Infinity, // Not a finite number safeNumber: 'safe', // Invalid type includesWorld: 'Hello', // Does not include "world" stringType: 123, // Invalid type numberType: '123', // Invalid type bigintType: '123', // Invalid type booleanType: 'true', // Invalid type dateType: '2022-01-01', // Invalid type symbolType: 'symbol', // Invalid type undefinedType: null, // Invalid type nullType: undefined, // Invalid type voidType: null, // Invalid type anyType: 123, // Invalid type unknownType: 123, // Invalid type neverType: 'never', // Invalid type enumType: 'D', // Invalid value nativeEnumType: 'Yellow', // Invalid value setType: ['value1', 'value2'], // Invalid type mapType: { key1: 'value1', key2: 'value2' }, // Invalid type literalType: 'value', // Invalid value nanType: 'NaN', // Invalid type recordType: { key1: 'value1', key2: 'value2' }, // Invalid type unionType: true, // Invalid type discriminatedUnionType: { type: 'A', value: 123 }, // Invalid type intersectionType: { prop1: 123, prop2: 'string' }, // Invalid types promiseType: 'promise', // Invalid type preprocessedType: 'value', // Invalid value after preprocessing customType: 'invalid', // Invalid value andType: true, // Invalid type orType: false, // Invalid type } const result = await validate(data, ValidoDecoratorsTestClass, undefined, true) expect(result.success).toBe(false) if (!result.success) { expect(result.error).toMatchInlineSnapshot(` [ZodError: [ { "code": "invalid_type", "expected": "number", "received": "string", "path": [ "age" ], "message": "Expected number, received string" }, { "code": "invalid_type", "expected": "array", "received": "string", "path": [ "tags" ], "message": "Expected array, received string" }, { "code": "invalid_type", "expected": "string", "received": "number", "path": [ "upperName" ], "message": "Expected string, received number" }, { "code": "too_big", "maximum": 100, "type": "number", "inclusive": true, "exact": false, "message": "Number must be less than or equal to 100", "path": [ "limitedNumber" ] }, { "code": "invalid_type", "expected": "date", "received": "string", "path": [ "fromDate" ], "message": "Expected date, received string" }, { "code": "invalid_type", "expected": "date", "received": "string", "path": [ "toDate" ], "message": "Expected date, received string" }, { "code": "invalid_type", "expected": "string", "received": "undefined", "path": [ "nullableValue" ], "message": "Required" }, { "code": "invalid_type", "expected": "string", "received": "boolean", "path": [ "nullishValue" ], "message": "Expected string, received boolean" }, { "validation": "email", "code": "invalid_string", "message": "Invalid email", "path": [ "email" ] }, { "validation": "url", "code": "invalid_string", "message": "Invalid url", "path": [ "url" ] }, { "validation": "emoji", "code": "invalid_string", "message": "Invalid emoji", "path": [ "emoji" ] }, { "validation": "uuid", "code": "invalid_string", "message": "Invalid uuid", "path": [ "uuid" ] }, { "validation": "cuid", "code": "invalid_string", "message": "Invalid cuid", "path": [ "cuid" ] }, { "validation": "ulid", "code": "invalid_string", "message": "Invalid ulid", "path": [ "ulid" ] }, { "code": "invalid_string", "validation": "datetime", "message": "Invalid datetime", "path": [ "datetime" ] }, { "validation": "ip", "code": "invalid_string", "message": "Invalid ip", "path": [ "ip" ] }, { "validation": "regex", "code": "invalid_string", "message": "Invalid", "path": [ "uppercase" ] }, { "code": "invalid_string", "validation": { "startsWith": "Hello" }, "message": "Invalid input: must start with \\"Hello\\"", "path": [ "startsWithHello" ] }, { "code": "invalid_string", "validation": { "endsWith": "World" }, "message": "Invalid input: must end with \\"World\\"", "path": [ "endsWithWorld" ] }, { "code": "too_small", "minimum": 10, "type": "number", "inclusive": false, "exact": false, "message": "Number must be greater than 10", "path": [ "greaterThanTen" ] }, { "code": "too_small", "minimum": 20, "type": "number", "inclusive": true, "exact": false, "message": "Number must be greater than or equal to 20", "path": [ "greaterThanOrEqualToTwenty" ] }, { "code": "too_big", "maximum": 30, "type": "number", "inclusive": false, "exact": false, "message": "Number must be less than 30", "path": [ "lessThanThirty" ] }, { "code": "too_big", "maximum": 40, "type": "number", "inclusive": true, "exact": false, "message": "Number must be less than or equal to 40", "path": [ "lessThanOrEqualToForty" ] }, { "code": "invalid_type", "expected": "integer", "received": "float", "message": "Expected integer, received float", "path": [ "integer" ] }, { "code": "too_small", "minimum": 0, "type": "number", "inclusive": false, "exact": false, "message": "Number must be greater than 0", "path": [ "positiveNumber" ] }, { "code": "too_small", "minimum": 0, "type": "number", "inclusive": true, "exact": false, "message": "Number must be greater than or equal to 0", "path": [ "nonNegativeNumber" ] }, { "code": "too_big", "maximum": 0, "type": "number", "inclusive": false, "exact": false, "message": "Number must be less than 0", "path": [ "negativeNumber" ] }, { "code": "too_big", "maximum": 0, "type": "number", "inclusive": true, "exact": false, "message": "Number must be less than or equal to 0", "path": [ "nonPositiveNumber" ] }, { "code": "not_multiple_of", "multipleOf": 5, "message": "Number must be a multiple of 5", "path": [ "multipleOfFive" ] }, { "code": "not_finite", "message": "Number must be finite", "path": [ "finiteNumber" ] }, { "code": "invalid_type", "expected": "number", "received": "string", "path": [ "safeNumber" ], "message": "Expected number, received string" }, { "code": "invalid_string", "validation": { "includes": "world" }, "message": "Invalid input: must include \\"world\\"", "path": [ "includesWorld" ] }, { "code": "invalid_type", "expected": "string", "received": "number", "path": [ "stringType" ], "message": "Expected string, received number" }, { "code": "invalid_type", "expected": "number", "received": "string", "path": [ "numberType" ], "message": "Expected number, received string" }, { "code": "invalid_type", "expected": "bigint", "received": "string", "path": [ "bigintType" ], "message": "Expected bigint, received string" }, { "code": "invalid_type", "expected": "boolean", "received": "string", "path": [ "booleanType" ], "message": "Expected boolean, received string" }, { "code": "invalid_type", "expected": "date", "received": "string", "path": [ "dateType" ], "message": "Expected date, received string" }, { "code": "invalid_type", "expected": "symbol", "received": "string", "path": [ "symbolType" ], "message": "Expected symbol, received string" }, { "code": "invalid_type", "expected": "undefined", "received": "null", "path": [ "undefinedType" ], "message": "Expected undefined, received null" }, { "code": "invalid_type", "expected": "null", "received": "undefined", "path": [ "nullType" ], "message": "Required" }, { "code": "invalid_type", "expected": "void", "received": "null", "path": [ "voidType" ], "message": "Expected void, received null" }, { "received": "D", "code": "invalid_enum_value", "options": [ "A", "B", "C" ], "path": [ "enumType" ], "message": "Invalid enum value. Expected 'A' | 'B' | 'C', received 'D'" }, { "received": "Yellow", "code": "invalid_enum_value", "options": [ "RED", "GREEN", "BLUE" ], "path": [ "nativeEnumType" ], "message": "Invalid enum value. Expected 'RED' | 'GREEN' | 'BLUE', received 'Yellow'" }, { "code": "invalid_type", "expected": "set", "received": "array", "path": [ "setType" ], "message": "Expected set, received array" }, { "code": "invalid_type", "expected": "map", "received": "object", "path": [ "mapType" ], "message": "Expected map, received object" }, { "received": "value", "code": "invalid_literal", "expected": "literal", "path": [ "literalType" ], "message": "Invalid literal value, expected \\"literal\\"" }, { "code": "invalid_type", "expected": "nan", "received": "string", "path": [ "nanType" ], "message": "Expected nan, received string" }, { "code": "invalid_type", "expected": "number", "received": "string", "path": [ "recordType", "key1" ], "message": "Expected number, received string" }, { "code": "invalid_type", "expected": "number", "received": "string", "path": [ "recordType", "key2" ], "message": "Expected number, received string" }, { "code": "invalid_type", "expected": "string", "received": "number", "path": [ "discriminatedUnionType", "value" ], "message": "Expected string, received number" }, { "code": "invalid_type", "expected": "string", "received": "number", "path": [ "intersectionType", "prop1" ], "message": "Expected string, received number" }, { "code": "invalid_type", "expected": "number", "received": "string", "path": [ "intersectionType", "prop2" ], "message": "Expected number, received string" }, { "code": "invalid_type", "expected": "object", "received": "boolean", "path": [ "andType" ], "message": "Expected object, received boolean" }, { "code": "invalid_type", "expected": "object", "received": "boolean", "path": [ "andType" ], "message": "Expected object, received boolean" }, { "code": "unrecognized_keys", "keys": [ "neverType" ], "path": [], "message": "Unrecognized key(s) in object: 'neverType'" }, { "code": "custom", "message": "Invalid input", "path": [ "role" ] }, { "code": "custom", "fatal": true, "path": [ "customType" ], "message": "Invalid input" }, { "code": "invalid_union", "unionErrors": [ { "issues": [ { "code": "invalid_type", "expected": "string", "received": "boolean", "path": [ "unionType" ], "message": "Expected string, received boolean" } ], "name": "ZodError" }, { "issues": [ { "code": "invalid_type", "expected": "number", "received": "boolean", "path": [ "unionType" ], "message": "Expected number, received boolean" } ], "name": "ZodError" } ], "path": [ "unionType" ], "message": "Invalid input" }, { "code": "invalid_union", "unionErrors": [ { "issues": [ { "code": "invalid_type", "expected": "object", "received": "boolean", "path": [ "orType" ], "message": "Expected object, received boolean" } ], "name": "ZodError" }, { "issues": [ { "code": "invalid_type", "expected": "object", "received": "boolean", "path": [ "orType" ], "message": "Expected object, received boolean" } ], "name": "ZodError" } ], "path": [ "orType" ], "message": "Invalid input" } ]] `) } }) })
require('dotenv').config(); const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const cors = require('cors'); const UserRouter = require('./routers/user.router'); const PostRouter = require('./routers/post.router'); const CommentRouter = require('./routers/comment.router'); // database connection part mongoose.connect(process.env.MONGODB_LINK); const db = mongoose.connection; db.once('open', () => console.log('Connected to mongoDB')); db.on('error', (err) => console.log('MongoDB connection error', err)); // express const app = express(); app.use(bodyParser.json()); app.use(cors()); // express routers connection app.use('/api/users', UserRouter); app.use('/api/posts', PostRouter); app.use('/api/comments', CommentRouter); app.listen(3000, () => console.log('Project running on port 3000'));
package main.java.by.bntu.fitr.poisit.matnik.university.model; import entity.*; import main.java.by.bntu.fitr.poisit.matnik.university.util.CustomLogger; import org.apache.logging.log4j.core.Logger; import java.io.*; import java.util.ArrayList; import java.util.List; public class FileHandler { private static final Logger logger = (Logger) CustomLogger.getLogger(); // Save a list of heroes to a binary file public static void saveHeroesToFile(List<Hero> heroes, String fileName) { try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName))) { out.writeObject(heroes); logger.info("Saved heroes to file: " + fileName); } catch (IOException e) { logger.error("Error while saving heroes to file:" + fileName + e); } } // Load a list of heroes from a binary file public static List<Hero> loadHeroesFromFile(String fileName) throws IOException, ClassNotFoundException { try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName))) { logger.info("Loaded heroes from file:" + fileName); return (List<Hero>) in.readObject(); } catch (IOException | ClassNotFoundException e) { logger.error("Error while loading heroes from file:" + fileName + e); throw e; } } // Save a list of heroes to a text file public static void saveHeroesToTextFile(List<Hero> heroes, String fileName) throws IOException { try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) { for (Hero hero : heroes) { writer.write(hero.toString() + "\n"); } logger.info("Saved heroes to text file:" + fileName); } catch (IOException e) { logger.error("Error while saving heroes to text file:" + fileName + e); } } public static void customSerialize(List<Hero> heroes, String filename) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) { for (Hero hero : heroes) { writer.write("HeroType: " + hero.getClass().getSimpleName() + "\n"); writer.write("Name: " + hero.getName() + "\n"); writer.write("Race: " + hero.getRace() + "\n"); writer.write("Level: " + hero.getLevel() + "\n"); // Сериализация артефактов for (Artifact artifact : hero.getArtifacts()) { writer.write("Artifact: " + artifact.getType() + "\n"); List<Integer> stats = artifact.getStats(); writer.write("Stats: "); for (int i = 0; i < stats.size(); i++) { writer.write(stats.get(i).toString()); if (i < stats.size() - 1) { writer.write(", "); } } writer.write("\n"); } // Сериализация способностей (для героев, у которых они есть) if (hero.getAbilities() != null) { writer.write("Abilities: "); for (Abilities ability : hero.getAbilities()) { writer.write(ability.name()); if (ability != hero.getAbilities().get(hero.getAbilities().size() - 1)) { writer.write(", "); } } writer.write("\n"); } // Разделитель между героями writer.write("\n"); logger.info("Custom serialization to file:" + filename); } } catch (IOException e) { logger.error("Error during custom serialization:" + filename + e); } } public static List<Hero> customDeserialize(String filename) { List<Hero> heroes = new ArrayList<>(); Hero hero = null; // Используем, чтобы хранить текущего обрабатываемого героя List<Artifact> artifacts = new ArrayList<>(); List<Abilities> abilities = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { String line; while ((line = reader.readLine()) != null) { String[] parts = line.split(": "); if (parts.length == 2) { String field = parts[0]; String value = parts[1]; switch (field) { case "HeroType": // Создаем нового героя при обнаружении нового типа if (hero != null) { hero.setArtifacts(artifacts); hero.setAbilities(abilities); heroes.add(hero); } hero = createHero(value, "", 0, "", new ArrayList<>()); artifacts.clear(); abilities.clear(); break; case "Name": if (hero != null) { hero.setName(value); } break; case "Race": if (hero != null) { hero.setRace(value); } break; case "Level": if (hero != null) { hero.setLevel(Integer.parseInt(value)); } break; case "Artifact": if (hero != null) { String artifactType = value; line = reader.readLine(); // Следующая строка должна содержать статы артефакта parts = line.split(": "); if (parts.length == 2 && parts[0].equals("Stats")) { String[] statsStr = parts[1].split(", "); List<Integer> stats = new ArrayList<>(); for (String statStr : statsStr) { stats.add(Integer.parseInt(statStr)); } artifacts.add(new Artifact(artifactType, stats)); } } break; case "Abilities": if (hero != null) { String[] abilitiesStr = value.split(", "); for (String abilityStr : abilitiesStr) { abilities.add(Abilities.valueOf(abilityStr)); } } break; } } } // Добавляем последнего героя, так как после цикла обработки не будет разделителя if (hero != null) { hero.setArtifacts(artifacts); hero.setAbilities(abilities); heroes.add(hero); } logger.info("Custom deserialization from file:" + filename); } catch (IOException e) { logger.error("Error during custom deserialization:" + filename + e); } return heroes; } private static Hero createHero(String heroType, String name, int level, String race, List<Artifact> artifacts) { switch (heroType) { case "Support": return new Support(name, level, race, artifacts); case "Tank": return new Tank(name, level, race, artifacts); case "Assassin": return new Assassin(name, level, race, artifacts); default: return null; // Обработка других типов героев } } }
--- title: 在使用wavesurfer-js之前 date: 2022-10-30 description: wavesurfer-js音频处理实战优化,和网络加载有关 --- ![banner](https://image.liuyongzhi.cn/imageswavesurfer-js.png) ## 什么是[wavesurfer-js](https://wavesurfer-js.org/)? > **wavesurfer.js** is a customizable audio waveform visualization, built on top of [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API) and [HTML5 Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). **wavesurfer.js**是一个可定制的音频波形可视化,建立在[Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API)和[HTML5 Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API)之上。 wavesurfer还支持[插件]([wavesurfer.js](https://wavesurfer-js.org/plugins/)),包括并不限于剪裁、录制等 ## wavesurfer的使用 ```bash npm i wavesurfer.js ``` ```js const srouce = "https://wavesurfer-js.org/example/media/demo.wav" const ref = Wavesurferjs.create({ container: refs.current, // 目标dom waveColor: '#544979', // 波形图颜色 progressColor: '#6B58B2', // 播放进度颜色 height: 40, hideCursor: true, fillParent: true, barGap:1, barWidth:1, }) ref.load(source) ``` ### 坑点 - `WavesurferJS`可以实时解析音频文件的波状图,波状图解析速度与文件大小成正比 > `load`函数还可以接受第二个参数,第二个参数是一个`json`数据,也是波形图绘制的数据。在`wavesurfer`实例上存在`backend`属性,此属性中存在`getPeaks`函数,我们可以在后台上传时,先解析出音频数据,将音频数据与音频文件绑定上传,这样C端可以直接使用音频数据,省去解析时间 #### example ```js const parseWaveView = url => new Promise((resolve, reject) => { const target = document.createElement('div') target.style.width = '100%' target.style.height = '200px' target.style.position = 'absolute' target.style.top = '-100%' const instance = wavesurfer.create({ container: target }) instance.load(url) instance.on('ready', async() => { const peaks = instance.backend.getPeaks( instance.backend.mergedPeaks.length, 0, instance.backend.mergedPeaks.length ) await putWaveform2Oss({ mediaId: mediaId, confArr: peaks }) document.body.removeChild(target) resolve(peaks) }) }) // getPeaks函数接收三个参数,分别是音频数据总长度、截取的起始位置、截取的结束位置 // 参数可以在backend中拿到 ``` - 播放音频时,如果音频文件过大并且在没有加载完成后播放其他实例,会加载混乱,播放的声音和应该播放的音频不一致,还会导致内存溢出等问题。 > `load`函数的第一个参数可以使用一个空的音频文件,在播放时可以获取当前播放的音频地址使用`audio`标签控制播放,保证同一时间只加载一个音频资源,减少内存压力。另外在点击波形图改变进度时,可以[监听事件]([wavesurfer.js](https://wavesurfer-js.org/docs/events.html))获取当前时间来设置`audio`标签时间。同样在`audio`播放中获取当前播放进度同步波形图进度 #### example ```js // 设置波形图播放进度 time 0 - 1 nstance.seekTo([time]) // 点击波形图调整播放时间 // 1. 点击时获取播放进度的长度除以总波形图的长度得到百分比 // 2. 使用百分比乘以音频总时长得到当前时间 // 3. 设置audio当前时间 const setCurrentProgress = current => { audio.currentTime = current * duration } nstance.drawer.on("click", e => { setCurrentProgress(e.layerX / e.target.clientWidth) }) ``` ### 最后 - [wavesurfer-js](https://wavesurfer-js.org/) - [peaks.js](https://github.com/bbc/peaks.js) - 如果你还想来我的[博客](https://overdev.cn)看看
#' Get FN121_GPS - GPS data from FN_Portal API #' #' This function accesses the api endpoint for FN121_GPS_Tracks #' records. FN121_GPS_Tracks records contain GPS tracks for projects #' where GPS data is recorded (e.g. trawls, electrofishing, etc.), including #' the track ID, coordinates in decimal decrees, the timestamp and site depth. #' Other relevant details for each SAM are found in the FN121 table. #' This function takes an optional filter list which can be used to #' return records based on attributes of the SAM including site depth, timestamp, #' start and end date and time, effort duration, gear, site depth and location #' as well as attributes of the projects they are associated with such project #' code, or part of the project code, lake, first year, last year, #' protocol, etc. #' #' See #' http://10.167.37.157/fn_portal/api/v1/redoc/#operation/fn121_gps_tracks_list #' for the full list of available filter keys (query parameters) #' #' @param filter_list list #' @param show_id When 'FALSE', the default, the 'id' and 'slug' #' fields are hidden from the data frame. To return these columns #' as part of the data frame, use 'show_id = TRUE'. #' @param to_upper - should the names of the dataframe be converted to #' upper case? #' #' @author Adam Cottrill \email{adam.cottrill@@ontario.ca} #' @return dataframe #' @export #' @examples #' #' # TODO: Update with relevant examples when more data exists in the portal #' #' fn121_gps <- get_FN121_GPS_Tracks(list(lake = "HU", prj_cd__like = "_306")) #' fn121_gps <- get_FN121_GPS_Tracks(list(lake = "HU", prj_cd__like = "_306"), show_id = TRUE) get_FN121_GPS_Tracks <- function(filter_list = list(), show_id = FALSE, to_upper = TRUE) { recursive <- ifelse(length(filter_list) == 0, FALSE, TRUE) query_string <- build_query_string(filter_list) check_filters("fn121_gps_tracks", filter_list, "fn_portal") my_url <- sprintf( "%s/fn121_gps_tracks/%s", get_fn_portal_root(), query_string ) payload <- api_to_dataframe(my_url, recursive = recursive) payload <- prepare_payload(payload, show_id, to_upper) return(payload) }
import { useDispatch, useSelector } from "react-redux"; import { Checkbox } from "antd"; // import _ from "lodash"; import { setVisibleModalCreateOrUpdate, deleteDistrict, setDetailDistrict, setIsTypeModalCreate, setSelectedRows, setPagination, setFilteredDataDistrict, resetDataDistrict } from '../../states/modules/home'; export default function Handle() { const dispatch = useDispatch(); const dataDistrict = useSelector(state => state.home.dataDistrict); const dataProvince = useSelector(state => state.home.dataProvince); const selectedRows = useSelector(state => state.home.selectedRows); const isTypeModalCreate = useSelector(state => state.home.isTypeModalCreate); const detailDistrict = useSelector(state => state.home.detailDistrict); const visibleModalCreateOrUpdate = useSelector(state => state.home.visibleModalCreateOrUpdate); const pagination = useSelector(state => state.home.pagination); const handleTableChange = (pagination) => { dispatch(setPagination(pagination)); }; const columns = [ { title: 'STT', dataIndex: 'index', key: 'index', render: (text, record, index) => ((pagination.current - 1) * pagination.pageSize) + index + 1, }, { title: 'Mã Quận/Huyện', dataIndex: 'DistrictCode', key: 'DistrictCode' }, { title: 'Mã tỉnh/TP', dataIndex: 'ProvinceCode', key: 'ProvinceCode' }, { title: 'Tên quận/huyện', dataIndex: 'DistrictName', key: 'DistrictName' }, { title: 'Trạng thái', dataIndex: 'FlagActive', key: 'FlagActive' }, { title: 'Select', dataIndex: 'select', key: 'select', render: (text, record) => ( <Checkbox checked={selectedRows.includes(record.id)} onChange={() => handleCheckboxChange(record.id)} /> ), }, ]; const optionsProvinc = dataProvince.map(item => ({ value: item.ProvinceCode, label: item.ProvinceName })); const optionsDistrict = dataDistrict.map(item => ({ value: item.DistrictCode, label: item.DistrictName })); const handleDelete = () => { dispatch(deleteDistrict()); }; const handleCheckboxChange = (id) => { const newSelected = selectedRows.includes(id) ? selectedRows.filter(key => key !== id) : [...selectedRows, id]; if (newSelected.includes(id)) { dispatch(setDetailDistrict(dataDistrict.find(district => district.id === id))); } else { dispatch(setDetailDistrict({})); } dispatch(setSelectedRows(newSelected)); }; const handleToggleVisibleModalCreateOrUpdate = () => { dispatch(setVisibleModalCreateOrUpdate(!visibleModalCreateOrUpdate)); } const openModalCreate = () => { dispatch(setIsTypeModalCreate(true)); handleToggleVisibleModalCreateOrUpdate(); } const openModalEdit = () => { if (selectedRows.length === 1) { dispatch(setIsTypeModalCreate(false)); handleToggleVisibleModalCreateOrUpdate(); } else { alert("Vui lòng chọn một phần tử để sửa"); } } const handleChange = (value) => { console.log(`Selected: ${value}`); }; const handleSearch = (value) => { if (value.trim() === "") { dispatch(resetDataDistrict()); } else { const filteredData = dataDistrict.filter(item => item.DistrictCode.includes(value) || item.DistrictName.includes(value) ); dispatch(setFilteredDataDistrict(filteredData)); } }; return { dataDistrict, columns, handleDelete, handleChange, handleSearch, optionsProvinc, optionsDistrict, isTypeModalCreate, openModalCreate, openModalEdit, detailDistrict, handleToggleVisibleModalCreateOrUpdate, visibleModalCreateOrUpdate, handleTableChange, pagination } }
/* * Copyright (c) 2024-present HiveMQ and the HiveMQ Community * * 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 expres or implied. * See the License for the specific language governing permissions and limitations under the License. * */ package com.hivemq.client.spring.autoconfigure; import com.hivemq.client.mqtt.mqtt3.Mqtt3AsyncClient; import com.hivemq.client.mqtt.mqtt3.Mqtt3BlockingClient; import com.hivemq.client.mqtt.mqtt3.Mqtt3RxClient; import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient; import com.hivemq.client.mqtt.mqtt5.Mqtt5BlockingClient; import com.hivemq.client.mqtt.mqtt5.Mqtt5RxClient; import com.hivemq.client.mqtt.mqtt5.auth.Mqtt5EnhancedAuthMechanism; import com.hivemq.client.spring.config.MqttProperties; import com.hivemq.client.spring.factories.Mqtt3ClientFactory; import com.hivemq.client.spring.factories.Mqtt5ClientFactory; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.lang.Nullable; /** * Auto configuration for HiveMQ MQTT client. * @since 1.0.0 * @author Sven Kobow */ @Configuration @EnableConfigurationProperties(MqttProperties.class) @ComponentScan(basePackages = { "com.hivemq.client.spring" }) public class HiveMQMqttAutoConfiguration { private final MqttProperties mqttProperties; public HiveMQMqttAutoConfiguration(final MqttProperties mqttProperties) { this.mqttProperties = mqttProperties; } @Bean @ConditionalOnProperty(name = "hivemq.client.mqtt-version", havingValue = "5", matchIfMissing = true) public Mqtt5ClientFactory mqtt5ClientFactory() { return new Mqtt5ClientFactory(); } @Bean(destroyMethod = "disconnect") @ConditionalOnMissingBean @ConditionalOnProperty(name = "hivemq.client.mqtt-version", havingValue = "5", matchIfMissing = true) public Mqtt5AsyncClient mqtt5AsyncClient(final Mqtt5ClientFactory clientFactory, @Nullable Mqtt5EnhancedAuthMechanism enhancedAuthMechanism) { if (mqttProperties.getMqttVersion() == 3) { throw new BeanCreationException("Mqtt5AsyncClient is not available for MQTT version 3. Use Mqtt3AsyncClient instead."); } return clientFactory.mqttClient(mqttProperties, enhancedAuthMechanism); } @Bean(destroyMethod = "disconnect") @ConditionalOnMissingBean @ConditionalOnProperty(name = "hivemq.client.mqtt-version", havingValue = "5", matchIfMissing = true) public Mqtt5RxClient mqtt5RxClient(final Mqtt5ClientFactory clientFactory, @Nullable Mqtt5EnhancedAuthMechanism enhancedAuthMechanism) { return mqtt5AsyncClient(clientFactory, enhancedAuthMechanism).toRx(); } @Bean(destroyMethod = "disconnect") @ConditionalOnMissingBean @ConditionalOnProperty(name = "hivemq.client.mqtt-version", havingValue = "5", matchIfMissing = true) public Mqtt5BlockingClient mqtt5BlockingClient(final Mqtt5ClientFactory clientFactory, @Nullable Mqtt5EnhancedAuthMechanism enhancedAuthMechanism) { return mqtt5AsyncClient(clientFactory, enhancedAuthMechanism).toBlocking(); } @Bean @ConditionalOnProperty(name = "hivemq.client.mqtt-version", havingValue = "3") public Mqtt3ClientFactory mqtt3ClientFactory() { return new Mqtt3ClientFactory(); } @Bean(destroyMethod = "disconnect") @ConditionalOnMissingBean @ConditionalOnProperty(name = "hivemq.client.mqtt-version", havingValue = "3") public Mqtt3AsyncClient mqtt3AsyncClient(final Mqtt3ClientFactory clientFactory) { if (mqttProperties.getMqttVersion() == 5) { throw new BeanCreationException("Mqtt3AsyncClient is not available for MQTT version 5. Use Mqtt5AsyncClient instead."); } return clientFactory.mqttClient(mqttProperties); } @Bean(destroyMethod = "disconnect") @ConditionalOnMissingBean @ConditionalOnProperty(name = "hivemq.client.mqtt-version", havingValue = "3") public Mqtt3RxClient mqtt3RxClient(final Mqtt3ClientFactory clientFactory) { return mqtt3AsyncClient(clientFactory).toRx(); } @Bean(destroyMethod = "disconnect") @ConditionalOnMissingBean @ConditionalOnProperty(name = "hivemq.client.mqtt-version", havingValue = "3") public Mqtt3BlockingClient mqtt3BlockingClient(final Mqtt3ClientFactory clientFactory) { return mqtt3AsyncClient(clientFactory).toBlocking(); } }
{% extends "base.html" %} {% block content %} <div class="articles-section"> <div class="article-content"> <!-- Сортировка тут --> <form action="" method="post"> <div class="article-sort"> <div class="row"> <div class="col-xl-3"> <div class="category"> <div class="text"> <p>Категория:</p> </div> <select name="category_id" class="browser-default custom-select"> {% for item in form['categories'] %} {% if form['selected'][0] == loop.index0 %} <option value="{{ loop.index0 }}" selected>{{ item }}</option> {% else %} <option value="{{ loop.index0 }}">{{ item }}</option> {% endif %} {% endfor %} </select> </div> </div> <div class="col-xl-4"> <div class="sort-by"> <div class="text"> <p>Сортировать по:</p> </div> <select name="sort_by" class="browser-default custom-select"> {% for item in form['sort_list'] %} {% if form['selected'][1] == loop.index0 %} <option value="{{ loop.index0 }}" selected>{{ item }}</option> {% else %} <option value="{{ loop.index0 }}">{{ item }}</option> {% endif %} {% endfor %} </select> </div> </div> <div class="col-xl-2"> <div class="reverse"> <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-outline-primary {% if form['selected'][2] == 0 %} active {% endif %}"> <input type="radio" name="reverse" value="0" {% if form['selected'][2] == 0 %} checked {% endif %}>Возрастание </label> <label class="btn btn-outline-primary {% if form['selected'][2] == 1 %} active {% endif %}"> <input type="radio" name="reverse" value="1" {% if form['selected'][2] == 1 %} checked {% endif %}>Убывание </label> </div> </div> </div> <div class="col-xl-3"> <div class="search-group"> <div class="search"> <input type="text" name="search" class="form-control" value="{{ form['selected'][3] }}" placeholder="Хочу искать!!!"/> </div> <div class="search-button"> <input type="submit" class="btn" value="Показать"/> </div> </div> </div> </div> </div> </form> {% if form['articles']|count > 0 %} <div class="article-count"> <p class="count">Результатов: {{ form['articles']|count }}</p> </div> <div class="article-list"> {% for item in form['articles'] %} <div class="card m-4 rounded" style="width: 20rem;"> <a href="/articles/show/{{ item.id }}"> <div class="inner" style="width: 100%; height: 13rem;"> <img class="card-img-top" src="{{ url_for('static', filename=item.photo_url) }}" alt="Card image cap"> </div> <div class="card-body text-center"> <h5 class="card-title">{{ item.title }}</h5> <p class="card-text card-hover">{{ item.description }}</p> <div class="center"> <div class="block"> {% if item.rating < 0 %} <p class="is-private card-text card-hover" style="background: rgba(255,0,0,0.5)">{{ item.rating }}</p> {% else %} <p class="is-private card-text card-hover" style="background: rgba(0,255,0,0.5)">{{ item.rating }}</p> {% endif %} </div> </div> <p class="card-views card-hover">Просмотров: {{ item.views }}</p> </div> </a> </div> {% endfor %} </div> {% else %} <div class="not-found"> <p class="title">Статей не найдено</p> </div> {% endif %} </div> </div> {% endblock %}
<?php namespace common\models; use Yii; use backend\components\traits\HasTimestamp; /** * This is the model class for table "faq". * * @property int $id * @property int $faq_category_id * @property string $question * @property string $answer * @property string $created_at * @property string $updated_at */ class Faq extends \yii\db\ActiveRecord { use HasTimestamp; /** * {@inheritdoc} */ public static function tableName() { return 'faq'; } /** * {@inheritdoc} */ public function rules() { return [ [['faq_category_id', 'question', 'answer'], 'required'], [['faq_category_id'], 'integer'], [['created_at', 'updated_at'], 'safe'], [['question'], 'string', 'max' => 150], [['answer'], 'string'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'faq_category_id' => 'Faq Category ID', 'question' => 'Question', 'answer' => 'Answer', 'created_at' => 'Created At', 'updated_at' => 'Updated At', ]; } /** * **/ public function getFaqCategory() { return $this->hasOne(FaqCategory::class, ['id' => 'faq_category_id']); } }
<template> <v-container> <h1 class="my-5 text-center text-h5 text-sm-h2"> Editando el curso: {{ name }} </h1> <div class="mt-10"> <v-form ref="form" v-model="valid" lazy-validation> <v-text-field v-model="name" :counter="20" :rules="nameRules" label="Nombre" required ></v-text-field> <v-text-field v-model="image" label="URL imagen" required type="url" ></v-text-field> <v-text-field v-model="room" :rules="roomRules" label="Cupos del curso" required ></v-text-field> <v-text-field v-model="enrolled" :rules="enrolledRules" label="Inscritos en el curso" required ></v-text-field> <v-text-field v-model="duration" label="Duración del curso" required ></v-text-field> <v-text-field v-model="cost" :rules="costRules" label="Costo del curso" required ></v-text-field> <v-text-field v-model="code" label="Código del curso" required ></v-text-field> <v-textarea outlined label="Descripción del curso" v-model="description" > </v-textarea> <v-text-field v-model="registerDate" label="Fecha de Registro" required type="date" ></v-text-field> <v-switch v-model="status" :label="status ? 'Terminado: Si' : 'Terminado: No'" color="indigo" :true-value="status" hide-details ></v-switch> <v-container class=" mt-5 d-flex justify-center align-content-center flex-column flex-sm-column flex-md-row flex-lg-row flex-xl-row " > <v-btn :disabled="!valid" color="success" class="mt-2 mt-sm-2 mt-md-0 mt-lg-0 mt-xl-0 mx-4" @click="validate" > Actualizar </v-btn> <v-btn color="error" class="mt-4 mt-sm-4 mt-md-0 mt-lg-0 mt-xl-0 mx-4" @click="reset" > Limpiar Formulario </v-btn> <v-btn color="warning" class="mt-4 mt-sm-4 mt-md-0 mt-lg-0 mt-xl-0 mx-4" @click="resetValidation" > Limpiar Validación </v-btn> <v-btn color="primary" class="mt-4 mt-sm-4 mt-md-0 mt-lg-0 mt-xl-0 mx-4" @click="$router.go(-1)" > Regresar </v-btn> </v-container> </v-form> </div> </v-container> </template> <script> import Swal from 'sweetalert2' import { mapGetters } from 'vuex' export default { name: 'Editing', props: ['id'], computed: { ...mapGetters(['sendingCourses']) }, data() { return { valid: true, name: '', image: '', code: '', enrolled: 0, description: '', room: 0, roomRules: [ (v) => !!v || 'Debes ingresar cupos', (v) => (v && v.length >= 0 && /\d/gim.test(v) && v >= 0) || 'Solo se admiten números positivos' ], enrolledRules: [ (v) => !!v || 'Ingresa un número de inscritos', (v) => (v && v.length >= 0 && /\d/gim.test(v) && v >= 0) || 'Solo se admiten números positivos', (v) => v <= this.room || 'No pueden haber más inscritos que cupos' ], duration: '', cost: 0, costRules: [ (v) => !!v || 'Ingresa un costo', (v) => (v && v.length >= 0 && /\d/gim.test(v) && v >= 0) || 'Solo se admiten números positivos' ], nameRules: [ (v) => !!v || 'El nombre es necesario', (v) => (v && v.length >= 2) || 'El nombre debe ser mayor o igual a dos caracteres' ], dialog: false, registerDate: '', status: false } }, watch: { status(nuevo) { if (nuevo) { this.enrolled = 0 } } }, mounted() { let foundCourse = this.sendingCourses.find( (result) => result.courseId === this.id ) if (foundCourse !== undefined) { this.room = parseInt(foundCourse.room) this.duration = foundCourse.duration this.code = foundCourse.code this.courseId = foundCourse.courseId this.image = foundCourse.image this.description = foundCourse.description this.name = foundCourse.name this.cost = parseFloat(foundCourse.cost) this.status = foundCourse.status this.enrolled = parseInt(foundCourse.enrolled) this.registerDate = foundCourse.registerDate } else { Swal.fire({ icon: 'error', title: 'Error', text: 'Curso no encontrado', footer: 'Intenta nuevamente' }) setTimeout(() => { this.$router.replace({ name: 'Administracion' }) }, 1000) } }, methods: { validate() { this.$refs.form.validate() if (this.$refs.form.validate()) { let newCourse = { name: this.name, code: this.code, cost: parseFloat(this.cost), room: parseInt(this.room), enrolled: parseInt(this.enrolled), image: this.image, duration: this.duration, status: this.status, registerDate: this.registerDate, courseId: this.courseId, description: this.description } this.$store.dispatch('updateCourse', newCourse).then(() => { Swal.fire('Ok', 'Curso Actualizado', 'éxito') this.reset() setTimeout(() => { this.$router.replace({ name: 'Administracion' }) }, 1000) }) } else { Swal.fire({ icon: 'error', title: 'Error', text: 'Algo salió mal', footer: 'Intenta nuevamente' }) } }, reset() { this.$refs.form.reset() }, resetValidation() { this.$refs.form.resetValidation() } } } </script> <style></style>
<!DOCTYPE html> <html> <head> <meta charset='utf-8' /> <title>Swipe between maps</title> <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.js'></script> <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.css' rel='stylesheet' /> <!-- JS and CSS for the swipe plugin --> <script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.js'></script> <link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-compare/v0.4.0/mapbox-gl-compare.css' type='text/css' /> <style> body { margin:0; padding:0; overflow: hidden;} body * { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .map { position: absolute; top: 0; bottom: 0; width: 100%; } </style> </head> <body> <div id="comparison-container"> <div id='owners' class='map'></div> <!-- div for owners map div --> <div id='renters' class='map'></div> <!-- div for renters map div --> </div> <script> mapboxgl.accessToken = 'pk.eyJ1Ijoic2Zhc3NiZXJnIiwiYSI6ImNsZzVlOHNhaDAwYXEzc29ka2VpMmh3cXMifQ.S6OurZ6z7jh6BGc7YDv8NQ'; //Set access token var ownerMap = new mapboxgl.Map({ container: 'owners', // owners map div style: 'mapbox://styles/mapbox/dark-v10', // Mapbox dark style center: [-122.6765, 45.4231], zoom: 9, minZoom: 9, maxBounds: [ [-126.0, 44.5], // Southwest corner [longitude, latitude] [-120.3, 45.8] // Northeast corner [longitude, latitude] ] }); var renterMap = new mapboxgl.Map({ // container: 'renters', // renters map div style: 'mapbox://styles/mapbox/dark-v10', // Mapbox dark style for seamless swipe center: [-122.6765, 45.4231], // Use the same center as your other map so that they are perfectly aligned zoom: 9, minZoom: 9, maxBounds: [ [-126.0, 44.5], // Southwest corner [longitude, latitude] [-120.3, 45.8] // Northeast corner [longitude, latitude] ] }); var container = '#comparison-container'; var popup = new mapboxgl.Popup({ closeButton: false, closeOnClick: false }); var map = new mapboxgl.Compare(ownerMap, renterMap, container, { }); // Add data and visualization to ownerMap ownerMap.on('load', function() { ownerMap.addLayer({ id: 'Owner Data', type: "fill", source: { type: 'vector', url: 'mapbox://sfassberg.836f89vt' }, 'source-layer': 'Owner-Renter-Pop-bn6zds', //input your source layer name e.g. 'Owner-Renter-Pop-ca08iw' paint: { 'fill-color': // Color scheme of data ["step", ["get", "Own"], "hsl(225, 100%, 97%)", 17.0, "hsl(203, 47%, 82%)", 22.0, "hsl(202, 57%, 63%)", 27.0, "#3182bd", 32.0, "hsl(210, 90%, 32%)" ], "fill-opacity": 0.7 } }); // Create popup with owner data on mousemove ownerMap.on('mousemove', 'Owner Data', function (e) { // Change the cursor style as a UI indicator. ownerMap.getCanvas().style.cursor = 'pointer'; var coordinates = e.lngLat; var description = e.features[0].properties.Own; // Populate the popup and set its coordinates // based on the feature found. popup.setLngLat(coordinates) .setHTML("Owners: " + description + "%") .addTo(ownerMap); }); //Remove popup and reset cursor when user unhovers ownerMap.on('mouseleave', 'Owner Data', function () { ownerMap.getCanvas().style.cursor = ''; popup.remove(); }); }); // Add data and visualization to renterMap renterMap.on('load', function() { renterMap.addLayer({ id: 'Renter Data', type: "fill", source: { type: 'vector', url: 'mapbox://sfassberg.836f89vt' }, 'source-layer': 'Owner-Renter-Pop-bn6zds', paint: { 'fill-color': ["step", ["get", "Rent"], "hsl(225, 100%, 97%)", 17.0, "hsl(203, 47%, 82%)", 22.0, "hsl(202, 57%, 63%)", 27.0, "#3182bd", 32.0, "hsl(210, 90%, 32%)" ], "fill-opacity": 0.7 } }); // Show a popup with renter data on mousemove renterMap.on('mousemove', 'Renter Data', function (e) { // Change the cursor style as a UI indicator. renterMap.getCanvas().style.cursor = 'pointer'; var coordinates = e.lngLat; var description = e.features[0].properties.Rent; // Populate the popup and set its coordinates // based on the feature found. popup.setLngLat(coordinates) .setHTML("Renters: " + description + "%") .addTo(renterMap); }); // Remove the popup and reset cursor style on mouseleave renterMap.on('mouseleave', 'Renter Data', function () { renterMap.getCanvas().style.cursor = ''; popup.remove(); }); }); </script> </body> </html>
<mat-form-field> <input matInput (keyup.enter)="getPatientsPage()" placeholder="ID or Last Name" #searchValue> </mat-form-field> <div class="mat-elevation-z8"> <div class="loader" *ngIf="isLoadingResults"> <mat-spinner></mat-spinner> </div> <table mat-table [dataSource]="dataSource"> <!-- id Column --> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef>ID</th> <td mat-cell *matCellDef="let element"> {{element.id}}</td> </ng-container> <!-- firstName Column --> <ng-container matColumnDef="firstName"> <th mat-header-cell *matHeaderCellDef>First Name</th> <td mat-cell *matCellDef="let element"> {{element.firstName}}</td> </ng-container> <!-- lastName Column --> <ng-container matColumnDef="lastName"> <th mat-header-cell *matHeaderCellDef>Last Name</th> <td mat-cell *matCellDef="let element"> {{element.lastName}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr> <tr mat-row (click)="editPatient(row)" *matRowDef="let row; columns: displayedColumns;"></tr> </table> <mat-paginator [length]="resultsLength" [pageIndex]="pageIndex" [pageSize]="pageSize" [pageSizeOptions]="pageSizeOptions" (page)="getPatientsPage($event.pageIndex, $event.pageSize)" showFirstLastButtons> </mat-paginator> </div>
import * as styled from 'styled-components'; const GlobalStyle = styled.createGlobalStyle` :root { --NavHeight: 70px; --bg: rgba(50, 181, 233, 1); --bg-darker: rgba(47, 140, 195, 0.7); --outline-1: #94bfff; --outline-2: #94ffb1; --outline-3: #ffe694; --outline-white: white; --fine-outline: black; --deck-1: white; --deck-2: white; --deck-3: white; --white: white; --blue: blue; --green: green; --red: red; --black: black; --gold: gold; --faded-blue: lightblue; --faded-green: lightgreen; --faded-red: lightpink; --faded-black: darkgray; --faded-purple: #c994ff; --trans-gray: rgba(50, 50, 50, 0.5); --semi-trans-gray: rgba(50, 50, 50, 0.35); --card-width: 100px; --card-height: 125px; --sm-emblem-size: 20px; --emblem-size: 25px; --big-emblem-size: 60px; --big-padding: 25px; --small-padding: 8px; --xs-padding: 3px; --sm-radius: 5px; --med-radius: 15px; --big-ft-sz: 1.5em; --med-ft-sz: 1.5em; --sm-ft-sz: 1.5em; } * { margin: 0; padding: 0; box-sizing: border-box; } html, body { scroll-behavior: smooth; background-color: var(--bg); height: 100%; } /* Nav Header */ .header { /* Positioning */ display: flex; align-items: center; position: fixed; z-index: 1000; /* Box sizing */ height: calc(var(--NavHeight, 60px) - 10px); width: 100%; top: 0%; /* Color */ background-color: var(--bg-darker); color: white; font-family: monospace; .title { /* font-family: monospace; */ margin: auto 0; } } // Game page content container .container { display: flex; flex-flow: column; position: absolute; width: 100%; // window width top: var(--NavHeight); align-items: center; > .player-list { position: absolute; right: 0; top: 0; } } .board { width: fit-content; position: relative; background-color: #cccccc; border-radius: var(--med-radius); .board-container { display: grid; grid-template-columns: calc(var(--card-width) + var(--big-padding)) repeat(4, var(--card-width)); grid-template-rows: calc(var(--card-height) + var(--big-padding)) repeat(3, var(--card-height)); grid-gap: var(--big-padding); padding: var(--big-padding); } } // card representation (applies to nobles as well) .card { display: grid; grid-template-columns: 1fr var(--emblem-size); height: var(--card-height); width: var(--card-width); border: 1px solid var(--fine-outline); outline: var(--small-padding) solid var(--outline-white); font-family: monospace; font-weight: 900; color: white; -webkit-text-stroke: 1px black; padding: 5px; border-radius: var(--sm-radius); .cost { grid-column: 2; justify-self: right; align-self: end; padding: 0; border: none; text-align: center; * { border-radius: 50%; margin-top: var(--xs-padding); padding: 0px; font-size: var(--sm-ft-sz); font-weight: 900; width: var(--emblem-size); height: var(--emblem-size); line-height: var(--emblem-size); border: 1px solid var(--fine-outline); } } .points { display: flex; font-size: var(--med-ft-sz); background-color: #cccccc; border: 1px solid black; width: fit-content; height: fit-content; grid-row: 1; padding: var(--xs-padding) var(--small-padding); align-self: start; border-radius: var(--sm-radius); justify-content: center; align-content: center; flex-direction: column; * { vertical-align: middle; white-space: pre; } } } .deck { grid-column: 1 / 2; margin-right: var(--big-padding); align-items: center; display: grid; justify-content: center; width: var(--card-width); height: var(--card-height); border: 1px solid var(--fine-outline); background-color: var(--white); font-family: monospace; font-weight: 900; font-size: var(--m-ft-sz); color: white; -webkit-text-stroke: 2px black; paint-order: stroke fill; padding: 5px; border-radius: var(--sm-radius); .deck-label { border: none; font-size: 1.7em; color: darkgray; transform: rotate(-30deg); } } // Assign cards to correct row .grid-filler { border: none; grid-column: 1; grid-row: 1; } .board-card.noble { grid-row: 1; } .board-card.level-three { grid-row: 2; } .board-card.level-two { grid-row: 3; } .board-card.level-one { grid-row: 4; } .deck.level-3 { grid-row: 2 / 3; outline: var(--small-padding) solid var(--outline-3); } .deck.level-2 { grid-row: 3 / 4; outline: var(--small-padding) solid var(--outline-2); } .deck.level-1 { grid-row: 4 / 5; outline: var(--small-padding) solid var(--outline-1); } .bank { /* Grid and positioning */ display: grid; grid-template-rows: 60px; grid-template-columns: repeat(6, 60px); grid-column-gap: var(--xs-padding); margin: auto; margin-bottom: var(--big-padding); padding: var(--small-padding); width: min-content; /* Colors */ background-color: #e7e7e7; border-radius: 10px; color: white; /* fonts */ font-family: 'Roboto Mono', monospace; font-size: 3em; font-weight: 900; -webkit-text-stroke: 3px black; paint-order: stroke fill; text-align: center; .bank-gems { /* Positioning */ display: flex; align-items: center; justify-content: center; /* Size and shape */ height: var(--big-emblem-size); width: var(--big-emblem-size); border-radius: 50%; font-family: monospace; } } .bank-modal > .bank { margin-top: 0; padding: var(--big-padding); grid-template-columns: repeat(5, 60px); } .player.current-turn { outline: 5px solid black; } .player { position: relative; z-index: 2000; display: grid; grid-auto-flow: column; margin-bottom: var(--big-padding); font-family: 'Roboto Mono', monospace; /* max-width: 130px; */ background-color: #dddddd; font-weight: 900; padding: var(--small-padding); border-top-left-radius: var(--med-radius); border-bottom-left-radius: var(--med-radius); .player-info { display: flex; font-size: var(--med-ft-sz); align-items: center; justify-content: space-between; .player-points { margin-right: var(--small-padding); color: var(--white); font-size: var(--med-ft-sz); -webkit-text-stroke: 3px black; paint-order: stroke fill; } } .player-bank { justify-self: center; display: flex; grid-row: 2; /* flex-direction: column; */ .player-bank-gem { margin-right: var(--xs-padding); justify-content: center; text-align: center; .bank-deck-value { background-color: transparent; -webkit-text-stroke: 2px black; paint-order: stroke fill; } .bank-deck-value.white { color: var(--white); } .bank-deck-value.blue { color: var(--blue); } .bank-deck-value.green { color: var(--green); } .bank-deck-value.red { color: var(--red); } .bank-deck-value.black { color: var(--black); -webkit-text-stroke: 2px white; } .bank-deck-value.gold { color: var(--gold); } .bank-gem-value { color: white; -webkit-text-stroke: 2px black; paint-order: stroke fill; width: var(--sm-emblem-size); aspect-ratio: 1; border-radius: 50%; } } } } .reserved-deck { position: relative; grid-row: 3; display: grid; direction: rtl; grid-auto-flow: column; justify-self: right; } .player-card-container:not(:first-child) { position: relative; margin-right: -70px; } .player-card-container:first-child { position: relative; margin-right: 0px; } .player-card { direction: ltr; transform: scale(0.6); position: relative; :hover { z-index: 2001; transition: 0.1s all; transform: scale(0.9); } } // GameList styling .wrapper { text-align: center; height: 100%; .game-list-buttons { margin-top: var(--NavHeight); button { font-family: 'Roboto Mono', monospace; margin: var(--small-padding); } } .game-list-container { text-align: left; width: 50%; margin: auto; font-family: 'Roboto Mono', monospace; max-height: 650px; overflow-y: scroll; height: 100%; .game-list-item-wrapper { .game-list-item { display: grid; grid-template-columns: 3fr 1fr; padding: 5px; margin: 10px 0px; background-color: #dddddd; font-size: 1em; border-radius: 5px; .game-list-item-detail { display: flex; flex-direction: column; * { font-family: 'Roboto Mono', monospace; } .creation-time { padding: 0; margin: 0; font-size: 0.6em; margin-bottom: var(--small-padding); } } .join-game { margin: auto; button { font-family: 'Roboto Mono', monospace; align-content: right; align-self: middle; } } } } } } .modal { display: flex; flex-direction: column; border-radius: 1em; background-color: var(--trans-gray); z-index: 1000; } .game-modal { position: absolute; bottom: 0%; width: 100%; min-height: 100%; align-items: center; justify-content: center; div button { margin: calc(var(--big-padding) * 3) var(--big-padding); font-family: 'Roboto Mono', monospace; } } .form-container { position: absolute; align-items: center; justify-content: center; max-width: 40%; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: var(--trans-gray); z-index: 100; padding: var(--big-padding); border-radius: var(--small-padding); border: 3px solid var(--semi-trans-gray); .form { display: flex; flex-wrap: wrap; flex-direction: row; align-items: center; justify-content: center; button { margin: var(--small-padding); font-family: 'Roboto Mono', monospace; } .form-input { margin-bottom: var(--big-padding); font-size: 1em; font-family: 'Roboto Mono', monospace; } } } /* Utility classes */ .white { background-color: var(--white); } .blue { background-color: var(--blue); } .green { background-color: var(--green); } .red { background-color: var(--red); } .black { background-color: var(--black); color: white; } .gold { background-color: var(--gold); } .noble { background-color: var(--faded-purple); } .disabled { display: none; filter: saturate(30%) brightness(30%); } .board-card.white, .player-card.white { background-color: var(--white); } .board-card.blue, .player-card.blue { background-color: var(--faded-blue); } .board-card.green, .player-card.green { background-color: var(--faded-green); } .board-card.red, .player-card.red { background-color: var(--faded-red); } .board-card.black, .player-card.black { background-color: var(--faded-black); color: white; } .bank-gems.black, .bank-gems.blue, .bank-gems.green, .bank-gems.red, .bank-gems.gold { border: 3px solid white; } .bank-gems.white { border: 3px solid black; } .hover-zoom { :hover { transition: 0.1s all; transform: scale(1.5); z-index: 100; } } .zoomed { transform: scale(1.5); } `; export default GlobalStyle;
require "active_support/inflector" class CodewordsSolver class Dictionary include ActiveSupport::Inflector DEFAULT_FILEPATH = File.join(__dir__, "..", "..", "word_list.txt") def initialize load! end def find_by_regexp(regexp) @words.filter { |w| w.length > 2 and w.match? regexp } end def has?(word) @words.include? word end def load! @words = import_words_by_filepath(DEFAULT_FILEPATH) end alias_method :reload!, :load! private def import_words_by_filepath(filepath) # puts "Loading words in from #{filepath}" file = File.read(filepath) file.chomp! words = file.split("\n") words.map! do |w| w.upcase! w = transliterate(w, "") w.gsub!(/[^A-Z]/, "") w end # puts "Loaded #{words.length} words" words end end end
<template> <div class="flex justify-center"> <form id="form" class="my-4 w-6/12" @submit.prevent="createPost"> <div class="mx-auto flex items-center bg-white p-2 rounded-md shadow-md"> <div class="flex flex-col flex-grow m-3"> <input v-model="title" class="m-2 w-90 input-primary" type="text" placeholder="Title" /> <input v-model="author" class="m-2 w-90 input-primary" type="text" placeholder="By" /> <textarea rows="4" v-model="description" class="m-2 w-90 input-primary" type="text" placeholder="What's on your mind?" /> <div class="flex-shrink-0"> <button type="submit" class="btn-primary" > Add </button> </div> </div> </div> </form> </div> </template> <script lang="ts"> import { IPost } from '@/interfaces/Post' import { useStore } from '@/store' import { MutationType } from '@/store/modules/posts/mutations' import { defineComponent, ref } from 'vue' import { useRouter } from 'vue-router' export default defineComponent({ setup() { const title = ref('') const author = ref('') const description = ref('') const store = useStore() const router = useRouter() const createPost = () => { const post: IPost = { id: Date.now(), title: title.value, author: author.value, description: description.value } store.commit(MutationType.createPost, post) router.push("/") } return { createPost, description, author, title } } }) </script>
// eslint-disable-next-line no-unused-vars import React, { useState } from "react"; import { addUser } from "../../UserServices/UserServices.jsx"; // eslint-disable-next-line react/prop-types const UserForm = ({ onAddUser }) => { const [username, setUserName] = useState(""); const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [phone, setPhone] = useState(""); const handleSubmit = async (e) => { e.preventDefault(); const newUser = { username, name, email, phone, }; try { const addedUser = await addUser(newUser); onAddUser(addedUser); setUserName(""); setName(""); setEmail(""); setPhone(""); } catch (error) { console.log("error"); } }; return ( <div> <h2>Add User</h2> <form onSubmit={handleSubmit}> <label>User-Name:</label> <input type="text" value={username} onChange={(e) => setUserName(e.target.value)} required /> <label>Name:</label> <input type="text" value={name} onChange={(e) => setName(e.target.value)} required /> <label>Email:</label> <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required /> <label>Phone:</label> <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} required /> <button type="submit">Add User</button> </form> </div> ); }; export default UserForm;
public class App { public static void main(String[] args) throws Exception { AttendenceApprover dean = new DeanOfAcademic(); AttendenceApprover hod = new HeadOfDepeartment(); AttendenceApprover prof = new AssistantProfessor(); Student s = new Student(); prof.setNextApprover(hod); hod.setNextApprover(dean); dean.setNextApprover(null); s.setAttendance(41); s.setCGPA(9.5); s.setMedicalCertificate("Sach me bemaar tha sir!!"); prof.approve(s); } }
<x-app-layout> <div class="container lg:w-1/2 md:w-4/5 w-11/12 mx-auto mt-8 px-8 bg-indigo-600 shadow-md rounded-md"> <h2 class="text-center text-lg text-white font-bold pt-6 tracking-widest">ホテル情報登録</h2> <x-validation-errors :errors="$errors" /> <form action="{{ route('hotels.store') }}" method="POST" class="rounded pt-3 pb-8 mb-4"> @csrf <div class="mb-4"> <label class="block text-white mb-2" for="name"> 名前 </label> <input type="text" name="name" class="rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-pink-600 w-full py-2 px-3" required placeholder="名前" value="{{ old('name') }}"> </div> <div> <label class="block text-white mb-2" for="prefecture_id"> 都道府県 </label> <select name="prefecture_id" class="rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-pink-600 w-full py-2 px-3"> <option disabled selected value="">選択してください</option> @foreach ($prefectures as $prefecture) <option value="{{ $prefecture->id }}" @if ($prefecture->id == old('prefecture_id')) selected @endif> {{ $prefecture->name }}</option> @endforeach </select> </div> <div class="mb-4"> <label class="block text-white mb-2" for="adress"> 住所 </label> <input type="text" name="adress" class="rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-pink-600 w-full py-2 px-3" required placeholder="住所" value="{{ old('adress') }}"> </div> <div class="mb-4"> <label class="block text-white mb-2" for="phonenumber"> 電話番号 </label> <input type="text" name="phonenumber" class="rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-pink-600 w-full py-2 px-3" required placeholder="電話番号" value="{{ old('phonenumber') }}"> </div> <div class="mb-4"> <label class="block text-white mb-2" for="capacity"> 部屋数 </label> <input type="number" name="capacity" class="rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-pink-600 w-full py-2 px-3" required placeholder="10部屋 => 10と記入" value="{{ old('capacity') }}"> </div> <div class="mb-4"> <label class="block text-white mb-2" for="description"> 詳細 </label> <textarea name="description" rows="10" class="rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-pink-600 w-full py-2 px-3" placeholder="詳細">{{ old('description') }}</textarea> </div> <input type="submit" value="登録" class="w-full flex justify-center bg-gradient-to-r from-pink-500 to-purple-600 hover:bg-gradient-to-l hover:from-purple-500 hover:to-pink-600 text-gray-100 p-2 rounded-full tracking-wide font-semibold shadow-lg cursor-pointer transition ease-in duration-500"> </form> </div> </x-app-layout>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03_cv.Models { public class AVL<T> where T : IComparable<T> { Node? root; class Node { public T value; public Node left, right; public int height; public Node(T value) { this.value = value; this.height = 1; } public int GetBallance() { return (this.left == null ? 0 : this.left.GetHeight()) - (this.right == null ? 0 : this.right.GetHeight()); } public int GetHeight() { if (this == null) return 0; return height; } public override string ToString() { return $"{value}"; } } public void Add(T value) { if (root == null) { root = new Node(value); return; } if (value.CompareTo(root.value) <= 0) { root.left = AddRek(root.left, value); } else { root.right = AddRek(root.right, value); } UpdateHeight(root); } private Node AddRek(Node node, T value) { if (node == null) { return new Node(value); } if (value.CompareTo(node.value) <= 0) { node.left = AddRek(node.left, value); } else { node.right = AddRek(node.right, value); } UpdateHeight(node); return BalanceTree(node, value); } public string Preorder() { if (root == null) { return string.Empty; } string sb = ""; sb += "PREORDER"; sb += $"\n{root.ToString()},"; if (root.left != null) { sb += $"{PreorderRek(root.left)}"; } if (root.right != null) { sb += $"{PreorderRek(root.right)}"; } return sb; } private string PreorderRek(Node node) { string sb = ""; sb += $"{node.ToString()},"; if (node.left != null) { sb += $"{PreorderRek(node.left)}"; } if (node.right != null) { sb += $"{PreorderRek(node.right)}"; } return sb.ToString(); } public string Inorder() { if (root == null) { return String.Empty; } string sb = "INORDER\n"; if (root.left != null) { sb += $"{InorderRek(root.left)}"; } sb += $"{root.ToString()},"; if (root.right != null) { sb += $"{InorderRek(root.right)}"; } return sb; } private string InorderRek(Node node) { string sb = ""; if (node.left != null) { sb += $"{InorderRek(node.left)}"; } sb += $"{node.ToString()},"; if (node.right != null) { sb += $"{InorderRek(node.right)}"; } return sb; } public string Postorder() { if (root == null) { return String.Empty; } string sb = "POSTORDER\n"; if (root.left != null) { sb += $"{PostorderRek(root.left)}"; } if (root.right != null) { sb += $"{PostorderRek(root.right)}"; } sb += $"{root.ToString()},"; return sb; } private string PostorderRek(Node node) { string sb = ""; if (node.left != null) { sb += $"{PostorderRek(node.left)}"; } if (node.right != null) { sb += $"{PostorderRek(node.right)}"; } sb += $"{node.ToString()},"; return sb; } private void UpdateHeight(Node node) { if (node == null) { return; } UpdateHeight(node.left); UpdateHeight(node.right); node.height = Math.Max(node.right == null ? 0 : node.right.GetHeight(), node.left == null ? 0 : node.left.GetHeight()) + 1; } private Node BalanceTree(Node node, T value) { if (node.GetBallance() > 1) { if (node.left.GetBallance() >= 1) { return RotateRight(node); } else if (node.left.GetBallance() <= -1) { node.left = RotateLeft(node.left); return RotateRight(node); } } if (node.GetBallance() < -1) { if (node.right.GetBallance() <= -1) { return RotateLeft(node); } else if (node.right.GetBallance() >= 1) { node.right = RotateRight(node.right); return RotateLeft(node); } } return node; } private Node RotateRight(Node node) { Node temp = node.left; node.left = temp.right; temp.right = node; UpdateHeight(temp); UpdateHeight(node); return temp; } private Node RotateLeft(Node node) { Node temp = node.right; node.right = temp.left; temp.left = node; UpdateHeight(temp); UpdateHeight(node); return temp; } public void PrintTree() { PrintF(root); } class NodeInfo { public Node Node; public string Text; public int StartPos; public int Size { get { return Text.Length; } } public int EndPos { get { return StartPos + Size; } set { StartPos = value - Size; } } public NodeInfo Parent, Left, Right; } private void PrintF(Node root, int topMargin = 2, int leftMargin = 2) { if (root == null) return; int rootTop = Console.CursorTop + topMargin; var last = new List<NodeInfo>(); var next = root; for (int level = 0; next != null; level++) { var item = new NodeInfo { Node = next, Text = next.value.ToString() }; if (level < last.Count) { item.StartPos = last[level].EndPos + 1; last[level] = item; } else { item.StartPos = leftMargin; last.Add(item); } if (level > 0) { item.Parent = last[level - 1]; if (next == item.Parent.Node.left) { item.Parent.Left = item; item.EndPos = Math.Max(item.EndPos, item.Parent.StartPos); } else { item.Parent.Right = item; item.StartPos = Math.Max(item.StartPos, item.Parent.EndPos); } } next = next.left ?? next.right; for (; next == null; item = item.Parent) { Print(item, rootTop + 2 * level); if (--level < 0) break; if (item == item.Parent.Left) { item.Parent.StartPos = item.EndPos; next = item.Parent.Node.right; } else { if (item.Parent.Left == null) item.Parent.EndPos = item.StartPos; else item.Parent.StartPos += (item.StartPos - item.Parent.EndPos) / 2; } } } Console.SetCursorPosition(0, rootTop + 2 * last.Count - 1); } private static void Print(NodeInfo item, int top) { SwapColors(); Print(item.Text, top, item.StartPos); SwapColors(); if (item.Left != null) PrintLink(top + 1, "┌", "┘", item.Left.StartPos + item.Left.Size / 2, item.StartPos); if (item.Right != null) PrintLink(top + 1, "└", "┐", item.EndPos - 1, item.Right.StartPos + item.Right.Size / 2); } private static void PrintLink(int top, string start, string end, int startPos, int endPos) { Print(start, top, startPos); Print("─", top, startPos + 1, endPos); Print(end, top, endPos); } private static void Print(string s, int top, int left, int right = -1) { Console.SetCursorPosition(left, top); if (right < 0) right = left + s.Length; while (Console.CursorLeft < right) Console.Write(s); } private static void SwapColors() { var color = Console.ForegroundColor; Console.ForegroundColor = Console.BackgroundColor; Console.BackgroundColor = color; } } }
package com.github.j5ik2o.cqrs.es.java.domain.groupchat; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.f4b6a3.ulid.UlidCreator; import com.github.j5ik2o.cqrs.es.java.domain.useraccount.UserAccountId; import com.github.j5ik2o.event.store.adapter.java.Aggregate; import io.vavr.Tuple2; import io.vavr.collection.Vector; import io.vavr.control.Either; import java.time.Instant; import java.util.Objects; import javax.annotation.Nonnull; public final class GroupChat implements Aggregate<GroupChat, GroupChatId> { private final GroupChatId id; private final boolean deleted; private final GroupChatName name; @JsonProperty("members") private final Members members; @JsonProperty("messages") private final Messages messages; private final long sequenceNumber; private final long version; private GroupChat( @Nonnull @JsonProperty("id") GroupChatId id, @JsonProperty("deleted") boolean deleted, @Nonnull @JsonProperty("name") GroupChatName name, @Nonnull @JsonProperty("members") Members members, @Nonnull @JsonProperty("messages") Messages messages, @JsonProperty("sequenceNumber") long sequenceNumber, @JsonProperty("version") long version) { this.id = id; this.deleted = deleted; this.name = name; this.members = members; this.messages = messages; this.sequenceNumber = sequenceNumber; this.version = version; } @Nonnull @Override public GroupChatId getId() { return id; } public boolean isDeleted() { return deleted; } public Members getMembers() { return members; } public Messages getMessages() { return messages; } @Override public long getSequenceNumber() { return this.sequenceNumber; } @Override public long getVersion() { return this.version; } @Override public GroupChat withVersion(long l) { return new GroupChat(id, deleted, name, members, messages, sequenceNumber, l); } @Nonnull public GroupChatName getName() { return name; } public Either<GroupChatError, Tuple2<GroupChat, GroupChatEvent>> delete( UserAccountId executorId) { if (deleted) { return Either.left(new GroupChatError.AlreadyDeletedError(id)); } if (!members.isAdministrator(executorId)) { return Either.left(new GroupChatError.NotAdministratorError(id, executorId)); } var newSequenceNumber = this.sequenceNumber + 1; var newGroupChat = new GroupChat(id, true, name, members, messages, newSequenceNumber, version); return Either.right( new Tuple2<>( newGroupChat, new GroupChatEvent.Deleted( UlidCreator.getMonotonicUlid(), id, executorId, newSequenceNumber, Instant.now()))); } public Either<GroupChatError, Tuple2<GroupChat, GroupChatEvent>> rename( GroupChatName name, UserAccountId executorId) { if (deleted) { return Either.left(new GroupChatError.AlreadyDeletedError(id)); } if (!members.isMember(executorId)) { return Either.left(new GroupChatError.NotMemberError(id, executorId)); } if (this.name.equals(name)) { return Either.left(new GroupChatError.AlreadyRenamedError(id, name)); } var newSequenceNumber = this.sequenceNumber + 1; var newGroupChat = new GroupChat(id, deleted, name, members, messages, newSequenceNumber, version); return Either.right( new Tuple2<>( newGroupChat, new GroupChatEvent.Renamed( UlidCreator.getMonotonicUlid(), id, executorId, name, newSequenceNumber, Instant.now()))); } public Either<GroupChatError, Tuple2<GroupChat, GroupChatEvent>> addMember( Member member, UserAccountId executorId) { if (deleted) { return Either.left(new GroupChatError.AlreadyDeletedError(id)); } if (!members.isAdministrator(executorId)) { return Either.left(new GroupChatError.NotAdministratorError(id, executorId)); } if (members.isMember(member.getUserAccountId())) { return Either.left(new GroupChatError.AlreadyMemberError(id, member.getUserAccountId())); } var newMembers = members.add(member); var newSequenceNumber = this.sequenceNumber + 1; var newGroupChat = new GroupChat(id, deleted, name, newMembers, messages, newSequenceNumber, version); var event = new GroupChatEvent.MemberAdded( UlidCreator.getMonotonicUlid(), id, member, executorId, newSequenceNumber, Instant.now()); return Either.right(new Tuple2<>(newGroupChat, event)); } public Either<GroupChatError, Tuple2<GroupChat, GroupChatEvent>> removeMemberByUserAccountId( UserAccountId userAccountId, UserAccountId executorId) { if (deleted) { return Either.left(new GroupChatError.AlreadyDeletedError(id)); } if (!members.isAdministrator(executorId)) { return Either.left(new GroupChatError.NotAdministratorError(id, executorId)); } if (!members.isMember(userAccountId)) { return Either.left(new GroupChatError.NotMemberError(id, userAccountId)); } var memberAndMembersOption = members.removeByUserAccountId(userAccountId); if (memberAndMembersOption.isEmpty()) { return Either.left(new GroupChatError.NotMemberError(id, userAccountId)); } var memberAndMembers = memberAndMembersOption.get(); var newSequenceNumber = this.sequenceNumber + 1; var newGroupChat = new GroupChat( id, deleted, name, memberAndMembers._2(), messages, newSequenceNumber, version); var event = new GroupChatEvent.MemberRemoved( UlidCreator.getMonotonicUlid(), id, memberAndMembers._1(), executorId, newSequenceNumber, Instant.now()); return Either.right(new Tuple2<>(newGroupChat, event)); } public Either<GroupChatError, Tuple2<GroupChat, GroupChatEvent>> postMessage( Message message, UserAccountId executorId) { if (deleted) { return Either.left(new GroupChatError.AlreadyDeletedError(id)); } if (!members.isMember(executorId)) { return Either.left(new GroupChatError.NotMemberError(id, executorId)); } var newMessages = messages.add(message); var newSequenceNumber = this.sequenceNumber + 1; var newGroupChat = new GroupChat(id, deleted, name, members, newMessages, newSequenceNumber, version); var event = new GroupChatEvent.MessagePosted( UlidCreator.getMonotonicUlid(), id, message, executorId, newSequenceNumber, Instant.now()); return Either.right(new Tuple2<>(newGroupChat, event)); } public Either<GroupChatError, Tuple2<GroupChat, GroupChatEvent>> deleteMessageByMessageId( MessageId messageId, UserAccountId executorId) { if (deleted) { return Either.left(new GroupChatError.AlreadyDeletedError(id)); } if (!members.isMember(executorId)) { return Either.left(new GroupChatError.NotAdministratorError(id, executorId)); } if (!messages.containsByMessageId(messageId)) { return Either.left(new GroupChatError.MessageNotFoundError(id, messageId)); } var messageAndMessagesOption = messages.removeByMessageId(messageId); if (messageAndMessagesOption.isEmpty()) { return Either.left(new GroupChatError.MessageNotFoundError(id, messageId)); } var messageAndMessages = messageAndMessagesOption.get(); var newSequenceNumber = this.sequenceNumber + 1; var newGroupChat = new GroupChat( id, deleted, name, members, messageAndMessages._2(), newSequenceNumber, version); var event = new GroupChatEvent.MessageDeleted( UlidCreator.getMonotonicUlid(), id, messageAndMessages._1(), executorId, newSequenceNumber, Instant.now()); return Either.right(new Tuple2<>(newGroupChat, event)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GroupChat groupChat = (GroupChat) o; return deleted == groupChat.deleted && sequenceNumber == groupChat.sequenceNumber && version == groupChat.version && Objects.equals(id, groupChat.id) && Objects.equals(name, groupChat.name) && Objects.equals(members, groupChat.members) && Objects.equals(messages, groupChat.messages); } @Override public int hashCode() { return Objects.hash(id, deleted, name, members, messages, sequenceNumber, version); } @Override public String toString() { return "GroupChat{" + "id=" + id + ", deleted=" + deleted + ", name=" + name + ", members=" + members + ", messages=" + messages + ", sequenceNumber=" + sequenceNumber + ", version=" + version + '}'; } public GroupChat applyEvent(@Nonnull GroupChatEvent event) { if (event instanceof GroupChatEvent.Deleted) { var e = (GroupChatEvent.Deleted) event; return delete(e.executorId()).get()._1(); } else if (event instanceof GroupChatEvent.Renamed) { var e = (GroupChatEvent.Renamed) event; return rename(e.name(), e.executorId()).get()._1(); } else if (event instanceof GroupChatEvent.MemberAdded) { var e = (GroupChatEvent.MemberAdded) event; return addMember(e.member(), e.executorId()).get()._1(); } else if (event instanceof GroupChatEvent.MemberRemoved) { var e = (GroupChatEvent.MemberRemoved) event; return removeMemberByUserAccountId(e.member().getUserAccountId(), e.executorId()).get()._1(); } else if (event instanceof GroupChatEvent.MessagePosted) { var e = (GroupChatEvent.MessagePosted) event; return postMessage(e.message(), e.executorId()).get()._1(); } else if (event instanceof GroupChatEvent.MessageDeleted) { var e = (GroupChatEvent.MessageDeleted) event; return deleteMessageByMessageId(e.message().getId(), e.executorId()).get()._1(); } else { throw new IllegalArgumentException(); } } public static GroupChat replay(Vector<GroupChatEvent> events, GroupChat snapshot) { return events.foldLeft(snapshot, GroupChat::applyEvent); } public static Tuple2<GroupChat, GroupChatEvent> create( GroupChatId id, GroupChatName name, UserAccountId executorId) { long sequenceNumber = 1; long version = 1; return new Tuple2<>( new GroupChat( id, false, name, Members.ofAdministratorId(executorId), Messages.ofEmpty(), sequenceNumber, version), new GroupChatEvent.Created( UlidCreator.getMonotonicUlid(), id, executorId, name, Members.ofAdministratorId(executorId), sequenceNumber, Instant.now())); } public static GroupChat from( GroupChatId id, boolean deleted, GroupChatName name, Members members, Messages messages, long sequenceNumber, long version) { return new GroupChat(id, deleted, name, members, messages, sequenceNumber, version); } }
package tests; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.annotations.Test; import pages.HomePage; import pages.LoginPage; import pages.ProductPage; import pages.ShoppingCartPage; import utilities.CommonMethods; import utilities.ConfigReader; import utilities.Driver; import utilities.TestBaseRapor; import java.io.IOException; public class finalCase1 extends TestBaseRapor { HomePage homePage; LoginPage loginPage; ProductPage productPage; ShoppingCartPage shoppingCartPage; private static final Logger logger = LogManager.getLogger(finalCase1.class.getName()); @Test public void kullaniciGirisiYapilarakSepeteEkleme() throws IOException { homePage = new HomePage(); loginPage = new LoginPage(); productPage = new ProductPage(); shoppingCartPage = new ShoppingCartPage(); logger.info("---Kullanıcı girişi yapılarak sepete ürün eklenmesi---"); extentTest = extentReports.createTest("finalCase1", "Kullanıcı girişi yapılarak sepete ürün eklenmesi"); Driver.getDriver().get(ConfigReader.getProperty("hepsiburadaUrl")); logger.info("Kullanıcı Hepsiburada.com sitesini ziyaret eder"); extentTest.info("Kullanıcı Hepsiburada.com sitesini ziyaret eder"); CommonMethods.dogrulamaMethodu(homePage.hepsiburadaLogo); CommonMethods.getScreenshot("GirisYapılarak_AnaSayfa"); logger.info("Kullanıcının doğru sayfada olduğu doğrulanir"); extentTest.pass("Kullanıcının doğru sayfada olduğu doğrulanir"); CommonMethods.jsclick(homePage.cerezKabul); logger.info("Kullanici çerezleri kabul eder"); extentTest.info("Kullanici çerezleri kabul eder"); HomePage.kullaniciGirisi(); logger.info("Kullanici gecerli e-mail ve sifre ile giris yapar"); extentTest.info("Kullanici gecerli e-mail ve sifre ile giris yapar"); CommonMethods.dogrulamaMethodu(homePage.basariliGiris); logger.info("Yönlendirmeden sonra anasayfada kullanıcı giriş işleminin yapıldığı doğrulanır"); extentTest.pass("Yönlendirmeden sonra anasayfada kullanıcı giriş işleminin yapıldığı doğrulanır"); HomePage.urunArama(homePage.aramaMetinKutusu); logger.info("Kullanıcı, burada satın almak istediği ürün için arama yapar"); extentTest.info("Kullanıcı, burada satın almak istediği ürün için arama yapar"); CommonMethods.webElementClick(productPage.urunSecimi); logger.info("Kullanıcı, Arama sonucunda ekrana gelen ürün listesinden (veya tek bir sonuç da dönmüş olabilir) ürün seçer"); extentTest.info("Kullanıcı, Arama sonucunda ekrana gelen ürün listesinden (veya tek bir sonuç da dönmüş olabilir) ürün seçer."); CommonMethods.switchWindow(1); CommonMethods.webElementClick(productPage.ilkUrunuSepeteEkle); logger.info("Kullanıcı seçilen ürün için ilk satıcıdan ürünü sepete ekler "); extentTest.info("Kullanıcı seçilen ürün için ilk satıcıdan ürünü sepete ekler"); CommonMethods.webElementClick(productPage.gelenSayfayiKapat); logger.info("Kullanıcı ürün sepetinizde,sayfasını kapatır"); extentTest.info("Kullanıcı ürün sepetinizde,sayfasını kapatır"); CommonMethods.webElementClick(productPage.ikinciUrunuSepeteEkle); logger.info("Kullanıcı seçilen ürün için ikinci satıcıdan ürünü sepete ekler"); extentTest.info("Kullanıcı seçilen ürün için ikinci satıcıdan ürünü sepete ekler"); CommonMethods.webElementClick(productPage.gelenSayfayiKapat); logger.info("Kullanıcı ürün sepetinizde,sayfasını kapatır"); extentTest.info("Kullanıcı ürün sepetinizde,sayfasını kapatır"); ProductPage.farkliSaticilardanSecilenUrununDogrulanmasi(productPage.ilkSaticiIsmi, productPage.ikinciSaticiIsmi); logger.info("İki farklı satıcıdan ürün seçildiği doğrulanır"); extentTest.pass("İki farklı satıcıdan ürün seçildiği doğrulanır"); CommonMethods.webElementClick(productPage.sepetimButonu); logger.info("Kullanici 'Sepetim' butonuna tıklar"); extentTest.info("Kullanici 'Sepetim' butonuna tıklar"); CommonMethods.dogrulamaMethodu(shoppingCartPage.sepetim); logger.info("Sepetim sayfasında olunduğu doğrulanır"); extentTest.pass("Sepetim sayfasında olunduğu doğrulanır"); ShoppingCartPage.urununSepetteDogrulanmasi(productPage.urunSecimi, shoppingCartPage.sepettekiIlkUrun, shoppingCartPage.sepettekiIkinciUrun); logger.info("Seçilen ürünün doğru olarak eklendiği ‘Sepetim’ sayfasında doğrulanır"); extentTest.pass("Seçilen ürünün doğru olarak eklendiği ‘Sepetim’ sayfasında doğrulanır"); ShoppingCartPage.sepetiTemizleme(shoppingCartPage.urunuKaldir, shoppingCartPage.urunAzalt); logger.info("Sepetteki ürünler temizlenir"); extentTest.info("Sepetteki ürünler temizlenir"); Driver.quitDriver(); logger.info("Tarayıcı kapatılır"); extentTest.info("Tarayıcı kapatılır"); extentReports.flush(); } }
plot3d1 ======= 3D gray or color level plot of a surface Calling Sequence ~~~~~~~~~~~~~~~~ :: plot3d1(x,y,z,[theta,alpha,leg,flag,ebox]) plot3d1(xf,yf,zf,[theta,alpha,leg,flag,ebox]) plot3d1(x,y,z,<opts_args>) plot3d1(xf,yf,zf,<opts_args>) Arguments ~~~~~~~~~ :x,y row vectors of sizes n1 and n2 (x-axis and y-axis coordinates). These coordinates must be monotone. : :z matrix of size (n1,n2). `z(i,j)` is the value of the surface at the point (x(i),y(j)). : :xf,yf,zf matrices of size (nf,n). They define the facets used to draw the surface. There are `n` facets. Each facet `i` is defined by a polygon with `nf` points. The x-axis, y-axis and z-axis coordinates of the points of the ith facet are given respectively by `xf(:,i)`, `yf(:,i)` and `zf(:,i)`. : :<opt_args> This represents a sequence of statements `key1=value1, key2=value2`,... where `key1`, `key2,...` can be one of the following: theta, alpha ,leg,flag,ebox (see definition below). : :theta, alpha real values giving in degree the spherical coordinates of the observation point. : :leg string defining the labels for each axis with @ as a field separator, for example "X@Y@Z". : :flag a real vector of size three. `flag=[mode,type,box]`. :mode an integer (surface color). :mode>0 the surface is painted with color `"mode"` ; the boundary of the facet is drawn with current line style and color. : :mode=0: a mesh of the surface is drawn. : :mode<0: the surface is painted with color `"-mode"` ; the boundary of the facet is not drawn. Note that the surface color treatement can be done using `color_mode` and `color_flag` options through the surface entity properties (see `surface_properties`_). : : :type an integer (scaling). :type=0: the plot is made using the current 3D scaling (set by a previous call to `param3d`, `plot3d`, `contour` or `plot3d1`). : :type=1: rescales automatically 3d boxes with extreme aspect ratios, the boundaries are specified by the value of the optional argument `ebox`. : :type=2: rescales automatically 3d boxes with extreme aspect ratios, the boundaries are computed using the given data. : :type=3: 3d isometric with box bounds given by optional `ebox`, similarily to `type=1`. : :type=4: 3d isometric bounds derived from the data, to similarily `type=2`. : :type=5: 3d expanded isometric bounds with box bounds given by optional `ebox`, similarily to `type=1`. : :type=6: 3d expanded isometric bounds derived from the data, similarily to `type=2`. Note that axes boundaries can be customized through the axes entity properties (see `axes_properties`_). : : :box an integer (frame around the plot). :box=0: nothing is drawn around the plot. : :box=1: unimplemented (like box=0). : :box=2: only the axes behind the surface are drawn. : :box=3: a box surrounding the surface is drawn and captions are added. : :box=4: a box surrounding the surface is drawn, captions and axes are added. Note that axes aspect can also be customized through the axes entity properties (see `axes_properties`_). : : : :ebox It specifies the boundaries of the plot as the vector `[xmin,xmax,ymin,ymax,zmin,zmax]`. This argument is used together with `type` in `flag` : if it is set to `1`, `3` or `5` (see above to see the corresponding behaviour). If `flag` is missing, `ebox` is not taken into acoount. Note that, when specified, the `ebox` argument acts on the `data_bounds` field that can also be reset through the axes entity properties (see `axes_properties`_). : Description ~~~~~~~~~~~ `plot3d1` plots a surface with colors depending on the z-level of the surface. This special plot function can also be enabled setting `color_flag=1` after a `plot3d` (see `surface_properties`_) Enter the command `plot3d1()` to see a demo. Examples ~~~~~~~~ :: // simple plot using z=f(x,y) t=[0:0.3:2*%pi]'; z=`sin`_(t)*`cos`_(t'); plot3d1(t,t,z) // same plot using facets computed by genfac3d [xx,yy,zz]=`genfac3d`_(t,t,z); `clf`_(); plot3d1(xx,yy,zz) // multiple plots `clf`_(); plot3d1([xx xx],[yy yy],[zz 4+zz]) // simple plot with viewpoint and captions `clf`_() ; plot3d1(1:10,1:20,10*`rand`_(10,20),35,45,"X@Y@Z",[2,2,3]) // same plot without grid `clf`_() plot3d1(1:10,1:20,10*`rand`_(10,20),35,45,"X@Y@Z",[-2,2,3]) // plot of a sphere using facets computed by eval3dp `deff`_("[x,y,z]=sph(alp,tet)",["x=r*cos(alp).*cos(tet)+orig(1)*ones(tet)";.. "y=r*cos(alp).*sin(tet)+orig(2)*ones(tet)";.. "z=r*sin(alp)+orig(3)*ones(tet)"]); r=1; orig=[0 0 0]; [xx,yy,zz]=`eval3dp`_(sph,`linspace`_(-%pi/2,%pi/2,40),`linspace`_(0,%pi*2,20)); `clf`_() `plot3d`_(xx,yy,zz) e=`gce`_(); e.color_flag=1; `scf`_(2); plot3d1(xx,yy,zz) // the 2 graphics are similar See Also ~~~~~~~~ + `plot3d`_ 3D plot of a surface + `gca`_ Return handle of current axes. + `gce`_ Get current entity handle. + `scf`_ set the current graphic figure (window) + `clf`_ clear or reset the current graphic figure (window) to default values .. _plot3d: plot3d.html .. _gce: gce.html .. _surface_properties: surface_properties.html .. _clf: clf.html .. _axes_properties: axes_properties.html .. _scf: scf.html .. _gca: gca.html
#include <zest/app.hpp> #include <zest/raylib_wrapper.hpp> #include <zest/text.hpp> #include <zest/tree_sitter.hpp> #include <zest/types.hpp> #include <zest/highlight/captures.hpp> #include <zest/highlight/queries.hpp> #include <fstream> #include <iostream> #include <optional> #include <stdexcept> #include <string> #include <vector> zest::CellPos window_to_cursor_pos(Editor& editor, LineBuffer& line_buffer, zest::Vec2 pos) { pos.x += editor.file_space_x - editor.top_left_x; pos.y += editor.file_space_y - editor.top_left_y; int col = std::round(pos.x/editor.cell_width); int row = pos.y/editor.cell_height; if (col > line_buffer.get_line(row).size()) col = line_buffer.get_line(row).size(); if (row >= line_buffer.line_count()) row = line_buffer.line_count(); return { row, col }; } zest::CellPos window_to_cell_pos(Editor& editor, LineBuffer& line_buffer, zest::Vec2 pos) { pos.x += editor.file_space_x - editor.top_left_x; pos.y += editor.file_space_y - editor.top_left_y; int col = pos.x/editor.cell_width; int row = pos.y/editor.cell_height; if (col > line_buffer.get_line(row).size()) col = line_buffer.get_line(row).size(); if (row >= line_buffer.line_count()) row = line_buffer.line_count(); return { row, col }; } bool move_cursor_up(CursorState& cursor, const LineBuffer& line_buffer) { if (cursor.line == 0) return false; cursor.line--; cursor.col = std::min((size_t)cursor.original_col, line_buffer.get_line(cursor.line).size()); return true; } bool move_cursor_down(CursorState& cursor, const LineBuffer& line_buffer) { if (cursor.line > line_buffer.line_count() - 1) return false; cursor.line++; cursor.col = std::min((size_t)cursor.original_col, line_buffer.get_line(cursor.line).size()); return true; } bool move_cursor_left(CursorState& cursor, const LineBuffer& line_buffer) { if (cursor.col == 0) { bool has_moved = move_cursor_up(cursor, line_buffer); if (has_moved) { cursor.col = line_buffer.get_line(cursor.line).size(); cursor.original_col = cursor.col; } return has_moved; } cursor.col--; cursor.original_col = cursor.col; return true; } bool move_cursor_right(CursorState& cursor, const LineBuffer& line_buffer) { if (cursor.col == line_buffer.get_line(cursor.line).size()) { bool has_moved = move_cursor_down(cursor, line_buffer); if (has_moved) { cursor.col = 0; cursor.original_col = cursor.col; } return has_moved; } cursor.col++; cursor.original_col = cursor.col; return true; } void stop_cursor(CursorState& cursor) { cursor.state_down.active = false; cursor.state_up.active = false; cursor.state_right.active = false; cursor.state_left.active = false; } template<typename MoveFunc> void update_cursor_direction(LineBuffer& line_buffer, CursorState& cursor, Editor& editor, MoveFunc move, int key, CursorState::MoveState& state, double time_delta) { auto move_cursor = [&] () { bool has_moved = move(cursor, line_buffer); if (has_moved) { cursor.time = 0; cursor.visible = true; } }; if (IsKeyPressed(key)) { stop_cursor(cursor); move_cursor(); state.down_time = cursor.move_rate - cursor.initial_delay; state.active = true; editor.cursorize_view = true; } else if (IsKeyDown(key) && state.active) { state.down_time += time_delta; if (state.down_time >= cursor.move_rate) { move_cursor(); state.down_time -= cursor.move_rate; } editor.cursorize_view = true; } } void set_cursor_to_mouse(CursorState& cursor, Editor& editor, LineBuffer& line_buffer) { zest::Vec2 mouse_pos = zest::zestify(GetMousePosition()); if (!zest::is_inside(mouse_pos, editor.text_area_rect)) return; zest::CellPos cell_pos = window_to_cursor_pos(editor, line_buffer, mouse_pos); cursor.col = cell_pos.col; cursor.original_col = cursor.col; cursor.line = cell_pos.line; cursor.visible = true; cursor.time = 0; } void set_file_view_to_cursor(CursorState& cursor, Editor& editor) { zest::Rect cursor_cell = { float(cursor.col*editor.font_info.char_step), float(cursor.line*editor.font_info.font_size), editor.font_info.char_step, float(editor.font_info.font_size) }; if (zest::get_top(cursor_cell) < editor.file_space_y) editor.file_space_y = cursor_cell.y; if (zest::get_bot(cursor_cell) > editor.file_space_y + editor.height) editor.file_space_y = zest::get_bot(cursor_cell) - editor.height; if (zest::get_left(cursor_cell) < editor.file_space_x) editor.file_space_x = zest::get_left(cursor_cell); if (zest::get_right(cursor_cell) > editor.file_space_x + editor.width) editor.file_space_x = zest::get_right(cursor_cell) - editor.width; editor.view_rect.x = editor.file_space_x; editor.view_rect.y = editor.file_space_y; } void update_selection(Editor& editor, LineBuffer& line_buffer) { zest::Vec2 mouse_pos = zest::zestify(GetMousePosition()); if (is_inside(mouse_pos, editor.text_area_rect) && IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) { editor.selecting = true; editor.selection_valid = true; editor.selection_origin = window_to_cursor_pos(editor, line_buffer, mouse_pos); editor.selection_current = editor.selection_origin; } if (editor.selecting) { if (IsMouseButtonDown(MOUSE_BUTTON_LEFT)) editor.selection_current = window_to_cursor_pos(editor, line_buffer, mouse_pos); if (IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) editor.selecting = false; } } void update(LineBuffer& line_buffer, CursorState& cursor, Editor& editor, double time_delta) { update_cursor_direction(line_buffer, cursor, editor, move_cursor_left, KEY_LEFT, cursor.state_left, time_delta); update_cursor_direction(line_buffer, cursor, editor, move_cursor_right, KEY_RIGHT, cursor.state_right, time_delta); update_cursor_direction(line_buffer, cursor, editor, move_cursor_up, KEY_UP, cursor.state_up, time_delta); update_cursor_direction(line_buffer, cursor, editor, move_cursor_down, KEY_DOWN, cursor.state_down, time_delta); if (editor.cursorize_view) set_file_view_to_cursor(cursor, editor); editor.cursorize_view = false; if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT) || IsMouseButtonDown(MOUSE_BUTTON_LEFT)) { set_cursor_to_mouse(cursor, editor, line_buffer); } cursor.time += time_delta; if (cursor.time >= cursor.blink_time) { cursor.time -= cursor.blink_time; cursor.visible = !cursor.visible; } editor.file_space_y += -GetMouseWheelMove()*editor.cell_height; editor.view_rect.y = editor.file_space_y; if (editor.file_space_y < 0) editor.file_space_y = 0; float file_bot = (line_buffer.line_count() - 1) * editor.cell_height; if (editor.file_space_y >= file_bot) editor.file_space_y = file_bot; // Set the mouse cursor to correct image zest::Vec2 mouse_pos = zest::zestify(GetMousePosition()); if (mouse_pos.x >= editor.top_left_x && mouse_pos.x <= editor.top_left_x + editor.width && mouse_pos.y >= editor.top_left_y && mouse_pos.y <= editor.top_left_y + editor.height) { SetMouseCursor(MOUSE_CURSOR_IBEAM); } else { SetMouseCursor(MOUSE_CURSOR_DEFAULT); } update_selection(editor, line_buffer); } void draw_clipped_rectangle(Image& img, const zest::Rect& image_rect, const zest::Rect& target_rect, Color color) { zest::Rect rect = zest::clip_rect_to_fit(image_rect, target_rect); if (rect.width == 0 || rect.height == 0) return; zest::raylib::draw_rectangle(img, rect, color); } void draw_text_segment(Image* image, const char* text, int from, int to, zest::Vec2 pos, const FontInfo& font_info, std::vector<char>& buffer, Color text_color, std::optional<Color> bg_color) { if (from >= to) return; int n = to - from; if (buffer.size() < n + 1) buffer.resize(n + 1); std::memcpy(buffer.data(), text + from, n); buffer[n] = 0; if (bg_color) ImageDrawRectangle(image, pos.x, pos.y, n*font_info.char_step, font_info.font_size, *bg_color); ImageDrawTextEx(image, font_info.font, buffer.data(), { pos.x, pos.y }, font_info.font_size, font_info.char_spacing, text_color); } void draw_node(Editor& editor, LineBuffer& line_buff, TSNode node, zest::Color color) { TSPoint start = ts_node_start_point(node); TSPoint end = ts_node_end_point(node); if (end.row != start.row) { //std::cout << ts_node_type(node) << "\n"; std::cerr << "PANIC!\n"; return; } uint32_t len = end.column - start.column; zest::Rect node_rect = { start.column*editor.cell_width, start.row*editor.cell_height, len*editor.cell_width, editor.cell_height }; std::vector<char> buffer(len + 1, 0); std::memcpy(buffer.data(), line_buff.get_line(start.row).c_str() + start.column, len); if (!zest::are_intersecting(node_rect, editor.view_rect)) return; float x = node_rect.x - editor.view_rect.x; float y = node_rect.y - editor.view_rect.y; ImageDrawTextEx(&editor.text_area_image, editor.font_info.font, buffer.data(), { x, y }, editor.font_info.font_size, editor.font_info.char_spacing, zest::raylib::to_raylib(color)); } void draw_highlights(Editor& editor, LineBuffer& line_buff) { zest::tree_sitter::TreePtr tree = zest::tree_sitter::parse_text(editor.parser.get(), line_buff); TSNode root = ts_tree_root_node(tree.get()); ts_query_cursor_exec(editor.query_cursor.get(), editor.queries.get(), root); TSQueryMatch match; uint32_t capture_idx; while (ts_query_cursor_next_capture(editor.query_cursor.get(), &match, &capture_idx)) { const TSQueryCapture& capture = match.captures[capture_idx]; uint32_t name_len; const char* capture_name = ts_query_capture_name_for_id(editor.queries.get(), capture.index, &name_len); std::string_view capture_view(capture_name, name_len); //std::cout << capture_view << "\n"; auto it = zest::highlight::highlights.find(capture_view); if (it == zest::highlight::highlights.end()) { std::cerr << "Capture not found!\n"; continue; } zest::Color color = it->second; draw_node(editor, line_buff, capture.node, color); } } void draw_selection(LineBuffer& line_buffer, CursorState& cursor, Editor& editor) { zest::Rect img_rect = { 0, 0, editor.text_area_rect.width, editor.text_area_rect.height }; zest::CellPos selection_start = editor.selection_origin; zest::CellPos selection_end = editor.selection_current; if (editor.selection_origin.line > editor.selection_current.line || (editor.selection_origin.line == editor.selection_current.line && editor.selection_origin.col >= editor.selection_current.col)) { std::swap(selection_start, selection_end); } std::vector<char> buffer; for (int i = selection_start.line; i <= selection_end.line; ++i) { int line_len = (int)line_buffer.get_line(i).size(); int from = i == selection_start.line ? selection_start.col : 0; int to = i == selection_end.line ? selection_end.col : line_len; int n = to - from; float x = from*editor.cell_width - editor.file_space_x; float y = i*editor.cell_height - editor.file_space_y; int added_len = selection_end.line > selection_start.line && i != selection_end.line ? 1 : 0; draw_clipped_rectangle( editor.text_area_image, img_rect, { x, y, (n + added_len)*editor.cell_width, editor.cell_height }, WHITE); if (n == 0) continue; if (buffer.size() < n + 1) buffer.resize(n + 1); std::memcpy(buffer.data(), &line_buffer.get_line(i)[from], n); buffer[n] = 0; ImageDrawTextEx(&editor.text_area_image, editor.font_info.font, buffer.data(), { x, y }, editor.font_info.font_size, editor.font_info.char_spacing, BLACK); } } void draw(LineBuffer& line_buffer, CursorState& cursor, Editor& editor) { int font_size = editor.font_info.font_size; ImageClearBackground(&editor.text_area_image, BLUE); int first_row = editor.file_space_y/font_size; int last_row = (editor.file_space_y + editor.height)/font_size; int rows = line_buffer.line_count(); int first_col = editor.file_space_x/editor.cell_width; float x = first_col*editor.cell_width - editor.file_space_x; float y = first_row*font_size - editor.file_space_y; for (int i = first_row; i <= last_row && i < rows; ++i) { if (first_col < line_buffer.get_line(i).size()) ImageDrawTextEx(&editor.text_area_image, editor.font_info.font, &line_buffer.get_line(i)[first_col], { x, y }, font_size, editor.font_info.char_spacing, WHITE); y += font_size; } if (editor.selection_valid) draw_selection(line_buffer, cursor, editor); if (cursor.visible) { float offset_x = cursor.col*editor.cell_width - editor.file_space_x; float offset_y = cursor.line*editor.cell_height - editor.file_space_y; if (offset_y > -editor.cell_height && offset_y < editor.height) draw_clipped_rectangle( editor.text_area_image, { 0, 0, editor.text_area_rect.width, editor.text_area_rect.height }, { offset_x, offset_y, 2, (float)font_size }, WHITE); } draw_highlights(editor, line_buffer); Texture2D text_area_texture = LoadTextureFromImage(editor.text_area_image); BeginDrawing(); ClearBackground(BLACK); DrawTexture(text_area_texture, editor.top_left_x, editor.top_left_y, WHITE); DrawRectangleLines(editor.top_left_x - 1, editor.top_left_y - 1, editor.width + 2, editor.height + 2, RED); zest::Vec2 mouse_pos = zest::zestify(GetMousePosition()); DrawRectangle(mouse_pos.x, mouse_pos.y, 2, 2, RED); EndDrawing(); UnloadTexture(text_area_texture); } int main(int argc, char** argv) { std::string file_path; if (argc < 2) file_path = "../main.cpp"; else file_path = argv[1]; LineBuffer line_buffer = load_file(file_path); int fps = 30; double target_frame_time = 1.0/60.0; int window_width = 800; int window_height = 450; SetTraceLogLevel(LOG_WARNING); SetConfigFlags(FLAG_WINDOW_HIGHDPI); InitWindow(window_width, window_height, "edwin"); App app = init_app(window_width, window_height); double last_frame_time = 0.0f; while (true) { if (WindowShouldClose()) break; double start_time = GetTime(); update(line_buffer, app.cursor, app.editor, last_frame_time); draw(line_buffer, app.cursor, app.editor); double elapsed = GetTime() - start_time; if (elapsed < target_frame_time) WaitTime(target_frame_time - elapsed); last_frame_time = GetTime() - start_time; } UnloadImage(app.editor.text_area_image); UnloadFont(app.editor.font_info.font); CloseWindow(); }
// // This file is part of the 2FAS iOS app (https://github.com/twofas/2fas-ios) // Copyright © 2023 Two Factor Authentication Service, Inc. // Contributed by Zbigniew Cisiński. All rights reserved. // // 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 // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/> // import UIKit import Common struct AppearanceSection: TableViewSection { let title: String? var cells: [AppearanceCell] let footer: String? } struct AppearanceCell: Hashable { enum Accessory: Hashable { case toggle(isOn: Bool) case checkmark(selected: Bool) } enum Kind: Hashable { case incomingToken case activeSearch case defaultList case compactList case hideTokens } let icon: UIImage? let title: String let accessory: Accessory let kind: Kind } extension AppearancePresenter { func buildMenu() -> [AppearanceSection] { let isIncomingTokenEnabled = interactor.isNextTokenEnabled let incoming = AppearanceSection( title: nil, cells: [ .init( icon: Asset.settingsNextToken.image, title: T.Settings.showNextToken, accessory: .toggle(isOn: isIncomingTokenEnabled), kind: .incomingToken ) ], footer: T.Settings.seeIncomingTokens ) let isActiveSearchEnabled = interactor.isActiveSearchEnabled let activeSearch = AppearanceSection( title: nil, cells: [ .init( icon: Asset.settingsActiveSearch.image, title: T.Appearance.toggleActiveSearch, accessory: .toggle(isOn: isActiveSearchEnabled), kind: .activeSearch ) ], footer: T.Appearance.activeSearchDescription ) let selectedStyle = interactor.selectedListStyle let listStyle = AppearanceSection( title: T.Settings.listStyle, cells: [ .init( icon: UIImage(systemName: "rectangle.grid.1x2.fill")? .apply(Theme.Colors.Fill.theme)? .scalePreservingAspectRatio(targetSize: Theme.Metrics.settingsSmallIconSize), title: T.Settings.listStyleOptionDefault, accessory: .checkmark(selected: selectedStyle == .default), kind: .defaultList ), .init( icon: UIImage(systemName: "rectangle.grid.2x2.fill")? .apply(Theme.Colors.Fill.theme)? .scalePreservingAspectRatio(targetSize: Theme.Metrics.settingsSmallIconSize), title: T.Settings.listStyleOptionCompact, accessory: .checkmark(selected: selectedStyle == .compact), kind: .compactList ) ], footer: nil ) let tokensHidden = AppearanceSection( title: nil, cells: [ .init( icon: UIImage(systemName: "eye.fill")? .apply(Theme.Colors.Fill.theme)? .scalePreservingAspectRatio(targetSize: Theme.Metrics.settingsSmallIconSize), title: T.Settings.hideTokensTitle, accessory: .toggle(isOn: interactor.areTokensHidden), kind: .hideTokens ) ], footer: T.Settings.hideTokensDescription ) return[ incoming, activeSearch, listStyle, tokensHidden ] } }
<template> <el-form ref="userRef" :model="form" :rules="rules" label-width="100px" > <el-form-item label="手机号码:" prop="phonenumber"> <el-input v-model="form.phonenumber" maxlength="11" /> </el-form-item> <el-form-item label="用户邮箱:" prop="email"> <el-input v-model="form.email" maxlength="50" /> </el-form-item> <el-form-item> <el-button type="primary" @click="handleSubmit">保存</el-button> </el-form-item> </el-form> </template> <script setup> import {defineProps, ref} from "vue"; import requestUtil from "@/util/request"; import { ElMessage } from 'element-plus' import store from "@/store"; const props=defineProps( { user:{ type:Object, default:()=>{}, required:true } } ) const form=ref({ id:-1, phonenumber:'', email:'' }) const userRef=ref(null) //表单校验规则 const rules = ref({ email: [{ required: true, message: "邮箱地址不能为空", trigger: "blur" }, { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }], phonenumber: [{ required: true, message: "手机号码不能为空", trigger: "blur" }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }], }); //取出component传过来的值 form.value=props.user; //表单提交 const handleSubmit=()=>{ userRef.value.validate(async (valid)=>{ if(valid) { //验证通过之后提交 let result = await requestUtil.post("sys/user/save", form.value); let data = result.data; if (data.code === 200) { ElMessage.success("执行成功!") //更新store中的userInfo store.commit("SET_USERINFO", form.value) } } }) } </script> <style lang="sass" scoped> </style>
from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer def generate_resume(name, email, phone, address, education, experience, skills, template): pdf_path = 'resume.pdf' doc = SimpleDocTemplate(pdf_path, pagesize=A4) story = [] styles = getSampleStyleSheet() style_title = styles[template['title']] style_heading = styles[template['heading_style']] style_body = styles[template['body_style']] story.append(Paragraph(name, style_title)) story.append(Spacer(1, 12)) story.append(Paragraph(f"Email: {email}", style_body)) story.append(Paragraph(f"Phone: {phone}", style_body)) story.append(Paragraph(f"Address: {address}", style_body)) story.append(Spacer(1, 12)) story.append(Paragraph("教育背景", style_heading)) for year, content in education: story.append(Paragraph(f"{year}: {content}", style_body)) story.append(Spacer(1, 12)) story.append(Paragraph("工作经历", style_heading)) for year, content in experience: story.append(Paragraph(f"{year}: {content}", style_body)) story.append(Spacer(1, 12)) story.append(Paragraph("技能", style_heading)) for year, content in skills: story.append(Paragraph(f"{year}: {content}", style_body)) story.append(Spacer(1, 12)) doc.build(story) return pdf_path
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@200;600&display=swap" rel="stylesheet"> <!-- Styles --> <style> html, body { background-color: #fff; color: #636b6f; font-family: 'Nunito', sans-serif; font-weight: 200; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links > a { color: #636b6f; padding: 0 25px; font-size: 13px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } </style> </head> <body> <div class="flex-center position-ref full-height"> @if (Route::has('login')) <div class="top-right links"> @auth <a href="{{ url('/home') }}">Home</a> @else <a href="{{ route('login') }}">Login</a> @if (Route::has('register')) <a href="{{ route('register') }}">Register</a> @endif @endauth </div> @endif <div class="content"> <div class="title m-b-md"> Laravel </div> {{-- <h1> {{__('messages.hello')}} </h1> --}} {{-- <p>{{$id}} -- {{$name}}</p> --}} <p>{{$obj ->name}} -- {{$obj->gender}}</p> {{-- @if($obj -> name == 'mohamed') --}} {{-- <p> yea am mohamed ahmed</p> @else <p>not mohamed ahmed</p> @endif --}} {{-- @if($name2 == 'mohamed') <p> yea am mohamed ahmed</p> @else <p>not mohamed ahmed</p> @endif --}} {{-- @foreach ($data as $_data) <p>{{$_data}}</p> @if($_data =='mohamed') <p>yea mohamed exist</p> @elseif($_data == 'ahmed') <p>yea ahmed exist</p> @else <p>{{$_data}} is not defined</p> @endif @endforeach --}} {{-- @forelse ($data2 as $_data2) <p>{{$_data2}}</p> @empty <p> sorry but this is empty array</p> @endforelse --}} </div> </div> </body> </html>
import json from http import HTTPStatus from typing import Any, Dict, Optional import httpx from ... import errors from ...client import AuthenticatedClient, Client from ...models.remove_mount_remove_mount_201_response import ( RemoveMountRemoveMount201Response, ) from ...models.remove_mount_remove_mount_request import RemoveMountRemoveMountRequest from ...types import ApiError, Error, Response def _get_kwargs( ship_symbol: str, *, _client: AuthenticatedClient, json_body: RemoveMountRemoveMountRequest, ) -> Dict[str, Any]: url = "{}/my/ships/{shipSymbol}/mounts/remove".format( _client.base_url, shipSymbol=ship_symbol ) headers: Dict[str, str] = _client.get_headers() cookies: Dict[str, Any] = _client.get_cookies() json_json_body = json_body.dict(by_alias=True) return { "method": "post", "url": url, "headers": headers, "cookies": cookies, "timeout": _client.get_timeout(), "follow_redirects": _client.follow_redirects, "json": json_json_body, } def _parse_response( *, client: Client, response: httpx.Response ) -> Optional[RemoveMountRemoveMount201Response]: if response.status_code == HTTPStatus.CREATED: response_201 = RemoveMountRemoveMount201Response(**response.json()) return response_201 if client.raise_on_unexpected_status: raise errors.UnexpectedStatus(response.status_code, response.content) else: return None def _build_response( *, client: Client, response: httpx.Response ) -> Response[RemoveMountRemoveMount201Response]: return Response( status_code=HTTPStatus(response.status_code), content=response.content, headers=response.headers, parsed=_parse_response(client=client, response=response), ) def sync_detailed( ship_symbol: str, *, _client: AuthenticatedClient, raise_on_error: Optional[bool] = None, **json_body: RemoveMountRemoveMountRequest, ) -> Response[RemoveMountRemoveMount201Response]: """Remove Mount Remove a mount from a ship. The ship must be docked in a waypoint that has the `Shipyard` trait, and must have the desired mount that it wish to remove installed. A removal fee will be deduced from the agent by the Shipyard. Args: ship_symbol (str): json_body (RemoveMountRemoveMountRequest): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx.TimeoutException: If the request takes longer than Client.timeout. Returns: Response[RemoveMountRemoveMount201Response] """ json_body = RemoveMountRemoveMountRequest.parse_obj(json_body) kwargs = _get_kwargs( ship_symbol=ship_symbol, _client=_client, json_body=json_body, ) response = httpx.request( verify=_client.verify_ssl, **kwargs, ) resp = _build_response(client=_client, response=response) raise_on_error = ( raise_on_error if raise_on_error is not None else _client.raise_on_error ) if not raise_on_error: return resp if resp.status_code < 300: return resp.parsed.data try: error = json.loads(resp.content) details = error.get("error", {}) except Exception: details = {"message": resp.content} raise ApiError( Error( status_code=resp.status_code, message=details.get("message"), code=details.get("code"), data=details.get("data"), headers=resp.headers, ) ) async def asyncio_detailed( ship_symbol: str, *, _client: AuthenticatedClient, raise_on_error: Optional[bool] = None, **json_body: RemoveMountRemoveMountRequest, ) -> Response[RemoveMountRemoveMount201Response]: """Remove Mount Remove a mount from a ship. The ship must be docked in a waypoint that has the `Shipyard` trait, and must have the desired mount that it wish to remove installed. A removal fee will be deduced from the agent by the Shipyard. Args: ship_symbol (str): json_body (RemoveMountRemoveMountRequest): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx.TimeoutException: If the request takes longer than Client.timeout. Returns: Response[RemoveMountRemoveMount201Response] """ json_body = RemoveMountRemoveMountRequest.parse_obj(json_body) kwargs = _get_kwargs( ship_symbol=ship_symbol, _client=_client, json_body=json_body, ) async with httpx.AsyncClient(verify=_client.verify_ssl) as c: response = await c.request(**kwargs) resp = _build_response(client=_client, response=response) raise_on_error = ( raise_on_error if raise_on_error is not None else _client.raise_on_error ) if not raise_on_error: return resp if resp.status_code < 300: return resp.parsed.data try: error = json.loads(resp.content) details = error.get("error", {}) except Exception: details = {"message": resp.content} raise ApiError( Error( status_code=resp.status_code, message=details.get("message"), code=details.get("code"), data=details.get("data"), headers=resp.headers, ) )
package com.example.leetCodeRepetition.Controller; import com.example.leetCodeRepetition.Model.Email; import com.example.leetCodeRepetition.Model.User; import com.example.leetCodeRepetition.Repo.UserRepository; import com.example.leetCodeRepetition.utils.JwtUtil; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import com.example.leetCodeRepetition.utils.MyLogger; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping(path = "api/v1/users") public class UserController { @Autowired private final UserRepository repository; @Autowired private JwtUtil jwtUtil; // private final MyLogger logger = new MyLogger(); public UserController(UserRepository repository) { this.repository = repository; } // Add a new user @PostMapping("/add") public ResponseEntity<Object> createUser(@RequestBody User user) { logger.info("Creating user: " + user.getEmail()); logger.info("Creating user: " + user.getLogin_method()); if(repository.findUserByEmail(user.getEmail()) != null){ logger.info("User already exists"); return new ResponseEntity<>(repository.findUserByEmail(user.getEmail()), HttpStatus.OK); } User createdUser = repository.save(new User(user.getEmail(),user.getLogin_method())); if (createdUser.getId() != null) { return new ResponseEntity<>(createdUser, HttpStatus.CREATED); } else { // Rollback the insertion and return an error response repository.delete(createdUser); return new ResponseEntity<>("Failed to create user", HttpStatus.INTERNAL_SERVER_ERROR); } } @PostMapping("/testUserLogin") public ResponseEntity<Object> testUserLogin(@RequestBody Email emailObj) { logger.info("Logging in test user: " + emailObj.getEmail()); String email = emailObj.getEmail(); if(repository.findUserByEmail(email) == null){ logger.info("No such test user:" +email); return new ResponseEntity<>("No such test user: "+email, HttpStatus.NOT_FOUND); } String token = jwtUtil.generateToken(email); //cookie.setSecure(true); Map<String, String> responseBody = new HashMap<>(); responseBody.put("message", "Welcome, " + email + "!"); responseBody.put("token", token); return new ResponseEntity<>(responseBody, HttpStatus.OK); } // @GetMapping("/logout") // public ResponseEntity<String> logout(HttpServletResponse response) { // Cookie cookie = new Cookie("token", null); // name should be the same as the one you want to remove // cookie.setPath("/"); // path should be the same as the one you want to remove // cookie.setHttpOnly(true); // cookie.setMaxAge(0); // setting max age to 0 deletes the cookie // response.addCookie(cookie); // return new ResponseEntity<>("Logged out", HttpStatus.OK); // } // Find a user by email @GetMapping("/find") public ResponseEntity<Object> findUserByEmail(@RequestParam String email) { email = email.replace("\"", ""); User user = repository.findUserByEmail(email); if (user == null) { return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND); } return new ResponseEntity<>(user, HttpStatus.OK); } // delete a user by email @DeleteMapping("/delete") public ResponseEntity<Object> deleteUserByEmail(@RequestParam String email) { User user = repository.findUserByEmail(email); if (user == null) { return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND); } repository.delete(user); return new ResponseEntity<>("User deleted", HttpStatus.OK); } }
import React, { useEffect, useState } from "react"; import AddCircleIcon from "@mui/icons-material/AddCircle"; import { Box, Button, IconButton, InputBase, Modal, Stack, TextField, } from "@mui/material"; import ArchiveIcon from "@mui/icons-material/Archive"; import PaletteIcon from "@mui/icons-material/Palette"; import MyNotes from "./MyNotes"; import axios from "axios"; import { useDispatch, useSelector } from "react-redux"; import { addNote, selectAllArchived, selectAllNotes, } from "../redux/slice/noteSlice"; import { selectCurrentLogin, selectCurrentToken, } from "../redux/slice/authSlice"; const NotesPage = () => { const [isHovered, setIsHovered] = useState(false); const [open, setOpen] = useState(false); const token = useSelector(selectCurrentToken); const archivedNotes = useSelector(selectAllArchived); const login = useSelector(selectCurrentLogin); const notes = useSelector(selectAllNotes); const dispatch = useDispatch(); const [inputs, setInputs] = useState({ title: "", content: "", }); const handleOpen = () => setOpen(true); const handleClose = () => { handleCreate(); setOpen(false); }; useEffect(() => {}, [notes, archivedNotes]); const handleCreate = async () => { try { const config = { headers: { Authorization: `${token}`, }, }; const response = await axios.post( "http://localhost:4000/api/v1/note/create-notes", { title: inputs.title, content: inputs.content, }, config ); if (response.data.success) { dispatch(addNote(response.data.data)); setOpen(false); alert(response.data.message); setInputs({ title: "", content: "" }); } else { setOpen(false); alert(response.data.message); setInputs({ title: "", content: "" }); } } catch (error) { console.log(error); alert("Error in creating the note, try again later"); setOpen(false); } }; const handleMouseEnter = () => { setIsHovered(true); }; const handleMouseLeave = () => { setIsHovered(false); }; const handleChangeTitle = (e) => { setInputs((prevState) => ({ ...prevState, title: e.target.value, })); }; const handleChangeContent = (e) => { setInputs((prevState) => ({ ...prevState, content: e.target.value, })); }; return ( <> {login && ( <Box sx={{ width: "100%", minHeight: "100vh", position: "relative" }}> <Box> <MyNotes /> </Box> <Box sx={{ position: "fixed", bottom: "2vh", right: "1vw", zIndex: 9999, }} > <IconButton onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} onClick={handleOpen} > <AddCircleIcon sx={{ color: isHovered ? "grey" : "black", fontSize: "5rem" }} /> </IconButton> <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={{ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", width: "90%", maxWidth: "43.75rem", height: "80%", bgcolor: "background.paper", boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 2px 6px 2px", borderRadius: "0.4375rem", overflow: "auto", p: "1rem", }} > <Box sx={{ background: "#060b26", borderRadius: "0.625rem", padding: "0.5rem", margin: "0.625rem", }} > <Stack direction={"row"} spacing="0.625rem" sx={{ alignItems: "center", display: "flex", justifyContent: "flex-end", alignItem: "flex-end", }} > <ArchiveIcon sx={{ color: "white" }} /> <PaletteIcon sx={{ color: "white" }} /> <Button sx={{ color: "white" }} onClick={handleClose}> Close </Button> </Stack> </Box> <Stack spacing="1.875rem" sx={{ margin: "5%" }}> <TextField id="standard-basic" label="Title" variant="standard" onChange={handleChangeTitle} value={inputs.title} /> <InputBase multiline fullWidth placeholder="Take a Note..." maxRows={6} onChange={handleChangeContent} value={inputs.content} sx={{ border: "none", borderBottom: "none" }} // Custom styles to remove the underline /> <Button sx={{ position: "fixed", bottom: "1.25rem", right: "1.25rem", padding: "0.8125rem", }} onClick={handleCreate} > Create Note.. </Button> </Stack> </Box> </Modal> </Box> </Box> )} </> ); }; export default NotesPage;
<table mat-table [dataSource]="dataSource" matSort (click)="tableSort()" class="mat-elevation-z8 table-view"> <ng-container matColumnDef="image"> <th mat-header-cell *matHeaderCellDef></th> <td class="image-cell" mat-cell *matCellDef="let element"> <img style="height: 10vh;" src="{{element.imageUrl}}" alt="{{element.planetName}}"> </td> </ng-container> <ng-container matColumnDef="planetName"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th> <td class="mat-column-planet-name" mat-cell *matCellDef="let element"> <div class="planet-name">{{element.planetName}}</div> <div class="planet-description">{{element.description}}</div> </td> </ng-container> <ng-container matColumnDef="planetColor"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Color </th> <td mat-cell *matCellDef="let element"> {{element.planetColor}} </td> </ng-container> <ng-container matColumnDef="planetRadiusKM"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Radius in km </th> <td mat-cell *matCellDef="let element"> {{element.planetRadiusKM}} </td> </ng-container> <ng-container matColumnDef="fromSun"> <th mat-header-cell *matHeaderCellDef> Dist. from Sun </th> <td mat-cell *matCellDef="let element"> {{element.distInMillionsKM.fromSun}} </td> </ng-container> <ng-container matColumnDef="fromEarth"> <th mat-header-cell *matHeaderCellDef> Dist. from Earth </th> <td mat-cell *matCellDef="let element"> {{element.distInMillionsKM.fromEarth}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr class="table-row" [routerLink]="['/planet-details/', row.id]" mat-row *matRowDef="let row; columns: displayedColumns;"> </tr> <tr *matNoDataRow> <td>No data to display</td> </tr> </table>
#include <unistd.h> #include <fcntl.h> #include "main.h" /** * append_text_to_file - appends text to a file * @filename: file to receive appended text * @text_content: text to be appended * * Return: 1 on success, -1 on failure */ int append_text_to_file(const char *filename, char *text_content) { int fd, nWrite, contentLen; contentLen = _strlen(text_content); if (filename == NULL) return (-1); fd = open(filename, O_WRONLY | O_APPEND); if (fd == -1) return (-1); if (contentLen != 0) nWrite = write(fd, text_content, contentLen); if (nWrite == -1) return (-1); if (close(fd) == -1) return (-1); return (1); } /** * _strlen - returns the length of a string * @s: input string * * Return: string length */ int _strlen(char *s) { int len = 0; if (s == NULL) return (0); while (*s != '\0') { len++; s++; } return (len); }
package com.example.JavaTestApplication.mockito.injectmocks; import com.example.JavaTestApplication.mockito.mock.TestService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.annotation.Description; @ExtendWith(MockitoExtension.class) public class InjectMocksTest { @Mock TestService testService; @InjectMocks WrappingTestService wrappingTestService = new WrappingTestService(new TestService("tet", 3), "dest"); @Test @DisplayName("@InjectMocks 테스트") @Description("WrappingTestService의 TestService가 Mock으로 생성된 TestService와 동일한 객체인지 검사" + "@InjectMocks으로 생성된 객체는 Mock 객체가 아니라 실제 객체인 것을 검사") void injectMocksTest() { // given // when // then Assertions.assertSame(testService, wrappingTestService.getTestService()); Assertions.assertNull(wrappingTestService.getTestService().getName()); Assertions.assertEquals(0, wrappingTestService.getTestService().getNumber()); Assertions.assertNull(wrappingTestService.getTestService().getNameTimes()); Assertions.assertEquals("dest", wrappingTestService.getWrappingDes()); } @Test @DisplayName("@InjectMocks stubbing 테스트") void injectMocksStubbingTest() { // given Mockito.when(testService.getName()).thenReturn("mockName"); // when // then Assertions.assertSame(testService, wrappingTestService.getTestService()); Assertions.assertEquals(testService.getName(), wrappingTestService.getTestService().getName()); Assertions.assertEquals("dest", wrappingTestService.getWrappingDes()); } @Test @DisplayName("@InjectMocks 객체 Stubbing 에러 테스트") @Description("@InjectMocks로 생성한 객체에 Stubbing을 했을 경우 Exception이 발생하는지 검사") void exceptionThrowWhenStubbing() { // given // when // then Assertions.assertThrows(Exception.class, () -> { Mockito.when(wrappingTestService.getWrappingDes()).thenReturn("stubbing des"); }); } }
import { Stack, Grid, Box, Typography, useTheme, useMediaQuery } from '@mui/material'; import { News } from '@src/apis/home/news'; const SectionNewsCardDesktop = ({ title, description, image }: News) => { const { palette } = useTheme(); return ( <Stack display={'flex'} direction={'row'} spacing={3} alignItems={'center'}> <Box width="100%" maxWidth="474px" height="294px" maxHeight={'294px'} borderRadius={2} overflow={'hidden'} flex={'1 0 474px'} bgcolor={palette.hotelPrimary[10]} display={'flex'} alignItems={'center'} > <img src={image} alt={description} width="100%" height="auto" /> </Box> <Grid container direction={'column'} alignItems={'flex-start'} justifyContent={'flex-start'} flex={'1 1 auto'} > <Typography variant="H3_32px_B" color={palette.neutral[100]} component={'h3'} mb={3}> {title} </Typography> <Typography variant="Body_16px_R" color={palette.neutral[80]}> {description} </Typography> </Grid> </Stack> ); }; const SectionNewsCardMobile = ({ title, description, image }: News) => { const { palette } = useTheme(); return ( <Stack display={'flex'} direction={'column'} spacing={3} alignItems={'center'}> <Box width="100%" maxWidth="351px" height="294px" maxHeight={'294px'} borderRadius={2} overflow={'hidden'} flex={'1 0 294px'} bgcolor={palette.hotelPrimary[10]} display={'flex'} alignItems={'center'} > <img src={image} alt={description} width="100%" height="auto" /> </Box> <Grid container direction={'column'} alignItems={'flex-start'} justifyContent={'flex-start'} flex={'1 1 auto'} > <Typography variant="H4_28px_B" color={palette.neutral[100]} component={'h4'} mb={1}> {title} </Typography> <Typography variant="Body2_14px_R" color={palette.neutral[80]}> {description} </Typography> </Grid> </Stack> ); }; const SectionNewsCard = ({ news }: { news: News }) => { const { breakpoints } = useTheme(); const isDesktop = useMediaQuery(breakpoints.up('md')); return isDesktop ? SectionNewsCardDesktop(news) : SectionNewsCardMobile(news); }; export default SectionNewsCard;
import { type ReactNode, useEffect, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; export const Portal = ({ children }: { children: ReactNode }) => { const portalRef = useRef<HTMLElement | null>(null); const [mounted, setMounted] = useState(false); useEffect(() => { portalRef.current = document.getElementById('portal'); setMounted(true); }, []); return mounted && portalRef.current ? createPortal(children, portalRef.current) : null; };
public abstract class Student { private String firstname; private String major; private int units; public Student( String firstname, String major, int units) { this.firstname = firstname; this.major = major; this.units = units; } // multi-constructor public void setfirstname(String firstname) { this.firstname = firstname; } //set name public String getfirstname() { return firstname; } //get name public void setmajor(String major) { this.major = major; } //set major public String getmajor() { return major; } //get major public void setunits(int units) { this.units = units; } //set units public int getunits() { return units; } //get units public abstract int calculateTuition(); public String toString() { String output = new String(); output = "First name: " + firstname + "\n" + "Major: " + major + "\n" + "Units: " + units + "\n" + "Tuition fees: " + calculateTuition(); return output; } // end toString } // end class
from typing import Tuple class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return f"Node({self.data})" def __str__(self): return f"{self.data}" class LinkedList: """LinkedList""" def __init__(self): self.__head__ = None self.__tail__ = None self.__size__ = 0 def __move_to_index__(self, at_index: int) -> Tuple[Node, Node]: """_summary_ Args: at_index (int): _description_ Raises: IndexError: _description_ IndexError: _description_ Returns: Tuple[Node, Node]: prev, curr nodes """ if at_index < 0 or at_index > self.__size__: raise IndexError(f'Idx {at_index} does not exiust') curr_idx = 0 curr = self.__head__ prev = None # move curr to desired index while curr is not None and curr_idx < at_index: prev = curr curr = curr.next curr_idx += 1 return (prev, curr) def __repr__(self): tokens = [] curr = self.__head__ while curr is not None: arrow = "" if curr.next is None else " -> " tokens.append(curr.data) tokens.append(arrow) curr = curr.next return "".join(tokens) def is_empty(self): """True if the list is empty""" return self.__head__ is None def delete_list(self): """Delete the list""" self.__head__ = None self.__tail__ = None self.__size__ = 0 def length(self) -> int: """the size of the linked list Returns: _type_: _description_ """ return self.__size__ def append(self, data): """insert an element at the end of the list Args: data (_type_): _description_ """ new_node = Node(data) if self.__head__ is None: self.__head__ = new_node if self.__tail__ is not None: self.__tail__.next = new_node self.__tail__ = new_node self.__size__ += 1 def prepend(self, data): """insert an element at the beginning of the list Args: data (_type_): _description_ """ new_node = Node(data) if self.__head__ is None: self.__head__ = new_node else: new_node.next = self.__head__ self.__head__ = new_node self.__size__ += 1 def remove(self, value): """remove Args: value (_type_): _description_ """ curr = self.__head__ if self.is_empty(): return found = False prev = None while not found and curr is not None: found = curr.data == value if found: # special cases if self.__head__ == curr: self.__head__ = curr.next if self.__tail__ == curr: self.__tail__ = prev if prev is not None: prev.next = curr.next else: prev = curr curr = curr.next self.__size__ -= 1 def insert(self, at_index: int, data): """insert at a given 0-based index Args: at_index (int): _description_ data (_type_): _description_ """ # no need to calculate anything if at_index == 0: self.prepend(data) return try: (prev, curr) = self.__move_to_index__(at_index) except IndexError as exc: raise exc new_node = Node(data) if curr is not None: new_node.next = curr if prev is not None: prev.next = new_node self.__size__ += 1 def delete(self, at_index: int): """delete at index Args: at_index (int): _description_ data (_type_): _description_ """ if at_index == 0: self.__head__ = self.__head__.next self.__size__ -= 1 return (prev, curr) = self.__move_to_index__(at_index) if curr is not None and prev is not None: prev.next = curr.next self.__size__ -= 1 def reverse(self): """reverse Reverses the order of the nodes, w/o copying """ if self.is_empty() or self.length() == 1: return head = self.__head__ tail = self.__tail__ # we now now we have at least 2 nodes to swap prev = None curr = head next_node = curr.next while next_node is not None: print(f"Processing {self}") curr.next = prev prev = curr curr = next_node if next_node is not None: next_node = next_node.next print(f"Result {self}") curr.next = prev self.__head__ = tail self.__tail__ = head def count(self, value) -> int: """count instances of a given value Args: value (_type_): _description_ Returns: int: _description_ """ acc = 0 if not self.is_empty(): curr = self.__head__ while curr is not None: if curr.data == value: acc += 1 curr = curr.next return acc def contains(self, value) -> bool: """determines if an element is contained in a list Args: value (_type_): _description_ Returns: bool: _description_ """ if self.is_empty(): return False curr = self.__head__ while curr is not None: if curr.data == value: return True curr = curr.next return False def find(self, at_index: int, from_end=False) -> str: try: if from_end: target_idx = (self.__size__ - at_index) - 1 else: target_idx = at_index (_, curr) = self.__move_to_index__(target_idx) return curr.data except IndexError as exc: raise exc
// // MenuController.swift // MakeupApp // // Created by IOS DEV PRO 1 on 05/10/2021. // Copyright © 2021 LTD. All rights reserved. // import UIKit protocol DisplayContentControllerDelegate { func tabDidSelectAction(_ sender: UIView) } final class MenuController: UIViewController, UITableViewDelegate, UITableViewDataSource, ImageUploaded { private var menuList: [MenuType] = [.teamScore, .HighScore] lazy var tableView: UITableView = { let tv = UITableView(frame: .zero, style: .plain) tv.delegate = self tv.estimatedRowHeight = 50 tv.backgroundColor = .white tv.separatorStyle = .none tv.tableFooterView = UIView(frame: .zero) tv.rowHeight = UITableView.automaticDimension tv.delegate = self tv.dataSource = self tv.translatesAutoresizingMaskIntoConstraints = false return tv }() lazy var bottomContainerView: UIView = { let iv = UIView() iv.translatesAutoresizingMaskIntoConstraints = false return iv }() lazy var finalBottomContainerView: UIView = { let iv = UIView() iv.translatesAutoresizingMaskIntoConstraints = false return iv }() lazy var seperatorView: UIView = { let iv = UIView() iv.backgroundColor = .lightGray iv.translatesAutoresizingMaskIntoConstraints = false return iv }() lazy var bottomSeperatorView: UIView = { let iv = UIView() iv.backgroundColor = .lightGray iv.translatesAutoresizingMaskIntoConstraints = false return iv }() lazy var profileView: MenuTopView = { let iv = MenuTopView() iv.profileBtn.addTarget(self, action: #selector(goToProfileWithAnimation), for: .touchUpInside) iv.translatesAutoresizingMaskIntoConstraints = false return iv }() lazy var privacyLabel: UILabel = { let l = UILabel() l.font = UIFont.systemFont(ofSize: HavaConstants.DEFAULT_FONT_SIZE) l.textAlignment = .natural l.textColor = UIColor(hexString: "#00824F") l.adjustsFontSizeToFitWidth = true l.isUserInteractionEnabled = true l.minimumScaleFactor = 0.1 l.text = "Privacy policy" + " •" l.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openCopyRight))) l.translatesAutoresizingMaskIntoConstraints = false return l }() lazy var termsLabel: UILabel = { let l = UILabel() l.font = UIFont.systemFont(ofSize: HavaConstants.DEFAULT_FONT_SIZE) l.textAlignment = .natural l.textColor = UIColor(hexString: "#00824F") l.adjustsFontSizeToFitWidth = true l.isUserInteractionEnabled = true l.minimumScaleFactor = 0.1 l.text = "Terms of Service" l.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openCopyRight))) l.translatesAutoresizingMaskIntoConstraints = false return l }() lazy var ftcBtn: UIButton = { let b = UIButton() b.setImage(#imageLiteral(resourceName: "image-logo-1"), for: .normal) b.imageView?.contentMode = .scaleAspectFit b.isUserInteractionEnabled = true b.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openSite))) b.translatesAutoresizingMaskIntoConstraints = false return b }() override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() setupViews() setNeedsStatusBarAppearanceUpdate() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } fileprivate func setupViews() { imageUploaded() view.addSubview(tableView) view.addSubview(profileView) view.addSubview(seperatorView) view.addSubview(bottomContainerView) view.addSubview(bottomSeperatorView) view.backgroundColor = .white bottomContainerView.backgroundColor = .white tableView.contentInset.top = (CGFloat(50 * 3) - tableView.contentSize.height) / 2 tableView.contentInset.bottom = (CGFloat(50 * 3) - tableView.contentSize.height) / 2 tableView.register(MenuCell.self, forCellReuseIdentifier: MenuCell.identifier) bottomContainerView.addSubview(termsLabel) bottomContainerView.addSubview(privacyLabel) bottomContainerView.addSubview(ftcBtn) profileView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true profileView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true profileView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true profileView.heightAnchor.constraint(equalToConstant: view.frame.height / 5).isActive = true profileView.bottomAnchor.constraint(equalTo: seperatorView.topAnchor, constant: -HavaConstants.DEFAULT_PADDING).isActive = true seperatorView.topAnchor.constraint(equalTo: profileView.bottomAnchor, constant: HavaConstants.DEFAULT_PADDING).isActive = true seperatorView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: HavaConstants.DOUBLE_PADDING).isActive = true seperatorView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -HavaConstants.DOUBLE_PADDING).isActive = true seperatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true seperatorView.bottomAnchor.constraint(equalTo: tableView.topAnchor, constant: -HavaConstants.DEFAULT_PADDING * 3).isActive = true let tableHeight = CGFloat(50 * 3) tableView.topAnchor.constraint(equalTo: seperatorView.bottomAnchor, constant: HavaConstants.DEFAULT_PADDING * 3).isActive = true tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true tableView.heightAnchor.constraint(equalToConstant: tableHeight).isActive = true tableView.bottomAnchor.constraint(equalTo: bottomSeperatorView.topAnchor, constant: -HavaConstants.DEFAULT_PADDING * 3).isActive = true bottomSeperatorView.topAnchor.constraint(equalTo: tableView.bottomAnchor, constant: HavaConstants.DEFAULT_PADDING * 3).isActive = true bottomSeperatorView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: HavaConstants.DOUBLE_PADDING).isActive = true bottomSeperatorView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true bottomSeperatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true bottomSeperatorView.bottomAnchor.constraint(equalTo: bottomContainerView.topAnchor, constant: -16).isActive = true bottomContainerView.topAnchor.constraint(equalTo: bottomSeperatorView.bottomAnchor, constant: HavaConstants.DOUBLE_PADDING).isActive = true bottomContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: HavaConstants.DOUBLE_PADDING).isActive = true bottomContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true bottomContainerView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -16).isActive = true privacyLabel.topAnchor.constraint(equalTo: bottomContainerView.topAnchor).isActive = true privacyLabel.trailingAnchor.constraint(equalTo: bottomContainerView.centerXAnchor).isActive = true privacyLabel.bottomAnchor.constraint(equalTo: privacyLabel.bottomAnchor).isActive = true termsLabel.topAnchor.constraint(equalTo: privacyLabel.topAnchor).isActive = true termsLabel.leadingAnchor.constraint(equalTo: bottomContainerView.centerXAnchor).isActive = true termsLabel.bottomAnchor.constraint(equalTo: termsLabel.bottomAnchor).isActive = true ftcBtn.centerYAnchor.constraint(equalTo: bottomContainerView.centerYAnchor).isActive = true ftcBtn.centerXAnchor.constraint(equalTo: bottomContainerView.centerXAnchor).isActive = true ftcBtn.heightAnchor.constraint(equalToConstant: 60).isActive = true ftcBtn.widthAnchor.constraint(equalTo: bottomContainerView.widthAnchor, multiplier: 0.6).isActive = true } func imageUploaded() { profileView.profilePicture.image = APIHelper.shared.getImage() } // MARK: - Tableview delegate methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: MenuCell.identifier) as? MenuCell ?? MenuCell() cell.selectionStyle = .none cell.dataSourceItem = menuList[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let item = menuList[indexPath.row] switch item { case .teamScore: navigationController?.pushViewController(FeedBackViewController(isFromHome: true), animated: true) case .HighScore: navigationController?.pushViewController(HighScoresViewController(), animated: true) } } // Open copyright @objc fileprivate func openCopyRight() { navigationController?.pushViewController(WebViewController(), animated: true) } // Open more info website @objc fileprivate func openSite() { if let url = URL(string: HavaConstants.moreInfoUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } } }
<?php namespace App\Http\Traits; /** * Motor para convertir cantidades numericas de moneda a letras. * * Class NumToLetrasEngine * @package App\Http\Modulos\Utils */ trait NumToLetrasEngine { /** * @function num2letras_en () * @abstract Dado un número lo devuelve escrito en letras en inglés * @param $num number - Número a convertir (máximo dos decimales) * @result string - Devuelve el número escrito en letras. * @return string */ public static function num2letras_en($num) { $decones = array( '01' => 'Zero One', '02' => 'Zero Two', '03' => 'Zero Three', '04' => 'Zero Four', '05' => 'Zero Five', '06' => 'Zero Six', '07' => 'Zero Seven', '08' => 'Zero Eight', '09' => 'Zero Nine', 10 => 'Ten', 11 => 'Eleven', 12 => 'Twelve', 13 => 'Thirteen', 14 => 'Fourteen', 15 => 'Fifteen', 16 => 'Sixteen', 17 => 'Seventeen', 18 => 'Eighteen', 19 => 'Nineteen' ); $ones = array( 0 => '', 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine', 10 => 'Ten', 11 => 'Eleven', 12 => 'Twelve', 13 => 'Thirteen', 14 => 'Fourteen', 15 => 'Fifteen', 16 => 'Sixteen', 17 => 'Seventeen', 18 => 'Eighteen', 19 => 'Nineteen' ); $tens = array( 0 => '', 1 => 'Ten', 2 => 'Twenty', 3 => 'Thirty', 4 => 'Forty', 5 => 'Fifty', 6 => 'Sixty', 7 => 'Seventy', 8 => 'Eighty', 9 => 'Ninety' ); $hundreds = array( 'Hundred', 'Thousand', 'Million', 'Billion', 'Trillion', 'Quadrillion' ); $num = number_format($num, 2, '.', ','); $num_arr = explode('.', $num); $wholenum = $num_arr[0]; $decnum = $num_arr[1]; $whole_arr = array_reverse(explode(",", $wholenum)); krsort($whole_arr); $rettxt = ""; foreach ($whole_arr as $key => $i) { if ($i < 20) { $rettxt .= $ones[abs($i)]; } elseif ($i < 100) { $rettxt .= $tens[substr($i, 0, 1)]; if (strlen($i) == 3) { $rettxt .= ' ' . $tens[substr($i, 1, 1)]; $rettxt .= ($ones[substr($i, 2, 1)] != '') ? '-' . $ones[substr($i, 2, 1)] : ' '; } else { $rettxt .= ' ' . $ones[substr($i, 1, 1)]; } } else { $rettxt .= $ones[substr($i, 0, 1)] . ' ' . $hundreds[0]; $rettxt .= ' ' . $tens[substr($i, 1, 1)]; if (substr($i, 2, 2) < 20) { $rettxt .= ($ones[substr($i, 2, 1)] != '' && $ones[substr($i, 1, 1)] != '') ? '-' . $ones[substr($i, 2, 1)] : ' ' . $ones[substr($i, 2, 1)]; } else { $rettxt .= ' ' . $tens[substr($i, 2, 1)]; $rettxt .= ($ones[substr($i, 3, 1)] != '') ? '-' . $ones[substr($i, 3, 1)] : ' '; } } if ($key > 0) { $rettxt .= ' ' . $hundreds[$key] . ' '; } } $rettxt = $rettxt . " dollars"; if ($decnum > 0) { $rettxt .= " and "; if ($decnum < 20) { $rettxt .= $decones[$decnum]; } elseif ($decnum < 100) { $rettxt .= $tens[substr($decnum, 0, 1)]; $rettxt .= " " . $ones[substr($decnum, 1, 1)]; } $rettxt = $rettxt . " cents"; } else { $rettxt = $rettxt . " and zero cents"; } $rettxt = strtoupper(str_replace(' ', ' ', $rettxt)); return $rettxt; } /** * @function num2letras () * @abstract Dado un número lo devuelve escrito en letras en español * @param $num number - Número a convertir (máximo dos decimales) y el número no debe tener seprador de miles * @param $fem bool - Forma femenina (true) o no (false). * @param $dec bool - Con decimales (true) o no (false). * @param string $moneda Por defecto es Pesos Colombianos * @result string - Devuelve el n?mero escrito en letra. * @return string */ public static function num2letras($num, $fem = false, $dec = true, $moneda = 'COP') { $end_num = ''; $matuni[2] = "DOS"; $matuni[3] = "TRES"; $matuni[4] = "CUATRO"; $matuni[5] = "CINCO"; $matuni[6] = "SEIS"; $matuni[7] = "SIETE"; $matuni[8] = "OCHO"; $matuni[9] = "NUEVE"; $matuni[10] = "DIEZ"; $matuni[11] = "ONCE"; $matuni[12] = "DOCE"; $matuni[13] = "TRECE"; $matuni[14] = "CATORCE"; $matuni[15] = "QUINCE"; $matuni[16] = "DIECISEIS"; $matuni[17] = "DIECISIETE"; $matuni[18] = "DIECIOCHO"; $matuni[19] = "DIECINUEVE"; $matuni[20] = "VEINTE"; $matunisub[2] = "DOS"; $matunisub[3] = "TRES"; $matunisub[4] = "CUATRO"; $matunisub[5] = "QUIN"; $matunisub[6] = "SEIS"; $matunisub[7] = "SETE"; $matunisub[8] = "OCHO"; $matunisub[9] = "NOVE"; $matdec[2] = "VEINT"; $matdec[3] = "TREINTA"; $matdec[4] = "CUARENTA"; $matdec[5] = "CINCUENTA"; $matdec[6] = "SESENTA"; $matdec[7] = "SETENTA"; $matdec[8] = "OCHENTA"; $matdec[9] = "NOVENTA"; $matsub[3] = 'MILL'; $matsub[5] = 'BILL'; $matsub[7] = 'MILL'; $matsub[9] = 'TRILL'; $matsub[11] = 'MILL'; $matsub[13] = 'BILL'; $matsub[15] = 'MILL'; $matmil[4] = 'MILLONES'; $matmil[6] = 'BILLONES'; $matmil[7] = 'DE BILLONES'; $matmil[8] = 'MILLONES DE BILLONES'; $matmil[10] = 'TRILLONES'; $matmil[11] = 'DE TRILLONES'; $matmil[12] = 'MILLONES DE TRILLONES'; $matmil[13] = 'DE TRILLONES'; $matmil[14] = 'BILLONES DE TRILLONES'; $matmil[15] = 'DE BILLONES DE TRILLONES'; $matmil[16] = 'MILLONES DE BILLONES DE TRILLONES'; if ($num == "0.00" && $moneda == 'COP') { $end_num = ' CERO PESOS M/CTE'; } elseif ($num == "0.00" && $moneda == 'USD') { $end_num = ' CERO DOLARES CON CERO CENTAVOS'; } else { //Zi hack $float = explode('.', $num); $num = $float[0]; if (count($float) == 1) { $float[1] = 0; } $num = trim((string)@$num); if ($num[0] == '-') { $neg = 'menos '; $num = substr($num, 1); } else { $neg = ''; } if(strlen($num) > 1) $num = ltrim($num, '0'); if ($num[0] < '1' or $num[0] > 9) $num = '0' . $num; $zeros = true; $punt = false; $ent = ''; $fra = ''; for ($c = 0; $c < strlen($num); $c++) { $n = $num[$c]; if (!(strpos(".,'''", $n) === false)) { if ($punt) break; else { $punt = true; continue; } } elseif (!(strpos('0123456789', $n) === false)) { if ($punt) { if ($n != '0') $zeros = false; $fra .= $n; } else $ent .= $n; } else break; } $ent = ' ' . $ent; if ($dec and $fra and !$zeros) { $fin = ' coma'; for ($n = 0; $n < strlen($fra); $n++) { if (($s = $fra[$n]) == '0') $fin .= ' cero'; elseif ($s == '1') $fin .= $fem ? ' una' : ' un'; else $fin .= ' ' . $matuni[$s]; } } else $fin = ''; $tex = ''; $sub = 0; $mils = 0; $neutro = false; if ((int)$ent === 0) $tex = ' Cero'; while (($num = substr($ent, -3)) != ' ') { $ent = substr($ent, 0, -3); if (++$sub < 3 and $fem) { $matuni[1] = 'una'; $subcent = 'as'; } else { $matuni[1] = $neutro ? 'un' : 'uno'; $subcent = 'os'; } $t = ''; $n2 = substr($num, 1); if ($n2 == '00') { // } elseif ($n2 < 21) $t = ' ' . $matuni[(int)$n2]; elseif ($n2 < 30) { $n3 = $num[2]; if ($n3 != 0) $t = 'i' . $matuni[$n3]; $n2 = $num[1]; $t = ' ' . $matdec[$n2] . $t; } else { $n3 = $num[2]; if ($n3 != 0) $t = ' y ' . $matuni[$n3]; $n2 = $num[1]; $t = ' ' . $matdec[$n2] . $t; } $n = $num[0]; if ($n == 1) { // $t = ' ciento' . $t; if (substr($num, 1) == "00") { $t = ' cien' . $t; } else { $t = ' ciento' . $t; } } elseif ($n == 5) { $t = ' ' . $matunisub[$n] . 'ient' . $subcent . $t; } elseif ($n != 0) { $t = ' ' . $matunisub[$n] . 'cient' . $subcent . $t; } if ($sub == 1) { } elseif (!isset($matsub[$sub])) { if ($num == 1) { $t = ' mil'; } elseif ($num > 1) { $t .= ' mil'; } } elseif ($num == 1) { $t .= ' ' . $matsub[$sub] . 'on'; } elseif ($num > 1) { $t .= ' ' . $matsub[$sub] . 'ones'; } if ($num == '000') $mils++; elseif ($mils != 0) { if (isset($matmil[$sub])) $t .= ' ' . $matmil[$sub]; $mils = 0; } $neutro = true; $tex = $t . $tex; } $tex = $neg . substr($tex, 1) . $fin; if ($moneda == 'COP') { if ($float[1] != '' && $float[1] > 0) $end_num = strtoupper($tex) . ' PESOS ' . (string)$float[1] . '/100'; else $end_num = strtoupper($tex) . ' PESOS M/CTE'; } elseif ($moneda == 'USD') { $end_num = strtoupper($tex) . ' DOLARES CON ' . $float[1] . ' CENTAVOS'; } } return $end_num; } /** * @function num3letras () * @abstract Dado un número lo devuelve escrito en letras en español y los centavos en letras * @param $num number - Número a convertir (máximo dos decimales) y el número no debe tener seprador de miles * @param $fem bool - Forma femenina (true) o no (false). * @param $dec bool - Con decimales (true) o no (false). * @param string $moneda Por defecto es Pesos Colombianos * @result string - Devuelve el n?mero escrito en letra. * @return string */ public static function num3letras($num, $fem = false, $dec = true, $moneda = 'COP') { $matuni[1] = "UNO"; $matuni[2] = "DOS"; $matuni[3] = "TRES"; $matuni[4] = "CUATRO"; $matuni[5] = "CINCO"; $matuni[6] = "SEIS"; $matuni[7] = "SIETE"; $matuni[8] = "OCHO"; $matuni[9] = "NUEVE"; $matuni[10] = "DIEZ"; $matuni[11] = "ONCE"; $matuni[12] = "DOCE"; $matuni[13] = "TRECE"; $matuni[14] = "CATORCE"; $matuni[15] = "QUINCE"; $matuni[16] = "DIECISEIS"; $matuni[17] = "DIECISIETE"; $matuni[18] = "DIECIOCHO"; $matuni[19] = "DIECINUEVE"; $matuni[20] = "VEINTE"; $matunisub[2] = "DOS"; $matunisub[3] = "TRES"; $matunisub[4] = "CUATRO"; $matunisub[5] = "QUIN"; $matunisub[6] = "SEIS"; $matunisub[7] = "SETE"; $matunisub[8] = "OCHO"; $matunisub[9] = "NOVE"; $matdec[2] = "VEINT"; $matdec[3] = "TREINTA"; $matdec[4] = "CUARENTA"; $matdec[5] = "CINCUENTA"; $matdec[6] = "SESENTA"; $matdec[7] = "SETENTA"; $matdec[8] = "OCHENTA"; $matdec[9] = "NOVENTA"; $matsub[3] = 'MILL'; $matsub[5] = 'BILL'; $matsub[7] = 'MILL'; $matsub[9] = 'TRILL'; $matsub[11] = 'MILL'; $matsub[13] = 'BILL'; $matsub[15] = 'MILL'; $matmil[4] = 'MILLONES'; $matmil[6] = 'BILLONES'; $matmil[7] = 'DE BILLONES'; $matmil[8] = 'MILLONES DE BILLONES'; $matmil[10] = 'TRILLONES'; $matmil[11] = 'DE TRILLONES'; $matmil[12] = 'MILLONES DE TRILLONES'; $matmil[13] = 'DE TRILLONES'; $matmil[14] = 'BILLONES DE TRILLONES'; $matmil[15] = 'DE BILLONES DE TRILLONES'; $matmil[16] = 'MILLONES DE BILLONES DE TRILLONES'; if ($num == "0.00" && $moneda == 'COP') { $end_num = ' CERO PESOS M/CTE'; } elseif ($num == "0.00" && $moneda == 'USD') { $end_num = ' CERO DOLARES CON CERO CENTAVOS'; } else { //Zi hack $float = explode('.', $num); $num = $float[0]; if (count($float) == 1) { $float[1] = 0; } $num = trim((string)@$num); if ($num[0] == '-') { $neg = 'menos '; $num = substr($num, 1); } else { $neg = ''; } if(strlen($num) > 1) $num = ltrim($num, '0'); if ($num[0] < '1' or $num[0] > 9) $num = '0' . $num; $zeros = true; $punt = false; $ent = ''; $fra = ''; for ($c = 0; $c < strlen($num); $c++) { $n = $num[$c]; if (!(strpos(".,'''", $n) === false)) { if ($punt) break; else { $punt = true; continue; } } elseif (!(strpos('0123456789', $n) === false)) { if ($punt) { if ($n != '0') $zeros = false; $fra .= $n; } else $ent .= $n; } else break; } $ent = ' ' . $ent; if ($dec and $fra and !$zeros) { $fin = ' coma'; for ($n = 0; $n < strlen($fra); $n++) { if (($s = $fra[$n]) == '0') $fin .= ' cero'; elseif ($s == '1') $fin .= $fem ? ' una' : ' un'; else $fin .= ' ' . $matuni[$s]; } } else $fin = ''; $tex = ''; $sub = 0; $mils = 0; $neutro = false; if ((int)$ent === 0) $tex = ' Cero'; while (($num = substr($ent, -3)) != ' ') { $ent = substr($ent, 0, -3); if (++$sub < 3 and $fem) { $matuni[1] = 'una'; $subcent = 'as'; } else { $matuni[1] = $neutro ? 'un' : 'uno'; $subcent = 'os'; } $t = ''; $n2 = substr($num, 1); if ($n2 == '00') { // } elseif ($n2 < 21) $t = ' ' . $matuni[(int)$n2]; elseif ($n2 < 30) { $n3 = $num[2]; if ($n3 != 0) $t = 'i' . $matuni[$n3]; $n2 = $num[1]; $t = ' ' . $matdec[$n2] . $t; } else { $n3 = $num[2]; if ($n3 != 0) $t = ' y ' . $matuni[$n3]; $n2 = $num[1]; $t = ' ' . $matdec[$n2] . $t; } $n = $num[0]; if ($n == 1) { // $t = ' ciento' . $t; if (substr($num, 1) == "00") { $t = ' cien' . $t; } else { $t = ' ciento' . $t; } } elseif ($n == 5) { $t = ' ' . $matunisub[$n] . 'ient' . $subcent . $t; } elseif ($n != 0) { $t = ' ' . $matunisub[$n] . 'cient' . $subcent . $t; } if ($sub == 1) { } elseif (!isset($matsub[$sub])) { if ($num == 1) { $t = ' mil'; } elseif ($num > 1) { $t .= ' mil'; } } elseif ($num == 1) { $t .= ' ' . $matsub[$sub] . 'on'; } elseif ($num > 1) { $t .= ' ' . $matsub[$sub] . 'ones'; } if ($num == '000') $mils++; elseif ($mils != 0) { if (isset($matmil[$sub])) $t .= ' ' . $matmil[$sub]; $mils = 0; } $neutro = true; $tex = $t . $tex; } $tex = $neg . substr($tex, 1) . $fin; $texto_moneda = ($moneda == 'COP') ? "PESOS" : (($moneda == 'USD') ? "DOLARES" : ""); if ($float[1] != '' && $float[1] > 0) { if ((int)$float[1] <= 20) { $end_num = strtoupper($tex) . ' ' . $texto_moneda . ' CON ' . $matuni[(int)$float[1]] . ' CENTAVOS'; } else { $cen_dec = substr($float[1], 0, 1); $cen_uni = substr($float[1], 1, 1); if ($cen_uni > 0) { if ((int)$float[1] <= 30) { $end_num = strtoupper($tex) . ' ' . $texto_moneda . ' CON ' . $matdec[(int)$cen_dec] . 'I' . $matuni[(int)$cen_uni] . ' CENTAVOS'; } else { $end_num = strtoupper($tex) . ' ' . $texto_moneda . ' CON ' . $matdec[(int)$cen_dec] . ' Y ' . $matuni[(int)$cen_uni] . ' CENTAVOS'; } } else { $end_num = strtoupper($tex) . ' ' . $texto_moneda . ' CON ' . $matdec[(int)$cen_dec] . ' CENTAVOS'; } } } else $end_num = strtoupper($tex) . ' ' . $texto_moneda . ' M/CTE'; } return $end_num; } }
import 'package:cinemapedia/domain/entities/movie.dart'; abstract class MoviesDatasource { Future<Movie> getMovieById(String id); Future<List<Movie>> getNowPlaying({int page = 1}); Future<List<Movie>> getPopular({int page = 1}); Future<List<Movie>> getTopRate({int page = 1}); Future<List<Movie>> getUpcoming({int page = 1}); }
const express = require('express'); const fs = require('fs'); const moment = require('moment-timezone'); const cache = require('./cache'); // cache.js 모듈 불러오기 const cors = require('cors'); const { SERVER_URL } = require('./config'); // config.js에서 SERVER_URL을 가져옵니다 const createServer = (port, targetLang) => { const app = express(); const allowedOrigins = [`http://${SERVER_URL}:5173`]; app.use(cors({ origin: allowedOrigins, methods: ['GET'] })); app.get('/', async (req, res) => { try { const cacheKey = targetLang === 'en' ? 'formattedData' : `formattedData-${targetLang}`; const cachedData = cache.translationCache.get(cacheKey); if (cachedData) { console.log('Data found in cache'); res.json(cachedData); // 캐시에서 데이터를 클라이언트에 전송 return; } // schedule.json 파일에서 데이터를 읽어옴 const data = JSON.parse(fs.readFileSync('../data.gg/schedule.json', 'utf8')); const matches = data.match; const formattedData = await Promise.all(matches.map(async (match) => { const dateTime = match.matchInfo.date + 'T' + match.matchInfo.time; const koreaTime = moment.utc(dateTime.replace('Z', '')).tz('Asia/Seoul'); const homeTeamName = targetLang !== 'en' ? await cache.translateText(match.matchInfo.contestant[0].name, targetLang) : match.matchInfo.contestant[0].name; const awayTeamName = targetLang !== 'en' ? await cache.translateText(match.matchInfo.contestant[1].name, targetLang) : match.matchInfo.contestant[1].name; const homeTeamId = match.matchInfo.contestant[0].id; const awayTeamId = match.matchInfo.contestant[1].id; const venueName = match.matchInfo.venue.shortName; const goals = match.liveData.goal; return { ID: match.matchInfo.id, Date: koreaTime.format('YYYY-MM-DD'), Time: koreaTime.format('HH:mm:ss'), Team: [ { position: 'home', name: homeTeamName, id: homeTeamId }, { position: 'away', name: awayTeamName, id: awayTeamId } ], Result: match.liveData.matchDetails.scores ? match.liveData.matchDetails.scores.total : "예정", Round: match.matchInfo.week, Place: venueName, goal: goals }; })); // 포맷팅된 데이터를 캐시에 저장 cache.translationCache.set(cacheKey, formattedData); // 클라이언트에 JSON 형태로 데이터를 보냄 res.json(formattedData); } catch (error) { console.error('Failed to load data from schedule.json:', error); res.status(500).json({ error: '데이터를 불러오는데 실패했습니다.' }); } }); app.listen(port, () => { console.log(`서버가 http://${SERVER_URL}:${port}/ 에서 실행 중입니다.`); }); }; // 영어 서버 실행 createServer(4401, 'en'); // 한국어 서버 실행 createServer(8201, 'ko'); // 일본어 서버 실행 createServer(8101, 'ja');
<!doctype html> <html lang="ja"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> <!-- material icons CDN --> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <title>サイト作成 練習</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="mainNav"> <a class="navbar-brand" href="#"><img src="img/navbar-logo.svg" alt=""></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">MENU <span class="material-icons">menu</span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto mr-3"> <li class="nav-item"> <a class="nav-link" href="#">Top</a> </li> <li class="nav-item"> <a class="nav-link" href="#contents">Contents</a> </li> <li class="nav-item"> <a class="nav-link" href="#target">Map</a> </li> <li class="nav-item"> <a class="nav-link" href="#contact">Contact</a> </li> </ul> </div> </nav> <header class="masthead"> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="img/bg-1.jpg" alt="背景1"> <div class="bg-text"> <h1>Welome To Our Site</h1> </div> </div> <div class="carousel-item"> <img class="d-block w-100" src="img/bg-2.jpg" alt="背景2"> <div class="bg-text"> <h1>Welome To Our Site</h1> </div> </div> <div class="carousel-item"> <img class="d-block w-100" src="img/bg-3.jpg" alt="背景3"> <div class="bg-text"> <h1>Welome To Our Site</h1> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> </header> <div class="container" id="contents"> <div class="curry-menu"> <div class="row no-gutters"> <div class="col-lg-4"> <img id="curryImg" class="card-img"> <ul class="curryImg thumbnails"></ul> </div> <div class="col-lg-8"> <div class="card-body"> <h4 class="card-title">カスタマンダップ<small>(ネパールカレー)</small></h4> <p class="card-text">「Kasthamandap カスタマンダップ」は北谷町、58号線沿いにあり、那覇からだと車で約30分のドライブで到着です。「カスタマンダップ(Kasthamandap)」とは「木の家」の意味だそうです、店の外観もなんとなく木の感じがします。スパイスレベルは1から5まで選べます、辛さが苦手な方も安心です。<br>イチ押しは<strong>チキンバターカリー</strong>です。 </p> <p class="address">住所:沖縄県中頭郡北谷町北前1-10-10</p> </div> </div> </div> </div> <div class="chicken-menu"> <div class="row no-gutters"> <div class="col-lg-4"> <img id="chickenImg" class="card-img"> <ul class="chickenImg thumbnails"></ul> </div> <div class="col-lg-8"> <div class="card-body"> <h4 class="card-title">cc's chicken&waffles<small>(アメリカ料理)</small></h4> <p class="card-text">チキンとワッフルがワンプレートに乗って運ばれてくるスタイルで、同時に茶色いシロップ(バターシロップ)が乗っているのですが、このシロップをワッフルだけではなくチキンにも付けて食べます。とてもアメリカンな食べ物です。天気のいい日はテイクアウトして店の前の海を眺めながら沖縄らしさも味わえます。<br>イチ押しは<strong>ソーセージマカロニ&チーズ</strong>です。 </p> <p class="address">住所:沖縄県中頭郡北谷町宮城1-68</p> </div> </div> </div> </div> <div class="pizza-menu"> <div class="row no-gutters"> <div class="col-lg-4"> <img id="pizzaImg" class="card-img"> <ul class="pizzaImg thumbnails"></ul> </div> <div class="col-lg-8"> <div class="card-body"> <h4 class="card-title">ピザハウスジュニア<small>(ピッツァ)</small></h4> <p class="card-text">「Kasthamandap カスタマンダップ」は北谷町、58号線沿いにあり、那覇からだと車で約30分のドライブで到着です。「カスタマンダップ(Kasthamandap)」とは「木の家」の意味だそうです、店の外観もなんとなく木の感じがします。スパイスレベルは1から5まで選べます、辛さが苦手な方も安心です。<br>イチ押しは<strong>チキンバターカリー</strong>です。 </p> <p class="address">住所:沖縄県中頭郡北谷町美浜3-5-9</p> </div> </div> </div> </div> </div> <div id="target"> </div> <section class="page-section" id="contact"> <div class="container"> <div class="text-center"> <h2 class="section-heading text-uppercase">Contact Us</h2> <h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3> </div> <form id="contactForm" name="sentMessage" novalidate="novalidate"> <div class="row align-items-stretch mb-5"> <div class="col-md-6"> <div class="form-group"> <input class="form-control" id="name" type="text" placeholder="Your Name *" required="required" data-validation-required-message="Please enter your name." /> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input class="form-control" id="email" type="email" placeholder="Your Email *" required="required" data-validation-required-message="Please enter your email address." /> <p class="help-block text-danger"></p> </div> <div class="form-group mb-md-0"> <input class="form-control" id="phone" type="tel" placeholder="Your Phone *" required="required" data-validation-required-message="Please enter your phone number." /> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-6"> <div class="form-group form-group-textarea mb-md-0"> <textarea class="form-control" id="message" placeholder="Your Message *" required="required" data-validation-required-message="Please enter a message."></textarea> <p class="help-block text-danger"></p> </div> </div> </div> <div class="text-center"> <div id="success"></div> <button class="btn btn-primary btn-xl text-uppercase" id="sendMessageButton" type="submit">Send Message</button> </div> </form> </div> </section> <footer class="container"> <p class="Copyright">Copyright &copy; by Leo & Ou</p> </footer> </main> </body> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <!-- google Map key --> <script src="https://maps.googleapis.com/maps/api/js?language=ja&region=JP&key=AIzaSyADpkw6KlTl1xqjqwS7olR-W4H5C9X_sEk&callback=initMap" async defer></script> <script src="js/main.js"></script> </body> </html>
// // AsyncCoverImage.swift // BookStoreApp // // Created by Alex on 09.12.2023. // import SwiftUI struct AsyncCoverImage: View { let url: URL let cornerRadius: CGFloat init(url: URL, cornerRadius: CGFloat = 0) { self.url = url self.cornerRadius = cornerRadius } var body: some View { AsyncImage(url: url) { phase in if let image = phase.image { image .resizable() .scaledToFill() .clipShape(.rect(cornerRadius: cornerRadius)) } else if phase.error != nil { Image(systemName: "xmark.circle") .resizable() .frame(width: 50, height: 50) .foregroundStyle(.secondary) Text("Image loading error.") .font(.caption) .foregroundStyle(.secondary) } else { ProgressView() } } } } //#Preview { // AsyncCoverImage(url: MockBook.getBook().coverImageURL) //}
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:mailer/mailer.dart'; import 'package:mailer/smtp_server.dart'; import 'package:shared_preferences/shared_preferences.dart'; class IdeaDetailsPage extends StatefulWidget { final String description; final String ideaName; final String partners; final String problemStatement; final String theme; final String userUUID; final String uuid; IdeaDetailsPage({ required this.description, required this.ideaName, required this.partners, required this.problemStatement, required this.theme, required this.userUUID, required this.uuid, }); @override State<IdeaDetailsPage> createState() => _IdeaDetailsPageState(); } class _IdeaDetailsPageState extends State<IdeaDetailsPage> { late Future<String?> _roleFuture; @override void initState() { super.initState(); _roleFuture = getRole(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Idea Details'), ), body: FutureBuilder<String?>( future: _roleFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { // Show a loading indicator while waiting for the role return Center(child: CircularProgressIndicator()); } else if (snapshot.hasError) { // Show an error message if role retrieval fails return Center(child: Text('Error: ${snapshot.error}')); } else { final role = snapshot.data; // Build the UI based on the role return buildContent(role); } }, ), ); } Widget buildContent(String? role) { return Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text( 'Idea Name:', style: TextStyle(fontWeight: FontWeight.bold), ), Text(widget.ideaName), const SizedBox(height: 16.0), const Text( 'Theme:', style: TextStyle(fontWeight: FontWeight.bold), ), Text(widget.theme), const SizedBox(height: 16.0), const Text( 'Partners:', style: TextStyle(fontWeight: FontWeight.bold), ), Text(widget.partners), const SizedBox(height: 16.0), const Text( 'Problem Statement:', style: TextStyle(fontWeight: FontWeight.bold), ), Text(widget.problemStatement), const SizedBox(height: 16.0), const Text( 'Description:', style: TextStyle(fontWeight: FontWeight.bold), ), Text(widget.description), const SizedBox(height: 16.0), const SizedBox( height: 10, ), if (role == 'Investor') SizedBox( width: double.infinity, child: ElevatedButton( onPressed: () async { SharedPreferences _prefs = await SharedPreferences.getInstance(); List<String>? userDetails = await _prefs.getStringList('userDetails'); print(userDetails); QuerySnapshot<Map<String, dynamic>> documentSnapshot = await FirebaseFirestore.instance .collection('users') .where('uuid', isEqualTo: widget.userUUID) .get(); List<String> documentIds = documentSnapshot.docs.map((doc) => doc.id).toList(); if (documentIds.isNotEmpty) { print(documentSnapshot.docs[0]['email']); print(documentIds[0]); } else { print('No user found for this idea.'); } debugPrint( "Hello ${documentSnapshot.docs[0]['name']}, Your profile Viewed by ${userDetails![0]} \n For Contact mail to ${userDetails[2]}"); // Future<void> sendEmail() async { final username = '[email protected]'; final password = 'vroaaccameonlxjp'; final smtpServer = gmail(username, password); final message = Message() ..from = Address(username, 'Startup Hub') ..recipients.add(documentSnapshot.docs[0]['email']) ..subject = "Regarding your startup idea listed on startup hub." ..text = "Hello ${documentSnapshot.docs[0]['name']},I hope you are doing great. Mr.${userDetails[0]} has shown intrest in you startup idea. You can contact at ${userDetails[2]} this email for further details. Best of luck for your startup journey."; try { final sendReport = await send(message, smtpServer); print('Message sent: ' + sendReport.toString()); } catch (e) { print('Error occurred while sending email: $e'); } }, style: ElevatedButton.styleFrom( elevation: 5, padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), ), child: const Text('Interested'), ), ), ], ), ); } Future<String?> getRole() async { SharedPreferences _prefs = await SharedPreferences.getInstance(); String? role = await _prefs.getString('profile'); print(role); return role; } }
const express = require("express"); const router = express.Router(); const { User, validateUser } = require("../models/userModel"); const _ = require("lodash"); const bcrypt = require("bcrypt"); const validObjectId = require("../middleware/validObjectId"); router.get("/", async (req, res) => { const users = await User.find({}); if (users.length == 0) return res.status(404).send("No Users found"); res.send(users); }); router.get("/:id", validObjectId, async (req, res) => { const user = await User.findById({ _id: req.params.id }); if (!user) return res.status(404).send("No User found"); }); router.post("/", async (req, res) => { const { error } = validateUser(req.body); if (error) return res.status(400).send(error.details[0].message); let user = await User.findOne({ email: req.body.email }); if (user) return res.status(400).send(" Email id Already Exist"); user = new User({ name: req.body.name, email: req.body.email, password: req.body.password, isAdmin: req.body.isAdmin, }); const salt = await bcrypt.genSalt(10); user.password = await bcrypt.hash(user.password, salt); await user.save(); res.send(_.pick(user, ["_id", "name", "email", "isAdmin"])); }); router.put("/:id", validObjectId, async (req, res) => { const user = await User.findByIdAndUpdate( req.params.id, { $set: { name: req.body.name, password: req.body.password, email: req.body.email, isAdmin: req.body.isAdmin, }, }, { new: true } ); if (!user) { return res.status(404).send("User not found"); } else { res.send(user); } }); router.delete("/:id", validObjectId, async (req, res) => { const user = await User.findByIdAndDelete(req.params.id); if (!user) return res.status(404).send("User not found"); res.send(user); }); module.exports = router;
import "package:easy_localization/easy_localization.dart"; import "package:euterpe/blocs/blocs.dart"; import "package:euterpe/main.dart"; import "package:euterpe/res/res.dart"; import "package:euterpe/services/store.dart"; import "package:euterpe/utils/utils.dart"; import "package:euterpe/views/home_page.dart"; import "package:flutter/material.dart"; import "package:flutter/services.dart"; import "package:flutter_bloc/flutter_bloc.dart"; class EuterpeApp extends StatefulWidget { EuterpeApp({Key? key}) : super(key: key); @override _EuterpeAppState createState() => _EuterpeAppState(); } class _EuterpeAppState extends State<EuterpeApp> with WidgetsBindingObserver { @override void initState() { super.initState(); WidgetsBinding.instance!.addObserver(this); } @override void dispose() { WidgetsBinding.instance!.removeObserver(this); super.dispose(); } @override void didChangeLocales(List<Locale>? locales) { context.setLocale(getLocale()); super.didChangeLocales(locales); } @override Widget build(BuildContext context) => BlocBuilder<ThemeBloc, ThemeState>( builder: (context, themeState) => MaterialApp( onGenerateTitle: (context) => "${ResStrings.appName.tr()} ${ResStrings.textRecorder.tr()}", theme: lightTheme, darkTheme: ThemeData( brightness: Brightness.dark, primaryColor: const ResColors(Store.themeValueDark).primaryColor, accentColor: const ResColors(Store.themeValueDark).accentColor, disabledColor: const ResColors(Store.themeValueDark).disabledColor, highlightColor: Colors.transparent, textSelectionTheme: TextSelectionThemeData( cursorColor: const ResColors(Store.themeValueDark).accentColor, selectionColor: const ResColors(Store.themeValueDark) .accentColor .withOpacity(0.5), selectionHandleColor: const ResColors(Store.themeValueDark).accentColor, ), textTheme: TextTheme( headline1: TextStyle( color: const ResColors(Store.themeValueDark).accentColor, fontSize: ResDimens.largeTitleFontSize, fontWeight: FontWeight.w700, ), subtitle2: TextStyle( color: const ResColors(Store.themeValueDark).colorOnSecondary, fontSize: ResDimens.smallTitleFontSize, fontWeight: FontWeight.w700, ), headline4: TextStyle( color: Colors.white, fontSize: ResDimens.subtitleFontSize, fontWeight: FontWeight.w400, ), headline3: TextStyle( color: Colors.white, fontSize: ResDimens.mediumTitleFontSize, fontWeight: FontWeight.w700, ), bodyText2: TextStyle( color: const ResColors(Store.themeValueDark).subtextColor, fontSize: ResDimens.subtextFontSize, fontWeight: FontWeight.w400, ), bodyText1: TextStyle( color: const ResColors(Store.themeValueDark).textColor, fontSize: ResDimens.textFontSize, fontWeight: FontWeight.w500, ), ), fontFamily: "MontserratAlternates", ), themeMode: themeState.themeMode, supportedLocales: context.supportedLocales, localizationsDelegates: context.localizationDelegates, locale: context.locale, debugShowCheckedModeBanner: false, home: EuterpeHomePage(), builder: (context, child) => MediaQuery( child: child!, data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), ), )); }
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:twitterapp/auth/services/tweetRepository.dart'; import 'package:twitterapp/screens/tweetScreen.dart'; import 'package:twitterapp/auth/tweet.dart'; class homeScreen extends StatefulWidget { const homeScreen({Key? key}) : super(key: key); @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<homeScreen> { final FirebaseFirestore firestore = FirebaseFirestore.instance; final FirebaseStorage firestorage = FirebaseStorage.instance; List<Tweet> tweets = []; @override void initState() { loadTweets(); super.initState(); } Future<void> loadTweets() async { TweetRepository tweetRepository = TweetRepository(firestore: firestore, firestorage: firestorage); List<Tweet>? loadedTweets = await tweetRepository.getAllTweets(); if (loadedTweets != null) { setState(() { tweets = loadedTweets; }); } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Colors.white, elevation: 0, title: SizedBox( height: 25, child: Image.asset( 'assets/images/logo.png', fit: BoxFit.contain, ), ), centerTitle: true, leading: Builder( builder: (BuildContext context) { return IconButton( icon: const Icon(Icons.menu, color: Colors.blue), onPressed: () { Scaffold.of(context).openDrawer(); }, ); }, ), actions: [ IconButton( icon: const Icon(Icons.star, color: Colors.blue), onPressed: () {}, ), ], ), drawer: Drawer( child: ListView( padding: EdgeInsets.zero, children: <Widget>[ const UserAccountsDrawerHeader( accountName: Text(''), accountEmail: Text(''), currentAccountPicture: CircleAvatar( child: Icon(Icons.account_circle), ), decoration: BoxDecoration( color: Colors.blue, ), ), ListTile( leading: Icon(Icons.people), title: Text('Following'), onTap: () {}, ), ListTile( leading: Icon(Icons.people_outline), title: Text('Followers'), onTap: () {}, ), ListTile( leading: Icon(Icons.list), title: Text('Lists'), onTap: () {}, ), ], ), ), body: ListView( padding: const EdgeInsets.symmetric(vertical: 10), children: [ _buildSectionTitle(''), SizedBox( height: 80, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: 10, itemBuilder: (context, index) { return const Padding( padding: EdgeInsets.all(8.0), child: CircleAvatar( radius: 25, backgroundColor: Colors.blue, ), ); }, ), ), ...tweets.map((tweet) => _buildTweetWidget(tweet)).toList(), ], ), floatingActionButton: FloatingActionButton( onPressed: () async { final newTweet = await Navigator.push( context, MaterialPageRoute(builder: (context) => const tweetScreen()), ); if (newTweet != null && newTweet is Tweet) { setState(() { tweets.add(newTweet); }); } }, foregroundColor: Colors.white, backgroundColor: Colors.blue, child: const Icon(Icons.add), ), bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: '', ), BottomNavigationBarItem( icon: Icon(Icons.search), label: '', ), BottomNavigationBarItem( icon: Icon(Icons.notifications), label: '', ), BottomNavigationBarItem( icon: Icon(Icons.mail_outline), label: '', ), ], selectedItemColor: Colors.blue, unselectedItemColor: Colors.grey, showUnselectedLabels: true, ), ); } String getUsername() { User? user = FirebaseAuth.instance.currentUser; return (user?.displayName ?? 'DefaultUsername'); } String getEmail() { User? user = FirebaseAuth.instance.currentUser; return (user?.email ?? 'DefaultUsername'); } Widget _buildSectionTitle(String title) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: Text( title, style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), ); } Widget _buildTweetWidget(Tweet tweet) { return Container( padding: const EdgeInsets.all(12.0), margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(12.0), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ const CircleAvatar( backgroundColor: Colors.blue, radius: 20, ), const SizedBox(width: 12), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( tweet.userName, style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 16, ), ), Text( tweet.userHandle, style: TextStyle( color: Colors.grey, ), ), ], ), ], ), const SizedBox(height: 12), Text( tweet.tweetContent, style: TextStyle(fontSize: 16), ), const SizedBox(height: 12), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( icon: const Icon(Icons.repeat, color: Colors.grey), onPressed: () {}, ), IconButton( icon: const Icon(Icons.favorite_border, color: Colors.grey), onPressed: () {}, ), IconButton( icon: const Icon(Icons.share, color: Colors.grey), onPressed: () {}, ), ], ), ], ), ); } }
package com.zelda.hackernewsandroid import okhttp3.OkHttpClient import okhttp3.Request import org.jsoup.Jsoup import java.io.IOException object ContentExtractor { private val client = OkHttpClient() fun fetchContent(url: String?): String { val request = Request.Builder() .url(url.toString()) .build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) throw IOException("Failed to download content: $url") // later to handler error: java.io.IOException: Failed to download content: https://twitter.com/Bertrand_Meyer/status/1742613897675178347 val htmlContent = response.body?.string() ?: "" return extractTextFromHtml(htmlContent) } } private fun extractTextFromHtml(html: String): String { val document = Jsoup.parse(html) return document.text() // extracts all the text from the HTML for now } }
<?php /** * Camps class for managing camp data. */ class Camps { /** * @var array An array to store camp data. */ public $campData = []; /** * @var array An array to store validation errors. */ public $errors = []; /** * @var string $_GET to filter the posts by the term */ public $termFilter = null; /** * Set camp data based on the given postcode and maximum distance. * * @param string|null $givenPostcode The postcode for filtering or null for no filtering. * @param float|null $maxDistance The maximum distance for filtering or null for no filtering. */ public function setCampData(?string $givenPostcode, ?float $maxDistance): void { $errors = $this->validate($givenPostcode); $this->termFilter = $_GET['term'] ?? null; if (count($errors)) { $this->errors = $errors; return; } $campData = $this->fetchPosts(); if (!$givenPostcode) { $this->campData = $campData; return; } $givenCoordinates = $this->fetchPostcodeLocationData($givenPostcode); if (!$givenCoordinates) { $this->errors = ['postcode' => 'Please provide a valid postcode']; return; } $transformed = $this->transform($campData, $givenCoordinates, $maxDistance); $this->campData = $this->filter($transformed, $maxDistance); } private function filter(array $campData, $maxDistance): array { $filteredByDistance = $maxDistance ? array_filter($campData, fn ($item) => $item['distance'] <= $maxDistance) : $campData; usort($filteredByDistance, fn ($a, $b) => ($a['distance'] ?? null) <=> ($b['distance'] ?? null)); if (!$this->termFilter) return $filteredByDistance; return array_filter($filteredByDistance, function ($camp) { $filteredTerms = array_filter($camp['opening_months'] ?? [], function ($term) { return in_array(strtolower($term), $this->termFilter); }); return !!$filteredTerms; }); } private function transform(array $campData, $givenCoordinates, $maxDistance): array { $transformed = []; foreach ($campData as $item) { if (!($item['latitude'] ?? null) || !($item['longitude'] ?? null)) continue; $coordinates = [ 'latitude' => $item['latitude'], 'longitude' => $item['longitude'], ]; $item['distance'] = $this->calculateHaversineDistance($givenCoordinates, $coordinates); $transformed[] = $item; } return $transformed; } /** * Validate a UK postcode. * * @param string $postcode The postcode to validate. * * @return array An array of validation errors. */ private function validate(string|null $postcode): array { $errors = []; if ($postcode && !$this->validateUKPostcode($postcode)) { $errors['postcode'] = 'Please provide a valid UK postcode'; } return $errors; } /** * Fetch camp data from a data source. * * @return array An array of camp data. */ private function fetchPosts(): array { $args = [ 'post_type' => 'camps', 'posts_per_page' => -1, ]; $query = new WP_Query($args); $campData = []; if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); $fields = get_fields(); if ($fields) { $campData[] = $fields; } } wp_reset_postdata(); } return $campData; } /** * Calculate the great-circle distance between two points on the Earth's surface using the Haversine formula. * * @param array $coord1 An associative array containing latitude and longitude of the first point. * @param array $coord2 An associative array containing latitude and longitude of the second point. * * @return float The calculated distance in miles. */ private function calculateHaversineDistance(array $coord1, array $coord2): float { $earthRadiusMiles = 3959; // Earth's radius in miles (mean value) $lat1 = deg2rad($coord1['latitude']); $lon1 = deg2rad($coord1['longitude']); $lat2 = deg2rad($coord2['latitude']); $lon2 = deg2rad($coord2['longitude']); $dlat = $lat2 - $lat1; $dlon = $lon2 - $lon1; $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2); $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); $distance = $earthRadiusMiles * $c; // Distance in miles return $distance; } /** * Fetch coordinates for a given postcode. * * @param string $postcode The postcode to fetch coordinates for. * * @return array|null An associative array containing latitude and longitude, or null if coordinates cannot be retrieved. */ private function fetchPostcodeLocationData(string $postcode): ?array { $url = "https://api.postcodes.io/postcodes/$postcode"; $response = wp_safe_remote_get($url); if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) return null; $data = json_decode(wp_remote_retrieve_body($response), true); if (!isset($data['result'])) return null; $locationData = $data['result']; if (!$locationData) return null; return [ 'latitude' => $locationData['latitude'], 'longitude' => $locationData['longitude'], ]; } function validateUKPostcode($postcode) { // Remove any whitespace from the input string $postcode = preg_replace('/\s+/', '', $postcode); // Define the regex pattern for UK postcodes $pattern = '/^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKPS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$/i'; // Use preg_match to check if the postcode matches the pattern if (preg_match($pattern, $postcode)) { return true; // Valid UK postcode } else { return false; // Invalid UK postcode } } }
import { Connection, PublicKey, clusterApiUrl } from "@solana/web3.js"; import { getKeypairFromEnvironment } from "@solana-developers/helpers"; import { getOrCreateAssociatedTokenAccount } from "@solana/spl-token"; require('dotenv').config(); const keypair = getKeypairFromEnvironment("SECRET_KEY"); // npx esrun .\04_token_program_spl\04_getOrCreateAssociatedTokenAccount.ts const connection = new Connection(clusterApiUrl("devnet")); const mintAccountPubKey = "6Ry6TFKLnXVw55iRLvMmzsjtZb9jGoKEn48ybcUpWMBE"; const mint = new PublicKey(mintAccountPubKey); /* You can also use getOrCreateAssociatedTokenAccount to get the Token Account associated with a given address or create it if it doesn't exist. For example, if you were writing code to airdrop tokens to a given user, you'd likely use this function to ensure that the token account associated with the given user gets created if it doesn't already exist. */ const associatedTokenAccount = await getOrCreateAssociatedTokenAccount( connection, keypair, // Signer/Payer mint, // Mint: the token mint that the new token account is associated with keypair.publicKey, // Owner: the account of the owner of the new token account ); console.log(associatedTokenAccount); console.log(`ATA Address: ${associatedTokenAccount.address}`); console.log(`Owner Address: ${associatedTokenAccount.owner}`); console.log(`Mint Address: ${associatedTokenAccount.mint}`); console.log(`Amount: ${associatedTokenAccount.amount}\n`); console.log(`getOrCreateAssociatedTokenAccount: '${associatedTokenAccount.address}'`); console.log(`getOrCreateAssociatedTokenAccount: https://explorer.solana.com/address/${associatedTokenAccount.address}?cluster=devnet`);
<?php namespace App; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Http; class ZoomOAuthHelper { public static function getAccessToken() { $clientId = config('services.zoom.client_id'); $clientSecret = config('services.zoom.client_secret'); $accountId = config('services.zoom.account_id'); \Log::info('ZOOM client_id -->' . $clientId); \Log::info('ZOOM clientSecret -->' . $clientSecret); \Log::info('ZOOM accountId -->' . $accountId); $response = Http::withBasicAuth($clientId, $clientSecret) ->asForm() ->post('https://zoom.us/oauth/token', [ 'grant_type' => 'account_credentials', 'account_id' => $accountId, ]); if ($response->successful()) { $tokenResponse = $response->json(); // Handle the token response as needed return $tokenResponse; } else { // Log and handle errors $errorResponse = $response->json(); // Log the error message and code Log::error('Zoom OAuth Error: ' . $errorResponse['error']); Log::error('Zoom OAuth Error Description: ' . $errorResponse['error_description']); // Handle the error in an appropriate way (e.g., return an error response). return $errorResponse; } } }
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:rent_cruise/controller/card_screeen/card_screen_controller.dart'; import 'package:rent_cruise/controller/checkout_controller/checkout_controller.dart'; import 'package:rent_cruise/controller/product_details_provider/details_screen_controller.dart'; import 'package:rent_cruise/database/db.dart'; import 'package:rent_cruise/model/checkout_card_model/checkout_card_model.dart'; import 'package:rent_cruise/utils/color_constant.dart/color_constant.dart'; import 'package:rent_cruise/view/checkout_screen/checkout_screen.dart'; import 'package:top_snackbar_flutter/custom_snack_bar.dart'; import 'package:top_snackbar_flutter/top_snack_bar.dart'; import 'package:url_launcher/url_launcher.dart'; class ProductDetailsScreen extends StatefulWidget { final int index; final int categoryIndex; final bool isDirecthome; ProductDetailsScreen( {Key? key, required this.index, required this.categoryIndex, required this.isDirecthome}) : super(key: key); @override State<ProductDetailsScreen> createState() => _ProductDetailsScreenState(); } class _ProductDetailsScreenState extends State<ProductDetailsScreen> { @override Widget build(BuildContext context) { final checkoutController = Provider.of<CheckoutController>(context); final cardController = Provider.of<CardScreenController>(context); final detailController = Provider.of<ProductDetailsController>(context); final product = Database.random[widget.index]; final ctProducts = Database.categories[widget.categoryIndex]["details"][widget.index]; return SafeArea( child: Scaffold( body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Stack( children: [ Container( height: 300, width: double.infinity, child: Image.asset( widget.isDirecthome ? product.imgMain : ctProducts.imgMain, fit: BoxFit.cover, ), ), Positioned( left: 20, top: 15, child: GestureDetector( onTap: () { Navigator.of(context).pop(); }, child: CircleAvatar( radius: 20, child: Center( child: Icon( Icons.arrow_back, size: 20, color: Colors.white, ), ), backgroundColor: ColorConstant.primaryColor, ), ), ), Positioned( right: 30, top: 15, child: GestureDetector( onTap: () { detailController.totalPriceCalc(widget.index); print("cliced"); Provider.of<CardScreenController>(context, listen: false) .addProductToCart( index: widget.index, id: widget.isDirecthome ? product.id.toString() : ctProducts.id.toString(), isDirectHome: widget.isDirecthome, context: context, price: widget.isDirecthome ? product.price.toString() : ctProducts.price.toString(), selectedDays: detailController.totalDays.toString(), totalPrice: detailController.totalPrice.toString(), categoryIndex: widget.categoryIndex); Provider.of<CardScreenController>(context, listen: false) .exist ? 0 : Provider.of<CardScreenController>(context, listen: false) .calculateAllProductPrice(); }, child: Stack( children: [ CircleAvatar( radius: 20, child: Center( child: Icon(Icons.shopping_cart, size: 20, color: Colors.white), ), backgroundColor: ColorConstant.primaryColor, ), Positioned( right: 0, child: Container( width: 18, height: 18, decoration: BoxDecoration( color: const Color.fromRGBO(244, 67, 54, 1), shape: BoxShape.circle), child: Center( child: Text( cardController.cardlist.length.toString(), style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold), )), ), ) ], ), ), ), Positioned( right: 80, top: 15, child: GestureDetector( onTap: () { showTopSnackBar( animationDuration: Duration(seconds: 1), displayDuration: Duration(milliseconds: 2), Overlay.of(context), CustomSnackBar.success( message: " Product saved", )); }, child: CircleAvatar( radius: 20, child: Icon( Icons.favorite_border, size: 20, color: Colors.white, ), backgroundColor: ColorConstant.primaryColor, ), ), ), ], ), SizedBox( height: 15, ), Padding( padding: const EdgeInsets.all(9.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ SizedBox( width: MediaQuery.of(context).size.width * 0.8, child: Text( widget.isDirecthome ? product.productName : ctProducts.productName, style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: Colors.black, ), overflow: TextOverflow.ellipsis, ), ), Padding( padding: const EdgeInsets.only(right: 10), child: Row( children: [ Icon( Icons.star, size: 23, color: Colors.amber, ), Text( widget.isDirecthome ? product.rating : ctProducts.rating, style: TextStyle( color: Colors.black, fontSize: 18, fontWeight: FontWeight.bold), ) ], ), ), ], ), ), Padding( padding: const EdgeInsets.all(9.0), child: Text( widget.isDirecthome ? product.desc : ctProducts.desc, style: TextStyle(fontSize: 14), textAlign: TextAlign.justify, ), ), Divider( color: Colors.grey, thickness: 0.1, ), ListTile( leading: CircleAvatar( radius: 26, backgroundImage: AssetImage( widget.isDirecthome ? product.profilePic : ctProducts.profilePic, )), title: Text( widget.isDirecthome ? product.profileName : ctProducts.profileName, style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black), ), subtitle: Text( widget.isDirecthome ? product.place : ctProducts.place, style: TextStyle(color: Colors.grey), ), trailing: Container( width: 90, child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ GestureDetector( onTap: () { Provider.of<ProductDetailsController>(context, listen: false) .launchWhatsapp( number: '+916238747202', name: "Hi there, I'm [Your Name]. I'm interested in booking a rental and would appreciate more information about the process, availability, and any requirements. Thank you for your assistance!"); }, child: Container( width: 40, height: 40, decoration: BoxDecoration( color: Colors.grey[300], borderRadius: BorderRadius.circular(10)), child: IconButton( onPressed: () {}, icon: Image.asset("assets/icons/whatsapp.png")), ), ), SizedBox( width: 10, ), Container( width: 40, height: 40, decoration: BoxDecoration( color: Colors.grey[300], borderRadius: BorderRadius.circular(10)), child: IconButton( onPressed: () { final url = Uri.parse('tel:+916238747202'); print(url); launchUrl(url); }, icon: Icon( Icons.call, color: Colors.blue, )), ), ], ), ), ), Divider( color: Colors.grey, thickness: 0.1, ), SizedBox(height: 15), Padding( padding: const EdgeInsets.only(left: 20), child: Text( "Gallery", style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), ), SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Container( width: 80, height: 80, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), ), child: ClipRRect( borderRadius: BorderRadius.circular(13), child: Image.asset( widget.isDirecthome ? product.gallery[0] : ctProducts.gallery[0], fit: BoxFit.cover, ), ), ), Container( width: 80, height: 80, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), ), child: ClipRRect( borderRadius: BorderRadius.circular(13), child: Image.asset( widget.isDirecthome ? product.gallery[1] : ctProducts.gallery[1], fit: BoxFit.cover, ), ), ), Container( width: 80, height: 80, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), ), child: ClipRRect( borderRadius: BorderRadius.circular(13), child: Image.asset( widget.isDirecthome ? product.gallery[2] : ctProducts.gallery[2], fit: BoxFit.cover, ), ), ), Container( width: 80, height: 80, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), image: DecorationImage( image: AssetImage( widget.isDirecthome ? product.gallery[3] : ctProducts.gallery[3], ), fit: BoxFit.cover), color: Colors.grey), child: Center( child: Text( "+1", style: TextStyle(fontSize: 20, color: Colors.white), )), ) ], ), SizedBox( height: 20, ), Padding( padding: const EdgeInsets.only(left: 15, right: 15), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "How long do you want to rent this for?", style: TextStyle(fontWeight: FontWeight.bold), ), Container( width: 90, height: 40, decoration: BoxDecoration( color: Colors.grey[300], borderRadius: BorderRadius.circular(8)), child: Center( child: Text( "${detailController.totalDays} Days", style: TextStyle( fontSize: 15, fontWeight: FontWeight.bold), )), ) ], ), ), SizedBox( height: 30, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: 130, height: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: ColorConstant.primaryColor, ), child: Center( child: DropdownButton<int>( borderRadius: BorderRadius.circular(15), dropdownColor: Colors.black, underline: Text(""), iconEnabledColor: Colors.white, iconSize: 28, value: detailController.selectedNumber, onChanged: (value) { detailController.selectedNumber = value!; detailController.totalDays = Provider.of<ProductDetailsController>(context, listen: false) .calculateTotalDays(); detailController.totalPriceCalc(widget.index); }, items: List.generate(10, (index) { return DropdownMenuItem<int>( value: index + 1, child: Text( (index + 1).toString(), style: TextStyle(color: Colors.white, fontSize: 18), ), ); }), ), ), ), SizedBox( width: 50, ), Container( width: 130, height: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: ColorConstant.primaryColor, ), child: Center( child: DropdownButton<String>( borderRadius: BorderRadius.circular(15), dropdownColor: Colors.black, style: TextStyle(color: Colors.amber), underline: Text(""), iconEnabledColor: Colors.white, iconSize: 28, value: detailController.selectedTimeUnit, onChanged: (value) { detailController.selectedTimeUnit = value!; detailController.totalDays = Provider.of<ProductDetailsController>(context, listen: false) .calculateTotalDays(); detailController.totalPriceCalc(widget.index); }, items: detailController.timeUnits.map((unit) { return DropdownMenuItem<String>( value: unit, child: Text( unit, style: TextStyle(color: Colors.white, fontSize: 18), ), ); }).toList(), ), ), ), ], ), Padding( padding: const EdgeInsets.only(top: 20, left: 15), child: Text( "Total Price: ₹${detailController.totalPrice ?? 0}", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20), ), ), SizedBox( height: 20, ), Padding( padding: const EdgeInsets.only(left: 20, bottom: 5), child: Text( "Location", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), ), GestureDetector( onTap: () { // final url = Uri.parse( 'https://www.google.com/maps/@9.9894452,76.2979403,15z/data=!5m1!1e1?entry=ttu'); print(url); launchUrl(url); }, child: Center( child: Container( margin: EdgeInsets.only(left: 13, right: 13), height: 190, decoration: BoxDecoration( color: Colors.grey, borderRadius: BorderRadius.circular(20)), child: ClipRRect( borderRadius: BorderRadius.circular(20), child: Image.asset("assets/images/map.png")), ), ), ), SizedBox( height: 30, ) ], ), ), bottomNavigationBar: Container( height: 65, decoration: BoxDecoration( color: ColorConstant.primaryColor, borderRadius: BorderRadius.only( topLeft: Radius.circular(15), topRight: Radius.circular(15))), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( widget.isDirecthome ? '₹${product.price} / day' : '${ctProducts.price} / day', style: TextStyle(color: Colors.white, fontSize: 17), ), InkWell( onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => Checkout_screen())); Provider.of<CheckoutController>(context, listen: false) .checkAmmount(detailController.totalPrice!); if (checkoutController.checkoutList .any((e) => e.id == widget.index)) { print('already exist'); ScaffoldMessenger.of(context).showSnackBar(SnackBar( backgroundColor: Colors.orange, content: Text("this item already selected for checkout"))); } else { Provider.of<CheckoutController>(context, listen: false) .addProduct(CheckoutCartModel( id: widget.index.toString(), img: widget.isDirecthome ? product.imgMain : ctProducts.imgMain, name: widget.isDirecthome ? product.productName : ctProducts.productName, totalPrice: detailController.totalPrice.toString(), selectedDays: detailController.totalDays.toString(), perdayprice: Database.random[widget.index].price.toString(), )); } }, child: Container( height: 40, width: 120, child: Padding( padding: const EdgeInsets.all(8.0), child: Center( child: Text( "Rent Now", style: TextStyle(fontWeight: FontWeight.bold), ), ), ), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), ), ), ) ], ), ), ), ); } }
import * as bases from 'bases'; import Long from 'long'; import { gameTypes } from '../types/ClashRoyale'; import { IHiLo } from '../types/common/HiLo'; /** * Helper functions for handling hashtags from the game. */ const characterSet = '0289PYLQGRJCUV'; const characterCount = characterSet.length; /** * Converts Hashtag (player or clantag) to a normalized version without # or common pitfalls * @param hashtag Player- or clantag */ export function normalizeHashtag(hashtag = ''): string { return hashtag?.trim().toUpperCase() .replace('#', '') .replace(/O/g, '0'); // replace capital O with zero } /** * Checks if a hashtag is potentially valid. Hashtags will be normalized before running through the test. * @param hashtag The to be checked hashtag */ export function isValidHashtag(hashtag: string): boolean { // Simple validation first before doing computationally more expensive stuff if (hashtag === undefined || hashtag === null) return false; if (hashtag.length > 14 || hashtag.length < 3) return false; const tagNormalized = normalizeHashtag(hashtag); const tagCharacters = ['0', '2', '8', '9', 'P', 'Y', 'L', 'Q', 'G', 'R', 'J', 'C', 'U', 'V']; for (const char of tagNormalized) { if (tagCharacters.indexOf(char) === -1) return false; } return true; } /** * Player Hashtags consist of high and low ids which are used for a better loadbalancing * on Supercells end. This HiLo algorithm reverses player tags to their hi and lo ids * * @param hashtag Normalized player tag */ export function getHiLoFromHashtag(hashtag: string): IHiLo { let id = 0; hashtag.split('').forEach((char: string) => { const charIndex = characterSet.indexOf(char); if (charIndex === -1) { // Invalid char in playerTag has been used to calculate the HiLo return null; } id = id * characterCount; id += charIndex; }); const hi = id % 256; // tslint:disable-next-line:no-bitwise const lo = (id - hi) >>> 8; return { high: hi, low: lo }; } /** * Returns a player tag (without hashtag) for a given playerid * @param high Player's high bits * @param low Player's low bits */ export function getHashtagFromHiLo(high: number, low: number): string { if (high >= 255) { return ''; } let id: Long = new Long(low, 0, true); // tslint:disable-next-line:no-bitwise id = id.shiftLeft(8); id = id.or(high); const hashTagId = id.toNumber(); let hashtag = ''; // Base14 encode hashtag = bases.toAlphabet(hashTagId, characterSet); return hashtag; } /** * Returns a user friendly game type name for a given gameType id * @param gameType The gametype to be resolved */ export function getGameTypeName(gameType: string): string { return gameTypes[gameType] as string; } export function cardImageURL(cardName: string, gold = false): string { const cardSlug = cardName.toLocaleLowerCase().replaceAll(" ", "-").replaceAll(".", ""); return `/images/${gold ? 'cards-gold' : 'cards'}/${cardSlug}.png`; }
<template> <div> <div v-if="success" class="alert alert-success text-center" role="alert"> {{ message }} </div> <div class="description"> <div class="d-flex gap-5"> <h2 class="card-title-info" v-for="object in post.objects" :key="object.id">{{ object.quantity }}x {{ object.name }}</h2> </div> <p v-if="post.countReservations <= 0" class="text-info">Personne ne s'est encore proposé, soyez le premier !</p> <p v-else class="text-info">{{ post.countReservations }} proposition(s) en cours</p> </div> <div class="row my-2 bg-secondary-light"> <h6 class="card-title-info my-1 mx-2">Details</h6> <div class="my-2"> <div v-for="object in post.objects" :key="object.id"> <div class="fw-bold">{{ object.quantity }}x {{ object.name }}</div> <div>Poids : {{ object.weight }} à {{ object.price }}/kg</div> </div> <div class="d-flex mt-4 gap-5"> <div> <div class="fw-bold">Proposition de tarif</div> <p>{{ totalToPay }} €</p> </div> <div> <div class="fw-bold">Livraison souhaitée</div> <p>{{ post.dateFrom | formatDate }}. - {{ post.dateTo | formatDate }}.</p> </div> </div> <div class="d-flex mt-4 gap-5"> <div class="from"> <div class="title fw-bold">Lieu de départ</div> <p>{{ post.from }}</p> </div> <div class="to"> <div class="title fw-bold">Lieu d'arrivée</div> <p>{{ post.to }}</p> </div> </div> <div class="row"> <label class="fw-bold">Message: </label> <div class="">{{ post.content }}</div> </div> <a class="btn btn-success my-3" @click.prevent="proposition()" v-if="!showProposal">Faire une proposition</a> </div> </div> <div class="row" v-if="showProposal"> <h6 class="card-title-info">Faire ma proposition</h6> <div class="proposal d-flex gap-2 border py-4 my-2"> <input class="border text-end px-2 mx-2" v-model="proposalPrice"> <button class="btn btn-success plus" @click.prevent="decrement()">-</button> <button class="plus btn btn-success" @click.prevent="increment()">+</button> </div> <textarea class="form-control mb-2" type="text" rows="5" v-model="booking.message" placeholder="laisser un message..."></textarea> <a href="#" @click="send()" class="btn btn-success">Me proposer <span v-if="show" class="spinner-grow float-end" role="status"></span></a> </div> </div> </template> <script lang="ts"> import { Vue, Component } from 'vue-property-decorator' import ContactComponent from "../shared/ContactComponent.vue"; import axios from "axios"; import { ValidationProvider, ValidationObserver } from 'vee-validate'; import toast from "vue-toastification"; Vue.use(toast, { transition: "Vue-Toastification__bounce", maxToasts: 20, newestOnTop: true }) @Component({ components: { ContactComponent, ValidationProvider, ValidationObserver}, props: { post: {}, auth: {} } }) export default class Coli extends Vue { proposalPrice: number = 0; error: boolean = false; success: boolean = false; message: String = ''; show: boolean = false; errors: any = []; objects: any = []; showProposal: boolean = false; booking: any = { message: '', objects: {}, bookedObjects: {}, price: '', kilo: '', travel: '' } increment() { this.proposalPrice++ } decrement() { if (this.proposalPrice > 1) { this.proposalPrice-- } } send(): void { this.show = true; this.booking.objects = JSON.stringify(this.objects); this.booking.price = this.proposalPrice; this.booking.kilo = this.$props.post.kilo; this.booking.travel = this.$props.post.id axios.post('/post/booking/' + this.$props.post.id, this.booking).then((response) => { this.show = false; this.$toast.success(response.data, { timeout: 2000 }); setTimeout(function() { window.location.reload(); }, 2000); }).catch((error) => { if(error.response.data){ this.$toast.error(error.response.data.message, { timeout: 2000 }); this.show = false; } }) } get totalToPay() { let total: any = 0; this.objects.forEach(function (obj) { if (obj.type === 'Courrier'){ total += (obj.quantity * obj.price); } total += (obj.weight * obj.price); }) return total; } proposition() { this.showProposal = true; this.booking.message = "Bonjour " + this.$props.post.user.firstname + ",\n" + "Votre annonce m’intéresse. Je suis disponible pour effectuer cette livraison.\n" + "Quelles sont les disponibilités de l’expéditeur et du destinataire ?\n" + "Merci de votre réponse !\n" + "A bientôt !\n" + this.$props.auth.firstname + " " + this.$props.auth.lastname } mounted(): void { this.objects = this.$props.post.objects; this.proposalPrice = this.totalToPay; this.showProposal = false; } } </script> <style lang="scss" scoped> .large-icon { font-size: 60px; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .proposal input { font-size: 1.2em; width: 100px; color: black; font-weight: bold; } </style>
import React, { useEffect, useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import "../../styles/crud.css"; import { saveProduct, listProducts, deleteProduct } from "./crudActions"; import axios from "axios"; function ProductCrud(props) { const [modalVisible, setModalVisible] = useState(false); const [id, setId] = useState(""); const [name, setName] = useState(""); const [price, setPrice] = useState(""); const [image, setImage] = useState(""); const [brand, setBrand] = useState(""); const [category, setCategory] = useState(""); const [description, setDescription] = useState(""); const productList = useSelector(state => state.productList); const [uploading, setUploading] = useState(false); const { products } = productList; const productSave = useSelector(state => state.productSave); const { loading: loadingSave, success: successSave, error: errorSave } = productSave; const productDelete = useSelector(state => state.productDelete); const { success: successDelete} = productDelete; const dispatch = useDispatch(); useEffect(() => { if (successSave) { setModalVisible(false); } dispatch(listProducts()); return () => { // }; }, [successSave, successDelete]); const openModal = (product) => { setModalVisible(true); setId(product._id); setName(product.name); setPrice(product.price); setDescription(product.description); setImage(product.image); setBrand(product.brand); setCategory(product.category); } const submitHandler = (e) => { e.preventDefault(); dispatch(saveProduct({ _id: id, name, price, image, brand, category, description })); } const deleteHandler = (product) => { dispatch(deleteProduct(product._id)); } // upload file to aws const uploadFileHandler = (e) => { const file = e.target.files[0]; const bodyFormData = new FormData(); bodyFormData.append('image', file); setUploading(true); axios .post('/api/uploads/s3', bodyFormData, { headers: { 'Content-Type': 'multipart/form-data', }, }) .then((response) => { setImage(response.data); setUploading(false); }) .catch((err) => { console.log(err); setUploading(false); }); }; //-------------------------upload file locally------------------------------- // const uploadFileHandler = (e) => { // const file = e.target.files[0]; // const bodyFormData = new FormData(); // bodyFormData.append('image', file); // setUploading(true); // axios // .post('/api/uploads', bodyFormData, { // headers: { // 'Content-Type': 'multipart/form-data', // }, // }) // .then((response) => { // setImage(response.data); // setUploading(false); // }) // .catch((err) => { // console.log(err); // setUploading(false); // }); // }; return <div className="content content-margined"> <div className="product-header"> <h2 onClick={() => setModalVisible(false)} className="button-secondary">Product-List </h2> <button className="button-primary" onClick={() => openModal({})}>Create Product</button> </div> {modalVisible && <div className="form"> <form onSubmit={submitHandler} > <ul className="form-container"> <li> <p className="newPro">Create/Update Product</p> </li> <li> {loadingSave && <div>Loading...</div>} {errorSave && <div>{errorSave}</div>} </li> <li> <label htmlFor="name"> Name </label> <input type="text" name="name" value={name} id="name" onChange={(e) => setName(e.target.value)}> </input> </li> <li> <label htmlFor="price"> Price </label> <input type="text" name="price" value={price} id="price" onChange={(e) => setPrice(e.target.value)}> </input> </li> <li> <label htmlFor="image"> Image </label> <input type="text" name="image" value={image} id="image" onChange={(e) => setImage(e.target.value)}> </input> <input type="file" onChange={uploadFileHandler}></input> {uploading && <div>Uploading...</div>} </li> <li> <label htmlFor="brand"> Brand </label> <input type="text" name="brand" value={brand} id="brand" onChange={(e) => setBrand(e.target.value)}> </input> </li> <li> <label htmlFor="name"> Category </label> <input type="text" name="category" value={category} id="category" onChange={(e) => setCategory(e.target.value)}> </input> </li> <li> <label htmlFor="description"> Description </label> <textarea name="description" value={description} id="description" onChange={(e) => setDescription(e.target.value)}></textarea> </li> <li> <button type="submit" className="button primary">{id ? "Update" : "Create"}</button> </li> <li> <button type="button" onClick={() => setModalVisible(false)} className="button secondary">Back</button> </li> </ul> </form> </div> } <div className="product-list"> <table className="table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Price</th> <th>Category</th> <th>Brand</th> <th>Action</th> </tr> </thead> <tbody> {products.map(product => (<tr key={product._id}> <td>{product._id}</td> <td>{product.name}</td> <td>{product.price}</td> <td>{product.category}</td> <td>{product.brand}</td> <td> <button className="button" onClick={() => openModal(product)} >Edit</button> {" "} <button className="button" onClick={() => deleteHandler(product)} >Delete</button> </td> </tr>))} </tbody> </table> </div> </div> } export default ProductCrud;
import XRegExp from 'xregexp'; import { JSONData, TypeNames } from '../declarations'; import { StringType } from './StringType'; class UrlType extends StringType { name(): TypeNames { return TypeNames.URL; } protected validateType(value: JSONData): boolean { const regex = XRegExp( ` ^ # http:// or https:// or ftp:// or ftps:// (?:http|ftp)s?:// # domain... (?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+ (?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?) | # ...or ipv4 \\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3} | # ...or ipv6 \\[?[A-F0-9]*:[A-F0-9:]+\\]?) # optional port (?::\\d+)? (?:/?|[/?]\\S+) $ `, 'xi' ); return regex.test(value as string); } } export { UrlType };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Featured Jobs</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" /> <link rel="stylesheet" href="style.css"> </head> <body> <?php include 'authguard.php'; ?> <main class="container mt-5"> <div class="row"> <div class="col-md-6"> <h3>Filter</h3> <form id="search-form" action="JobFound.php" method="post"> <select name="location" class="form-select mb-3" aria-label="Filter Jobs by Location" id="filter-location" required> <option value="all">All Locations</option> <?php $conn = new mysqli("localhost", "root", "", "younggigs"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT DISTINCT location FROM jobs"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $capitalizedSkill = ucwords($row['location']); $lowercaseString = strtolower($row['location']); echo '<option value="' . $lowercaseString . '">' . $capitalizedSkill . '</option>'; } } ?> <!-- <option value="mumbai">Mumbai</option> <option value="kolkata">Kolkata</option> <option value="delhi">Delhi</option> <option value="bangalore">Bangalore</option> <option value="hyderabad">Hyderabad</option> <option value="chennai">Chennai</option> <option value="pune">Pune</option> <option value="ahmedabad">Ahmedabad</option> <option value="jaipur">Jaipur</option> <option value="surat">Surat</option> <option value="lucknow">Lucknow</option> <option value="kanpur">Kanpur</option> <option value="nagpur">Nagpur</option> <option value="patna">Patna</option> <option value="indore">Indore</option> <option value="thane">Thane</option> <option value="mulund">Mulund</option> <option value="bhopal">Bhopal</option> <option value="visakhapatnam">Visakhapatnam</option> <option value="vadodara">Vadodara</option> <option value="firozabad">Firozabad</option> <option value="ludhiana">Ludhiana</option> <option value="rajkot">Rajkot</option> <option value="agra">Agra</option> <option value="siliguri">Siliguri</option> <option value="nashik">Nashik</option> <option value="faridabad">Faridabad</option> <option value="patiala">Patiala</option> <option value="meerut">Meerut</option> <option value="kalyan">Kalyan</option> <option value="vasai-virar">Vasai-Virar</option> --> <option value="remote">Remote</option> </select> <select name="jobType" class="form-select mb-3" aria-label="Filter Jobs by Job Type" id="filter-job-type" required> <option value="all">All Job Types</option> <option value="full-time">Full-Time</option> <option value="part-time">Part-Time</option> <option value="contract">Contract</option> </select> <div id="selected-skills-container" class="mb-3"></div> <label for="skills"> Select Skills </label> <select name="skills[]" class="form-select" aria-placeholder="Select Skills" aria-label="Filter Jobs by Skills" id="filter-skills" multiple required> <?php $conn = new mysqli("localhost", "root", "", "younggigs"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM skills"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $capitalizedSkill = ucwords($row['skill']); echo '<option value="' . $row['skill'] . '">' . $capitalizedSkill . '</option>'; } } ?> </select> <div class="col-md-6"> <button type="submit" class="btn btn-primary mt-3 w-100">Search Jobs</button> </div> </form> </div> <nav aria-label="Page navigation"> <ul class="pagination justify-content-center" id="pagination"> </ul> </nav> </div> </main> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFOnpDpii0CWuVAy8M9D3PQQaGCz5ShROAzIqhqh1TLpCV4fEw7qQ4Txp0" crossorigin="anonymous"></script> <script> document.addEventListener('DOMContentLoaded', function() { var searchForm = document.getElementById('search-form'); searchForm.addEventListener('submit', function(event) { // event.preventDefault(); var searchInput = document.getElementById('search-input').value; var location = document.getElementById('filter-location').value; var jobType = document.getElementById('filter-job-type').value; var selectedSkills = Array.from(document.querySelectorAll('#filter-skills option:checked')).map(function(option) { return option.value; }); var searchData = { searchInput: searchInput, location: location, jobType: jobType, skills: selectedSkills }; console.log(searchData); // Send POST request to backend using Axios }); // Initialize Select2 $('#filter-skills').select2(); // Handle change event for skills $('#filter-skills').on('change', function() { updateSelectedSkillsTags(); }); function updateSelectedSkillsTags() { var selectedSkillsContainer = document.getElementById('selected-skills-container'); selectedSkillsContainer.innerHTML = ''; var selectedSkillsData = $('#filter-skills').select2('data'); selectedSkillsData.forEach(function(skill) { var tag = document.createElement('span'); tag.className = 'badge bg-primary me-1 mb-1'; tag.style.cursor = 'pointer'; tag.textContent = skill.text; tag.addEventListener('click', function() { var optionToRemove = $('#filter-skills option').filter(function() { return $(this).html() === skill.text; }); optionToRemove.prop('selected', false); $('#filter-skills').trigger('change.select2'); }); selectedSkillsContainer.appendChild(tag); }); } }); </script> </body> </html>
function qpskApp() message = 'hello world'; myStruct = myStructInit(message); [messageBits, berMask] = initMessage(message,myStruct.MessageLength,myStruct.NumberOfMessage); if coder.target('MATLAB') useScopes = false; else useScopes = false; end printData = true; % Copyright 2012-2017 The MathWorks, Inc. %#codegen persistent qpskTx qpskRx qpskScopes %qpskChan coder.extrinsic('createQPSKScopes','runQPSKScopes','releaseQPSKScopes') if isempty(qpskTx) % Initialize the components % Create and configure the transmitter System object qpskTx = QPSKTransmitter(... 'UpsamplingFactor', myStruct.Interpolation, ... 'RolloffFactor', myStruct.RolloffFactor, ... 'RaisedCosineFilterSpan', myStruct.RaisedCosineFilterSpan, ... 'MessageBits', messageBits, ... 'MessageLength', myStruct.MessageLength, ... 'NumberOfMessage', myStruct.NumberOfMessage, ... 'ScramblerBase', myStruct.ScramblerBase, ... 'ScramblerPolynomial', myStruct.ScramblerPolynomial, ... 'ScramblerInitialConditions', myStruct.ScramblerInitialConditions); % % Create and configure the AWGN channel System object % qpskChan = QPSKChannel(... % 'DelayType', myStruct.DelayType, ... % 'DelayStepSize', 0.0125*myStruct.Interpolation, ... % 'DelayMaximum', 2*myStruct.Interpolation, ... % 'DelayMinimum', 0.1, ... % 'RaisedCosineFilterSpan', myStruct.RaisedCosineFilterSpan, ... % 'PhaseOffset', myStruct.PhaseOffset, ... % 'SignalPower', 1/myStruct.Interpolation, ... % 'InterpolationFactor', myStruct.Interpolation, ... % 'EbNo', myStruct.EbNo, ... % 'BitsPerSymbol', log2(myStruct.ModulationOrder), ... % 'FrequencyOffset', myStruct.FrequencyOffset, ... % 'SampleRate', myStruct.Fs); % Create and configure the receiver System object qpskRx = QPSKReceiver(... 'ModulationOrder', myStruct.ModulationOrder, ... 'SampleRate', myStruct.Fs, ... 'DecimationFactor', myStruct.Decimation, ... 'FrameSize', myStruct.FrameSize, ... 'HeaderLength', myStruct.HeaderLength, ... 'NumberOfMessage', myStruct.NumberOfMessage, ... 'PayloadLength', myStruct.PayloadLength, ... 'DesiredPower', myStruct.DesiredPower, ... 'AveragingLength', myStruct.AveragingLength, ... 'MaxPowerGain', myStruct.MaxPowerGain, ... 'RolloffFactor', myStruct.RolloffFactor, ... 'RaisedCosineFilterSpan', myStruct.RaisedCosineFilterSpan, ... 'InputSamplesPerSymbol', myStruct.Interpolation, ... 'MaximumFrequencyOffset', myStruct.MaximumFrequencyOffset, ... 'PostFilterOversampling', myStruct.Interpolation/myStruct.Decimation, ... 'PhaseRecoveryLoopBandwidth', myStruct.PhaseRecoveryLoopBandwidth, ... 'PhaseRecoveryDampingFactor', myStruct.PhaseRecoveryDampingFactor, ... 'TimingRecoveryDampingFactor', myStruct.TimingRecoveryDampingFactor, ... 'TimingRecoveryLoopBandwidth', myStruct.TimingRecoveryLoopBandwidth, ... 'TimingErrorDetectorGain', myStruct.TimingErrorDetectorGain, ... 'PreambleDetectorThreshold', myStruct.PreambleDetectorThreshold, ... 'DescramblerBase', myStruct.ScramblerBase, ... 'DescramblerPolynomial', myStruct.ScramblerPolynomial, ... 'DescramblerInitialConditions', myStruct.ScramblerInitialConditions,... 'BerMask', berMask, ... 'pMessage', message, ... 'pMessageLength', myStruct.MessageLength, ... 'PrintOption', printData); if useScopes % Create the System object for plotting all the scopes sampleRate = myStruct.Rsym*myStruct.Interpolation/myStruct.Decimation; qpskScopes = createQPSKScopes(sampleRate); end end qpskRx.PrintOption = printData; transmittedSignal = coder.nullcopy(complex(2266,1)); if coder.target('MATLAB') % Create and configure the Pluto System object. radio_tx = sdrtx('Pluto'); radio_tx.RadioID = myStruct.Address; radio_tx.CenterFrequency = myStruct.PlutoCenterFrequency; radio_tx.BasebandSampleRate = myStruct.PlutoFrontEndSampleRate; radio_tx.SamplesPerFrame = myStruct.PlutoFrameLength; radio_tx.Gain = 0; % radio_rx = sdrrx('Pluto'); radio_rx.RadioID = myStruct.Address; radio_rx.CenterFrequency = myStruct.PlutoCenterFrequency; radio_rx.BasebandSampleRate = myStruct.PlutoFrontEndSampleRate; radio_rx.SamplesPerFrame = myStruct.PlutoFrameLength; radio_rx.GainSource = 'Manual'; radio_rx.Gain = myStruct.PlutoGain; radio_rx.OutputDataType = 'double'; end transmittedSignal = qpskTx(); % Transmitter if coder.target('MATLAB') % Data transmission on repeat radio_tx.transmitRepeat(transmittedSignal); end for count = 1:myStruct.TotalFrame if coder.target('MATLAB') rcvdSignal = radio_rx(); else rcvdSignal = transmittedSignal; end [RCRxSignal, timingRecSignal, freqRecSignal, BER] = qpskRx(rcvdSignal); % Receiver if useScopes runQPSKScopes(qpskScopes, rcvdSignal, RCRxSignal, timingRecSignal, freqRecSignal); % Plots all the scopes end end disp(BER); if isempty(coder.target) release(qpskTx); % release(qpskChan); release(qpskRx); end if useScopes releaseQPSKScopes(qpskScopes); end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> 'use strict' const arr0 = [10,50,40,70,60,30]; arr0.sort(); document.write( arr0 ,'<br>'); const arr1 = [100,150,10,50,40,60,30]; arr1.sort(); document.write( arr1 ,'<br>'); const arr2 = [100,150,10,50,40,60,30]; arr2.sort( function( a , b ){ if( a > b ) { return 1 }else if( a < b ) { return -1 } else{ return 0 } }) document.write( arr2 ,'<br>'); const arr3 = [100,150,10,50,40,60,30]; arr3.sort( function( a, b ) { if( a > b ) { return -1 }else if( a < b) { return 1 }else { return 0 } }) document.write( arr3 ,'<br>'); const arr4 = [100,150,10,50,40,60,30]; arr4.sort( function(a , b ) { // return a - b return b - a }) document.write( arr4 ,'<br>'); const arr5 = [100,150,10,50,40,60,30]; arr5.sort( (a, b) => { return a - b }) document.write( arr5 ,'<br>'); // return 결과가 하나일때는 const arr6 = [100,150,10,50,40,60,30]; arr6.sort( ( a, b) => a - b ); document.write( arr6 ,'<br>'); const arr7 = [ 10,15,100,20 ] arr7.reverse(); document.write( arr7 ,'<br>'); arr6.reverse(); document.write( arr6 ,'<br>'); </script> </head> <body> <pre> Array.prototype.sort() sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 정렬은 stable sort가 아닐 수 있습니다. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다. 정렬 속도와 복잡도는 각 구현방식에 따라 다를 수 있습니다. </pre> </body> </html>
###### Visualising WorldClim data for Tasmanian Euc project #### Load packages and data #### library(raster) library(tidyverse) ###### Extracting PPT, PET and MD for Tasmania! ##### #et is evapotranspiration #ai is aridity index #the 12 correspond to months #yr is annual average #Evapotranspiration et1 <- raster("Data/Global-ET0_v3_monthly/et0_v3_01.tif") et2 <- raster("Data/Global-ET0_v3_monthly/et0_v3_02.tif") et3 <- raster("Data/Global-ET0_v3_monthly/et0_v3_03.tif") et4 <- raster("Data/Global-ET0_v3_monthly/et0_v3_04.tif") et5 <- raster("Data/Global-ET0_v3_monthly/et0_v3_05.tif") et6 <- raster("Data/Global-ET0_v3_monthly/et0_v3_06.tif") et7 <- raster("Data/Global-ET0_v3_monthly/et0_v3_07.tif") et8 <- raster("Data/Global-ET0_v3_monthly/et0_v3_08.tif") et9 <- raster("Data/Global-ET0_v3_monthly/et0_v3_09.tif") et10 <- raster("Data/Global-ET0_v3_monthly/et0_v3_10.tif") et11 <- raster("Data/Global-ET0_v3_monthly/et0_v3_11.tif") et12 <- raster("Data/Global-ET0_v3_monthly/et0_v3_12.tif") #Year etyr <- raster("Data/Global-AI_ET0_v3_annual/et0_v3_yr.tif") #plot(etyr, xlim=c(144, 150), ylim=c(-44, -40)) #Cropping data to just have Tas tas_et1 <- crop(et1, c(144.5,149.1,-44,-40.6)) tas_et2 <- crop(et2, c(144.5,149.1,-44,-40.6)) tas_et3 <- crop(et3, c(144.5,149.1,-44,-40.6)) tas_et4 <- crop(et4, c(144.5,149.1,-44,-40.6)) tas_et5 <- crop(et5, c(144.5,149.1,-44,-40.6)) tas_et6 <- crop(et6, c(144.5,149.1,-44,-40.6)) tas_et7 <- crop(et7, c(144.5,149.1,-44,-40.6)) tas_et8 <- crop(et8, c(144.5,149.1,-44,-40.6)) tas_et9 <- crop(et9, c(144.5,149.1,-44,-40.6)) tas_et10 <- crop(et10, c(144.5,149.1,-44,-40.6)) tas_et11 <- crop(et11, c(144.5,149.1,-44,-40.6)) tas_et12 <- crop(et12, c(144.5,149.1,-44,-40.6)) ### Aridity Index aiyr <- raster("Data/Global-AI_ET0_v3_annual/ai_v3_yr.tif") #plot(aiyr, xlim=c(144, 150), ylim=c(-44, -40)) ## Monthly aridity index ai1 <- raster("Data/Global-AI_v3_monthly/ai_v3_01.tif") ai2 <- raster("Data/Global-AI_v3_monthly/ai_v3_02.tif") ai3 <- raster("Data/Global-AI_v3_monthly/ai_v3_03.tif") ai4 <- raster("Data/Global-AI_v3_monthly/ai_v3_04.tif") ai5 <- raster("Data/Global-AI_v3_monthly/ai_v3_05.tif") ai6 <- raster("Data/Global-AI_v3_monthly/ai_v3_06.tif") ai7 <- raster("Data/Global-AI_v3_monthly/ai_v3_07.tif") ai8 <- raster("Data/Global-AI_v3_monthly/ai_v3_08.tif") ai9 <- raster("Data/Global-AI_v3_monthly/ai_v3_09.tif") ai10 <- raster("Data/Global-AI_v3_monthly/ai_v3_10.tif") ai11 <- raster("Data/Global-AI_v3_monthly/ai_v3_11.tif") ai12 <- raster("Data/Global-AI_v3_monthly/ai_v3_12.tif") #Cropping data to just have Tas tas_ai1 <- crop(ai1, c(144.5,149.1,-44,-40.6)) tas_ai2 <- crop(ai2, c(144.5,149.1,-44,-40.6)) tas_ai3 <- crop(ai3, c(144.5,149.1,-44,-40.6)) tas_ai4 <- crop(ai4, c(144.5,149.1,-44,-40.6)) tas_ai5 <- crop(ai5, c(144.5,149.1,-44,-40.6)) tas_ai6 <- crop(ai6, c(144.5,149.1,-44,-40.6)) tas_ai7 <- crop(ai7, c(144.5,149.1,-44,-40.6)) tas_ai8 <- crop(ai8, c(144.5,149.1,-44,-40.6)) tas_ai9 <- crop(ai9, c(144.5,149.1,-44,-40.6)) tas_ai10 <- crop(ai10, c(144.5,149.1,-44,-40.6)) tas_ai11 <- crop(ai11, c(144.5,149.1,-44,-40.6)) tas_ai12 <- crop(ai12, c(144.5,149.1,-44,-40.6)) ### Need to convert aridity values to be real tas_ai1_real <- tas_ai1/10000 tas_ai2_real <- tas_ai2/10000 tas_ai3_real <- tas_ai3/10000 tas_ai4_real <- tas_ai4/10000 tas_ai5_real <- tas_ai5/10000 tas_ai6_real <- tas_ai6/10000 tas_ai7_real <- tas_ai7/10000 tas_ai8_real <- tas_ai8/10000 tas_ai9_real <- tas_ai9/10000 tas_ai10_real <- tas_ai10/10000 tas_ai11_real <- tas_ai11/10000 tas_ai12_real <- tas_ai12/10000 ### Calculate precipitation at monthly scale tas_ppt1 <- tas_ai1_real*tas_et1 tas_ppt2 <- tas_ai2_real*tas_et2 tas_ppt3 <- tas_ai3_real*tas_et3 tas_ppt4 <- tas_ai4_real*tas_et4 tas_ppt5 <- tas_ai5_real*tas_et5 tas_ppt6 <- tas_ai6_real*tas_et6 tas_ppt7 <- tas_ai7_real*tas_et7 tas_ppt8 <- tas_ai8_real*tas_et8 tas_ppt9 <- tas_ai9_real*tas_et9 tas_ppt10 <- tas_ai10_real*tas_et10 tas_ppt11 <- tas_ai11_real*tas_et11 tas_ppt12 <- tas_ai12_real*tas_et12 ### Calculate moisture deficit at monthly scale tas_md1 <- tas_et1-tas_ppt1 tas_md2 <- tas_et2-tas_ppt2 tas_md3 <- tas_et3-tas_ppt3 tas_md4 <- tas_et4-tas_ppt4 tas_md5 <- tas_et5-tas_ppt5 tas_md6 <- tas_et6-tas_ppt6 tas_md7 <- tas_et7-tas_ppt7 tas_md8 <- tas_et8-tas_ppt8 tas_md9 <- tas_et9-tas_ppt9 tas_md10 <- tas_et10-tas_ppt10 tas_md11 <- tas_et11-tas_ppt11 tas_md12 <- tas_et12-tas_ppt12 ### Annual scale #CMD is Climatic Moisture Deficit # Pet = Potential Evapotranspiration # Ppt = precipitation Tas_AIcrop <- crop(aiyr, c(144.5,149.1,-44,-40.6)) Tas_AIreal <- Tas_AIcrop/10000 Tas_PET <- crop(etyr, c(144.5,149.1,-44,-40.6)) #Doing the below step because AI is PPT/PET so multiplying by PET gives us PPT Tas_PPT <- Tas_AIreal * Tas_PET Tas_CMD <- Tas_PET-Tas_PPT ############ Calculating annual long-term MD for sites ################ ###This is an example of how to extract values from a single location # rlat <- -41.18608 # rlon <- 148.25668 # ptsCMD <- extract(x=Tas_CMD, y= cbind(rlon, rlat)) # ptsAI <- extract(x=Tas_AIreal, y=cbind(rlon, rlat)) # ptsPPT <- extract(x=Tas_PPT, y=cbind(rlon, rlat)) ### plotting PPT, PET, AI, and CMD in one place # par(mfrow=c(2,2), mar=c(.5,.5,2, 5.5)) # plot(Tas_PPT, xaxt="n", yaxt="n", main="PPT") # plot(Tas_PET, xaxt="n", yaxt="n", main="PET") # plot(Tas_AIreal, xaxt="n", yaxt="n", main="AI (PPT/PET)") #plot(Tas_CMD, xaxt="n", yaxt="n", main="AI/CMD (PET-PPT)") # import Tasmanian reserve lat long (in decimal degrees) ### ResTas <- read_csv("Data/site_coords_updated.csv") ResTas$AI <- extract(x=Tas_AIreal, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTas$PPT <- extract(x=Tas_PPT, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTas$PET <- extract(x=Tas_PET, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTas$CMD <- extract(x=Tas_CMD, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) #with old lats and longs - very similar. # ResTas$AI_old <- extract(x=Tas_AIreal, y= cbind(ResTas$Old_Long,ResTas$Old_Lat)) # ResTas$PPT_old <- extract(x=Tas_PPT, y= cbind(ResTas$Old_Long,ResTas$Old_Lat)) # ResTas$PET_old <- extract(x=Tas_PET, y= cbind(ResTas$Old_Long,ResTas$Old_Lat)) # ResTas$CMD_old <- extract(x=Tas_CMD, y= cbind(ResTas$Old_Long,ResTas$Old_Lat)) ### These are the annual features of the site (PPT, PET, CMD) simpleResTas <- ResTas %>% dplyr::select(Site, PPT, PET, CMD) ### Look at the extracted values #plot(Tas_CMD, main="CMD (PET-PPT)") #Size is based on aridity index! #points(Centred_Lat~Centred_Long, ResTas, pch=16, cex=AI, col='red') #### plotting just tasman peninsula #plot(Tas_CMD, xlim=c(147.5,148.5), ylim=c(-43.5, -42.5)) #### Calculating period climate anomaly #### # By site and by month #md_norm is agnostic to year, but calculated as an average per month #md_period matters which year ## These are the months (inclusive) that need to be summed to calculate # proportion period climate/norm climate, by site #Summing months where a majority of the month there was growth data dates_growth_site <- read_csv("Data/dates_monthly_period_growth.csv") #This is the dataset with the period climate data already in it #period_climate ## Need to extract site-level climate norm data by month first #Centred_Lat and Centred_Long are the coordinates that we want! #These coordinates are centred (spatially) relative to where the actual focal trees are #Curious how MD values vary from old coords and new ones: ResTasMonthly <- read_csv("Data/site_coords_updated.csv") #Can't have any extra columns because it will interfere with MD calculations below ResTasMonthly <- ResTasMonthly %>% dplyr::select(Site, Centred_Lat, Centred_Long) ResTasMonthly$CMD_1 <- raster::extract(x=tas_md1, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_2 <- raster::extract(x=tas_md2, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_3 <- raster::extract(x=tas_md3, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_4 <- raster::extract(x=tas_md4, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_5 <- raster::extract(x=tas_md5, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_6 <- raster::extract(x=tas_md6, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_7 <- raster::extract(x=tas_md7, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_8 <- raster::extract(x=tas_md8, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_9 <- raster::extract(x=tas_md9, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_10 <- raster::extract(x=tas_md10, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_11 <- raster::extract(x=tas_md11, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) ResTasMonthly$CMD_12 <- raster::extract(x=tas_md12, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat)) # import Site and Period table so that I can assign period values directly site_period <- period_climate %>% dplyr::select(Site, Period) climate_diff <- left_join(ResTasMonthly, site_period) ## Summing them for each site based on growth period (dates_growth_site) #From first month (including) to second month (excluding) climate_diff$norm_md <- 123 #Period 1 first: #EPF ### EPF period 1 and 2 - feb to feb and march to march - give same values # because it is one year #4 is Jan, 5 is Feb, 6 is March, 7 Apr, 8 May, 9 Jun, 10 Jul, 11 Aug, 12 Sep, 13 Oct, 14 Nov, 15 Dec #First line is saying sum feb to december + jan #GRA # gra_ppt_period1 <- bom_gra %>% subset(date >= "2020-02-01" & date <= "2021-01-31") %>% # summarise(period1_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) # gra_ppt_period2 <- bom_gra %>% subset(date >= "2021-02-01" & date <= "2022-01-31") %>% # summarise(period2_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) # gra_ppt_period3 <- bom_gra %>% subset(date >= "2022-02-01" & date <= "2023-02-28") %>% # summarise(period3_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) climate_diff$norm_md[climate_diff$Site=="EPF" & climate_diff$Period == 1] <- sum(climate_diff[1,5:15], climate_diff[1,4]) climate_diff$norm_md[climate_diff$Site=="TMP" & climate_diff$Period == 1] <- sum(climate_diff[4,5:15], climate_diff[4,4:5]) climate_diff$norm_md[climate_diff$Site=="MER" & climate_diff$Period == 1] <- sum(climate_diff[7,5:15], climate_diff[7,4]) climate_diff$norm_md[climate_diff$Site=="DOG" & climate_diff$Period == 1] <- sum(climate_diff[10,5:15], climate_diff[10,4]) climate_diff$norm_md[climate_diff$Site=="GRA" & climate_diff$Period == 1] <- sum(climate_diff[13,5:15], climate_diff[13,4]) climate_diff$norm_md[climate_diff$Site=="FREY" & climate_diff$Period == 1] <- sum(climate_diff[16,5:15], climate_diff[16,4:5]) climate_diff$norm_md[climate_diff$Site=="BOF" & climate_diff$Period == 1] <- sum(climate_diff[19,9:15], climate_diff[19,4]) #Period 2 climate_diff$norm_md[climate_diff$Site=="EPF" & climate_diff$Period == 2] <- sum(climate_diff[2,6:15], climate_diff[2,4:5]) climate_diff$norm_md[climate_diff$Site=="TMP" & climate_diff$Period == 2] <- sum(climate_diff[5,6:15], climate_diff[5,4]) climate_diff$norm_md[climate_diff$Site=="MER" & climate_diff$Period == 2] <- sum(climate_diff[8,5:15], climate_diff[8,4:5]) climate_diff$norm_md[climate_diff$Site=="DOG" & climate_diff$Period == 2] <- sum(climate_diff[11,5:15], climate_diff[11,4:5]) climate_diff$norm_md[climate_diff$Site=="GRA" & climate_diff$Period == 2] <- sum(climate_diff[14,5:15], climate_diff[14,4]) climate_diff$norm_md[climate_diff$Site=="FREY" & climate_diff$Period == 2] <- sum(climate_diff[17,6:15], climate_diff[17,4:5]) climate_diff$norm_md[climate_diff$Site=="BOF" & climate_diff$Period == 2] <- sum(climate_diff[20,5:15], climate_diff[20,4:5]) #Period 3 climate_diff$norm_md[climate_diff$Site=="EPF" & climate_diff$Period == 3] <- sum(climate_diff[3,6:15], climate_diff[3,4:5]) climate_diff$norm_md[climate_diff$Site=="TMP" & climate_diff$Period == 3] <- sum(climate_diff[6,5:15], climate_diff[6,4:5]) climate_diff$norm_md[climate_diff$Site=="MER" & climate_diff$Period == 3] <- sum(climate_diff[9,6:15], climate_diff[9,4:5]) climate_diff$norm_md[climate_diff$Site=="DOG" & climate_diff$Period == 3] <- sum(climate_diff[12,6:15], climate_diff[12,4:5]) climate_diff$norm_md[climate_diff$Site=="GRA" & climate_diff$Period == 3] <- sum(climate_diff[15,5:15], climate_diff[15,4:5]) climate_diff$norm_md[climate_diff$Site=="FREY" & climate_diff$Period == 3] <- sum(climate_diff[18,6:15], climate_diff[18,4:5]) climate_diff$norm_md[climate_diff$Site=="BOF" & climate_diff$Period == 3] <- sum(climate_diff[21,6:15], climate_diff[21,4:5]) climate_diff <- climate_diff %>% dplyr::select(Site, Period, norm_md) ### but period climate is currently calculated to the day - #I need to recalculate it at the month scale #### Calculating MD for period climate at the monthly scale #### ## BOM dataframes are loaded in from data_preparations file #Make a column for rainfall and pet data climate_diff$period_ppt_by_month <- 123 climate_diff$period_pet_by_month <- 123 ## EPF #Calculate rainfall for period 1 (Feb 2020-Feb 2021: including (from first), excluding (to second)) epf_ppt_period1 <- bom_epf %>% subset(date >= "2020-02-01" & date <= "2021-01-31") %>% summarise(period1_rainfall = sum(`Rainfall amount (millimetres)`)) #Calculate rainfall for period 2 (March 2021 - March 2022) epf_ppt_period2 <- bom_epf %>% subset(date >= "2021-03-01" & date <= "2022-02-28") %>% summarise(period2_rainfall = sum(`Rainfall amount (millimetres)`)) #Calculate rainfall for period 3 (March 2022 - March 2023) epf_ppt_period3 <- bom_epf %>% subset(date >= "2022-03-01" & date <= "2023-02-28") %>% summarise(period3_rainfall = sum(`Rainfall amount (millimetres)`, na.rm=T)) #Filling data in table climate_diff <- within(climate_diff, period_ppt_by_month[Period == '1' & Site == 'EPF'] <- epf_ppt_period1) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '2' & Site == 'EPF'] <- epf_ppt_period2) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '3' & Site == 'EPF'] <- epf_ppt_period3) ## TMP tmp_ppt_period1 <- bom_tmp %>% subset(date >= "2020-02-01" & date <= "2021-02-28") %>% summarise(period1_rainfall = sum(`Rainfall amount (millimetres)`, na.rm=TRUE)) tmp_ppt_period2 <- bom_tmp %>% subset(date >= "2021-03-01" & date <= "2022-01-31") %>% summarise(period2_rainfall = sum(`Rainfall amount (millimetres)`, na.rm=TRUE)) tmp_ppt_period3 <- bom_tmp %>% subset(date >= "2022-02-01" & date <= "2023-02-28") %>% summarise(period3_rainfall = sum(`Rainfall amount (millimetres)`, na.rm=TRUE)) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '1' & Site == 'TMP'] <- tmp_ppt_period1) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '2' & Site == 'TMP'] <- tmp_ppt_period2) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '3' & Site == 'TMP'] <- tmp_ppt_period3) ## MER mer_ppt_period1 <- bom_mer %>% subset(date >= "2020-02-01" & date <= "2021-01-31") %>% summarise(period1_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) mer_ppt_period2 <- bom_mer %>% subset(date >= "2021-02-01" & date <= "2022-02-28") %>% summarise(period2_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) mer_ppt_period3 <- bom_mer %>% subset(date >= "2022-03-01" & date <= "2023-02-28") %>% summarise(period3_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '1' & Site == 'MER'] <- mer_ppt_period1) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '2' & Site == 'MER'] <- mer_ppt_period2) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '3' & Site == 'MER'] <- mer_ppt_period3) ## DOG dog_ppt_period1 <- bom_dog %>% subset(date >= "2020-02-01" & date <= "2021-01-31") %>% summarise(period1_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) dog_ppt_period2 <- bom_dog %>% subset(date >= "2021-02-01" & date <= "2022-02-28") %>% summarise(period2_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) dog_ppt_period3 <- bom_dog %>% subset(date >= "2022-03-01" & date <= "2023-02-28") %>% summarise(period3_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '1' & Site == 'DOG'] <- dog_ppt_period1) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '2' & Site == 'DOG'] <- dog_ppt_period2) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '3' & Site == 'DOG'] <- dog_ppt_period3) ## GRA gra_ppt_period1 <- bom_gra %>% subset(date >= "2020-02-01" & date <= "2021-01-31") %>% summarise(period1_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) gra_ppt_period2 <- bom_gra %>% subset(date >= "2021-02-01" & date <= "2022-01-31") %>% summarise(period2_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) gra_ppt_period3 <- bom_gra %>% subset(date >= "2022-02-01" & date <= "2023-02-28") %>% summarise(period3_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '1' & Site == 'GRA'] <- gra_ppt_period1) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '2' & Site == 'GRA'] <- gra_ppt_period2) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '3' & Site == 'GRA'] <- gra_ppt_period3) ## FREY frey_ppt_period1 <- bom_frey %>% subset(date >= "2020-02-01" & date <= "2021-02-28") %>% summarise(period1_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) frey_ppt_period2 <- bom_frey %>% subset(date >= "2021-03-01" & date <= "2022-02-28") %>% summarise(period2_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) frey_ppt_period3 <- bom_frey %>% subset(date >= "2022-03-01" & date <= "2023-02-28") %>% summarise(period3_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '1' & Site == 'FREY'] <- frey_ppt_period1) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '2' & Site == 'FREY'] <- frey_ppt_period2) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '3' & Site == 'FREY'] <- frey_ppt_period3) ## BOF bof_ppt_period1 <- bom_bof %>% subset(date >= "2020-06-01" & date <= "2021-01-31") %>% summarise(period1_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) bof_ppt_period2 <- bom_bof %>% subset(date >= "2021-02-01" & date <= "2022-02-28") %>% summarise(period2_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) bof_ppt_period3 <- bom_bof %>% subset(date >= "2022-03-01" & date <= "2023-02-28") %>% summarise(period3_rainfall = sum(`Rainfall amount (millimetres)`, na.rm = TRUE)) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '1' & Site == 'BOF'] <- bof_ppt_period1) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '2' & Site == 'BOF'] <- bof_ppt_period2) climate_diff <- within(climate_diff, period_ppt_by_month[Period == '3' & Site == 'BOF'] <- bof_ppt_period3) # Some of these values are quite different - amount of rainfall that # fell over exact dates and that fell at the monthly scale #not a problem #### Now for evapotranspiration ## EPF epf_pet_period1 <- epf_evapo %>% subset(date >= "2020-02-01" & date <= "2021-01-31") %>% summarise(period1_pet = sum(evapotranspiration_mm, na.rm=TRUE)) epf_pet_period2 <- epf_evapo %>% subset(date >= "2021-03-01" & date <= "2022-02-28") %>% summarise(period2_pet = sum(evapotranspiration_mm, na.rm=TRUE)) epf_pet_period3 <- epf_evapo %>% subset(date >= "2022-03-01" & date <= "2023-02-28") %>% summarise(period3_pet = sum(evapotranspiration_mm, na.rm=TRUE)) climate_diff <- within(climate_diff, period_pet_by_month[Period == '1' & Site == 'EPF'] <- epf_pet_period1) climate_diff <- within(climate_diff, period_pet_by_month[Period == '2' & Site == 'EPF'] <- epf_pet_period2) climate_diff <- within(climate_diff, period_pet_by_month[Period == '3' & Site == 'EPF'] <- epf_pet_period3) ## TMP tmp_pet_period1 <- tmp_evapo %>% subset(date >= "2020-02-01" & date <= "2021-02-28") %>% summarise(period1_pet = sum(evapotranspiration_mm, na.rm=TRUE)) tmp_pet_period2 <- tmp_evapo %>% subset(date >= "2021-03-01" & date <= "2022-01-31") %>% summarise(period2_pet = sum(evapotranspiration_mm, na.rm=TRUE)) tmp_pet_period3 <- tmp_evapo %>% subset(date >= "2022-02-01" & date <= "2023-02-28") %>% summarise(period3_pet = sum(evapotranspiration_mm, na.rm = TRUE)) climate_diff <- within(climate_diff, period_pet_by_month[Period == '1' & Site == 'TMP'] <- tmp_pet_period1) climate_diff <- within(climate_diff, period_pet_by_month[Period == '2' & Site == 'TMP'] <- tmp_pet_period2) climate_diff <- within(climate_diff, period_pet_by_month[Period == '3' & Site == 'TMP'] <- tmp_pet_period3) ## MER #Uses same dataset as DOG for evapotranspiration mer_pet_period1 <- dog_evapo %>% subset(date >= "2020-02-01" & date <= "2021-01-31") %>% summarise(period1_pet = sum(evapotranspiration_mm, na.rm = TRUE)) mer_pet_period2 <- dog_evapo %>% subset(date >= "2021-02-01" & date <= "2022-02-28") %>% summarise(period2_pet = sum(evapotranspiration_mm, na.rm = TRUE)) mer_pet_period3 <- dog_evapo %>% subset(date >= "2022-03-01" & date <= "2023-02-28") %>% summarise(period3_pet = sum(evapotranspiration_mm, na.rm = TRUE)) climate_diff <- within(climate_diff, period_pet_by_month[Period == '1' & Site == 'MER'] <- mer_pet_period1) climate_diff <- within(climate_diff, period_pet_by_month[Period == '2' & Site == 'MER'] <- mer_pet_period2) climate_diff <- within(climate_diff, period_pet_by_month[Period == '3' & Site == 'MER'] <- mer_pet_period3) ## DOG dog_pet_period1 <- dog_evapo %>% subset(date >= "2020-02-01" & date <= "2021-01-31") %>% summarise(period1_pet = sum(evapotranspiration_mm, na.rm = TRUE)) dog_pet_period2 <- dog_evapo %>% subset(date >= "2021-02-01" & date <= "2022-02-28") %>% summarise(period2_pet = sum(evapotranspiration_mm, na.rm = TRUE)) dog_pet_period3 <- dog_evapo %>% subset(date >= "2022-03-01" & date <= "2023-02-28") %>% summarise(period3_pet = sum(evapotranspiration_mm, na.rm = TRUE)) climate_diff <- within(climate_diff, period_pet_by_month[Period == '1' & Site == 'DOG'] <- dog_pet_period1) climate_diff <- within(climate_diff, period_pet_by_month[Period == '2' & Site == 'DOG'] <- dog_pet_period2) climate_diff <- within(climate_diff, period_pet_by_month[Period == '3' & Site == 'DOG'] <- dog_pet_period3) ## GRA gra_pet_period1 <- gra_evapo %>% subset(date >= "2020-02-01" & date <= "2021-01-31") %>% summarise(period1_pet = sum(evapotranspiration_mm, na.rm = TRUE)) gra_pet_period2 <- gra_evapo %>% subset(date >= "2021-02-01" & date <= "2022-01-31") %>% summarise(period2_pet = sum(evapotranspiration_mm, na.rm = TRUE)) gra_pet_period3 <- gra_evapo %>% subset(date >= "2022-02-01" & date <= "2023-02-28") %>% summarise(period3_pet = sum(evapotranspiration_mm, na.rm = TRUE)) climate_diff <- within(climate_diff, period_pet_by_month[Period == '1' & Site == 'GRA'] <- gra_pet_period1) climate_diff <- within(climate_diff, period_pet_by_month[Period == '2' & Site == 'GRA'] <- gra_pet_period2) climate_diff <- within(climate_diff, period_pet_by_month[Period == '3' & Site == 'GRA'] <- gra_pet_period3) ## FREY frey_pet_period1 <- frey_evapo %>% subset(date >= "2020-02-01" & date <= "2021-02-28") %>% summarise(period1_pet = sum(evapotranspiration_mm, na.rm = TRUE)) frey_pet_period2 <- frey_evapo %>% subset(date >= "2021-03-01" & date <= "2022-02-28") %>% summarise(period2_pet = sum(evapotranspiration_mm, na.rm = TRUE)) frey_pet_period3 <- frey_evapo %>% subset(date >= "2022-03-01" & date <= "2023-02-28") %>% summarise(period3_pet = sum(evapotranspiration_mm, na.rm = TRUE)) climate_diff <- within(climate_diff, period_pet_by_month[Period == '1' & Site == 'FREY'] <- frey_pet_period1) climate_diff <- within(climate_diff, period_pet_by_month[Period == '2' & Site == 'FREY'] <- frey_pet_period2) climate_diff <- within(climate_diff, period_pet_by_month[Period == '3' & Site == 'FREY'] <- frey_pet_period3) ## BOF bof_pet_period1 <- bof_evapo %>% subset(date >= "2020-06-01" & date <= "2021-01-31") %>% summarise(period1_pet = sum(evapotranspiration_mm, na.rm = TRUE)) bof_pet_period2 <- bof_evapo %>% subset(date >= "2021-02-01" & date <= "2022-02-28") %>% summarise(period2_pet = sum(evapotranspiration_mm, na.rm = TRUE)) bof_pet_period3 <- bof_evapo %>% subset(date >= "2022-03-01" & date <= "2023-02-28") %>% summarise(period3_pet = sum(evapotranspiration_mm, na.rm = TRUE)) climate_diff <- within(climate_diff, period_pet_by_month[Period == '1' & Site == 'BOF'] <- bof_pet_period1) climate_diff <- within(climate_diff, period_pet_by_month[Period == '2' & Site == 'BOF'] <- bof_pet_period2) climate_diff <- within(climate_diff, period_pet_by_month[Period == '3' & Site == 'BOF'] <- bof_pet_period3) #Calculate monthly period moisture deficit climate_diff$period_pet_by_month <- as.numeric(climate_diff$period_pet_by_month) climate_diff$period_ppt_by_month <- as.numeric(climate_diff$period_ppt_by_month) climate_diff <- climate_diff %>% mutate(monthly_period_md = period_pet_by_month - period_ppt_by_month) ## Simplify dataset climate_diff <- climate_diff %>% dplyr::select(Site, Period, norm_md, monthly_period_md) ## Calculate anomaly! climate_diff <- climate_diff %>% mutate(anomaly = monthly_period_md-norm_md) ## Plot them # ggplot(climate_diff, aes (x = norm_md, y = monthly_period_md, colour = Site))+ # geom_point(cex=2, alpha =0.8)+ # theme_classic() # # # ggplot(climate_diff, aes (x = Site, y = norm_md, colour = Period))+ # geom_jitter(cex=3, alpha =0.4)+ # theme_classic() # ggplot(climate_diff, aes (x = Site, y = anomaly, colour = Period))+ # geom_jitter(cex=3, alpha =0.4)+ # theme_classic() ## How to calculate this as a proportion? #problem: -500/-300 = 1.6, and 500/300 = 1.6 but opposite scenarios (1.6x wetter, 1.6x drier) #... this is tricky! #https://math.stackexchange.com/questions/716767/how-to-calculate-the-percentage-of-increase-decrease-with-negative-numbers # some useful info #Could I write something that says if period value < norm value, add negative sign? #Don't need it to be a proportion for the analysis #Resetting this function select <- dplyr::select #### Testing minimum temperatures across Tas #### # data downloaded from WorldClim 1970-2000 climate averages temp1 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_01.tif") temp2 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_02.tif") temp3 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_03.tif") temp4 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_04.tif") temp5 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_05.tif") temp6 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_06.tif") temp7 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_07.tif") temp8 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_08.tif") temp9 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_09.tif") temp10 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_10.tif") temp11 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_11.tif") temp12 <- raster("Data/WorldClim_Tmin_10mins/wc2.1_10m_tmin_12.tif") #Year #BIO6 shows the long-term average annual Min Temperature of the coldest month tempyr <- raster("Data/WorldClim_Bio/wc2.1_10m_bio_6.tif") plot(tempyr, xlim=c(144, 150), ylim=c(-44, -40)) ## Extract values for my sites # import Tasmanian reserve lat long (in decimal degrees) ### ResTas <- read_csv("Data/site_coords_updated.csv") ResTas$Tmin <- raster::extract(x=tempyr, y= cbind(ResTas$Centred_Long,ResTas$Centred_Lat))
from rest_framework import serializers from django.contrib.auth import authenticate from .models import User class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=128, min_length=8, write_only=True) class Meta: model = User fields = ['username', 'name', 'password', 'public_id', 'created', 'updated'] def create(self, validated_data): return User.objects.create_user(**validated_data) class LoginSerializer(serializers.Serializer): username = serializers.CharField(max_length=255) name = serializers.CharField(max_length=255, read_only=True) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(read_only=True) def validate(self, data): username = data.get('username', None) password = data.get('password', None) if username is None: raise serializers.ValidationError('A username is required to log in') if password is None: raise serializers.ValidationError('A password is required to log in') user = authenticate(username=username, password=password) if user is None: raise serializers.ValidationError('A user with this username and password was not found.') if not user.is_active: raise serializers.ValidationError('Seems like this user has been deactivated') return { 'username': user.username, 'token': user.token, }
package org.ting.pattern.builder.service; import org.ting.pattern.builder.inter.Item; import java.util.ArrayList; import java.util.List; /** * 餐 * * @author 张韧炼 * @create 2019-07-02 下午2:47 **/ public class Meal { private List<Item> items = new ArrayList<>(16); public void addItem(Item item) { items.add(item); } public float getCost() { float cost = 0.0f; for (Item item : items) { cost += item.price(); } return cost; } public void showItems() { for (Item item : items) { System.out.print("Item:" + item.name()); System.out.print(",Packing:" + item.packing().pack()); System.out.println(",Price:" + item.price()); } } }
<template> <section class="modules-wrap"> <!-- 搜索栏 --> <div class="search-bar"> <div class="botton-wrap"> <el-button type="primary" plain @click.native="handleBack()" icon="el-icon-back" style="margin-right: 10px">返回</el-button> 搜索引擎 <el-select v-model="params.engine_name" clearable @change="search(1)"> <el-option v-for="item in engineList" :key="item.id" :label="item.name" :value="item.value"> </el-option> </el-select> <el-input clearable style="width:200px;" v-model="params.score" placeholder="最小匹配分数"></el-input> <el-input clearable style="width:200px;" v-model="params.content" placeholder="包含内容"></el-input> <el-button class="filter-item" type="primary" @click.native="search(1)" icon="el-icon-search">搜索</el-button> </div> </div> <!-- 主内容表格 --> <el-table v-loading="loading" :data="table.data" :highlight-current-row="true" size="max" stripe tooltip-effect="dark" style="width: 100%;" @sort-change="sortChange"> <el-table-column type="expand"> <template slot-scope="props"> <el-form label-position="left" inline class="demo-table-expand"> <el-form-item label="页面链接"> <span>{{ props.row.url }}</span> </el-form-item> <br/> <el-form-item label="子链接"> <span>{{ props.row.child_url }}</span> </el-form-item> <br/> <el-form-item label="页面内容"> <span>{{ props.row.content }}</span> </el-form-item> </el-form> </template> </el-table-column> <el-table-column align="center" prop="source_engine_name" :formatter="(row, column) => formatValue(row, column, 'engineList')" label="搜索引擎" width="150"></el-table-column> <el-table-column align="center" prop="title" label="标题" width="350"> <template slot-scope="scope"> <a :href="scope.row.url" target="_blank">{{ scope.row.title }}</a> </template> </el-table-column> <el-table-column align="center" prop="parent_url" label="父级URL" width="200" :show-overflow-tooltip="true"> <template slot-scope="scope"> <a :href="scope.row.parent_url" target="_blank">{{ scope.row.parent_url }}</a> </template> </el-table-column> <el-table-column align="center" prop="small_content" label="页面内容" width="200" :show-overflow-tooltip="true"></el-table-column> <el-table-column align="center" prop="match_content" label="匹配的部分内容" width="200" :show-overflow-tooltip="true"></el-table-column> <el-table-column align="center" prop="create_date" :formatter="formatDate" label="爬取时间" sortable="custom"></el-table-column> <el-table-column align="center" prop="similar_score" label="内容关联分数" width="120" sortable="custom"></el-table-column> </el-table> <PageView :total="table.total" :page="params.page"></PageView> </section> </template> <script> // 引入依赖 import { FormatJS, PageView } from '@/components/tools' import { pageSpider } from '@/api/spider.js' export default { name: 'engine_list', components: { PageView }, mixins: [FormatJS], data() { return { loading: false, engineList: [ { value: 'BaiDu', name: '百度', }, { value: 'Bing', name: '必应', }, { value: 'ChinaSo', name: '中国搜索', }, { value: 'Google', name: '谷歌', }, { value: '360', name: '360搜索', }, { value: 'Sougou', name: '搜狗搜索', }, { value: 'Yahoo', name: '雅虎', }, { value: 'Yandex', name: '俄罗斯Yandex', } ], params: { page: 1, size: 10, score: 0.001 }, table: { data: [{}], total: 0, }, } }, created() { this.params.task_id = this.$route.query.taskId this.search() }, methods: { /** * 分页查询, 默认从第一页查询 */ search(page) { this.loading = true if (page) { this.params.page = page } pageSpider(this.deleteNullParam(this.params)) .then((r) => { this.table.data = r.data.list ? r.data.list : [] this.table.total = Number(r.data.total) this.loading = false }) .catch((error) => { this.table.data = []; }) .finally(() => { this.loading = false; }); }, // 排序事件 sortChange(column, prop, order) { if (column.order) { this.params.order_by = column.prop if (column.order == 'ascending') { this.params.order_direction = 'ASC' } else { this.params.order_direction = 'DESC' } } else { delete this.params.order_by delete this.params.order_direction } this.search(1) }, /** * 点击返回 */ handleBack() { this.$router.go(-1) }, }, } </script>
<?php use App\Models\User; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('notifications', function (Blueprint $table) { $table->id(); $table->longText('title'); $table->text('description'); $table->string('link', 255)->nullable(); $table->string('icon', 255)->nullable(); $table->string('type', 255)->index(); $table->foreignIdFor(User::class)->nullable()->constrained('users')->onDelete('cascade')->onUpdate('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('meeting_offers'); } };
@model Mcd.HospitalManagement.Web.Models.WardModel <h3>Modify Ward</h3> @using (Html.BeginForm("Edit", "Ward", FormMethod.Post, new { @id = "form" })) { @Html.AntiForgeryToken() <div class="form-horizontal"> <hr /> @Html.ValidationSummary(true) @Html.HiddenFor(model => model.Id) <div class="form-group"> @Html.LabelFor(model => model.WardNo, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.WardNo, new {@class = "form-control", @name = "WardNo" }) @Html.ValidationMessageFor(model => model.WardNo) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.WardFee, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.WardFee, new {@class = "form-control", @name = "WardFee" }) @Html.ValidationMessageFor(model => model.WardFee) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" id="submit" value="Save" class="btn btn-primary" /> <a href="~/AdminHome/Index" id="cancel" class="btn btn-primary">Cancel</a> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { <script type="text/javascript"> $(document).ready(function () { var jsonObj = $('#form').serialize(); //validation rules $("#form").validate({ rules: { "WardNo": { required: true } , "WardFee": { required: true } }, //perform an AJAX post to ajax.php submitHandler: function () { $.ajax({ type: "POST", url: '@Url.Content("~/Ward/Edit")', data: $('#form').serialize(), success: function (data) { $('#submit').hide(); $("#cancel").html('Exit'); TriggerMsg(data.Message); }, error: function (jqXHR, textStatus, errorThrown) { alert("Error: " + errorThrown + " , Please try again"); } }); return false; } }); }); function TriggerMsg(value) { alert(value); return false; } </script> }
import {useNavigation} from '@react-navigation/native'; import React, {FC} from 'react'; import styled from 'styled-components/native'; import {Icons} from '../resources'; import {Typography} from '../theme'; import {IconButton} from './Button'; interface IBasicProps { title?: string; left?: boolean; onLeftPress?: () => void; right?: any; onRightPress?: () => void; } type AppBarStyle = { backgroundColor?: string; }; type BasicProps = IBasicProps & AppBarStyle; export const Basic: FC<BasicProps> = (props) => { const {title, left, onLeftPress, right, backgroundColor} = props; const navigation = useNavigation(); const goBack = () => { navigation.goBack(); }; return ( <Container backgroundColor={backgroundColor}> <Left> {left && <IconButton icon={Icons.backArrow} width={40} height={40} onPress={onLeftPress || goBack} />} </Left> <Center> <Typography.H4>{title}</Typography.H4> </Center> <Right>{right}</Right> </Container> ); }; export const Search: FC<BasicProps> = (props) => { const {title, left, onLeftPress, right, onRightPress, backgroundColor} = props; const navigation = useNavigation(); const goBack = () => { navigation.goBack(); }; const onSearch = () => { if (onRightPress) { onRightPress(); } }; return ( <Container backgroundColor={backgroundColor}> <Left> {left && <IconButton icon={Icons.backArrow} width={40} height={40} onPress={onLeftPress || goBack} />} </Left> <Center> <Typography.H4>{title}</Typography.H4> </Center> <Right>{right && <IconButton icon={Icons.IC_SEARCH} width={40} height={40} onPress={onSearch} />}</Right> </Container> ); }; const Left = styled.View` flex: 1; `; const Right = styled.View` flex: 1; flex-direction: row-reverse; `; const Center = styled.View` flex-grow: 1; align-items: center; justify-content: center; `; const Container = styled.View` height: 56px; width: 100%; flex-direction: row; align-items: center; padding-left: 8px; padding-right: 8px; justify-content: space-between; background-color: ${(props: AppBarStyle) => (props.backgroundColor && props.backgroundColor) || 'white'}; `;
const axios = require("axios"); const config = require("./config/configs"); const FormData = require("form-data"); function getHttpHeader(accessToken) { return { Authorization: "Bearer " + accessToken, "Content-type": "application/json", }; } function printResourceData(resource) { const resourceType = resource["resourceType"]; const itemId = resource["id"]; if (resourceType === "OperationOutcome") { console.log("\t" + resource); } else { const itemId = resource["id"]; console.log("\t" + resourceType + "/" + itemId); } } function printResponseResults(response) { const responseAsJson = response.data; if (!responseAsJson.entry) { printResourceData(responseAsJson); } else { for (const item of responseAsJson.entry) { const resource = item.resource; printResourceData(resource); } } } async function getAuthToken() { try { const data = new FormData(); data.append("client_id", config.appId); data.append("client_secret", config.appSecret); data.append("grant_type", "client_credentials"); data.append("resource", config.fhirEndpoint); const response = await axios.post( config.aadTenant + config.aadTenantId + "/oauth2/token", data ); const accessToken = response.data.access_token; console.log( "\tAAD Access Token acquired: " + accessToken.substring(0, 50) + "..." ); return accessToken; } catch (error) { console.log("\tError getting token: " + error.response.status); return null; } } async function postPatient(accessToken, data) { const patientData = { resourceType: "Patient", active: true, name: [ { use: "official", family: "LastName", given: ["FirstName", "MiddleName"], }, ], telecom: [ { system: "phone", value: "(11) 99988-7766", use: "mobile", rank: 1, }, ], gender: "male", birthDate: "1974-12-25", address: [ { use: "home", type: "both", text: "534 Erewhon St PeasantVille, Rainbow, Vic 3999", line: ["534 Erewhon St"], city: "PleasantVille", district: "Rainbow", state: "Vic", postalCode: "3999", period: { start: "1974-12-25", }, }, ], }; try { const response = await axios.post( config.fhirEndpoint + "Patient", data, { headers: getHttpHeader(accessToken), } ); const resourceId = response.data.id; console.log( "\tPatient ingested: " + resourceId + ". HTTP " + response.status ); return resourceId; } catch (error) { console.log("\tError persisting patient: " + error.response.status); console.log("\tError details: " + JSON.stringify(error.response.data)); return null; } } async function printPatientInfo(patientId, accessToken) { const baseUrl = config.fhirEndpoint + "Patient/" + patientId; try { const response = await axios.get(baseUrl, { headers: getHttpHeader(accessToken), }); printResponseResults(response); return response?.data; } catch (error) { console.log("\tError getting patient data: " + error.response.status); } } async function getPatients(accessToken) { const baseUrl = config.fhirEndpoint + "Patient"; try { const response = await axios.get(baseUrl, { headers: getHttpHeader(accessToken), }); return response?.data; } catch (error) { console.log("\tError getting patient data: " + error.response.status); } } async function deletePatient(patientId, accessToken) { const baseUrl = config.fhirEndpoint + "Patient/" + patientId; try { const response = await axios.delete(baseUrl, { headers: getHttpHeader(accessToken), }); if(response.status === 204) { return null; } } catch (error) { console.log("\tError getting patient data: " + error.response.status); return error } } const seed = async () => { // Step 2 - Acquire authentication token console.log("Acquire authentication token for secure communication."); const accessToken = await getAuthToken(); if (!accessToken) { process.exit(1); } // Step 3 - Insert Patient console.log("Persist Patient data."); const patientId = await postPatient(accessToken); if (!patientId) { process.exit(1); } // Step 6 - Print Patient info console.log("Query Patient's data."); printPatientInfo(patientId, accessToken); }; // seed(); module.exports = { printPatientInfo, postPatient, getAuthToken, getPatients, deletePatient };
//给你一个字符串 s ,仅反转字符串中的所有元音字母,并返回结果字符串。 // // 元音字母包括 'a'、'e'、'i'、'o'、'u',且可能以大小写两种形式出现。 // // // // 示例 1: // // //输入:s = "hello" //输出:"holle" // // // 示例 2: // // //输入:s = "leetcode" //输出:"leotcede" // // // // 提示: // // // 1 <= s.length <= 3 * 10⁵ // s 由 可打印的 ASCII 字符组成 // // Related Topics 双指针 字符串 👍 203 👎 0 package main import "strings" //leetcode submit region begin(Prohibit modification and deletion) func reverseVowels(s string) string { t, n := []rune(s), len(s) i, j := 0, n-1 for i < j { for i < n && !strings.ContainsRune("aeiouAEIOU", t[i]) { i++ } for j >= 0 && !strings.ContainsRune("aeiouAEIOU", t[j]) { j-- } if i < j { t[i], t[j] = t[j], t[i] i++ j-- } } return string(t) } //leetcode submit region end(Prohibit modification and deletion)
import { user } from '../models/user.model.js'; import bcrypt from 'bcryptjs'; import { createAccessToken } from '../libs/jwt.js'; import { Op } from 'sequelize'; export const getUsers = async (req, res) => { try { const users = await user.findAll({ where: { TypeUser_ID: 1 } }); res.json(users); } catch (error) { return res.status(500).json({ message: error.message }); } }; export const getUser = async (req, res) => { const { id } = req.params try { const getUser = await user.findOne({ where: { ID_User: id } }); if (!getUser) return res.status(404).json({ message: 'El usuario no existe' }) res.json(getUser); } catch (error) { return res.status(500).json({ message: error.message }); } }; export const checkForDuplicates = async (req, res, next) => { try { const { Document, Email } = req.body; const existingUser = await user.findOne({ where: { [Op.or]: [{ Document }, { Email }], }, }); if (existingUser) { return res.status(400).json({ error: 'Ya existe un usuario con la misma cédula o correo electrónico.', }); } next(); } catch (error) { return res.status(500).json({ message: error.message }); } }; export const createUser = async (req, res) => { const { Type_Document, Document, Name_User, LastName_User, Password, Email, Role_ID } = req.body; try { const passwordHast = await bcrypt.hash(Password, 10) const newUser = await user.create({ Type_Document, Document, Name_User, LastName_User, Email, Password: passwordHast, Restaurant: null, TypeUser_ID: 1, Role_ID, State: true }); const token = await createAccessToken({ id: newUser.id }); res.cookie('token', token); res.json({ message: "Usuario creado correctamente", Nombre: newUser.Name_User, }); } catch (error) { return res.status(500).json({ message: error.message }); } }; export const updateUser = async (req, res) => { const { id } = req.params try { const { Type_Document, Document, LastName_User, Name_User, Email, Role_ID } = req.body const updateUser = await user.findByPk(id) updateUser.Type_Document = Type_Document updateUser.Document = Document updateUser.Name_User = Name_User updateUser.LastName_User = LastName_User updateUser.Role_ID = Role_ID updateUser.Email = Email await updateUser.save(); return res.json(updateUser); } catch (error) { return res.status(500).json({ message: error.message }); } }; export const toggleUserStatus = async (req, res) => { const { id } = req.params; try { const statusUser = await user.findOne({ where: { ID_User: id }, }); if (!statusUser) { return res.status(404).json({ message: 'Usuario no encontrado' }); }; statusUser.State = !statusUser.State; await statusUser.save(); return res.json(statusUser); } catch (error) { return res.status(500).json({ message: error.message }); } }; export const deleteUser = async (req, res) => { const { id } = req.params try { await user.destroy({ where: { ID_User: id }, }); return res.sendStatus(204); } catch (error) { return res.status(500).json({ message: error.message }); } }; // --------------------------- Mesero ------------------------------------- // export const getWaiters = async (req, res) => { try { const users = await user.findAll({ where: { TypeUser_ID: 2 } }); res.json(users); } catch (error) { return res.status(500).json({ message: error.message }); } }; export const getWaiter = async (req, res) => { const { id } = req.params try { const getUser = await user.findOne({ where: { ID_User: id } }); if (!getUser) return res.status(404).json({ message: 'El usuario no existe' }) res.json(getUser); } catch (error) { return res.status(500).json({ message: error.message }); } }; export const createWaiter = async (req, res) => { const { Type_Document, Document, Name_User, LastName_User, Restaurant } = req.body; try { const newUser = await user.create({ Type_Document, Document, Name_User, LastName_User, Restaurant, TypeUser_ID: 2, Email: null, Password: null, Role_ID: null, State: true }); res.json({ message: "Mesero creado correctamente", Nombre: newUser.Name_User, }); } catch (error) { return res.status(500).json({ message: error.message }); } }; export const duplicateWaiter = async (req, res, next) => { try { const { Document } = req.body; const existingWaiter = await user.findOne({ where: { [Op.or]: [{ Document }], }, }); if (existingWaiter) { return res.status(400).json({ error: 'Ya existe un usuario con la misma cédula', }); } next(); } catch (error) { return res.status(500).json({ message: error.message }); } };
#' number of KPIs reported for each programme and last year they reported. #' #' @param x summary_main target in pipeline transform_prog_kpi_count <- function(x, include_last_year = T){ if(include_last_year == T) { y <- x %>% select(-contains("disagg")) %>% filter(achieved_total > 0 | is.na(achieved_total)) %>% mutate_all( ~replace_na(.,-Inf)) %>% mutate(latest_year_reported = names( select(., intersect(matches("/"), starts_with("achieved_"))) )[max.col(select(., intersect(matches("/"), starts_with("achieved_"))) != 0, 'last')] ) %>% group_by(programme_title, programme_id, latest_year_reported) %>% summarise(kpi_ids = str_c(unique(kpi_id), collapse=", ")) %>% mutate(count = str_count(kpi_ids, ",")+1) } else { y <- x %>% select(-contains("disagg")) %>% filter(achieved_total > 0 | is.na(achieved_total)) %>% group_by(programme_title, programme_id) %>% summarise(kpi_ids = str_c(unique(kpi_id), collapse=", ")) %>% mutate(count = str_count(kpi_ids, ",")+1) } return(y) }
<template> <div class="w-60 h-32 bg-gray-800 rounded-md overflow-hidden border-l-4 border-purple-700"> <div class="bg-gray-700 w-full h-12 text-sm text-white font-bold pl-3 overflow-hidden flex flex-col justify-evenly"> <p class="whitespace-nowrap text-ellipsis overflow-hidden">Simulator - {{ accountData.owner }}</p> <p class="whitespace-nowrap text-ellipsis overflow-hidden text-xs"> Total Balance {{ accountData.balance }} {{ accountData.currency }} </p> </div> <div class="grid grid-cols-2 gap-1 pt-2 w-full px-2"> <div class="text-gray-400 text-xs col-span-2">Open PnL</div> <div class="text-red-400 text-xs font-bold">-{{ accountData.open }} {{ accountData.currency }}</div> <div class="text-red-400 text-xs font-bold place-self-end">-{{ accountData.openPercent }}%</div> <div class="flex w-max"> <div class="text-gray-400 text-xs mr-1">Daily PnL</div> <div class="text-green-400 text-xs font-bold place-self-end"> {{ accountData.dailyResult }} {{ accountData.currency }} </div> </div> <div class="text-green-400 text-xs font-bold place-self-end">{{ accountData.dailyPercent }}%</div> </div> </div> </template> <script setup lang="ts"> import { faker } from '@faker-js/faker'; import { reactive } from 'vue'; const accountData = reactive({ owner: faker.name.fullName(), currency: faker.finance.currencyCode(), balance: faker.commerce.price(0, 1000, 2), dailyResult: faker.commerce.price(0, 1000, 2), open: faker.commerce.price(0, 500, 2), openPercent: faker.commerce.price(0, 5, 2), dailyPercent: faker.commerce.price(0, 10, 2), }); </script>
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; /** * @dev Abstract contract for managing a multi-signature wallet. */ abstract contract OwnerManager { mapping(address => bool) public owners; uint256 public threshold; uint256 public ownerCount; bool private isSetup; event AddOwner(address indexed owner); event RemoveOwner(address indexed owner); event ChangeThreshold(uint256 threshold); /** * @dev Sets up the owners of the multi-signature wallet. * * Requirements: * - Can only be called once in the constructor. * - each address cannot be zero address. * - threshold cannot be zero. * - _owners cannot be empty. * - threshold cannot be greater than the number of owners * * @param _owners The owners of the multi-signature wallet. * @param _threshold The threshold of the multi-signature wallet. * */ function setupOwners( address[] memory _owners, uint256 _threshold ) internal { require(!isSetup, "OwnerManager: already setup"); require(_owners.length > 0, "OwnerManager: no owners"); require( _owners.length > 1, "OwnerManager: must have at least two owners" ); require( _owners.length > _threshold, "OwnerManager: owner must be at least threshold" ); require(_threshold > 0, "OwnerManager: threshold cannot be zero"); for (uint256 i; i < _owners.length; i++) { require( _owners[i] != address(0), "OwnerManager: cannot be zero address" ); require(!isOwner(_owners[i]), "OwnerManager: owner already exists"); owners[_owners[i]] = true; } ownerCount = _owners.length; threshold = _threshold; isSetup = true; } /** * @dev Adds an owner to the multi-signature wallet. * * Requirements: * - _owner cannot be zero address * - _owner cannot already be an owner of the multi-signature wallet * - only the owner of the multi-signature wallet can add a new owner * * @param _owner The owner to add. * * Emits: * - AddOwner(address indexed owner) */ function addOwner(address _owner) external onlyOwner { require(_owner != address(0), "OwnerManager: cannot be zero address"); require(!isOwner(_owner), "OwnerManager: owner already exists"); owners[_owner] = true; ownerCount++; emit AddOwner(_owner); } /** * @dev Removes an owner from the multi-signature wallet. * * Requirements: * - _owner cannot be zero address * - _owner must be an owner of the multi-signature wallet * - new ownerCount must be greater than or equal to threshold * - only the owner of the multi-signature wallet can remove an owner * * @param _owner The owner to remove. * * Emits: * - RemoveOwner(address indexed owner) */ function removeOwner(address _owner) external onlyOwner { require(_owner != address(0), "OwnerManager: cannot be zero address"); require(isOwner(_owner), "OwnerManager: owner not found"); require( ownerCount - 1 > 1, "OwnerManager: new owner count must be at least two" ); require( ownerCount - 1 >= threshold, "OwnerManager: new owner count must be greater than or equal to threshold" ); owners[_owner] = false; ownerCount--; emit RemoveOwner(_owner); } /** * @dev Swaps an owner from the multi-signature wallet. * * Requirements: * - _oldOwner cannot be zero address * - _newOwner cannot be zero address * - _oldOwner must be an owner of the multi-signature wallet * - _newOwner must not be an owner of the multi-signature wallet * - only the owner of the multi-signature wallet can remove an owner * * @param _oldOwner The owner to swap. * @param _newOwner The owner to swap to. * * Emits: * - AddOwner(address indexed owner) * - RemoveOwner((address indexed owner) */ function swapOwner( address _oldOwner, address _newOwner ) external onlyOwner { require( _oldOwner != _newOwner, "OwnerManager: old and new owners are the same" ); require( _oldOwner != address(0), "OwnerManager: old owner cannot be zero address" ); require( _newOwner != address(0), "OwnerManager: new owner cannot be zero address" ); require(isOwner(_oldOwner), "OwnerManager: old owner not found"); require(!isOwner(_newOwner), "OwnerManager: new owner already exists"); owners[_newOwner] = true; owners[_oldOwner] = false; emit AddOwner(_newOwner); emit RemoveOwner(_oldOwner); } /** * @dev Changes the threshold of the multi-signature wallet. * * Requirements: * - _threshold cannot be zero * - new threshold must be less than or equal to ownerCount * - new threshold must be different from the current threshold * - only the owner of the multi-signature wallet can remove an owner * * @param _threshold The new threshold. * * Emits: * - ChangeThreshold(uint256 threshold) */ function changeThreshold(uint256 _threshold) external onlyOwner { require(_threshold > 0, "OwnerManager: threshold cannot be zero"); require( ownerCount >= _threshold, "OwnerManager: threshold must be less than or equal to ownerCount" ); require(threshold != _threshold, "OwnerManager: threshold unchanged"); require(_threshold > 1, "OwnerManager: threshold must be at least two"); threshold = _threshold; emit ChangeThreshold(_threshold); } /** * @dev Checks if an _owner is an owner of the multi-signature wallet. */ function isOwner(address _owner) public view returns (bool) { return owners[_owner]; } /** * @dev Checks if the caller is an owner of the multi-signature wallet. */ modifier onlyOwner() { require( isOwner(msg.sender), "OwnerManager: only owner can perform this action" ); _; } }
#ifndef POULTRYCHEF_H #define POULTRYCHEF_H #include "ChefHandler.h" /** * @class PoultryChef * @brief Represents a Poultry Chef responsible for preparing Poultry. */ class PoultryChef: public ChefHandler { public: /** * @brief Construct a new PoultryChef object. * * This constructor initializes a new instance of the PoultryChef class. */ PoultryChef(); /** * @brief Destroy the PoultryChef object. * * This virtual destructor is responsible for cleaning up any resources * associated with the PoultryChef object. */ virtual ~PoultryChef(); /** * @brief Handle a food order. * * This function is responsible for preparing Poultry if it is found in the order. * * @param order An order object representing the customer order. */ void handleOrder(Order* order); }; #endif
import { Sequelize } from 'sequelize' import { TaskModel } from './TaskModel' import { Request, Response } from 'express' import { v4 as uuidv4 } from 'uuid' class TaskController { async index(req: Request, res: Response) { try { const tasks = await TaskModel.findAll() return res.json({ data: tasks, message: 'Tasks successfully retrieved.', }) } catch (error) { return res.status(500).send('Failed to retrieve tasks') } } async show(req: Request, res: Response) { try { const { id } = req.params const data = await TaskModel.findOne({ where: { id }, }) if (!data) { return res.status(404).send('Task not found') } return res.json({ data: data.toJSON(), message: 'Task successfully retrieved.', }) } catch (error) { return res.status(500).send('Failed to create') } } async save(req: Request, res: Response) { try { const data = await TaskModel.create({ ...req.body, id: uuidv4(), }) return res.json({ data: data.toJSON(), message: 'Task successfully created.', }) } catch (error) { return res.status(500).send('Failed to create') } } async update(req: Request, res: Response) { try { const data = await TaskModel.update( { ...req.body }, { where: { id: req.params.id } } ) return res.json({ message: 'Task successfully updated.', }) } catch (error) { return res.status(500).send('Failed to update') } } async updateStatus(req: Request, res: Response) { try { const data = await TaskModel.update( { isDone: Sequelize.literal('NOT isDone') }, { where: { id: req.params.id } } ) return res.json({ message: 'Task status successfully updated.' }) } catch (error) { return res.status(500).send('Failed to update') } } async delete(req: Request, res: Response) { try { const data = await TaskModel.destroy({ where: { id: req.params.id } }) return res.json({ message: 'Task successfully deleted.', }) } catch (error) { return res.status(500).send('Failed to delete') } } } export default new TaskController()
#' Typeset multiple choice questions #' #' Formats multiple-choice questions for *MOSAIC Calculus* #' #' @param prompt Character string prompt #' @param \dots fixed-choice possibilities #' @param item_label Character string how to label each individual question #' @param out_format Either `"Markdown"` or `"PDF"` #' #' @rdname askMC #' @export MC_simple_format <- function(prompt="The question prompt", ..., item_label="Part", out_format = c("Markdown", "PDF")) { out_format <- match.arg(out_format) out <- paste(prompt, "\n\n") answer_table <- dots_to_answers(..., right_one = right_one, allow_multiple_correct = allow_multiple_correct) choices <- format_choices_simple( answer_table, width=40, out_format = out_format, seed=ifelse(random_answer_order, 435, NA)) Res <- knitr::asis_output(paste0( "\n", "\t**", item_label, MC_counter$get(), "** ", out, "\n", paste0(choices, collapse="\n"), "\n")) return(Res) } #' @rdname askMC #' @export askMC <- function (prompt = "The question prompt", ..., id = NULL, right_one = NULL, inline = FALSE, random_answer_order = FALSE, allow_retry = TRUE, correct = "Right!", incorrect = "Sorry.", message = NULL, post_message = NULL, submit_button = "Check answer", try_again_button = "Try again", allow_multiple_correct = FALSE, show_feedback=TRUE, out_format=c("PDF", "Markdown", "GradeScope"), item_label = "Part ", show_answers=FALSE) { out_format <- match.arg(out_format) out <- paste(prompt, "\n\n") answer_table <- dots_to_answers(..., right_one = right_one, allow_multiple_correct = allow_multiple_correct) ## GradeScope output module if (out_format == "GradeScope") { answers <- paste0("(", ifelse(answer_table$correct, "x ", " "), ") ", fix_dollar_signs(answer_table$item), collapse="\n") feedback_for_correct <- answer_table$feedback[answer_table$correct] if (nchar(gsub(" *", "", feedback_for_correct)) == 0) feedback_for_correct <- random_success() feedback <- paste0("[[", paste(fix_dollar_signs(feedback_for_correct), collapse = "\n"), "]]\n") total <- paste(fix_dollar_signs(out), answers, feedback, sep="\n\n") Res <- knitr::asis_output(paste0("<pre>", total, "\n</pre>\n")) return(Res) } ## End of GradeScope module ## latex/PDF output module if (out_format == "PDF") { choices <- format_choices_simple( answer_table, width=40, seed=ifelse(random_answer_order, 435, NA)) Res <- knitr::asis_output(paste0( "\n", "\t**", item_label, MC_counter$get(), "** ", out, "\n", paste0(choices, collapse="\n"), "\n")) return(Res) } ## End of latex/PDF module # # make all feedback strings the same length, so items will be # # evenly spaced # raw_feedback <- answer_table$feedback # # raw_feedback <- stringr::str_pad(raw_feedback, # # max(nchar(raw_feedback)), # # side="right", pad=".") # pad="‥") # # # place_inline <- inline || (sum(nchar(answer_table$item) + nchar(raw_feedback)) < 80) # # if (place_inline) { # answer_labels <- paste0(rep("    ", nrow(answer_table))) # newline <- "   " # success <- "$\\heartsuit\\ $" # container <- "span" # } else { # answer_labels <- paste0(answer_labels, ". ")[1:nrow(answer_table)] # newline <- " \n" # success <- paste0(random_success(), " ") # container <- "span" # # } # # if (show_feedback) { # feedback <- paste0("<", container, " class='mcanswer'>", # ifelse(answer_table$correct, success, "︎✘ "), # raw_feedback) # haven't yet closed <span> # feedback <- paste0(feedback, "</", container, "></span>") # close it up # } else { # feedback <- "" # } # # # answers <- paste0(answer_labels[1:nrow(answer_table)], # "<span class='Zchoice'>", # answer_table$item, # feedback, # collapse = newline) # # knitr::asis_output(paste0( # "**Question ", MC_counter$get(), "** ", # out, answers)) } # For Gradescope output #' @rdname askMC #' @export askGS <- function(...) { askMC(..., out_format = "GradeScope") } #' @export askPDF <- function(...) { askMC(..., out_format = "PDF") } #' @rdname askMC #' @export #' # fix the dollar signs for GradeScope fix_dollar_signs <- function(str) { str <- gsub("\\${1}", "\\$\\$", str) str <- gsub("\\${4}", "\\$\\$\\$", str) str } format_choices_simple <- function(answer_table, width=40, seed=NA, out_format="Markdown") { Ans <- tibble::tibble( text = answer_table$item ) if (!is.na(seed)) { set.seed(seed) Ans <- sample_n(Ans, size=nrow(Ans)) } if (max(nchar(Ans$text), na.rm = TRUE) > width/2) { # lay them out one to a line paste(paste0(letters[1:nrow(Ans)], ". ", Ans$text), collapse="\n") } else { spacer <- ifelse(out_format=="Markdown", "&emsp;", "\\hspace{3em}") paste(Ans$text, collapse= spacer) } } # split_rows <- function(nchars, max_width = 25) { # row <- 1 # rows <- rep(1, length(nchars)) # sofar <- 0 # for (k in 1:length(nchars)) { # if (sofar + nchars[k] < max_width) { # sofar <- sofar + nchars[k] # rows[k] <- row # } else { # row <- row+1 # sofar <- nchars[k] # rows[k] <- row # } # } # rows # } # format_answers_markdown <- function(answer_table, width=40, seed=NA, padding=2) { # Ans <- tibble::tibble( # text = answer_table$item # ) # cell_width <- max(nchar(Ans$text)) + 2 # Ans <- Ans %>% mutate(nletters = cell_width) # making them all equally wide # if (!is.na(seed)) { # set.seed(seed) # Ans <- sample_n(Ans, size=nrow(Ans)) # } # if (any(Ans$nletters > width/2)) { # # lay them out one to a line # paste(paste0(letters[1:nrow(Ans)], ". ", Ans$text), collapse="\n") # } else { # # break them up into groups according to length # Ans$group=split_rows(Ans$nletters, width) # # Ans <- Ans %>% group_by(group) |> # mutate(col=row_number()) |> # ungroup() # Mat <- matrix("", ncol=max(Ans$col), nrow=max(Ans$group)) # for (k in 1:nrow(Ans)) { # Mat[(Ans$group[k]), (Ans$col[k])] <- Ans$text[k] # } # if (knitr::is_latex_output()) format <- "latex" # else if (knitr::is_html_output()) format <- "html" # else format <- "latex" # row_width <- paste0(cell_width, "em") # Res <- knitr::kable(Mat, format=format, align="c") %>% # kableExtra::kable_paper("hover", full_width = FALSE) # if (knitr::is_latex_output()) { # # strip off the tabular environment # Res %>% # gsub("\\end{table}", "", ., fixed=TRUE) %>% # gsub("\\begin{table}", "", ., fixed=TRUE) %>% # gsub("\\centering", "", ., fixed=TRUE) # } else { # Res %>% # kableExtra::column_spec(1:ncol(Mat), width = row_width, border_left=TRUE) # } # # } # } # return a data frame with one row for each element of ... dots_to_answers <- function(..., right_one = "", allow_multiple_correct = FALSE) { dots <- list(...) if (length(dots) == 1) { if (is.list(dots[[1]])) choices <- dots[[1]] else if (is.vector(dots[[1]])) { # it's a character or numerical vector choices <- as.list(rep("", length(dots[[1]]))) names(choices) <- dots[[1]] } } else { choices <- dots } display <- names(choices) no_feedback <- if (is.null(display)) { # no names whatsoever display <- unlist(choices) choices <- as.list(rep("", length(display))) names(choices) <- display NULL } else which(display == "") # if it's not named, use the value as the name if (length(no_feedback) > 0) { display[no_feedback] <- choices[no_feedback] choices[no_feedback] <- "" # blank feedback } names(choices) <- display # update the names feedback <- unlist(choices) names(feedback) <- NULL # store as a data frame answers <- tibble(item=names(choices), feedback=feedback) if (!is.null(right_one)) answers$correct <- answers$item %in% right_one else answers$correct <- grepl("^\\+.*\\+$", answers$item) answers$item[answers$correct] <- gsub("^\\+(.*)\\+$", "\\1", answers$item[answers$correct]) if (sum(answers$correct) == 0) stop("Must provide one correct answer.") if (sum(answers$correct) > 1 && !allow_multiple_correct) stop("Must give only one correct answer.") answers } #' @rdname askMC #' @export format_latex_answers <- function(AT, linechars=50) { } #' @rdname askMC #' @export letter_counter <- function() { counter <- 0 uppercase <- c(LETTERS, paste0(LETTERS, 1), paste0(LETTERS, 2), paste0(LETTERS, 3), paste0(LETTERS, 4), paste0(LETTERS, 5)) lowercase <- tolower(uppercase) numbers <- 1:5000 ROMAN <- utils::as.roman(numbers) roman <- tolower(ROMAN) names <- uppercase res <- list() res$reset <- function(s = 0, labels=c("uppercase", "lowercase", "numbers", "ROMAN", "roman")) { labels <- match.arg(labels) names <<- parent.env(environment())[[labels]] counter <<- s } res$get <- function() { counter <<- counter+1 names[counter %% length(names)] # never run out } res }
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import pages.*; import utilities.DriverManager; public class CheckoutOverviewTests extends BaseTest { @Test public void verifyCheckOutWithCorrectValuesAndSelectedProducts() { LoginPage loginPage = new LoginPage(DriverManager.getDriver().driver); loginPage.setUserNameTextBox("standard_user"); loginPage.setPasswordTextBox("secret_sauce"); loginPage.clickOnLoginButton(); HomePage homePage = new HomePage(DriverManager.getDriver().driver); homePage.addProductToCart("Sauce Labs Fleece Jacket"); homePage.addProductToCart("Sauce Labs Bike Light"); homePage.clickOnShoppingCartButton(); YourCartPage yourCartPage = new YourCartPage(DriverManager.getDriver().driver); yourCartPage.clickOnCheckoutButton(); CheckoutInformationPage checkoutPage = new CheckoutInformationPage(DriverManager.getDriver().driver); checkoutPage.setFistNameTextBox("FirstName"); checkoutPage.setLastNameTextBox("LastName"); checkoutPage.setPostalCodeTextBox("1233"); checkoutPage.clickOnContinueButton(); CheckoutOverviewPage checkoutOverviewPage = new CheckoutOverviewPage(DriverManager.getDriver().driver); Assertions.assertTrue(checkoutOverviewPage.isButtonFinishDisplayed()); } @Test public void verifyCheckoutOverviewProducts() { LoginPage loginPage = new LoginPage(DriverManager.getDriver().driver); loginPage.setUserNameTextBox("standard_user"); loginPage.setPasswordTextBox("secret_sauce"); loginPage.clickOnLoginButton(); HomePage homePage = new HomePage(DriverManager.getDriver().driver); homePage.addProductToCart("Sauce Labs Fleece Jacket"); homePage.addProductToCart("Sauce Labs Bike Light"); homePage.clickOnShoppingCartButton(); YourCartPage yourCartPage = new YourCartPage(DriverManager.getDriver().driver); yourCartPage.clickOnCheckoutButton(); CheckoutInformationPage checkoutPage = new CheckoutInformationPage(DriverManager.getDriver().driver); checkoutPage.setFistNameTextBox("FirstName"); checkoutPage.setLastNameTextBox("LastName"); checkoutPage.setPostalCodeTextBox("1233"); checkoutPage.clickOnContinueButton(); CheckoutOverviewPage checkoutOverviewPage = new CheckoutOverviewPage(DriverManager.getDriver().driver); Assertions.assertTrue(checkoutOverviewPage.isProductDisplayed("Sauce Labs Fleece Jacket")); Assertions.assertTrue(checkoutOverviewPage.isProductDisplayed("Sauce Labs Bike Light")); } @Test public void cancelCheckOut() { LoginPage loginPage = new LoginPage(DriverManager.getDriver().driver); loginPage.setUserNameTextBox("standard_user"); loginPage.setPasswordTextBox("secret_sauce"); loginPage.clickOnLoginButton(); HomePage homePage = new HomePage(DriverManager.getDriver().driver); homePage.addProductToCart("Sauce Labs Fleece Jacket"); homePage.addProductToCart("Sauce Labs Bike Light"); homePage.clickOnShoppingCartButton(); YourCartPage yourCartPage = new YourCartPage(DriverManager.getDriver().driver); yourCartPage.clickOnCheckoutButton(); CheckoutInformationPage checkoutPage = new CheckoutInformationPage(DriverManager.getDriver().driver); checkoutPage.setFistNameTextBox("FirstName"); checkoutPage.setLastNameTextBox("LastName"); checkoutPage.setPostalCodeTextBox("1233"); checkoutPage.clickOnContinueButton(); CheckoutOverviewPage checkoutOverviewPage = new CheckoutOverviewPage(DriverManager.getDriver().driver); checkoutOverviewPage.clickOnCancelButton(); Assertions.assertTrue(homePage.isComboBoxDisplayed()); } @Test public void verifyPricesOfAddedProducts() { LoginPage loginPage = new LoginPage(DriverManager.getDriver().driver); loginPage.setUserNameTextBox("standard_user"); loginPage.setPasswordTextBox("secret_sauce"); loginPage.clickOnLoginButton(); HomePage homePage = new HomePage(DriverManager.getDriver().driver); homePage.addProductToCart("Sauce Labs Fleece Jacket"); homePage.addProductToCart("Sauce Labs Bike Light"); homePage.addProductToCart("Sauce Labs Onesie"); double price1i = homePage.getPriceAddedProduct("Sauce Labs Fleece Jacket"); double price2i = homePage.getPriceAddedProduct("Sauce Labs Bike Light"); double price3i = homePage.getPriceAddedProduct("Sauce Labs Onesie"); homePage.clickOnShoppingCartButton(); YourCartPage yourCartPage = new YourCartPage(DriverManager.getDriver().driver); yourCartPage.clickOnCheckoutButton(); CheckoutInformationPage checkoutPage = new CheckoutInformationPage(DriverManager.getDriver().driver); checkoutPage.setFistNameTextBox("FirstName"); checkoutPage.setLastNameTextBox("LastName"); checkoutPage.setPostalCodeTextBox("1233"); checkoutPage.clickOnContinueButton(); CheckoutOverviewPage checkoutOverviewPage = new CheckoutOverviewPage(DriverManager.getDriver().driver); double subTotal = checkoutOverviewPage.getSubTotal(); Assertions.assertEquals(price1i + price2i + price3i, subTotal); } }
<script setup lang="ts"> import type { HillDef } from "@/stores/station"; import { defineProps, ref } from "vue"; import { EventsOn } from "../../wailsjs/runtime/runtime"; import { SetSignal } from "../../wailsjs/go/main/App"; type Props = { hill: HillDef; }; const { hill } = defineProps<Props>(); const setState = (signal: string) => SetSignal(hill, signal); const signal = ref('Off'); EventsOn("message", (message: string) => { if (!message.includes(`${hill.signal}:`)) return const splitted = message.split(':') if (splitted.length !== 2) return signal.value = splitted[1] }); </script> <template> <div class="w-100 rounded overflow-hidden shadow-md mb-5"> <div class="px-6 py-4"> <div class="font-bold text-xl mb-2 border-b-2"> Main signal: {{ hill.signal }} </div> </div> <div class="px-6 pt-4 pb-2"> <button @click="setState('Off')" class="inline-block rounded-full px-3 py-1 font-semibold mr-2 mb-2" :class="signal == 'Off' ? 'bg-green-300' : 'text-gray-700 bg-gray-200'" > Rt0 - Off </button> <button @click="setState('Rt1')" class="inline-block rounded-full px-3 py-1 font-semibold mr-2 mb-2" :class="signal == 'Rt1' ? 'bg-green-300' : 'text-gray-700 bg-gray-200'" > Rt1 - Push forbidden </button> <button @click="setState('Rt2')" class="inline-block rounded-full px-3 py-1 font-semibold mr-2 mb-2" :class="signal == 'Rt2' ? 'bg-green-300' : 'text-gray-700 bg-gray-200'" > Rt2 - Push slowly </button> <button @click="setState('Rt3')" class="inline-block rounded-full px-3 py-1 font-semibold mr-2 mb-2" :class="signal == 'Rt3' ? 'bg-green-300' : 'text-gray-700 bg-gray-200'" > Rt3 - Push </button><button @click="setState('Rt4')" class="inline-block rounded-full px-3 py-1 font-semibold mr-2 mb-2" :class="signal == 'Rt4' ? 'bg-green-300' : 'text-gray-700 bg-gray-200'" > Rt4 - Reverse </button><button @click="setState('Rt5')" class="inline-block rounded-full px-3 py-1 font-semibold mr-2 mb-2" :class="signal == 'Rt5' ? 'bg-green-300' : 'text-gray-700 bg-gray-200'" > Rt5 - Push towards hill </button> </div> </div> </template>
<!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>array練習</title> </head> <body> <script> //練習一 //建立自己的array let myArr=['a','b','c','d']; //練習二 //用key & value console.log出來 console.log(myArr[0]); //a console.log(myArr[1]); //b console.log(myArr[2]); //c console.log(myArr[3]); //d //練習三 //foreach 抓出全部的值 myArr.forEach(function(value,key){ console.log(value); }); //push 增加一個元素在最後面 myArr.push('e'); console.log(myArr); //--------------------------------- let numArr=[1,3,5,7,9]; let sum=0; numArr.forEach(function(value,key){ sum=sum+value; console.log(sum); }) //---------------------------------- //pop 減少最後一個元素 let popArr=[1,3,5,7,9]; popArr.pop(); console.log('popArr',popArr); console.log(popArr[3]); //顯示7 popArr[4]=9; //直接更改一個9到[4] console.log(popArr); //1,3,5,7 console.log(popArr[4]);//顯示9 //shift/unshift 刪除/增加第一個元素 let shiftArr=[1,2,3,4,5]; shiftArr.shift(); //刪除1 console.log(shiftArr); //2,3,4,5 shiftArr.unshift(9); //增加9到第一個 console.log(shiftArr);// 9,2,3,4,5 //splice 刪除(指定位置)元素 let spliceArr=[1,2,3,4,5]; // spliceArr.splice(3); //從第[3]個(包含)往後刪除(等於把4,5刪除) spliceArr.splice(1,2); //從[1]往後刪除2個(等於把2,3刪除) console.log(spliceArr); //array toString 陣列變字串 let stringArr=['a','b','c']; let getString=stringArr.toString(); console.log(getString); //把陣列輸出字串 //concact 合併陣列 let a1=[1,2,3]; let a2=[4,5,6]; let a3=a1.concat(a2); console.log(a3); //... 分散運算子 spread operator let aa=['a','b','c']; let bb=['d','e','f']; let a4=[...aa,...bb];//也等於concact合併 console.log(a4); //indexOf() let arrIndexOf=['a','b','c']; console.log('arrIndexOf',arrIndexOf); console.log(arrIndexOf.indexOf('a')); //0 console.log(arrIndexOf.indexOf('b')); //1 console.log(arrIndexOf.indexOf('c')); //2 console.log(arrIndexOf.indexOf('dog')); //-1 不存在 </script> </body> </html>
push = require 'push' Class = require 'class' require 'Player' require 'Ball' WINDOW_WIDTH = 1280 WINDOW_HEIGHT = 720 VIRTUAL_WIDTH = 432 VIRTUAL_HEIGHT = 243 PLAYER_SPEED = 8 gameState = 'start' function love.load() love.graphics.setDefaultFilter('nearest', 'nearest') love.window.setTitle('Pong') math.randomseed(os.time()) mediumFont = love.graphics.newFont('font.ttf', 10) largeFont = love.graphics.newFont('font.ttf', 20) love.graphics.setFont(mediumFont) push:setupScreen(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, WINDOW_WIDTH, WINDOW_HEIGHT, { fullscreen = false, resizable = true, vsync = true }) sounds = { ['hit'] = love.audio.newSource('sounds/hit.wav', 'static'), ['score'] = love.audio.newSource('sounds/score.wav', 'static') } player1 = Player(20, VIRTUAL_HEIGHT / 2 - 12) player2 = Player((VIRTUAL_WIDTH - 20) - 8, VIRTUAL_HEIGHT / 2 - 12) server = 1 winner = 0 player1Score = 0 player2Score = 0 ball = Ball(VIRTUAL_WIDTH / 2 - 2, VIRTUAL_HEIGHT / 2 - 2) end function love.resize(weight, height) push:resize(weight, height) end function love.keypressed(key) if key == 'escape' then love.event.quit() end if key == 'enter' or key == 'return' then if gameState == 'start' then gameState = 'serve' elseif gameState == 'serve' then gameState = 'play' elseif gameState == 'win' then gameState = 'start' winner = 0 player1Score = 0 player2Score = 0 end end end function love.update(dt) if gameState == 'serve' then ball.dy = math.random(-60, 60) if server == 1 then ball.dx = math.random(120, 210) else ball.dx = -math.random(120, 210) end elseif gameState == 'play' then if ball:collides(player1) then ball.dx = -ball.dx * 1.03 ball.x = player1.x + 5 if ball.dy < 0 then ball.dy = -math.random(10, 150) else ball.dy = math.random(10, 150) end sounds['hit']:play() end if ball:collides(player2) then ball.dx = -ball.dx * 1.03 ball.x = player2.x - 5 if ball.dy < 0 then ball.dy = -math.random(10, 150) else ball.dy = math.random(10, 150) end sounds['hit']:play() end if ball.y <= 0 then ball.y = 0 ball.dy = -ball.dy sounds['hit']:play() end if ball.y >= VIRTUAL_HEIGHT - 4 then ball.y = VIRTUAL_HEIGHT - 4 ball.dy = -ball.dy sounds['hit']:play() end if ball.x < 0 then server = 1 player2Score = player2Score + 1 sounds['score']:play() if player2Score == 10 then winner = 2 gameState = 'win' else gameState = 'serve' end ball:reset() end if ball.x > VIRTUAL_WIDTH then server = 2 player1Score = player1Score + 1 sounds['score']:play() if player1Score == 10 then winner = 1 gameState = 'win' else gameState = 'serve' end ball:reset() end ball:update(dt) end if love.keyboard.isDown('w') then player1.y = math.max(player1.y - PLAYER_SPEED, 0) elseif love.keyboard.isDown('s') then player1.y = math.min(player1.y + PLAYER_SPEED, VIRTUAL_HEIGHT - player1.height) end if love.keyboard.isDown('up') then player2.y = math.max(player2.y - PLAYER_SPEED, 0) elseif love.keyboard.isDown('down') then player2.y = math.min(player2.y + PLAYER_SPEED, VIRTUAL_HEIGHT - player2.height) end end function love.draw() push:start() love.graphics.clear(40/255, 40/255, 50/255, 255/255) displayScore() if gameState == 'start' then love.graphics.setFont(mediumFont) love.graphics.printf('Welcome to Pong!', 0, 10, VIRTUAL_WIDTH, 'center') love.graphics.printf('Press Enter!', 0, 22, VIRTUAL_WIDTH, 'center') elseif gameState == 'serve' then love.graphics.setFont(mediumFont) love.graphics.printf('Press Enter to serve!', 0, 10, VIRTUAL_WIDTH, 'center') elseif gameState == 'win' then love.graphics.setFont(mediumFont) love.graphics.printf('Player ' .. winner .. ' has won', 0, 10, VIRTUAL_WIDTH, 'center') end player1:render() player2:render() ball:render() push:finish() end function displayScore() love.graphics.setFont(largeFont) love.graphics.print(player1Score, VIRTUAL_WIDTH / 2 - 50, VIRTUAL_HEIGHT / 3) love.graphics.print(player2Score, VIRTUAL_WIDTH / 2 + 30, VIRTUAL_HEIGHT / 3) end
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { OnScreenDirectionDataInterface } from '../../component-library/OnScreenDirection'; interface OnScreenDirectionState { current: OnScreenDirectionDataInterface; visible: boolean; tapToReceiveDirectionSeen: boolean; mainButtonDirectionSeen: boolean; answerButtonDirectionSeen: boolean; } export default createSlice({ name: 'onScreenDirection', initialState: { current: null, visible: false, tapToReceiveDirectionSeen: false, mainButtonDirectionSeen: false, answerButtonDirectionSeen: false, }, reducers: { setCurrent: ( state: OnScreenDirectionState, action: PayloadAction<OnScreenDirectionDataInterface>, ) => { state.current = action.payload; }, setVisible: ( state: OnScreenDirectionState, action: PayloadAction<boolean>, ) => { state.visible = action.payload; }, markTapToReceiveDirectionAsSeen: (state: OnScreenDirectionState) => { state.tapToReceiveDirectionSeen = true; }, markMainButtonDirectionAsSeen: (state: OnScreenDirectionState) => { state.mainButtonDirectionSeen = true; }, markAnswerButtonDirectionAsSeen: (state: OnScreenDirectionState) => { state.answerButtonDirectionSeen = true; }, }, }); export const onScreenDirectionProps = state => ({ onScreenDirection: { current: state.onScreenDirection.current, visible: state.onScreenDirection.visible, tapToReceiveDirectionSeen: state.onScreenDirection.tapToReceiveDirectionSeen, mainButtonDirectionSeen: state.onScreenDirection.mainButtonDirectionSeen, answerButtonDirectionSeen: state.onScreenDirection.answerButtonDirectionSeen, }, }); export interface OnScreenDirectionStatePropsInterface { onScreenDirection: OnScreenDirectionState; } export interface OnScreenDirectionsActionPropsInterface { setCurrent: (current: OnScreenDirectionDataInterface) => void; setVisible: (visible: boolean) => void; markTapToReceiveDirectionAsSeen: () => void; markMainButtonDirectionAsSeen: () => void; markAnswerButtonDirectionAsSeen: () => void; } export interface OnScreenDirectionPropsInterface extends OnScreenDirectionStatePropsInterface, OnScreenDirectionsActionPropsInterface {}
# Chapter 5: Implementing backpropagation for a whole expression graph We previosuly saw how to automate backpropagation by setting and calling a backward method for each in our graph. Our ability to make this work properly depended on our abilty to call the backward() methods in the right order. That is, backward propagation should only go through a node when it has gone through all of its ancestors. To automate this process of knowing which node to backpropagate next, we can use Topological Sort. Topological Sort is essentially a way to sort the nodes of a Directled Acyclic Graph such that all the edges go only in one way. Hence, a node in a topological sorting of a given DAG has all its descendants ahead of it. We will make use of this sorting method to implement backpropagation on our entire graph. ## Mutlivariant Chain Rule Our current solution suffers from a pretty bad bug: it does not work when nodes are reused, their grad simply gets overwritten each time it is calculated in another context. The solution here, if we look at the multivariant version of the chain rule is that we have to add the gradients. This allows us to obtain such construct: ![Alt text](./illustrations/introducing_multivariant_backprop.png?raw=true "Mutlivariant Backpropagation") Adding our Operations Finally, we imrpoved our Value class by enabling it to handle more operations. These additional operations are showcased in the following graph, where we replaced the used of the tanh() function with the written out version of tanh(). ![Alt text](./illustrations/adding_operations.png?raw=true "Adding Operations")
import * as Card from "../card/index.js"; import * as AddCard from "../add-card/index.js"; import todoStore from "../../store/todoStore.js"; import { setEvent } from "../../utils/handler.js"; export function template({ column }) { return ` <h2 class="column__head"> <span class="column__title text-bold display-bold16"> ${column.columnName} </span> <div class="badge rounded-8 text-weak">${column.cards.length}</div> <button class="column__head-plus" data-editable=false data-column-id="${ column.id }" type="button"> <img src="./assets/icons/plus.svg" width='24' height='24' /> <button class="column__head-close" type="button"> <img src="./assets/icons/close.svg" width='24' height='24' /> </button> </h2> <div class="column__cards-container" data-column-id="${column.id}"> <ul class="column__cards" data-column-id="${column.id}"> ${AddCard.template({ columnId: column.id })} ${column.cards .map((card) => Card.template({ columnId: column.id, card })) .join("")} </ul> </div> `; } const app = document.querySelector("#app"); // handler 등록 setEvent(app, "click", (event) => getAddCard(event)); setEvent(app, "dragstart", (event) => cardDragStart(event)); setEvent(app, "dragend", (event) => cardDragend(event)); setEvent(app, "dragover", (event) => cardDragover(event)); // addCard 화면에 가져오기 const getAddCard = (event) => { const target = event.target.closest(".column__head-plus"); if (!target) { return; } const columnId = target.getAttribute("data-column-id"); const editable = target.getAttribute("data-editable") === "true"; const addCard = document.querySelector( `.card__editable[data-column-id="${columnId}"]` ); // addCard 초기화 addCard.querySelector(".card__title-input").value = ""; addCard.querySelector(".card__description-input").value = ""; addCard.style.display = editable ? "none" : "flex"; target.setAttribute("data-editable", !editable); }; // drag start const cardDragStart = (event) => { const draggingCard = event.target.closest(".card"); if (draggingCard === null) { return; } draggingCard.classList.add("dragging"); }; // drag end : 변경된 데이터 전송 const cardDragend = (event) => { const movedCard = event.target.closest(".dragging"); const movedColumn = event.target.closest(".column__cards"); if (movedCard === null || movedColumn == null) { return; } movedCard.classList.remove("dragging"); const originColumnId = Number(movedCard.getAttribute("data-column-id")); const movedColumnId = Number(movedColumn.getAttribute("data-column-id")); const cardId = Number(movedCard.getAttribute("data-card-id")); const cards = [...movedColumn.querySelectorAll("li.card")]; const movedIndex = cards.findIndex((card) => card === movedCard); // 보내줘야할 데이터: 기존 컬럼, 이동한 컬럼, 추가된 위치(인덱스) todoStore.dispatch({ type: "MOVE_TODO", parameter: originColumnId === movedColumnId ? [originColumnId] : [originColumnId, movedColumnId], payload: { originColumnId: originColumnId, movedColumnId: movedColumnId, movedIndex: movedIndex, cardId: cardId, }, }); }; // dragover const cardDragover = (event) => { const column = event.target.closest(".column__cards"); const draggingCard = document.querySelector(".dragging"); if (column === null || draggingCard === null) { return; } event.preventDefault(); const afterElement = getDragAfterElement(column, event.clientY); if (afterElement === undefined) { column.appendChild(draggingCard); } else { column.insertBefore(draggingCard, afterElement); } }; // dragover 시 카드를 위치시킬 곳 바로 뒤의 카드를 가져옴 const getDragAfterElement = (container, y) => { // .draggable 클래스를 가지며 .dragging 클래스를 가지지 않은 모든 자식 요소를 가져옴. const draggableElements = [ ...container.querySelectorAll(".card:not(.dragging)"), ]; // reduce 함수를 사용하여 가장 가까운 요소를 찾습니다. return draggableElements.reduce( (closest, child) => { const box = child.getBoundingClientRect(); // 드래그 중인 요소를 드롭되어야 할 위치에 대해 Y 좌표에서의 offset을 계산 const offset = y - box.top - box.height / 2; // offset이 0보다 작고 closest.offset 보다 클 경우, 가장 가까운 요소를 업데이트 if (offset < 0 && offset > closest.offset) { return { offset: offset, element: child }; } else { return closest; } }, { offset: Number.NEGATIVE_INFINITY } ).element; };
import { beforeEach, describe, expect, it } from 'vitest' import { InMemoryOrganizationRepository } from '@/repositories/in-memory/in-memory-organization' import { InMemoryPetRepository } from '@/repositories/in-memory/in-memory-pet' import { makeOrganization } from '@/tests/makeOrg' import { makePet } from '@/tests/makePet' import { SearchPetsUseCase } from '.' let petRepository: InMemoryPetRepository let sut: SearchPetsUseCase let organizationRepository: InMemoryOrganizationRepository describe('Search Pets Use Case', async () => { beforeEach(async () => { organizationRepository = new InMemoryOrganizationRepository() petRepository = new InMemoryPetRepository() sut = new SearchPetsUseCase(petRepository) }) it('should be able to search for a pet by params', async () => { const fakeOrg = makeOrganization() const organization = await organizationRepository.create(fakeOrg) const fakePet1 = makePet() const fakePet2 = makePet({ breed: 'Cocker Spaniel', traits: ['Travesso', 'Fofo'], }) const promises = [fakePet1, fakePet2].map((pet) => petRepository.create({ ...pet, organization, }), ) await Promise.all(promises) const { pets } = await sut.execute({ traits: ['travesso', 'fofo'], age: 4, city: organization.address.city, }) expect(pets).toHaveLength(2) }) it('should return empty search', async () => { const fakeOrg = makeOrganization() const organization = await organizationRepository.create(fakeOrg) const fakePet1 = makePet() const fakePet2 = makePet({ breed: 'Cocker Spaniel', traits: ['Travesso', 'Fofo'], }) const promises = [fakePet1, fakePet2].map((pet) => petRepository.create({ ...pet, organization, }), ) await Promise.all(promises) const { pets } = await sut.execute({ age: 1, city: 'são paulo', size: 'big', }) expect(pets).toHaveLength(0) }) it('should be able to search by traits', async () => { const fakeOrg = makeOrganization() const organization = await organizationRepository.create(fakeOrg) const fakePet = makePet({ traits: ['Travesso'], }) const fakePet2 = makePet({ traits: ['Fofo'], }) const promises = [fakePet, fakePet2].map((pet) => petRepository.create({ ...pet, organization, }), ) await Promise.all(promises) const { pets } = await sut.execute({ traits: ['Travesso'], }) expect(pets).toHaveLength(1) expect(pets[0].traits).toContain('Travesso') }) })
import React, { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { authActions } from "../../store/auth-store.store"; import { RootState } from "../../store"; const ChangePasswordPage: React.FC = () => { const dispatch = useDispatch(); const { changePasswordSuccess, user, isLoading, error } = useSelector((state: RootState) => state.auth) const [formData, setLoginData] = useState({ password: '', newPassword: '', confirmPassword: '' }) const onChangeFormData = (event: React.ChangeEvent<HTMLInputElement>) => { setLoginData({ ...formData, [event.target.name]: event.target.value }) } useEffect(()=>{ dispatch(authActions.updateState({changePasswordSuccess:false, error: null})) },[]) return <div className='page change-password-page animate-fade-in'> <div className="card change-password-card"> <div className="card-title"> <h3 className="section-title">Change Password</h3> </div> <div className="card-body"> {error&&<p className="error-message">{error}</p>} {!changePasswordSuccess?<div className="px-15"> <div className='input-box mt-15'> <label className='form-label'>Password</label> <input type="text" name='password' value={formData.password} onChange={onChangeFormData} className='input' /> </div> <div className='input-box mt-15'> <label className='form-label'>New Password</label> <input type="text" name='newPassword' value={formData.newPassword} onChange={onChangeFormData} className='input' /> </div> <div className='input-box mt-15'> <label className='form-label'>Confirm Password</label> <input type="text" name='confirmPassword' value={formData.confirmPassword} onChange={onChangeFormData} className='input' /> </div> <button className="btn btn-md btn-primary mt-15 float-right" disabled={isLoading || !formData.password || formData.newPassword != formData.confirmPassword || !formData.newPassword} onClick={() => { authActions.changePassword(formData.password, formData.newPassword)(dispatch) }}>Change Password {isLoading&&<span className="fa fa-sync fa-spin"></span>}</button> </div>:<div><p>Password changed successfully</p></div>} </div> </div> </div> } export default ChangePasswordPage;