text
stringlengths
184
4.48M
//import React from 'react' - обязательно импортируй, ВСЕГДА!!! // Для включения поддержки TSX в проекте добавьте следующую строку в файл tsconfig.json: // { // "compilerOptions": { // "jsx": "react" // } // } import React from "react"; type Props = { isDisabled?: boolean; size: "Big" | "Small"; text: string; onClick(event: React.MouseEvent<HTMLButtonElement>): void; }; export function FancyButton(props: Props) { const [toggled, setToggled] = React.useState(false); return ( <button className={"Size-" + props.size} disabled={props.isDisabled || false} onClick={(event) => { setToggled(!toggled); props.onClick(event); }} > {props.text} </button> ); } let button = ( <FancyButton size="Big" text="Sign Up Now" onClick={() => console.log("Clicked!")} /> ); // FOR CLASS COMPONENT import React from "react"; import { FancyButton } from "./FancyButton"; type Props = { firstName: string; userId: string; }; type State = { isLoading: boolean; }; class SignupForm extends React.Component<Props, State> { state = { isLoading: false }; render() { return ( <> <h2> Sign up for a 7-day supply of our tasty toothpaste now,{" "} {this.props.firstName}. </h2> <FancyButton isDisabled={this.state.isLoading} size="Big" text="Sign Up Now" onClick={this.signUp} /> </> ); } private signUp = async () => { this.setState({ isLoading: true }); try { await fetch("/api/signup?userId=" + this.props.userId); } finally { this.setState({ isLoading: false }); } }; } let form = <SignupForm firstName="Albert" userId="13ab9g3" />;
package org.example; import org.example.exceptions.DivisionByZeroException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class CalculatorTest { @Test void shouldAddTwoNumbers() { int firstNumber = 2; int secondNumber = 4; int actualResult = 6; Calculator calculator = new Calculator(); int expectedResult = calculator.add(firstNumber, secondNumber); assertEquals(expectedResult, actualResult); } @Test void shouldMultiplyTwoNumbers() { int firstNumber = 2; int secondNumber = 4; int actualResult = 8; Calculator calculator = new Calculator(); int expectedResult = calculator.multiply(firstNumber, secondNumber); assertEquals(expectedResult, actualResult); } @Test void shouldGiveWholeNumberWhenBiggerDividesSmaller() throws DivisionByZeroException { int firstNumber = 6; int secondNumber = 2; double actualResult = 3; Calculator calculator = new Calculator(); double expectedResult = calculator.divide(firstNumber, secondNumber); assertEquals(expectedResult, actualResult); } @Test void shouldGiveDecimalNumberWhenSmallerDividesBigger() throws DivisionByZeroException { int firstNumber = 2; int secondNumber = 4; double actualResult = 0.5; Calculator calculator = new Calculator(); double expectedResult = calculator.divide(firstNumber, secondNumber); assertEquals(expectedResult, actualResult); } @Test void shouldThrowExceptionOnDivisionByZero() { int number = 2; assertThrows(DivisionByZeroException.class, () -> new Calculator().divide(number, 0)); } @Test void shouldGiveSquareRootOfANumber() { double number = 4; double actualResult = 2; Calculator calculator = new Calculator(); double expectedResult = calculator.squareRoot(number); assertEquals(expectedResult, actualResult); } @Test void shouldThrowExceptionOnNegativeInputToSqrt() { double number = -1; assertThrows(IllegalArgumentException.class, () -> new Calculator().squareRoot(number)); } @Test void shouldReturnOneForFactorialOfOne() { int number = 1; int actualResult = 1; Calculator calculator = new Calculator(); int expectedValue = calculator.factorial(number); assertEquals(expectedValue, actualResult); } @Test void shouldReturnTwoForFactorialOfTwo() { int number = 2; int actualResult = 2; Calculator calculator = new Calculator(); int expectedValue = calculator.factorial(number); assertEquals(expectedValue, actualResult); } @Test void shouldReturnSixForFactorialOfThree() { int number = 3; int actualResult = 6; Calculator calculator = new Calculator(); int expectedValue = calculator.factorial(number); assertEquals(expectedValue, actualResult); } @Test void shouldThrowExceptionOnNegativeInputToFactorial() { int number = -1; assertThrows(IllegalArgumentException.class, () -> new Calculator().factorial(number)); } @Test void shouldGivePowerOfTwoNumbers() { int firstNumber = 2; int secondNumber = 4; double actualResult = 16; Calculator calculator = new Calculator(); double expectedResult = calculator.power(firstNumber, secondNumber); assertEquals(expectedResult, actualResult); } @Test void shouldReturnLogarithmicOfGivenNumber() { int number = 3; double actualResult = Math.log(3); Calculator calculator = new Calculator(); double expectedValue = calculator.log(number); assertEquals(expectedValue, actualResult); } @Test void shouldThrowExceptionOnNegativeInputToLogarithm() { int number = -1; assertThrows(IllegalArgumentException.class, () -> new Calculator().log(number)); } }
#define BLINKER_WIFI #define OLED_RESET -1 #define BuzzPin D2 #define RelayPin D6 #define TouchPin D7 #define GreenPin D8 #define BluePin D9 #define TrigPin D10 #define EchoPin D11 #define DHTPin D12 #define PIRPin D3 #define LdrPin A0 #define FlamePin A1 #define DHTType DHT11 #include <Blinker.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <Adafruit_Sensor.h> #include <DHT.h> #include <NTPClient.h> #include <WiFiUdp.h> // WiFi Configuration char auth[] = ""; char ssid[] = "Wpa"; char pswd[] = ""; // Init global objects DHT dht(DHTPin, DHTType); WiFiUDP ntpUDP; Adafruit_SSD1306 display(128, 64, &Wire, OLED_RESET); NTPClient timeClient(ntpUDP, "ntp1.aliyun.com",60*60*8, 30*60*1000); int LdrV = 0; int touchState = 0; double dis = 0; int pirV = 0, pirC = 0, pirLock = 0; String pirTime = ""; uint32_t read_time = 0; float humi_read, temp_read; BlinkerNumber LUMI("lumi"); BlinkerText PIRREC("pirrec"); BlinkerNumber PIRC("pirc"); BlinkerButton Button1("btn-light"); BlinkerButton Button2("btn-relay"); void button1_callback(const String & state) { BLINKER_LOG("Toggle LED D2: ", state); digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } void button2_callback(const String & state) { BLINKER_LOG("Toggle Relay: ", state); digitalWrite(RelayPin, !digitalRead(RelayPin)); } void dataRead(const String & data) { BLINKER_LOG("Blinker readString: ", data); uint32_t BlinkerTime = millis(); Blinker.vibrate(); Blinker.print("millis", BlinkerTime); digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } void dataStorage() { Blinker.dataStorage("tempS", temp_read); Blinker.dataStorage("humiS", humi_read); } long getTime() { digitalWrite(TrigPin,HIGH); delayMicroseconds(10); digitalWrite(TrigPin,LOW); return pulseIn(EchoPin,HIGH); } void PIRSensor() { pirV = digitalRead(PIRPin); if(pirV == HIGH){ PIRREC.print(timeClient.getFormattedTime()); pirTime = timeClient.getFormattedTime(); Blinker.delay(500); if(pirV == HIGH){ pirLock = 1; } } else if (pirLock ==1 && pirV == LOW) { pirLock = 0; pirC++; PIRC.print(pirC); } else{ Serial.println("nothing detected"); } } void displayOLED(){ display.clearDisplay(); display.setCursor(0,0); display.print("[Temp] "); display.print(temp_read); display.println("C"); display.print("[Humi] "); display.print(humi_read); display.println("%"); display.print("[Lumi] "); display.print(LdrV); display.println("lux"); display.print("[PIRT] "); display.print(pirTime); display.println(""); display.println(""); display.print("Distance:"); display.print(dis); display.println("cm"); display.drawRect(0, 52, 128, 12, WHITE); display.fillRect(2, 54, map(dis, 2, 30, 2, 124), 8, WHITE); display.display(); } void setup() { // Init Serial Serial.begin(115200); BLINKER_DEBUG.stream(Serial); BLINKER_DEBUG.debugAll(); // Init HC-SR04 pinMode(TrigPin, OUTPUT); pinMode(EchoPin, INPUT); // Init PIR pinMode(PIRPin, INPUT); // Init Relay pinMode(RelayPin, OUTPUT); digitalWrite(RelayPin, HIGH); // Init TouchSensor pinMode(TouchPin, INPUT); // Init D2 LED pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, HIGH); // Init Blinker Blinker.begin(auth, ssid, pswd); Blinker.attachData(dataRead); Blinker.attachRTData(rtData); Blinker.attachDataStorage(dataStorage); Button1.attach(button1_callback); Button2.attach(button2_callback); // Init DHT11 dht.begin(); // Init Display display.begin(SSD1306_SWITCHCAPVCC, 0x3C); display.setTextColor(WHITE); display.clearDisplay(); display.setTextSize(1); // Init Internet Time Server timeClient.begin(); } void rtData(){ Blinker.sendRtData("dis", dis); Blinker.sendRtData("lumi", LdrV); Blinker.sendRtData("temp", temp_read); Blinker.sendRtData("humi", humi_read); Blinker.printRtData(); } void loop() { // Blinker handle Blinker.run(); Blinker.delay(1000); // Handle NTP Time info timeClient.update(); //Serial.println(timeClient.getFormattedTime()); // Collect sensor data // LDR LdrV = analogRead(LdrPin); // DHT11 humi_read = dht.readHumidity(); temp_read = dht.readTemperature(); // HC-SR04 dis = getTime()/ 58.3; // PIR PIRSensor(); // OLED displayOLED(); }
package p02.menus; import java.util.Iterator; import p02.modelos.Platillo;; /** * Clase abstracta que representa un menu * @author Alcantara Estrada Kevin Isaac * @author Curenio Sanchez Misael * @author Hernandez Paramo ELizabeth */ public abstract class Menu { public abstract Iterator<Platillo> createIterator(); /** * Metodo que representa en cadena a la clase * @return String */ @Override public String toString() { String res = "MENU DEL DIA\n\n"; Iterator<Platillo> it = createIterator(); while (it.hasNext()) { res += it.next().toString(); } it.remove(); return res + "\n"; } public Platillo buscarPlatillo(Long id) { Iterator<Platillo> it = createIterator(); while(it.hasNext()) { Platillo cur = it.next(); if (cur.getId().equals(id)) { return cur; } } return null; } }
import { Routes, Route } from "react-router-dom" import { Context } from "../../context" import FruitsPage from "../../pages/FruitsPage"; import VegetablesPage from "../../pages/VegetablesPage"; import NavMenu from "../NavMenu"; import { fruits } from "../../data/fruits" import { vegetables } from "../../data/vegetables"; import { useState, useEffect } from "react"; function App() { const [ vegCards, setVegCards ] = useState(vegetables); const [ frutCards, setFrutCards ] = useState(fruits); useEffect(() => { const veg = JSON.parse(localStorage.getItem("vegCards")); const frut = JSON.parse(localStorage.getItem("frutCards")); setVegCards(veg); setFrutCards(frut); }, []); useEffect(() => { localStorage.setItem("vegCards", JSON.stringify(vegCards)); localStorage.setItem("frutCards", JSON.stringify(frutCards)); }, [vegCards, frutCards]); const add_veg_cards = (title, price, country) => setVegCards ([ ...vegCards, { id: Date.now(), title, price, country } ]); const add_frut_cards = (title, price, country) => setFrutCards ([ ...frutCards, { id: Date.now(), title, price, country } ]); const delete_veg = (id) => setVegCards(vegCards.filter(el => el.id !== id)); const delete_frut = (id) => setFrutCards(frutCards.filter(el => el.id !== id)); return ( <div> <Context.Provider value={{ vegCards, frutCards, add_veg_cards, add_frut_cards, delete_veg, delete_frut }}> <NavMenu /> <Routes> <Route path="/fruits_page" element={<FruitsPage />} /> <Route path="/vegetables_page" element={<VegetablesPage />} /> </Routes> </Context.Provider> </div> ); } export default App;
package fje.edu.m03uf6projecterestaurant.controllers; import fje.edu.m03uf6projecterestaurant.classes.Plat; import fje.edu.m03uf6projecterestaurant.classes.PlatDAO; import fje.edu.m03uf6projecterestaurant.classes.PlatDAOImpl; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.stage.Stage; import java.io.IOException; import java.sql.SQLException; import java.util.Optional; public class EditarEsborrarPlatController { private String categoria; @FXML private void canviarEscenaAction(ActionEvent event) throws IOException { Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); Parent root = FXMLLoader.load(getClass().getResource("/fje/edu/m03uf6projecterestaurant/primer_plat.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } private PlatDAO platDAO = new PlatDAOImpl(); private Plat plat; @FXML private Button EditarButton; @FXML private Button EsborrarButton; @FXML private TextField camp_nom; @FXML private TextArea camp_descripcio; @FXML private TextField camp_preu; @FXML private TextArea camp_ingredients; @FXML private TextField camp_UrlIMG; private Plat platSeleccionat; public void setPlatSeleccionat(Plat plat) { this.platSeleccionat = plat; camp_nom.setText(plat.getNom()); camp_descripcio.setText(plat.getDescripcio()); camp_preu.setText(String.valueOf(plat.getPreu())); camp_ingredients.setText(plat.getIngredients()); camp_UrlIMG.setText(plat.getUrlIMG()); } @FXML private void editarPlat(ActionEvent event) throws IOException, SQLException { String nom = camp_nom.getText(); String descripcio = camp_descripcio.getText(); Double preu = Double.parseDouble(camp_preu.getText()); String ingredients = camp_ingredients.getText(); String urlIMG = camp_UrlIMG.getText(); Plat plat = new Plat(platSeleccionat.getId(), nom, descripcio, preu, ingredients, urlIMG, categoria); PlatDAO platDAO = new PlatDAOImpl(); if (platDAO.updatePlat(plat)) { Alert info = new Alert(Alert.AlertType.INFORMATION); info.setTitle("Informació"); info.setHeaderText(null); info.setContentText("Plat actualitzat correctament!"); info.showAndWait(); Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); stage.close(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fje/edu/m03uf6projecterestaurant/primer_plat.fxml")); Parent root = loader.load(); PrimersPlatsController controller = loader.getController(); controller.inicialitzarBotonsPlats(); Scene scene = new Scene(root); Stage newStage = new Stage(); newStage.setScene(scene); newStage.show(); } else { Alert error = new Alert(Alert.AlertType.ERROR); error.setTitle("Error"); error.setHeaderText(null); error.setContentText("No s'ha pogut actualitzar el plat!"); error.showAndWait(); } } public void esborrarPlat() { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmació"); alert.setHeaderText(null); alert.setContentText("Estàs segur que vols eliminar aquest plat?"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK){ PlatDAO platDAO = new PlatDAOImpl(); boolean eliminat = platDAO.deletePlat(platSeleccionat); if (eliminat) { Alert info = new Alert(Alert.AlertType.INFORMATION); info.setTitle("Informació"); info.setHeaderText(null); info.setContentText("Plat eliminat correctament!"); info.showAndWait(); try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fje/edu/m03uf6projecterestaurant/primer_plat.fxml")); Parent root = loader.load(); PrimersPlatsController controller = loader.getController(); controller.inicialitzarBotonsPlats(); Scene scene = EsborrarButton.getScene(); scene.setRoot(root); } catch (IOException ex) { throw new RuntimeException(ex); } catch (SQLException e) { throw new RuntimeException(e); } } else { Alert error = new Alert(Alert.AlertType.ERROR); error.setTitle("Error"); error.setHeaderText(null); error.setContentText("No s'ha pogut eliminar el plat!"); error.showAndWait(); } } } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>위도,경도를 이용한 구글맵</title> <!-- 인증번호 받기 https://cloud.google.com/maps-platform/ https://maps.googleapis.com AIzaSyBZO3MrykFpNpemqO2zPtG5M9ADUXSoApw --geocode-- AIzaSyBiyi8IBKuUJnY0RccI6KvVWJslar5cPWg --> <style> #gMap{ width :100%; height :600px; border: 1px solid black; } </style> <!-- 지도를 사용하기 위하여 구글에서 자바스크립트를 외부파일로 링크를 걸어야한다. --> <script async defer src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBZO3MrykFpNpemqO2zPtG5M9ADUXSoApw&callback=initMap"></script> </head> <body> <!-- 지도를 표시할 곳 --> <div id="gMap"></div> <script> // 지도의 정보를 표시하는 함수 위도 ,경도 var latitude = 37.5729503; //위도 var longitude = 126.9793578; // 경도 var lati = [37.5768383, 37.57777103,37.5783533]; var longi = [126.9776538, 126.9735678, 126.9793571]; function initMap(){ //지도의 센터지정 var myCenter = new google.maps.LatLng(latitude,longitude); //맵 옵션 JSON 방식 기입 var mapProperty ={ center : myCenter, zoom : 12, //0~21까지의 값을 사용한다. 숫자가 클수록 확대 mapTypeId : google.maps.MapTypeId.ROADMAP // 지도종류(RODAMAP,HYBRID,STEELITE,TERRAIN) }; //맵 생성 객체 // 지도를 표시할곳 ,맵 옵션지정 var map =new google.maps.Map(document.getElementById("gMap"),mapProperty); //마커표시 var marker = new google.maps.Marker({ position : myCenter,// 마커표시위치 map : map,// 마커를 표시할 지도 title :'마커에 표시할 내용' , icon : 'gmap_pin.png' }); marker.setMap(map); //마커를 클릭하면 대화상자 표시하기 //대화상자에 표시될 내용 var info = "위도:"+latitude+"<br/>경도:"+longitude; info += "<br/><img src ='../../img/01.jpg' widht='80' height='80'/>"; var infoObj= new google.maps.InfoWindow({content:info}); //마커를 클릭시 대화상자가 보여지도록 이벤트등록 google.maps.event.addListener(marker,'click',function(){infoObj.open(map,marker)}); //여러개의 마커표시 for (i=0; i<lati.length; i++){ var mk = new google.maps.Marker({ position :new google.maps.LatLng(lati[i],longi[i]), map : map, title: "위도:"+lati[i]+"<br/>경도:"+longi[i] }); mk.setMap(map); } //반경표시 var myCity = new google.maps.Circle({ center : myCenter ,radius : 500 // m 단위 ,strokeColor : '#f00' // 경계선 색상 ,strokeWidth : 3 //선의두께 (px 단위) ,strokeOpacity : 0.5//0~1사이 선의 투명도 ,fillColor : '#ff0' //원안의 배경색 ,fillOpacity : 0.5 // 원의 배경색의 투명도 }); myCity.setMap(map); } </script> </body> </html>
import 'dart:developer'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:my_todo_app/infrastructure/model/todo.model.dart'; class TodoService { FirebaseFirestore firestore = FirebaseFirestore.instance; Future<bool> addTask( {required String title, required String description}) async { try { await firestore.collection('tasks').add({ 'title': title, 'description': description, 'completed': false, // You can add more fields as needed }); return true; } catch (e) { log('Error adding task: $e'); return false; } } Future<bool> updateTaskStatus( {required String taskId, required bool isCompleted}) async { /// FirebaseFirestore firestore = FirebaseFirestore.instance; await firestore.collection('tasks').doc(taskId).update({ 'completed': isCompleted, }); return true; } Future<bool> deleteTask({required String taskId}) async { //FirebaseFirestore firestore = FirebaseFirestore.instance; await firestore.collection('tasks').doc(taskId).delete(); return true; } Future<List<TodoModel>> fetchTodos() async { //FirebaseFirestore firestore = FirebaseFirestore.instance; try { final QuerySnapshot querySnapshot = await firestore.collection('tasks').get(); List<TodoModel> todos = []; for (var task in querySnapshot.docs) { final taskData = task.data() as Map<String, dynamic>; final todo = TodoModel( id: task.id, title: taskData['title'], description: taskData['description'], completed: taskData['completed'], ); todos.add(todo); } return todos; } catch (e) { print('Error fetching todos: $e'); return []; } } Future<List<TodoModel>> fetchTodosByStatus({required bool todoStatus}) async { // FirebaseFirestore firestore = FirebaseFirestore.instance; try { final QuerySnapshot querySnapshot = await firestore .collection('tasks') .where('completed', isEqualTo: todoStatus) .get(); List<TodoModel> todos = []; for (var task in querySnapshot.docs) { final taskData = task.data() as Map<String, dynamic>; final todo = TodoModel( id: task.id, title: taskData['title'], description: taskData['description'], completed: taskData['completed'], ); todos.add(todo); } return todos; } catch (e) { print('Error fetching todos: $e'); return []; } } Future<bool> updateTaskTitle( {required String taskId, required String title, required String description}) async { /// FirebaseFirestore firestore = FirebaseFirestore.instance; try { await firestore .collection('tasks') .doc(taskId) .update({'title': title, 'description': description}); return true; } catch (e) { print('Error updating task title: $e'); return false; } } }
/** @jsxImportSource @emotion/react */ import { css } from '@emotion/react'; import React, { useEffect, useState } from 'react'; import { Calendar } from 'oyc-ds'; import TimePicker, { TimeData } from '../../molecules/TimePicker'; interface DateTimePickerProps { onChange: (date: Date) => void; date?: Date; } const timeCss = css` display: flex; justify-content: flex-end; margin-right: 1rem; `; const DateTimePicker = ({ onChange, date = new Date(), }: DateTimePickerProps) => { const [selectedDate, setSelectedDate] = useState<string>( `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`, ); const [time, setTime] = useState<TimeData>({ hours: date.getHours(), minutes: date.getMinutes(), }); const handleDateChange = (year: number, month: number, day: number) => { const newDate = `${year}-${month}-${day}`; setSelectedDate(newDate); onChange(new Date(`${newDate} ${time.hours}:${time.minutes}`)); }; const handleTimeChange = (time: TimeData) => { setTime(time); onChange(new Date(`${selectedDate} ${time.hours}:${time.minutes}`)); }; useEffect(() => { setSelectedDate( `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`, ); setTime({ hours: date.getHours(), minutes: date.getMinutes() }); }, [setTime, date]); return ( <div> <Calendar onClick={handleDateChange} selected={[selectedDate]} year={parseInt(selectedDate.split('-')[0])} month={parseInt(selectedDate.split('-')[1])} /> <div css={timeCss}> <TimePicker onChange={handleTimeChange} time={time} /> </div> </div> ); }; export default DateTimePicker;
<!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Site title</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" type="image/x-icon" href="#"> <!-- Place favicon.ico in the root directory --> <!-- CSS here --> <link rel="stylesheet" href="assets/css/aos.css"> <link rel="stylesheet" href="assets/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/css/owl.carousel.min.css"> <link rel="stylesheet" href="assets/css/style.css"> <link rel="stylesheet" href="assets/css/responsive.css"> </head> <body> <!-- header-area START --> <div class="header-area" data-aos="fade-down" > <div class="container lg"> <div class="row align-items-center"> <div class=" col-12 "> <div class="header__content"> <div class="logo-area"> <a href="index.html"><img src="assets/img/logo.svg" alt=""></a> </div> <div class="header-btn"> <a href="#">Pagamentos</a> <button type="button">Começar</button> </div> </div> </div> </div> </div> </div> <!-- header-area END --> <main> <!---------hero Section START ----------> <section class="hero-area"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="hero__content"> <div class="hero__text" data-aos="fade-up" data-aos-delay="500" > <h1 class="text-bg">Educação Inteligente: </h1> <h1>O Futuro Começa Aqui!</h1> <p>Preparando Alunos para o Amanhã</p> <div class="hero__btm"> <a href="#" class="thm_btn white">Começar</a> <div class="avater__blk" data-aos="zoom-in" > <h4> 250+ <span>estudantes</span> </h4> <i> <img src="assets/img/avater-img.png" alt=""> </i> </div> </div> </div> <i data-aos="fade-up" > <img src="assets/img/hero-img.png" alt=""> </i> <img src="assets/img/hero-mobile.png" class="hero-mobile" alt=""> </div> </div> </div> </div> </section> <!---------hero Section End ----------> <!---------service Section START ----------> <section class="service-area mt_100 mb_100 overflow-hidden"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center mb_50" data-aos="fade-up" > <div class="sec__title"> <h1 class="title">Opte pela <span>Evolve</span></h1> <p>O nosso centro de explicações é a escolha ideal porque integramos inteligência artificial no ensino, <br> proporcionamos acesso a computadores e oferecemos suporte personalizado para todos os alunos.</p> </div> </div> </div> <div class="row align-items-center flex-lg-row flex-column-reverse mb-5 mb-lg-0"> <div class="col-lg-6" data-aos="zoom-in" > <div class="svc__img"> <i><img src="assets/img/svc-1.png" alt=""></i> </div> </div> <div class="col-lg-6" data-aos="fade-left" > <div class="svc__text m__auto"> <h2>Suporte </h2> <p>Reconhecemos e atendemos às necessidades individuais de cada aluno. Sendo assim, somos constituidos de uma equipa adequada para satisfazer as necessidades do seu aluno.</p> </div> </div> </div> <div class="row align-items-end "> <div class="col-lg-6" data-aos="fade-right" > <div class="svc__text"> <h2>Instalações Modernas</h2> <p>Com a nossa infraestrutura , garantimos um espaço de aprendizado e um ambiente onde a inovação e a tecnologia se encontram para fornecer uma experiência educacional excepcional.</p> </div> </div> <div class="col-lg-6" data-aos="zoom-in" > <div class="svc__img"> <i><img src="assets/img/svc-2.png" alt=""></i> </div> </div> </div> <div class="row align-items-center my-5 pt_50 flex-lg-row flex-column-reverse"> <div class="col-lg-6" data-aos="zoom-in" > <div class="svc__img"> <i><img src="assets/img/svc-3.png" alt=""></i> </div> </div> <div class="col-lg-6" data-aos="fade-left" > <div class="svc__text m__auto"> <h2>Novas Tecnologias</h2> <p>oferecemos tecnologias que transformam o modo como o conhecimento é absorvido e aplicado. Usando computadores acessíveis a tudos os alunos</p> </div> </div> </div> <div class="row align-items-center"> <div class="col-lg-6" data-aos="fade-right" > <div class="svc__text"> <h2>Inteligência Artificial</h2> <p>A Inteligência Artificial desempanha um papel significativo no nosso ensino, e que com a sua ajuda recebemos feedback sobre as dificuldades que até então não tinham sido atendidas. </p> </div> </div> <div class="col-lg-6" data-aos="zoom-in" > <div class="svc__img"> <i><img src="assets/img/svc-4.png" alt=""></i> </div> </div> </div> </div> </section> <!---------service Section End ----------> <!---------nossos Section START ----------> <section class="nossos-area"> <div class="container-fluid position-relative"> <h1 class="" data-aos="fade-right" >Os nossos serviços</h1> <div class="row"> <div class="col-lg-12"> <div class="nossos__wrp"> <ul > <li data-aos="zoom-in" data-aos-delay="100" > <a href="#"><img src="assets/img/svc-item-1.svg" alt=""></a> </li> <li data-aos="zoom-in" data-aos-delay="200" > <a href="#"><img src="assets/img/svc-item-2.svg" alt=""></a> </li> <li data-aos="zoom-in" data-aos-delay="300" > <a href="#"><img src="assets/img/svc-item-3.svg" alt=""></a> </li> <li data-aos="zoom-in" data-aos-delay="400" > <a href="#"><img src="assets/img/svc-item-4.svg" alt=""></a> </li> </ul> <ul class="d-none d-md-flex"> <li data-aos="zoom-in " data-aos-delay="100" > <a href="#"><img src="assets/img/svc-item-5.svg" alt=""></a> </li> <li data-aos="zoom-in " data-aos-delay="200" > <a href="#"><img src="assets/img/svc-item-6.svg" alt=""></a> </li> <li data-aos="zoom-in " data-aos-delay="300" > <a href="#"><img src="assets/img/svc-item-7.svg" alt=""></a> </li> <li data-aos="zoom-in " data-aos-delay="400" > <a href="#" class="svc-8"><img src="assets/img/svc-item-8.png" alt=""></a> </li> </ul> <ul class="d-none d-md-flex"> <li data-aos="zoom-in " data-aos-delay="200" > <a href="#"><img src="assets/img/svc-item-9.svg" alt=""></a> </li> <li data-aos="zoom-in " data-aos-delay="300" > <a href="#"><img src="assets/img/svc-item-10.svg" alt=""></a> </li> <li data-aos="zoom-in " data-aos-delay="400" > <a href="#"><img src="assets/img/svc-item-11.svg" alt=""></a> </li> </ul> <ul class="d-md-flex d-md-none"> <li data-aos="zoom-in " data-aos-delay="500" > <a href="#"><img src="assets/img/svc-item-5.svg" alt=""></a> </li> <li data-aos="zoom-in " data-aos-delay="500" > <a href="#"><img src="assets/img/svc-item-6.svg" alt=""></a> </li> <li data-aos="zoom-in " data-aos-delay="500" > <a href="#"><img src="assets/img/svc-item-7.svg" alt=""></a> </li> <li data-aos="zoom-in " data-aos-delay="500" > <a href="#"><img src="assets/img/svc-item-9.svg" alt=""></a> </li> <li data-aos="zoom-in " data-aos-delay="500" > <a href="#"><img src="assets/img/svc-item-10.svg" alt=""></a> </li> <li data-aos="zoom-in " data-aos-delay="500" > <a href="#"><img src="assets/img/svc-item-11.svg" alt=""></a> </li> </ul> </div> </div> </div> </div> </section> <!---------nossos Section End ----------> <!---------Tutors Section START ----------> <section class="Tutors-area mt_100 mb_100"> <div class="container"> <div class="row"> <div class="col-lg-12" data-aos="fade-right" > <div class="sec__title"> <h1 class="title">meet our <span>Tutors</span></h1> </div> </div> <div class="col-lg-12" data-aos="fade-up" > <div class="Tutors__slider owl-carousel"> <div class="Tutors__blk" data-aos="zoom-in" > <i><img src="assets/img/tutor1.png" alt=""></i> <h3>John Doe</h3> <h5>Position Name</h5> <p>Lorem ipsum dolor sit amet consectetur. Id turpis maecenas nunc imperdiet sed ultricies mi. Elementum nulla nec netus cursus vel tempor nisl. Egestas.</p> </div> <div class="Tutors__blk" data-aos="zoom-in" data-aos-delay="100" > <i><img src="assets/img/tutor2.png" alt=""></i> <h3>John Doe</h3> <h5>Position Name</h5> <p>Lorem ipsum dolor sit amet consectetur. Id turpis maecenas nunc imperdiet sed ultricies mi. Elementum nulla nec netus cursus vel tempor nisl. Egestas.</p> </div> <div class="Tutors__blk" data-aos="zoom-in" data-aos-delay="300" > <i><img src="assets/img/tutor3.png" alt=""></i> <h3>John Doe</h3> <h5>Position Name</h5> <p>Lorem ipsum dolor sit amet consectetur. Id turpis maecenas nunc imperdiet sed ultricies mi. Elementum nulla nec netus cursus vel tempor nisl. Egestas.</p> </div> <div class="Tutors__blk"> <i><img src="assets/img/tutor1.png" alt=""></i> <h3>John Doe</h3> <h5>Position Name</h5> <p>Lorem ipsum dolor sit amet consectetur. Id turpis maecenas nunc imperdiet sed ultricies mi. Elementum nulla nec netus cursus vel tempor nisl. Egestas.</p> </div> </div> </div> </div> </div> </section> <!---------Tutors Section End ----------> <!---------timeline Section START ----------> <section class="timeline-area mb_150"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center mb_50" data-aos="fade-up" > <div class="sec__title"> <h1 class="title">How It <span>Works</span></h1> </div> </div> <div class="col-lg-12"> <div class="timeline__wrp"> <ul data-aos="zoom-in" > <li data-aos="fade-right" > <i>01</i> <h3>Step 1</h3> <p>Lorem ipsum dolor sit amet consectetur. Aliquam.</p> </li> <li data-aos="fade-right" data-aos-delay="200" > <i>02</i> <h3>Step 2</h3> <p>Lorem ipsum dolor sit amet consectetur. Aliquam.</p> </li> <li data-aos="fade-right" data-aos-delay="400" > <i>03</i> <h3>Step 3</h3> <p>Lorem ipsum dolor sit amet consectetur. Aliquam.</p> </li> <li data-aos="fade-right" data-aos-delay="600" > <i>04</i> <h3>Step 4</h3> <p>Lorem ipsum dolor sit amet consectetur. Aliquam.</p> </li> </ul> </div> </div> </div> </div> </section> <!---------timeline Section End ----------> <!---------faq Section START ----------> <section class="faq-area"> <div class="container"> <div class="row"> <div class="col-lg-5" data-aos="fade-right" > <div class="faq__content"> <h1>Questões frequentemente perguntadas</h1> <a href="#" class="thm_btn">ver mais</a> </div> </div> <div class="col-lg-7"> <div class="faq-accordion"> <div class="accordion" id="accordionExample"> <div class="accordion-item" data-aos="fade-up" > <h2 class="accordion-header" id="headingOne"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Posso ter explicações em várias disciplinas? </button> </h2> <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <div class="accordion-body"> <p>Sim, é possível ter explicações em diversas disciplinas. Garantimos uma grande variedade de explicações, onde fornecemos explicadores para as 7 disciplinas principais</p> </div> </div> </div> <div class="accordion-item" data-aos="fade-up" data-aos-delay="100" > <h2 class="accordion-header" id="headingTwo"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Têm explicações até que ano? </button> </h2> <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample"> <div class="accordion-body"> <p>Sim, é possível ter explicações em diversas disciplinas. Garantimos uma grande variedade de explicações, onde fornecemos explicadores para as 7 disciplinas principais</p> </div> </div> </div> <div class="accordion-item" data-aos="fade-up" data-aos-delay="200" > <h2 class="accordion-header" id="headingThree"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> Qual é a eficácia da ajuda dos computadores? </button> </h2> <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample"> <div class="accordion-body"> <p>Sim, é possível ter explicações em diversas disciplinas. Garantimos uma grande variedade de explicações, onde fornecemos explicadores para as 7 disciplinas principais</p> </div> </div> </div> <div class="accordion-item" data-aos="fade-up" data-aos-delay="300" > <h2 class="accordion-header" id="headingfour"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapsefour" aria-expanded="false" aria-controls="collapsefour"> Lorem ipsum dolor sit amet? </button> </h2> <div id="collapsefour" class="accordion-collapse collapse" aria-labelledby="headingfour" data-bs-parent="#accordionExample"> <div class="accordion-body"> <p>Sim, é possível ter explicações em diversas disciplinas. Garantimos uma grande variedade de explicações, onde fornecemos explicadores para as 7 disciplinas principais</p> </div> </div> </div> <div class="accordion-item" data-aos="fade-up" data-aos-delay="400" > <h2 class="accordion-header" id="headingfive"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapsefive" aria-expanded="false" aria-controls="collapsefive"> Lorem ipsum dolor sit amet? </button> </h2> <div id="collapsefive" class="accordion-collapse collapse" aria-labelledby="headingfive" data-bs-parent="#accordionExample"> <div class="accordion-body"> <p>Sim, é possível ter explicações em diversas disciplinas. Garantimos uma grande variedade de explicações, onde fornecemos explicadores para as 7 disciplinas principais</p> </div> </div> </div> <div class="accordion-item" data-aos="fade-up" data-aos-delay="500" > <h2 class="accordion-header" id="headingsix"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapsesix" aria-expanded="false" aria-controls="collapsesix"> Quais são os métodos de pagamentos aceites? </button> </h2> <div id="collapsesix" class="accordion-collapse collapse" aria-labelledby="headingsix" data-bs-parent="#accordionExample"> <div class="accordion-body"> <p>Sim, é possível ter explicações em diversas disciplinas. Garantimos uma grande variedade de explicações, onde fornecemos explicadores para as 7 disciplinas principais</p> </div> </div> </div> </div> </div> </div> </div> </div> </section> <!---------faq Section End ----------> <!---------newLatter Section START ----------> <section class="newLatter-area"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="newLatter__wrp"> <div class="" data-aos="fade-right" > <h1>Pronto para começar? </h1> <p>Estás pronto para te comprometeres com a excelência acadêmica e aprofundares os teus conhecimentos? Aguardamos o teu ingresso nesta jornada enriquecedora.</p> <a href="#" class="thm_btn">Começar</a> </div> <i data-aos="fade-left" > <img class="d-none d-md-block" src="assets/img/v-icon.png" alt=""> <img class="d-block d-md-none" src="assets/img/v-mobile.png" alt=""> </i> </div> </div> </div> </div> </section> <!---------newLatter Section End ----------> </main> <!---------footer Section START ----------> <footer class="footer-area" > <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="footer__top"> <a href="#"><img src="assets/img/logo.svg" alt=""></a> <a href="#">Pagamentos</a> </div> </div> <div class="col-lg-12"> <div class="footer__btm"> <p>© 2024. Todos os diretos reservados.</p> <ul> <li><a href=""><img src="assets/img/insta.svg" alt=""></a></li> <li><a href=""><img src="assets/img/fb.svg" alt=""></a></li> <li><a href=""><img src="assets/img/twt.svg" alt=""></a></li> <li><a href=""><img src="assets/img/link-in.svg" alt=""></a></li> </ul> </div> </div> </div> </div> </footer> <!---------footer Section End ----------> <!-- JS here --> <script src="assets/js/jquery-3.4.1.min.js"></script> <script src="assets/js/popper.min.js"></script> <script src="assets/js/bootstrap.min.js"></script> <script src="assets/js/aos.js"></script> <script src="assets/js/owl.carousel.min.js"></script> <script src="assets/js/main.js"></script> </body> </html>
package de.mariushoefler.flutterenhancementsuite.editor import com.intellij.lang.Language import com.intellij.psi.ElementDescriptionUtil import com.intellij.psi.PsiElement import com.intellij.refactoring.util.RefactoringDescriptionLocation import com.intellij.ui.breadcrumbs.BreadcrumbsProvider import com.jetbrains.lang.dart.DartLanguage import com.jetbrains.lang.dart.psi.DartClassDefinition import com.jetbrains.lang.dart.psi.DartFactoryConstructorDeclaration import com.jetbrains.lang.dart.psi.DartMethodDeclaration import com.jetbrains.lang.dart.psi.DartPsiCompositeElement import com.jetbrains.lang.dart.psi.DartVarAccessDeclaration import icons.FlutterIcons import javax.swing.Icon /** * Breadcrumbs Navigation Provider for Dart files * * @author Marius Höfler * @since v1.6.1 */ class DartBreadcrumbsInfoProvider : BreadcrumbsProvider { override fun getLanguages(): Array<Language> = arrayOf(DartLanguage.INSTANCE) override fun acceptElement(e: PsiElement) = when (e) { is DartClassDefinition, is DartFactoryConstructorDeclaration, is DartMethodDeclaration, is DartVarAccessDeclaration -> { e is DartPsiCompositeElement && e.name != null } else -> false } override fun getElementInfo(e: PsiElement) = when (e) { is DartClassDefinition -> e.name!! is DartFactoryConstructorDeclaration -> "factory ${e.name}()" is DartMethodDeclaration -> "${e.name}()" is DartVarAccessDeclaration -> e.name!! else -> "" } override fun getElementIcon(element: PsiElement): Icon? { if (element is DartClassDefinition) { if (element.isAbstract) return FlutterIcons.CustomClassAbstract return FlutterIcons.CustomClass } return super.getElementIcon(element) } override fun getElementTooltip(element: PsiElement) = ElementDescriptionUtil.getElementDescription(element, RefactoringDescriptionLocation.WITH_PARENT) }
import java.util.*; class Solution { public long solution(int n, int[] works) { long answer = 0; // 우선순위 큐 선언 ( 역순 정렬 행태로 선언 ) PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); // 최초 원소들의 합계값을 확인해서 답이 0이면 불필요한 연산 없이 메서드 종료하기 위한 변수 int sum = 0; // 우선순위 큐에 업무들을 넣음. for(Integer x : works){ pq.add(x); sum += x; } // 합계와 잔여 시간 비교 if(sum < n){ return 0; } int overtime = 0; // 우선순위 큐에서 원소 하나씩 빼서 잔여시간 중 한시간을 사용해 업무 처리 후 다시 큐에 넣음. while(n>0){ overtime = pq.poll(); overtime-=1; n-=1; pq.add(overtime); } while(pq.size()>0){ overtime = pq.poll(); answer += overtime*overtime; } return answer; } }
package main //运行命令: go run main.go 100 import ( "bufio" //文件读取 "fmt" //打印输出 "os" //文件操作权限 "strconv" //字符转类型转换 "strings" "time" ) const NB_TRAVAILLERUS = 5 //线程数量 // paquet是火车的停站数据 type paquet struct { arrivee string //到达时间 depart string //出发时间 arret int //停站时间,初始为0 } // requet用于处理请求 type requete struct { recu paquet //接收到的火车停站数据 retour chan paquet //返回处理后的结果 } func lecteur(donneesChan chan string, file_name string) { file, err := os.Open(file_name) if err != nil { panic(err) } defer file.Close() //在return之后关闭文件 scanner := bufio.NewScanner(file) scanner.Scan() //跳过第一行 for scanner.Scan() { str := scanner.Text() donneesChan <- str //将读取到的数据发送到donneesChan } } // 数据处理部分 func travailleur(donneesChan chan string, serveurChan chan requete, redacteurChan chan paquet) { for { donnees := <-donneesChan //接收donneesChan里的数据 go func(s string) { params := strings.Split(s, ",") //以","切割字符串 p := paquet{arrivee: params[1], depart: params[2], arret: 0} //创建火车停站数据 priveRetourChan := make(chan paquet) //创建相关chan serveurChan <- requete{recu: p, retour: priveRetourChan} //将停站数据发送给serveurChan paquetRetour := <-priveRetourChan //等待从serveur的处理结果 redacteurChan <- paquetRetour //将处理后的数据打包发送到redacteurChan }(donnees) } } func serveur(serveurChan chan requete) { for { req := <-serveurChan //读取serveurChan里的数据 go func(r requete) { arrivee, _ := time.Parse("15:04:05", r.recu.arrivee) //按照24小时格式来处理信息 depart, _ := time.Parse("15:04:05", r.recu.depart) //同上,处理时间格式 r.recu.arret = int(depart.Sub(arrivee).Seconds()) //出发-到达就是停站时间 res := r.recu r.retour <- res //最后将处理过的数据打包发送回travailleur }(req) //这里也就是说,req就是r requete,上面的只是定义数据类型和名字,这里才是真正使用的数据 } } // 计算总停站时间和平均时长 func redacteur(redacteurChan chan paquet, mainChan chan int) { counter := 0 //班次数量 arretTotal := 0 //总时长 for { select { case paquet := <-redacteurChan: //如果能够读取数据 counter++ arretTotal += paquet.arret //停站时间 case <-mainChan: //如果从mainChan里接收到信息,就开始计算 moyenne := arretTotal / counter fmt.Println("Temps d'arrêt Total: ", arretTotal) fmt.Println("Nombre de trains: ", counter) mainChan <- moyenne //将计算之后的平均数据发送到mainChan里 return } } } func main() { if len(os.Args) < 2 { fmt.Println("Usage: <Time_Waiting>") return } donneesChan := make(chan string) serveurChan := make(chan requete) redacteurChan := make(chan paquet) mainChan := make(chan int) //固定读取stop_times.txt,将读到的数据传输到donneesChan里 go func() { lecteur(donneesChan, "./stop_times.txt") }() //将donneesChan里的数据分批打包传输到serveurChan里和redacteurChan里 for i := 0; i < NB_TRAVAILLERUS; i++ { go func() { travailleur(donneesChan, serveurChan, redacteurChan) }() } //处理时间格式以及停站事件之后,将数据打包成requet go func() { serveur(serveurChan) }() //计算班次,总时长,将平均时长发送到mainChan里 go func() { redacteur(redacteurChan, mainChan) }() //文件运行仅有一个参数,就是main的睡眠时间,需要先进行水眠以保证所有的数据都被读取完之后再正常运行 tempsAttente, _ := strconv.Atoi(os.Args[1]) time.Sleep(time.Duration(tempsAttente) * time.Millisecond) //这里给mainChan输入值,激活redacteur里的第二个情况,开始进行计算并且返回平均值到mainChan里 mainChan <- 0 resultat := <-mainChan fmt.Println("Temps d'arrêt en moyenne: ", resultat) }
# PWR036: Avoid indirect array access to improve performance ### Issue [Indirect array access](../../Glossary/Memory-access-pattern.md) may impact performance. ### Actions Consider using techniques like loop fusion, [loop interchange](../../Glossary/Loop-interchange.md), [loop tiling](../../Glossary/Loop-tiling.md) or changing the data layout to avoid non-consecutive accesses in hot loops. ### Relevance Accessing an array indirectly (e.g. through another array containing the positions to be accessed) is generally less efficient than accessing consecutive positions because the latter improves [locality of reference](../../Glossary/Locality-of-reference.md). ### Code example Consider the example code below to illustrate the presence of indirect access patterns. The elements of array `a` are accessed in an indirect manner through the array b. Thus, the code exhibits random accesses that cannot be predicted before the actual execution of the code. ```c void example(float *a, unsigned *b, unsigned size) { for (unsigned i = 0; i < size; ++i) { a[b[i]] = 0.0f; } } ``` Next, consider another example code where memory access patterns are optimized in order to improve locality of reference. More specifically, the elements of array `a` are accessed indirectly, through array `index`. What this means is that the program is accessing random elements of the array `a`, which leads to a low performance because of the poor usage of the memory subsystem. ```c for (int i = 0; i < LEN_1D; ++i) { for (int j = 1; j < LEN_1D; j++) { c[i] += a[index[j]]; } } ``` The alternative implementation shown below takes advantage of loop interchange to improve locality of reference. Now, the loop over `j` becomes the outer loop, and the loop over `i` becomes the inner loop. By doing this, the access to `a[index[j]]` is an access to a constant memory location, since the value of `j` doesn't change inside the loop. This leads to performance improvement. ```c for (int j = 1; j < LEN_1D; j++) { for (int i = 0; i < LEN_1D; ++i) { c[i] += a[index[j]]; } } ``` ### Related resources * [PWR036 examples](../PWR036) ### References * [Memory access pattern](../../Glossary/Memory-access-pattern.md) (indirect array access) * [Locality of reference](../../Glossary/Locality-of-reference.md) * [Loop interchange](../../Glossary/Loop-interchange.md) * [Loop tiling](../../Glossary/Loop-tiling.md)
import { ref } from 'vue' import { defineStore } from 'pinia' import router from '@/router' import axios from 'axios' const REST_REVIEW_API = `http://localhost:8080/api/Review` export const useReviewStore = defineStore('review', () => { const registReview = function (Review) { console.log(Review) axios({ url : REST_REVIEW_API, method : "POST", data : Review}) .then(() => router.push({ name: 'reviewList'})) .catch((err) => console.log(err)) } const reviewList = ref([]); const searchReview = function (SearchCondition) { axios({ url : REST_REVIEW_API, headers: { "Content-type": "application/json", }, method : "GET", params : SearchCondition}) .then((res) => { console.log(res.data) reviewList.value = res.data }) .catch((err) => console.log(err)) } const SC = ref({ key: "review_place", word: 0, orderBy: "none", orderByDir: "ASC" }); // SC로 장소를 필터링하고나서 , 작성자로 다시 필터링한다. 왜냐하면 복합키이기 때문 const searchReviewDetail = function (placeId, reviewWriter) { SC.value.word = placeId; console.log(SC.value) axios.get(REST_REVIEW_API, SC.value) .then((res) => { reviewList.value = res.data.filter((rs) => rs.reviewWriter == reviewWriter) }) .catch((err) => console.log(err)) }; const updateReview = function (Review) { axios.put(REST_REVIEW_API, Review) .then(() => { router.push(`/trainplace/${Review.reviewPlace}`) router.reload(); }) .catch((err) => console.log(err)) } const updateStar = function (Review) { axios.put(`${REST_REVIEW_API}/star`, Review) .then(() => router.push({ name: 'reviewList'})) .catch((err) => console.log(err)) } const deleteReview = function(Review){ console.log(Review); axios( {url:`${REST_REVIEW_API}/${Review.reviewPlace}/${Review.reviewWriter}`, method: 'delete' }) .then(()=>router.push({ name: 'reviewList'})) .catch((err)=>console.log(err)) } return { registReview, reviewList, searchReview, updateReview, updateStar, deleteReview, searchReviewDetail } }, {persist:true})
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Import dependencies import numpy as np import pandas as pd from pathlib import Path from sklearn.metrics import balanced_accuracy_score, confusion_matrix, classification_report, accuracy_score from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split # In[ ]: # Read the CSV file from the Resources folder into a Pandas DataFrame path = "outputs/emails_df.csv" email_df = pd.read_csv(path) # Review the DataFrame email_df.head() # In[ ]: # Drop the email name column email_df = email_df.drop(columns=email_df.columns[0]) # # Logistic Regression # In[ ]: # Separate the data into labels and features # Separate the y variable, the labels y = email_df['Spam Indicator'] # Separate the X variable, the features X = email_df.drop(columns=['Spam Indicator']) # In[ ]: # Import the train_test_learn module from sklearn.model_selection import train_test_split # Split the data using train_test_split # Assign a random_state of 1 to the function X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y) # In[ ]: # Import the LogisticRegression module from SKLearn from sklearn.linear_model import LogisticRegression # Instantiate the Logistic Regression model # Assign a random_state parameter of 1 to the model classifier = LogisticRegression(solver='lbfgs', max_iter=200, random_state=1) # Fit the model using training data classifier.fit(X_train, y_train) # In[ ]: # Make a prediction using the testing data predictions = classifier.predict(X_test) results = pd.DataFrame({"Prediction": predictions, "Actual": y_test}).reset_index(drop=True) # In[ ]: # Print the balanced_accuracy score of the model balanced_accuracy_score(y_test, predictions) # In[ ]: # Generate a confusion matrix for the model confusion_matrix(y_test, predictions) # In[ ]: # Print the classification report for the model print(classification_report(y_test, predictions)) # In[ ]: # Import the RandomOverSampler module form imbalanced-learn from imblearn.over_sampling import RandomOverSampler # Instantiate the random oversampler model # # Assign a random_state parameter of 1 to the model model = RandomOverSampler(random_state=1) # Fit the original training data to the random_oversampler model X_over, y_over = model.fit_resample(X_train, y_train) # In[ ]: # Count the distinct values of the resampled labels data y_over.nunique() # In[ ]: # Instantiate the Logistic Regression model # Assign a random_state parameter of 1 to the model classifier = LogisticRegression(solver='lbfgs', max_iter=200, random_state=1) # Fit the model using the resampled training data classifier.fit(X_over, y_over) # Make a prediction using the testing data predictions = classifier.predict(X_test) results = pd.DataFrame({"Predictions": predictions, "Actual": y_test}).reset_index(drop=True) # In[ ]: # Print the balanced_accuracy score of the model balanced_accuracy_score(y_test, predictions) # In[ ]: # Generate a confusion matrix for the model confusion_matrix(y_test, predictions) # In[ ]: # Print the classification report for the model print(classification_report(y_test, predictions)) # # Support Vector Machine (SVM) # In[ ]: # Get the target variables. target = email_df["Spam Indicator"] target_names = ["ham", "spam"] # In[ ]: # Get the features. data = email_df.drop(columns=['Spam Indicator']) feature_names = data.columns # In[ ]: # Split data into training and testing from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=1) # In[ ]: # Support vector machine linear classifier from sklearn.svm import SVC model = SVC(kernel='linear') model.fit(X_train, y_train) # In[ ]: # Model Accuracy print('Test Acc: %.3f' % model.score(X_test, y_test)) # In[ ]: # Calculate the classification report from sklearn.metrics import classification_report predictions = model.predict(X_test) print(classification_report(y_test, predictions, target_names=target_names)) # # Random Forest # In[ ]: # Separate the data into labels and features # Separate the y variable, the labels y = email_df['Spam Indicator'] # Separate the X variable, the features X = email_df.drop(columns=['Spam Indicator']) # In[ ]: # Import the train_test_learn module from sklearn.model_selection import train_test_split # Split the data using train_test_split # Assign a random_state of 1 to the function X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y) # In[ ]: # Create the StandardScaler instance scaler = StandardScaler() # In[ ]: # Fit the Standard Scaler with the training data X_scaler = scaler.fit(X_train) # In[ ]: # Scale the training data X_train_scaled = X_scaler.transform(X_train) X_test_scaled = X_scaler.transform(X_test) # In[ ]: # Create the random forest classifier instance rf_model = RandomForestClassifier(n_estimators=500, random_state=78) # In[ ]: # Fit the model and use .ravel()on the "y_train" data. rf_model = rf_model.fit(X_train_scaled, y_train.ravel()) # In[ ]: # Making predictions using the testing data predictions = rf_model.predict(X_test_scaled) # In[ ]: # Calculating the confusion matrix cm = confusion_matrix(y_test, predictions) cm_df = pd.DataFrame( cm, index=["Actual 0", "Actual 1"], columns=["Predicted 0", "Predicted 1"] ) # Calculating the accuracy score acc_score = accuracy_score(y_test, predictions) # In[ ]: # Displaying results print("Confusion Matrix") display(cm_df) print(f"Accuracy Score : {acc_score}") print("Classification Report") print(classification_report(y_test, predictions)) # In[ ]: # Get the feature importance array importances = rf_model.feature_importances_ # List the top 10 most important features importances_sorted = sorted(zip(rf_model.feature_importances_, X.columns), reverse=True) importances_sorted[:10]
# -*- coding: utf-8 -*- from __future__ import division from pathlib import Path import pandas as pd from utils import * def prepare_lsmdc_df(out_df, path_lsmdc_anno_train, path_lsmdc_anno_val, path_lsmdc_anno_test, path_meta): """ :param out_df: The out path of the dataframe for lsmdc annotation summary :param path_lsmdc_anno_train: The path of the training annotation file :param path_lsmdc_anno_val: The path of the validation annotation file :param path_lsmdc_anno_test: The path of the test annotation file :param path_meta: The path of the meta file :return: """ def time2s(t): h, m, s, ms = [int(x) for x in t.split(".")] s = ms / 1000 + s + m * 60 + h * 3600 return s def rm_id(x): """ remove id labels """ x = re.sub(r'<PERSON>.*</PERSON>', 'SOMEONE', x) res = [r'SOMEONE<.+?>', r'SOMEONE\'s<.+?>', r'She<.+?>', r'she<.+?>', r'He<.+?>', r'he<.+?>'] subs = ['SOMEONE', 'SOMEONE\'s', 'She', 'she', 'He', 'he'] for idx, r in enumerate(res): while re.search(r, x): x = re.sub(r, subs[idx], x, 1) return x def rm_someone(x): """ remove someone """ x = x.replace('<PERSON>', '').replace('</PERSON>', '') res = [r'SOMEONE<.+?>', r'SOMEONE\'s<.+?>', r'She<.+?>', r'she<.+?>', r'He<.+?>', r'he<.+?>', r'HE<.+?>'] left = ['SOMEONE<', 'SOMEONE\'s<', 'She<', 'she<', 'He<', 'he<', 'HE'] for idx, r in enumerate(res): while re.search(r, x): x = re.sub(r, re.search(r, x).group(0).replace(left[idx], '', 1).replace('>', '', 1), x, 1) return x df_heads = ["clip", "start_aligned", "end_aligned", "start", "end", "sentence"] df_anno_train = pd.read_csv(path_lsmdc_anno_train, sep="\t", encoding="ISO-8859-1", names=df_heads) df_anno_val = pd.read_csv(path_lsmdc_anno_val, sep="\t", encoding="ISO-8859-1", names=df_heads) df_anno_test = pd.read_csv(path_lsmdc_anno_test, sep="\t", encoding="ISO-8859-1", names=df_heads) df = df_anno_train.append([df_anno_val], ignore_index=True) df = df.drop_duplicates() df["movie"] = df["clip"].apply(lambda x: x.split("_0")[0]) df["movie_name"] = df["movie"].apply(lambda x: ' '.join(x.split('_')[1:]).replace('-', ' ').strip().lower()) df["start_s"] = df["start"].apply(lambda x: time2s(x)) df["end_s"] = df["end"].apply(lambda x: time2s(x)) df["duration"] = df["end_s"] - df["start_s"] df.sort_values(["movie", "start_s", "end_s"], inplace=True) df["start_to_end"] = df["start_s"] - df["end_s"].shift(1) df["end_to_end"] = df["end_s"] - df["end_s"].shift(1) df.fillna(0, inplace=True) df = df.round(5) # fix to_be_fixed = [df[df["movie"] == x].index[0] for x in list(set(df["movie"].to_list()))] for x in to_be_fixed: df.loc[x, "start_to_end"] = 1000.0 df.loc[x, "end_to_end"] = 1000.0 # remove repeated df = df[(~df['movie'].str.contains('1001')) & (~df['movie'].str.contains('1010'))] df['sentence_someone'] = df['sentence'].apply(lambda x: rm_id(x)) df['sentence_id'] = df['sentence'].apply(lambda x: rm_someone(x)) df_meta = pd.read_csv(path_meta, names=['movie', 'link', 'category', 'color'], sep='\t') df_meta['category'] = df_meta['category'].str.lower() df_meta['movie_name'] = df_meta['movie'].str.replace('-', ' ').str.replace('_', '').str.lower().str.strip() df_meta = df_meta[['movie_name', 'category']] assert df.merge(df_meta, on='movie_name').shape[0] == df.shape[0] df = df.merge(df_meta, on='movie_name') df = df[ ["movie", "movie_name", "clip", "category", "start_s", "end_s", "start_to_end", "end_to_end", "duration", "start_aligned", "end_aligned", "sentence", "sentence_someone", "sentence_id"]] df.reset_index(drop=True, inplace=True) df.to_csv(out_df, index=False, sep='\t') def load_lsmdc_df(path_df): return pd.read_csv(path_df, encoding="ISO-8859-1", sep='\t') def to_movie_name(movie): """ convert original LSMDC movie name to readable movie name for example, 0001_American_Beauty -> american beauty :param movie: :return: """ return movie.replace('_', ' ').replace('-', ' ').lower() def indexing_lsmdc(out_json, path_frames): """ index the LSMDC dataset as json file :param out_json: the output json file :param path_frames: the path of the frames root folder :return: """ movies = sorted(list(path_frames.glob('*')), key=natural_keys_obj) clips = [list(m.glob('*')) for m in movies] frame_nb = [[len(list(c.glob('*.jpg'))) for c in c_lst] for c_lst in clips] # index to names i2n = {str(i_m): [m.name, {str(i_c): c.name for i_c, c in enumerate(clips[i_m])}] for i_m, m in enumerate(movies)} # names to index n2i = {m.name: [str(i_m), {c.name: str(i_c) for i_c, c in enumerate(clips[i_m])}] for i_m, m in enumerate(movies)} data = {i_m: {c: frame_nb[int(i_m)][int(c)] for c in i2n[i_m][1]} for i_m in i2n.keys()} json_dump(out_json, { 'data': data, 'i2n': i2n, 'n2i': n2i }, formatting=False) def lsmdc_dict(lsmdc): """ Get the LSMDC frame entire structure as a dictionary { 'i2n': {'0': ['0001_American_Beauty', {'0': 'clip_0', '1': 'clip_1', ...}]}, 'n2i': {'0001_American_Beauty': ['0', {'clip_0': '0', 'clip_1': '1', ...}]}, 'data': {'0': {'0': (number of clips), '1': (number of clips), ...}} } To save space, using i2n for "index to name", use n2i for "name to index" :param lsmdc: the loaded LSMDC json file :return: """ i2n = lsmdc['i2n'] d = lsmdc['data'] d_ = {i2n[m][0]: { i2n[m][1][c]: list(range(d[m][c])) for c in d[m] } for m in d} return d_ def get_clips(movie, lsmdc): """ Get the clips of a movie :param movie: the movie name :param lsmdc: the loaded LSMDC json file :return: """ clips = sorted(lsmdc['n2i'][movie][1].keys()) return clips def mc2i(m, c, lsmdc): """ Get the "id" of a movie clip. The "id" is used in a dataset json file :param m: movie name :param c: clip name :param lsmdc: the loaded LSMDC json file :return: the "id" of a movie clip """ ref = lsmdc['n2i'][m] i = 'l_{}_{}'.format(ref[0], ref[1][c]) return i def mcf2i(m, c, f): """ Get the "id" of a movie clip frame. The "id" is used in a dataset json file :param m: movie name :param c: clip name :param f: frame index :return: the "id" of a movie clip frame """ ref = lsmdc['n2i'][m] i = 'l_{}_{}_{}'.format(ref[0], ref[1][c], f) return i def i2mcf(i): """ "id" to names of movie, clip, frame :param i: the "id" of a movie clip frame :return: movie name, clip name, frame index """ _, i_m, i_c, i_f = i.split("_") ref = lsmdc["i2n"][i_m] m = ref[0] c = ref[1][i_c] return m, c, i_f def i2mc(i): """ "id" to names of movie, clip :param i: the "id" of a movie clip :return: movie name, clip name """ _, i_m, i_c = i.split("_") ref = lsmdc["i2n"][i_m] m = ref[0] c = ref[1][i_c] return m, c if __name__ == '__main__': path_base = Path(__file__).resolve().parent path_data = path_base / "data" path_lsmdc = path_data / "lsmdc.json" lsmdc = json.load(path_lsmdc.open('r')) data = lsmdc_dict()
package com.github.dillonfarber.thelistoffavorites.mediaTypes import android.content.Context import android.content.Intent import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.RecyclerView import com.github.dillonfarber.thelistoffavorites.APIs.TMDB_API import com.github.dillonfarber.thelistoffavorites.CardBlowupActivity import com.github.dillonfarber.thelistoffavorites.DataClasses.TMDB.TMDB_MovieResults import com.github.dillonfarber.thelistoffavorites.MovieCardActivity import com.github.dillonfarber.thelistoffavorites.R import com.squareup.picasso.Picasso class MoviesAdapter(private val context: Context, movieArrayList: ArrayList<TMDB_MovieResults>) : RecyclerView.Adapter<MoviesAdapter.ViewHolder>(){ private val movieArrayList: ArrayList<TMDB_MovieResults> override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.activity_card_view, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val model: TMDB_MovieResults = movieArrayList[position] Picasso.get().load("https://image.tmdb.org/t/p/w185/${model.posterPath}") .placeholder(R.drawable.controller) .into(holder.cover) holder.cover.setOnClickListener{ TMDB_API.getMovieDetails(model.id!!) val intent = Intent(context, MovieCardActivity::class.java) context.startActivity(intent) } } override fun getItemCount(): Int { return movieArrayList.size } class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){ val cover: ImageView init{ cover = itemView.findViewById(R.id.coverImage) } } init { this.movieArrayList = movieArrayList } }
import { isFunction } from '@universal-ui/utils'; import { useMemo } from 'react'; export function setRef<T>( ref: React.MutableRefObject<T | null> | ((instance: T | null) => void) | null | undefined, value: T | null, ): void { if (isFunction(ref)) { ref(value); } else if (ref) { // eslint-disable-next-line no-param-reassign ref.current = value; } } export function useForkRef<T>(...refs: (React.Ref<T> | undefined)[]): React.RefCallback<T> | null { /** * This will create a new function if the refs passed to this hook change and * are all defined. This means React will call the old forkRef with `null` and * the new forkRef with the ref. Cleanup naturally emerges from this behavior. */ return useMemo(() => { if (refs.every((ref) => ref == null)) { return null; } return (instance) => { for (const ref of refs) { setRef(ref, instance); } }; // eslint-disable-next-line react-hooks/exhaustive-deps }, refs); }
class StackCalculator { constructor() { this.stack = []; } putValue(value) { this.stack.push(value); } getValue() { return this.stack.pop(); } peekValue() { return this.stack[this.stack.length - 1]; } clear() { this.stack = []; } divide() { const divisor = this.getValue(); const dividend = this.getValue(); const result = dividend / divisor; this.putValue(result); return result; } multiply() { const multiplicand = this.getValue(); const multiplier = this.getValue(); const result = multiplier * multiplicand; this.putValue(result); return result; } } function patchToSafeCalculator(calculator) { const divideOrig = calculator.divide; calculator.divide = () => { const divisor = calculator.peekValue(); if (divisor === 0) { throw Error('Division by 0'); } return divideOrig.apply(calculator); }; return calculator; } const calculator = new StackCalculator(); const safeCalculator = patchToSafeCalculator(calculator); calculator.putValue(3); calculator.putValue(2); console.log(calculator.multiply()); safeCalculator.putValue(2); console.log(safeCalculator.multiply()); calculator.putValue(0); console.log(calculator.divide()); safeCalculator.clear(); safeCalculator.putValue(4); safeCalculator.putValue(0); console.log(safeCalculator.divide());
/** * Sets * Set in JavaScript is a collection of items that are unique i.e no element can be repeated. * Set in ES6 are ordered: elements of the set can be iterated in the insertion order. * A set can store any type of value whether primitive or objects. */ // ES6 Set let sets = new Set([4,4,3,3,2,2,1,1,0,0,'A','B','C']); console.log(sets); // Set(4) { 1, 2, 3, 4 } -- Only unique values sets.forEach((e, i) => { console.log(e, i); }); sets.add(10); sets.add(20); sets.add(30); console.log(sets); console.log(sets, sets.has(10), sets.delete(10)); // delete value and return boolean: true true console.log(sets, sets.has(10), sets.delete(10)); // delete value and return boolean: false false for (const iterator of sets.values()) { console.log(iterator); } sets.delete('A'); sets.delete('B'); sets.delete('C'); console.log("Minimum element: " + Math.min(...sets)); console.log("Maximum element: " + Math.max(...sets)); console.log("Size of the set is: " + sets.size); // Printing the size of the set
import { Configuration, OpenAIApi } from "openai"; import express from "express"; import bodyParser from "body-parser"; import cors from 'cors'; const configuration = new Configuration({ organization: "", apiKey: "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" }); const openai = new OpenAIApi(configuration); const app = express(); const port = 5004; app.use(bodyParser.json()); app.use(cors()); app.post("/", async (req, res) => { const { messages } = req.body; console.log(messages); const formattedMessages = messages.map((message) => { return { role: "user", content: message }; }); const completion = await openai.createChatCompletion({ model: "gpt-3.5-turbo", messages: [ { role: "system", content: "You are Deepika Padukone , who is a highly acclaimed Indian actress known for her talent, beauty, and versatility in portraying diverse roles. With her exceptional performances and strong screen presence, she has become one of the leading actresses in Bollywood.and you have access to all the content of him so reply as if you are if you are Deepika Padukone" }, ...formattedMessages ] }); res.json({ completion: completion.data.choices[0].message }); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); }); export default app;
import readline from "node:readline"; import prisma from "@/lib/prisma"; import { createHashedPassword } from "@/lib/auth/auth.helpers"; interface QuestionData { email: string; password: string; } const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const askQuestion = async (query: string): Promise<string> => { return new Promise((resolve) => rl.question(query, resolve)); }; const userCountQuestion = async () => { const answer = await askQuestion("How many users would you like to create?"); const numberedValue = Number(answer); if (isNaN(numberedValue) || numberedValue < 1) throw new Error("Invalid number"); return numberedValue; }; const updateUserQuestion = async ( count: number, answers: QuestionData[] = [] ) => { if (count <= 0) return; const email = await askQuestion("Enter email: "); const password = await askQuestion("Enter password: "); answers.push({ email, password }); await updateUserQuestion(count - 1, answers); }; async function main() { const userCount = await userCountQuestion(); const answers: QuestionData[] = []; console.log(`--- Creating ${userCount} users ---`); await updateUserQuestion(userCount, answers); const confirmAnswer = await askQuestion( "Confirm accounts to be created. Press enter to continue or type in NO to cancel: " ); if (confirmAnswer === "NO") { console.log("Canceled creating users"); rl.close(); return; } for (const user of answers) { const encrypted_password = await createHashedPassword(user.password); await prisma.user.upsert({ where: { email: user.email }, update: { encrypted_password }, create: { email: user.email, encrypted_password }, }); } console.log("Users created! 🚀"); } main() .catch((e) => { console.log("SEEDING ERROR::: 🥺 \n"); console.error(e); process.exit(1); }) .finally(async () => { await prisma.$disconnect(); rl.close(); });
import { CatsRepository } from './cats.repository'; import { CatRequestDto } from './dto/cats.request.dto'; import { Injectable, HttpException } from '@nestjs/common'; // import { InjectModel } from '@nestjs/mongoose'; import { Cat } from './cats.schema'; // import { Model } from 'mongoose'; import * as bcrypt from 'bcrypt'; @Injectable() export class CatsService { // 서비스 로직에서 디비에 쿼리를 하기위해 스키마를 사용해야한다. // 모듈에 등록된 스키마를 데코레이터를 사용하여 서비스로직에서 사용할수있게 주입해야한다. // 스키마를 사용하려면 해당 클래스에 디펜더싱 인젝션을 해주어야하는데 아래와 같이 진행된다. // constructor(@InjectModel(Cat.name) private readonly catModel: Model<Cat>) {} // Repository 적용(module의 provider에 CatsRepository를 추가해주고 사용해야한다.) constructor(private readonly catsRepository: CatsRepository) {} // 안에서 await를 필요함으로 async함수로 선언 async signUp(data: CatRequestDto) { const { email, password, name } = data; // 해당 이메일이 디비에 존재하는지 안한는지 exists쿼리를 사용하여 확인한다. const checkEmail = await this.catsRepository.existsByEmail(email); if (checkEmail) { throw new HttpException( '해당 이메일은 이미 존재하는 이메일 입니다.', 401, ); } // 비밀번호는 암호화해서 저장해야하기에 bcrypt를 사용하여 해쉬후 저장한다. // bycrpt는 프로미스값을 리턴하기에 await를 걸어주어 값을 받고 진행되게 한다. const hashpassword = await bcrypt.hash(password, 10); const cat: Cat = await this.catsRepository.catsCreate({ email: email, name: name, password: hashpassword, }); // 버추얼 필드를 사용하여 내가 원하는 형태로 값을 넘겨준다. return cat.readOnlyData; } // 파일 업로드된 것을 디비에 저장후 정보를 리턴 async uploadImg(cat: Cat, files: Express.Multer.File[]) { const file_url = files.map( (f) => `http://localhost:8000/media/cats/${f.filename}`, ); // catRepository를 사용하여 db작업후 새로운 cat정보를 받는다. const newcat = await this.catsRepository.catsUpdateImg(cat.id, file_url); return newcat; } // 모든 고양이 사진 들고 오기 async getAllCats() { const allcat: Cat[] = await this.catsRepository.allCats(); const readOnlyCats = allcat.map((cat) => cat.readOnlyData); return readOnlyCats; } }
# Tennis colab compete RL ## Algorithm The algorithm used to optimize learning was the deep deterministic policy gradient (DDPG). This algorithm uses two sets of networks for each agent, the actor and the critical, each with a local and a target network. The actor's function is to return an action for each state (that is deterministic part of the algorithm), and the critical returns the Q value from the state and the action that the actor returns. Each network starts with the random weights, which induce exploration in the first episodes. At each step, an action is selected through the actor, and the environment returns the reward, the next state and if the episode ended (done). That is, at each step we have a set of state, action, reward, next state and done, this set is considered an experience and is saved in an experience buffer. As soon as we have enough experience, the system starts to learn. Learning happens at the end of each step, in this process, a number of previous experiences are selected and the weights of the networks are updated. the ddpg algorithm was first developed for the case of a single agent. To generalize to more agents, there is a single buffer that saves the experience of all agents. Critical networks observe the experiences of all agents, however the actor continues to learn only from the agent's own experiences. The critical network is updated from the difference between the Q-value of the current state and the Q-value of the next state plus the reward. <div style="text-align: center;">Q_targets_next = critic_target(next_state, action_next)</div> <div style="text-align: center;">Q_target = reward + gamma * Q_targets_next</div> <div style="text-align: center;">Q_expected = critic_local(state, action)</div> <div style="text-align: center;">critic_loss = loss_function(Q_expected, Q_target) </div> The actor network is updated using the gradient of the critical network when receiving the states and actions predicted by the actor network. <div style="text-align: center;">actions_pred = actor_local(state)</div> <div style="text-align: center;">actor_loss = -critic_local(state, actions_pred)</div> The fact that the action is determined by one network and the Q value is calculated in another one increases the stability of the algorithm. More details about the algorithm [here](https://papers.nips.cc/paper/2017/file/68a9750337a418a86fe06c1991a1d64c-Paper.pdf). We also added some changes to the algorithm, so it could converge. First, we add an epsilon parameter, this parameter represents the agent's chance to choose a random action instead of the action returned by the actor. Thus, in the first episodes the actions are chosen in a predominantly random way, which necessarily makes some actions with positive rewards added to the buffer. Second, the ddpg algorithm tends to overestimate the Q-value, to minimize this effect we add a noise in the state that the actor observes. Finally, we added a delay between the learning of the local actor and other networks. The learning of critical networks and the target actor only occurs every two times that the local actor learns. ## Hyperparameters | Hyperparameter | Value | | ----------------------------------- | ----- | | Replay buffer size | 1e5 | | Batch size | 128 | | Gamma | 0.99 | | Tau | 1e-3 | | Epsilon initial | 1 | | Epsilon decay | 0.998 | | Epsilon min | 1e-3 | | Theta | 0.2 | | Sigma | 0.15 | | Learning rate actor | 1e-4 | | Learning rate critic | 1e-3 | | POLICY_DELAY | 2 | | Weight decay | 0 | | Number of episodes | 10000 | ## Model architeture ### Actor The local and the target networks have the same architecture. Input layer: 24 linear nodes (the state size of a single agent). First hidden layer: 256 linear nodes. Second hidden layer: 128 linear nodes. Output layer: 2 linear nodes (the action size of a single agent). Between each layer there is a ReLU activation function and a hyperbolic tangent after the output layer. ### Critic The local and the target networks have the same architecture. Input layer: 56 linear nodes (the state size * agents + action size * agents). First hidden layer: 260 linear nodes (256 + action size * agents). Second hidden layer: 128 linear nodes. Output layer: 1 linear node (the Q value). Between each layer there is a ReLU activation function.
/* * file-path.test.ts * * Copyright (C) 2022 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ import { describe } from 'mocha'; import { assert } from 'chai'; import { randomString } from '../unit-utils'; import fs from 'fs'; import fsPromises from 'fs/promises'; import path from 'path'; import os from 'os'; import { FilePath } from '../../../src/core/file-path'; import { userHomePath } from '../../../src/core/user'; import { setLogger, NullLogger } from '../../../src/core/logger'; import { clearCoreSingleton } from '../../../src/core/core-state'; import { isFailure, isSuccessful } from '../../../src/core/err'; function realpathSync(path: string): string { return fs.realpathSync(path); } async function realpath(path: string): Promise<string> { return fsPromises.realpath(path); } function getTestDir(): FilePath { return new FilePath(path.join(os.tmpdir(), 'rstudio-temp-tests-' + randomString())); } // A path that should never exist const bogusPath = '/super/bogus/path/42'; // A path that a non-elevated user cannot create const cannotCreatePath = process.platform === 'win32' ? 'C:\\Program Files\\a_test_folder' : '/foo/bar/crazy'; // An absolute path in generic format (see boost filesystem for description of "generic" format) const absolutePath = process.platform === 'win32' ? 'C:/Users/human/documents' : '/users/human/documents'; describe('FilePath', () => { before(() => { setLogger(new NullLogger()); }); after(() => { clearCoreSingleton(); }); afterEach(() => { // make sure we leave cwd in a valid place process.chdir(__dirname); }); describe('Constructor checks', () => { it('Should store and return the supplied path', () => { const path1 = 'hello/world'; const path2 = '~/foo'; const path3 = '/once/upon/a/time'; const path4 = '~'; assert.strictEqual(new FilePath(path1).getAbsolutePath(), path1); assert.strictEqual(new FilePath(path2).getAbsolutePath(), path2); assert.strictEqual(new FilePath(path3).getAbsolutePath(), path3); assert.strictEqual(new FilePath(path4).getAbsolutePath(), path4); assert.strictEqual(new FilePath(path3).toString(), path3); }); it('Should create empty path when given no arguments', () => { const path = new FilePath(); assert.isEmpty(path.getAbsolutePath()); assert.isTrue(path.isEmpty()); }); it('getAbsolutePathNative should return raw path on Windows', () => { if (process.platform === 'win32') { const originalPath = 'C:\\Windows\\Was\\Here'; const fp1 = new FilePath(originalPath); const native = fp1.getAbsolutePathNative(); assert(native === originalPath); } }); }); describe('Comparisons', () => { it('equals should return true if storing exact same path string', () => { const path1 = new FilePath('/hello/world'); const path2 = new FilePath('/hello/world'); assert.isTrue(path1.equals(path2)); }); it('equals should return false if they are storing different path strings', () => { const path1 = new FilePath('/hello/world'); const path2 = new FilePath('/hello/../hello/world'); assert.isFalse(path1.equals(path2)); }); it('equals should return true if both are empty', () => { const path1 = new FilePath(); const path2 = new FilePath(); assert.isTrue(path1.equals(path2)); }); it('isWithin should handle detect simple path containment checks', () => { const pPath = new FilePath('/path/to'); const aPath = new FilePath('/path/to/a'); const bPath = new FilePath('/path/to/b'); assert.isTrue(aPath.isWithin(pPath)); assert.isTrue(bPath.isWithin(pPath)); assert.isFalse(aPath.isWithin(bPath)); }); it('isWithin should not be fooled by directory traversal', () => { // the first path is not inside the second even though it appears to be lexically const aPath = new FilePath('/path/to/a/../b'); const bPath = new FilePath('path/to/a'); assert.isFalse(aPath.isWithin(bPath)); }); it('isWithin should not be fooled by substrings', () => { const cPath = new FilePath('/path/to/foo'); const dPath = new FilePath('path/to/foobar'); assert.isFalse(dPath.isWithin(cPath)); }); }); describe('Retrieval methods', () => { it('getCanonicalPathSync should return empty results for empty path', () => { const f = new FilePath(); assert.isFalse(f.existsSync()); assert.isFalse(!!f.getAbsolutePath()); assert.isTrue(f.isEmpty()); assert.isTrue(f.isWithin(f)); assert.isFalse(f.isWithin(new FilePath('/some/path'))); assert.isEmpty(f.getCanonicalPathSync()); assert.isEmpty(f.getExtension()); assert.isEmpty(f.getExtensionLowerCase()); assert.isEmpty(f.getFilename()); }); it('getCanonicalPathSync should return a non-empty path for a path that exists', () => { const f = new FilePath(os.tmpdir()); assert.isTrue(f.existsSync()); assert.isNotEmpty(f.getCanonicalPathSync()); }); it("getCanonicalPathSync should return an empty path for a path that doesn't exist", () => { const f = new FilePath('/some/really/bogus/path'); assert.isFalse(f.existsSync()); assert.isEmpty(f.getCanonicalPathSync()); }); it('getCanonicalPath should return empty results for empty path', async () => { const f = new FilePath(); assert.isFalse(await f.existsAsync()); assert.isFalse(!!f.getAbsolutePath()); assert.isTrue(f.isEmpty()); assert.isTrue(f.isWithin(f)); assert.isFalse(f.isWithin(new FilePath('/some/path'))); assert.isEmpty(await f.getCanonicalPath()); }); it('getCanonicalPath should return a non-empty path for a path that exists', async () => { const f = new FilePath(os.tmpdir()); assert.isTrue(await f.existsAsync()); assert.isNotEmpty(await f.getCanonicalPath()); }); it("getCanonicalPath should return an empty path for a path that doesn't exist", async () => { const f = new FilePath('/some/really/bogus/path'); assert.isFalse(await f.existsAsync()); const result = await f.getCanonicalPath(); assert.isEmpty(result); }); it('getExtension should return the extension including leading period', () => { const f = new FilePath('/some/stuff/hello.tXt'); assert.strictEqual(f.getExtension(), '.tXt'); }); it('getExtension should return no extension for extension-only filename', () => { const f = new FilePath('/some/stuff/.foo'); assert.isEmpty(f.getExtension()); }); it('getExtension should return blank extension for file without extension', () => { const f = new FilePath('/some/stuff/hello'); assert.isEmpty(f.getExtension()); }); it('getExtensionLowerCase should return the extension in lowercase', () => { const f = new FilePath('/some/stuff/hello.tXt'); assert.strictEqual(f.getExtensionLowerCase(), '.txt'); }); it('getExtensionLowerCase should return blank extension for file without extension', () => { const f = new FilePath('/some/stuff/hello'); assert.isEmpty(f.getExtension()); }); it('getFilename should return filename including extension', () => { const f = new FilePath('/etc/foo/hello.txt.world'); assert.strictEqual(f.getFilename(), 'hello.txt.world'); }); it('getFilename should return filename when there is no extension', () => { const f = new FilePath('/etc/foo/hello'); assert.strictEqual(f.getFilename(), 'hello'); }); it('getFilename should return filename for extension-only filename', () => { const f = new FilePath('/etc/foo/.hello'); assert.strictEqual(f.getFilename(), '.hello'); }); it('getLastWriteTimeSync should return zero for non-existent file', () => { const f = new FilePath('/some/file/that/will/not/exist'); assert.strictEqual(f.getLastWriteTimeSync(), 0); }); it('getStem returns the file stem', () => { assert.equal(new FilePath('/path/to/file.txt').getStem(), 'file'); assert.equal(new FilePath('file.txt').getStem(), 'file'); assert.equal(new FilePath('noExtension').getStem(), 'noExtension'); assert.equal(new FilePath('.hiddenFile.txt').getStem(), '.hiddenFile'); assert.equal(new FilePath('.hiddenFileNoExtension').getStem(), '.hiddenFileNoExtension'); // You could debate that this should only return 'file'. Including test here to show current behavior assert.equal(new FilePath('/path/to/file.extra.txt').getStem(), 'file.extra'); // A full path to a file with no extension is ambiguous. Including test here to show current behavior assert.equal(new FilePath('/path/to/noExtensionOrDirectory').getStem(), 'noExtensionOrDirectory'); assert.equal(new FilePath('/path/to/directory/').getStem(), ''); }); }); describe('Get a safe current path', () => { it('safeCurrentPathSync should return current working directory if it exists', () => { const cwd = new FilePath(process.cwd()); const rootPath = new FilePath('/'); const currentPath = FilePath.safeCurrentPathSync(rootPath); assert.strictEqual(currentPath.getAbsolutePath(), cwd.getAbsolutePath()); assert.strictEqual(realpathSync(cwd.getAbsolutePath()), realpathSync(process.cwd())); }); it("safeCurrentPathSync should change to supplied safe path if it exists if cwd doesn't exist", () => { const origDir = new FilePath(process.cwd()); // create a temp folder, chdir to it, then delete it let testDir = getTestDir().getAbsolutePath(); fs.mkdirSync(testDir); process.chdir(testDir); testDir = realpathSync(testDir); try { fs.rmdirSync(testDir); } catch (error: unknown) { // On Windows, trying to remove current-working-directory may fail so can't // execute rest of this test case; cleanup and exit assert.isTrue(process.platform === 'win32'); assert.doesNotThrow(() => process.chdir(origDir.getAbsolutePath())); assert.doesNotThrow(() => fs.rmdirSync(testDir)); return; } const currentPath = FilePath.safeCurrentPathSync(origDir); assert.strictEqual(realpathSync(origDir.getAbsolutePath()), realpathSync(process.cwd())); assert.strictEqual(realpathSync(currentPath.getAbsolutePath()), realpathSync(process.cwd())); }); it("safeCurrentPathSync should change to home folder when both cwd and revert paths don't exist", () => { const origDir = new FilePath(process.cwd()); // create a temp folder, chdir to it, then delete it let testDir = getTestDir().getAbsolutePath(); fs.mkdirSync(testDir); process.chdir(testDir); testDir = realpathSync(testDir); try { fs.rmdirSync(testDir); } catch (error: unknown) { // On Windows, trying to remove current-working-directory may fail so can't // execute rest of this test case; cleanup and exit assert.isTrue(process.platform === 'win32'); assert.doesNotThrow(() => process.chdir(origDir.getAbsolutePath())); assert.doesNotThrow(() => fs.rmdirSync(testDir)); return; } const currentPath = FilePath.safeCurrentPathSync(new FilePath(bogusPath)); assert.strictEqual(realpathSync(currentPath.getAbsolutePath()), realpathSync(os.homedir())); }); it('safeCurrentPath should return current working directory if it exists', async () => { const cwd = new FilePath(process.cwd()); const rootPath = new FilePath('/'); const currentPath = await FilePath.safeCurrentPath(rootPath); assert.strictEqual(currentPath.getAbsolutePath(), cwd.getAbsolutePath()); assert.strictEqual(await realpath(cwd.getAbsolutePath()), await realpath(process.cwd())); }); it("safeCurrentPath should change to supplied safe path if it exists if cwd doesn't exist", async () => { const origDir = new FilePath(process.cwd()); // create a temp folder, chdir to it, then delete it let testDir = getTestDir().getAbsolutePath(); await fsPromises.mkdir(testDir); process.chdir(testDir); testDir = await realpath(testDir); try { await fsPromises.rmdir(testDir); } catch (error: unknown) { // On Windows, trying to remove current-working-directory may fail so can't // execute rest of this test case; cleanup and exit assert.isTrue(process.platform === 'win32'); assert.doesNotThrow(() => process.chdir(origDir.getAbsolutePath())); assert.doesNotThrow(() => fs.rmdirSync(testDir)); return; } const currentPath = await FilePath.safeCurrentPath(origDir); assert.strictEqual(await realpath(origDir.getAbsolutePath()), await realpath(process.cwd())); assert.strictEqual(await realpath(currentPath.getAbsolutePath()), await realpath(process.cwd())); }); it("safeCurrentPath should change to home folder when both cwd and revert paths don't exist", async () => { const origDir = new FilePath(process.cwd()); // create a temp folder, chdir to it, then delete it let testDir = getTestDir().getAbsolutePath(); await fsPromises.mkdir(testDir); process.chdir(testDir); testDir = await realpath(testDir); try { await fsPromises.rmdir(testDir); } catch (error: unknown) { // On Windows, trying to remove current-working-directory may fail so can't // execute rest of this test case; cleanup and exit assert.isTrue(process.platform === 'win32'); assert.doesNotThrow(() => process.chdir(origDir.getAbsolutePath())); assert.doesNotThrow(() => fs.rmdirSync(testDir)); return; } const currentPath = await FilePath.safeCurrentPath(new FilePath(bogusPath)); assert.strictEqual(await realpath(currentPath.getAbsolutePath()), await realpath(os.homedir())); }); }); describe('Path existence checks', () => { it("isEmpty should detect if this object's path is empty", () => { assert.isTrue(new FilePath().isEmpty()); }); it("existsSync should detect when object's path exists", () => { assert.isTrue(new FilePath(os.tmpdir()).existsSync()); }); it('existsSync should return false for empty path', () => { assert.isFalse(new FilePath('').existsSync()); }); it("existsSync should detect when object's path doesn't exist", () => { assert.isFalse(new FilePath(bogusPath).existsSync()); }); it('existsSync should detect when a supplied path exists', () => { assert.isTrue(FilePath.existsSync(os.tmpdir())); }); it("existsSync should detect when a supplied path doesn't exist", () => { assert.isFalse(FilePath.existsSync(bogusPath)); }); it('existsSync should return false for existence of a null path', () => { assert.isFalse(new FilePath().existsSync()); }); it('exists should return false for empty path', async () => { assert.isFalse(await new FilePath().existsAsync()); }); it("exists should detect when object's path exists", async () => { assert.isTrue(await new FilePath(os.tmpdir()).existsAsync()); }); it("exists should detect when object's path doesn't exist", async () => { assert.isFalse(await new FilePath(bogusPath).existsAsync()); }); it('exists should detect when a supplied path exists', async () => { assert.isTrue(await FilePath.existsAsync(os.tmpdir())); }); it("exists should detect when a supplied path doesn't exist", async () => { assert.isFalse(await FilePath.existsAsync(bogusPath)); }); it('exists should return false for existence of a null path', async () => { assert.isFalse(await new FilePath().existsAsync()); }); }); describe('Synchronous Directory creation', () => { it('createDirectorySync should create directory stored in FilePath', () => { const target = path.join(os.tmpdir(), randomString()); const fp = new FilePath(target); assert(isSuccessful(fp.createDirectorySync())); assert.isTrue(fp.existsSync()); fs.rmdirSync(target); }); it('createDirectorySync should succeed if directory in FilePath already exists', () => { const target = path.join(os.tmpdir(), randomString()); const fp = new FilePath(target); assert(isSuccessful(fp.createDirectorySync())); assert.isTrue(fp.existsSync()); assert(isSuccessful(fp.createDirectorySync())); assert.isTrue(fp.existsSync()); fs.rmdirSync(target); }); it('createDirectorySync should create directory relative to path in FilePath', () => { const target = randomString(); const fp = new FilePath(os.tmpdir()); assert(isSuccessful(fp.createDirectorySync(target))); const newPath = path.join(os.tmpdir(), target); assert.isTrue(fs.existsSync(newPath)); fs.rmdirSync(newPath); }); it('createDirectorySync should recursively create directories', () => { const target = path.join(os.tmpdir(), randomString(), randomString()); const fp = new FilePath(target); assert(isSuccessful(fp.createDirectorySync())); assert.isTrue(fp.existsSync()); fs.rmdirSync(target); }); it('createDirectorySync should recursively create directories relative to path in FilePath', () => { const firstLevel = randomString(); const extraFolder = randomString(); const target = path.join(os.tmpdir(), firstLevel, randomString()); const fp = new FilePath(target); const result = fp.createDirectorySync(extraFolder); assert(isSuccessful(result)); const newPath = path.join(target, extraFolder); assert.isTrue(fs.existsSync(newPath)); fs.rmdirSync(path.join(os.tmpdir(), firstLevel), { recursive: true }); }); it('createDirectorySync should fail when it cannot create the directory', () => { const fp = new FilePath(cannotCreatePath); assert.isFalse(fp.existsSync()); let result = fp.createDirectorySync(''); assert(isFailure(result)); result = fp.createDirectorySync('stuff'); assert(isFailure(result)); }); it('createDirectorySync should ignore base when given an absolute path', () => { const fp = new FilePath(cannotCreatePath); assert.isFalse(fp.existsSync()); const target = path.join(os.tmpdir(), randomString()); const result = fp.createDirectorySync(target); assert(isSuccessful(result)); assert.isTrue(fs.existsSync(target)); fs.rmdirSync(target); }); it('ensureDirectorySync should return success when asked to ensure existing directory exists', () => { const existingFolder = new FilePath(os.homedir()); assert.isTrue(existingFolder.existsSync()); const result = existingFolder.ensureDirectorySync(); assert(isSuccessful(result)); }); it('ensureDirectorySync should create directory when asked to ensure it exists', () => { const newFolder = path.join(os.tmpdir(), randomString()); const newFilePath = new FilePath(newFolder); assert.isFalse(fs.existsSync(newFolder)); const result = newFilePath.ensureDirectorySync(); assert(isSuccessful(result)); assert.isTrue(fs.existsSync(newFolder)); fs.rmdirSync(newFolder); }); it('ensureDirectory should return success when asked to ensure existing directory exists', async () => { const existingFolder = new FilePath(os.homedir()); assert.isTrue(await existingFolder.existsAsync()); const result = await existingFolder.ensureDirectory(); assert(isSuccessful(result)); }); it('ensureDirectory should create directory when asked to ensure it exists', async () => { const newFolder = path.join(os.tmpdir(), randomString()); const newFilePath = new FilePath(newFolder); assert.isFalse(await FilePath.existsAsync(newFolder)); const result = await newFilePath.ensureDirectory(); assert(isSuccessful(result)); assert.isTrue(await FilePath.existsAsync(newFolder)); await fsPromises.rmdir(newFolder); }); }); describe('Async Directory creation', () => { it('createDirectory should create directory stored in FilePath', async () => { const target = path.join(os.tmpdir(), randomString()); const fp = new FilePath(target); const result = await fp.createDirectory(); assert(isSuccessful(result)); assert.isTrue(await fp.existsAsync()); await fsPromises.rmdir(target); }); it('createDirectory should succeed if directory in FilePath already exists', async () => { const target = path.join(os.tmpdir(), randomString()); const fp = new FilePath(target); let result = await fp.createDirectory(); assert.isTrue(await fp.existsAsync()); result = await fp.createDirectory(); assert(isSuccessful(result)); assert.isTrue(await fp.existsAsync()); await fsPromises.rmdir(target); }); it('createDirectory should create directory relative to path in FilePath', async () => { const target = randomString(); const fp = new FilePath(os.tmpdir()); assert(isSuccessful(await fp.createDirectory(target))); const newPath = path.join(os.tmpdir(), target); assert.isTrue(await FilePath.existsAsync(newPath)); await fsPromises.rmdir(newPath); }); it('createDirectory should recursively create directories', async () => { const target = path.join(os.tmpdir(), randomString(), randomString()); const fp = new FilePath(target); const result = await fp.createDirectory(); assert(isSuccessful(result)); assert.isTrue(await fp.existsAsync()); await fsPromises.rmdir(target); }); it('createDirectory should recursively create directories relative to path in FilePath', async () => { const firstLevel = randomString(); const extraFolder = randomString(); const target = path.join(os.tmpdir(), firstLevel, randomString()); const fp = new FilePath(target); const result = await fp.createDirectory(extraFolder); assert(isSuccessful(result)); const newPath = path.join(target, extraFolder); assert.isTrue(await FilePath.existsAsync(newPath)); await fsPromises.rmdir(path.join(os.tmpdir(), firstLevel), { recursive: true }); }); it('createDirectory should fail when it cannot create the directory', async () => { const fp = new FilePath(cannotCreatePath); let result = await fp.createDirectory(''); assert(isFailure(result)); result = await fp.createDirectory('stuff'); assert(isFailure(result)); }); it('createDirectory should ignore base when given an absolute path', async () => { const fp = new FilePath(cannotCreatePath); const target = path.join(os.tmpdir(), randomString()); const result = await fp.createDirectory(target); assert(isSuccessful(result)); assert.isTrue(await FilePath.existsAsync(target)); await fsPromises.rmdir(target); }); }); describe('Manipulate current working directory', () => { it('makeCurrentPath should change cwd to existing folder', () => { const cwd = new FilePath(process.cwd()); const newFolder = path.join(os.tmpdir(), randomString()); fs.mkdirSync(newFolder); const newFilePath = new FilePath(newFolder); const result = newFilePath.makeCurrentPath(); assert(isSuccessful(result)); assert.strictEqual(realpathSync(process.cwd()), realpathSync(newFolder)); process.chdir(cwd.getAbsolutePath()); fs.rmdirSync(newFolder); }); it('makeCurrentPath with false autocreate flag should fail to change cwd to non-existent folder', () => { const cwd = process.cwd(); const newFolder = path.join(os.tmpdir(), randomString()); const f1 = new FilePath(newFolder); assert.isFalse(fs.existsSync(newFolder)); const result = f1.makeCurrentPath(); assert(isFailure(result)); assert.strictEqual(process.cwd(), cwd); }); it('makeCurrentPath with autocreate should create and change cwd to non-existent folder', () => { const origCwd = process.cwd(); const newFolder = path.join(os.tmpdir(), randomString()); const f1 = new FilePath(newFolder); assert.isFalse(fs.existsSync(newFolder)); const result = f1.makeCurrentPath(true); assert(isSuccessful(result)); assert.strictEqual(realpathSync(process.cwd()), realpathSync(newFolder)); process.chdir(origCwd); fs.rmdirSync(newFolder); }); }); describe('Path resolutions', () => { it('resolveAliasedPathSync should return home if empty path provided', () => { const home = userHomePath(); const result = FilePath.resolveAliasedPathSync('', home); assert.strictEqual(result.getAbsolutePath(), home.getAbsolutePath()); }); it("resolveAliasedPathSync should resolve '~' as home", () => { const home = userHomePath(); const result = FilePath.resolveAliasedPathSync('~', home); assert.strictEqual(result.getAbsolutePath(), home.getAbsolutePath()); }); it("resolveAliasedPathSync should replace '~' in path", () => { const start = '~/foo/bar'; const result = FilePath.resolveAliasedPathSync(start, userHomePath()); const resultStr = result.getAbsolutePath(); assert.isAtLeast(resultStr.length, start.length); assert.notEqual(resultStr.charAt(0), '~'); assert.isAbove(resultStr.lastIndexOf('/foo/bar'), -1); }); it('completePath should return absolute path as-is ignoring base', () => { const f1 = userHomePath(); const result = f1.completePath(absolutePath); assert.strictEqual(result.getAbsolutePath(), absolutePath); }); it('completePath should resolve relative path to cwd when no base', () => { const f1 = new FilePath(); const result = f1.completePath('some/path'); const expected = new FilePath(path.join(process.cwd(), 'some/path')); assert.strictEqual(result.getAbsolutePath(), expected.getAbsolutePath()); }); it('completeChildPath should return same path when no child provided', () => { const aPath = new FilePath('/path/to/a'); const result = aPath.completeChildPath(''); assert.isTrue(result.equals(aPath)); }); it('completeChildPath should correctly handle a simple request', () => { const aPathStr = process.platform === 'win32' ? 'C:\\path\\to\\a' : '/path/to/a'; const bPathStr = process.platform === 'win32' ? 'C:\\path\\to\\a\\b' : '/path/to/a/b'; const aPath = new FilePath(aPathStr); const bPath = new FilePath(bPathStr); const result = aPath.completeChildPath('b'); assert.isTrue(result.equals(bPath)); }); it('completeChildPath should not complete a path outside and instead return original path', () => { const cPath = new FilePath('/path/to/foo'); assert.strictEqual(cPath.completeChildPath('../bar'), cPath); assert.strictEqual(cPath.completeChildPath('/path/to/quux'), cPath); }); }); describe('Aliased paths', () => { it('Paths are aliased correctly', () => { const path = new FilePath('/Users/user/path/to/project'); const home = new FilePath('/Users/user'); const aliasedPath = FilePath.createAliasedPath(path, home); assert(aliasedPath === '~/path/to/project'); }); it('Paths are aliased correctly, even with trailing slashes', () => { const path = new FilePath('/Users/user/path/to/project'); const home = new FilePath('/Users/user/'); const aliasedPath = FilePath.createAliasedPath(path, home); assert(aliasedPath === '~/path/to/project'); }); it('Paths with differing slashes are aliased correctly', () => { const path = new FilePath('//server/home/user/path/to/project'); const home = new FilePath('\\\\server\\home\\user'); const aliasedPath = FilePath.createAliasedPath(path, home); assert(aliasedPath === '~/path/to/project'); }); it('DOS paths are handled', () => { const path = new FilePath('C:/Users/user/path/to/project'); const home = new FilePath('C:\\Users\\user'); const aliasedPath = FilePath.createAliasedPath(path, home); assert(aliasedPath === '~/path/to/project'); }); it('Original path returned is aliasing fails', () => { const path = new FilePath('/home/other/path/to/project'); const home = new FilePath('/home/user'); const aliasedPath = FilePath.createAliasedPath(path, home); assert(new FilePath(aliasedPath).getAbsolutePath() === path.getAbsolutePath()); }); }); describe('Remove file and folders', () => { it('remove deletes an existing folder', async () => { const testDir = getTestDir(); await testDir.createDirectory(); assert.isTrue(await testDir.existsAsync()); assert(isSuccessful(await testDir.remove())); assert.isFalse(await testDir.existsAsync()); }); it('remove fails if asked to delete a non-existing folder', async () => { const testDir = getTestDir(); assert.isFalse(await testDir.existsAsync()); assert(isFailure(await testDir.remove())); }); it('removeSync deletes an existing folder', () => { const testDir = getTestDir(); testDir.createDirectorySync(); assert.isTrue(testDir.existsSync()); assert(isSuccessful(testDir.removeSync())); assert.isFalse(testDir.existsSync()); }); it('removeSync fails if asked to delete a non-existing folder', () => { const testDir = getTestDir(); assert.isFalse(testDir.existsSync()); assert(isFailure(testDir.removeSync())); }); it('removeIfExists deletes an existing folder', async () => { const testDir = getTestDir(); await testDir.createDirectory(); assert.isTrue(await testDir.existsAsync()); assert(isSuccessful(await testDir.removeIfExists())); assert.isFalse(await testDir.existsAsync()); }); it('removeIfExists returns success if asked to delete a non-existing folder', async () => { const testDir = getTestDir(); assert.isFalse(await testDir.existsAsync()); assert(isSuccessful(await testDir.removeIfExists())); }); it('removeIfExistsSync deletes an existing folder', () => { const testDir = getTestDir(); testDir.createDirectorySync(); assert.isTrue(testDir.existsSync()); assert(isSuccessful(testDir.removeIfExistsSync())); assert.isFalse(testDir.existsSync()); }); it('removeIfExistsSync returns success if asked to delete a non-existing folder', () => { const testDir = getTestDir(); assert.isFalse(testDir.existsSync()); assert(isSuccessful(testDir.removeIfExistsSync())); }); }); describe('enumerate children', () => { it("getChildren returns error if it doesn't exist", () => { const testDir = getTestDir(); const children: FilePath[] = []; assert(isFailure(testDir.getChildren(children))); }); it("getChildren returns error if it isn' a directory", () => { const testDir = getTestDir(); testDir.createDirectorySync(); const fileName = testDir.completeChildPath(randomString()); fs.writeFileSync(fileName.getAbsolutePath(), 'This is a test file.'); const children: FilePath[] = []; assert(isFailure(fileName.getChildren(children))); fileName.removeIfExistsSync(); testDir.removeIfExistsSync(); }); it('getChildren handles case with no children', () => { const testDir = getTestDir(); testDir.createDirectorySync(); const children: FilePath[] = []; assert(isSuccessful(testDir.getChildren(children))); assert.equal(0, children.length); testDir.removeIfExistsSync(); }); it('getChildren handles case with single child file', () => { const testDir = getTestDir(); testDir.createDirectorySync(); const fileName = testDir.completeChildPath(randomString()); fs.writeFileSync(fileName.getAbsolutePath(), 'This is a test file.'); const children: FilePath[] = []; assert(isSuccessful(testDir.getChildren(children))); assert.equal(1, children.length); assert.equal(fileName.getAbsolutePath(), children[0].getAbsolutePath()); fileName.removeIfExistsSync(); testDir.removeIfExistsSync(); }); it('getChildren handles case with multiple child files', () => { const testDir = getTestDir(); testDir.createDirectorySync(); const fileName1 = testDir.completeChildPath(randomString()); fs.writeFileSync(fileName1.getAbsolutePath(), 'This is test file one.'); const fileName2 = testDir.completeChildPath(randomString()); fs.writeFileSync(fileName2.getAbsolutePath(), 'This is test file two.'); const children: FilePath[] = []; assert(isSuccessful(testDir.getChildren(children))); assert.equal(2, children.length); fileName1.removeIfExistsSync(); fileName2.removeIfExistsSync(); testDir.removeIfExistsSync(); }); it('getChildren handles case with child directory', () => { const testDir = getTestDir(); testDir.createDirectorySync(); const subDir = testDir.completeChildPath(randomString()); fs.mkdirSync(subDir.getAbsolutePath()); const children: FilePath[] = []; assert(isSuccessful(testDir.getChildren(children))); assert.equal(1, children.length); assert.equal(subDir.getAbsolutePath(), children[0].getAbsolutePath()); subDir.removeIfExistsSync(); testDir.removeIfExistsSync(); }); }); describe('NYI placeholders', () => { it('sync methods should throw exception', () => { const fp1 = new FilePath(); const fp2 = new FilePath(); assert.throws(() => FilePath.isEqualCaseInsensitive(fp1, fp2)); assert.throws(() => FilePath.isRootPath('/')); assert.throws(() => FilePath.makeCurrent('/')); assert.throws(() => FilePath.tempFilePath()); assert.throws(() => FilePath.uniqueFilePath('/')); if (process.platform === 'win32') { assert.doesNotThrow(() => fp1.changeFileMode('')); } else { assert.throws(() => fp1.changeFileMode('')); } assert.throws(() => fp1.copy(fp2)); assert.throws(() => fp1.copyDirectoryRecursive(fp2)); assert.throws(() => fp1.ensureFile()); assert.throws(() => fp1.getChildrenRecursive()); assert.throws(() => fp1.getFileMode()); assert.throws(() => fp1.getMimeContentType()); assert.throws(() => fp1.getParent()); assert.throws(() => fp1.getRelativePath(fp2)); assert.throws(() => fp1.getSize()); assert.throws(() => fp1.getSizeRecursive()); assert.throws(() => fp1.hasExtension('.txt')); assert.throws(() => fp1.hasExtensionLowerCase('.txt')); assert.throws(() => fp1.hasTextMimeType()); assert.throws(() => fp1.isDirectory()); assert.throws(() => fp1.isEquivalentTo(fp2)); assert.throws(() => fp1.isHidden()); assert.throws(() => fp1.isJunction()); assert.throws(() => fp1.isReadable()); assert.throws(() => fp1.isRegularFile()); assert.throws(() => fp1.isSymlink()); assert.throws(() => fp1.move()); assert.throws(() => fp1.moveIndirect(fp2)); assert.throws(() => fp1.openForRead()); assert.throws(() => fp1.openForWrite()); assert.throws(() => fp1.resetDirectory()); assert.throws(() => fp1.resolveSymlink()); assert.throws(() => fp1.setLastWriteTime()); assert.throws(() => fp1.testWritePermissions()); }); }); });
<?php /** * Project: MEWA Hospital Intranet * Developed by: Muhyadin Abdullahi (muhidin.rashid@mewa.or.ke) & Salim Juma (salim.silaha@mewa.or.ke). * * Copyright (c) 2018: This project is open-sourced software licensed under the GNU Affero General Public License v3.0 (https://opensource.org/licenses/AGPL-3.0). * */ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; /** * Class CreateDepartmentsTable. */ class CreateDepartmentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('departments', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->nullable(); $table->string('mailing_list')->nullable(); $table->string('slug'); $table->text('overview')->nullable(); $table->string('hod')->nullable(); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('departments'); } }
<?php namespace App\Livewire; use Livewire\Component; class EditPost extends Component { public $title; public $content; public $post; public $successMessage = ""; public $rules = [ 'title' => 'required|min:6', 'content' => 'required|min:6', ]; public function mount($post) { $this->title = $post->title; $this->content = $post->content; $this->post = $post; } public function render() { return view('livewire.edit-post'); } public function save() { $this->validate(); $this->post->title = $this->title; $this->post->content = $this->content; $this->post->save(); $this->successMessage = "Post successfully updated."; } public function resetForm() { $this->title = ""; $this->content = ""; $this->successMessage = ""; $this->resetErrorBag(); } }
<?php namespace IXP\Services\Grapher\Graph; /* * Copyright (C) 2009-2016 Internet Neutral Exchange Association Company Limited By Guarantee. * All Rights Reserved. * * This file is part of IXP Manager. * * IXP Manager 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, version v2.0 of the License. * * IXP Manager 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 v2.0 * along with IXP Manager. If not, see: * * http://www.gnu.org/licenses/gpl-2.0.html */ use IXP\Services\Grapher; use IXP\Services\Grapher\{Graph,Statistics}; use IXP\Exceptions\Services\Grapher\{BadBackendException,CannotHandleRequestException,ConfigurationException,ParameterException}; use Entities\Customer as CustomerEntity; use Auth, Log; /** * Grapher -> Customer Graph (LAGs) * * @author Barry O'Donovan <barry@islandbridgenetworks.ie> * @category Grapher * @package IXP\Services\Grapher * @copyright Copyright (C) 2009-2016 Internet Neutral Exchange Association Company Limited By Guarantee * @license http://www.gnu.org/licenses/gpl-2.0.html GNU GPL V2.0 */ class Customer extends Graph { /** * Customer to graph * @var \Entities\Customer */ private $cust = null; /** * Constructor */ public function __construct( Grapher $grapher, CustomerEntity $c ) { parent::__construct( $grapher ); $this->cust = $c; } /** * Get the customer we're set to use * @return \Entities\Vlan */ public function customer(): CustomerEntity { return $this->cust; } /** * Set the customer we should use * @param Entities\customer $i=c * @return \IXP\Services\Grapher Fluid interface * @throws \IXP\Exceptions\Services\Grapher\ParameterException */ public function setCustomer( CustomerEntity $c ): Grapher { if( $this->customer() && $this->customer()->getId() != $c->getId() ) { $this->wipe(); } $this->cust = $c; return $this; } /** * The name of a graph (e.g. member name, IXP name, etc) * @return string */ public function name(): string { return $this->customer()->getName(); } /** * A unique identifier for this 'graph type' * * E.g. for an IXP, it might be ixpxxx where xxx is the database id * @return string */ public function identifier(): string { return sprintf( "aggregate-%05d", $this->customer()->getId() ); } /** * This function controls access to the graph. * * {@inheritDoc} * * For (public) vlan aggregate graphs we pretty much allow complete access. * * @return bool */ public function authorise(): bool { if( !Auth::check() ) { return $this->deny(); } if( Auth::user()->isSuperUser() ) { return $this->allow(); } if( Auth::user()->getCustomer()->getId() == $this->customer()->getId() ) { return $this->allow(); } Log::notice( sprintf( "[Grapher] [Customer]: user %d::%s tried to access a customer aggregate graph " . "{$this->customer()->getId()} which is not theirs", Auth::user()->getId(), Auth::user()->getUsername() ) ); return $this->deny(); } /** * Generate a URL to get this graphs 'file' of a given type * * @param array $overrides Allow standard parameters to be overridden (e.g. category) * @return string */ public function url( array $overrides = [] ): string { return parent::url( $overrides ) . sprintf("&id=%d", isset( $overrides['id'] ) ? $overrides['id'] : $this->customer()->getId() ); } /** * Get parameters in bulk as associative array * * Extends base function * * @return array $params */ public function getParamsAsArray(): array { $p = parent::getParamsAsArray(); $p['id'] = $this->customer()->getId(); return $p; } /** * Process user input for the parameter: cust * * Does a abort(404) if invalid * * @param int $i The user input value * @return int The verified / sanitised / default value */ public static function processParameterCustomer( int $i ): CustomerEntity { // if we're not an admin, default to the currently logged in customer if( !$i && Auth::check() && !Auth::user()->isSuperUser() && !Auth::user()->getCustomer()->isTypeAssociate() ) { return Auth::user()->getCustomer(); } if( !$i || !( $cust = d2r( 'Customer' )->find( $i ) ) ) { abort(404); } return $cust; } }
# Lesson 5: Introductions to 'For' Loops in JS // Write five console.log statements. console.log(1) console.log(2) console.log(3) console.log(4) console.log(5) # Lesson 6: Search Text for Your Name /*jshint multistr:true */ text = "Blah blah blah blah blah blah Eric\ blah blah blah Eric blah blah Eric blah blah \ blah blah blah blah blah Eric"; var myName = "Eric"; var hits = []; // Look for "E" in the text for(var i = 0; i < text.length; i++) { if (text[i] === "E") { // If we find it, add characters up to // the length of my name to the array for (var j = i; j < (myName.length + i); j++) { hits.push(text[j]); } } } if (hits.length === 0) { console.log("Your name isn't found!"); } else { console.log(hits); }
import React, {useEffect, useState} from 'react'; import {GoogleMap, Marker, withGoogleMap, withScriptjs} from "react-google-maps"; import {StandaloneSearchBox} from "@react-google-maps/api"; import {compose, withProps} from "recompose"; const MyMapComponent = compose( withProps({ googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_CLIENT_ID}&v=3.exp&libraries=geometry,drawing,places`, loadingElement: <div style={{ height: `100%` }} />, containerElement: <div style={{ height: `332px` }} />, mapElement: <div style={{ height: `100%` }} /> }), withScriptjs, withGoogleMap )(props => { const [map, setMap] = useState(null); const [searchBox, setSearchBox] = useState(null); const onPlacesChanged = () => { const places = searchBox.getPlaces(); const google = window.google; const bounds = new google.maps.LatLngBounds(); // setPosition({lat:lat,lng:lng}) places.forEach((place) => { console.log(place.geometry.location.lat()) console.log(place.geometry.location.lat()) props.markerChange({lat:place.geometry.location.lat(),lng:place.geometry.location.lng()}) if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }) map.fitBounds(bounds); }; const onSBLoad = ref => { setSearchBox(ref); }; return( <div className={'position-relative'}> <GoogleMap defaultZoom={8} center={{lat: props.position.lat, lng: props.position.lng}} ref={mapRef => { setMap(mapRef); }} defaultCenter={{lat: props.position.lat, lng: props.position.lng}}> <Marker position={props.position} draggable={true} onDragEnd={props.onMarkerDragEnd} /> <StandaloneSearchBox onPlacesChanged={onPlacesChanged} onLoad={onSBLoad} > <input type="text" placeholder="Search place" style={{ boxSizing: 'border-box', border: `1px solid transparent`, width: `270px`, height: `40px`, padding: `0 12px`, borderRadius: `3px`, boxShadow: `0 2px 6px rgba(0, 0, 0, 0.1)`, fontSize: `14px`, outline: `none`, margin: 'center', textOverflow: `ellipses`, position: 'absolute', bottom: '285px', marginLeft: '40%' }} /> </StandaloneSearchBox> </GoogleMap> </div> ) } ); export default function StudentLocationAdd(props) { const [position,setPosition] = useState({lat:6.927079,lng:79.861244}) useEffect(()=>{ if(!props.location){ return } console.log(props.location) setPosition(props.location) },[props.location]) function onMarkerDragEnd (coord, index) { console.log(coord) const { latLng } = coord; let lat = latLng.lat(); let lng = latLng.lng(); setPosition({lat:lat,lng:lng}) props.onChange({lat:lat,lng:lng}) } function markerChange(data) { setPosition(data) props.onChange(data) } return ( <div> <MyMapComponent onMarkerDragEnd={onMarkerDragEnd} position={position} markerChange={markerChange}/> </div> ); }
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Company } from '../company/company.model'; import { CompanyService } from '../company/company.service'; @Injectable({ providedIn: 'root' }) export class DataStorageService { constructor(private http: HttpClient, private companySrvc: CompanyService) {} getCompanies() { this.http .get<Company[]>('http://localhost:8080/company/all') .subscribe((companyData) => { this.companySrvc.setCompanies(companyData); console.log(companyData); }); } createCompany(newCompany: Company) { this.http .post('http://localhost:8080/company/create', { name: newCompany.name, address: newCompany.address, businessHours: newCompany.businessHours, }) .subscribe(() => { console.log('Succesfully added Company!'); }); } deleteCompany(deletableCompanyId: number) { this.http .delete('http://localhost:8080/company/' + deletableCompanyId) .subscribe({ next: (data) => { console.log('Succesfully deleted Company!'); }, error: (error) => { console.error('There was an error!', error); }, }); } updateCompany(updatedCompany: Company, idOfEditedCompany: number) { this.http .post('http://localhost:8080/company/update', { id: idOfEditedCompany, name: updatedCompany.name, address: updatedCompany.address, businessHours: updatedCompany.businessHours, works: updatedCompany.works, }) .subscribe((response) => { console.log(response); }); } }
from pydantic import BaseModel,confloat,validator,Field,ConfigDict,model_validator from datetime import date,datetime,timedelta from enums import DepartmentEnum from typing import Literal import uuid class Module(BaseModel): id:int|uuid.UUID name:str professor:str credits:Literal[10,20] registration_code:str class Student(BaseModel): id:uuid.UUID name:str date_of_birth:date=Field(default_factory=lambda: datetime.today().date()) GPA:confloat(ge=0,le=5) course:str|None department:DepartmentEnum fees_paid:bool modules:list[Module]=Field(default=[],max_items=10) # model_config = ConfigDict(extra='allow',title='Student Model') @model_validator def validate_gpa_and_dept(values): dept=values.get('department') gpa=values.get('GPA') dept_science=dept==DepartmentEnum.SCIENCE_AND_ENGINEERING.value valid_gpa=gpa>=3.0 if dept_science: if not valid_gpa: raise ValueError ('GPA not high enough for S&E') return values @validator('modules') def validate_module_length(cls,value): if(len(value) and len(value)!=3): raise ValueError("The modules length should be 3") return value @validator('GPA') def validate_gpa(cls,value,values): print(value) @validator('date_of_birth') def ensure_16_years_above(cls,value): sixteen_years_ago=datetime.now()-timedelta(days=365*16) sixteen_years_ago=sixteen_years_ago.date() if value>sixteen_years_ago: raise ValueError("Too young to enroll, sorry") return value
import React from "react"; import { Swiper, SwiperSlide } from "swiper/react"; import { Navigation, Pagination } from "swiper"; import SectionWrapper from "../../shared/SectionWrapper"; import TestimonialCard from "./TestimonialCard"; import data from "./data/data.json"; import "./testimonial.styles.css"; import "swiper/css"; import "swiper/css/navigation"; import "swiper/css/pagination"; const Testimonial = () => ( <SectionWrapper name="testimonial"> <span className="section__subtitle">My Clients Say</span> <h2 className="section__title">Testimonial</h2> <div className="testimonial__container container"> <Swiper style={{ overflow: "visible" }} modules={[Navigation, Pagination]} spaceBetween={window.screen.width > 400 ? 50 : 10} slidesPerView={window.screen.width > 400 ? 2 : 1} // navigation pagination={{ clickable: true }} > {data.map(({ image, name, description }) => ( <SwiperSlide> <TestimonialCard key={name} image={image} name={name} description={description} /> </SwiperSlide> ))} </Swiper> </div> </SectionWrapper> ); export default Testimonial;
### .NET发展史 ​ 2010之前 的PC时代的时候,互联网规模还不是特别庞大, JAVA和.Net没什么太大区别,.net以windows自居。 ​ 2010年以JAVA为代表的Hadoop大数据兴起后,微软跟进失败,曾今也实现了一套api,但后来还是放弃维护了。 ​ 2012年移动互联网兴起,.net跟进失败。wp(windows phone)市场占有率太低,微软就放弃了。 ​ 2014-2015 微服务时代的来临,以go为代表的docker技术,python为代表的devops,java的spring cloud技术兴起,微服务造就了多语言的盛行,微软还想维护的windows平台占有率,不想改变。 ​ 2014年云计算事业部副总裁萨提亚·纳德拉出任微软CEO,改变微软企业文化,开始开源、拥抱linux。 ​ 2014年2月4日,微软公司宣布由萨提亚·纳德拉接替史蒂夫·鲍尔默,成为下一任首席执行官。 ​ 2015年微软对.net 平台进行了重新架构。 ​ 2016.6.27 netcore 1.0 项目发布,彻底的改变了 windows only的场景,拥抱开源。这个版本不稳定。 ## .NET Core设计目标 - 支持或可以移转 (port) 到更多的操作系统平台与芯片架构 (未来项目会跨出 x86 平台。目前已至此x64、arm)。 - 具有引人注目的性能与高可靠度。 - 开发人员能快速与直接的获取 .NET Core 开发环境。 - 在直觉与具生产力的情况下建造应用程序,使用文件,示例与 NuGet 组件。 ## .NET Core与其他平台的关系   **.NET Framework**   .NET Framework是.NETCore的爹,从2002年Framework始终独占window平台,不开源、不跨平台,在2016年docker出现后持续走低。Core摒弃framework的缺点,开源、跨平台、完美支持docker。 ## .NET未来和优势 * 在全球,.net是市场上唯一能涵盖人工智能、物联网、桌面开发、网页开发、云原生、移动应用、游戏等厂家的开源框架。 * C# 的语法之优美,语法糖之丰富,使用C#开发效率极高、性能极佳,配合宇宙最强IDE让人欲罢不能
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:navbar="http://xmlns.jcp.org/jsf/composite/components/navbar" xmlns:p="http://primefaces.org/ui" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:f="http://xmlns.jcp.org/jsf/core"> <h:head> <title>Subscription</title> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <link rel="shortcut icon" type="image/x-icon" href="../../../images/favicon.ico"/> <h:outputStylesheet library="css" name="styles.css"/> <h:outputStylesheet library="css" name="primeflex.min.css"/> </h:head> <h:body class="bg-gray-200" style="font-family: sans-serif;"> <navbar:tourist-navbar user="#{touristBean.userMaster}" sideNavigationBean="#{navigationBean}"/> <!--Subscription Cards--> <h:form id="form"> <section class=" flex flex-column relative" style="height: 350px;background-color: #8c239e"> <div class="py-4 md\:-py-6"> <div class="text-center my-4 text-5xl text-white">Choose a Plan</div> <div class="text-center text-100 text-xl mt-3 mb-4">Pick a plan. Get amazing features. Explore more in a better way.</div> </div> <div class="absolute top-50 left-50 w-full" style="transform: translate(-50%,0%)"> <div class="grid justify-content-center w-full"> <ui:repeat var="item" value="${subsModelBean.subscriptionModel}"> <div class="col-12 md:col-6 lg:col-4"> <div class="p-3 h-full"> <div class="card-select py-4 px-6 mx-auto h-full flex flex-column surface-card border-round-3xl" style="border-radius: 6px"> <div class="font-medium text-4xl text-center mb-2">#{item.name}</div> <hr class="my-3 mx-0 border-top-1 border-bottom-none surface-border"/> <div class="flex align-items-center flex-column"> <div> <span class="text-7xl -mr-3 text-purple-700">${item.cost} </span> <span class="material-symbols-outlined text-purple-700 font-semibold"> currency_rupee </span> </div> <span class="text-2xl text-600 blocks"> for #{item.durationInMonth} month </span> </div> <hr class="my-5 mx-0 border-top-1 border-bottom-none surface-border"/> <ul class="list-none p-0 m-0 flex-grow-1"> <ui:repeat var="desc" value="#{item.details.split('\\.')}" > <li class="flex align-items-center mb-3 text-lg"> <i class="pi pi-check-circle text-green-500 mr-2"/> <span>${desc}.</span> </li> </ui:repeat> </ul> <hr class="my-5 mx-0 border-top-1 border-bottom-none surface-border mt-auto"/> <p:commandButton action="#{subsModelBean.onModalAction(item)}" value="Buy Now" styleClass="px-3 py-2 w-full text-xl mt-auto ui-button-raised ui-button-help rounded-button"> <f:setPropertyActionListener target="#{subsModelBean.modelForPayment}" value="${item}"/> <f:setPropertyActionListener target="#{subsModelBean.currentCost}" value="#{item.cost}" /> </p:commandButton> </div> </div> </div> </ui:repeat> </div> </div> </section> <!--Payment Modal--> </h:form> <h:form id="dialog"> <p:dialog widgetVar="paymentModal" id="payment-modal" showEffect="fade" header="Make your Payment" modal="true" class="w-full md:w-5 border-round-xl"> <p:outputPanel id="manage-payment-content"> <div class="p-4 border-round"> <div class="font-medium"> <div class="modal-container"> <p:messages id="msgs"/> <div class="ui-fluid"> <div class=" mx-1 grid justify-content-between"> <div class="ui-input-icon-right"> <i class="pi pi-credit-card text-2xl mt-0"/> <p:outputLabel for="cardNumber">Card Number</p:outputLabel> <p:inputMask id="cardNumber" placeholder="XXXX XXXX XXXX XXXX" class="my-2" mask="9999 9999 9999 9999" value="#{subsModelBean.cardNumber}" required="true" requiredMessage="Card number is required" > </p:inputMask> </div> <div> <p:outputLabel for="cvv">CVV</p:outputLabel> <p:password id="cvv" class="my-2" required="true" requiredMessage="CVV number is required" maxlength="3"> <f:validateLength minimum="3" maximum="3"/> </p:password> </div> </div> <div class=" mx-1 grid justify-content-between my-2"> <div class="ui-input-icon-right"> <p:outputLabel for="expiryDate">Expiry Date</p:outputLabel> <p:datePicker id="expiryDate" showIcon="true" inline="false" class="mt-2" view="month" pattern="MM/yyyy" yearNavigator="true" yearRange="2023:2090" required="true" requiredMessage="Expiry Date is required"/> </div> <div> <p:graphicImage value="/images/PaymentCards.png" style="width: 200px;height: 50px;margin-top: 20px"/> </div> </div> <div class="mx-1 mt-1 "> <div class="ui-input-icon-right "> <i class="pi pi-user text-2xl" style="margin-top:2px" /> <p:outputLabel for="nameOnCard">Card Holder's Name</p:outputLabel> <p:inputText id="nameOnCard" class="mt-2 w-full" required="true" requiredMessage="Name is required"/> </div> </div> <div class="mx-1 mt-3 mb-1"> <span class="text-2xl font-semibold" > Total Amount: #{subsModelBean.currentCost} </span> </div> <div class=" mt-2 grid justify-content-start col-12 md:col-6"> <div class="mx-2"> <p:commandButton id="payBtn" icon="pi pi-check" action="#{subsModelBean.Subscribe()}" update="manage-payment-content" process="manage-payment-content @this" value="Pay Now" styleClass="ui-button-success border-round-xl"/> </div> <div> <p:commandButton id="cancelBtn" icon="pi pi-times" type="button" onclick="PF('paymentModal').hide()" value="Cancel" styleClass="ui-button-danger border-round-xl"/> </div> </div> </div> </div> </div> </div> </p:outputPanel> </p:dialog> </h:form> <!--Success Dialog--> <h:form> <p:dialog id="success-dialog" header="Success" widgetVar="success_dlg" minHeight="40" width="350" showEffect="fade"> <p class="m-0 text-xl">Subscribed successfully!</p> <f:facet name="footer"> <p:commandButton value="Close" class="ui-button-success" icon="pi pi-times" type="button" onclick="PF('success_dlg').hide()"/> </f:facet> </p:dialog> </h:form> <h:form> <p:dialog id="is-subscribed-dialog" header="Warning" widgetVar="isSubscribedDlg" height="50" width="350" showEffect="fade"> <div class="text-center"> <i class="pi pi-exclamation-circle text-5xl" /> </div> <div class="text-center text-xl mt-3">You already Subscribed to this plan!</div> <f:facet name="footer"> <p:commandButton value="Close" class="ui-button-danger" icon="pi pi-times" type="button" onclick="PF('isSubscribedDlg').hide()"/> </f:facet> </p:dialog> </h:form> </h:body> </html>
<template> <div> <div class="tooltip-example"> Right <tooltip width="small" placement="right"> Right side </tooltip> </div> <div class="tooltip-example"> Left <tooltip width="small" placement="left"> Left side </tooltip> </div> <div class="tooltip-example"> Top <tooltip width="small" placement="top"> Top </tooltip> </div> <div class="tooltip-example"> Bottom <tooltip width="small" placement="bottom"> Bottom </tooltip> </div> <div class="tooltip-example"> <i class="fas fa-info-circle"> <tooltip width="small" placement="top"> It also works on icons </tooltip> </i> </div> <div class="tooltip-example"> <p> This is some wide text this is some wide text <br> This text is also multiline <tooltip width="small" placement="right"> <div> This is a <br> multiline tooltip </div> </tooltip> </p> </div> <div class="tooltip-example"> <p> This <br> text <br> spans <br> many <br> lines <br> <tooltip width="small" placement="right"> Hey </tooltip> </p> </div> <div class="tooltip-example"> <p> Small <tooltip width="small" placement="top"> This is a small tooltip </tooltip> </p> </div> <div class="tooltip-example"> <p> Medium <tooltip width="medium" placement="top"> This is a medium tooltip. It is medium. </tooltip> </p> </div> <div class="tooltip-example"> <p> Large and overlap <tooltip width="large" placement="right"> This is a large tooltip. It is rather large, wouldn't you say? It also overlaps content to the right. </tooltip> </p> </div> <div class="tooltip-example"> This gets covered <tooltip width="large" placement="right"> This tooltip overlaps content on the right </tooltip> </div> </div> </template> <script lang="ts"> import { Component, Prop, Vue } from 'vue-property-decorator'; import Tooltip from '@/components/tooltip.vue'; @Component({ components: {Tooltip} }) export default class TooltipDemo extends Vue { } </script> <style scoped lang="scss"> .tooltip-example { display: inline-block; margin: 80px 100px; } </style>
function [ind,G]=triShortestPath(faces,vertices,x,G,verbose) % [ind,G]=triShortestPath(faces,vertices,x,G) % % This function searches for the shortest paths between all points xi in a % triangulated mesh with faces and vertices, or - if given - in its % representation as a sparse graph G % % Input % % faces - faces (index Nx3) specifying the indices of the vertices % as standard after delaunay triangularization % vertices - vertices (Mx2) or (Mx3) % x - either the data points xi or an index of data points, % which implies xi=x(xi,:) % G - optional, sparse, weighted graph representation of % the mesh [tri,x], i.e. the adjacency is given by the % simplexes and weights by some distance between vertices % % Output % % ind - indices of resultant points, i.e. x(ind,:) gives the % points on the mesh in 3D % G - graph respresentation of the mesh [tri,x] % % (c) marlow 10/2019 % % This file is released under the terms of the GNU General Public License, % version 3. See http://www.gnu.org/licenses/gpl.html if nargin<5, verbose=true; end % if the graph representation is not given, we compute it ... if nargin<4 || isempty(G) G=tri2graph(faces,vertices); % adjacencies=edges, weights=distances end % if xi is given as 3D points determine the corresponding vertex indices if size(x,2)>1 indXi=find(ismember(vertices,x,'rows')); else indXi=x; end % this is only needed for the progress report k=0; N=floor(numel(indXi)*(numel(indXi)-1)/2/20); ind=indXi; for i=1:numel(indXi) % loop over all point pairs in the mesh/graph indPath=[]; fXi=faces(any(faces==indXi(i),2),:); for j=i+1:numel(indXi) % check whether indXi(i) & indXi(j) are in a triangle if nnz(indPath==indXi(j))==0 && nnz(fXi==indXi(j))==0 % if indXi(i) & indXi(j) are not already connected, estimate % the shortest distance of the undirected graph using % Dijkstra's algorithm ... [~,indP]=graphshortestpath(G,indXi(i),indXi(j),... 'Directed',false,'Method','Dijkstra'); indPath=unique([indPath,indP]); end % progress report if verbose && mod(k,N)==0, fprintf('.'); end; k=k+1; end ind=unique([indPath';ind]); end end
import { afterEach, beforeEach, describe, describe as context, expect, it, vi } from 'vitest'; import nock from 'nock'; import { airtableBuilder, databaseBuilder, generateAuthorizationHeader, knex } from '../../../test-helper.js'; import { createServer } from '../../../../server.js'; import axios from 'axios'; import { Mission } from '../../../../lib/domain/models/index.js'; import { MissionForRelease } from '../../../../lib/domain/models/release/MissionForRelease.js'; const { buildArea, buildAttachment, buildChallenge, buildCompetence, buildFramework, buildSkill, buildThematic, buildTube, buildTutorial, } = airtableBuilder.factory; async function mockCurrentContent() { const expectedCurrentContent = { frameworks: [{ id: 'recFramework0', name: 'Nom du referentiel' }], areas: [{ id: 'recArea0', name: '1. Titre du Domaine - fr', code: '1', title_i18n: { fr: 'Titre du Domaine - fr', en: 'Titre du Domaine - en', nl: 'Titre du Domaine - nl', }, competenceIds: ['recCompetence0'], competenceAirtableIds: ['recCompetence123'], color: 'jaffa', frameworkId: 'recFramework0', }], competences: [{ id: 'recCompetence0', index: '1.1', name_i18n: { fr: 'Nom de la Compétence - fr', en: 'Nom de la Compétence - en', nl: 'Nom de la Compétence - nl', }, areaId: '1', origin: 'Pix', skillIds: ['recSkill0'], thematicIds: ['recThematic0'], description_i18n: { fr: 'Description de la compétence - fr', en: 'Description de la compétence - en', nl: 'Nom de la Compétence - nl', } }], thematics: [{ id: 'recThematic0', name_i18n: { fr: 'Nom', en: 'name', nl: 'name nl', }, competenceId: 'recCompetence0', tubeIds: ['recTube0'], index: 0 }], tubes: [{ id: 'recTube0', name: 'Nom du Tube', practicalTitle_i18n: { fr: 'Titre pratique du Tube - fr', en: 'Titre pratique du Tube - en', nl: 'Titre pratique du Tube - nl', }, practicalDescription_i18n: { fr: 'Description pratique du Tube - fr', en: 'Description pratique du Tube - en', nl: 'Description pratique du Tube - nl', }, competenceId: 'recCompetence0', thematicId: 'recThematic0', skillIds: ['recSkill0'], isMobileCompliant: true, isTabletCompliant: false, }], skills: [{ id: 'recSkill0', name: 'Nom de l‘Acquis', hint_i18n: { fr: 'Indice - fr', en: 'Indice - en', nl: 'Indice - nl', }, hintStatus: 'Statut de l‘indice', tutorialIds: ['recTutorial0'], learningMoreTutorialIds: ['recTutorial1'], pixValue: 8, competenceId: 'recCompetence0', status: 'validé', tubeId: 'recTube0', version: 1, level: 1, }], challenges: [{ id: 'recChallenge0', instruction: 'Consigne du Challenge - fr-fr', proposals: 'Propositions du Challenge - fr-fr', type: 'Type d\'épreuve', solution: 'Bonnes réponses du Challenge - fr-fr', solutionToDisplay: 'Bonnes réponses du Challenge à afficher - fr-fr', t1Status: false, t2Status: true, t3Status: false, status: 'validé', skillId: 'recSkill0', embedUrl: 'Embed URL', embedTitle: 'Embed title', embedHeight: 'Embed height', timer: 12, illustrationUrl: 'url de l‘illustration', attachments: ['url de la pièce jointe'], competenceId: 'recCompetence0', illustrationAlt: 'Texte alternatif illustration', format: 'mots', autoReply: false, locales: ['fr-fr'], alternativeInstruction: 'Consigne alternative - fr-fr', focusable: false, delta: 0.5, alpha: 0.9, responsive: ['Smartphone'], genealogy: 'Prototype 1', }], tutorials: [{ id: 'recTutorial0', duration: 'Durée du Tutoriel', format: 'Format du Tutoriel', link: 'Lien du Tutoriel', source: 'Source du Tutoriel', title: 'Titre du Tutoriel', locale: 'Langue du Tutoriel', }], courses: [{ id: 'recCourse0', name: 'Nom du Course', description: 'Description du Course', isActive: true, challenges: ['recChallenge0'], }], missions: [new Mission({ id: 1, name_i18n: { fr: 'Ma première mission' }, competenceId: 'competenceId', thematicIds: 'thematicId,thematicId', learningObjectives_i18n: { fr: 'Que tu sois le meilleur' }, validatedObjectives_i18n: { fr: 'Rien' }, status: Mission.status.ACTIVE, createdAt: new Date('2010-01-04'), }), new Mission({ id: 2, name_i18n: { fr: 'Alt name' }, competenceId: 'competenceId', thematicIds: 'thematicId,thematicId', learningObjectives_i18n: { fr: 'Alt objectives' }, validatedObjectives_i18n: { fr: 'Alt validated objectives' }, status: Mission.status.INACTIVE, createdAt: new Date('2010-01-05'), })] }; const attachments = [{ id: 'attid1', url: 'url de l‘illustration', type: 'illustration', challengeId: 'recChallenge0', localizedChallengeId: 'recChallenge0', }, { id: 'attid2', url: 'url de la pièce jointe', type: 'attachment', challengeId: 'recChallenge0', localizedChallengeId: 'recChallenge0', }, { id: 'attid3', url: 'url of the joint piece', type: 'attachment', challengeId: 'recChallenge0', localizedChallengeId: 'recChallenge0En', }]; airtableBuilder.mockLists({ areas: [buildArea(expectedCurrentContent.areas[0])], attachments: attachments.map(buildAttachment), challenges: [buildChallenge({ ...expectedCurrentContent.challenges[0], files: attachments.map(({ id: fileId, localizedChallengeId }) => ({ fileId, localizedChallengeId })) })], competences: [buildCompetence(expectedCurrentContent.competences[0])], frameworks: [buildFramework(expectedCurrentContent.frameworks[0])], skills: [buildSkill(expectedCurrentContent.skills[0])], thematics: expectedCurrentContent.thematics.map(buildThematic), tubes: [buildTube(expectedCurrentContent.tubes[0])], tutorials: [buildTutorial(expectedCurrentContent.tutorials[0])], }); databaseBuilder.factory.buildStaticCourse({ id: 'recCourse0', name: 'Nom du Course', description: 'Description du Course', isActive: true, challengeIds: 'recChallenge0', }); databaseBuilder.factory.buildMission({ id: 1, name: 'Ma première mission', competenceId: 'competenceId', thematicIds: 'thematicId,thematicId', learningObjectives: 'Que tu sois le meilleur', validatedObjectives: 'Rien', status: Mission.status.ACTIVE, createdAt: new Date('2010-01-04'), }); databaseBuilder.factory.buildMission({ id: 2, name: 'Alt name', competenceId: 'competenceId', thematicIds: 'thematicId,thematicId', learningObjectives: 'Alt objectives', validatedObjectives: 'Alt validated objectives', status: Mission.status.INACTIVE, createdAt: new Date('2010-01-05'), }); for (const locale of ['fr', 'en', 'nl']) { databaseBuilder.factory.buildTranslation({ key: `competence.${expectedCurrentContent.competences[0].id}.name`, locale, value: expectedCurrentContent.competences[0].name_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `competence.${expectedCurrentContent.competences[0].id}.description`, locale, value: expectedCurrentContent.competences[0].description_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `thematic.${expectedCurrentContent.thematics[0].id}.name`, locale, value: expectedCurrentContent.thematics[0].name_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `skill.${expectedCurrentContent.skills[0].id}.hint`, locale, value: expectedCurrentContent.skills[0].hint_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `area.${expectedCurrentContent.areas[0].id}.title`, locale, value: expectedCurrentContent.areas[0].title_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `tube.${expectedCurrentContent.tubes[0].id}.practicalTitle`, locale, value: expectedCurrentContent.tubes[0].practicalTitle_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `tube.${expectedCurrentContent.tubes[0].id}.practicalDescription`, locale, value: expectedCurrentContent.tubes[0].practicalDescription_i18n[locale], }); } databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.instruction`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].instruction, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.alternativeInstruction`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].alternativeInstruction, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.proposals`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].proposals, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.solution`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].solution, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.solutionToDisplay`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].solutionToDisplay, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.embedTitle`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].embedTitle, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.illustrationAlt`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].illustrationAlt, }); databaseBuilder.factory.buildLocalizedChallenge({ id: expectedCurrentContent.challenges[0].id, challengeId: expectedCurrentContent.challenges[0].id, locale: 'fr-fr', embedUrl: expectedCurrentContent.challenges[0].embedUrl, }); await databaseBuilder.commit(); return expectedCurrentContent; } async function mockContentForRelease() { const expectedCurrentContent = { frameworks: [{ id: 'recFramework0', name: 'Nom du referentiel' }], areas: [{ id: 'recArea0', name: '1. Titre du Domaine - fr', code: '1', competenceIds: ['recCompetence0'], competenceAirtableIds: ['recCompetence123'], color: 'jaffa', frameworkId: 'recFramework0', title_i18n: { en: 'Titre du Domaine - en', fr: 'Titre du Domaine - fr', nl: 'Titre du Domaine - nl', }, }], competences: [{ id: 'recCompetence0', index: '1.1', areaId: '1', origin: 'Pix', skillIds: ['recSkill0'], thematicIds: ['recThematic0'], name_i18n: { en: 'Nom de la Compétence - en', fr: 'Nom de la Compétence - fr', nl: 'Nom de la Compétence - nl', }, description_i18n: { en: 'Description de la compétence - en', fr: 'Description de la compétence - fr', nl: 'Description de la compétence - nl', }, }], thematics: [{ id: 'recThematic0', competenceId: 'recCompetence0', tubeIds: ['recTube0'], index: 0, name_i18n: { en: 'name', fr: 'Nom', nl: 'name nl', }, }], tubes: [{ id: 'recTube0', name: 'Nom du Tube', competenceId: 'recCompetence0', thematicId: 'recThematic0', skillIds: ['recSkill0'], isMobileCompliant: true, isTabletCompliant: false, practicalTitle_i18n: { en: 'Titre pratique du Tube - en', fr: 'Titre pratique du Tube - fr', nl: 'Titre pratique du Tube - nl', }, practicalDescription_i18n: { en: 'Description pratique du Tube - en', fr: 'Description pratique du Tube - fr', nl: 'Description pratique du Tube - nl', }, }], skills: [{ id: 'recSkill0', name: 'Nom de l‘Acquis', hintStatus: 'Statut de l‘indice', tutorialIds: ['recTutorial0'], learningMoreTutorialIds: ['recTutorial1'], pixValue: 8, competenceId: 'recCompetence0', status: 'validé', tubeId: 'recTube0', version: 1, level: 1, hint_i18n: { en: 'Indice - en', fr: 'Indice - fr', nl: 'Indice - nl', }, }], challenges: [{ id: 'recChallenge0', instruction: 'Consigne du Challenge - fr-fr', proposals: 'Propositions du Challenge - fr-fr', type: 'Type d\'épreuve', solution: 'Bonnes réponses du Challenge - fr-fr', solutionToDisplay: 'Bonnes réponses du Challenge à afficher - fr-fr', t1Status: false, t2Status: true, t3Status: false, status: 'validé', skillId: 'recSkill0', embedUrl: 'Embed URL', embedTitle: 'Embed title', embedHeight: 'Embed height', timer: 12, competenceId: 'recCompetence0', format: 'mots', autoReply: false, locales: ['fr-fr'], alternativeInstruction: 'Consigne alternative - fr-fr', focusable: false, delta: 0.5, alpha: 0.9, responsive: ['Smartphone'], genealogy: 'Prototype 1', attachments: ['url de la pièce jointe'], illustrationUrl: 'url de l‘illustration', illustrationAlt: 'Texte alternatif illustration', }], tutorials: [{ id: 'recTutorial0', duration: 'Durée du Tutoriel', format: 'Format du Tutoriel', link: 'Lien du Tutoriel', source: 'Source du Tutoriel', title: 'Titre du Tutoriel', locale: 'Langue du Tutoriel', }], courses: [{ id: 'recCourse0', name: 'Nom du Course', description: 'Description du Course', isActive: true, challenges: ['recChallenge0'], }], missions: [new MissionForRelease({ id: 1, name_i18n: { fr: 'Ma première mission' }, competenceId: 'competenceId', learningObjectives_i18n: { fr: 'Que tu sois le meilleur' }, validatedObjectives_i18n: { fr: 'Rien' }, status: Mission.status.ACTIVE, content: { dareChallenges: [], steps: [] } }), new MissionForRelease({ id: 2, name_i18n: { fr: 'Alt name' }, competenceId: 'competenceId', learningObjectives_i18n: { fr: 'Alt objectives' }, validatedObjectives_i18n: { fr: 'Alt validated objectives' }, status: Mission.status.INACTIVE, content: { dareChallenges: [], steps: [] } })], }; const attachments = [{ id: 'attid1', url: 'url de l‘illustration', type: 'illustration', challengeId: 'recChallenge0', localizedChallengeId: 'recChallenge0', }, { id: 'attid2', url: 'url de la pièce jointe', type: 'attachment', challengeId: 'recChallenge0', localizedChallengeId: 'recChallenge0', }, { id: 'attid3', url: 'url de la pièce jointe', type: 'attachment', challengeId: 'recChallenge0', localizedChallengeId: 'recChallenge0En', }]; airtableBuilder.mockLists({ areas: [buildArea(expectedCurrentContent.areas[0])], attachments: attachments.map(buildAttachment), challenges: [buildChallenge({ ...expectedCurrentContent.challenges[0], files: attachments.map(({ id: fileId, localizedChallengeId }) => ({ fileId, localizedChallengeId })) })], competences: [buildCompetence(expectedCurrentContent.competences[0])], frameworks: [buildFramework(expectedCurrentContent.frameworks[0])], skills: [buildSkill(expectedCurrentContent.skills[0])], thematics: expectedCurrentContent.thematics.map(buildThematic), tubes: [buildTube(expectedCurrentContent.tubes[0])], tutorials: [buildTutorial(expectedCurrentContent.tutorials[0])], }); databaseBuilder.factory.buildStaticCourse({ id: 'recCourse0', name: 'Nom du Course', description: 'Description du Course', isActive: true, challengeIds: 'recChallenge0', imageUrl: 'Image du Course', }); for (const locale of ['fr', 'en', 'nl']) { databaseBuilder.factory.buildTranslation({ key: `competence.${expectedCurrentContent.competences[0].id}.name`, locale, value: expectedCurrentContent.competences[0].name_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `competence.${expectedCurrentContent.competences[0].id}.description`, locale, value: expectedCurrentContent.competences[0].description_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `thematic.${expectedCurrentContent.thematics[0].id}.name`, locale, value: expectedCurrentContent.thematics[0].name_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `skill.${expectedCurrentContent.skills[0].id}.hint`, locale, value: expectedCurrentContent.skills[0].hint_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `area.${expectedCurrentContent.areas[0].id}.title`, locale, value: expectedCurrentContent.areas[0].title_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `tube.${expectedCurrentContent.tubes[0].id}.practicalTitle`, locale, value: expectedCurrentContent.tubes[0].practicalTitle_i18n[locale], }); databaseBuilder.factory.buildTranslation({ key: `tube.${expectedCurrentContent.tubes[0].id}.practicalDescription`, locale, value: expectedCurrentContent.tubes[0].practicalDescription_i18n[locale], }); } databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.instruction`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].instruction, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.alternativeInstruction`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].alternativeInstruction, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.proposals`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].proposals, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.solution`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].solution, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.solutionToDisplay`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].solutionToDisplay, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.embedTitle`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].embedTitle, }); databaseBuilder.factory.buildTranslation({ key: `challenge.${expectedCurrentContent.challenges[0].id}.illustrationAlt`, locale: 'fr-fr', value: expectedCurrentContent.challenges[0].illustrationAlt, }); databaseBuilder.factory.buildLocalizedChallenge({ id: expectedCurrentContent.challenges[0].id, challengeId: expectedCurrentContent.challenges[0].id, locale: 'fr-fr', embedUrl: expectedCurrentContent.challenges[0].embedUrl, }); await databaseBuilder.commit(); return expectedCurrentContent; } describe('Acceptance | Controller | release-controller', () => { describe('GET /current-content - Returns release from current Airtable data', () => { context('nominal case', () => { let user; beforeEach(async function() { user = databaseBuilder.factory.buildAdminUser(); await databaseBuilder.commit(); }); it('should return current learning content', async () => { // Given const expectedCurrentContent = await mockCurrentContent(); const server = await createServer(); const currentContentOptions = { method: 'GET', url: '/api/current-content', headers: generateAuthorizationHeader(user), }; // When const response = await server.inject(currentContentOptions); // Then expect(JSON.parse(response.result)).to.deep.equal(JSON.parse(JSON.stringify(expectedCurrentContent))); }); it('should handle error', async () => { // Given airtableBuilder.mockList({ tableName: 'Domaines' }).returns().activate(500); airtableBuilder.mockList({ tableName: 'Competences' }).returns().activate(500); airtableBuilder.mockList({ tableName: 'Tubes' }).returns().activate(500); airtableBuilder.mockList({ tableName: 'Acquis' }).returns().activate(500); airtableBuilder.mockList({ tableName: 'Epreuves' }).returns().activate(500); airtableBuilder.mockList({ tableName: 'Tutoriels' }).returns().activate(500); const server = await createServer(); // When const response = await server.inject({ method: 'GET', url: '/api/current-content', headers: generateAuthorizationHeader(user), }); // Then expect(() => JSON.parse(response.result)).to.throw(Error); }); }); }); describe('GET /latest-release - Returns latest release', () => { context('nominal case', () => { let user; beforeEach(async function() { user = databaseBuilder.factory.buildAdminUser(); }); it('should return latest release of learning content', async () => { // Given const expectedLatestRelease = databaseBuilder.factory.buildRelease({ content: { areas: [], challenges: [], competences: [], courses: [], frameworks: [], skills: [], thematics: [], tubes: [], tutorials: [], missions: [], } }); const expectedContent = { areas: [], challenges: [], competences: [], courses: [], frameworks: [], skills: [], thematics: [], tubes: [], tutorials: [], missions: [], }; await databaseBuilder.commit(); const server = await createServer(); // When const response = await server.inject({ method: 'GET', url: '/api/releases/latest', headers: generateAuthorizationHeader(user), }); // Then const latestRelease = JSON.parse(response.result); expect(latestRelease.content).to.deep.equal(expectedContent); expect(latestRelease.id).to.deep.equal(expectedLatestRelease.id); expect(latestRelease.date).to.deep.equal(expectedLatestRelease.date); }); }); }); describe('POST /releases - Creates the release', () => { beforeEach(function() { vi.spyOn(axios, 'post').mockResolvedValue(); }); afterEach(function() { return knex('releases').delete(); }); context('nominal case', () => { it('should create the release', async () => { // Given const user = databaseBuilder.factory.buildAdminUser(); databaseBuilder.factory.buildMission({ id: 1, name: 'Ma première mission', competenceId: 'competenceId', thematicIds: 'thematicId,thematicId', learningObjectives: 'Que tu sois le meilleur', validatedObjectives: 'Rien', status: Mission.status.ACTIVE, }); databaseBuilder.factory.buildMission({ id: 2, name: 'Alt name', competenceId: 'competenceId', thematicIds: 'thematicId,thematicId', learningObjectives: 'Alt objectives', validatedObjectives: 'Alt validated objectives', status: Mission.status.INACTIVE, }); const server = await createServer(); await databaseBuilder.commit(); const expectedCurrentContent = await mockContentForRelease(); nock('https://api.phrase.com') .get('/v2/projects/MY_PHRASE_PROJECT_ID/locales') .matchHeader('authorization', 'token MY_PHRASE_ACCESS_TOKEN') .reply(200, [ { id: 'frLocaleId', name: 'fr', code: 'fr', default: true, }, ]); // When const response = await server.inject({ method: 'POST', url: '/api/releases', headers: generateAuthorizationHeader(user), }); // Then expect(response.statusCode).to.equal(200); const release = JSON.parse(response.result); expect(release.content).to.deep.equal(JSON.parse(JSON.stringify(expectedCurrentContent))); }); }); context('error case', async () => { it('should return a 403 when user is not allowed to create release', async () => { //given const user = databaseBuilder.factory.buildReadonlyUser(); const server = await createServer(); await databaseBuilder.commit(); // When const response = await server.inject({ method: 'POST', url: '/api/releases', headers: generateAuthorizationHeader(user), }); // Then expect(response.statusCode).to.equal(403); }); }); }); describe('GET /releases/:id - Returns given release', () => { let user; beforeEach(async function() { user = databaseBuilder.factory.buildAdminUser(); }); context('nominal case', () => { it('should return release specified by id', async () => { // Given const expectedRelease = databaseBuilder.factory.buildRelease({ id: 42, content: { areas: [], challenges: [], competences: [], courses: [], frameworks: [], skills: [], thematics: [], tubes: [], tutorials: [] }, createdAt: new Date('2021-01-01') }); databaseBuilder.factory.buildRelease({ id: 43, content: { some: 'other-release' }, createdAt: new Date('2022-01-01') }); const expectedContent = { areas: [], challenges: [], competences: [], courses: [], frameworks: [], skills: [], thematics: [], tubes: [], tutorials: [], missions: [], }; await databaseBuilder.commit(); const server = await createServer(); // When const response = await server.inject({ method: 'GET', url: '/api/releases/42', headers: generateAuthorizationHeader(user), }); // Then expect(response.statusCode).to.equal(200); const release = JSON.parse(response.result); expect(release.content).to.deep.equal(expectedContent); expect(release.id).to.deep.equal(expectedRelease.id); expect(release.date).to.deep.equal(expectedRelease.date); }); }); context('error case', () => { it('should return a 404 when the release does not exist', async () => { // Given await databaseBuilder.commit(); const server = await createServer(); // When const response = await server.inject({ method: 'GET', url: '/api/releases/42', headers: generateAuthorizationHeader(user), }); // Then expect(response.statusCode).to.equal(404); }); }); }); });
-- Set the leader key for Vim to be the spacebar. vim.g.mapleader = " " -- In normal mode, when you press the leader key followed by "pv", it will execute the Ex command. vim.keymap.set("n", "<leader>pv", vim.cmd.Ex) -- In visual mode, pressing "J" will move the selected lines down one position. vim.keymap.set("v", "J", ":m '>+1<CR>gv=gv") -- In visual mode, pressing "K" will move the selected lines up one position. vim.keymap.set("v", "K", ":m '<-2<CR>gv=gv") -- In normal mode, pressing "J" will join the current line with the line below and move the cursor back to where it was. vim.keymap.set("n", "J", "mzJ`z") -- In normal mode, when pressing Ctrl + d, the screen will scroll down and center on the cursor. vim.keymap.set("n", "<C-d>", "<C-d>zz") -- In normal mode, when pressing Ctrl + u, the screen will scroll up and center on the cursor. vim.keymap.set("n", "<C-u>", "<C-u>zz") -- In normal mode, after pressing "n" to find the next search occurrence, the screen will center on the found occurrence. vim.keymap.set("n", "n", "nzzzv") -- In normal mode, after pressing "N" to find the previous search occurrence, the screen will center on the found occurrence. vim.keymap.set("n", "N", "Nzzzv") -- In visual mode, pressing the leader key followed by "p" will paste over the selected text without overwriting the clipboard. vim.keymap.set("x", "<leader>p", [["_dP]]) -- Map copying to system clipboard with leader+y in both normal and visual modes. vim.keymap.set({"n", "v"}, "<leader>y", [["+y]]) vim.keymap.set("n", "<leader>Y", [["+Y]]) -- Map deleting without affecting the clipboard in both normal and visual modes. vim.keymap.set({"n", "v"}, "<leader>d", [["_d]]) -- In insert mode, pressing Ctrl + c will exit to normal mode. vim.keymap.set("i", "<C-c>", "<Esc>") -- Disable the Q command in normal mode. vim.keymap.set("n", "Q", "<nop>") -- In normal mode, pressing Ctrl + f will open a new tmux window named "tmux-sessionizer". vim.keymap.set("n", "<C-f>", "<cmd>silent !tmux neww tmux-sessionizer<CR>") -- In normal mode, pressing the leader key followed by "f" will format the buffer using LSP. vim.keymap.set("n", "<leader>f", vim.lsp.buf.format) -- Move between compilation errors using Ctrl + k (next) and Ctrl + j (previous), centering the screen on the error. vim.keymap.set("n", "<C-k>", "<cmd>cnext<CR>zz") vim.keymap.set("n", "<C-j>", "<cmd>cprev<CR>zz") -- Move between location list items using leader + k (next) and leader + j (previous), centering the screen. vim.keymap.set("n", "<leader>k", "<cmd>lnext<CR>zz") vim.keymap.set("n", "<leader>j", "<cmd>lprev<CR>zz") -- In normal mode, pressing leader + s will bring up a search and replace prompt using the word under the cursor. vim.keymap.set("n", "<leader>s", [[:%s/\<<C-r><C-w>\>/<C-r><C-w>/gI<Left><Left><Left>]]) -- In normal mode, pressing leader + x will make the current file executable. vim.keymap.set("n", "<leader>x", "<cmd>!chmod +x %<CR>", { silent = true }) -- Open the personal configuration for "packer.lua" with leader+vpp. vim.keymap.set("n", "<leader>vpp", "<cmd>e ~/.config/nvim/lua/koba/packer.lua<CR>") -- Toggle auto save vim.api.nvim_set_keymap("n", "<leader>n", ":ASToggle<CR>", {}) -- In normal mode, pressing leader twice will source the current file (usually for configurations). vim.keymap.set("n", "<leader><leader>", function() vim.cmd("so") end) -- <leader>t brings up a bottom-split terminal vim.api.nvim_set_keymap('n', '<leader>t', ':bo sp | terminal<CR>', { noremap = true, silent = true }) -- In normal mode, pressing leader followed by "sw" will set wrap and linebreak. vim.keymap.set("n", "<leader>sw", function() vim.cmd("set wrap") vim.cmd("set linebreak") end)
# Codespaces You can create a [GitHub Codespace][github-com-codespaces] for pgec that has PostgreSQL and Prometheus setup with [instructions from GitHub on creating a codespace][gihub-com-cacfar]. Some CLI convenience snippets follow. Firstly, follow the [GitHub CLI installation instructions][github-com-installation] for your OS. Clone the pgec repository: ```shell gh repo clone shortishly/pgec ``` Create a codespace for pgec: ```shell gh codespace create \ --repo $(gh repo view \ --json nameWithOwner \ --jq .nameWithOwner) \ --branch develop \ --machine basicLinux32gb ``` Run a secure shell into the codespace: ```shell gh codespace ssh \ --codespace $(gh codespace ls \ --repo $(gh repo view \ --json nameWithOwner \ --jq .nameWithOwner) \ --json name \ --jq '.[].name') ``` Once in the secure shell environment, you can check that [PostgreSQL][postgresql-org] and [Prometheus][prometheus-io] are running OK: ```shell docker compose --profile all ps ``` To build pgec, [dialyze][erlang-org-dialyzer] and run the [unit][erlang-org-eunit-ug] tests: ```shell make deps app dialyze eunit ``` To run the [common tests][erlang-org-ctug] against the [PostgreSQL][postgresql-org] already running in the [codespace][github-com-codespaces]: ```shell make ct ``` To run an interactive Erlang/OTP shell with the pgec application running: ```shell make shell ``` Once you are finished you can delete the [codespace][github-com-codespaces] using: ```shell gh codespace delete \ --codespace $(gh codespace ls \ --repo $(gh repo view \ --json nameWithOwner \ --jq .nameWithOwner) \ --json name \ --jq '.[].name') ``` [erlang-org-ctug]: https://www.erlang.org/doc/apps/common_test/users_guide.html [erlang-org-dialyzer]: https://www.erlang.org/doc/man/dialyzer.html [erlang-org-eunit-ug]: https://www.erlang.org/doc/apps/eunit/users_guide.html [gihub-com-cacfar]: https://docs.github.com/en/codespaces/developing-in-codespaces/creating-a-codespace-for-a-repository [github-com-codespaces]: https://docs.github.com/en/codespaces [github-com-installation]: https://cli.github.com/manual/installation [postgresql-org]: https://www.postgresql.org/ [prometheus-io]: https://prometheus.io
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:widgets_app/config/router/app_router.dart'; import 'package:widgets_app/config/theme/app_theme.dart'; import 'package:widgets_app/presentation/providers/theme_provider.dart'; void main() { // river provider runApp(const ProviderScope(child: MainApp())); } class MainApp extends ConsumerWidget { const MainApp({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { // Listen the display mode of device. // final isDarkmode = ref.watch(isDarkmodeProvider); // final selectedColor = ref.watch(selectedColorProvider); final AppTheme appTheme = ref.watch(themeNotifierProvider); return MaterialApp.router( title: 'Flutter Widgets', // Define the route of all screen into the app routerConfig: appRouter, debugShowCheckedModeBanner: false, theme: appTheme.getTheme(), ); } }
import React, { FunctionComponent, useState } from "react"; import { Paper, Accordion, AccordionSummary, AccordionDetails, Typography, Tooltip, IconButton, TableRow, TableCell, Table, TableBody, Box, } from "@mui/material"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import { Fetcher } from "../../../../common/components/Fetcher"; import { SQLService } from "../../../services/SQLService"; import { ICustomError, IDatabseStorageSizeResponse, DatabseStorageSizeResponse, IMetricMetadata, } from "../../../models"; import { CopyToClipboard } from "../../../components/CopyToClipboard"; import CodeIcon from "@mui/icons-material/Code"; import { ShowQueryScreen } from "../ShowQueryScreen"; import ReplayIcon from "@mui/icons-material/Replay"; import AddAlertIcon from "@mui/icons-material/AddAlert"; import { useStyles } from "../../../components/StyleClass"; import Chart from "react-google-charts"; import { MetricHeader } from "../../../components/MetricHeader"; import SettingsIcon from "@mui/icons-material/Settings"; import { SingleTriggerDialog } from "../../../components/SingleTriggerDialog"; import { SqlAlertDialog } from "../../../components/SqlAlertDialog"; import { reloadMetricEvent, showQueryEvent, expandMetricEvent, configureDataRecordingViewEvent, } from "../../../tracking/TrackEventMethods"; import { useAdminEmail } from "../../../../hooks"; import { MenuText, MenuTitle } from "../DatabaseDashboardScreen"; import {Helpers} from "../../../helpers"; interface DatabaseStorageSizeScreenProps { databaseName: string; } export const DatabaseStorageSizeScreen: FunctionComponent< DatabaseStorageSizeScreenProps > = (props) => { const classes = useStyles(); const [errorMessage, setErrorMessage] = useState<string | null>(null); const [dbStorageSize, setDbStorageSize] = useState< DatabseStorageSizeResponse[] >([]); const [showQuery, setShowQuery] = useState<boolean>(false); const [expanded, setExpanded] = React.useState<boolean>(false); const [metadata, setMetadata] = useState<IMetricMetadata>(); const [jobConfigureDialogOpen, setJobConfigureDialogOpen] = useState<boolean>(false); const [alertDialogOpen, setAlertDialogOpen] = useState<boolean>(false); const email = useAdminEmail(); const handleOnApiResponse = ( r: IDatabseStorageSizeResponse | ICustomError ) => { if ("code" in r && "message" in r && "details" in r) { setErrorMessage(`${r.message}: ${r.details}`); } else { const result = r.metricOutput.result.queryList; setMetadata(r.metadata); let results = Helpers.changeSize(result); setDbStorageSize(results); } }; const closeAlertDialog = () => { setAlertDialogOpen(false); }; const basicPropsForMixPanel = { dbName: props.databaseName, userEmail: email, metricTitle: MenuTitle.STORAGE, metricText: `${MenuText.DATABASE_LEVEL}_STORAGE_SIZE`, }; const handleReload = () => { SQLService.getDatabaseStorageSize(props.databaseName) .then((r) => { handleOnApiResponse(r); setErrorMessage(""); setExpanded(true); metadata && reloadMetricEvent(basicPropsForMixPanel); }) .catch((e) => { setErrorMessage(e); setExpanded(true); }); }; const handleChange = () => { setExpanded((prev) => !prev); metadata && expandMetricEvent(basicPropsForMixPanel); }; const handleShowQuery = () => { setShowQuery(!showQuery); metadata && showQueryEvent({ ...basicPropsForMixPanel, query: metadata.underlyingQueries[0], }); }; const showAlertDialog = () => { setAlertDialogOpen(true); }; const handleJobConfigureDialogOpen = () => { setJobConfigureDialogOpen(true); configureDataRecordingViewEvent(basicPropsForMixPanel); }; return ( <Accordion expanded={expanded}> <AccordionSummary expandIcon={<ExpandMoreIcon />} onClick={handleChange} > <div className={classes.summaryContent}> <MetricHeader title="Database Storage Size" metadata={metadata} /> </div> </AccordionSummary> <AccordionDetails> {metadata?.supportsAlert && ( <SqlAlertDialog open={alertDialogOpen} handleClose={closeAlertDialog} databaseName={props.databaseName} supportedAlertTypes={metadata?.supportedAlerts} /> )} <Paper style={{ width: "100%" }}> <div style={{ float: "right" }}> {showQuery && metadata && metadata.underlyingQueries && ( <CopyToClipboard text={metadata.underlyingQueries[0]} /> )} {metadata && metadata.supportsAlert && ( <Tooltip title="Manage Alerts"> <IconButton onClick={() => showAlertDialog()} size="large"> <AddAlertIcon /> </IconButton> </Tooltip> )} {metadata && metadata.supportsHistorical && ( <Tooltip title="Configure Data Recording"> <IconButton onClick={handleJobConfigureDialogOpen} size="large"> <SettingsIcon /> </IconButton> </Tooltip> )} <Tooltip title={showQuery ? "Hide the source" : "Show the source"}> <IconButton aria-label="delete" onClick={() => handleShowQuery()} size="large"> <CodeIcon /> </IconButton> </Tooltip> <Tooltip title="Reload"> <IconButton onClick={handleReload} size="large"> <ReplayIcon /> </IconButton> </Tooltip> </div> {errorMessage && ( <div style={{ marginLeft: "5px", padding: "10px", color: "red", fontFamily: "monospace", }} > <details open> <summary>Error</summary> <p>{errorMessage}</p> </details> </div> )} <Fetcher fetchData={() => SQLService.getDatabaseStorageSize(props.databaseName) } onFetch={(r) => handleOnApiResponse(r)} > {showQuery && metadata && metadata.underlyingQueries && ( <ShowQueryScreen query={metadata.underlyingQueries[0]} /> )} {!showQuery && ( <Box paddingTop={8} paddingRight={8} paddingBottom={4} paddingLeft={4} > <div style={{ height: 700, width: "100%" }}> {dbStorageSize.length && ( <Chart width={"1500px"} height={"300px"} chartType="PieChart" loader={<div>Loading Chart</div>} data={[ ["Name", "Size in GB"], [ "Data " + dbStorageSize[0].data, parseFloat(dbStorageSize[0].data), ], [ "Index " + dbStorageSize[0].indexSize, parseFloat(dbStorageSize[0].indexSize), ], [ "Unused " + dbStorageSize[0].unused, parseFloat(dbStorageSize[0].unused), ], [ "Total " + dbStorageSize[0].dbTotalSize.toString(), dbStorageSize[0].dbTotalSize, ], ]} options={{ title: "Database Storage Space Breakup ", pieSliceText: "label", }} rootProps={{ "data-testid": "1" }} /> )} {!errorMessage && dbStorageSize.length ? ( <Table> <TableBody> {Object.entries(dbStorageSize[0]).map((x, y) => { return ( <TableRow> <TableCell> {x[0] .split(/(?=[A-Z])/) .join(" ") .toUpperCase()} </TableCell> <TableCell>{x[1]}</TableCell> </TableRow> ); })} </TableBody> </Table> ) : ( <Typography>No records found</Typography> )} </div> </Box> )} </Fetcher> </Paper> </AccordionDetails> <SingleTriggerDialog open={jobConfigureDialogOpen} handleClose={() => setJobConfigureDialogOpen(false)} databaseName={props.databaseName} metricId={"storage_db"} metricName={"Database Storage Size"} minimumRepeatInterval={metadata?.minimumRepeatInterval} /> </Accordion> ); };
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; use frame_support::{ dispatch::{DispatchErrorWithPostInfo, DispatchResult, DispatchResultWithPostInfo}, ensure, traits::{Currency, ExistenceRequirement, Get, OnTimestampSet}, }; use frame_system::{self, ensure_signed}; use sp_core::H256; use sp_runtime::traits::SaturatedConversion; #[cfg(not(feature = "skip-ias-check"))] use sp_runtime::traits::CheckedSub; use sp_std::{prelude::*, str}; use teerex_primitives::*; use sgx_verify::{ deserialize_enclave_identity, deserialize_tcb_info, extract_certs, verify_certificate_chain, }; #[cfg(not(feature = "skip-ias-check"))] use sgx_verify::{verify_dcap_quote, verify_ias_report, SgxReport}; pub use crate::weights::WeightInfo; // Disambiguate associated types pub type AccountId<T> = <T as frame_system::Config>::AccountId; pub type BalanceOf<T> = <<T as Config>::Currency as Currency<AccountId<T>>>::Balance; pub use pallet::*; const MAX_RA_REPORT_LEN: usize = 5244; const MAX_DCAP_QUOTE_LEN: usize = 5000; const MAX_URL_LEN: usize = 256; /// Maximum number of topics for the `publish_hash` call. const TOPICS_LIMIT: usize = 5; /// Maximum number of bytes for the `data` in the `publish_hash` call. const DATA_LENGTH_LIMIT: usize = 100; #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] #[pallet::without_storage_info] pub struct Pallet<T>(PhantomData<T>); #[pallet::hooks] impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {} #[pallet::config] pub trait Config: frame_system::Config + timestamp::Config { type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>; type Currency: Currency<<Self as frame_system::Config>::AccountId>; type MomentsPerDay: Get<Self::Moment>; type WeightInfo: WeightInfo; type MaxSilenceTime: Get<Self::Moment>; /// The origin who can set the admin account type SetAdminOrigin: EnsureOrigin<Self::RuntimeOrigin>; } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { AdminChanged { old_admin: Option<T::AccountId>, }, AddedEnclave(T::AccountId, Vec<u8>), RemovedEnclave(T::AccountId), Forwarded(ShardIdentifier), ShieldFunds(Vec<u8>), UnshieldedFunds(T::AccountId), ProcessedParentchainBlock(T::AccountId, H256, H256, T::BlockNumber), SetHeartbeatTimeout(u64), UpdatedScheduledEnclave(SidechainBlockNumber, MrEnclave), RemovedScheduledEnclave(SidechainBlockNumber), /// An enclave with [mr_enclave] has published some [hash] with some metadata [data]. PublishedHash { mr_enclave: MrEnclave, hash: H256, data: Vec<u8>, }, NewMrenclaveSet { new_mrenclave: MrEnclave, }, } #[pallet::storage] #[pallet::getter(fn admin)] pub type Admin<T: Config> = StorageValue<_, T::AccountId, OptionQuery>; // Watch out: we start indexing with 1 instead of zero in order to // avoid ambiguity between Null and 0. #[pallet::storage] #[pallet::getter(fn enclave)] pub type EnclaveRegistry<T: Config> = StorageMap<_, Blake2_128Concat, u64, Enclave<T::AccountId, Vec<u8>>, OptionQuery>; #[pallet::storage] #[pallet::getter(fn enclave_count)] pub type EnclaveCount<T: Config> = StorageValue<_, u64, ValueQuery>; #[pallet::storage] #[pallet::getter(fn quoting_enclave)] pub type QuotingEnclaveRegistry<T: Config> = StorageValue<_, QuotingEnclave, ValueQuery>; #[pallet::storage] #[pallet::getter(fn tcb_info)] pub type TcbInfo<T: Config> = StorageMap<_, Blake2_128Concat, Fmspc, TcbInfoOnChain, ValueQuery>; #[pallet::storage] #[pallet::getter(fn enclave_index)] pub type EnclaveIndex<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, u64, ValueQuery>; #[pallet::storage] #[pallet::getter(fn confirmed_calls)] pub type ExecutedCalls<T: Config> = StorageMap<_, Blake2_128Concat, H256, u64, ValueQuery>; #[pallet::storage] #[pallet::getter(fn allow_sgx_debug_mode)] pub type AllowSGXDebugMode<T: Config> = StorageValue<_, bool, ValueQuery>; #[pallet::type_value] pub fn HeartbeatTimeoutDefault<T: Config>() -> T::Moment { T::Moment::saturated_from::<u64>(172_800_000) // default 48h } // keep track of a list of scheduled/allowed enchalves, mainly used for enclave updates, // can only be modified by AdminOrigin // sidechain_block_number -> expected MrEnclave // // about the first time enclave registration: // prior to `register_enclave` this map needs to be populated with (0, expected-mrenclave), // otherwise the registration will fail // // Theorectically we could always push the enclave in `register_enclave`, but the problem is // anyone could try to register it as long as the enclave is remotely attested: // see https://github.com/litentry/litentry-parachain/issues/1163 // so we need an "enclave whitelist" anyway #[pallet::storage] #[pallet::getter(fn scheduled_enclave)] pub type ScheduledEnclave<T: Config> = StorageMap<_, Blake2_128Concat, SidechainBlockNumber, MrEnclave>; #[pallet::storage] #[pallet::getter(fn heartbeat_timeout)] pub type HeartbeatTimeout<T: Config> = StorageValue<_, T::Moment, ValueQuery, HeartbeatTimeoutDefault<T>>; #[pallet::genesis_config] pub struct GenesisConfig<T: Config> { pub allow_sgx_debug_mode: bool, pub admin: Option<T::AccountId>, } #[cfg(feature = "std")] impl<T: Config> Default for GenesisConfig<T> { fn default() -> Self { Self { allow_sgx_debug_mode: false, admin: None } } } #[pallet::genesis_build] impl<T: Config> GenesisBuild<T> for GenesisConfig<T> { fn build(&self) { AllowSGXDebugMode::<T>::put(self.allow_sgx_debug_mode); if let Some(ref admin) = self.admin { Admin::<T>::put(admin); } } } #[pallet::call] impl<T: Config> Pallet<T> where // Needed for the conversion of `mr_enclave` to a `Hash`. // The condition holds for all known chains. <T as frame_system::Config>::Hash: From<[u8; 32]>, { // the litentry-worker wants to register his enclave #[pallet::call_index(0)] #[pallet::weight((<T as Config>::WeightInfo::register_enclave(), DispatchClass::Normal, Pays::Yes))] pub fn register_enclave( origin: OriginFor<T>, ra_report: Vec<u8>, worker_url: Vec<u8>, shielding_key: Option<Vec<u8>>, vc_pubkey: Option<Vec<u8>>, ) -> DispatchResultWithPostInfo { log::info!("teerex: called into runtime call register_enclave()"); let sender = ensure_signed(origin)?; ensure!(ra_report.len() <= MAX_RA_REPORT_LEN, <Error<T>>::RaReportTooLong); ensure!(worker_url.len() <= MAX_URL_LEN, <Error<T>>::EnclaveUrlTooLong); log::info!("teerex: parameter length ok"); #[cfg(not(feature = "skip-ias-check"))] let enclave = Self::verify_report(&sender, ra_report.clone()).map(|report| { #[cfg(test)] { return Enclave::new( sender.clone(), report.mr_enclave, report.timestamp, worker_url.clone(), shielding_key, vc_pubkey, report.build_mode, Default::default(), ) } #[cfg(not(test))] Enclave::new( sender.clone(), report.mr_enclave, report.timestamp, worker_url.clone(), shielding_key, vc_pubkey, report.build_mode, report.metadata, ) })?; #[cfg(not(feature = "skip-ias-check"))] if !<AllowSGXDebugMode<T>>::get() && enclave.sgx_mode == SgxBuildMode::Debug { log::error!("substraTEE_registry: debug mode is not allowed to attest!"); return Err(<Error<T>>::SgxModeNotAllowed.into()) } #[cfg(feature = "skip-ias-check")] log::warn!("[teerex]: Skipping remote attestation check. Only dev-chains are allowed to do this!"); #[cfg(feature = "skip-ias-check")] let enclave = Enclave::new( sender.clone(), // insert mrenclave if the ra_report represents one, otherwise insert default <MrEnclave>::decode(&mut ra_report.as_slice()).unwrap_or_default(), <timestamp::Pallet<T>>::get().saturated_into(), worker_url.clone(), shielding_key, vc_pubkey, SgxBuildMode::default(), SgxEnclaveMetadata::default(), ); // TODO: imagine this fn is not called for the first time (e.g. when worker restarts), // should we check the current sidechain_blocknumber >= registered // sidechain_blocknumber? #[cfg(not(feature = "skip-scheduled-enclave-check"))] ensure!( ScheduledEnclave::<T>::iter_values().any(|m| m == enclave.mr_enclave), Error::<T>::EnclaveNotInSchedule ); Self::add_enclave(&sender, &enclave)?; Self::deposit_event(Event::AddedEnclave(sender, worker_url)); Ok(().into()) } #[pallet::call_index(1)] #[pallet::weight((<T as Config>::WeightInfo::unregister_enclave(), DispatchClass::Normal, Pays::Yes))] pub fn unregister_enclave(origin: OriginFor<T>) -> DispatchResultWithPostInfo { log::info!("teerex: called into runtime call unregister_enclave()"); let sender = ensure_signed(origin)?; Self::remove_enclave(&sender)?; Self::deposit_event(Event::RemovedEnclave(sender)); Ok(().into()) } #[pallet::call_index(2)] #[pallet::weight((<T as Config>::WeightInfo::call_worker(), DispatchClass::Normal, Pays::Yes))] pub fn call_worker(origin: OriginFor<T>, request: Request) -> DispatchResult { let _sender = ensure_signed(origin)?; log::info!("call_worker with {:?}", request); Self::deposit_event(Event::Forwarded(request.shard)); Ok(()) } /// The integritee worker calls this function for every processed parentchain_block to /// confirm a state update. #[pallet::call_index(3)] #[pallet::weight((<T as Config>::WeightInfo::confirm_processed_parentchain_block(), DispatchClass::Normal, Pays::Yes))] pub fn confirm_processed_parentchain_block( origin: OriginFor<T>, block_hash: H256, #[pallet::compact] block_number: T::BlockNumber, trusted_calls_merkle_root: H256, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; log::debug!( "Processed parentchain block confirmed for enclave {:?}, block_hash {:?}, block_number {:?}", sender, block_hash, block_number ); Self::ensure_registered_enclave(&sender)?; let mut enclave = Self::get_enclave(&sender)?; enclave.timestamp = <timestamp::Pallet<T>>::get().saturated_into(); Self::add_enclave(&sender, &enclave)?; Self::deposit_event(Event::ProcessedParentchainBlock( sender, block_hash, trusted_calls_merkle_root, block_number, )); Ok(().into()) } /// Sent by a client who requests to get shielded funds managed by an enclave. For this /// on-chain balance is sent to the bonding_account of the enclave. The bonding_account does /// not have a private key as the balance on this account is exclusively managed from /// withing the pallet_teerex. Note: The bonding_account is bit-equivalent to the worker /// shard. #[pallet::call_index(4)] #[pallet::weight((1000, DispatchClass::Normal, Pays::No))] pub fn shield_funds( origin: OriginFor<T>, incognito_account_encrypted: Vec<u8>, amount: BalanceOf<T>, bonding_account: T::AccountId, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; T::Currency::transfer( &sender, &bonding_account, amount, ExistenceRequirement::AllowDeath, )?; Self::deposit_event(Event::ShieldFunds(incognito_account_encrypted)); Ok(().into()) } /// Sent by enclaves only as a result of an `unshield` request from a client to an enclave. #[pallet::call_index(5)] #[pallet::weight((1000, DispatchClass::Normal, Pays::No))] pub fn unshield_funds( origin: OriginFor<T>, public_account: T::AccountId, amount: BalanceOf<T>, bonding_account: T::AccountId, call_hash: H256, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; Self::ensure_registered_enclave(&sender)?; let sender_enclave = Self::get_enclave(&sender)?; ensure!( sender_enclave.mr_enclave.encode() == bonding_account.encode(), <Error<T>>::WrongMrenclaveForBondingAccount ); if !<ExecutedCalls<T>>::contains_key(call_hash) { log::info!("Executing unshielding call: {:?}", call_hash); T::Currency::transfer( &bonding_account, &public_account, amount, ExistenceRequirement::AllowDeath, )?; <ExecutedCalls<T>>::insert(call_hash, 0); Self::deposit_event(Event::UnshieldedFunds(public_account)); } else { log::info!("Already executed unshielding call: {:?}", call_hash); } <ExecutedCalls<T>>::mutate(call_hash, |confirmations| *confirmations += 1); Ok(().into()) } #[pallet::call_index(6)] #[pallet::weight((195_000_000, DispatchClass::Normal, Pays::No))] pub fn set_heartbeat_timeout( origin: OriginFor<T>, #[pallet::compact] timeout: u64, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; ensure!(Some(sender) == Self::admin(), Error::<T>::RequireAdmin); <HeartbeatTimeout<T>>::put(T::Moment::saturated_from(timeout)); Self::deposit_event(Event::SetHeartbeatTimeout(timeout)); Ok(().into()) } #[pallet::call_index(7)] #[pallet::weight((<T as Config>::WeightInfo::register_dcap_enclave(), DispatchClass::Normal, Pays::Yes))] pub fn register_dcap_enclave( origin: OriginFor<T>, dcap_quote: Vec<u8>, worker_url: Vec<u8>, ) -> DispatchResultWithPostInfo { log::info!("teerex: called into runtime call register_dcap_enclave()"); let sender = ensure_signed(origin)?; ensure!(dcap_quote.len() <= MAX_DCAP_QUOTE_LEN, <Error<T>>::RaReportTooLong); ensure!(worker_url.len() <= MAX_URL_LEN, <Error<T>>::EnclaveUrlTooLong); log::info!("teerex: parameter length ok"); let dummy_shielding_key: Option<Vec<u8>> = Default::default(); let dummy_vc_pubkey: Option<Vec<u8>> = Default::default(); let dummy_meta = Default::default(); #[cfg(not(feature = "skip-ias-check"))] let enclave = Self::verify_dcap_quote(&sender, dcap_quote).map(|report| { Enclave::new( sender.clone(), report.mr_enclave, report.timestamp, worker_url.clone(), dummy_shielding_key, dummy_vc_pubkey, report.build_mode, dummy_meta, ) })?; #[cfg(not(feature = "skip-ias-check"))] if !<AllowSGXDebugMode<T>>::get() && enclave.sgx_mode == SgxBuildMode::Debug { log::error!("substraTEE_registry: debug mode is not allowed to attest!"); return Err(<Error<T>>::SgxModeNotAllowed.into()) } #[cfg(feature = "skip-ias-check")] log::warn!("[teerex]: Skipping remote attestation check. Only dev-chains are allowed to do this!"); #[cfg(feature = "skip-ias-check")] let enclave = Enclave::new( sender.clone(), // insert mrenclave if the ra_report represents one, otherwise insert default <MrEnclave>::decode(&mut dcap_quote.as_slice()).unwrap_or_default(), <timestamp::Pallet<T>>::get().saturated_into(), worker_url.clone(), dummy_shielding_key, dummy_vc_pubkey, SgxBuildMode::default(), dummy_meta, ); Self::add_enclave(&sender, &enclave)?; Self::deposit_event(Event::AddedEnclave(sender, worker_url)); Ok(().into()) } #[pallet::call_index(8)] #[pallet::weight((195_000_000, DispatchClass::Normal, Pays::No))] pub fn update_scheduled_enclave( origin: OriginFor<T>, #[pallet::compact] sidechain_block_number: SidechainBlockNumber, mr_enclave: MrEnclave, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; ensure!(Some(sender) == Self::admin(), Error::<T>::RequireAdmin); ScheduledEnclave::<T>::insert(sidechain_block_number, mr_enclave); Self::deposit_event(Event::UpdatedScheduledEnclave(sidechain_block_number, mr_enclave)); Ok(().into()) } #[pallet::call_index(9)] #[pallet::weight((<T as Config>::WeightInfo::register_quoting_enclave(), DispatchClass::Normal, Pays::Yes))] pub fn register_quoting_enclave( origin: OriginFor<T>, enclave_identity: Vec<u8>, signature: Vec<u8>, certificate_chain: Vec<u8>, ) -> DispatchResultWithPostInfo { log::info!("teerex: called into runtime call register_quoting_enclave()"); // Quoting enclaves are registered globally and not for a specific sender let _sender = ensure_signed(origin)?; let quoting_enclave = Self::verify_quoting_enclave(enclave_identity, signature, certificate_chain)?; <QuotingEnclaveRegistry<T>>::put(quoting_enclave); Ok(().into()) } #[pallet::call_index(10)] #[pallet::weight((195_000_000, DispatchClass::Normal, Pays::No))] pub fn remove_scheduled_enclave( origin: OriginFor<T>, #[pallet::compact] sidechain_block_number: SidechainBlockNumber, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; ensure!(Some(sender) == Self::admin(), Error::<T>::RequireAdmin); ensure!( ScheduledEnclave::<T>::contains_key(sidechain_block_number), Error::<T>::ScheduledEnclaveNotExist ); ScheduledEnclave::<T>::remove(sidechain_block_number); Self::deposit_event(Event::RemovedScheduledEnclave(sidechain_block_number)); Ok(().into()) } #[pallet::call_index(11)] #[pallet::weight((<T as Config>::WeightInfo::register_dcap_enclave(), DispatchClass::Normal, Pays::Yes))] pub fn register_tcb_info( origin: OriginFor<T>, tcb_info: Vec<u8>, signature: Vec<u8>, certificate_chain: Vec<u8>, ) -> DispatchResultWithPostInfo { log::info!("teerex: called into runtime call register_tcb_info()"); // TCB info is registered globally and not for a specific sender let _sender = ensure_signed(origin)?; let (fmspc, on_chain_info) = Self::verify_tcb_info(tcb_info, signature, certificate_chain)?; <TcbInfo<T>>::insert(fmspc, on_chain_info); Ok(().into()) } /// Publish a hash as a result of an arbitrary enclave operation. /// /// The `mrenclave` of the origin will be used as an event topic a client can subscribe to. /// `extra_topics`, if any, will be used as additional event topics. /// /// `data` can be anything worthwhile publishing related to the hash. If it is a /// utf8-encoded string, the UIs will usually even render the text. #[pallet::call_index(12)] #[pallet::weight((<T as Config>::WeightInfo::publish_hash(), DispatchClass::Normal, Pays::Yes))] pub fn publish_hash( origin: OriginFor<T>, hash: H256, extra_topics: Vec<T::Hash>, data: Vec<u8>, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; Self::ensure_registered_enclave(&sender)?; let enclave = Self::get_enclave(&sender)?; ensure!(extra_topics.len() <= TOPICS_LIMIT, <Error<T>>::TooManyTopics); ensure!(data.len() <= DATA_LENGTH_LIMIT, <Error<T>>::DataTooLong); let mut topics = extra_topics; topics.push(enclave.mr_enclave.into()); Self::deposit_event_indexed( &topics, Event::PublishedHash { mr_enclave: enclave.mr_enclave, hash, data }, ); Ok(().into()) } /// Change the admin account /// similar to sudo.set_key, the old account will be supplied in event #[pallet::call_index(13)] #[pallet::weight((195_000_000, DispatchClass::Normal, Pays::No))] pub fn set_admin(origin: OriginFor<T>, new: T::AccountId) -> DispatchResultWithPostInfo { T::SetAdminOrigin::ensure_origin(origin)?; Self::deposit_event(Event::AdminChanged { old_admin: Self::admin() }); <Admin<T>>::put(new); // Do not pay a fee Ok(Pays::No.into()) } /// Set registered mrenclave /// This is a workaround to overcome the problem that the ra-report seems to contain /// the old mrenclave after doing enclave update, which breaks the client/IDHub. /// See https://github.com/litentry/litentry-parachain/issues/1820 /// /// To be removed once the issue is solved #[pallet::call_index(30)] #[pallet::weight((195_000_000, DispatchClass::Normal, Pays::No))] pub fn set_mrenclave( origin: OriginFor<T>, new_mrenclave: MrEnclave, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; ensure!(Some(sender) == Self::admin(), Error::<T>::RequireAdmin); // not the best way but just to get the job done for index in <EnclaveRegistry<T>>::iter_keys() { let mut enclave = <EnclaveRegistry<T>>::get(index).ok_or(Error::<T>::EmptyEnclaveRegistry)?; enclave.mr_enclave = new_mrenclave; <EnclaveRegistry<T>>::insert(index, enclave); } Self::deposit_event(Event::NewMrenclaveSet { new_mrenclave }); // Do not pay a fee Ok(Pays::No.into()) } } #[pallet::error] pub enum Error<T> { /// This operation needs the admin permission RequireAdmin, /// Failed to decode enclave signer. EnclaveSignerDecodeError, /// Sender does not match attested enclave in report. SenderIsNotAttestedEnclave, /// Verifying RA report failed. RemoteAttestationVerificationFailed, RemoteAttestationTooOld, /// The enclave cannot attest, because its building mode is not allowed. SgxModeNotAllowed, /// The enclave is not registered. EnclaveIsNotRegistered, /// The bonding account doesn't match the enclave. WrongMrenclaveForBondingAccount, /// The shard doesn't match the enclave. WrongMrenclaveForShard, /// The worker url is too long. EnclaveUrlTooLong, /// The Remote Attestation report is too long. RaReportTooLong, /// No enclave is registered. EmptyEnclaveRegistry, /// Can not found the desired scheduled enclave. ScheduledEnclaveNotExist, /// Enclave not in the scheduled list, therefore unexpected. EnclaveNotInSchedule, /// The provided collateral data is invalid CollateralInvalid, /// The number of `extra_topics` passed to `publish_hash` exceeds the limit. TooManyTopics, /// The length of the `data` passed to `publish_hash` exceeds the limit. DataTooLong, } } impl<T: Config> Pallet<T> { pub fn add_enclave( sender: &T::AccountId, enclave: &Enclave<T::AccountId, Vec<u8>>, ) -> DispatchResultWithPostInfo { let enclave_idx = if <EnclaveIndex<T>>::contains_key(sender) { log::info!("Updating already registered enclave"); <EnclaveIndex<T>>::get(sender) } else { let enclaves_count = Self::enclave_count() .checked_add(1) .ok_or("[Teerex]: Overflow adding new enclave to registry")?; <EnclaveIndex<T>>::insert(sender, enclaves_count); <EnclaveCount<T>>::put(enclaves_count); enclaves_count }; <EnclaveRegistry<T>>::insert(enclave_idx, enclave); Ok(().into()) } fn remove_enclave(sender: &T::AccountId) -> DispatchResultWithPostInfo { ensure!(<EnclaveIndex<T>>::contains_key(sender), <Error<T>>::EnclaveIsNotRegistered); let index_to_remove = <EnclaveIndex<T>>::take(sender); let enclaves_count = Self::enclave_count(); let new_enclaves_count = enclaves_count .checked_sub(1) .ok_or("[Teerex]: Underflow removing an enclave from the registry")?; Self::swap_and_pop(index_to_remove, new_enclaves_count + 1)?; <EnclaveCount<T>>::put(new_enclaves_count); Ok(().into()) } pub(crate) fn get_enclave( sender: &T::AccountId, ) -> Result<Enclave<T::AccountId, Vec<u8>>, Error<T>> { let sender_index = <EnclaveIndex<T>>::get(sender); <EnclaveRegistry<T>>::get(sender_index).ok_or(Error::<T>::EmptyEnclaveRegistry) } /// Our list implementation would introduce holes in out list if if we try to remove elements /// from the middle. As the order of the enclave entries is not important, we use the swap and /// pop method to remove elements from the registry. fn swap_and_pop(index_to_remove: u64, new_enclaves_count: u64) -> DispatchResultWithPostInfo { if index_to_remove != new_enclaves_count { let last_enclave = <EnclaveRegistry<T>>::get(new_enclaves_count) .ok_or(Error::<T>::EmptyEnclaveRegistry)?; <EnclaveRegistry<T>>::insert(index_to_remove, &last_enclave); <EnclaveIndex<T>>::insert(last_enclave.pubkey, index_to_remove); } <EnclaveRegistry<T>>::remove(new_enclaves_count); Ok(().into()) } fn unregister_silent_workers(now: T::Moment) { let minimum = (now - Self::heartbeat_timeout()).saturated_into::<u64>(); let silent_workers = <EnclaveRegistry<T>>::iter() .filter(|e| e.1.timestamp < minimum) .map(|e| e.1.pubkey); for index in silent_workers { let result = Self::remove_enclave(&index); match result { Ok(_) => { log::info!("Unregister enclave because silent worker : {:?}", index); Self::deposit_event(Event::RemovedEnclave(index.clone())); }, Err(e) => { log::error!("Cannot unregister enclave : {:?}", e); }, }; } } /// Check if the sender is a registered enclave pub fn ensure_registered_enclave( account: &T::AccountId, ) -> Result<(), DispatchErrorWithPostInfo> { ensure!(<EnclaveIndex<T>>::contains_key(account), <Error<T>>::EnclaveIsNotRegistered); Ok(()) } /// Deposit a pallets teerex event with the corresponding topics. /// /// Handles the conversion to the overarching event type. fn deposit_event_indexed(topics: &[T::Hash], event: Event<T>) { <frame_system::Pallet<T>>::deposit_event_indexed( topics, <T as Config>::RuntimeEvent::from(event).into(), ) } #[cfg(not(feature = "skip-ias-check"))] fn verify_report( sender: &T::AccountId, ra_report: Vec<u8>, ) -> Result<SgxReport, DispatchErrorWithPostInfo> { let report = verify_ias_report(&ra_report) .map_err(|_| <Error<T>>::RemoteAttestationVerificationFailed)?; log::info!("teerex: IAS report successfully verified"); let enclave_signer = T::AccountId::decode(&mut &report.pubkey[..]) .map_err(|_| <Error<T>>::EnclaveSignerDecodeError)?; ensure!(sender == &enclave_signer, <Error<T>>::SenderIsNotAttestedEnclave); // TODO: activate state checks as soon as we've fixed our setup #83 // ensure!((report.status == SgxStatus::Ok) | (report.status == // SgxStatus::ConfigurationNeeded), "RA status is insufficient"); // log::info!("teerex: status is acceptable"); Self::ensure_timestamp_within_24_hours(report.timestamp)?; Ok(report) } #[cfg(not(feature = "skip-ias-check"))] fn verify_dcap_quote( sender: &T::AccountId, dcap_quote: Vec<u8>, ) -> Result<SgxReport, DispatchErrorWithPostInfo> { let verification_time = <timestamp::Pallet<T>>::get(); let qe = <QuotingEnclaveRegistry<T>>::get(); let (fmspc, tcb_info, report) = verify_dcap_quote(&dcap_quote, verification_time.saturated_into(), &qe).map_err( |e| { log::warn!("verify_dcap_quote failed: {:?}", e); <Error<T>>::RemoteAttestationVerificationFailed }, )?; log::info!("teerex: DCAP quote verified. FMSPC from quote: {:?}", fmspc); let tcb_info_on_chain = <TcbInfo<T>>::get(fmspc); ensure!(tcb_info_on_chain.verify_examinee(&tcb_info), "tcb_info is outdated"); let enclave_signer = T::AccountId::decode(&mut &report.pubkey[..]) .map_err(|_| <Error<T>>::EnclaveSignerDecodeError)?; ensure!(sender == &enclave_signer, <Error<T>>::SenderIsNotAttestedEnclave); // TODO: activate state checks as soon as we've fixed our setup #83 // ensure!((report.status == SgxStatus::Ok) | (report.status == // SgxStatus::ConfigurationNeeded), "RA status is insufficient"); // log::info!("teerex: status is acceptable"); Ok(report) } fn verify_quoting_enclave( enclave_identity: Vec<u8>, signature: Vec<u8>, certificate_chain: Vec<u8>, ) -> Result<QuotingEnclave, DispatchErrorWithPostInfo> { let verification_time: u64 = <timestamp::Pallet<T>>::get().saturated_into(); let certs = extract_certs(&certificate_chain); ensure!(certs.len() >= 2, "Certificate chain must have at least two certificates"); let intermediate_slices: Vec<&[u8]> = certs[1..].iter().map(Vec::as_slice).collect(); let leaf_cert = verify_certificate_chain(&certs[0], &intermediate_slices, verification_time)?; let enclave_identity = deserialize_enclave_identity(&enclave_identity, &signature, &leaf_cert)?; if enclave_identity.is_valid(verification_time.try_into().unwrap()) { Ok(enclave_identity.to_quoting_enclave()) } else { Err(<Error<T>>::CollateralInvalid.into()) } } pub fn verify_tcb_info( tcb_info: Vec<u8>, signature: Vec<u8>, certificate_chain: Vec<u8>, ) -> Result<(Fmspc, TcbInfoOnChain), DispatchErrorWithPostInfo> { let verification_time: u64 = <timestamp::Pallet<T>>::get().saturated_into(); let certs = extract_certs(&certificate_chain); ensure!(certs.len() >= 2, "Certificate chain must have at least two certificates"); let intermediate_slices: Vec<&[u8]> = certs[1..].iter().map(Vec::as_slice).collect(); let leaf_cert = verify_certificate_chain(&certs[0], &intermediate_slices, verification_time)?; let tcb_info = deserialize_tcb_info(&tcb_info, &signature, &leaf_cert)?; if tcb_info.is_valid(verification_time.try_into().unwrap()) { Ok(tcb_info.to_chain_tcb_info()) } else { Err(<Error<T>>::CollateralInvalid.into()) } } #[cfg(not(feature = "skip-ias-check"))] fn ensure_timestamp_within_24_hours(report_timestamp: u64) -> DispatchResultWithPostInfo { let elapsed_time = <timestamp::Pallet<T>>::get() .checked_sub(&T::Moment::saturated_from(report_timestamp)) .ok_or("Underflow while calculating elapsed time since report creation")?; if elapsed_time < T::MomentsPerDay::get() { Ok(().into()) } else { Err(<Error<T>>::RemoteAttestationTooOld.into()) } } } impl<T: Config> OnTimestampSet<T::Moment> for Pallet<T> { fn on_timestamp_set(moment: T::Moment) { Self::unregister_silent_workers(moment) } } mod benchmarking; #[cfg(test)] mod mock; #[cfg(test)] mod tests; pub mod weights;
import React, { useState } from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faPaperPlane } from '@fortawesome/free-regular-svg-icons'; import styled from 'styled-components'; const Chat = styled.div` background-color: ${props => props.theme.colors.white}; box-shadow: 0 5px 20px rgba(0,0,0,.08); border-radius: ${props => props.theme.borderRadius[2]}; position: relative; width: 420px; ` const ChatHeader = styled.header` border-top-left-radius: ${props => props.theme.borderRadius[2]}; border-top-right-radius: ${props => props.theme.borderRadius[2]}; padding: ${props => props.theme.space[5]}; background-color: ${props => props.theme.colors.lightBluePrimary}; color: ${props => props.theme.colors.white}; font-size: ${props => props.theme.fontSizes.mediumLarge}; font-weight: bold; line-height: 1; `; const ChatBody = styled.div` border-bottom-left-radius: ${props => props.theme.borderRadius[2]}; border-bottom-right-radius: ${props => props.theme.borderRadius[2]}; padding: ${props => props.theme.space[5]} ${props => props.theme.space[5]} ${props => props.theme.space[10]}; `; const ChatOutputWrap = styled.div` height: 480px; overflow-y: auto; font-size: ${props => props.theme.fontSizes.medium}; color: ${props => props.theme.colors.blackPrimary}; `; const ChatOutput = styled.div` max-height: 480px; `; const ChatInputWrap = styled.div` position: absolute; bottom: 20px; display: flex; justify-content: space-between; width: calc(100% - 40px); background-color: ${props => props.theme.colors.white}; padding-top: ${props => props.theme.space[5]}; `; const ChatInput = styled.input` -webkit-appearance: none; -moz-appearance: none; appearance: none; background: transparent; border: none; border-radius: 0; font: inherit; outline: none; width: calc(100% - 52px); border-radius: ${props => props.theme.borderRadius[1]}; word-break: break-word; padding: ${props => props.theme.space[2]}; border: solid 1px ${props => props.theme.colors.lightGray}; `; const SendButton = styled.button` border-radius: ${props => props.theme.borderRadius[1]}; background: ${props => props.theme.colors.lightBluePrimary}; display: flex; justify-content: center; align-items: center; color: ${props => props.theme.colors.white}; font-size: ${props => props.theme.fontSizes.medium}; font-weight: bold; cursor: pointer; width: 42px; &:hover { opacity: .7; } ` const SupportChat = () => { const [data, setData] = useState<string>('スキルについて質問してください。'); const [inputText, setInputText] = useState(""); const [loading, setLoading] = useState(false); const headers = new Headers({ 'Content-Type': 'application/json', 'Custom-Header': 'ValidValue' }); async function fetchDataFromGeminiProAPI() { try { if (!inputText) { alert("Please enter text!"); return; } setLoading(true); const response = await fetch('/api/chat', { method: 'POST', headers: headers, body: JSON.stringify(inputText), }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const responseData = await response.json(); console.log(responseData); setLoading(false); setData(responseData); } catch (error) { setLoading(false); console.error("fetchDataFromGeminiAPI error: ", error); } } return ( <Chat> <ChatHeader> <p>AIスキルナビゲーター</p> </ChatHeader> <ChatBody> <ChatOutputWrap> <ChatOutput>{data}</ChatOutput> </ChatOutputWrap> <ChatInputWrap> <ChatInput type="text" value={inputText} onChange={(e) => setInputText(e.target.value)} /> <SendButton as="button" disabled={loading} onClick={() => fetchDataFromGeminiProAPI()}> {loading ? "..." : <FontAwesomeIcon icon={faPaperPlane} />} </SendButton> </ChatInputWrap> </ChatBody> </Chat> ); }; export default SupportChat;
class User < ApplicationRecord # default: 0 means that the default value of the role attribute is 0, which corresponds to the user role. enum role: [:user, :admin] # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :favorites, dependent: :destroy has_many :favorite_products, through: :favorites has_many :cart_items, dependent: :destroy has_many :orders def star(product) favorites.create(product_id: product.id) end def unstar(product) favorites.find_by(product_id: product.id).destroy end def favorite?(product) favorite_products.include?(product) end end
package com.example.assignment; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.room.Room; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.assignment.Entities.AccountAchievement; import com.example.assignment.Entities.Rewards; import com.google.android.material.bottomnavigation.BottomNavigationView; import java.util.ArrayList; import java.util.List; //this class shows the detailed reward attributes e.g. the user can see the qr voucher code //this is really handy for when the user wants to redeem a voucher at UNSW - they can conveniently find it in one app //when they have used the reward, they mark it as redeemed and the user will not be allowed to view the used QR code anymore public class RewardDetailActivity extends AppCompatActivity { BottomNavigationView bottomNavigation; private int rewardId = 0; private Rewards reward; private String email, id; MyDatabase myDb; private boolean redeemed, achieved; private List<AccountAchievement> mAccAchs = new ArrayList<>(); private ArrayList<Rewards> mRewards = new ArrayList<>(); private static final String TAG = "RewardDetailActivity"; private TextView name, expiry; private Button redeem; private ImageView image; private ImageButton cancel; @Override protected void onCreate(Bundle savedInstanceState) { setTitle("My Rewards"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_reward_detail); name = findViewById(R.id.name); redeem = findViewById(R.id.redeem); image = findViewById(R.id.image); cancel = findViewById(R.id.cancel); expiry = findViewById(R.id.expiry); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Intent intent = getIntent(); id = intent.getStringExtra("id"); System.out.println(id); rewardId = Integer.valueOf(id); System.out.println(rewardId); email = intent.getStringExtra("email"); mRewards = Rewards.getRewards(); for (Rewards r : mRewards) { if (r.getId() == rewardId) { reward = r; } } redeem.setVisibility(View.GONE); new GetAccountAchievements().execute(); //bottom nav bar bottomNavigation = findViewById(R.id.navigation); bottomNavigation.setItemIconTintList(null); bottomNavigation.setItemTextColor(null); bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Intent intent; switch (item.getItemId()) { case R.id.learning: intent = new Intent(getApplicationContext(), SelectDifficulty.class); startActivity(intent); return true; case R.id.quiz: intent = new Intent(getApplicationContext(), QuizActivity.class); startActivity(intent); return true; case R.id.leaderboard: intent = new Intent(getApplicationContext(), LeaderboardActivity.class); startActivity(intent); return true; case R.id.profile: intent = new Intent(getApplicationContext(), ProfileActivity.class); startActivity(intent); return true; } return false; } }); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), RewardActivity.class); startActivity(intent); } }); redeem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new UpdateRedemption().execute(); Toast.makeText(getApplicationContext(), "Your voucher has been redeemed!", Toast.LENGTH_SHORT).show(); redeem.setVisibility(View.GONE); image.setImageResource(R.drawable.redeem_success); expiry.setVisibility(View.GONE); } }); } //gets all the users account achievements to display the rewards appropriately private class GetAccountAchievements extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { myDb = Room.databaseBuilder(getApplicationContext(), MyDatabase.class, "my-db.db") .build(); mAccAchs = myDb.accountAchievementDao().getAccAch(email); redeemed = myDb.accountAchievementDao().getRedeemed(email, rewardId); Log.d(TAG, "doInBackground: redeemed " + redeemed); achieved = myDb.accountAchievementDao().getAchieved(email, rewardId); Log.d(TAG, "doInBackground: achieved " + achieved); Log.d(TAG, "doInBackground: ASYNC TASK "); return null; } @Override protected void onPostExecute(Void v) { super.onPostExecute(v); Log.d(TAG, "onPostExecute: FINISHED"); updateUi(); myDb.close(); } } private void updateUi() { if (achieved == false) { name.setText(reward.getName()); redeem.setVisibility(View.GONE); expiry.setVisibility(View.GONE); image.setImageResource(R.drawable.reward_unavailable); } else if ((achieved == true) && (redeemed == false)) { name.setText(reward.getName()); redeem.setVisibility(View.VISIBLE); expiry.setVisibility(View.VISIBLE); image.setImageResource(reward.getPhoto()); } else if ((achieved == true) && (redeemed == true)) { name.setText(reward.getName()); expiry.setVisibility(View.GONE); redeem.setVisibility(View.GONE); image.setImageResource(R.drawable.reward_redeemed); } } //when user clicks redeem, it will update the attribute redeemed in the database as true so they can no longer see the QR code private class UpdateRedemption extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { myDb = Room.databaseBuilder(getApplicationContext(), MyDatabase.class, "my-db.db") .build(); myDb.accountAchievementDao().updateRedeemed(true, email, rewardId); Log.d(TAG, "doInBackground: ASYNC TASK "); return null; } @Override protected void onPostExecute(Void v) { super.onPostExecute(v); Log.d(TAG, "onPostExecute: FINISHED"); myDb.close(); } } //added back button in the toolbar public boolean onOptionsItemSelected(MenuItem item) { Intent myIntent = new Intent(getApplicationContext(), RewardActivity.class); startActivityForResult(myIntent, 0); return true; } }
import { useSelector } from "react-redux"; import { useState } from "react"; import { RootState } from "../../store/store"; import Logo from "./Logo"; import BurgerMenu from "./BurgerMenu"; import DesktopNav from "./Navigation/DesktopNav"; import MobileNav from "./Navigation/MobileNav"; import UserProfileButton from "./UserProfileButton"; import CartButton from "./CartButton"; export default function Header() { const isMobile = useSelector((state: RootState) => state.deviceType.isMobile); const [mobileNavIsActive, setMobileNavIsActive] = useState(false); const showMobileNavHandler = () => { setMobileNavIsActive(prev => !prev); }; const hideMobileNavHandler = () => { setMobileNavIsActive(false); }; const headerClasses = "fixed top-0 left-0 right-0 mx-auto flex justify-between w-full p-4 lg:px-12 lg:py-4 max-w-7xl z-50 items-center border-b-4 z-50 bg-white"; return ( <> <div className='h-24 lg:h-28'></div> <header className={headerClasses}> <div className='flex justify-center items-center gap-4'> <BurgerMenu onClick={showMobileNavHandler} mobileNavIsActive={mobileNavIsActive} /> {isMobile && ( <MobileNav mobileNavIsActive={mobileNavIsActive} hideNav={hideMobileNavHandler} /> )} <Logo /> {!isMobile && <DesktopNav />} </div> <div className='flex justify-center items-center gap-4'> <CartButton /> <UserProfileButton /> </div> </header> </> ); }
// // ViewModifiers.swift // AdwumaX // // Created by Denis on 4/4/24. // import SwiftUI struct ButtonViewModifiers: View { var body: some View { Text("button1").button1() Text("button2").button2() Text("button3").button3() Text("button4").button4() Text("button5").button5() Text("buttonDisable1").button1().buttonDisable() Text("buttonDisable2").button2().buttonDisable() Text("buttonDisable3").button3().buttonDisable() Text("buttonDisable4").button4().buttonDisable() Text("buttonDisable5").button5().buttonDisable() } } var radius: CGFloat = 30 var maxHeight: CGFloat = 10 var lineThickness: CGFloat = 0.75 struct Button1: ViewModifier { @Environment(\.colorScheme) var colorScheme func body(content: Content) -> some View { content .foregroundColor(colorScheme == .dark ? .black : .white) .frame(minWidth: 140, maxHeight: maxHeight) .padding() .bold() .background(RoundedRectangle(cornerRadius: radius).fill(colorScheme == .dark ? .white : .black)) } } struct Button2: ViewModifier { @Environment(\.colorScheme) var colorScheme func body(content: Content) -> some View { content .foregroundColor(colorScheme == .dark ? .white : .black) .frame(maxWidth: .infinity, maxHeight: maxHeight) .padding() .bold() .background(RoundedRectangle(cornerRadius: radius) .fill(colorScheme == .dark ? .black : .white) .overlay( RoundedRectangle(cornerRadius: radius) .stroke(colorScheme == .dark ? .white : .black, lineWidth: lineThickness) ) ) } } struct Button3: ViewModifier { @Environment(\.colorScheme) var colorScheme func body(content: Content) -> some View { content .foregroundColor(colorScheme == .dark ? .black : .white) .frame(maxWidth: .infinity, maxHeight: maxHeight) .padding() .bold() .background(RoundedRectangle(cornerRadius: radius) .fill(Color.primary1)) } } struct Button4: ViewModifier { @Environment(\.colorScheme) var colorScheme func body(content: Content) -> some View { content .foregroundColor(Color.primary1) .frame(maxWidth: .infinity, maxHeight: maxHeight) .padding() .bold() .background(RoundedRectangle(cornerRadius: radius) .fill(colorScheme == .dark ? .black : .white) .overlay( RoundedRectangle(cornerRadius: radius) .stroke(Color.primary1, lineWidth: lineThickness) ) ) } } struct Button5: ViewModifier { @Environment(\.colorScheme) var colorScheme func body(content: Content) -> some View { content .foregroundColor(colorScheme == .dark ? .black : .white) .frame(maxWidth: .infinity, maxHeight: maxHeight) .padding() .bold() .background(RoundedRectangle(cornerRadius: 10).fill(Color.primary1)) // .foregroundColor(.white) // .frame(maxWidth: .infinity) // .padding() // .bold() // .background(RoundedRectangle(cornerRadius: 10).fill(Color.primary1)) } } struct ButtonDisable: ViewModifier { let status: Bool func body(content: Content) -> some View { if status { content .disabled(true) .opacity(0.4) } else { content .disabled(false) .opacity(1) } } } struct ButtonEnable: ViewModifier { func body(content: Content) -> some View { content .disabled(false) .opacity(1) } } extension View { public func button1() -> some View { modifier(Button1()) } public func button2() -> some View { modifier(Button2()) } public func button3() -> some View { modifier(Button3()) } public func button4() -> some View { modifier(Button4()) } public func button5() -> some View { modifier(Button5()) } public func buttonDisable(status: Bool = true) -> some View { self.modifier(status ? ButtonDisable(status: true) : ButtonDisable(status: false)) } public func buttonEnable() -> some View { modifier(ButtonEnable()) } } #Preview { ButtonViewModifiers() }
using Moq; using NUnit.Framework; using System.Linq; using TestNinja.Mocking; namespace TestNinja.UnitTest.Mocking { [TestFixture] public class VideoServiceTests { private Mock<IFileReader> fileReader; private Mock<IVideoRepository> videoRepository; private VideoService videoService; [SetUp] public void SetUp() { this.fileReader = new Mock<IFileReader>(); this.videoRepository = new Mock<IVideoRepository>(); this.videoService = new VideoService( this.fileReader.Object, this.videoRepository.Object); } [Test] public void ReadVideoTitle_EmptyFile_ReturnError() { fileReader.Setup(x => x.Read("video.txt")).Returns(string.Empty); var result = videoService.ReadVideoTitle(); Assert.That(result, Does.Contain("error").IgnoreCase); } [Test] public void GetUnprocessedVideosAsCsv_AllProcessedVideos_ReturnEmptyString() { videoRepository.Setup(x => x.GetUnprocessedVideos()) .Returns(Enumerable.Empty<Video>()); var result = videoService.GetUnprocessedVideosAsCsv(); Assert.That(result, Is.EqualTo(string.Empty)); } [Test] public void GetUnprocessedVideosAsCsv_AFewUnprocessedVideos_ReturnUnprocessedVideoIdsAsCsv() { videoRepository.Setup(x => x.GetUnprocessedVideos()) .Returns(new Video[] { new Video { Id = 1 }, new Video { Id = 2 }, }); var result = videoService.GetUnprocessedVideosAsCsv(); Assert.That(result, Is.EqualTo("1,2")); } } }
Catalan numbers satisfy the following recursive formula Co = 1 and C(n+1) = Sigmai=0 to n C(i) C(n-i) for n >= 0; def catalan(n): if n <= 1: return 1 res = 0 for i in range(n): res += catalan(i) * catalan(n-i-1) return res for i in range(10): print catalan(i) ##### Now a DP based function to find nth catalan number def catalan(n): if(n==0 or n==1): return 1 # Table to store the results of subproblems catalan = [0 for i in range(n+1)] catalan[0] = 1 catalan[1] = 1 # Fill entries in catalan[] using recursive formula for i in range(2,n+1): catalan[i] = 0 for j in range(i): catalan[i] = catalan[i] + catalan[j] * catalan[i-j-1] return catalan[n] # return lastentry for i in range(11): print(catalanDP(i))
import React, { Component } from 'react'; import Navigation from './components/Navigation/Navigation'; import Logo from './components/Logo/Logo'; import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm'; import Rank from './components/Rank/Rank'; import FaceRecognition from './components/FaceRecognition/FaceRecognition'; import SignIn from './components/SignIn/SignIn'; import Register from './components/Register/Register'; import Particles from "react-tsparticles"; import { loadFull } from "tsparticles"; import './App.css'; const particlesInit = async (main) => { console.log(main); // you can initialize the tsParticles instance (main) here, adding custom shapes or presets // this loads the tsparticles package bundle, it's the easiest method for getting everything ready // starting from v2 you can add only the features you need reducing the bundle size await loadFull(main); }; const particlesLoaded = (container) => { console.log(container); }; const initialState = { input: '', imageURL: '', box: {}, route: 'signin', isSignedIn: false, user: { id: '', name: '', email: '', entries: 0, joined: '' } } class App extends Component { constructor() { super(); this.state = { input: '', imageURL: '', box: {}, route: 'signin', isSignedIn: false, user: { id: '', name: '', email: '', entries: 0, joined: '' } } } loadUser = (data) => { this.setState({user: { id: data.id, name: data.name, email: data.email, entries: data.entries, joined: data.joined }}); } calculateFaceLocation = (data) => { const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box; const image = document.getElementById('inputImage'); const width = Number(image.width); const height = Number(image.height); return { leftCol: clarifaiFace.left_col * width, topRow: clarifaiFace.top_row * height, rightCol: width - (clarifaiFace.right_col * width), bottomRow: height - (clarifaiFace.bottom_row * height) } } displayFaceBox = (box) => { console.log(box); this.setState({ box: box}); } onInputChange = (event) => { this.setState({input: event.target.value}); } onSubmit = () => { this.setState({ imageURL: this.state.input}); fetch('https://thawing-citadel-11090.herokuapp.com/imageurl', { method: 'post', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ input: this.state.input }) }) .then(response => response.json()) .then(response => { fetch('https://thawing-citadel-11090.herokuapp.com/image', { method: 'put', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ id: this.state.user.id }) }) .then(response => response.json()) .then(count => { this.setState(Object.assign(this.state.user, {entries:count})); }) this.displayFaceBox(this.calculateFaceLocation(response))}) .catch(err => console.log(err)); } onRouteChange = (route) => { if (route === 'signin') { this.setState(initialState); } else if(route === 'home') { this.setState({isSignedIn: true}); } this.setState({route: route}); } render() { return ( <div className="App"> <Particles className='particles' id="tsparticles" init={particlesInit} loaded={particlesLoaded} options={{ fpsLimit: 120, interactivity: { events: { // onClick: { // enable: true, // mode: "push", // }, onHover: { enable: true, mode: "repulse", }, resize: true, }, modes: { push: { quantity: 4, }, repulse: { distance: 200, duration: 0.4, }, }, }, particles: { color: { value: "#ffffff", }, links: { color: "#ffffff", distance: 150, enable: true, opacity: 0.5, width: 1, }, collisions: { enable: true, }, move: { direction: "none", enable: true, outModes: { default: "bounce", }, random: false, speed: 2, straight: false, }, number: { density: { enable: true, area: 800, }, value: 100, }, opacity: { value: 0.5, }, shape: { type: "circle", }, size: { value: { min: 1, max: 5 }, }, }, detectRetina: true, }} /> <Navigation isSignedIn={this.state.isSignedIn} onRouteChange={this.onRouteChange} /> {this.state.route === 'home' ? <div> <Logo /> <Rank name={this.state.user.name} entries={this.state.user.entries}/> <ImageLinkForm onInputChange={ this.onInputChange} onButtonSubmit={ this.onSubmit } /> <FaceRecognition box={this.state.box} imageURL={this.state.imageURL} /> </div> : ( this.state.route === 'signin' ? <SignIn loadUser={this.loadUser} onRouteChange={this.onRouteChange}/> : <Register loadUser={this.loadUser} onRouteChange={this.onRouteChange} /> ) } </div> ); } } export default App;
package io.udemyapirestjava.adapters.in.controllers; import io.udemyapirestjava.application.ports.in.DividirInputPort; import io.udemyapirestjava.application.ports.in.MultiplicarInputPort; import io.udemyapirestjava.application.ports.in.SubtrairInputPort; import io.udemyapirestjava.application.ports.in.SomarInputPort; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class MathController { @Autowired private SomarInputPort somarInputPort; @Autowired private SubtrairInputPort subtrairInputPort; @Autowired private MultiplicarInputPort multiplicarInputPort; @Autowired private DividirInputPort dividirInputPort; @RequestMapping(path = "/sum/{numberOne}/{numberTwo}", method = RequestMethod.GET) public Double sum(@PathVariable(name = "numberOne") String numberOne, @PathVariable(name = "numberTwo") String numberTwo) { return this.somarInputPort.calcular(numberOne, numberTwo); } @RequestMapping(path = "/subtraction/{numberOne}/{numberTwo}", method = RequestMethod.GET) public Double subtraction(@PathVariable(name = "numberOne") String numberOne, @PathVariable(name = "numberTwo") String numberTwo) { return this.subtrairInputPort.calcular(numberOne, numberTwo); } @RequestMapping(path = "/multiplication/{numberOne}/{numberTwo}", method = RequestMethod.GET) public Double multiplication(@PathVariable(name = "numberOne") String numberOne, @PathVariable(name = "numberTwo") String numberTwo) { return this.multiplicarInputPort.calcular(numberOne, numberTwo); } @RequestMapping(path = "/division/{numberOne}/{numberTwo}", method = RequestMethod.GET) public Double division(@PathVariable(name = "numberOne") String numberOne, @PathVariable(name = "numberTwo") String numberTwo) { return this.dividirInputPort.calcular(numberOne, numberTwo); } }
------------------------------------------ -- ** Denotational & operational semantics open import Prelude.Init; open SetAsType open import Prelude.General open import Prelude.DecEq open import Prelude.Decidable open import Prelude.Ord open import Prelude.Semigroup open import Prelude.Monoid open import Prelude.Functor open import Prelude.InferenceRules open import Prelude.Apartness open import Prelude.Monad module ValueSepInt.Ledger (Part : Type) -- a fixed set of participants ⦃ _ : DecEq Part ⦄ where open import ValueSepInt.Maps V = ℤ instance Sℤ = Semigroup-ℤ-+ Sℤ⁺ = SemigroupLaws-ℤ-+ Mℤ = Monoid-ℤ-+ Mℤ⁺ = MonoidLaws-ℤ-+ variable A B C D : Part v v′ v″ : V -- The state of a ledger is a collection of participants, along with their balance. S : Type S = Map⟨ Part ↦ V ⟩ -- A transaction is transferring money from one participant to another. record Tx : Type where constructor _—→⟨_⟩_ field sender : Part value : V receiver : Part open Tx public unquoteDecl DecEq-Tx = DERIVE DecEq [ quote Tx , DecEq-Tx ] -- A ledger is a list of transactions. L = List Tx variable s s′ s″ s₁ s₁′ s₁″ s₂ s₂′ s₂″ s₃ s₃′ s₃″ s₂₃ s₂₃′ s₂₃″ : S t t′ t″ : Tx l l′ l″ l₁ l₂ : L ls ls′ ls″ : L × S ms ms′ ms″ : Maybe S mls mls′ mls″ : Maybe (L × S) -- ** Denotational semantics -- The meaning of a transaction or a whole ledger will be denoted by state transformers, -- i.e. a function from the current state to the updated one. Domain = S → S record Denotable (A : Type) : Type where field ⟦_⟧ : A → Domain open Denotable ⦃...⦄ public -- Express the action of tranferring values between keys in a map. -- NB: a transaction goes through only when: -- 1. both participants are present in the domain -- 2. the sender holds sufficient funds instance -- we denote a transaction as the map transformation that implements the transfer ⟦Tx⟧ : Denotable Tx ⟦Tx⟧ .⟦_⟧ (A —→⟨ v ⟩ B) s = s [ A ↝ (Integer._- v) ] [ B ↝ (Integer._+ v) ] -- we denote a ledger as the composition of the denotations of its transactions, -- i.e. we run all transactions in sequence ⟦L⟧ : Denotable L ⟦L⟧ .⟦_⟧ [] = id ⟦L⟧ .⟦_⟧ (t ∷ l) = ⟦ l ⟧ ∘ ⟦ t ⟧ comp : ∀ x → ⟦ l ++ l′ ⟧ x ≡ (⟦ l′ ⟧ ∘ ⟦ l ⟧) x comp {l = []} _ = refl comp {l = t ∷ l} x = comp {l} (⟦ t ⟧ x) -- Executing transactions never introduces new keys in the resulting map out-of-thin-air. -- ** Operational semantics -- We model configurations of the transition system as pairs of a ledger and its current state. infix 0 _—→_ data _—→_ : L × S → S → Type where base : ──────────── ε , s —→ s step : let t = A —→⟨ v ⟩ B in ∙ l , ⟦ t ⟧ s —→ s′ ───────────────── t ∷ l , s —→ s′ oper-comp : ∙ l , s —→ s′ ∙ l′ , s′ —→ s″ ────────────────── l ++ l′ , s —→ s″ oper-comp {l = []} base s′→s″ = s′→s″ oper-comp {l = _ ∷ _} (step s→s′) s′→s″ = step (oper-comp s→s′ s′→s″) -- ** Relating denotational and operational semantics. denot⇒oper : ⟦ l ⟧ s ≡ s′ ──────────── l , s —→ s′ denot⇒oper {l = []} refl = base denot⇒oper {l = A —→⟨ v ⟩ B ∷ l}{s} l≡ = step (denot⇒oper l≡) oper⇒denot : l , s —→ s′ ──────────── ⟦ l ⟧ s ≡ s′ oper⇒denot {l = .[]} base = refl oper⇒denot {l = A —→⟨ v ⟩ B ∷ _}{s} (step p) = oper⇒denot p denot⇔oper : ⟦ l ⟧ s ≡ s′ ════════════ l , s —→ s′ denot⇔oper = denot⇒oper , oper⇒denot
<!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>悬浮球</title> <style> body { /* 背景渐变 */ background-image: linear-gradient(to bottom right, #91defe, #99c0f9, #bdb6ec, #d7b3e3, #efb3d5, #f9bccc); display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; overflow: hidden; } .box { position: absolute; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 500px; left: 50%; top: 50%; transform: translate(-50%, -50%); } .ball { animation: float 3.5s ease-in-out infinite; height: 200px; width: 200px; border-radius: 50%; position: relative; /* 为球的背景添加径向渐变,渐变中心在 77% 水平、30% 垂直位置 */ background: radial-gradient(circle at 77% 30%, /* 渐变起点颜色为白色,半径为 5 像素 */ white 5px, /* 渐变颜色从白色平滑过渡到淡蓝色,半径为 8% */ aqua 8%, /* 渐变颜色从淡蓝色平滑过渡到深蓝色,半径为 60% */ darkblue 60%, /* 渐变颜色从深蓝色平滑过渡到淡蓝色,半径为 100% */ aqua 100%); /* 为球添加多重内阴影效果 */ /* 内部白色阴影,宽度 20 像素 */ box-shadow: inset 0 0 20px #fff, /* 内部淡蓝色阴影,位置偏右 10 像素,宽度 46 像素 */ inset 10px 0 46px #eaf5fc, /* 内部浅蓝色阴影,位置偏右 88 像素,宽度 60 像素 */ inset 88px 0px 60px #c2d8fe, /* 内部淡橙色阴影,位置偏左上方,宽度 100 像素 */ inset -20px -60px 100px #fde9ea, /* 内部淡橙色阴影,位置偏下方,宽度 140 像素 */ inset 0 50px 140px #fde9ea, /* 外部白色阴影,宽度 90 像素 */ 0 0 90px #fff; } .box:nth-child(2) { z-index: -999; } .box:nth-child(2) .ball { left: -80px; top: 35px; width: 100px; height: 100px; z-index: -999; opacity: .5; } .box:nth-child(3) .ball { left: 80px; top: -80px; width: 20px; height: 20px; opacity: .1; } .shadow { background: #b490b27c; width: 150px; height: 40px; top: 70%; animation: expand 4s infinite; position: absolute; border-radius: 50%; } .box:nth-child(2) .shadow { width: 90px; height: 20px; top: 72.5%; left: -75px; opacity: .4; } /* 添加漂浮动画 */ @keyframes float { 0% { transform: translatey(0px) rotate(-10deg); } 50% { transform: translatey(-80px) rotate(10deg); } 100% { transform: translatey(0px) rotate(-10deg); } } @keyframes expand { 0%, 100% { transform: scale(0.5); } 50% { transform: scale(1); } } .dropbtn { background-color: #333; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover {background-color: #f1f1f1} .dropdown:hover .dropdown-content { display: block; } .dropdown:hover .dropbtn { background-color: #111; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } li { float: left; } li a, .dropbtn { display: inline-block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover, .dropdown:hover .dropbtn { background-color: rgb(149, 23, 207); } li.dropdown { display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: left; } .dropdown-content a:hover {background-color: #f1f1f1;} .dropdown:hover .dropdown-content { display: block; } </style> </head> <body> <ul> <li><a href="http:///huiyi0923.github.io/indexth2.html">首页</a></li> <li><a href="https://huiyi0923.github.io/">旧网址</a></li> <li><a href="http://huiyi0923.github.io/indexth.html">悬浮球</a></li> <li class="dropdown"> <a href="javascript:void(0)" class="dropbtn">微清活动</a> <div class="dropdown-content"> <a href="http://huiyi0923.github.io/indexth3.html">关于我们</a> <a href="https://huiyi0923.github.io/indexth2.html">广告招租(向下滑)</a> <a href="https://huiyi0923.github.io/indexth5.html">微清悬赏令</a> <a href="https://huiyi0923.github.io/appxiazai.html">APP下载</a> </div> </li> </ul> <audio id="bgm" src="那一瞬间.m4a" autoplay preload loop="loop"></audio> <div class="shell"> <div class="box"> <div class="ball"></div> <div class="shadow"></div> </div> <div class="box"> <div class="ball"></div> <div class="shadow"></div> </div> <div class="box"> <div class="ball"></div> </div> </div> </body> </html>
import cv2 import numpy as np from tracker import tracker # Define a function that takes an image, gradient orientation, # and threshold min / max values. def abs_sobel_thresh(img, orient='x', thresh_min=25, thresh_max=255): # Convert to grayscale # gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(float) l_channel = hls[:, :, 1] s_channel = hls[:, :, 2] # Apply x or y gradient with the OpenCV Sobel() function # and take the absolute value if orient == 'x': abs_sobel = np.absolute(cv2.Sobel(l_channel, cv2.CV_64F, 1, 0)) if orient == 'y': abs_sobel = np.absolute(cv2.Sobel(l_channel, cv2.CV_64F, 0, 1)) # Rescale back to 8 bit integer scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel)) # Create a copy and apply the threshold binary_output = np.zeros_like(scaled_sobel) # Here I'm using inclusive (>=, <=) thresholds, but exclusive is ok too binary_output[(scaled_sobel >= thresh_min) & (scaled_sobel <= thresh_max)] = 1 # Return the result return binary_output # Define a function to return the magnitude of the gradient for a given sobel kernel size and threshold values def mag_thresh(img, sobel_kernel=3, mag_thresh=(0, 255)): # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Take both Sobel x and y gradients sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) # Calculate the gradient magnitude gradmag = np.sqrt(sobelx**2 + sobely**2) # Rescale to 8 bit scale_factor = np.max(gradmag)/255 gradmag = (gradmag/scale_factor).astype(np.uint8) # Create a binary image of ones where threshold is met, zeros otherwise binary_output = np.zeros_like(gradmag) binary_output[(gradmag >= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 1 # Return the binary image return binary_output # Define a function to threshold an image for a given range and Sobel kernel def dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)): # Grayscale gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Calculate the x and y gradients sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) # Take the absolute value of the gradient direction, # apply a threshold, and create a binary image result absgraddir = np.arctan2(np.absolute(sobely), np.absolute(sobelx)) binary_output = np.zeros_like(absgraddir) binary_output[(absgraddir >= thresh[0]) & (absgraddir <= thresh[1])] = 1 # Return the binary image return binary_output def color_threshold(image, sthresh=(0, 255), vthresh=(0, 255)): hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS) s_channel = hls[:, :, 2] s_binary = np.zeros_like(s_channel) s_binary[(s_channel > sthresh[0]) & (s_channel <= sthresh[1])] = 1 hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) v_channel = hsv[:, :, 2] v_binary = np.zeros_like(v_channel) v_binary[(v_channel > vthresh[0]) & (v_channel <= vthresh[1])] = 1 output = np.zeros_like(s_channel) output[(s_binary == 1) & (v_binary) == 1] = 1 # Return the combined s_channel & v_channel binary image return output def s_channel_threshold(image, sthresh=(0, 255)): hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS) s_channel = hls[:, :, 2] # use S channel # create a copy and apply the threshold binary_output = np.zeros_like(s_channel) binary_output[(s_channel >= sthresh[0]) & (s_channel <= sthresh[1])] = 1 return binary_output def window_mask(width, height, img_ref, center, level): output = np.zeros_like(img_ref) output[int(img_ref.shape[0]-(level+1)*height):int(img_ref.shape[0]-level*height), max(0, int(center-width)):min(int(center+width), img_ref.shape[1])] = 1 return output # Process videos to display the fitted lane lines, radius of curvature, and position of the car from the center # Set up the process videos function def process_videos(img): warptrap = np.copy(img) src = np.float32([(532, 496), (756, 496), (288, 664), (1016, 664)]) cv2.line(warptrap, (int(src[0][0]), int(src[0][1])), (int( src[1][0]), int(src[1][1])), [255, 0, 0], 10, cv2.LINE_AA) cv2.line(warptrap, (int(src[1][0]), int(src[1][1])), (int( src[2][0]), int(src[2][1])), [255, 0, 0], 10, cv2.LINE_AA) cv2.line(warptrap, (int(src[2][0]), int(src[2][1])), (int( src[3][0]), int(src[3][1])), [255, 0, 0], 10, cv2.LINE_AA) cv2.line(warptrap, (int(src[3][0]), int(src[3][1])), (int( src[0][0]), int(src[0][1])), [255, 0, 0], 10, cv2.LINE_AA) # pass image thru the pipeline # preprocessImage = np.zeros_like(img[:,:,0]) # gradx = abs_sobel_thresh(img, orient='x',thresh_min=20, thresh_max=100) # s_binary = s_channel_threshold(img, sthresh=(170,255)) # preprocessImage[((gradx == 1) | (s_binary == 1))] = 1 preprocessImage = np.zeros_like(img[:, :, 0]) gradx = abs_sobel_thresh(img, orient='x', thresh_min=12, thresh_max=255) grady = abs_sobel_thresh(img, orient='y', thresh_min=25, thresh_max=255) c_binary = color_threshold(img, sthresh=(100, 255), vthresh=(50, 255)) preprocessImage[((gradx == 1) & (grady == 1) | (c_binary == 1))] = 255 binaryImage = np.copy(preprocessImage) binaryImage = np.array( cv2.merge((binaryImage, binaryImage, binaryImage)), np.uint8) cv2.putText(binaryImage, 'Binary Image', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) img_size = (img.shape[1], img.shape[0]) bot_width = .76 # percentage of bottom trapezoidal height mid_width = .08 # percentage of mid trapezoidal height height_pct = .62 # percentage of trapezoidal height bottom_trim = .935 # percentage from top to bottom avoiding the hood of the car src = np.float32([[img.shape[1]*(0.5-mid_width/2), img.shape[0]*height_pct], [img.shape[1]*(0.5+mid_width/2), img.shape[0]*height_pct], [img.shape[1]*(0.5+bot_width/2), img.shape[0]*bottom_trim], [img.shape[1]*(0.5-bot_width/2), img.shape[0]*bottom_trim]]) offset = img_size[0]*0.25 dst = np.float32([[offset, 0], [img_size[0]-offset, 0], [img_size[0]-offset, img_size[1]], [offset, img_size[1]]]) # perform the warp perspective transform M = cv2.getPerspectiveTransform(src, dst) Minv = cv2.getPerspectiveTransform(dst, src) warped = cv2.warpPerspective( preprocessImage, M, img_size, flags=cv2.INTER_LINEAR) window_width = 25 window_height = 80 # set up the overall class to do the lane line tracking curve_centers = tracker(Mywindow_width=window_width, Mywindow_height=window_height, Mymargin=25, My_ym=10/720, My_xm=4/384, Mysmooth_factor=15) window_centroids = curve_centers.find_window_centroids(warped) # Points used to draw all the left and right windows l_points = np.zeros_like(warped) r_points = np.zeros_like(warped) # points used to find the right & left lanes rightx = [] leftx = [] # Go through each level and draw the windows for level in range(0, len(window_centroids)): # Window_mask is a function to draw window areas # Add center value found in frame to the list of lane points per left, right leftx.append(window_centroids[level][0]) rightx.append(window_centroids[level][1]) l_mask = window_mask(window_width, window_height, warped, window_centroids[level][0], level) r_mask = window_mask(window_width, window_height, warped, window_centroids[level][1], level) # Add graphic points from window mask here to total pixels found l_points[(l_points == 255) | ((l_mask == 1))] = 255 r_points[(r_points == 255) | ((r_mask == 1))] = 255 # Draw the results # add both left and right window pixels together template = np.array(r_points+l_points, np.uint8) zero_channel = np.zeros_like(template) # create a zero color channel # make window pixels green template = np.array( cv2.merge((zero_channel, template, zero_channel)), np.uint8) # making the original road pixels 3 color channels warpage = np.array(cv2.merge((warped, warped, warped)), np.uint8) # overlay the original road image with window results result = cv2.addWeighted(warpage, 1, template, 0.5, 0.0) windowfit = np.copy(result) cv2.putText(windowfit, 'Sliding window results', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) warpage1 = np.copy(warpage) cv2.putText(warpage1, 'Bird\'s-eye View', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) cv2.line(warpage1, (int(dst[0][0]), int(dst[0][1])), (int( dst[1][0]), int(dst[1][1])), [0, 0, 255], 10, cv2.LINE_AA) cv2.line(warpage1, (int(dst[1][0]), int(dst[1][1])), (int( dst[2][0]), int(dst[2][1])), [0, 0, 255], 10, cv2.LINE_AA) cv2.line(warpage1, (int(dst[2][0]), int(dst[2][1])), (int( dst[3][0]), int(dst[3][1])), [0, 0, 255], 10, cv2.LINE_AA) cv2.line(warpage1, (int(dst[3][0]), int(dst[3][1])), (int( dst[0][0]), int(dst[0][1])), [0, 0, 255], 10, cv2.LINE_AA) # fit the lane boundaries to the left, right center positions found yvals = range(0, warped.shape[0]) res_yvals = np.arange(warped.shape[0]-(window_height/2), 0, -window_height) left_fit = np.polyfit(res_yvals, leftx, 2) left_fitx = left_fit[0]*yvals*yvals + left_fit[1]*yvals + left_fit[2] left_fitx = np.array(left_fitx, np.int32) right_fit = np.polyfit(res_yvals, rightx, 2) right_fitx = right_fit[0]*yvals*yvals + right_fit[1]*yvals + right_fit[2] right_fitx = np.array(right_fitx, np.int32) left_lane = np.array(list(zip(np.concatenate((left_fitx-window_width/2, left_fitx[::-1]+window_width/2), axis=0), np.concatenate((yvals, yvals[::-1]), axis=0))), np.int32) right_lane = np.array(list(zip(np.concatenate((right_fitx-window_width/2, right_fitx[::-1]+window_width/2), axis=0), np.concatenate((yvals, yvals[::-1]), axis=0))), np.int32) middle_marker = np.array(list(zip(np.concatenate( (right_fitx-window_width/2, right_fitx[::-1]+window_width/2), axis=0), np.concatenate((yvals, yvals[::-1]), axis=0))), np.int32) inner_lane = np.array(list(zip(np.concatenate( (left_fitx+window_width/2, right_fitx[::-1]-window_width/2), axis=0), np.concatenate((yvals, yvals[::-1]), axis=0))), np.int32) road = np.zeros_like(img) road_bkg = np.zeros_like(img) cv2.fillPoly(road, [left_lane], color=[255, 0, 0]) cv2.fillPoly(road, [right_lane], color=[0, 0, 255]) cv2.fillPoly(road, [inner_lane], color=[0, 255, 0]) cv2.fillPoly(road_bkg, [left_lane], color=[255, 255, 255]) cv2.fillPoly(road_bkg, [right_lane], color=[255, 255, 255]) # Results screen portion for polynomial fit road1 = np.copy(road) cv2.putText(road1, 'Polynomial fit', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) road_warped = cv2.warpPerspective( road, Minv, img_size, flags=cv2.INTER_LINEAR) road_warped_bkg = cv2.warpPerspective( road_bkg, Minv, img_size, flags=cv2.INTER_LINEAR) base = cv2.addWeighted(img, 1.0, road_warped, -1.0, 0.0) result = cv2.addWeighted(base, 1.0, road_warped, 1.0, 0.0) ym_per_pix = curve_centers.ym_per_pix # meters per pixel in y dimension xm_per_pix = curve_centers.xm_per_pix # meters per pixel in x dimension curve_fit_cr = np.polyfit(np.array( res_yvals, np.float32)*ym_per_pix, np.array(leftx, np.float32)*xm_per_pix, 2) curverad = ((1 + (2*curve_fit_cr[0]*yvals[-1]*ym_per_pix + curve_fit_cr[1])**2)**1.5) / np.absolute(2*curve_fit_cr[0]) # Calculate the offset of the car on the road camera_center = (left_fitx[-1] + right_fitx[-1])/2 center_diff = (camera_center-warped.shape[1]/2)*xm_per_pix side_pos = 'left' if center_diff <= 0: side_pos = 'right' # draw the text showing curvature, offset & speed cv2.putText(result, 'Radius of Curvature='+str(round(curverad, 3)) + 'm ', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) cv2.putText(result, 'Vehicle is '+str(abs(round(center_diff, 3)))+'m '+side_pos + ' of center', (50, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) height, width = 1080, 1920 FinalScreen = np.zeros((height, width, 3), dtype=np.uint8) FinalScreen[0:720, 0:1280] = cv2.resize( result, (1280, 720), interpolation=cv2.INTER_AREA) FinalScreen[0:360, 1280:1920] = cv2.resize( warptrap, (640, 360), interpolation=cv2.INTER_AREA) FinalScreen[360:720, 1280:1920] = cv2.resize( binaryImage, (640, 360), interpolation=cv2.INTER_AREA) FinalScreen[720:1080, 1280:1920] = cv2.resize( warpage1, (640, 360), interpolation=cv2.INTER_AREA) FinalScreen[720:1080, 0:640] = cv2.resize( windowfit, (640, 360), interpolation=cv2.INTER_AREA) FinalScreen[720:1080, 640:1280] = cv2.resize( road1, (640, 360), interpolation=cv2.INTER_AREA) return FinalScreen, curverad, center_diff
import { eventTrigger, invokeTrigger } from "@trigger.dev/sdk"; import { client } from "@/trigger"; import { OpenAI } from "@trigger.dev/openai"; import { z } from "zod"; import { XMLParser } from "fast-xml-parser"; import { JSDOM } from "jsdom"; export const openai = new OpenAI({ id: "openai", apiKey: process.env.OPENAI_API_KEY!, }); const processSingleUrl = client.defineJob({ id: "process-single-url", name: "Process a single URL", version: "0.0.1", trigger: invokeTrigger({ schema: z.object({ url: z.string().url(), }), }), run: async (payload, io, ctx) => { const { text } = await io.runTask("get-url", async () => { const response = await fetch(payload.url); const text = await response.text(); return { text }; }); const dom = new JSDOM(text); // We remove all the scripts and styles from the page dom.window.document .querySelectorAll("script, style") .forEach((el) => el.remove()); // We grab all the titles from the page const content = Array.from( dom.window.document.querySelectorAll("h1, h2, h3, h4, h5, h6") ); // We grab the last element so we can get the content between the last element and the next element const lastElement = content[content.length - 1]?.parentElement?.nextElementSibling!; const elements = []; // We loop through all the elements and grab the content between each title for (let i = 0; i < content.length; i++) { const element = content[i]; const nextElement = content?.[i + 1] || lastElement; const elementsBetween = getElementsBetween(element, nextElement); elements.push({ title: element.textContent, content: elementsBetween.map((el) => el.textContent).join("\n"), }); } // We create a raw text format of all the content const page = ` ---------------------------------- url: ${payload.url}\n ${elements.map((el) => `${el.title}\n${el.content}`).join("\n")} ---------------------------------- `; return { page }; }, }); client.defineJob({ id: "process-site", name: "Process a site", version: "0.0.1", trigger: eventTrigger({ name: "process.site", schema: z.object({ url: z.string().url(), }), }), integrations: { openai, }, concurrencyLimit: 1, run: async (payload, io, ctx) => { const sitemapUrl = `${payload.url}/sitemap.xml`; const sitemapUrls = await io.runTask("get-sitemap-urls", async () => { const response = await fetch(sitemapUrl); const xml = await response.text(); const parser = new XMLParser(); const parsed = parser.parse(xml); const urls = parsed.urlset.url.map((x: any) => x.loc); return urls as string[]; }); // Chunk the site map urls into groups of 25 const chunks = []; for (let i = 0; i < sitemapUrls.length; i += 25) { chunks.push({ index: i, urls: sitemapUrls.slice(i, i + 25), }); } await io.logger.info(`Processing ${chunks.length} chunks`, { chunks }); const pages = []; for (const chunk of chunks) { const results = await processSingleUrl.batchInvokeAndWaitForCompletion( `invoke-batch-${chunk.index}`, chunk.urls.map((url) => ({ payload: { url } })) ); for (let i = 0; i < results.length; i++) { const result = results[i]; const url = chunk.urls[i]; if (result.ok) { pages.push({ url, page: result.output.page, }); } } } await io.logger.info(`Processed ${pages.length} pages`, { page1: pages[0], }); const fileContents = pages.map((page) => page.page).join("\n\n"); const file = await io.openai.files.createAndWaitForProcessing( "upload-file", { purpose: "assistants", file: fileContents, } ); const assistant = await io.store.env.get<{ id: string }>( "get-assistant", payload.url ); if (!assistant) { // Create a new assistant const { id } = await io.openai.beta.assistants.create( "create-assistant", { name: `assistant for ${payload.url}`, description: "Documentation", instructions: "You are a documentation assistant, you have been loaded with documentation from " + payload.url + ", return everything in an markdown format.", model: "gpt-4-1106-preview", tools: [{ type: "code_interpreter" }, { type: "retrieval" }], file_ids: [file.id], } ); await io.store.env.set("set-assistant", payload.url, { id }); return { id }; } else { await io.openai.beta.assistants.update("update-assistant", assistant.id, { file_ids: [file.id], }); return { id: assistant.id }; } }, }); function getElementsBetween(startElement: Element, endElement: Element) { let currentElement = startElement; const elements = []; // Traverse the DOM until the endElement is reached while (currentElement && currentElement !== endElement) { currentElement = currentElement.nextElementSibling!; // If there's no next sibling, go up a level and continue if (!currentElement) { // @ts-ignore currentElement = startElement.parentNode!; startElement = currentElement; if (currentElement === endElement) break; continue; } // Add the current element to the list if (currentElement && currentElement !== endElement) { elements.push(currentElement); } } return elements; } client.defineJob({ id: "delete-assistant", name: "Delete Assistant", version: "0.0.1", trigger: invokeTrigger({ schema: z.object({ id: z.string(), }), }), integrations: { openai, }, run: async (payload, io, ctx) => { await io.openai.beta.assistants.del("delete", payload.id); }, }); client.defineJob({ id: "question-assistant", name: "Question Assistant", version: "0.0.1", trigger: invokeTrigger({ schema: z.object({ content: z.string(), url: z.string(), threadId: z.string().optional(), }), }), integrations: { openai, }, run: async (payload, io, ctx) => { const assistant = await io.store.env.get<{ id: string }>( "get-assistant", payload.url ); if (!assistant) { throw new Error(`No assistant found for ${payload.url}`); } // Create or use an existing thread const thread = payload.threadId ? await io.openai.beta.threads.retrieve("get-thread", payload.threadId) : await io.openai.beta.threads.create("create-thread"); // Create a message in the threadimpo await io.openai.beta.threads.messages.create("create-message", thread.id, { content: payload.content, role: "user", }); // Run the thread const run = await io.openai.beta.threads.runs.createAndWaitForCompletion( "run-thread", thread.id, { model: "gpt-4-1106-preview", assistant_id: assistant.id, } ); // Check the status of the thread if (run.status !== "completed") { throw new Error( `Run finished with status ${run.status}: ${JSON.stringify( run.last_error )}` ); } // Get the messages from the thread const messages = await io.openai.beta.threads.messages.list( "list-messages", run.thread_id, { limit: 10, order: "desc", } ); return messages; }, });
import React from "react"; import "./product.css"; import { useStateValue } from "../../context/StateProvider"; const Product = ({ id, image, price, title, rating }) => { const [, dispatch] = useStateValue(); const addToCart = () => { dispatch({ type: "ADD_TO_CART", itemDetils: { id: id, image: image, price: price, rating: rating, image: image, }, }); }; return ( <div className="product"> <div className="product_info"> <p>{title}</p> <p className="product_price"> $: {price}</p> </div> <div className="product_rating"> {Array(rating) .fill() ?.map((_) => ( <p>⭐</p> ))} </div> <img height="200px" src={image} alt={image} /> <button onClick={addToCart}>Add to cart</button> </div> ); }; export default Product;
const { celebrate, Joi, Segments } = require('celebrate'); module.exports = { create: celebrate({ [Segments.BODY]: Joi .object() .keys({ brand: Joi.string().optional().allow(null).allow('').messages({ "string.base": `"Marca" debe ser una cadena de caracteres`, }), model: Joi.string().optional().allow(null).allow('').messages({ "string.base": `"Modelo" debe ser una cadena de caracteres`, }), placa: Joi.string().required().max(7).messages({ "string.base": `"Placa" debe ser una cadena de caracteres`, "string.empty": `"Placa" debe contener un valor`, "any.required": `"Placa" es un campo obligatorio` }), eco: Joi.string().required().max(3).messages({ "string.base": `"Número economico" debe ser un arreglo`, "string.empty": `"Número economico" debe contener un valor`, "any.required": `"Número economico" es un campo obligatorio` }), dependencyId: Joi.number().required().messages({ "number.base": `"Dependencia" debe ser numerico`, "number.empty": `"Dependencia" debe contener un valor`, "any.required": `"Dependencia" es un campo obligatorio` }), capacityId: Joi.number().required().messages({ "number.base": `"Capacidad" debe ser numerico`, "number.empty": `"Capacidad" debe contener un valor`, "any.required": `"Capacidad" es un campo obligatorio` }), firstName: Joi.string().required().messages({ "string.base": `"Nombre" debe ser una cadena de caracteres`, "string.empty": `"Nombre" debe contener un valor`, "any.required": `"Nombre" es un campo obligatorio` }), maternalSurname: Joi.string().optional().allow(null).allow('').messages({ "string.base": `"Apellido Materno" debe ser una cadena de caracteres`, }), paternalSurname: Joi.string().optional().allow(null).allow('').messages({ "string.base": `"Apellido Paterno" debe ser una cadena de caracteres`, }), phoneNumber: Joi.number().optional().allow(null).allow('').max(9999999999).messages({ "number.base": `"Número Telefónico" debe ser numerico`, }), }), }), update: celebrate( { [Segments.PARAMS]: Joi .object() .keys({ id: Joi.number().required().messages({ "number.base": `"Id" debe ser un identificador numerico`, }), }), [Segments.BODY]: Joi .object() .keys({ brand: Joi.string().optional().allow(null).allow('').messages({ "string.base": `"Marca" debe ser una cadena de caracteres`, }), model: Joi.string().optional().allow(null).allow('').messages({ "string.base": `"Modelo" debe ser una cadena de caracteres`, }), placa: Joi.string().required().max(7).messages({ "string.base": `"Placa" debe ser una cadena de caracteres`, "string.empty": `"Placa" debe contener un valor`, "any.required": `"Placa" es un campo obligatorio` }), eco: Joi.string().required().max(3).messages({ "string.base": `"Número economico" debe ser un arreglo`, "string.empty": `"Número economico" debe contener un valor`, "any.required": `"Número economico" es un campo obligatorio` }), dependencyId: Joi.number().required().messages({ "number.base": `"Dependencia" debe ser numerico`, "number.empty": `"Dependencia" debe contener un valor`, "any.required": `"Dependencia" es un campo obligatorio` }), capacityId: Joi.number().required().messages({ "number.base": `"Capacidad" debe ser numerico`, "number.empty": `"Capacidad" debe contener un valor`, "any.required": `"Capacidad" es un campo obligatorio` }), firstName: Joi.string().required().messages({ "string.base": `"Nombre" debe ser una cadena de caracteres`, "string.empty": `"Nombre" debe contener un valor`, "any.required": `"Nombre" es un campo obligatorio` }), maternalSurname: Joi.string().optional().allow(null).allow('').messages({ "string.base": `"Apellido Materno" debe ser una cadena de caracteres`, }), paternalSurname: Joi.string().optional().allow(null).allow('').messages({ "string.base": `"Apellido Paterno" debe ser una cadena de caracteres`, }), phoneNumber: Joi.number().optional().allow(null).allow('').max(9999999999).messages({ "number.base": `"Número Telefónico" debe ser numerico`, }), }), }), };
class IngredientsController < ApplicationController before_action :set_ingredient, only: %i[show edit update] before_action :require_admin, except: %i[index show] def new @ingredient = Ingredient.new end def create @ingredient = Ingredient.new(ingredient_params) if @ingredient.save flash[:success] = 'Ingredient added successfully' redirect_to @ingredient else flash[:danger] = 'Prevented the ingredient from being saved' render 'new', status: :unprocessable_entity end end def edit; end def update if @ingredient.update(ingredient_params) flash[:success] = 'Ingredient updated successfully' redirect_to @ingredient else flash[:danger] = 'Prevented this Ingredient from being updated' render 'edit', status: :unprocessable_entity end end def show @ingredient_recipes = @ingredient.recipes.order(:name).page params[:page] end def index @ingredients = Ingredient.order(:name).page params[:page] end private def set_ingredient @ingredient = Ingredient.find(params[:id]) end def ingredient_params params.require(:ingredient).permit(:name) end def require_admin return unless !logged_in? || (logged_in? and !current_user.admin) flash[:danger] = 'Only admin users can preform this action' redirect_to ingredients_path end end
import { Component, ElementRef, ViewChild } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import { Profesor } from 'src/app/Clases/Profesor/profesor'; import { ProfesoresService } from 'src/app/Servicios/Profesores/profesores.service'; import { DialogGuardarProfesoresComponent } from '../dialog-guardar-profesores/dialog-guardar-profesores.component'; @Component({ selector: 'app-profesores', templateUrl: './profesores.component.html', styleUrls: ['./profesores.component.css'] }) export class ProfesoresComponent { displayedColumns: string[] = ["Nombre", "Accion"]; dataSource!: MatTableDataSource<Profesor>; @ViewChild(MatPaginator) paginator!: MatPaginator; @ViewChild(MatSort) sort!: MatSort; @ViewChild("input")input?:ElementRef; constructor( private _profesorS: ProfesoresService, public dialog: MatDialog ) { } ngOnInit() { this.spProfesor_Obtener(); } appendAlert(message: string, type: string, styles: string, icon: string) { const alertPlaceholder = document.getElementById('liveAlertPlaceholder')!; const wrapper = document.createElement('div'); wrapper.innerHTML = [ `<div style="${styles}" data-bs-theme="dark" class="alert ${type} alert-dismissible" role="alert">`, ` <div style="font-size:large;">${message} ${icon}</div>`, ` <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>`, '</div>' ].join(''); alertPlaceholder.append(wrapper); } spProfesor_Obtener(): void { this._profesorS.spProfesores_Obtener().subscribe(response => { this.dataSource = new MatTableDataSource(response); this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; }); } openDialog(rowData: any, ponerTitulo: string): void { const dialogRef = this.dialog.open(DialogGuardarProfesoresComponent, { data: { rowData, ponerTitulo }, minWidth: "30%", width:"400px" }); dialogRef.afterClosed().subscribe(result => { if (result === true) { if (ponerTitulo === "Nuevo") { this.spProfesor_Obtener(); this.appendAlert("Se ha guardado correctamente", "", "background-color: #273646; color:white; text-align:center;", "<i class='fa-solid fa-circle-check' style='margin-left:10px;'></i>"); } else { if (ponerTitulo === "Modificar") { this.spProfesor_Obtener(); this.appendAlert("Se ha modificado correctamente", "", "background-color: #273646; color:white; text-align:center;", "<i class='fa-solid fa-pen-to-square' style='margin-left:10px;'></i>"); } else { this.spProfesor_Obtener(); this.appendAlert("Se ha borrado correctamente", "", "background-color: #1b5a4c; color:white; text-align:center;", "<i class='fa-solid fa-trash' style='margin-left:10px;'></i>"); } } } window.scrollTo({top:0, behavior:"smooth"}); /* setTimeout(() => { document.getElementById("liveAlertPlaceholder")!.style.display="none"; }, 10000); */ }); } applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } }
import { Client, Events, GatewayIntentBits, GuildMemberRoleManager, REST, Routes, SlashCommandBuilder } from "discord.js" import roles from './roles.json' const client = new Client({ intents: [GatewayIntentBits.Guilds] }) client.once(Events.ClientReady, client => { console.log(`Logged in as ${client.user?.tag}`) }) const roleChoices = Object.entries(roles).map(([name, id]) => ({ name, value: id })) const roleCommandData = new SlashCommandBuilder() .setName('role') .setDescription('Assign or remove roles') .addSubcommand(subcommand => subcommand .setName('add') .setDescription('Add a role') .addStringOption(option => option .setName('role') .setDescription('The role to add') .addChoices(...roleChoices) ) ) .addSubcommand(subcommand => subcommand .setName('remove') .setDescription('Remove a role') .addStringOption(option => option .setName('role') .setDescription('The role to remove') .addChoices(...roleChoices) ) ) const pingCommandData = new SlashCommandBuilder() .setName('hi') .setDescription('hi paracelsus') client.on(Events.InteractionCreate, async interaction => { if (!interaction.isChatInputCommand()) { return } if(interaction.commandName === 'hi') { interaction.reply('hi') } else if(interaction.commandName === 'role') { const subcommand = interaction.options.getSubcommand() const role = interaction.options.getString('role') if(!role) { interaction.reply('You must specify a role.') return } const member = interaction.member if(!member) { interaction.reply('You must use this command from a server.') return } if(!(member.roles instanceof GuildMemberRoleManager)) { interaction.reply('guoh') return } // @ts-ignore const roleName = Object.keys(roles).find(name => roles[name] === role) if(subcommand === 'add') { member.roles.add(role) interaction.reply(`Added role ${roleName}.`) } else if(subcommand === 'remove') { member.roles.remove(role) interaction.reply(`Removed role ${roleName}.`) } } }) // register commands and log in const TOKEN = process.env.TOKEN const CLIENT_ID = process.env.CLIENT_ID if(!TOKEN) { console.error('No token provided') process.exit(1) } if(!CLIENT_ID) { console.error('No client id provided') process.exit(1) } const rest = new REST().setToken(TOKEN) try { console.log('Registering commands ...') const data = await rest.put(Routes.applicationCommands(CLIENT_ID), { body: [roleCommandData, pingCommandData] }) console.log(`Registered ${(data as unknown[]).length} commands`) console.log('Logging in ...') await client.login(TOKEN) } catch (e) { console.error(e) process.exit(1) }
## [Day 7: The Treachery of Whales](https://adventofcode.com/2021/day/7) ## >A giant whale has decided your submarine is its next meal, and it's much faster than you are. There's nowhere to run! > >Suddenly, a swarm of crabs (each in its own tiny submarine - it's too deep for them otherwise) zooms in to rescue you! They seem to be preparing to blast a hole in the ocean floor; sensors indicate a massive underground cave system just beyond where they're aiming! > >The crab submarines all need to be aligned before they'll have enough power to blast a large enough hole for your submarine to get through. However, it doesn't look like they'll be aligned before the whale catches you! Maybe you can help? > >There's one major catch - crab submarines can only move horizontally. > >You quickly make a list of the horizontal position of each crab (your puzzle input). Crab submarines have limited fuel, so you need to find a way to make all of their horizontal positions match while requiring them to spend as little fuel as possible. > >For example, consider the following horizontal positions: >``` >16,1,2,0,4,2,7,1,2,14 >``` >This means there's a crab with horizontal position 16, a crab with horizontal position 1, and so on. > >Each change of 1 step in horizontal position of a single crab costs 1 fuel. You could choose any horizontal position to align them all on, but the one that costs the least fuel is horizontal position 2: >``` > Move from 16 to 2: 14 fuel > Move from 1 to 2: 1 fuel > Move from 2 to 2: 0 fuel > Move from 0 to 2: 2 fuel > Move from 4 to 2: 2 fuel > Move from 2 to 2: 0 fuel > Move from 7 to 2: 5 fuel > Move from 1 to 2: 1 fuel > Move from 2 to 2: 0 fuel > Move from 14 to 2: 12 fuel >``` >This costs a total of 37 fuel. This is the cheapest possible outcome; more expensive outcomes include aligning at position 1 (41 fuel), position 3 (39 fuel), or position 10 (71 fuel). > >Determine the horizontal position that the crabs can align to using the least fuel possible. How much fuel must they spend to align to that position? >--- Part Two --- > >The crabs don't seem interested in your proposed solution. Perhaps you misunderstand crab engineering? > >As it turns out, crab submarine engines don't burn fuel at a constant rate. Instead, each change of 1 step in horizontal position costs 1 more unit of fuel than the last: the first step costs 1, the second step costs 2, the third step costs 3, and so on. > >As each crab moves, moving further becomes more expensive. This changes the best horizontal position to align them all on; in the example above, this becomes 5: >``` > Move from 16 to 5: 66 fuel > Move from 1 to 5: 10 fuel > Move from 2 to 5: 6 fuel > Move from 0 to 5: 15 fuel > Move from 4 to 5: 1 fuel > Move from 2 to 5: 6 fuel > Move from 7 to 5: 3 fuel > Move from 1 to 5: 10 fuel > Move from 2 to 5: 6 fuel > Move from 14 to 5: 45 fuel >``` >This costs a total of 168 fuel. This is the new cheapest possible outcome; the old alignment position (2) now costs 206 fuel instead. > >Determine the horizontal position that the crabs can align to using the least fuel possible so they can make you an escape route! How much fuel must they spend to align to that position? # ## Part 1 ## This puzzle can be summarized as > Given a sequence of N values (a<sub>i</sub>), find the integer value m that minimises > > sum<sup>N</sup><sub>i=1</sub>(|a<sub>i</sub> - n|) By definition, the value `n` that would satisfy this is the median value of the data. This simplified the problem massively, as now we just need to sort the data, find the middle element, and calculate the sum of the fuel requirements. ## Part 2 ## The second part changes the sum requirements drastically. Now the equation to minimise is built on triangle numbers. If `T(n)` is the `n`<sup>`th`</sup> triangle number (equal to `n(n+1)/2`), then we need to minimise >sum<sup>N</sup><sub>i=1</sub>(T(|a<sub>i</sub> - n|)) With Part 1, we can prove that plugging the median value into `n` would minimise the equation by considering what happens when we slowly increase `n` by a little bit at a time. I feel like we can take a similar approach here. If we have a sequence of values `s`<sub>`i`</sub>, we can consider what happens to a variable `n` as it walks through these values. Let `j1` and `j2` integers such that `s`<sub>`j1`</sub>` < n < s`<sub>`j2`</sub>, then a small change in `n` will increase the fuel cost of all `s`<sub>`i`</sub>` <= n` by `n - s`<sub>`i`</sub>, and decrease the fuel cost of all `s`<sub>`i`</sub>` > n` by `s`<sub>`i`</sub>` - n`. The minimum point will thus be when the sum of all these differences equals `0`. In computing this value, and pulling the `n` terms out of the sums reveals the **mean** to be the solution. The problem restricts us to integer positions only, but it's easy enough to see that if the mean is greater than the median, rounding down gets us the next best option, and vice versa when the mean is less than the median.
<template> <div v-if="internalTableData !== undefined || Array.isArray(internalTableData)" > <div id="tablecontainer"> <table v-if="internalTableData.length > 0"> <thead class="heading"> <tr> <th v-for="col in columns" v-bind:key="col"> <action-button title="sort" @click="sort(col)"> {{ col }} </action-button> <span id="sortIndicator"> <template v-if="sortColumn === col"> <template v-if="order === 2"> <!-- DESCENDING --> <Icon icon="feather:arrow-down" width="24px" /> </template> <template v-else-if="order === 1"> <!-- ASCENDING --> <Icon icon="feather:arrow-up" width="24px" /> </template> <template v-else><!--- UNSORTED --></template> </template> </span> </th> </tr> </thead> <tbody> <tr v-for="row in internalTableData" v-bind:key="row.id"> <td v-for="col in columns" v-bind:key="col"> {{ row[col] }} </td> </tr> </tbody> </table> <span v-else>No Data</span> </div> </div> </template> <script lang="ts"> import { defineComponent } from "vue"; import _ from "lodash"; import { Icon } from "@iconify/vue"; import { TableData } from "./types"; import ActionButton from "./ActionButton.vue"; export default defineComponent({ components: { ActionButton, Icon, }, props: { tableData: Array }, data() { return { sortColumn: "", order: 0, internalTableData: undefined as TableData, }; }, computed: { columns(): string[] { return this.internalTableData === undefined || this.internalTableData.length === 0 ? [] : Object.keys(this.internalTableData[0]); }, }, watch: { tableData: function (dat) { this.internalTableData = dat; }, }, methods: { sort(column: string) { this.sortColumn = column; this.order = (this.order + 1) % 3; switch (this.order) { case 0: // unsorted this.internalTableData = this.tableData as TableData; return; case 1: // ascending return (this.internalTableData = _.orderBy( this.tableData, column, "asc" ) as TableData); case 2: // descending return (this.internalTableData = _.orderBy( this.tableData, column, "desc" ) as TableData); } }, }, }); </script> <style scoped> #tablecontainer { overflow-x: auto; white-space: nowrap; } #sortIndicator { height: 1.2em; width: 1em; display: inline-block; } table { border-collapse: collapse; border: none; } thead a { text-decoration: none; } thead a:hover { text-decoration: underline; } thead th { vertical-align: bottom; padding-right: 1em; border-bottom: 1px solid grey; } td { padding-right: 3em; } </style>
import { useState } from "react"; import Nav from "./components/Nav"; import NewArrivalSection from "./components/NewArrivalSection"; import ShowDetail from "./components/ShowDetail"; import Sidebar from "./components/Sidebar"; import { SHOE_LIST } from "./constant"; import Cart from "./components/Cart"; function App() { const [isSidebarOpen, setIsSidebarOpen] = useState(false); const [currentShoe, setCurrentShoe] = useState(SHOE_LIST[0]); const [cartItems, setCartItems] = useState([]); const removeFromCart = (productId) => { console.log(productId); const updatedCartItems = [...cartItems]; const existingItemIndex = cartItems.findIndex( (item) => item.product.id === productId ); updatedCartItems.splice(existingItemIndex, 1); setCartItems(updatedCartItems); }; const addToCart = (product, qty, size) => { if (qty && size) { const updatedCartItems = [...cartItems]; const existingItemIndex = cartItems.findIndex( (item) => item.product.id === product.id ); if (existingItemIndex > -1) { updatedCartItems[existingItemIndex].qty = qty; updatedCartItems[existingItemIndex].size = size; } else { updatedCartItems.push({ product, qty, size }); } setCartItems(updatedCartItems); } }; return ( <div className=" animate-fadeIn p-10 xl:px-24"> <Nav onClickShoppingBtn={() => setIsSidebarOpen(true)} /> <ShowDetail shoe={currentShoe} onClickAdd={addToCart} /> <NewArrivalSection items={SHOE_LIST} onClickCard={setCurrentShoe} /> <Sidebar isOpen={isSidebarOpen} onClickClose={() => setIsSidebarOpen(false)} > <Cart cartItems={cartItems} onClickTrash={removeFromCart} /> </Sidebar> </div> ); } export default App;
import os from tkinter import filedialog from tkinter import * from tkinter import simpledialog from cryptography.fernet import Fernet from tkinter import messagebox def encrypt_image(image_path, output_directory): key = Fernet.generate_key() f = Fernet(key) with open(image_path, 'rb') as image_file: image_data = image_file.read() encrypted_image = f.encrypt(image_data) encrypted_image_path = os.path.join(output_directory, 'encrypted_image.png') with open(encrypted_image_path, 'wb') as encrypted_file: encrypted_file.write(encrypted_image) return key, encrypted_image_path def copy_key_to_clipboard(key_text): key = key_text.get("1.0", "end-1c") root.clipboard_clear() root.clipboard_append(key) root.update() def decrypt_image(encrypted_image_path, key): f = Fernet(key) with open(encrypted_image_path, 'rb') as encrypted_file: encrypted_image = encrypted_file.read() decrypted_image = f.decrypt(encrypted_image) return decrypted_image def save_decrypted_image(decrypted_image, output_directory): output_filename = 'decrypted_image.png' output_path = os.path.join(output_directory, output_filename) with open(output_path, 'wb') as decrypted_file: decrypted_file.write(decrypted_image) return output_path def open_image_with_default_app(output_path): os.system(f'xdg-open {output_path}') root = Tk() root.withdraw() choice = messagebox.askquestion("Image Encryption/Decryption", "Do you want to encrypt or decrypt an image?") if choice == "yes": image_path = filedialog.askopenfilename(title="Select Image to Encrypt", filetypes=(("Image files", "*.png *.jpg *.jpeg *.bmp"), ("All files", "*.*"))) if not image_path: messagebox.showinfo("Information", "No image selected. Exiting.") else: output_directory = filedialog.askdirectory(title="Select Output Directory for Encrypted Image") if not output_directory: messagebox.showinfo("Information", "No output directory selected. Exiting.") else: key, encrypted_image_path = encrypt_image(image_path, output_directory) key_window = Tk() key_window.title("Encryption Key") key_text = Text(key_window, height=1, width=45) key_text.insert(END, key.decode()) key_text.pack() copy_button = Button(key_window, text="Copy Key", command=lambda: copy_key_to_clipboard(key_text)) copy_button.pack() ok_button = Button(key_window, text="OK", command=key_window.destroy) ok_button.pack() key_window.mainloop() messagebox.showinfo("Encryption Complete", f"Image encrypted successfully.\nEncrypted image saved at: {encrypted_image_path}") elif choice == "no": encrypted_image_path = filedialog.askopenfilename(title="Select Encrypted Image", filetypes=(("Image files", "*.png"), ("All files", "*.*"))) if not encrypted_image_path: messagebox.showinfo("Information", "No encrypted image selected. Exiting.") else: output_directory = filedialog.askdirectory(title="Select Output Directory for Decrypted Image") if not output_directory: messagebox.showinfo("Information", "No output directory selected. Exiting.") else: key_text = simpledialog.askstring("Input", "Enter the encryption key:", show="*") key = key_text.encode() try: decrypted_image = decrypt_image(encrypted_image_path, key) output_path = save_decrypted_image(decrypted_image, output_directory) open_image_with_default_app(output_path) print(f"Image decrypted successfully. Decrypted image saved at: {output_path}") except Exception as e: print(f"Error: {e}") else: messagebox.showinfo("Information", "Exiting without any action.") root.destroy()
import { IconProp } from '@fortawesome/fontawesome-svg-core'; import { faExpandArrowsAlt, faFaucet } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FC } from 'react'; import styled from 'styled-components'; import { Colour, colours } from '../Shared/SharedStyles'; interface IColourProps { colour: Colour; } const Container = styled.div` display: flex; align-items: center; justify-content: space-between; overflow: hidden; border-radius: 5px; `; const Subject = styled.div` background: ${(p: IColourProps) => colours[p.colour]}; color: ${colours.light}; display: flex; align-items: center; justify-content: center; font-weight: 600; height: 40px; width: 50px; `; const Value = styled.div` display: flex; align-items: center; justify-content: center; background: ${(p: IColourProps) => colours[p.colour]}4c; font-weight: 600; height: 40px; width: calc(100% - 50px); `; export const Icon = styled(FontAwesomeIcon)` color: ${colours.light}; `; interface IProps { colour: Colour; subject: string; value: string; icon: IconProp; } const Pill: FC<IProps> = ({colour, subject, value, icon}: IProps) => { return ( <Container> {/* <Subject colour={colour}>{subject}</Subject> */} <Subject colour={colour}><Icon icon={icon}/></Subject> <Value colour={colour}>{value}</Value> </Container> ); } export default Pill;
import { Card, CardHeader, CardBody, Typography, IconButton, Spinner, Button, Select, Option, } from "@material-tailwind/react"; import { PlusIcon, ArrowPathIcon } from "@heroicons/react/24/solid"; import { TABLE_HEAD } from "./constants"; import TrackingCoinRow from "./TrackingCoinRow"; import { MutateCoinDialog } from "@/components/dialogs/MutateCoinDialog"; import { STATUS_COIN, STATUS_OPTIONS } from "@/utils/constants"; import { isEmpty } from "lodash"; import { useGetTrackingCoinsQuery } from "@/app/api/apiSlice"; import { useMemo, useState } from "react"; import Summary from "./Summary"; export function TrackingCoin() { const [status, setStatus] = useState(String(STATUS_COIN.created)); const { isFetching, data, refetch } = useGetTrackingCoinsQuery({ status: status, }); const [isAddDial, setIsAddDial] = useState(false); const handleOpenAddDial = () => setIsAddDial(true); const handleCloseAddDial = () => setIsAddDial(false); const convertHead = useMemo(() => { if (Number(status) !== STATUS_COIN.sold) return TABLE_HEAD; return TABLE_HEAD.map((item) => { if (item.head === "Market Price") item.head = "Closed Price"; return item; }); }, [status]); const renderContent = () => { const colSpan = TABLE_HEAD.length; if (isFetching) return ( <tr> <td colSpan={colSpan} className="h-40"> <div className="flex items-center justify-center"> <Spinner className="h-8 w-8" /> </div> </td> </tr> ); if (!data || isEmpty(data)) return ( <tr> <td colSpan={colSpan} className="h-40"> <div className="flex items-center justify-center">No data</div> </td> </tr> ); return ( <> {data.map((item: any, index: number) => { const isLast = index === data?.length - 1; const classes = isLast ? "!p-4" : "!p-4 border-b border-gray-300"; return <TrackingCoinRow key={index} data={item} classes={classes} />; })} <Summary data={data} /> </> ); }; return ( <> <div className="mb-8 mt-12 flex flex-col gap-12"> <Card> <CardHeader variant="gradient" color="gray" className="mb-8 p-6"> <div className="flex flex-col items-start justify-center gap-2 sm:flex-row sm:items-center sm:justify-between " > <Typography variant="h6" color="white"> Tracking Revenue Table </Typography> <div className="flex items-center gap-2 self-end sm:self-center"> <Button variant="filled" color="white" size="sm" className="flex items-center gap-0.5 " onClick={handleOpenAddDial} > <PlusIcon className="h-5 w-5" /> Add Crypto </Button> <IconButton variant="text" color="white" size="md" onClick={refetch} > <ArrowPathIcon className="h-5 w-5 text-white" /> </IconButton> </div> </div> </CardHeader> <CardBody className="overflow-x-scroll px-0 pb-2 pt-0"> <div className="ml-4 w-full max-w-10 py-1"> <Select label="Select Status" value={String(status)} onChange={(val) => setStatus(String(val))} > {STATUS_OPTIONS.map((option) => ( <Option key={option.value} value={String(option.value)}> {option.label} </Option> ))} </Select> </div> <table className="w-full min-w-[640px] table-auto"> <thead> <tr> {convertHead.map(({ head, customeStyle }) => ( <th key={head} className={`border-b border-blue-gray-50 px-5 py-3 text-left ${customeStyle}`} > <Typography variant="small" className="text-[11px] font-bold uppercase text-blue-gray-400" > {head} </Typography> </th> ))} </tr> </thead> <tbody>{renderContent()}</tbody> </table> </CardBody> </Card> </div> {isAddDial && ( <MutateCoinDialog open={isAddDial} onClose={handleCloseAddDial} /> )} </> ); } export default TrackingCoin;
package org.itjl.model; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; public class ZxCriteria { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public ZxCriteria() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } protected void addCriterionForJDBCDate(String condition, Date value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } addCriterion(condition, new java.sql.Date(value.getTime()), property); } protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) { if (values == null || values.size() == 0) { throw new RuntimeException("Value list for " + property + " cannot be null or empty"); } List<java.sql.Date> dateList = new ArrayList<java.sql.Date>(); Iterator<Date> iter = values.iterator(); while (iter.hasNext()) { dateList.add(new java.sql.Date(iter.next().getTime())); } addCriterion(condition, dateList, property); } protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property); } public Criteria andZx_idIsNull() { addCriterion("zx_id is null"); return (Criteria) this; } public Criteria andZx_idIsNotNull() { addCriterion("zx_id is not null"); return (Criteria) this; } public Criteria andZx_idEqualTo(Integer value) { addCriterion("zx_id =", value, "zx_id"); return (Criteria) this; } public Criteria andZx_idNotEqualTo(Integer value) { addCriterion("zx_id <>", value, "zx_id"); return (Criteria) this; } public Criteria andZx_idGreaterThan(Integer value) { addCriterion("zx_id >", value, "zx_id"); return (Criteria) this; } public Criteria andZx_idGreaterThanOrEqualTo(Integer value) { addCriterion("zx_id >=", value, "zx_id"); return (Criteria) this; } public Criteria andZx_idLessThan(Integer value) { addCriterion("zx_id <", value, "zx_id"); return (Criteria) this; } public Criteria andZx_idLessThanOrEqualTo(Integer value) { addCriterion("zx_id <=", value, "zx_id"); return (Criteria) this; } public Criteria andZx_idIn(List<Integer> values) { addCriterion("zx_id in", values, "zx_id"); return (Criteria) this; } public Criteria andZx_idNotIn(List<Integer> values) { addCriterion("zx_id not in", values, "zx_id"); return (Criteria) this; } public Criteria andZx_idBetween(Integer value1, Integer value2) { addCriterion("zx_id between", value1, value2, "zx_id"); return (Criteria) this; } public Criteria andZx_idNotBetween(Integer value1, Integer value2) { addCriterion("zx_id not between", value1, value2, "zx_id"); return (Criteria) this; } public Criteria andZx_btIsNull() { addCriterion("zx_bt is null"); return (Criteria) this; } public Criteria andZx_btIsNotNull() { addCriterion("zx_bt is not null"); return (Criteria) this; } public Criteria andZx_btEqualTo(String value) { addCriterion("zx_bt =", value, "zx_bt"); return (Criteria) this; } public Criteria andZx_btNotEqualTo(String value) { addCriterion("zx_bt <>", value, "zx_bt"); return (Criteria) this; } public Criteria andZx_btGreaterThan(String value) { addCriterion("zx_bt >", value, "zx_bt"); return (Criteria) this; } public Criteria andZx_btGreaterThanOrEqualTo(String value) { addCriterion("zx_bt >=", value, "zx_bt"); return (Criteria) this; } public Criteria andZx_btLessThan(String value) { addCriterion("zx_bt <", value, "zx_bt"); return (Criteria) this; } public Criteria andZx_btLessThanOrEqualTo(String value) { addCriterion("zx_bt <=", value, "zx_bt"); return (Criteria) this; } public Criteria andZx_btLike(String value) { addCriterion("zx_bt like", value, "zx_bt"); return (Criteria) this; } public Criteria andZx_btNotLike(String value) { addCriterion("zx_bt not like", value, "zx_bt"); return (Criteria) this; } public Criteria andZx_btIn(List<String> values) { addCriterion("zx_bt in", values, "zx_bt"); return (Criteria) this; } public Criteria andZx_btNotIn(List<String> values) { addCriterion("zx_bt not in", values, "zx_bt"); return (Criteria) this; } public Criteria andZx_btBetween(String value1, String value2) { addCriterion("zx_bt between", value1, value2, "zx_bt"); return (Criteria) this; } public Criteria andZx_btNotBetween(String value1, String value2) { addCriterion("zx_bt not between", value1, value2, "zx_bt"); return (Criteria) this; } public Criteria andZx_dateIsNull() { addCriterion("zx_date is null"); return (Criteria) this; } public Criteria andZx_dateIsNotNull() { addCriterion("zx_date is not null"); return (Criteria) this; } public Criteria andZx_dateEqualTo(Date value) { addCriterionForJDBCDate("zx_date =", value, "zx_date"); return (Criteria) this; } public Criteria andZx_dateNotEqualTo(Date value) { addCriterionForJDBCDate("zx_date <>", value, "zx_date"); return (Criteria) this; } public Criteria andZx_dateGreaterThan(Date value) { addCriterionForJDBCDate("zx_date >", value, "zx_date"); return (Criteria) this; } public Criteria andZx_dateGreaterThanOrEqualTo(Date value) { addCriterionForJDBCDate("zx_date >=", value, "zx_date"); return (Criteria) this; } public Criteria andZx_dateLessThan(Date value) { addCriterionForJDBCDate("zx_date <", value, "zx_date"); return (Criteria) this; } public Criteria andZx_dateLessThanOrEqualTo(Date value) { addCriterionForJDBCDate("zx_date <=", value, "zx_date"); return (Criteria) this; } public Criteria andZx_dateIn(List<Date> values) { addCriterionForJDBCDate("zx_date in", values, "zx_date"); return (Criteria) this; } public Criteria andZx_dateNotIn(List<Date> values) { addCriterionForJDBCDate("zx_date not in", values, "zx_date"); return (Criteria) this; } public Criteria andZx_dateBetween(Date value1, Date value2) { addCriterionForJDBCDate("zx_date between", value1, value2, "zx_date"); return (Criteria) this; } public Criteria andZx_dateNotBetween(Date value1, Date value2) { addCriterionForJDBCDate("zx_date not between", value1, value2, "zx_date"); return (Criteria) this; } public Criteria andZx_llIsNull() { addCriterion("zx_ll is null"); return (Criteria) this; } public Criteria andZx_llIsNotNull() { addCriterion("zx_ll is not null"); return (Criteria) this; } public Criteria andZx_llEqualTo(Integer value) { addCriterion("zx_ll =", value, "zx_ll"); return (Criteria) this; } public Criteria andZx_llNotEqualTo(Integer value) { addCriterion("zx_ll <>", value, "zx_ll"); return (Criteria) this; } public Criteria andZx_llGreaterThan(Integer value) { addCriterion("zx_ll >", value, "zx_ll"); return (Criteria) this; } public Criteria andZx_llGreaterThanOrEqualTo(Integer value) { addCriterion("zx_ll >=", value, "zx_ll"); return (Criteria) this; } public Criteria andZx_llLessThan(Integer value) { addCriterion("zx_ll <", value, "zx_ll"); return (Criteria) this; } public Criteria andZx_llLessThanOrEqualTo(Integer value) { addCriterion("zx_ll <=", value, "zx_ll"); return (Criteria) this; } public Criteria andZx_llIn(List<Integer> values) { addCriterion("zx_ll in", values, "zx_ll"); return (Criteria) this; } public Criteria andZx_llNotIn(List<Integer> values) { addCriterion("zx_ll not in", values, "zx_ll"); return (Criteria) this; } public Criteria andZx_llBetween(Integer value1, Integer value2) { addCriterion("zx_ll between", value1, value2, "zx_ll"); return (Criteria) this; } public Criteria andZx_llNotBetween(Integer value1, Integer value2) { addCriterion("zx_ll not between", value1, value2, "zx_ll"); return (Criteria) this; } public Criteria andZx_lb_idIsNull() { addCriterion("zx_lb_id is null"); return (Criteria) this; } public Criteria andZx_lb_idIsNotNull() { addCriterion("zx_lb_id is not null"); return (Criteria) this; } public Criteria andZx_lb_idEqualTo(Integer value) { addCriterion("zx_lb_id =", value, "zx_lb_id"); return (Criteria) this; } public Criteria andZx_lb_idNotEqualTo(Integer value) { addCriterion("zx_lb_id <>", value, "zx_lb_id"); return (Criteria) this; } public Criteria andZx_lb_idGreaterThan(Integer value) { addCriterion("zx_lb_id >", value, "zx_lb_id"); return (Criteria) this; } public Criteria andZx_lb_idGreaterThanOrEqualTo(Integer value) { addCriterion("zx_lb_id >=", value, "zx_lb_id"); return (Criteria) this; } public Criteria andZx_lb_idLessThan(Integer value) { addCriterion("zx_lb_id <", value, "zx_lb_id"); return (Criteria) this; } public Criteria andZx_lb_idLessThanOrEqualTo(Integer value) { addCriterion("zx_lb_id <=", value, "zx_lb_id"); return (Criteria) this; } public Criteria andZx_lb_idIn(List<Integer> values) { addCriterion("zx_lb_id in", values, "zx_lb_id"); return (Criteria) this; } public Criteria andZx_lb_idNotIn(List<Integer> values) { addCriterion("zx_lb_id not in", values, "zx_lb_id"); return (Criteria) this; } public Criteria andZx_lb_idBetween(Integer value1, Integer value2) { addCriterion("zx_lb_id between", value1, value2, "zx_lb_id"); return (Criteria) this; } public Criteria andZx_lb_idNotBetween(Integer value1, Integer value2) { addCriterion("zx_lb_id not between", value1, value2, "zx_lb_id"); return (Criteria) this; } public Criteria andZx_tpIsNull() { addCriterion("zx_tp is null"); return (Criteria) this; } public Criteria andZx_tpIsNotNull() { addCriterion("zx_tp is not null"); return (Criteria) this; } public Criteria andZx_tpEqualTo(String value) { addCriterion("zx_tp =", value, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpNotEqualTo(String value) { addCriterion("zx_tp <>", value, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpGreaterThan(String value) { addCriterion("zx_tp >", value, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpGreaterThanOrEqualTo(String value) { addCriterion("zx_tp >=", value, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpLessThan(String value) { addCriterion("zx_tp <", value, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpLessThanOrEqualTo(String value) { addCriterion("zx_tp <=", value, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpLike(String value) { addCriterion("zx_tp like", value, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpNotLike(String value) { addCriterion("zx_tp not like", value, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpIn(List<String> values) { addCriterion("zx_tp in", values, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpNotIn(List<String> values) { addCriterion("zx_tp not in", values, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpBetween(String value1, String value2) { addCriterion("zx_tp between", value1, value2, "zx_tp"); return (Criteria) this; } public Criteria andZx_tpNotBetween(String value1, String value2) { addCriterion("zx_tp not between", value1, value2, "zx_tp"); return (Criteria) this; } public Criteria andZx_bqIsNull() { addCriterion("zx_bq is null"); return (Criteria) this; } public Criteria andZx_bqIsNotNull() { addCriterion("zx_bq is not null"); return (Criteria) this; } public Criteria andZx_bqEqualTo(String value) { addCriterion("zx_bq =", value, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqNotEqualTo(String value) { addCriterion("zx_bq <>", value, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqGreaterThan(String value) { addCriterion("zx_bq >", value, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqGreaterThanOrEqualTo(String value) { addCriterion("zx_bq >=", value, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqLessThan(String value) { addCriterion("zx_bq <", value, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqLessThanOrEqualTo(String value) { addCriterion("zx_bq <=", value, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqLike(String value) { addCriterion("zx_bq like", value, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqNotLike(String value) { addCriterion("zx_bq not like", value, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqIn(List<String> values) { addCriterion("zx_bq in", values, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqNotIn(List<String> values) { addCriterion("zx_bq not in", values, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqBetween(String value1, String value2) { addCriterion("zx_bq between", value1, value2, "zx_bq"); return (Criteria) this; } public Criteria andZx_bqNotBetween(String value1, String value2) { addCriterion("zx_bq not between", value1, value2, "zx_bq"); return (Criteria) this; } public Criteria andLb_idIsNull() { addCriterion("lb_id is null"); return (Criteria) this; } public Criteria andLb_idIsNotNull() { addCriterion("lb_id is not null"); return (Criteria) this; } public Criteria andLb_idEqualTo(Integer value) { addCriterion("lb_id =", value, "lb_id"); return (Criteria) this; } public Criteria andLb_idNotEqualTo(Integer value) { addCriterion("lb_id <>", value, "lb_id"); return (Criteria) this; } public Criteria andLb_idGreaterThan(Integer value) { addCriterion("lb_id >", value, "lb_id"); return (Criteria) this; } public Criteria andLb_idGreaterThanOrEqualTo(Integer value) { addCriterion("lb_id >=", value, "lb_id"); return (Criteria) this; } public Criteria andLb_idLessThan(Integer value) { addCriterion("lb_id <", value, "lb_id"); return (Criteria) this; } public Criteria andLb_idLessThanOrEqualTo(Integer value) { addCriterion("lb_id <=", value, "lb_id"); return (Criteria) this; } public Criteria andLb_idIn(List<Integer> values) { addCriterion("lb_id in", values, "lb_id"); return (Criteria) this; } public Criteria andLb_idNotIn(List<Integer> values) { addCriterion("lb_id not in", values, "lb_id"); return (Criteria) this; } public Criteria andLb_idBetween(Integer value1, Integer value2) { addCriterion("lb_id between", value1, value2, "lb_id"); return (Criteria) this; } public Criteria andLb_idNotBetween(Integer value1, Integer value2) { addCriterion("lb_id not between", value1, value2, "lb_id"); return (Criteria) this; } public Criteria andUser_idIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUser_idIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUser_idEqualTo(Integer value) { addCriterion("user_id =", value, "user_id"); return (Criteria) this; } public Criteria andUser_idNotEqualTo(Integer value) { addCriterion("user_id <>", value, "user_id"); return (Criteria) this; } public Criteria andUser_idGreaterThan(Integer value) { addCriterion("user_id >", value, "user_id"); return (Criteria) this; } public Criteria andUser_idGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "user_id"); return (Criteria) this; } public Criteria andUser_idLessThan(Integer value) { addCriterion("user_id <", value, "user_id"); return (Criteria) this; } public Criteria andUser_idLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "user_id"); return (Criteria) this; } public Criteria andUser_idIn(List<Integer> values) { addCriterion("user_id in", values, "user_id"); return (Criteria) this; } public Criteria andUser_idNotIn(List<Integer> values) { addCriterion("user_id not in", values, "user_id"); return (Criteria) this; } public Criteria andUser_idBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "user_id"); return (Criteria) this; } public Criteria andUser_idNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "user_id"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
import Word from '../Word'; import WordList from '../WordList'; let list; describe('WordList', () => { beforeAll(() => { list = new WordList('test/test.words'); }); test('should be creatable', () => { const list1 = new WordList('test/test.words'); expect(list1.words.length).toBe(26); }); test('should be able to return words that can be built from a string', () => { expect(list.canBeMadeFrom('merlots')).toEqual(['merlot']); }); test('should be able to return words that can be built from a Letter Map', () => { const lacquered = new Word('lacquered').letterMap; expect(list.canBeMadeFrom(lacquered)).toEqual(['lacquer']); }); test('should be able to return words that can be built from a Word', () => { const kerbstones = new Word('kerbstones'); expect(list.canBeMadeFrom(kerbstones)).toEqual(['kerbstone']); }); test('should return no words when none can be made', () => { const unstable = new Word('unstable'); expect(list.canBeMadeFrom(unstable)).toEqual([]); }); test('should return words in descending length, then alpha order', () => { const nonsense = new Word('daggahecticspenqull'); expect(list.canBeMadeFrom(nonsense)).toEqual([ 'sapience', 'hectic', 'dagga', 'naiad', 'quill', ]); }); });
int distance; int duration; const int trigPin = 11; const int echoPin = 10; int enA = 4; int in1 = 5; int in2 = 6; int in3 = 7; int in4 = 8; int enB = 9; void setup() { pinMode(enA, OUTPUT); pinMode(enB, OUTPUT); pinMode(in1, OUTPUT); pinMode(in2, OUTPUT); pinMode(in3, OUTPUT); pinMode(in4, OUTPUT); digitalWrite(in1, LOW); digitalWrite(in2, LOW); digitalWrite(in3, LOW); digitalWrite(in4, LOW); pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input Serial.begin(9600); } void loop() { //Ultrasonic Sensor digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = duration * 0.034 / 2; Serial.print("Distance: "); Serial.println(distance); forward(); if(distance<35){ left(); } else if(distance<20){ right(); } } void Stop() { analogWrite(in1, 0); analogWrite(in2, 0); analogWrite(in3, 0); analogWrite(in4, 0); } void forward(){ analogWrite(enA, 255); analogWrite(enB,255); Serial.print("forward"); digitalWrite(in1, HIGH); digitalWrite(in2, LOW); digitalWrite(in3, HIGH); digitalWrite(in4, LOW); } void backward() { digitalWrite(in1, LOW); digitalWrite(in2, HIGH); digitalWrite(in3, LOW); digitalWrite(in4, HIGH); analogWrite(enA, 255); analogWrite(enB,255); } void right() { digitalWrite(in1, LOW); digitalWrite(in2, HIGH); digitalWrite(in3, HIGH); digitalWrite(in4, LOW); analogWrite(enA, 255); analogWrite(enB,255); } void left() { digitalWrite(in1, HIGH); digitalWrite(in2, LOW); digitalWrite(in3, LOW); digitalWrite(in4, HIGH); analogWrite(enA, 255); analogWrite(enB,255); }
import React, { useState, useEffect } from 'react'; import { Card, CardContent, CardMedia, Grid, Typography, Box, Divider } from '@mui/material'; import { Link, useNavigate } from 'react-router-dom'; // Import Link from React Router import api from './Component/API/jsonapi'; import { useMediaQuery } from '@mui/material'; import ImageList from '@mui/material/ImageList'; import ImageListItem from '@mui/material/ImageListItem'; import { useTheme } from '@mui/material/styles'; import { AppBar, Toolbar, Button, Drawer, List, ListItem, ListItemText, IconButton, InputAdornment, TextField } from '@mui/material'; import { FaBars, FaTimes, FaSearch } from 'react-icons/fa'; import CallIcon from '@mui/icons-material/Call'; import BusinessIcon from '@mui/icons-material/Business'; import Pagination from '@mui/material/Pagination'; import Stack from '@mui/material/Stack'; import Footer from './Pages/Footer'; const AllUsers = () => { const [users, setUsers] = useState([]); const [currentPage, setCurrentPage] = useState(1); const theme = useTheme(); const isMobile = useMediaQuery(theme.breakpoints.down('sm')); const [searchValue, setSearchValue] = useState(''); const [openDrawer, setOpenDrawer] = useState(false); const [activeButton, setActiveButton] = useState(null); const navigate = useNavigate(); const itemsPerPage = 4; function srcset(image, size, rows = 1, cols = 1) { return { src: `${image}?w=${size * cols}&h=${size * rows}&fit=crop&auto=format`, srcSet: `${image}?w=${size * cols}&h=${size * rows }&fit=crop&auto=format&dpr=2 2x`, }; } const getPaginationRange = () => { const startIndex = (currentPage - 1) * itemsPerPage; const endIndex = Math.min(startIndex + itemsPerPage, users.length); return { startIndex, endIndex }; }; const { startIndex, endIndex } = getPaginationRange(); const itemData = [ { img: 'https://images.unsplash.com/photo-1551963831-b3b1ca40c98e', title: 'Breakfast', rows: 2, cols: 2, }, { img: 'https://images.unsplash.com/photo-1551782450-a2132b4ba21d', title: 'Burger', }, { img: 'https://images.unsplash.com/photo-1522770179533-24471fcdba45', title: 'Camera', }, { img: 'https://images.unsplash.com/photo-1444418776041-9c7e33cc5a9c', title: 'Coffee', cols: 2, }, { img: 'https://images.unsplash.com/photo-1533827432537-70133748f5c8', title: 'Hats', cols: 2, }, { img: 'https://images.unsplash.com/photo-1558642452-9d2a7deb7f62', title: 'Honey', author: '@arwinneil', rows: 2, cols: 2, }, { img: 'https://images.unsplash.com/photo-1516802273409-68526ee1bdd6', title: 'Basketball', }, { img: 'https://images.unsplash.com/photo-1518756131217-31eb79b20e8f', title: 'Fern', }, { img: 'https://images.unsplash.com/photo-1597645587822-e99fa5d45d25', title: 'Mushrooms', rows: 2, cols: 2, }, { img: 'https://images.unsplash.com/photo-1567306301408-9b74779a11af', title: 'Tomato basil', }, { img: 'https://images.unsplash.com/photo-1471357674240-e1a485acb3e1', title: 'Sea star', }, { img: 'https://images.unsplash.com/photo-1589118949245-7d38baf380d6', title: 'Bike', cols: 2, }, ]; const toggleDrawer = () => { setOpenDrawer(!openDrawer); }; const handleButtonClick = (link) => { setActiveButton(link.title); }; const handleSearch = () => { if (searchValue.trim() !== '') { navigate(`/profile/${searchValue}`); } }; const handleSearchIconClick = () => { handleSearch(); }; const handleAddBusinessClick = () => { navigate('/'); }; useEffect(() => { const fetchData = async () => { try { const response = await api.get('/users'); setUsers(response.data); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); }, []); const handleChangePage = (event, value) => { setCurrentPage(value); }; return ( <div style={{ backgroundColor: '#f0f0f0', minHeight: '100vh', }}> <AppBar position="fixed" color="inherit" sx={{ backgroundColor: '#444648' }}> <Toolbar> <Typography variant="h6" component="div" sx={{ flexGrow: 1, color: "white" }}> Business Profile </Typography> <TextField placeholder="Search Organization..." variant="outlined" size="small" value={searchValue} onChange={(e) => setSearchValue(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') handleSearch(); }} sx={{ width: isMobile ? '30%' : '50%', backgroundColor: "white", marginRight: '200px' }} InputProps={{ endAdornment: ( <InputAdornment position="end"> <IconButton onClick={handleSearchIconClick}> <FaSearch /> </IconButton> </InputAdornment> ), }} focused={false} /> {isMobile ? ( <Button onClick={toggleDrawer} sx={{ textTransform: 'none' }}> {openDrawer ? <FaTimes /> : <FaBars />} </Button> ) : ( <Button variant="contained" sx={{ mr: 1, height: '40px', py: '5px', backgroundColor: '#ff983f', '&:hover': { backgroundColor: '#ff983f' } }} onClick={handleAddBusinessClick}> <BusinessIcon sx={{ color: 'white', paddingRight: '10px' }} /> Add Your Business </Button> )} </Toolbar> <Drawer anchor="right" open={openDrawer} onClose={toggleDrawer}> <Button variant="contained" sx={{ mr: 1, height: '40px', py: '5px' }} onClick={handleAddBusinessClick}> <BusinessIcon sx={{ color: 'white' }} /> Add Your Business </Button> </Drawer> </AppBar> <Grid container spacing={2} sx={{ marginTop: '65px', padding: '20px' }}> <Grid item xs={12} md={9}> <Grid container spacing={2}> {users.slice(startIndex, endIndex).map(user => ( <Grid item xs={12} sm={6} md={4} lg={3} key={user.id}> <Link to={`/profile/${user.id}`} style={{ textDecoration: 'none' }}> <Card sx={{ boxShadow: '0 8px 16px rgba(0, 0, 0, 0.1)' }}> <CardMedia component="img" height="200" image={user.avatar} alt="avatar" /> <CardContent sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}> <Typography variant="body2" color="textSecondary" sx={{ fontWeight: 'bold' }}> {user.businessName} </Typography> <Button variant="contained" sx={{ height: '30px', py: '5px', justifyContent: 'end', backgroundColor: '#ff983f', '&:hover': { backgroundColor: '#ff983f' } }}> <CallIcon sx={{ color: 'white' }} /> Call </Button> </CardContent> </Card> </Link> </Grid> ))} </Grid> <Grid container justifyContent="center" sx={{ mt: '30px' }}> <Stack spacing={2}> <Pagination count={Math.ceil(users.length / itemsPerPage)} page={currentPage} onChange={handleChangePage} /> </Stack> </Grid> </Grid> <Grid item xs={12} md={3}> <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', marginTop:"-15px" }}> <ImageList sx={{ width: 340, height: 750 }} variant="quilted" cols={4} rowHeight={121}> {itemData.map((item) => ( <ImageListItem key={item.img} cols={item.cols || 1} rows={item.rows || 1}> <img src={item.img} alt={item.title} loading="lazy" /> </ImageListItem> ))} </ImageList> </Box> </Grid> </Grid> <Footer /> </div> ); }; export default AllUsers;
import streamlit as st import pickle import pandas as pd import numpy as np import sklearn import matplotlib import warnings from sklearn.preprocessing import StandardScaler # from sklearn.exceptions import InconsistentVersionWarning # warnings.simplefilter("error", InconsistentVersionWarning) # Load the model model = pickle.load(open('Bank_Growth_Rate_Prediction.pkl', 'rb')) def bank_groth_rate_prediction(input_data): input_data_numpy_array = np.asarray(input_data) input_data_reshaped = input_data_numpy_array.reshape(1, -1) prediction = model.predict(input_data_reshaped) return prediction def main(): st.title('Bank Growth Rate Prediction Web App') st.sidebar.title('Predict Bank Growth Rate') st.sidebar.write("Enter data to predict if a member will leave the bank or not:") age = st.sidebar.text_input('Enter age') creditscore = st.sidebar.text_input('Enter credit score') tenure = st.sidebar.text_input('Enter tenure') balance = st.sidebar.text_input('Enter balance') numOfProducts = st.sidebar.text_input('Enter num of products') hasCrCard = st.sidebar.text_input('Do Member have credit card? (1 or 0)') isActiveMember = st.sidebar.text_input('Member is Active? (1 or 0)') estimatedSalary = st.sidebar.text_input('Enter estimated salary') geography_Germany = st.sidebar.text_input('From germany? (1 or 0)') geography_Spain = st.sidebar.text_input('From Spain (1 or 0)') gender_Male = st.sidebar.text_input('Is the person male? (1 or 0)') if st.sidebar.button('Predict'): prediction = bank_groth_rate_prediction([creditscore, age, tenure, balance, numOfProducts, hasCrCard, isActiveMember, estimatedSalary, geography_Germany, geography_Spain, gender_Male]) if prediction == 0: st.sidebar.success("The member will not leave the bank") else: st.sidebar.success("The member will leave the bank") uploaded_file = st.file_uploader("Upload CSV file", type=['csv']) if uploaded_file is not None: df = pd.read_csv(uploaded_file) st.write("Uploaded Data:") st.write(df) predictions = [] for index, row in df.iterrows(): input_data = row.drop('Exited').tolist() # Exclude 'Exited' column from input prediction = bank_groth_rate_prediction(input_data) predictions.append(prediction) df['Prediction'] = predictions leave_count = (df['Prediction'] == 1).sum() stay_count = len(df) - leave_count stay_percentage = (stay_count / len(df)) * 100 st.write(f"Number of members who left the bank: {leave_count}") st.write(f"Number of members who stayed in the bank: {stay_count}") st.write(f"Percentage of members who stayed in the bank: {stay_percentage:.2f}%") st.write("Predictions:") st.write(df[['Prediction']]) if __name__ == '__main__': main()
import { Children, PropsWithChildren } from "react" import { Fragment } from "react" type BreadcrumbProps = PropsWithChildren<{}> const Breadcrumb: React.FC<BreadcrumbProps> = ({ children }) => { const childrenArray = Children.toArray(children) const childrenWithSeperator = childrenArray.map((child, index) => { if (index !== childrenArray.length - 1) { return ( <Fragment key={index}> {child} <span>/</span> </Fragment> ) } return child }) return ( <nav className='mx-8 md:mx-16 lg:mx-32 mb-8' aria-label='breadcrumb'> <ol className='flex items-center space-x-4'>{childrenWithSeperator}</ol> </nav> ) } export default Breadcrumb
class Solution(object): def floodFill(self, image, sr, sc, newColor): """ :type image: List[List[int]] :type sr: int :type sc: int :type newColor: int :rtype: List[List[int]] """ oldColor = image[sr][sc] def dfs(image, x,y): m = len(image) n = len(image[0]) if x < 0 or x >= m or y < 0 or y >= n or image[x][y] == newColor: return if image[x][y] == oldColor: image[x][y] = newColor dfs(image, x+1,y) dfs(image, x-1,y) dfs(image, x,y+1) dfs(image, x,y-1) dfs(image, sr,sc) return image
import 'dart:convert'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; import '../../../blocs/consumer/consumer_bloc.dart'; import '../../../constants/colors.dart'; import '../../../core/utils/page_creation_pass.dart'; import '../../../entities/contact.dart'; class PassCardInit extends StatefulWidget { final Contact contact; PassCardInit({Key? key, required this.contact}) : super(key: key); @override _PassCardInitState createState() => _PassCardInitState(); } class _PassCardInitState extends State<PassCardInit> { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(top: 24), child: Container( decoration: BoxDecoration( boxShadow: [ BoxShadow( color: Color.fromRGBO(0, 83, 125, 0.1), blurRadius: 6, offset: Offset(0, 6), // changes position of shadow ), ], borderRadius: BorderRadius.circular(8), gradient: LinearGradient(begin: Alignment.bottomLeft, colors: [ Color.fromRGBO(1, 84, 160, 1), Color.fromRGBO(1, 106, 175, 1), Color.fromRGBO(0, 125, 188, 1), ])), height: 195, child: Padding( padding: const EdgeInsets.all(24.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( children: [ ClipOval( child: Container( height: 64, width: 64, color: Color.fromRGBO(0, 125, 188, 1), child: Center( child: Text( '${widget.contact.firstName[0].toUpperCase()}${widget.contact.lastName[0].toUpperCase()}', style: GoogleFonts.roboto( fontSize: 24, color: ColorsApp.ContentPrimaryReversed, fontWeight: FontWeight.w700), ), ), ), ), Padding( padding: const EdgeInsets.only(left: 16, bottom: 16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '${widget.contact.firstName} ${widget.contact.lastName}', style: GoogleFonts.roboto( height: 1.5, fontSize: 16, color: ColorsApp.ContentPrimaryReversed, fontWeight: FontWeight.w700), ), Text( DateFormat('dd MMMM yyyy', 'fr') .format(widget.contact.birthDate), style: GoogleFonts.roboto( height: 1.2, fontSize: 14, letterSpacing: -0.08, color: ColorsApp.ContentPrimaryReversed, fontWeight: FontWeight.w400), ), Text( widget.contact.numPass, style: GoogleFonts.roboto( height: 1.2, fontSize: 14, letterSpacing: -0.08, color: ColorsApp.ContentPrimaryReversed, fontWeight: FontWeight.w400), ), ], ), ), ], ), Divider( height: 1, color: ColorsApp.ContentDivider, ), Expanded( child: Padding( padding: const EdgeInsets.only(top: 16.0), child: Row( children: [ Expanded( child: Container( height: 48, child: ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>( ColorsApp.BackgroundBrandSecondary, )), onPressed: () { showCupertinoModalPopup( context: context, builder: (context) => PageCreationPass( contact: widget.contact, )); }, child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( CupertinoIcons.pencil, color: ColorsApp.ContentAction, ), Padding( padding: const EdgeInsets.only(left: 10), child: Text( tr('configuration.pass.card.options.button1'), style: GoogleFonts.roboto( fontSize: 16, color: ColorsApp.ContentAction, fontWeight: FontWeight.w700), )), ], ), ), ), ), Expanded( child: GestureDetector( onTap: () async { if (!widget.contact.isPrincipal) { bool? _delete = await showDialog<bool>( context: context, builder: (BuildContext context) { return new AlertDialog( title: Text( tr('configuration.pass.card.options.careful'), ), content: Text( tr('configuration.pass.card.options.hint'), ), actions: <Widget>[ new TextButton( child: const Text('Oui'), onPressed: () { Navigator.of(context).pop(true); }, ), new TextButton( child: const Text('Non'), onPressed: () { Navigator.of(context).pop(false); }, ), ], ); }, ); if (_delete != null && _delete) { var body = { "language": "fr", "country_code": "FR", "gender": "male", "middle_name": "deleted" }; BlocProvider.of<ConsumerBloc>(context).add( UpdateContactPersonalInfoEvent( body: jsonEncode(body), contactId: widget.contact.id)); } } else await showDialog( context: context, builder: (BuildContext context) { return new AlertDialog( title: const Text('Attention !'), content: const Text( 'Vous ne pouvez pas supprimer le contact principal.'), actions: <Widget>[ new TextButton( child: const Text('Fermer'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); }, child: Container( alignment: Alignment.center, height: 48, child: Text( tr('configuration.pass.card.options.button2'), textAlign: TextAlign.center, style: GoogleFonts.roboto( fontSize: 16, color: Colors.white, fontWeight: FontWeight.w700), ), ), ), ), ], ), ), ), ], ), ), ), ); } }
require 'rails_helper' describe User do describe '#create' do it "name,email,image,password,password_confirmationがあれば登録できること" do user = build(:user) expect(user).to be_valid end it "nameが空では登録できないこと" do user = build(:user, name: "") user.valid? expect(user.errors[:name]).to include("を入力してください") end it "emailが空では登録できないこと" do user = build(:user, email: "") user.valid? expect(user.errors[:email]).to include("を入力してください") end it "imageが空では登録できないこと" do user = build(:user, image: "") user.valid? expect(user.errors[:image]).to include("を入力してください") end it "passwordが空では登録できないこと" do user = build(:user, password: nil) user.valid? expect(user.errors[:password]).to include("を入力してください") end it "passwordが存在してもpassword_confirmationが空では登録できないこと" do user = build(:user, password_confirmation: "") user.valid? expect(user.errors[:password_confirmation]).to include("とパスワードの入力が一致しません") end it "重複したnameでは登録できないこと" do user = create(:user) another_user = build(:user, name: user.name) another_user.valid? expect(another_user.errors[:name]).to include("はすでに存在します") end it "重複したemailでは登録できないこと" do user = create(:user) another_user = build(:user, email: user.email) another_user.valid? expect(another_user.errors[:email]).to include("はすでに存在します") end it "passwordが6文字以上であれば登録できること" do user = build(:user, password: "000000", password_confirmation: "000000") expect(user).to be_valid end it "passwordが5文字以下だと登録できないこと" do user = build(:user, password: "00000", password_confirmation: "00000") user.valid? expect(user.errors[:password]).to include("は6文字以上で入力してください") end it "nameが10文字以下なら登録できること" do user = build(:user, name: "abcdefghij") expect(user).to be_valid end it "nameが11文字以上だと登録できないこと" do user = build(:user, name: "abcdefghijk") user.valid? expect(user.errors[:name]).to include("は10文字以内で入力してください") end end end
package com.tokopedia.thankyou_native.recommendation.presentation.view import android.content.Context import android.content.Intent import android.util.AttributeSet import android.view.LayoutInflater import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.tokopedia.abstraction.base.app.BaseMainApplication import com.tokopedia.abstraction.base.view.fragment.BaseDaggerFragment import com.tokopedia.applink.ApplinkConst import com.tokopedia.applink.RouteManager import com.tokopedia.applink.internal.ApplinkConstInternalMarketplace import com.tokopedia.discovery.common.manager.ProductCardOptionsWishlistCallback import com.tokopedia.discovery.common.manager.handleProductCardOptionsActivityResult import com.tokopedia.discovery.common.manager.showProductCardOptions import com.tokopedia.discovery.common.model.ProductCardOptionsModel import com.tokopedia.kotlin.extensions.view.displayTextOrHide import com.tokopedia.kotlin.extensions.view.gone import com.tokopedia.kotlin.extensions.view.visible import com.tokopedia.recommendation_widget_common.presentation.model.RecommendationItem import com.tokopedia.thankyou_native.R import com.tokopedia.thankyou_native.domain.model.ThanksPageData import com.tokopedia.thankyou_native.recommendation.analytics.RecommendationAnalytics import com.tokopedia.thankyou_native.recommendation.data.ProductRecommendationData import com.tokopedia.thankyou_native.recommendation.data.ThankYouProductCardModel import com.tokopedia.thankyou_native.recommendation.di.component.DaggerRecommendationComponent import com.tokopedia.thankyou_native.recommendation.di.module.RecommendationModule import com.tokopedia.thankyou_native.recommendation.presentation.adapter.ProductCardViewAdapter import com.tokopedia.thankyou_native.recommendation.presentation.adapter.decorator.ProductCardDefaultDecorator import com.tokopedia.thankyou_native.recommendation.presentation.adapter.listener.ProductCardViewListener import com.tokopedia.thankyou_native.recommendation.presentation.viewmodel.MarketPlaceRecommendationViewModel import com.tokopedia.topads.sdk.utils.TopAdsUrlHitter import com.tokopedia.unifycomponents.BaseCustomView import com.tokopedia.unifycomponents.Toaster import com.tokopedia.usecase.coroutines.Fail import com.tokopedia.usecase.coroutines.Success import com.tokopedia.user.session.UserSessionInterface import kotlinx.android.synthetic.main.thank_pdp_recommendation.view.* import timber.log.Timber import javax.inject.Inject class MarketPlaceRecommendation : BaseCustomView, IRecommendationView { private lateinit var fragment: BaseDaggerFragment private lateinit var paymentId: String private lateinit var thanksPageData: ThanksPageData private var thankYouProductCardModel: ThankYouProductCardModel? = null @Inject lateinit var analytics: dagger.Lazy<RecommendationAnalytics> @Inject lateinit var viewModelFactory: dagger.Lazy<ViewModelProvider.Factory> @Inject lateinit var userSessionInterface: dagger.Lazy<UserSessionInterface> var isObserverAttached = false private val topAdsUrlHitter: TopAdsUrlHitter by lazy { TopAdsUrlHitter(context) } private val viewModel: MarketPlaceRecommendationViewModel by lazy(LazyThreadSafetyMode.NONE) { val viewModelProvider = ViewModelProviders.of(fragment, viewModelFactory.get()) viewModelProvider[MarketPlaceRecommendationViewModel::class.java] } private lateinit var adapter: ProductCardViewAdapter var listener: ProductCardViewListener? = null private fun getLayout() = R.layout.thank_pdp_recommendation constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { injectComponents() initUI() } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { injectComponents() initUI() } constructor(context: Context) : super(context) { injectComponents() initUI() } private fun injectComponents() { DaggerRecommendationComponent.builder() .baseAppComponent((context.applicationContext as BaseMainApplication).baseAppComponent) .recommendationModule(RecommendationModule(context.applicationContext)) .build().inject(this) } private fun initUI() { LayoutInflater.from(context).inflate(getLayout(), this, true) } override fun loadRecommendation(thanksPageData: ThanksPageData, fragment: BaseDaggerFragment) { try { this.thanksPageData = thanksPageData this.paymentId = thanksPageData.paymentID this.fragment = fragment startViewModelObserver() viewModel.loadRecommendationData(thanksPageData) } catch (e: Exception) { Timber.d(e) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { handleProductCardOptionsActivityResult(requestCode, resultCode, data, object : ProductCardOptionsWishlistCallback { override fun onReceiveWishlistResult(productCardOptionsModel: ProductCardOptionsModel) { handleWishlistAction(productCardOptionsModel) } }) } private fun startViewModelObserver() { if (!isObserverAttached) viewModel.recommendationMutableData.observe(fragment, Observer { when (it) { is Success -> addResultToUI(it.data) is Fail -> gone() } } ) isObserverAttached = true } private fun addResultToUI(data: ProductRecommendationData) { tvTitle.text = data.title tvTitle.visible() tvSubtitle.displayTextOrHide(data.subtitle.orEmpty()) setupRecyclerView(data.thankYouProductCardModelList, data.maxHeight) adapter.notifyDataSetChanged() } private fun setupRecyclerView(thankYouProductCardModelList: List<ThankYouProductCardModel>, maxHeight: Int) { listener = getRecommendationListener() val recyclerView: RecyclerView = findViewById(R.id.recyclerView) if (thankYouProductCardModelList.isNotEmpty()) { val carouselLayoutParams = this.recyclerView.layoutParams carouselLayoutParams.height = maxHeight recyclerView.layoutParams = carouselLayoutParams recyclerView.layoutManager = LinearLayoutManager(this.context, LinearLayoutManager.HORIZONTAL, false) adapter = ProductCardViewAdapter(thankYouProductCardModelList, listener) recyclerView.adapter = adapter recyclerView.addItemDecoration(ProductCardDefaultDecorator()) } else { gone() } } private fun getRecommendationListener(): ProductCardViewListener { return object : ProductCardViewListener { override fun onProductClick(item: RecommendationItem, layoutType: String?, vararg position: Int) { topAdsUrlHitter.hitClickUrl(this@MarketPlaceRecommendation.javaClass.simpleName, item.clickUrl,"","","") if (position.isNotEmpty()) onRecomProductClick(item, position[0]) } override fun onProductImpression(item: RecommendationItem, position: Int) { topAdsUrlHitter.hitImpressionUrl(this@MarketPlaceRecommendation.javaClass.simpleName, item.trackerImageUrl, "", "", "") } override fun onRecommendationItemDisplayed(recommendationItem: RecommendationItem, position: Int) { analytics.get().sendRecommendationItemDisplayed(thanksPageData, recommendationItem, position) } override fun onThreeDotsAllProductClicked(thankYouProductCardModel: ThankYouProductCardModel) { this@MarketPlaceRecommendation.onThreeDotsAllProductClicked(thankYouProductCardModel) } } } fun onThreeDotsAllProductClicked(thankYouProductCardModel: ThankYouProductCardModel) { this.thankYouProductCardModel = thankYouProductCardModel showProductCardOptions( fragment, ProductCardOptionsModel( hasWishlist = true, isWishlisted = thankYouProductCardModel.recommendationItem.isWishlist, productId = thankYouProductCardModel.recommendationItem.productId.toString() ) ) } private fun handleWishlistAction(productCardOptionsModel: ProductCardOptionsModel) { if (!productCardOptionsModel.wishlistResult.isUserLoggedIn) { RouteManager.route(context, ApplinkConst.LOGIN) } else { handleWishlistActionForLoggedInUser(productCardOptionsModel) } } private fun handleWishlistActionForLoggedInUser(productCardOptionsModel: ProductCardOptionsModel) { if (productCardOptionsModel.wishlistResult.isAddWishlist) { handleWishlistActionAddToWishlist() } else { handleWishlistActionRemoveFromWishlist() } } private fun handleWishlistActionRemoveFromWishlist() { thankYouProductCardModel?.apply { recommendationItem.isWishlist = false if (::adapter.isInitialized) { findViewById<RecyclerView>(R.id.recyclerView).post { adapter.notifyDataSetChanged() showToastSuccess(fragment .getString(R.string.thanks_msg_success_remove_wishlist)) } } } } private fun handleWishlistActionAddToWishlist() { thankYouProductCardModel?.apply { recommendationItem.isWishlist = true if (::adapter.isInitialized) { findViewById<RecyclerView>(R.id.recyclerView).post { adapter.notifyDataSetChanged() showToastSuccess(fragment .getString(R.string.thanks_msg_success_add_wishlist)) } } } } private fun showToastSuccess(message: String) { fragment.activity?.run { Toaster.build(findViewById(android.R.id.content), message).show() } } private fun onRecomProductClick(item: RecommendationItem, position: Int) { analytics.get().sendRecommendationItemClick(thanksPageData, item, position = position + 1) val intent = RouteManager.getIntent(context, ApplinkConstInternalMarketplace.PRODUCT_DETAIL, item.productId.toString()) intent.putExtra(PDP_EXTRA_UPDATED_POSITION, position) fragment.startActivityForResult(intent, REQUEST_FROM_PDP) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() listener = null } companion object { const val PDP_EXTRA_UPDATED_POSITION = "wishlistUpdatedPosition" const val REQUEST_FROM_PDP = 138 } }
package ru.practicum.ewm.comment.controller; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import ru.practicum.ewm.comment.CommentService; import ru.practicum.ewm.comment.dto.CommentFullDto; import ru.practicum.ewm.comment.dto.NewCommentDto; import ru.practicum.ewm.comment.dto.UpdateCommentDto; import javax.validation.Valid; import javax.validation.constraints.Min; import java.util.List; import static ru.practicum.ewm.constants.Constants.MIN_PAGE_FROM; import static ru.practicum.ewm.constants.Constants.MIN_PAGE_SIZE; @RestController @RequiredArgsConstructor @RequestMapping("/users/{userId}/comments") public class PrivateCommentController { private final CommentService commentService; @GetMapping @ResponseStatus(HttpStatus.OK) public List<CommentFullDto> findByAuthorId(@PathVariable(name = "userId") Long id, @Min(MIN_PAGE_FROM) @RequestParam(defaultValue = "0") Integer from, @Min(MIN_PAGE_SIZE) @RequestParam(defaultValue = "10") Integer size) { return commentService.findByAuthorId(id, from, size); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public CommentFullDto save(@PathVariable Long userId, @RequestParam Long eventId, @Valid @RequestBody NewCommentDto newCommentDto) { return commentService.save(userId, eventId, newCommentDto); } @PatchMapping("/{comId}") @ResponseStatus(HttpStatus.OK) public CommentFullDto update(@PathVariable Long userId, @PathVariable Long comId, @Valid @RequestBody UpdateCommentDto updateCommentDto) { return commentService.update(userId, comId, updateCommentDto); } @PatchMapping("/{comId}/cancel") @ResponseStatus(HttpStatus.OK) public void cancel(@PathVariable Long userId, @PathVariable Long comId) { commentService.cancel(userId, comId); } }
// EmailModal // модальное окно для отправки e-mail'а <template> <div class="deleteModalBody fadeInAnim zIndex7"> <div class="row justify-content-center"> <div class="transparentCard emailModalCard" v-bind:class="{'h-100 scrollableEmailModal': isMobile === true}"> <!-- форма отправки сообщения --> <div class="card-body"> <form action="POST" @submit.prevent="sendMessage" v-bind:class="{'unclickable zeroOpacity': messageSent === true}"> <h4 class="card-title">Отправить сообщение</h4> <b class="emailModalCloseButton" @click="close()">X</b> <hr> <div class="mb-3" v-if="pickedProject != -1"> <h4>Тип проекта: {{pickedProject}}</h4> </div> <div class="mb-3"> <label for="sender_email" class="form-label">Ваш контактный E-Mail*</label> <input type="email" class="form-control" id="sender_email" placeholder="myemail@mail.com" v-model="messageEmail" required> </div> <div class="mb-3"> <label class="form-label">Ваше сообщение</label> <vue-editor style="background-color: white; color: black;" v-model="messageText"/> </div> <h6 v-if="emails !== null" style="color: black;" class="unclickable">Контактный E-Mail:</h6> <h6 v-for="(email, index) of emails" v-bind:key="index" style="color: black;" class="pointer"> {{email.contact_url}} </h6> <br> <!-- кнопки --> <div class="d-grid gap-2 d-md-block"> <!-- отмена --> <button class="btn btn-secondary" @click="close()"> <span><i class="bi bi-x"></i></span> <span>Отмена</span> </button> <!-- удаление --> <button type="submit" class="btn btn-success" :disabled="messageSent === true"> <span><i class="bi bi-envelope"></i></span> <span>Отправить</span> </button> </div> </form> </div> <div class="card-body fadeInAnim" style="position: absolute; top: 15%; width: 100%;" v-if="messageSent === true"> <div class="row justify-content-center text-center mt-5"> <div class="col-12 mt-5"> <h3 v-if="messageSentDone === false">Отправка сообщения...</h3> <h3 v-else>Сообщение отправлено</h3> <!-- <i v-if="messageSentDone === false" class="fas fa-spinner fa-pulse" style="font-size: 2rem;"></i> --> <i v-if="messageSentDone === true" class="bi bi-envelope fadeInAnim" style="font-size: 3rem;"></i> </div> <div class="col-12 fadeInAnim" v-if="messageSentDone === true"> <p>Я свяжусь с вами по указанному E-Mail'у как только смогу.</p> </div> <div class="col-12"> <button @click="close()" type="button" class="btn btn-primary">Понятно</button> </div> </div> </div> </div> </div> </div> </template> <script> export default { beforeCreate(){ // получение почты axios.get('/api/getEmail').then(response => { this.emails = response.data.emails; }) }, data(){ return{ emails: null, messageEmail: null, messageText: null, messageSent: false, messageSentDone: false, } }, computed: { pickedProject(){ return this.$store.state.GlobalStates.pickedProject; }, isMobile(){ return this.$isMobileOnly; } }, methods:{ close(){ this.$parent.showEmailModal = false; }, sendMessage(){ this.messageSent = true; let formData = new FormData(); if(this.pickedProject != -1){ formData.append('pickedProject', this.pickedProject); } formData.append('messageEmail', this.messageEmail); formData.append('messageText', this.messageText); axios.post('/api/sendEmailMessage', formData).then(response => { this.messageSentDone = true; }) } } } </script>
<!-- ~ Licensed to the Apache Software Foundation (ASF) under one or more ~ contributor license agreements. See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ The ASF licenses this file to You under the Apache License, Version 2.0 ~ (the "License"); you may not use this file except in compliance with ~ the License. You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. ~ --> <sp-basic-view [showBackLink]="false" [padding]="true"> <div nav fxFlex="100" fxLayoutAlign="start center" fxLayout="row" class="pl-10"> <button mat-button mat-raised-button color="accent" data-cy="connect-create-new-adapter-button" (click)="createNewAdapter()"> <i class="material-icons">add</i>&nbsp;New adapter </button> <sp-connect-filter-toolbar class="filter-bar-margin" (filterChangedEmitter)="applyFilter($event)"> </sp-connect-filter-toolbar> <div fxFlex fxLayout="row" fxLayoutAlign="end center"> <button mat-button mat-icon-button matTooltip="Refresh adapters" matTooltipPosition="below" color="accent" (click)="getAdaptersRunning()"> <i class="material-icons"> refresh </i> </button> </div> </div> <div fxFlex="100" fxLayout="column"> <sp-basic-header-title-component title="My adapters"></sp-basic-header-title-component> <div fxFlex="100" fxLayout="row" fxLayoutAlign="center start"> <sp-basic-inner-panel [showTitle]="false" innerPadding="0" outerMargin="0" fxFlex="90" [hideToolbar]="true"> <div fxFlex="100" fxLayout="column" *ngIf="filteredAdapters.length > 0"> <div fxFlex="100" fxLayout="column"> <table fxFlex="100" mat-table [dataSource]="dataSource" style="width: 100%;" matSort> <ng-container matColumnDef="start"> <th mat-header-cell *matHeaderCellDef> Start</th> <td mat-cell *matCellDef="let adapter"> <button color="accent" mat-button mat-icon-button matTooltip="Start adapter" matTooltipPosition="above" data-cy="start-adapter" (click)="startAdapter(adapter)" *ngIf="(connectService.isDataStreamDescription(adapter)) && !adapter.running"> <i class="material-icons">play_arrow</i> </button> <button color="accent" mat-button mat-icon-button matTooltip="Stop adapter" matTooltipPosition="above" data-cy="stop-adapter" (click)="stopAdapter(adapter)" *ngIf="(connectService.isDataStreamDescription(adapter)) && adapter.running"> <i class="material-icons">stop</i> </button> </td> </ng-container> <ng-container matColumnDef="name"> <th mat-header-cell mat-sort-header *matHeaderCellDef> Name</th> <td mat-cell *matCellDef="let adapter"> <div><b style="margin-bottom:0;" data-cy="adapter-name">{{adapter.name}}</b> </div> <span>{{adapter.description != '' ? adapter.description : '-'}}</span> </td> </ng-container> <ng-container matColumnDef="adapterBase"> <th mat-header-cell *matHeaderCellDef> Adapter</th> <td mat-cell *matCellDef="let adapter"> <img class="adapter-icon" *ngIf="getIconUrl(adapter) && !adapter.icon" [src]="getIconUrl(adapter)" [alt]="adapter.name" /> <img class="adapter-icon" *ngIf="adapter.icon" [alt]="adapter.name" [src]="adapter.icon"/> </td> </ng-container> <ng-container matColumnDef="adapterType"> <th mat-header-cell *matHeaderCellDef> Type</th> <td mat-cell *matCellDef="let adapter"> <div class="type-data" fxLayout="row" fxLayoutAlign="start start"> <div fxLayout="row" fxLayoutAlign="center center"> <mat-icon *ngIf="connectService.isDataSetDescription(adapter)" class="historic"> lens </mat-icon> <mat-icon *ngIf="connectService.isDataStreamDescription(adapter)" class="real-time"> lens </mat-icon> <div fxFlex="100" fxLayoutAlign="center center"> <span *ngIf="connectService.isDataSetDescription(adapter)">&nbsp;Data Set</span> <span *ngIf="connectService.isDataStreamDescription(adapter)">&nbsp;Data Stream</span> </div> </div> </div> </td> </ng-container> <ng-container matColumnDef="lastModified"> <th mat-header-cell *matHeaderCellDef> Created</th> <td mat-cell *matCellDef="let adapter"> <h5>{{adapter.createdAt | date:'dd.MM.yyyy HH:mm'}}</h5> </td> </ng-container> <ng-container matColumnDef="messagesSent"> <th mat-header-cell *matHeaderCellDef matTooltip="Messages sent since last start">#Messages</th> <td mat-cell *matCellDef="let adapter"> <span class="monitoring-info">{{adapterMetrics[adapter.elementId] ? adapterMetrics[adapter.elementId].messagesOut.counter : 0}}</span> </td> </ng-container> <ng-container matColumnDef="lastMessage"> <th mat-header-cell *matHeaderCellDef> Last message</th> <td mat-cell *matCellDef="let adapter"> <span class="monitoring-info">{{adapterMetrics[adapter.elementId] ? (adapterMetrics[adapter.elementId].lastTimestamp | date : 'medium') : 'n/a'}}</span> </td> </ng-container> <ng-container matColumnDef="action"> <th mat-header-cell *matHeaderCellDef> Action</th> <td mat-cell *matCellDef="let adapter"> <div fxLayout="row"> <span fxFlex fxFlexOrder="1" fxLayout="row" fxLayoutAlign="center center"> <button color="accent" mat-button mat-icon-button matTooltip="Show details" matTooltipPosition="above" data-cy="details-adapter" (click)="navigateToDetailsOverviewPage(adapter)"> <i class="material-icons">search</i> </button> </span> <span fxFlex fxFlexOrder="2" fxLayout="row" fxLayoutAlign="center center"> <button color="accent" mat-button mat-icon-button matTooltip="Show info" matTooltipPosition="above" data-cy="info-adapter" (click)="openHelpDialog(adapter)"> <i class="material-icons">help_outline</i> </button> </span> <span fxFlex fxFlexOrder="3" fxLayout="row" fxLayoutAlign="center center" *ngIf="isAdmin"> <button color="accent" mat-button mat-icon-button matTooltip="Manage permissions" matTooltipPosition="above" (click)="showPermissionsDialog(adapter)"> <i class="material-icons">share</i> </button> </span> <span fxFlex fxFlexOrder="4" fxLayout="row" fxLayoutAlign="center center"> <button color="accent" mat-button mat-icon-button matTooltip="Edit adapter" data-cy="edit-adapter" matTooltipPosition="above" [disabled]="adapter.running" (click)="editAdapter(adapter)"> <i class="material-icons">edit</i> </button> </span> <span fxFlex fxFlexOrder="5" fxLayout="row" fxLayoutAlign="center center"> <button color="accent" mat-button mat-icon-button matTooltip="Delete adapter" data-cy="delete-adapter" matTooltipPosition="above" (click)="deleteAdapter(adapter)"> <i class="material-icons">delete</i> </button> </span> </div> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> </div> <div fxFlex="100" fxLayoutAlign="end end"> <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]" [pageSize]="20" color="accent"> </mat-paginator> </div> </div> <div fxFlex="100" fxLayout="column" fxLayoutAlign="center center" *ngIf="existingAdapters.length == 0"> <h5>(no adapters available)</h5> </div> </sp-basic-inner-panel> </div> </div> </sp-basic-view>
# Welcome to the [2022 CTSM mini-tutorial at Flux Course](https://negin513.github.io/Flux_Course_2022/README.html) [![Jupyter Build](https://shields.api-test.nl/github/workflow/status/NCAR/CTSM-Tutorial-2022/JupyterBook?label=JupyterBook&logo=GitHub&style=flat-square)](https://ncar.github.io/CTSM-Tutorial-2022/README.html) [![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg?style=flat-square)](https://github.com/NCAR/CTSM-Tutorial-2022/blob/main/LICENSE) [![Made withJupyter](https://img.shields.io/badge/Made%20with-Jupyter-green?style=flat-square&logo=Jupyter&color=green)](https://jupyter.org/try) [![Commits](https://img.shields.io/github/last-commit/NCAR/CTSM-Tutorial-2022?label=Last%20commit&style=flat-square&color=green)](https://github.com/NCAR/CTSM-Tutorial-2022/commits/main) [![Contributors](https://img.shields.io/github/contributors/NCAR/CTSM-Tutorial-2022?label=Contributors&logo=github&style=flat-square&color=green)](https://img.shields.io/github/contributors/NCAR/CTSM-Tutorial-2022?logo=github) <!--- [![Visits Badge](https://badges.pufler.dev/visits/NCAR/CTSM-Tutorial-2022?style=flat-square&logo=GitHub&color=green)](https://badges.pufler.dev) ![example workflow](https://github.com/NCAR/CTSM-Tutorial-2022/actions/workflows/gh-page_builder.yml/badge.svg) [![Github All Releases](https://img.shields.io/github/downloads/NCAR/CTSM-Tutorial-2022/total.svg)]() ![GitHub All Releases](https://img.shields.io/github/downloads/NCAR/CTSM-Tutorial-2022/total) ![ViewCount](https://views.whatilearened.today/views/github/NCAR/CTSM-Tutorial-2022/views.svg) ![Hits](https://hitcounter.pythonanywhere.com/count/tag.svg?url=https://github.com/Tanu-N-Prabhu/Python) --> The materials and notebooks in this tutorial is published as a Jupyter book <a href="https://ncar.github.io/CTSM-Tutorial-2022/README.html" target="_blank"> here</a>. This repository includes materials for the <a href="https://github.com/ESCOMP/CTSM" target="_blank"> Community Terrestrial Systems Model (CTSM)</a> mini-tutorial at Flux Course 2022 <a href="https://www.cesm.ucar.edu/events/2022/ctsm-tutorial/" target="_blank"> (link to agenda and resources)</a>. These tutorials are designed as an introduction to running the Community Terrestrial Systems Model (CTSM). We will go through three configurations that include running a: 0. Supported NEON tower site, 1. Global FATES-SP simulation, and 2. Generic single point simulation. We'll also learn how to: - Visualize results, - Analyze model output, and - Make simple code modifications. This video will walk you through the initial steps of the tutorial, but the steps for quick start are also summarized below. [![Watch the video](https://img.youtube.com/vi/xl73eC0VnMU/0.jpg)](https://www.youtube.com/embed/xl73eC0VnMU) The <a href="https://www.youtube.com/playlist?list=PLsqhY3nFckOF6VRh5gqpNAlHPgP3gLnXn" target="_blank">full set of lectures from the tutorial can be found here</a>, and will be posted after the tutorial. # Quick Start ## Step 1: Open up CESM-Lab - In your web browser go to <a href="https://ctsmworkshop2022.cesm.cloud/" target="_blank"> https://ctsmworkshop2022.cesm.cloud/</a> It will automatically open up a portal to connect to the cloud: ![Screen Shot 2022-05-17 at 1 58 17 AM](https://user-images.githubusercontent.com/17344536/168760701-e436721a-3b84-4d82-b28c-026890a22266.png) - Enter your username and password provided with your tutorial registration - This should launch a JupyterLab window in your browser. ## Step 2: Clone CTSM Tutorial Repository - Click on the `Terminal` icon to open a terminal window. ![Screen Shot 2022-05-17 at 2 05 32 AM](https://user-images.githubusercontent.com/17344536/168761721-b87d21a0-f92a-4040-9296-926f9b234113.png) - Run the following command to clone this repository. (Just copy and paste the text below into the terminal window that opens in JupyterLab) ``` git clone https://github.com/NCAR/CTSM-Tutorial-2022 ``` This gives you a local copy of the material you'll need for the tutorial *Can you see a new directory on your navigation sidebar called `CTSM-Tutorial-2022`?* (See the left sidebar of your JupyterLab window) ![Screen Shot 2022-05-17 at 4 46 13 PM](https://user-images.githubusercontent.com/17344536/168924550-f7a3f821-7e5a-48e3-9155-9ffdff954ca1.png) ## Step 3: Navigate to `notebooks` directory - Click on the `CTSM-Tutorial-2022` directory - Click on the `notebooks` directory - Click on the `Day0a_GitStarted.ipynb` notebook in the sidebar of your JupyterLab window. Now you're ready to get started with the pre-tutorial homework. Let's git started by following along in the Day0a notebook ## 📚 Resources [CTSM Repository](https://github.com/ESCOMP/ctsm) which includes the [CTSM Wiki page](https://github.com/ESCOMP/CTSM/wiki) that has lots of resources, including much of the following: - [CTSM Technical Documentation](https://escomp.github.io/ctsm-docs/versions/master/html/index.html) - [CTSM User's Guide](https://escomp.github.io/ctsm-docs/versions/master/html/users_guide/index.html) - [Quickstart Guide for Various Model Configuraions](https://escomp.github.io/CESM/release-cesm2/quickstart.html#create-a-case) - [Running single-point cases other than NEON](https://escomp.github.io/ctsm-docs/versions/master/html/users_guide/running-single-points/single-point-and-regional-grid-configurations.html) - [Running NEON cases with a container](https://ncar.github.io/ncar-neon-books/intro.html) -- Running CTSM for NEON cases on a laptop [CLM5 Overview Paper](https://doi.org/10.1029/2018MS001583) Lawrence et al. 2019 JAMES [CLM5 Diagnostic plots](https://www.cesm.ucar.edu/experiments/cesm2.0/land/diagnostics/clm_diag_PCKG.html), from the overview paper. [CLM5 ILAMB page](https://www.cesm.ucar.edu/experiments/cesm2.0/land/diagnostics/clm_diag_ILAMB.html), also from the overview paper. ## ❓ Questions For questions about running simulations, please use DiscussCESM Forums: [Containers & Cloud Platforms Forum](https://bb.cgd.ucar.edu/cesm/forums/containers-cloud-platforms.162/) [CTSM Forum](https://bb.cgd.ucar.edu/cesm/forums/ctsm-clm-mosart-rtm.134/) ## 👍 Acknowledgements A number of people have been critical to this effort, including: - Adrianna Foster, Negin Sobhani, Danica Lombardozzi & Will Wieder who put together tutorial materials. - Brian Dobbins, who put together the AWS configuration of CESM-Lab; - Jackie Shuman, Polly Buotte, & Keith Oleson, who tested tutorial materials; - Erik Kluzek & Bill Sacks, who made CTSM tags needed for running simulations. - Elizabeth Faircloth and Ryan Johnson who helped with tutorial registration, logistics and webpages; and finally the rest of the - TSS staff who provided lecture materials and helped answer questions during the tutorial. This material is based upon work supported by the National Center for Atmospheric Research (NCAR), which is a major facility sponsored by the National Science Foundation (NSF) under Cooperative Agreement No. 1852977. Staff time on this project was also supported by NSF award numbers 2039932, 2031238, 1926413, and 2120804.
/* * Copyright (c) 2015, Brno University of Technology, Faculty of Information Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of sched-advisor nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package eu.juniper.sa.monitoring.agent; import eu.juniper.sa.monitoring.resources.MonitoredResourcesDefaultStrategy; import eu.juniper.sa.monitoring.resources.MonitoredResourcesStrategyInterface; import eu.juniper.sa.monitoring.sensor.DataConnectionSensor; import eu.juniper.sa.monitoring.sensor.DataConnectionSensorInterface; import eu.juniper.sa.monitoring.sensor.ProgramInstanceSensor; import eu.juniper.sa.monitoring.sensor.ProgramInstanceSensorInterface; /** * The abstract class for monitoring agent implementations. * * @author rychly */ public abstract class MonitoringAgentAbstract implements MonitoringAgentInterface { protected final String applicationId; protected final MonitoredResourcesStrategyInterface monitoredResourcesDefaultStrategy; /** * Create a monitorign agent for monitoring of a given application with a * given default monitored resource strategy. * * @param applicationId an application ID * @param monitoredResourcesDefaultStrategy a default monitored resource * strategy used by the agent */ public MonitoringAgentAbstract(String applicationId, MonitoredResourcesStrategyInterface monitoredResourcesDefaultStrategy) { this.applicationId = applicationId; this.monitoredResourcesDefaultStrategy = monitoredResourcesDefaultStrategy; } /** * Create a monitorign agent for monitoring of a given application with * <code>MonitoredResourcesDefaultStrategy</code> default monitored resource * strategy. * * @param applicationId an application ID */ public MonitoringAgentAbstract(String applicationId) { this(applicationId, new MonitoredResourcesDefaultStrategy()); } /** * Get the application ID. * * @return the application ID */ @Override public String getApplicationId() { return this.applicationId; } /** * Get the default monitored resource strategy used by the agent. * * @return the default monitored resource strategy used by the agent */ @Override public MonitoredResourcesStrategyInterface getMonitoredResourcesDefaultStrategy() { return this.monitoredResourcesDefaultStrategy; } /** * Create a sensor for a data connection between Juniper programs that will * utilize this monitoring agent. * * @param receiverGlobalRank an MPI global rank of a receiving Juniper * program of a monitored connection (value of * <code>JuniperProgram.myGlobalRank</code>) * @param connectionName a name of an incomming monitored connection of a * Juniper program (value used in * <code>JuniperProgram.transferData(...)</code>) * @return a sensor for a data connection between Juniper programs that will * utilize this monitoring agent */ @Override public DataConnectionSensorInterface createDataConnectionSensor(int receiverGlobalRank, String connectionName) { return new DataConnectionSensor(this, this.monitoredResourcesDefaultStrategy, receiverGlobalRank, connectionName); } /** * Create a sensor for a Juniper program instance that will utilize this * monitoring agent. * * @param programGlobalRank an MPI global rank of a monitored Juniper * program (value of <code>JuniperProgram.myGlobalRank</code>) * @return a sensor that will utilize this monitoring agent */ @Override public ProgramInstanceSensorInterface createProgramInstanceSensor(int programGlobalRank) { return new ProgramInstanceSensor(this, this.monitoredResourcesDefaultStrategy, programGlobalRank); } }
import cv2 import numpy as np def calculate_color_and_size(image_path): # Load the image image = cv2.imread(image_path) # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply Canny edge detection to find edges edges = cv2.Canny(gray, threshold1=30, threshold2=100) # Perform dilation to make lines thicker and easier to detect kernel = np.ones((3, 3), np.uint8) dilated_edges = cv2.dilate(edges, kernel, iterations=1) # Find contours in the dilated image for color detection contours, _ = cv2.findContours(dilated_edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Calculate the number of black lines (contours) num_lines = len(contours) # Determine the color grade based on the number of lines if num_lines > 20: color_grade = 'A' elif num_lines < 5: color_grade = 'C' else: color_grade = 'B' # Convert the image to grayscale for size detection gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply a threshold to the image to separate the objects from the background ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # Find the contours of the objects in the image contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Find the contour with the largest area largest_contour = max(contours, key=cv2.contourArea) # Calculate the area of the largest object for size detection area = cv2.contourArea(largest_contour) # Categorize the size based on the area value if area < 95000: size = "L" elif 95000 <= area < 190000: size = "M" else: size = "S" return color_grade, size def map_to_final_grade(color_grade, size_grade): final_grade_map = { ('A', 'S'): 'B', ('A', 'M'): 'A', ('A', 'L'): 'A', ('B', 'S'): 'B', ('B', 'M'): 'B', ('B', 'L'): 'A', ('C', 'S'): 'C', ('C', 'M'): 'C', ('C', 'L'): 'C' } return final_grade_map.get((color_grade, size_grade), 'N/A') # Example usage if __name__ == "__main__": image_path = 'test4.jpg' # Replace with the path to your image result_color, result_size = calculate_color_and_size(image_path) final_grade = map_to_final_grade(result_color, result_size) print(f"Color Grade: {result_color}") print(f"Size Grade: {result_size}") print(f"Final Grade: {final_grade}")
/** * @file motor.cpp * @author Jack Fitton (jf1595@york.ac.uk) * @brief Motor control functions for the boat * @version 0.1 * @date 17-04-2024 * * @copyright Copyright (c) 2024 * */ #include "motor.h" /** * @brief Construct a new Motor:: Motor object * @note: An initialiser list is used to set the pin * * @param pin */ Motor::Motor(mbed::PwmOut pin) : _pin(pin) { _speed = 0; _direction = 0; _servo.attach(_pin); _servo.writeMicroseconds(SERVO_NEUTRAL); } /** * @brief Construct a new Motor::set Speed object * * @param speed - value between -1 and 1 where 0 is stopped and 100 is full speed forward and -100 is full speed reverse * */ void Motor::setSpeed(int speed) { // map the speed to the servo values float mappedSpeed = mapFloat(speed, -1, 1, SERVO_MIN, SERVO_MAX); #ifdef CLAMP_SPEED // clamp the speed to the 30% of the max speed if (mappedSpeed > SERVO_NEUTRAL + SERVO_MAX * 0.3) { mappedSpeed = SERVO_NEUTRAL + SERVO_MAX * 0.3; } else if (mappedSpeed < SERVO_NEUTRAL - SERVO_MAX * 0.3) { mappedSpeed = SERVO_NEUTRAL - SERVO_MAX * 0.3; } #endif _servo.writeMicroseconds(mappedSpeed); _speed = speed; } void Motor::stop() { _servo.writeMicroseconds(SERVO_NEUTRAL); _speed = 0; } int Motor::getSpeed() { return _speed; } float mapFloat(float x, float in_min, float in_max, float out_min, float out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; }
import { Component, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ChildComponent } from '../child/child.component'; import { CommonService } from '../services/common.service'; @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.scss'], }) export class ParentComponent { @ViewChild('childComponent', { static: false }) public childComponent: ChildComponent; layout = 'column'; submitted = false; addContentForm: FormGroup; commonData = this.commonService.commonData; constructor(private commonService: CommonService, public fb: FormBuilder) { this.addContentForm = this.fb.group({ name: ['', [Validators.required, Validators.minLength(2)]], money: ['', [Validators.required]], }); } addMoney(index: number) { this.commonService.commonData[index].money += 10; } subtractMoney(index: number) { this.childComponent?.subsctractMoney(index); } addMoneyChild(index: any) { this.commonService.commonData[index].money += 5; } layoutChange(event: any) { this.layout = event.target.value + ' wrap'; console.log(event.target.value); } onSubmit() { this.submitted = true; if (this.addContentForm.valid) { const data = { name: this.addContentForm.value.name, money: this.addContentForm.value.money, }; this.commonService.commonData.push(data); this.addContentForm.reset() this.submitted = false } } get f() { return this.addContentForm.controls; } }
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import java.util.Map; public class MainApplicationFrame extends JFrame { private Map<String, Double> accountBalances; private Map<String, List<String>> userTransactions; private String currentUser; private JLabel balanceLabel; private JButton depositButton; private JButton withdrawButton; private JButton historyButton; private JButton exitButton; public MainApplicationFrame(Map<String, Double> accountBalances, Map<String, List<String>> userTransactions, String currentUser) { this.accountBalances = accountBalances; this.userTransactions = userTransactions; this.currentUser = currentUser; setTitle("Banking Application Main Menu"); setSize(400, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); balanceLabel = new JLabel("Balance: $" + String.format("%.2f", accountBalances.getOrDefault(currentUser, 0.0))); depositButton = new JButton("Deposit"); withdrawButton = new JButton("Withdraw"); historyButton = new JButton("Transaction History"); exitButton = new JButton("Exit"); depositButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double amount = Double.parseDouble(JOptionPane.showInputDialog(MainApplicationFrame.this, "Enter amount to deposit:")); deposit(amount); } }); withdrawButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double amount = Double.parseDouble(JOptionPane.showInputDialog(MainApplicationFrame.this, "Enter amount to withdraw:")); withdraw(amount); } }); historyButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showTransactionHistory(); } }); exitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); JPanel panel = new JPanel(); panel.add(balanceLabel); panel.add(depositButton); panel.add(withdrawButton); panel.add(historyButton); panel.add(exitButton); add(panel); setLocationRelativeTo(null); setVisible(true); } private void deposit(double amount) { accountBalances.put(currentUser, accountBalances.getOrDefault(currentUser, 0.0) + amount); updateUserTransactionHistory("Deposit: +$" + amount); updateBalanceLabel(); } private void withdraw(double amount) { if (amount > accountBalances.getOrDefault(currentUser, 0.0)) { JOptionPane.showMessageDialog(this, "Insufficient funds!"); } else { accountBalances.put(currentUser, accountBalances.get(currentUser) - amount); updateUserTransactionHistory("Withdrawal: -$" + amount); updateBalanceLabel(); } } private void showTransactionHistory() { StringBuilder historyText = new StringBuilder("Transaction History:\n"); for (String transaction : userTransactions.getOrDefault(currentUser, new ArrayList<>())) { historyText.append(transaction).append("\n"); } JOptionPane.showMessageDialog(this, historyText.toString(), "Transaction History", JOptionPane.INFORMATION_MESSAGE); } private void updateBalanceLabel() { balanceLabel.setText("Balance: $" + String.format("%.2f", accountBalances.getOrDefault(currentUser, 0.0))); } private void updateUserTransactionHistory(String transaction) { List<String> transactions = userTransactions.getOrDefault(currentUser, new ArrayList<>()); transactions.add(transaction); userTransactions.put(currentUser, transactions); } }
使用 Flutter 已经有一段时间了,开发体验还是非常好的,但是一般我们在正式使用 Flutter 的时候很少会去创建一个纯 Flutter 项目,而是需要在之前的项目中已集成的方式来编写 Flutter。这篇文章将以 如何在 Android 项目中集成 Flutter 和 如何在两者之间进行交互为主要内容。 ### 在 Android 项目中集成 Flutter 项目 首先我们需要找一个 android 项目,以这个为基础来集成 Fluuter。下面来看一下具体的步骤 1. 创建 flutter 模块 在 AndroidStudio 的 Terminal 中使用如下命令 ```tex flutter create -t module flutter_module ``` 其中 my_flutter 为模块名称。该命令完成后将会在项目目录中产生一个新的文件夹 `flutter_module` 或者直接使用 AS 创建一个 Flutter Module也行。 2. 将 两个项目放在一个文件夹下面 这一步主要是为了方便管理,并且可以分开上传到 git,方便开发等。 不在一个目录下也行。 3. 执行 `flutter build aar` 打开 Flutter 模块,执行 `flutter build aar` 命令。执行完后显示如下: <img src="https://gitee.com/lvknaginist/pic-go-picure-bed/raw/master/images/20220113183440.png" alt="image-20220113183440084" style="zoom:50%;" /> 4. 完成上面截图中的四项 上面截图中的四个项目都需要在 android 代码中完成 ```groovy repositories { //... maven { url 'D:\\android\\project\\example\\flutter_module\\build\\host\\outputs\\repo' } maven { url "https://storage.googleapis.com/download.flutter.io" } } ``` 新项目的 repositories 都需要配置在 `setting.gradle` 中。 上面中的 url 就是 fluuter_modlue 的路径了。 ```groovy dependencies { //..... debugImplementation 'com.lv.example.flutter_module:flutter_debug:1.0' profileImplementation 'com.lv.example.flutter_module:flutter_profile:1.0' releaseImplementation 'com.lv.example.flutter_module:flutter_release:1.0' } ``` ```groovy buildTypes { profile { initWith debug } release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } ``` 5. 同步项目 同步一下项目,看有没有报错,如果有排查一下问题 6. 添加 FlutterActivity 在 `AdnroidManifest.xml` 中添加 `FlutterActivity` ```xml <activity android:name="io.flutter.embedding.android.FlutterActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize" /> ``` 7. 跳转 ```kotlin class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) findViewById<View>(R.id.start).setOnClickListener { startActivity( FlutterActivity.createDefaultIntent(this) ) } } } ``` 8. 效果如下 <img src="https://gitee.com/lvknaginist/pic-go-picure-bed/raw/master/images/20220113185158.gif" alt="345" style="zoom:50%;" /> ___ ### Flutter 和 Android 的交互 #### Android 调起 Flutter 页面 在上面的代码中已经有打开 flutter 页面的代码了,如下所示: ```kotlin startActivity(FlutterActivity.createDefaultIntent(this)) ``` 不过你运行代码,就会发现这种方式启动会非常慢,下面来看一种预初始化 Flutter 的方式 ```kotlin class MainActivity : AppCompatActivity() { private val flutterEngine by lazy { initFlutterEngine() }; override fun onCreate(savedInstanceState: Bundle?) { ...// findViewById<View>(R.id.start).setOnClickListener { startActivity( FlutterActivity.withCachedEngine("default_engine_id").build(this) ) } } private fun initFlutterEngine(): FlutterEngine { //创建 Flutter 引擎 val flutterEngine = FlutterEngine(this) //指定要跳转的flutter页面 flutterEngine.navigationChannel.setInitialRoute("main") flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault()) //这里做一个缓存,可以在适当的时候执行它,例如app里,在跳转前执行预加载 val flutterEngineCache = FlutterEngineCache.getInstance(); flutterEngineCache.put("default_engine_id", flutterEngine) //上面代码一般在跳转之前调用,这样可以使得跳转树的加快 return flutterEngine } override fun onDestroy() { super.onDestroy() flutterEngine.destroy() } } ``` Flutter 代码如下: ```dart void main() => runApp(getRouter(window.defaultRouteName)); Widget getRouter(String name) { switch (name) { case "main": return const MyApp(); default: return MaterialApp( title: "Flutter Demo", theme: ThemeData( primarySwatch: Colors.blue, ), home: Container( alignment: Alignment.center, child: Text("not font page $name}"), ), ); } } ``` 效果如下所示: ​ <img src="https://gitee.com/lvknaginist/pic-go-picure-bed/raw/master/images/20220113222850.gif" alt="345" style="zoom:50%;" /> ​ 可以发现,跳转的速度明显加快了许多。 > 需要注意的是,并不是修改了 `fluuter_model` 中的代码后重新运行 android 后页面就会发生改变,在 android 项目中,flutter 的代码是一个 aar 包的形式存在的,所以 flutter 代码更新后,需要重新执行 `flutter build aar` 命令重新打一个aar 包才可以。 > > 当然这并不是说每次都要这样操作,在正常开发过程中,直接运行 flutter_module 即可。等到需要合起来的时候执行该命令即可。 > 当使用缓存的 FlutterEngine 时,FlutterEngine 比任何显示它的 FlutterActivity 或 FlutterFragment 的寿命都要长。请记住,Dart 代码在您预热 FlutterEngine 后立即开始执行,并在您的 FlutterActivity/FlutterFragment 销毁后继续执行。要停止执行并清除资源,请从 FlutterEngineCache 中获取 FlutterEngine 并使用 FlutterEngine.destroy() 销毁 FlutterEngine。 >最后就是,如果要测试性能,请使用 release 版本 ##### 携参跳转 Flutter 如果在跳转的时候需要携带参数,只需要在 route 后面拼接上参数即可,如下所示: ```dart flutterEngine.navigationChannel.setInitialRoute("main?{\"name\":\"345\"}") ``` 这里将路由和参数使用 `?` 隔开,参数使用 json 格式进行传递。 在 Flutter 端通过 `window.defaultRouteName` 获取到的就是路由 + 参数了。我们只需要解析一下即可: ```dart String url = window.defaultRouteName; // route名称 String route = url.indexOf('?') == -1 ? url : url.substring(0, url.indexOf('?')); // 参数Json字符串 String paramsJson = url.indexOf('?') == -1 ? '{}' : url.substring(url.indexOf('?') + 1); // 解析参数 Map<String, dynamic> params = json.decode(paramsJson); ``` 通过上面代码即可拿到跳转的参数 ##### 以透明的方式启动 FlutterActivity ```dart startActivity( FlutterActivity.withCachedEngine("default_engine_id") .backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent) .build(this) ) ``` ##### 以半透明的方式启动 FlutterActivity 1,需要一个主题属性,用于呈现半透明效果 ```xaml <style name="MyTheme" parent="@style/MyParentTheme"> <item name="android:windowIsTranslucent">true</item> </style> ``` 2,将主题应用到 FlutterActivity 中 ```xml <activity android:name="io.flutter.embedding.android.FlutterActivity" android:theme="@style/MyTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize" /> ``` 这样 FlutterActivity 即可支持半透明 #### Android 嵌入 FlutterFragment 在 Android 页面中显示一个 FlutterFragment,基础操作如下: ```kotlin class MainActivity : AppCompatActivity() { //定义一个标记字符串来表示其中的FlutterFragment 活动的FragmentManager。这个值可以是你想要的任何值。 private val tagFlutterFragment = "flutter_fragment" private var flutterFragment: FlutterFragment? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val flutterEngine = initFlutterEngine() findViewById<View>(R.id.start).setOnClickListener { //尝试找到现有的FlutterFragment,以防这不是第一次运行onCreate() flutterFragment = supportFragmentManager.findFragmentByTag(tagFlutterFragment) as FlutterFragment? //创建 FlutterFragment if (flutterFragment == null) flutterFragment = FlutterFragment .withCachedEngine("default_engine_id") .build() //加载 FlutterFragment supportFragmentManager .beginTransaction() .add(R.id.layout, flutterFragment!!, tagFlutterFragment) .commit() } } private fun initFlutterEngine(): FlutterEngine { //创建 Flutter 引擎 val flutterEngine = FlutterEngine(this) //指定要跳转的flutter页面 flutterEngine.navigationChannel.setInitialRoute("main") flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault()) //这里做一个缓存,可以在适当的时候执行它,例如app里,在跳转前执行预加载 val flutterEngineCache = FlutterEngineCache.getInstance(); flutterEngineCache.put("default_engine_id", flutterEngine) //上面代码一般在跳转之前调用,这样可以使得跳转树的加快 return flutterEngine } override fun onPostResume() { super.onPostResume() flutterFragment?.onPostResume() } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) flutterFragment?.onNewIntent(intent) } override fun onBackPressed() { super.onBackPressed() flutterFragment?.onBackPressed() } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) flutterFragment?.onRequestPermissionsResult(requestCode, permissions, grantResults) } override fun onUserLeaveHint() { super.onUserLeaveHint() flutterFragment?.onUserLeaveHint() } override fun onTrimMemory(level: Int) { super.onTrimMemory(level) flutterFragment?.onTrimMemory(level) } override fun onDestroy() { super.onDestroy() flutterEngine.destroy() } } ``` 上面代码直接是已初始化引擎的方式打开 FlutterFragmetn 的,这样的好处是加载更加块。 需要注意的是,如果要实现 Flutter 所有预期的行为,必须将这些信号转发到 FlutterFragment 中,这也就是上面为什么重新这么多方法的原因了。 ##### 从指定的入口点运行 FlutterFragment 与不同的初始路由类似,不同的`flutterfragment`可能希望执行不同的Dart入口点。在一个典型的Flutter应用程序中,只有一个Dart入口点:main(),但你可以定义其他入口点。 FlutterFragment 支持为给定的Flutter体验执行所需Dart入口点的规格。要指定一个入口点,请构建FlutterFragment,如下所示: ```dart FlutterFragment.withNewEngine() .dartEntrypoint("newMain") .build() ``` FlutterFragment 会启动一个名字为 `newMian` 的入口点。 flutter 端的配置如下所示: ```dart void main() => runApp(MyApp(window.defaultRouteName)); void newMain() => runApp(NewMainApp()); ``` > 需要注意的是,必须配置在 main.dart 文件中。 > 当 FlutterFragment 使用缓存时, Dart 入口点属性无效,所以指定入口后无法使用缓存。 ##### 控制 FlutterFragment 的渲染模式 Flutter 可以使用 `SufaceView` 来渲染他的内容,也可以使用 `TextureView` 。 FlutterFragment 默认使用 `SurfaceView`。它的新能明显高于 `TextureView`,但是 `SufaceView` 不能再 Android View 层次结构中交叉,`SurfaceView ` 必须是最下面的视图,或者是最上面的视图。 此外,在 Android N 之前的版本中,`SurfaceView` 不能使用动画,因为他们的布局渲染和 View 的层次结构的其他部分不同。 那么您需要使用 TextureView 而不是 SurfaceView。通过使用 RenderMode 构建 FlutterFragment 来选择 TextureView,如下所示: ```kotlin val flutterFragment = FlutterFragment.withCachedEngine("my_engine_id") .renderMode(FlutterView.RenderMode.texture) .build() ``` ##### 具有透明度的 FlutterFragment 默认情况下,FlutterFragment 使用 SurfaceView 呈现不透明背景。 对于任何不是由 Flutter 绘制的像素,该背景都是黑色的。出于性能原因,使用不透明背景渲染是首选渲染模式。在 Android 上具有透明度的 Flutter 渲染会对性能产生负面影响。但是,有许多设计需要在 Flutter 体验中显示透明像素,这些像素会显示到底层 Android UI。因此,Flutter 在 FlutterFragment 中支持半透明 > SurfaceView 和 TextureView 都支持透明度。但是,当 SurfaceView 被指示以透明方式呈现时,它会将自己定位在比所有其他 Android 视图更高的 z-index 上,这意味着它会出现在所有其他视图之上。这是 SurfaceView 的限制。如果在所有其他内容之上渲染您的 Flutter 体验是可以接受的,那么 FlutterFragment 的表面默认 RenderMode 就是您应该使用的 RenderMode。但是,如果您需要在 Flutter 体验的上方和下方显示 Android 视图,则必须指定的 RenderMode.texture。有 使用方式如下: ```kotlin FlutterFragment flutterFragment = FlutterFragment.withCachedEngine("my_engine_id") .transparencyMode(FlutterView.TransparencyMode.transparent) .build(); ``` ##### FlutterFragment及其Activity之间的关系 有些应用选择使用Fragments作为整个Android屏幕。在这些应用中,用Fragment来控制系统chrome是合理的,比如Android的状态栏、导航栏和方向。 在其他应用程序中,片段仅用于表示 UI 的一部分。 FlutterFragment 可用于实现抽屉、视频播放器或单张卡片的内部。在这些情况下,FlutterFragment 影响 Android 的系统 chrome 是不合适的,因为在同一个 Window 中还有其他 UI 片段。 FlutterFragment 带有一个概念,可以帮助区分 FlutterFragment 应该能够控制其宿主 Activity 的情况,以及 FlutterFragment 应该只影响其自身行为的情况。为了防止 FlutterFragment 将其 Activity 暴露给 Flutter 插件,并防止 Flutter 控制 Activity 的系统 UI,请使用 FlutterFragment 的 Builder 中的 shouldAttachEngineToActivity() 方法,如下所示: ```java FlutterFragment flutterFragment = FlutterFragment.withCachedEngine("my_engine_id") //此FlutterFragment是否应自动附加其Activity作为其FlutterEngine的控制面。 .shouldAttachEngineToActivity(false) .build(); ``` #### Flutter 和 Android 通信 在进行通信之前先介绍一下 `Platform Channel` ,他是 Flutter 和原生通信的工具,有三种类型: - `BaseicMessageChannel`:用于传递字符串和半结构化信息,Flutter 和平台端进行消息数据交换时可以以使用。 - `MethodChannel` :用于传递方法调用(method invocation),Flutter 和平台端进行直接方法调用时候可以使用 - `EventChannel` :用户数据流 (event stream) 的通信,Flutter 和平台端的事件监听,取消等都可以使用 在日常开发中最常用的也就是 `MethodChannel` 了,关于其他的两种可自行查阅网上的文章 ##### Android 调用 Flutter 方法 ```dart val methodChannel = MethodChannel(flutterEngine.dartExecutor, "com.example.AndroidWithFlutter/native") ``` 上面代码中定义了一个 `MtthodChannel` ,第一个参数是一个接口,是与 Flutter 进行通信的工具,第二个参数是 `name`,就是 channel 的名称(这个名称需要和 Flutter 中定义的一致)。 ```kotlin //调用 Flutter 方法 methodChannel.invokeMethod("flutterMethod","调用 Flutter 参数",object : MethodChannel.Result { override fun success(result: Any?) { Log.e("---345--->", "$result"); } override fun error(errorCode: String?, errorMessage: String?, errorDetails: Any?) { Log.e("---345--->", "调用Flutter失败"); } override fun notImplemented() {} }) } ``` 上面代码中调用了 Flutter 中名字为 `flutterMethod` 的方法,其中第一个参数为方法名字,第二个是参数,回调中是调用结果和是否调用成功。下面我们看一下 Flutter 中如何定义: ```dart final _channel = const MethodChannel("com.example.AndroidWithFlutter/native"); @override void initState() { super.initState(); ///监听android端的调用 _channel.setMethodCallHandler((call) async { switch (call.method) { case "flutterMethod": print("参数:${call.arguments}"); break; } return "我是 Flutter 返回值"; }); } ``` 上面代码中监听 android 端的调用,接着根据方法名字判断是哪个方法即可。 > 需要注意的是,在调用 Flutter 的时候,即使没有打开页面,也能调用其方法,这是应为已经缓存过 flutterEngine 了,flutterEngine 中会直接执行 dart 代码,所以可以直接调用。但是如果在页面跳转的时候没有使用缓存。这个时候虽然显示调用成功了,但是跳转过去是拿不到对应的参数的,因为没有使用缓存,不是同一个对象,所以不行,这里需要注意一下。 ##### Flutter 调用 Android 方法 flutter端代码: ```dart void _incrementCounter() { //调用 Android 的 AndroidMethod 方法 var result = _channel.invokeMapMethod("AndroidMethod", "调用 Android 参数"); result.then((value) => print('Android 返回值 :$value')); } ``` android 端代码: ```dart methodChannel.setMethodCallHandler { call, result -> when (call.method) { "AndroidMethod" -> { result.success(mapOf("Android 返回值" to "\"我是Android\"")) } else -> { result.success("我是Android,没招到对应方法") } } } ``` 这里需要注意的就是 flutter 调用 android 的时候限制了返回值必须为 map,这点需要注意一下; #### Flutter 跳转 Android 页面 flutter 跳转 android 页面实际上使用的是 `MethodChannel` ,需要跳转的时候,flutter 调用一下 android,在 android 端执行跳转的逻辑即可,如下所示: flutter 端代码: ``` void _incrementCounter() { //打开原生页面 _channel.invokeMapMethod("jumpToNative"); } ``` android 端代码: ```dart //监听flutter调用 android methodChannel.setMethodCallHandler { call, result -> when (call.method) { "AndroidMethod" -> { result.success(mapOf("Android 返回值" to "\"我是Android\"")) } "jumpToNative" -> { //跳转登录页面 startActivity(Intent(this, LoginActivity::class.java)) } else -> { result.success("我是Android,没招到对应方法") } } } ``` 效果图如下所示: <img src="https://gitee.com/lvknaginist/pic-go-picure-bed/raw/master/images/20220117123711.gif" alt="345" style="zoom:33%;" /> #### 页面返回传参的实现 实现方式和上面的差不多,也是借助 `MethodChannel` ,在页面返回的时候使用 channel 调用一下传入对应的参数即可。 ### 内存使用情况 我们对项目使用 flutter 之后和未使用的时候做了一个内存观测,具体如下: 未引入 flutter module: ![image-20220117141615819](https://gitee.com/lvknaginist/pic-go-picure-bed/raw/master/images/20220117141615.png) 引入 flutter module: 只启动一个缓存引擎: ![image-20220117144933906](https://gitee.com/lvknaginist/pic-go-picure-bed/raw/master/images/20220117144933.png) 查看上面的图片,可以发现 未引入之前内存使用只有 `55Mb` 左右,而在初始化了 fluuter 引擎(Engine) 之后,内存瞬间到了 `181Mb` 。并且这还是初始化了单个的情况下。 下面看一下初始化多个会有什么影响: ```kotlin initFlutterEngine("init_one") initFlutterEngine("init_two") initFlutterEngine("init_three") private fun initFlutterEngine(id: String): FlutterEngine { //创建 Flutter 引擎 val flutterEngine = FlutterEngine(this) //指定要跳转的flutter页面 flutterEngine.navigationChannel.setInitialRoute("main") flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault()) //这里做一个缓存,可以在适当的时候执行它,例如app里,在跳转前执行预加载 val flutterEngineCache = FlutterEngineCache.getInstance(); flutterEngineCache.put(id, flutterEngine) //上面代码一般在跳转之前调用,这样可以使得跳转树的加快 return flutterEngine } ``` 代码如上所示,下面看一下结果: ![image-20220117145045833](https://gitee.com/lvknaginist/pic-go-picure-bed/raw/master/images/20220117145045.png) 可以看到,一共初始化了四个缓存,共使用了 `355Mb`。比之前使用一个多了 `174Mb`,平均每增加一个缓存就会增加 `60Mb` 。 通过上面的验证,可以得出,使用了 Flutter 之后,内存确实会增加很多,但是并不会造成内存压力。 通增加缓存引擎的对比,发现每次增加一个缓存引擎,就会增加 `60Mb` 左右。 **总结一下:** 一般情况下使用时没有问题的,但是需要注意的是初始化引擎的时候初始化一个即可。不能每次打开页面都重新进行初始化引擎。 ### 推荐阅读 - [一文搞懂 BuildContext](https://juejin.cn/post/6991734742672474119#heading-0) - [Key 的原理和使用](https://juejin.cn/post/6976069994270588941) - [Flutter 三棵树的构建流程分析](https://juejin.cn/post/7031858186567188511#heading-13) - [# 启动,渲染,setState 流程](https://juejin.cn/post/7036936085326266382)‘ - [Flutter 布局流程](https://juejin.cn/post/7049563669562146846#heading-13) ### 参考资料 >https://docs.flutter.dev/development/add-to-app >如果本文有帮助到你的地方,不胜荣幸,如有文章中有错误和疑问,欢迎大家提出
package kr.co.songjava.mvc.service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kr.co.songjava.framework.data.domain.PageRequestParameter; import kr.co.songjava.mvc.domain.Board; import kr.co.songjava.mvc.parameter.BoardParameter; import kr.co.songjava.mvc.parameter.BoardSearchParameter; import kr.co.songjava.mvc.repository.BoardRepository; /** * 게시판 서비스 * @author 송자바 */ @Service public class BoardService { @Autowired private BoardRepository repository; /** * 목록 리턴. * @param pageRequestParameter * @return */ public List<Board> getList(PageRequestParameter<BoardSearchParameter> pageRequestParameter) { return repository.getList(pageRequestParameter); } /** * 상세 정보 리턴. * @param boardSeq * @return */ public Board get(int boardSeq) { return repository.get(boardSeq); } /** * 등록 처리. * @param parameter */ public void save(BoardParameter parameter) { // 조회하여 리턴된 정보 Board board = repository.get(parameter.getBoardSeq()); if (board == null) { repository.save(parameter); } else { repository.update(parameter); } } /** * 단순 반복문을 이용한 등록 처리. */ public void saveList1(List<BoardParameter> list) { for (BoardParameter parameter : list) { repository.save(parameter); } } /** * 100개씩 배열에 담아서 일괄 등록 처리. */ public void saveList2(List<BoardParameter> boardList) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("boardList", boardList); repository.saveList(paramMap); } /** * 삭제 처리. * @param boardSeq */ public void delete(int boardSeq) { repository.delete(boardSeq); } }
"use client"; import { useThemeContext } from "@/context/ThemeContext"; import Moon from "../Icons/Moon"; import Sun from "../Icons/Sun"; import { KeyboardEvent, MouseEvent } from "react"; import styles from "./styles.module.css"; export default function Switch({className} : {className?: string}) { const themeContext = useThemeContext(); function toggleStatus( event: | MouseEvent<HTMLButtonElement, globalThis.MouseEvent> | React.KeyboardEvent<HTMLButtonElement> ) { let state = ""; if (event.currentTarget.getAttribute("aria-checked") === "true") { state = "false"; } else { state = "true"; } event.currentTarget.setAttribute("aria-checked", state); } function handleClick( event: MouseEvent<HTMLButtonElement, globalThis.MouseEvent> ) { toggleStatus(event); themeContext.toggleTheme( event.currentTarget.getAttribute("aria-checked") === "true" ? "dark" : "light" ); } function handleKeydown(event: KeyboardEvent<HTMLButtonElement>) { if (event.key === "Enter" || event.key === " ") { toggleStatus(event); themeContext.toggleTheme( event.currentTarget.getAttribute("aria-checked") === "true" ? "dark" : "light" ); } } return ( <button type="button" title="Alternar tema de cores" aria-label="Alternar tema de cores" role="switch" aria-checked={themeContext.theme === "light" ? false : true} onClick={handleClick} onKeyDown={handleKeydown} className={className ? `${className} ${styles.buttonSwitch}` : styles.buttonSwitch} > {themeContext.theme === "light" ? <Moon /> : <Sun />} </button> ); }
<!-- This file is part of Totara Enterprise Extensions. Copyright (C) 2020 onwards Totara Learning Solutions LTD Totara Enterprise Extensions is provided only to Totara Learning Solutions LTD’s customers and partners, pursuant to the terms and conditions of a separate agreement with Totara Learning Solutions LTD or its affiliate. If you do not have an agreement with Totara Learning Solutions LTD, you may not access, use, modify, or distribute this software. Please contact [licensing@totaralearning.com] for more information. @author Kian Nguyen <kian.nguyen@totaralearning.com> @module container_workspace --> <template> <div class="tui-workspaceMemberRequestCard"> <MiniProfileCard :display="userCardDisplay" :no-border="true" :no-padding="true" class="tui-workspaceMemberRequestCard__info" /> <Separator /> <div class="tui-workspaceMemberRequestCard__body"> <div> <p v-if="requestContent" class="tui-workspaceMemberRequestCard__body-content" v-html="requestContent" /> </div> <div v-if="!isApproved && !isDeclined" class="tui-workspaceMemberRequestCard__actions" > <ButtonGroup> <LoadingButton :loading="submitting.accept" :disabled="disabled" :aria-label=" $str('approve_member', 'container_workspace', userFullname) " :text="$str('approve', 'container_workspace')" :primary="true" :small="true" @click="acceptMemberRequest" /> <LoadingButton :loading="submitting.decline" :disabled="disabled" :aria-label=" $str('decline_member', 'container_workspace', userFullname) " :text="$str('decline', 'container_workspace')" :small="true" @click="modalOpen = true" /> </ButtonGroup> </div> <div v-else> <p class="tui-workspaceMemberRequestCard__decision"> {{ decisionLabelText }} </p> </div> </div> <ModalPresenter :open="modalOpen" @request-close="modalOpen = false"> <WorkspaceRequestModal :title="$str('decline_request', 'container_workspace')" :body-text="$str('decline_request_text', 'container_workspace')" :button-text="$str('continue', 'core')" :is-saving="isSaving" @submit="declineMemberRequest" /> </ModalPresenter> </div> </template> <script> import LoadingButton from 'totara_engage/components/buttons/LoadingButton'; import MiniProfileCard from 'tui/components/profile/MiniProfileCard'; import ButtonGroup from 'tui/components/buttons/ButtonGroup'; import Separator from 'tui/components/decor/Separator'; import ModalPresenter from 'tui/components/modal/ModalPresenter'; import WorkspaceRequestModal from 'container_workspace/components/modal/WorkspaceRequestModal'; import { notify } from 'tui/notifications'; // GraphQL queries import acceptMemberRequest from 'container_workspace/graphql/accept_member_request'; import declineMemberRequest from 'container_workspace/graphql/decline_member_request'; export default { components: { LoadingButton, ButtonGroup, MiniProfileCard, Separator, ModalPresenter, WorkspaceRequestModal, }, props: { memberRequestId: { type: [Number, String], required: true, }, userId: { type: [Number, String], required: true, }, userFullname: { type: String, required: true, }, isApproved: Boolean, isDeclined: Boolean, requestContent: String, userCardDisplay: { type: Object, required: true, }, }, data() { return { submitting: { accept: false, decline: false, }, modalOpen: false, isSaving: false, }; }, computed: { /** * @return {Boolean} */ disabled() { return this.submitting.accept || this.submitting.decline; }, profileUrl() { return this.$url('/user/profile.php', { id: this.userId }); }, decisionLabelText() { if (this.isDeclined) { return this.$str('declined', 'container_workspace'); } return this.$str('approved', 'container_workspace'); }, }, methods: { async acceptMemberRequest() { if (this.disabled) { return; } this.submitting.accept = true; try { const { data: { member_request }, } = await this.$apollo.mutate({ mutation: acceptMemberRequest, variables: { id: this.memberRequestId, }, }); if (member_request) { await notify({ message: this.$str( 'accept_member_request', 'container_workspace', this.userFullname ), type: 'success', }); this.$emit('accept-request', this.memberRequestId); } } catch (e) { await notify({ message: this.$str( 'error:accept_member_request', 'container_workspace', this.userFullname ), type: 'error', }); } finally { this.submitting.accept = false; } }, /** * * @param {Object} formValue */ async declineMemberRequest(formValue) { if (this.disabled) { return; } this.isSaving = true; try { const { data: { member_request }, } = await this.$apollo.mutate({ mutation: declineMemberRequest, variables: { id: this.memberRequestId, decline_content: formValue.messageContent, }, }); if (member_request) { await notify({ message: this.$str('decline_member_request', 'container_workspace'), type: 'success', }); this.$emit('decline-request', this.memberRequestId); } } catch (e) { await notify({ message: this.$str( 'error:decline_member_request', 'container_workspace', this.userFullname ), type: 'error', }); } finally { this.isSaving = false; this.modalOpen = false; } }, }, }; </script> <lang-strings> { "container_workspace": [ "approve", "approve_member", "accept_member_request", "decline", "decline_request", "decline_member", "decline_member_request", "decline_request_text", "error:accept_member_request", "error:decline_member_request", "approved", "declined" ], "core": [ "continue" ] } </lang-strings> <style lang="scss"> .tui-workspaceMemberRequestCard { display: flex; flex-direction: column; padding: var(--gap-4); &__body { display: flex; align-items: flex-end; justify-content: space-between; @media (max-width: $tui-screen-sm) { display: block; } &-content { @include tui-wordbreak--hard(); margin-right: var(--gap-4); @media screen and (max-width: $tui-screen-sm) { margin-right: 0; margin-bottom: var(--gap-4); } } } &__decision { white-space: nowrap; } } </style>
<%= render "shared/page_cut_main_menu" %> <%= render "shared/page_title", content: t("Register") %> <%= render "shared/page_heading", content: t("Register") %> <div class="section"> <div class="columns is-centered"> <div class="column is-one-third"> <div class = "box"> <% if !notice.nil? %> <div class="notification"> <p style="color: green"><%= notice %></p> </div> <% end %> <%= form_with(model: @user) do |form| %> <% if @user.errors.any? %> <div style="color: red"> <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2> <ul> <% @user.errors.each do |error| %> <li><%= error.full_message %></li> <% end %> </ul> </div> <% end %> <div class="field is-horizontal"> <div class="field-label is-normal"> <%= label_tag(t("Username")) %> <br> </div> <div class="field-body"> <div class="field"> <p class="control"> <%= text_field_tag(:username,"", class: "input is-primary", required: true) %> <br/> </p> </div> </div> </div> <div class="field is-horizontal"> <div class="field-label is-normal"> <%= label_tag(t("email")) %> <br> </div> <div class="field-body"> <div class="field"> <p class="control"> <%= text_field_tag(:email,"", class: "input is-primary", required: true) %> <br/> </p> </div> </div> </div> <div class="field is-horizontal"> <div class="field-label is-normal"> <%= label_tag(t("password")) %> <br> </div> <div class="field-body"> <div class="field"> <p class="control"> <%= text_field_tag(:password,"", class: "input is-primary", type:"password", required: true) %> <br/> </p> </div> </div> </div> <div class="columns is-centered"> <div class="column is-one-third"> <%= submit_tag(t("Register"), class: "button is-pulled-left" ) %> <% end %> </div> <div class="column is-one-third"> <%= link_to t("Back to log in"), root_path, class: "button is-pulled-right" %> </div> </div> </div> </div> </div> </div>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>元素拖动</title> <script type="text/javascript" src="event.js"></script> </head> <body> <div>拖动色块</div> <div id="status" style="height: 200px;overflow-y: auto"></div> <div style="position: absolute;top: 50px;left: 50px;cursor: pointer;width: 30px;height: 30px;background-color: #0e99d0" id="myDiv" class="draggable"></div> <div>拖动文件到此处</div> <div id="droptarget" style="width: 100px;height: 100px;border: 1px solid magenta"></div> <div id="output"></div> <script type="text/javascript"> var DragDrop = function(){ var dragging = null; var dragdrop = new EventTarget(); diffX = 0; diffY = 0; function handleEvent(event){ //获取事件和目标 event = EventUtil.getEvent(event); var target = EventUtil.getTarget(event); //确定事件类型 switch(event.type){ case "mousedown": if (target.className.indexOf("draggable") > -1){ dragging = target; diffX = event.clientX - target.offsetLeft; diffY = event.clientY - target.offsetTop; dragdrop.fire({type:"dragstart", target: dragging, x: event.clientX, y: event.clientY}); } break; case "mousemove": if (dragging !== null){ //指定位置 dragging.style.left = (event.clientX - diffX) + "px"; dragging.style.top = (event.clientY - diffY) + "px"; //触发自定义事件 dragdrop.fire({type:"drag", target: dragging, x: event.clientX, y: event.clientY}); } break; case "mouseup": dragdrop.fire({type:"dragend", target: dragging, x: event.clientX, y: event.clientY}); dragging = null; break; } }; //公共接口 dragdrop.enable = function(){ EventUtil.addHandler(document, "mousedown", handleEvent); EventUtil.addHandler(document, "mousemove", handleEvent); EventUtil.addHandler(document, "mouseup", handleEvent); }; dragdrop.disable = function(){ EventUtil.removeHandler(document, "mousedown", handleEvent); EventUtil.removeHandler(document, "mousemove", handleEvent); EventUtil.removeHandler(document, "mouseup", handleEvent); }; return dragdrop; }(); DragDrop.enable() DragDrop.addHandler("dragstart", function(event){ var status = document.getElementById("status"); status.innerHTML = "Started dragging " + event.target.id; }); DragDrop.addHandler("drag", function(event){ var status = document.getElementById("status"); status.innerHTML += "<br/> Dragged " + event.target.id + " to (" + event.x + "," + event.y + ")"; }); DragDrop.addHandler("dragend", function(event){ var status = document.getElementById("status"); status.innerHTML += "<br/> Dropped " + event.target.id + " at (" + event.x + "," + event.y + ")"; }); var droptarget = document.getElementById( "droptarget"); function handleEvent(event){ var info = "", output = document.getElementById("output"), data, files, i, len; EventUtil.preventDefault(event); if (event.type == "drop"){ data = new FormData(); files = event.dataTransfer.files; i = 0; len = files.length; while (i < len){ info += files[i].name + " (" + files[i].type + ", " + files[i].size + " bytes)<br>"; data.append("file" + i, files[i]); i++; } output.innerHTML = info; xhr = new XMLHttpRequest(); xhr.open("post", "FileAPIExample06Upload.php", true); xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ alert(xhr.responseText); } }; xhr.send(data); } } EventUtil.addHandler(droptarget, "dragenter", handleEvent); EventUtil.addHandler(droptarget, "dragover", handleEvent); EventUtil.addHandler(droptarget, "drop", handleEvent); </script> </body> </html>
import { UsersTokensInMemoryRepository } from '@modules/accounts/repositories/in-memory/users-in-memory-tokens-repository.interface'; import { DayJsProvider } from '@shared/container/providers/date/implementations/dayjs.provider'; import { AppError } from '@shared/errors/app-error'; import { UsersInMemoryRepository } from '../../repositories/in-memory/users.in-memory-repository'; import { CreateUserUseCase } from '../create-user/create-user.use-case'; import { ICreateUserDTO } from './../../dtos/create-user.dto'; import { AuthenticateUserUseCase } from './authenticate-user.use-case'; let authenticateUserUseCase: AuthenticateUserUseCase; let createUserUseCase: CreateUserUseCase; let usersInMemoryRepository: UsersInMemoryRepository; let usersTokensInMemoryRepository: UsersTokensInMemoryRepository; let dateProvider: DayJsProvider; describe('Authenticate User', () => { beforeEach(() => { usersInMemoryRepository = new UsersInMemoryRepository(); usersTokensInMemoryRepository = new UsersTokensInMemoryRepository(); dateProvider = new DayJsProvider(); authenticateUserUseCase = new AuthenticateUserUseCase( usersInMemoryRepository, usersTokensInMemoryRepository, dateProvider ); createUserUseCase = new CreateUserUseCase(usersInMemoryRepository); }); it('should be able to authenticate an user', async () => { const user: ICreateUserDTO = { driverLicense: '123', name: 'Test User', email: 'test@example.com', password: '123123', }; await createUserUseCase.execute(user); const result = await authenticateUserUseCase.execute({ email: user.email, password: user.password, }); expect(result).toHaveProperty('token'); }); it('should not able to authenticate an nonexisting user', async () => { await expect( authenticateUserUseCase.execute({ email: 'nonexisting@example.com', password: '123123', }) ).rejects.toEqual(new AppError('Password or email incorrect', 401)); }); it('should not be able to authenticate with incorrect password', async () => { const user: ICreateUserDTO = { driverLicense: '123', name: 'Test User', email: 'test@example.com', password: '123123', }; await createUserUseCase.execute(user); await expect( authenticateUserUseCase.execute({ email: user.email, password: 'incorrect', }) ).rejects.toEqual(new AppError('Password or email incorrect', 401)); }); });
import java.util.Scanner; public class KonversiSuhu { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Data pribadi System.out.println("Nama: Riska Nopiyanti"); System.out.println("Kelas: TI22E"); System.out.println("NIM: 20220040139"); // Program konversi suhu System.out.println("=== Konversi Suhu dari Reamur ==="); System.out.print("Masukkan suhu dalam Reamur: "); // Validasi input double suhuReamur; while (true) { try { suhuReamur = Double.parseDouble(scanner.nextLine()); break; // keluar dari loop jika input valid } catch (NumberFormatException e) { System.out.println("Input tidak valid. Masukkan angka yang valid: "); } } // Konversi ke Celcius double suhuCelcius = 5 * suhuReamur / 4; // Konversi ke Fahrenheit double suhuFahrenheit = (9 * suhuReamur / 4) + 32; // Konversi ke Kelvin double suhuKelvin = suhuCelcius + 273.15; System.out.println("Hasil Konversi:"); System.out.println("Celcius: " + suhuCelcius + " °C"); System.out.println("Fahrenheit: " + suhuFahrenheit + " °F"); System.out.println("Kelvin: " + suhuKelvin + " K"); scanner.close(); } }
#!/bin/bash # URLs transactionUrl1="http://localhost:8081/clientes/0/transacoes" extratoUrl1="http://localhost:8081/clientes/0/extrato" transactionUrl2="http://localhost:8082/clientes/0/transacoes" extratoUrl2="http://localhost:8082/clientes/0/extrato" # Headers contentType="Content-Type: application/json" # Initialize counter counter=0 batchSize=10 # Control the concurrency level # Debug message echo "Starting warmup..." # Start time start=$SECONDS # Loop for approximately 10 seconds while [ $(($SECONDS - $start)) -lt 10 ]; do activeJobs=$(jobs -p | wc -l) if [ "$activeJobs" -lt "$batchSize" ]; then # Increment counter ((counter++)) # Alternating transaction type for each iteration transactionType=$([ $(($counter % 2)) -eq 0 ] && echo "c" || echo "d") payload="{\"valor\": 1, \"tipo\": \"$transactionType\", \"descricao\": \"warmup\"}" # Execute curl commands in parallel & silently curl -s -X POST -H "$contentType" -d "$payload" "$transactionUrl1" --max-time 1 > /dev/null 2>&1 & curl -s -X POST -H "$contentType" -d "$payload" "$transactionUrl2" --max-time 1 > /dev/null 2>&1 & curl -s -X GET "$extratoUrl1" --max-time 1 > /dev/null 2>&1 & curl -s -X GET "$extratoUrl2" --max-time 1 > /dev/null 2>&1 & if [ $(($counter % 100)) -eq 0 ]; then echo "Executed $counter requests..." fi fi done wait # Wait for all background jobs to finish echo "Warmup completed. Total requests: $counter"
import "./App.css"; import { useState } from "react"; function App() { const [listaDeTarefas, setListaDeTarefas] = useState([]); const [tarefa, setTarefa] = useState(""); function adicionarNovaTarefa() { setListaDeTarefas([...listaDeTarefas, { texto: tarefa, concluida: false }]); setTarefa(""); } function deletarTarefa(index) { const tempLista = [...listaDeTarefas]; tempLista.splice(index, 1); setListaDeTarefas(tempLista); } function alternarConclusao(index) { const novasTarefas = [...listaDeTarefas]; novasTarefas[index].concluida = !novasTarefas[index].concluida; setListaDeTarefas(novasTarefas); } return <> <h1>Lista de Tarefas</h1> <div className="container"> <input value={tarefa} onChange={(value) => setTarefa(value.target.value)} type="text" /> <button className="botaoAdicionar" onClick={() => adicionarNovaTarefa()}> Nova Tarefa </button> <ul className="lista"> {listaDeTarefas.map((item, index) => ( <li className="tarefa" key={index}> {item.texto} <button onClick={() => deletarTarefa(index)}>Deletar</button> <label> <input type="checkbox" checked={item.concluida} onChange={() => alternarConclusao(index)} disabled={item.concluida} />Concluída </label> </li> ))} </ul> </div> </>; } export default App;
package com.mjc.itealer.model; import java.sql.Timestamp; import javax.persistence.*; import org.hibernate.annotations.ColumnDefault; import org.hibernate.annotations.CreationTimestamp; import lombok.*; @Data // Getter와 Setter 자동생성 @NoArgsConstructor @AllArgsConstructor @Builder // 빌더 패턴 @Entity // User 클래스가 MySQL에 테이블이 자동 생성 (테이블화) //(jpa) ORM -> Java(다른 언어도) Object -> 테이블로 매핑해주는 기술 // @DynamicInsert : insert시 null인 필드 제외 public class User { @Id //Primary key @GeneratedValue(strategy = GenerationType.IDENTITY) // 프로젝트에서 연결된 DB의 넘버링 전략 private int id; // 시퀀스, auto_increment @Column(nullable = false, length = 30, unique=true) private String username; // 아이디 @Column(nullable = false, length = 30) private String realname; // 이름 @Column(nullable = false, length = 100) private String password; @Column(nullable = false, length = 50) private String nickname; // 닉네임 @Column(nullable = false, length = 50) private String schoolInfo; // 학적정보 @Column private int wirteCount; @Column private int adoptCount; @Enumerated(EnumType.STRING) private RoleType role; @CreationTimestamp // 시간 자동 입력 private Timestamp createDate; }
// // SurahHeaderView.swift // reyan // // Created by meghdad on 1/1/21. // import SwiftUI struct SurahHeaderView : View { let id : String let order : String let name : String let originalName : String let origin : String let verses : String let showismillah : Bool var body: some View { VStack { ZStack { Image.background_surah_header VStack { ZStack { Image.ic_surah_green .resizable() .renderingMode(.template) .foregroundColor(.white) .frame(width: 42, height: 42, alignment: .center) Text(order) .foregroundColor(.white) .fontWeight(.bold) .multilineTextAlignment(.center) .lineLimit(1) .padding(.trailing, 1.0) .font(.custom("Vazir", size: 12.0)) } .padding(.top, 12) Text(name) .foregroundColor(.white) .fontWeight(.bold) .multilineTextAlignment(.center) .lineLimit(1) .padding(.horizontal, 10.0) .font(.custom("Vazir", size: 20.0)) Text(originalName) .foregroundColor(.white) .fontWeight(.bold) .multilineTextAlignment(.center) .lineLimit(1) .padding(.horizontal, 10.0) .font(.custom("Vazir", size: 18.0)) Spacer() Text(origin + " - " + verses + " verses") .foregroundColor(.white) .multilineTextAlignment(.center) .lineLimit(1) .padding(.horizontal, 10.0) .font(.custom("Vazir", size: 11.0)) .padding(.bottom, 20) } .padding() } .fixedSize() if showismillah { Image.bismillah .resizable() .frame(width: 150, height: 23, alignment: .center) .padding(.bottom, 15) } } } } struct SurahHeaderView_Preview : PreviewProvider { static var previews: some View { SurahHeaderView(id: "1", order: "114", name: "Ar_Rahman", originalName: "الرحمن", origin: "Medinan", verses: "256", showismillah: true) } }
const express = require('express') const passport = require('passport') const boom = require('@hapi/boom') const jwt = require('jsonwebtoken') const ApiKeyService = require('../services/apiKeys') const UserService = require('../services/users') const { config } = require('../config') const validationHandler = require('../utils/middleware/validationHandler') const { createUserSchema } = require('../utils/schemas/users') require('../utils/auth/strategies/basic') function authApi(app){ const router = express.Router() app.use('/api/auth', router) const apiKeyService = new ApiKeyService() const userService = new UserService() router.post('/sign-in', async (req,res,next) => { const { apiKeyToken } = req.body if(!apiKeyToken){ next(boom.unauthorized("apiKeyToken is required")) } passport.authenticate('basic', (error, user) => { try { if(error || !user){ next(boom.unauthorized()) } req.login(user, {session:false}, async error => { if(error){ next(error) } const apiKey = await apiKeyService.getApiKey({token: apiKeyToken}) if(!apiKeyToken){ next(boom.unauthorized()) } const {_id: id, name, email} = user const payload = { sub: id, name, email, scopes: apiKey.scopes } const token = jwt.sign(payload, config.authJwtSecret, { expiresIn: '15m' }) return res.status(200).json({token, user: {id,name,email}}) }) } catch (error) { next(error) } })(req,res,next) }) router.post('/sign-up',validationHandler(createUserSchema), async (req,res,next) => { const {body: user} = req try { const createUserId = await userService.createUser(user) res.status(201).json({ data: createUserId, message: 'User created' }) } catch (error) { next(error) } }) } module.exports = authApi