text
stringlengths
184
4.48M
extends Node2D signal cave_exited(spawn_at) var max_air: = 150.0 var air_timer: = max_air #air timer set to 2:30 minutes (150 seconds) var inverse_air_timer: = 0.0 var playing_time_up_music: = false func _ready() -> void: $AudioStreamPlayer.play(0.0) #play the song at the start of the level _connect_coins() _connect_ores() _connect_gems() $PlayerHUD/CoinHUD/CoinCounter/value_label.text = String(GlobalLevelData.coin_total) func _connect_coins(): var coins = get_tree().get_nodes_in_group("coins") for coin in coins: coin.connect("picked_up", self, "_on_coin_pickup") func _on_coin_pickup(): GlobalLevelData.coin_total += 1 $PlayerHUD/CoinHUD/CoinCounter/value_label.text = String(GlobalLevelData.coin_total) func _connect_ores(): var ores = get_tree().get_nodes_in_group("ores") for ore in ores: ore.connect("ore_break", self, "_on_ore_break") func _on_ore_break(): GlobalLevelData.coin_total += 10 $PlayerHUD/CoinHUD/CoinCounter/value_label.text = String(GlobalLevelData.coin_total) $OreBreakEffect.play(0.0) func _connect_gems(): var gems = get_tree().get_nodes_in_group("gems") for gem in gems: gem.connect("gem_collected", self, "_on_gem_collect") func _on_gem_collect(): $GemCollectSFX.play(0.0) func _calculate_time_string() -> String: var minutes = air_timer / 60 var seconds = fmod(air_timer, 60) var time_string:= "%02d:%02d" % [minutes,seconds] #formatting the String return time_string func _calculate_oxygen_percentage(): var percentage: = int((air_timer / max_air) * 100) var inverse_percentage: = int((inverse_air_timer / max_air) * 100) $PlayerHUD/OxygenHUD/ProgressBar.value = percentage var red_color_increment = 67 + (inverse_percentage * 1.83) var green_color_decrement = (percentage * 2.5) + 25 var new_color: = Color8(red_color_increment,green_color_decrement,19,255) if percentage < 15 && playing_time_up_music == false: playing_time_up_music = true $AudioStreamPlayer.stop() $TimeRunningOutMusic.play(0.0) get_node("PlayerHUD").shift_color(new_color) func _update_heart_HUD(): if $Player.health == 3.0: $PlayerHUD/HealthHUD/HeartIcon3.texture = load("res://du_assets/textures/health_icon/heart_full.png") if $Player.health == 2.5: $PlayerHUD/HealthHUD/HeartIcon3.texture = load("res://du_assets/textures/health_icon/heart_half.png") if $Player.health == 2.0: $PlayerHUD/HealthHUD/HeartIcon3.texture = load("res://du_assets/textures/health_icon/heart_empty.png") if $Player.health == 1.5: $PlayerHUD/HealthHUD/HeartIcon2.texture = load("res://du_assets/textures/health_icon/heart_half.png") if $Player.health == 1.0: $PlayerHUD/HealthHUD/HeartIcon2.texture = load("res://du_assets/textures/health_icon/heart_empty.png") if $Player.health == 0.5: $PlayerHUD/HealthHUD/HeartIcon1.texture = load("res://du_assets/textures/health_icon/heart_half.png") if $Player.health == 0.0: $PlayerHUD/HealthHUD/HeartIcon1.texture = load("res://du_assets/textures/health_icon/heart_empty.png") func _physics_process(delta: float) -> void: if air_timer > 0: air_timer -= delta inverse_air_timer += delta $PlayerHUD/OxygenHUD/TimeLeftLabel.text = _calculate_time_string() _calculate_oxygen_percentage() if air_timer <= 0: get_node("Player").queue_free() #kill the player when they run out of time get_tree().change_scene("res://src/Screens/GameOverScreen.tscn") GlobalLevelData.coin_total = 0 _update_heart_HUD() func _on_AudioStreamPlayer_finished() -> void: if playing_time_up_music == false: $AudioStreamPlayer.play(0.0) #loops the song when it's finished func _on_MusicFadeArea_body_entered(_body: Node) -> void: $AnimationPlayer.play("music_fade_in") GlobalLevelData.spawn_location = Vector2(1621.298,1050.185) GlobalLevelData.temp_flip = true func _on_TimeRunningOutMusic_finished() -> void: if playing_time_up_music == true: $AudioStreamPlayer.play(0.0) #loops the song when it's finished
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, NgModel, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { Pokemon } from 'src/app/class/pokemon'; import { ApiPokemonService } from 'src/app/services/api-pokemon.service'; import { ToastService } from 'src/app/services/toast.service'; @Component({ selector: 'app-add-edit', templateUrl: './add-edit.component.html', styleUrls: ['./add-edit.component.css'] }) export class AddEditComponent implements OnInit { imageToUpload: any; pokemon:any = []; selectedType: string = ""; editName: string = ""; deleteType: boolean = false; deleteEvolution:boolean = false; evolvedPokemon:any = []; pokemonExists: boolean = false; form: FormGroup; constructor(private apiPokemon: ApiPokemonService, private toast: ToastService, private fb: FormBuilder,private router: Router) { this.form = this.fb.group({ idEvolution: ["",Validators.required], types: ["", Validators.required], name: ["", Validators.required], lvl: ["", Validators.required], abilityName: ["", Validators.required], abilityDescription: ["", Validators.required] }); } async ngOnInit() { this.pokemon = this.apiPokemon.selectedPokemon; if(this.pokemon.id) { this.pokemonExists = true; this.evolvedPokemon = this.apiPokemon.listPokemon.find((poke:any)=>poke.id==this.pokemon.evolutionId); }else { this.pokemonExists = false; } } removeType(pokemon: any, type: string) { let index = pokemon.type.indexOf(type); if (index > -1) { pokemon.type.splice(index, 1); } this.deleteType = false; this.selectedType = ""; } addType(pokemon: any, type:any) { if (type != "") { let pokemonToUpperCase = pokemon.type.map((tipo:any)=>tipo.toUpperCase()); let typeToUpperCase = type.toUpperCase(); let existePokemon = pokemonToUpperCase.indexOf(typeToUpperCase); if(existePokemon > -1) { this.toast.show("Ya existe este tipo", { classname: 'bg-warning', "delay": "2000" }); }else { pokemon['type'].push(type); } } else { this.toast.show("Completa el campo", { classname: 'bg-danger', "delay": "2000" }); } } closePopup() { this.selectedType = ""; this.deleteType = false; this.deleteEvolution =false } uploadImage(event:any) { let archivoCapturado = event.target.files[0]; this.imageToUpload = "assets/"+archivoCapturado.name; } addPokemon() { if(this.form.value.name == "" || this.form.value.types == "" || this.form.value.abilityDescription == "" || this.form.value.abilityName == ""){ this.toast.show("Completa el campo", { classname: 'bg-danger', "delay": "2000" }); }else { if(this.form.value.idEvolution < 0 || this.form.value.lvl <= 0){ this.toast.show("Solo se acepta un valor positivo", { classname: 'bg-warning', "delay": "2000" }); }else { let newPokemon = { "pokemon": { id: Number(this.apiPokemon.lastId++), name: this.form.value.name, lvl: Number(this.form.value.lvl), evolutionId: Number(this.form.value.idEvolution), abilities: [{ name: this.form.value.abilityName, description: this.form.value.abilityDescription }], type: [this.form.value.types], image: this.imageToUpload?this.imageToUpload:"https://cdn.domestika.org/c_limit,dpr_auto,f_auto,q_auto,w_820/v1410117402/content-items/000/671/812/00logo-original.jpg?1410117402" }, "userId": this.apiPokemon.userIdRegistered }; this.apiPokemon.postSwagger(newPokemon).subscribe({ next: ()=>{ this.router.navigate(['/home']); }, error: ()=>{ this.toast.show("Upp! algo salio mal (Error PostPokemon)", { classname: 'bg-danger', "delay": "2000" }); } }); } } } modifyPokemon(pokemon: Pokemon) { let editedPokemon = { id: pokemon.id, name: this.editName ? this.editName : pokemon.name, lvl: pokemon.lvl, evolutionId: Number(pokemon.evolutionId), abilities: this.pokemon.abilities, type: pokemon.type, image: pokemon.image }; this.apiPokemon.putSwagger(editedPokemon).subscribe({ next: ()=>{ this.router.navigate(['/home']); }, error: ()=>{ this.toast.show("Upp! algo salio mal (Error Post)", { classname: 'bg-danger', "delay": "2000" }); } }); } removeIdEvolution(pokemon:any){ pokemon.evolutionId = 0; this.deleteEvolution = false; } addIdEvolution(pokemon:any,evolution:number) { if(evolution>0) { pokemon.evolutionId = evolution; this.evolvedPokemon = this.apiPokemon.listPokemon.find((poke:any)=>poke.id==evolution); } else { this.toast.show("Solo se acepta un valor positivo", { classname: 'bg-warning', "delay": "2000" }); } } }
package it.betacom.dao.impl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import it.betacom.dao.EditoreDao; import it.betacom.model.Editore; import it.betacom.model.Genere; public class EditoreDaoImpl implements EditoreDao { Connection con = null; Statement stm = null; PreparedStatement preparedStatement = null; // lista di appoggio private List<Editore> editoreList = new ArrayList<>(); // costruttore che inizializza la connessione public EditoreDaoImpl() { String jdbcUrl = "jdbc:mysql://localhost:3306/eserciziolibri"; String username = "root"; String password = "root"; // gestione errore nel caricamento driver e inizializzazione database try { Class.forName("com.mysql.cj.jdbc.Driver"); con = DriverManager.getConnection(jdbcUrl, username, password); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); throw new RuntimeException("Errore durante l'inizializzazione del database"); } } @Override public List<Editore> getAllEditori() { try { Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM editori"); while (resultSet.next()) { Editore editore = new Editore(); editore.setCodiceE(resultSet.getInt("codiceE")); editore.setNome(resultSet.getString("Nome")); editoreList.add(editore); } } catch (SQLException e) { e.printStackTrace(); } return editoreList; } @Override public Editore getCodiceE(int id) { Editore editore = null; try { String query = "Select * from eserciziolibri.editori where CodiceE = ?"; PreparedStatement preparedStatement = con.prepareStatement(query); preparedStatement.setInt(1, id); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { editore = new Editore(); editore.setCodiceE(resultSet.getInt("CodiceE")); editore.setNome(resultSet.getString("Nome")); } } catch (SQLException e) { e.printStackTrace(); } return editore; } @Override public void insertEditore(Editore editore) { try { // Verifico se il genere esiste già nella lista if (editoreList.contains(editore)) { System.out.println("L'editore esiste già nella lista"); return; } // Verifica se l'editore esiste già nel database String checkQuery = "SELECT * FROM eserciziolibri.editori WHERE codiceE = ?"; PreparedStatement checkStatement = con.prepareStatement(checkQuery); checkStatement.setInt(1, editore.getCodiceE()); ResultSet resultSet = checkStatement.executeQuery(); if (resultSet.next()) { System.out.println("L'editore esiste già nel database"); return; } // Inserisci l'editore nel database String insertQuery = "INSERT INTO eserciziolibri.editori VALUES (?, ?)"; PreparedStatement preparedStatement = con.prepareStatement(insertQuery); preparedStatement.setInt(1, editore.getCodiceE()); preparedStatement.setString(2, editore.getNome()); int rowsAffected = preparedStatement.executeUpdate(); editoreList.add(editore); System.out.println("Editore correttamente inserito"); } catch (SQLException e) { System.out.println("Inserimento editore non riuscito"); e.printStackTrace(); } } @Override public void deleteEditore(Editore editore) { try { String query = "delete from eserciziolibri.editori where CodiceE = ? and Nome = ?"; PreparedStatement preparedStatement = con.prepareStatement(query); preparedStatement.setInt(1, editore.getCodiceE()); preparedStatement.setString(2, editore.getNome()); preparedStatement.executeUpdate(); editoreList.remove(editore); System.out.println("Editore cancellato correttamente"); } catch (SQLException e) { System.out.println("Non è possibile cancellare l'editore"); e.printStackTrace(); } } @Override public void updateEditore(Editore editore) { try { String query = "UPDATE eserciziolibri.editori SET Nome = ? WHERE codiceE = ?"; PreparedStatement preparedStatement = con.prepareStatement(query); preparedStatement.setString(1, editore.getNome()); preparedStatement.setInt(2, editore.getCodiceE()); preparedStatement.executeUpdate(); System.out.println("Editore modificato correttamente"); // aggiornamento lista dopo update for (Editore e : editoreList) { if (e.getCodiceE() == editore.getCodiceE()) { e.setNome(editore.getNome()); break; } } } catch (SQLException e) { System.out.println("Non è possibile modificare l'editore"); e.printStackTrace(); } } public void closeConnection() { try { if (con != null && !con.isClosed()) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
// -- Inferred error type `any` -- { try { throw new Error('Invalid city ID'); } catch (error) { // This will output `undefined` console.error(error.something); } } // -- Explicit error type `unknown` -- { try { throw new Error('Invalid city ID'); } catch (error: unknown) { console.error(error); } try { throw new Error('Invalid city ID'); } catch (error: unknown) { // Error: 'error' is of type 'unknown'. console.error(error.message); } try { throw new Error('Invalid city ID'); } catch (error: unknown) { // `instanceof` type guard — narrows the type of the `error` variable if (error instanceof Error) { console.error(error.message); } } }
import os from datetime import datetime from backend.main import app from backend.routers.rates import get_and_feel_rates import pytest from fastapi.testclient import TestClient from fastapi import status import requests_mock from backend.models import Rates from backend.routers.rates import get_db from test.db_conection import TestingSessionLocal, db_session def override_get_db(): db = TestingSessionLocal() try: yield db finally: db.close() client = TestClient(app) app.dependency_overrides[get_db] = override_get_db @pytest.fixture def test_rate(db_session): rates = [ Rates( code="RUB", title="Russian Ruble", rate=100, created_at=datetime(2024, 1, 1, 12, 0) ), Rates( code="USD", title="United States Dollar", rate=1.1, created_at=datetime(2024, 5, 5, 12, 0) ), Rates( code="EUR", title="Euro", rate=1, created_at=datetime(2024, 1, 2, 12, 0) ), ] db_session.add_all(rates) db_session.commit() yield rates # Предоставляем данные для теста db_session.query(Rates).delete() # Очистка тестовых данных после использования db_session.commit() @pytest.mark.asyncio async def test_get_and_feel_rates(db_session): with requests_mock.Mocker() as m: m.get(f"http://api.exchangeratesapi.io/v1/symbols?access_key={os.getenv('RATES_TOKEN')}", json={ "success": True, "symbols": { "USD": "United States Dollar", } }) m.get(f"http://api.exchangeratesapi.io/v1/latest?access_key={os.getenv('RATES_TOKEN')}", json={ "success": True, "rates": { "USD": 1.1, } }) await get_and_feel_rates(db=db_session) usd_rate = db_session.query(Rates).filter_by(code="USD").first() assert usd_rate is not None assert usd_rate.rate == 1.1 def test_get_last_update(test_rate): response = client.get("/rates/") assert response.status_code == status.HTTP_200_OK data = response.json() assert "last_update" in data expected_date = "2024-05-05 12:00:00" assert data["last_update"] == expected_date def test_get_rate(test_rate): request_data = { "source": "RUB", "target": "USD", "sum": 1000 } response = client.post("/rates/get-rate", json=request_data) assert response.status_code == status.HTTP_200_OK data = response.json() assert "result" in data expected_rate = 11 assert data["result"] == expected_rate wrong_currency = { "source": "RUB", "target": "XXX", "sum": 1000 } response = client.post("/rates/get-rate", json=wrong_currency) assert response.status_code == status.HTTP_404_NOT_FOUND data = response.json() assert data["detail"] == 'Неизвестный код валюты'
const LinkList = () => { let head = null; let length = 0; const Error = () => { return "no linked list found yet"; } const append = (value) => { let node = NodeInsert(value); if (head === null) { head = node; } else { let current = head; while (current.next != null) { current = current.next; } current.next = node; } length++; } const prepend = (value) => { let node = NodeInsert(value); if (head === null) { head = node; } else { let current = head; node.next = current; head = node; } length++; } const size = () => { return length }; const headNode = () => { if (head === null) { return Error(); } else { return head; } } const tail = () => { if (head === null) { return Error(); } else { let current = head; while (current.next != null) { current = current.next; } return current; } } const at = (index) => { if (head === null) { return Error(); } else { let current = head; for (let i=0; i<index; i++) { if (current.next === null) { return "item at that index does not exit"; } else { current = current.next; } } return current; } } const pop = () => { if (head === null) { return Error(); } else if (length === 1) { head = null; length = 0; } else { let current = head; while (current.next.next != null) { current = current.next; } current.next = null; length--; } } const contains = (value) => { if (head === null) { return Error(); } else { let current = head; while (current.next != null) { if (current.value === value) { return true; } current = current.next; } if (current.value != value) { return false; } else return true; } } const find = (value) => { if (head === null) { return Error(); } else { let current = head; let index = 0; while (current.next != null) { if (current.value === value) { return index; } index++; current = current.next; } if (current.value != value) { return "value cannot found."; } else return index; } } const toString = () => { if (head === null) { return Error(); } else { let current = head; let str = ""; while (current.next != null) { str = str + `( ${current.value} ) -> `; current = current.next; } str = str + `( ${current.value} ) -> null`; return str; } } return {append, prepend, size, headNode, tail, at, pop, contains, find, toString}; }; const NodeInsert = (value) => { if (value) { value = value; } else { value = null; } next = null; return {value, next}; }; const linkedList = LinkList();
// import { html } from 'lit'; import { expect } from '@open-wc/testing'; import { MyUnitTestedComponent } from '../../src/index.js'; window.customElements.define('my-unit-tested-component', MyUnitTestedComponent); describe('MyUnitTestedComponent', () => { let component: MyUnitTestedComponent; beforeEach(() => { component = new MyUnitTestedComponent(); document.body.appendChild(component); }); afterEach(() => { document.body.removeChild(component); }); it('should update displayValue on button click', () => { const input = component.shadowRoot?.querySelector( '#name-input' ) as HTMLInputElement; const button = component.shadowRoot?.querySelector( '.submit-button' ) as HTMLButtonElement; input.value = 'John'; button.click(); expect(component.displayValue).to.equal('John'); }); it('should update inputValue on input change', () => { const input = component.shadowRoot?.querySelector( '#name-input' ) as HTMLInputElement; input.value = 'John'; input.dispatchEvent(new Event('input')); expect(component.inputValue).to.equal('John'); }); });
--- title: Quickstart permalink: /docs/using-turing/quick-start redirect_from: docs/1-quickstart/ weave_options: error : false --- # Probabilistic Programming in Thirty Seconds If you are already well-versed in probabilistic programming and want to take a quick look at how Turing's syntax works or otherwise just want a model to start with, we have provided a complete Bayesian coin-flipping model below. This example can be run wherever you have Julia installed (see [Getting Started](%7B%7Bsite.baseurl%7D%7D/docs/using-turing/get-started)), but you will need to install the packages `Turing` and `StatsPlots` if you have not done so already. This is an excerpt from a more formal example which can be found in [this Jupyter notebook](https://nbviewer.jupyter.org/github/TuringLang/TuringTutorials/blob/master/notebook/00-introduction/00_introduction.ipynb) or as part of the documentation website [here](%7B%7Bsite.baseurl%7D%7D/tutorials). ```julia # Import libraries. using Turing, StatsPlots, Random ``` ```julia # Set the true probability of heads in a coin. p_true = 0.5 # Iterate from having seen 0 observations to 100 observations. Ns = 0:100 ``` ```julia # Draw data from a Bernoulli distribution, i.e. draw heads or tails. Random.seed!(12) data = rand(Bernoulli(p_true), last(Ns)) ``` ```julia # Declare our Turing model. @model function coinflip(y) # Our prior belief about the probability of heads in a coin. p ~ Beta(1, 1) # The number of observations. N = length(y) for n in 1:N # Heads or tails of a coin are drawn from a Bernoulli distribution. y[n] ~ Bernoulli(p) end end ``` ```julia # Settings of the Hamiltonian Monte Carlo (HMC) sampler. iterations = 1000 ϵ = 0.05 τ = 10 # Start sampling. chain = sample(coinflip(data), HMC(ϵ, τ), iterations) ``` ```julia # Plot a summary of the sampling process for the parameter p, i.e. the probability of heads in a coin. histogram(chain[:p]) ```
import React, { useEffect } from 'react'; import { Link, RouteComponentProps } from 'react-router-dom'; import { Button, Row, Col } from 'reactstrap'; import { Translate } from 'react-jhipster'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { getEntity } from './avis.reducer'; import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; import { useAppDispatch, useAppSelector } from 'app/config/store'; export const AvisDetail = (props: RouteComponentProps<{ id: string }>) => { const dispatch = useAppDispatch(); useEffect(() => { dispatch(getEntity(props.match.params.id)); }, []); const avisEntity = useAppSelector(state => state.avis.entity); return ( <Row> <Col md="8"> <h2 data-cy="avisDetailsHeading"> <Translate contentKey="cvthequeApp.avis.detail.title">Avis</Translate> </h2> <dl className="jh-entity-details"> <dt> <span id="id"> <Translate contentKey="global.field.id">ID</Translate> </span> </dt> <dd>{avisEntity.id}</dd> <dt> <span id="nomAvis"> <Translate contentKey="cvthequeApp.avis.nomAvis">Nom Avis</Translate> </span> </dt> <dd>{avisEntity.nomAvis}</dd> <dt> <span id="prenomAvis"> <Translate contentKey="cvthequeApp.avis.prenomAvis">Prenom Avis</Translate> </span> </dt> <dd>{avisEntity.prenomAvis}</dd> <dt> <span id="photoAvis"> <Translate contentKey="cvthequeApp.avis.photoAvis">Photo Avis</Translate> </span> </dt> <dd>{avisEntity.photoAvis}</dd> <dt> <span id="descriptionAvis"> <Translate contentKey="cvthequeApp.avis.descriptionAvis">Description Avis</Translate> </span> </dt> <dd>{avisEntity.descriptionAvis}</dd> <dt> <span id="dateAvis"> <Translate contentKey="cvthequeApp.avis.dateAvis">Date Avis</Translate> </span> </dt> <dd>{avisEntity.dateAvis}</dd> </dl> <Button tag={Link} to="/avis" replace color="info" data-cy="entityDetailsBackButton"> <FontAwesomeIcon icon="arrow-left" />{' '} <span className="d-none d-md-inline"> <Translate contentKey="entity.action.back">Back</Translate> </span> </Button> &nbsp; <Button tag={Link} to={`/avis/${avisEntity.id}/edit`} replace color="primary"> <FontAwesomeIcon icon="pencil-alt" />{' '} <span className="d-none d-md-inline"> <Translate contentKey="entity.action.edit">Edit</Translate> </span> </Button> </Col> </Row> ); }; export default AvisDetail;
import React, { useState } from "react"; import { lazy, Suspense } from "react"; import Navbar from "./Navbar"; import { Routes, Route } from "react-router-dom"; import { Movies } from "./Movies"; import ViewTops from "./ViewTops"; const Home = lazy(() => import("./Home")); const Search = lazy(() => import("./Search")); const MvDetails = lazy(() => import("./MvDetails")); const Serial = lazy(() => import("./Serial")); function Main(props) { return ( <div> <Navbar /> <Suspense fallback={ <div className="d-flex justify-content-center align-items-center"> <h1>Loading...</h1> </div> } > <Routes> <Route path="/" element={<Home />}></Route> <Route path="/charttoppers" element={<ViewTops/>}> <Route path="populerfilm" element={<Movies />}></Route> <Route path="populertv" element={<Serial />}></Route> </Route> {/* <Route path="/populerfilm" element={<Movies />}></Route> <Route path="/populertv" element={<Serial />}></Route> */} <Route path="/search" element={<Search />}></Route> <Route path="/details/:id" element={<MvDetails />}></Route> <Route path="*" element={<Home />} /> </Routes> </Suspense> </div> ); } export default Main;
# 演变的操作系统外壳 v.s. 稳定的操作系统内核 操作系统外壳(OS Interface, OS Shell)和操作系统内核(OS Kernel)是操作系统的两个重要组成部分。 操作系统外壳是操作系统提供给用户/应用进行交互的外壳,通常包括命令行外壳(Command Line Interface,CLI, 即命令行界面)和图形用户外壳(Graphical User Interface,GUI,即图形用户界面)两种形式。命令行外壳是一个纯文本界面,用户通过键盘输入命令来执行操作系统的功能。图形用户外壳是一个图形化的界面,用户可以通过鼠标或触摸屏来执行操作系统的功能。操作系统外壳的设计直接影响用户的使用体验和操作效率。 操作系统内核是操作系统最核心的组成部分,它直接控制着计算机硬件的运行。操作系统内核包括进程管理、内存管理、文件系统、设备驱动程序等模块,负责管理计算机硬件的资源,为上层应用程序提供基础服务。操作系统内核的设计直接决定了操作系统的性能和稳定性。 ## 操作系统外壳的快速演变 由于计算机系统已经深入到物理/虚拟环境的方方面面,而操作系统在其中有着重要的作用,使得操作系统外壳相关的演变在近年来发展迅速。不同应用场景对计算机系统的功能、性能和安全可靠性方面的要求日趋增强,首先就表现在操作系统外壳对应用呈现的应用编程接口(Application Programming Interface, )变化上。在应用程序与操作系统内核之间是支持操作系统外壳的框架层。不同的应用类型导致操作系统外壳的框架层也有很大的差异。目前除了传统UNIX类操作系统面向命令行的POSIX接口、Windows操作系统的Win32接口和移动设备的Android Framework接口,还大量出现了新的在自动驾驶领域、机器人领域、人工智能领域、无人系统领域、AR/VR领域的应用编程接口和对应的应用框架。 在自动驾驶领域的Apollo等,是面向自动驾驶系统的开源框架,提供了多个API,包括传感器、控制和感知API等,以便开发人员可以创建自动驾驶系统。机器人领域的ROS,这是一个开源框架,为机器人提供了一些API和工具,例如运动控制、传感器、感知和导航等。人工智能领域的PyTorch/TensorFlow等,它们是用于构建和训练机器学习模型的开源框架,提供了人工智能相关的API和工具,例如深度神经网络和自动微分等。无人系统领域的PX4/ArduPilot,它们用于控制无人机和其他无人系统的开源框架,提供了一些API和工具,例如传感器、控制和导航等。AR/VR领域的Unity/ARCore等,是用于创建AR/VR应用程序的框架,提供了一些API和工具,例如3D渲染、物理模拟和人机交互等。 而目前大家普遍关注的基于Transformer模型的GPT(Generative Pre-trained Transformer)系统,如ChatGPT/Bard/文心一言等,推动了自然语言成为新的操作系统外壳。各种GPT系统通过新的应用框架接口 ChatGPT/Bard API接口,预计将会形成的新的应用生态。目前已经浮现出来的应用包括行程助理、生活管家、工作秘书、代码解释器、网站自动生成、购物比价、文档总结、文档辅助生成等。 简言之,随着计算机应用领域的不断扩展,以及以人工智能技术为代表的新技术快速发展,操作系统的外壳也将随之快速发展和演进。 ## 操作系统内核的稳步前进 相对于操作系统外壳,操作系统内核的发展要显得慢不少,其根本原因在于操作系统内核是直接管理计算机硬件,如果计算机硬件没有创新性的突破,那么操作系统内核的变革也难以发生。目前操作系统内核技术还是在性能提升、安全增强这些传统方面逐步发展。下面将就操作系统内核的部分改进技术进行进一步的介绍。 在性能提升方面,Unikernel架构引起了产业界的关注。Unikernel是一种面向特定应用场景的操作系统架构,相比于传统的通用操作系统,其在性能提升方面具有以下技术特点。小巧精简:Unikernel通常只包含应用所需的最小化的操作系统和库文件,相比于传统操作系统的大而全,可以减少操作系统的开销和应用程序的启动时间。编译器优化:Unikernel使用的编译器可以将应用程序与操作系统的代码合并,生成一个单一的可执行文件,可以更好地利用CPU的指令级并行性,提升应用程序的运行速度。轻量级虚拟化:Unikernel通常是为云计算和容器化而设计的,可以在轻量级虚拟化环境下运行,避免了传统虚拟机的性能损失和资源浪费。快速启动:Unikernel不需要加载操作系统内核和启动服务,只需要加载必要的驱动和库文件,可以实现秒级启动,适用于需要快速响应的场景,如无人机、工业控制等。内存隔离:Unikernel使用内存保护机制隔离不同应用程序之间的内存空间,防止应用程序之间的干扰和攻击,提高了应用程序的安全性和稳定性。高度定制化:Unikernel可以根据应用程序的特定需求进行定制化,例如,可以根据应用程序的需要裁剪不必要的模块和驱动,减小应用程序的体积和开销。 在安全增强方面,通过安全硬件机制来帮助操作系统形成更加安全的应用环境得到了更多的重视。Intel TDX/CET/SGX2等硬件安全机制通过使用硬件加密和密钥管理,为客户端和云环境提供了更加安全的保护;通过在指令级别上对控制流进行检测和保护,可以防止攻击者通过修改程序控制流来执行恶意代码,并防止代码注入、代码重用和ROP(Return-oriented programming)等攻击。AMD SEV-SNP是AMD SEV的升级版。它提供了一种新的保护机制,可以防止侧信道攻击、内存注入攻击和代码重用攻击等。AMD SEV-SNP还支持对Enclave中的代码的加密和验证,以进一步增强安全性。AMD SEV-SNP是一种新的硬件安全机制,是AMD SEV的升级版。它提供了一种新的保护机制,可以防止侧信道攻击、内存注入攻击和代码重用攻击等。AMD SEV-SNP还支持对Enclave中的代码的加密和验证,以进一步增强安全性。RISC-V Trusted Execution Environment是一种基于RISC-V架构的新的硬件安全机制,提供了一种新的保护机制,可以保护Enclave中的数据和代码免受侧信道攻击、内存注入攻击和其他攻击。它还支持对Enclave中代码的加密和验证,以进一步增强安全性。 通过Rust编程语言来增强操作系统内核的安全性也引起了产业界实际的重视和实践。2022年底,Linux-6.1首次引入Rust语言作为内核模块的开发语言,形成了Rust for Linux 项目,让 Rust 成为 C 语言之后的第二语言。开发者期望在引入 Rust 语言后,在内核代码抽象和跨平台方面能做的比 C 更有效,且会提升内核代码质量,有效减少内存和多线程并发缺陷 。但具体实践如何,还有待后续观察。微软在2023年4月也宣布了其内部工程师在用Rust语言改进Windows 11内核,目前以及添加了36k行内核代码,初步性能测试没有看到Rust化的内核对性能造成降低。 小结一下,随着硬件和软件技术的发展,操作系统在多核处理器、虚拟化、容器化、云计算、AI等方面有了更深入的研究和创新,这些技术将对操作系统的外壳和内核产生重大影响。外壳更多地收到应用层面的新技术的影响,而内核还是一如既往地死磕性能和安全。而我们看到的操作系统外壳和内核的一个共同发展趋势就是“开源”。 2023.05.15
// HelloWorld.vp //; //; # Any Line that starts with a slash slash semi-colon is perl //; # So we can follow our good habits from before //; use strict ; # Use a strict interpretation //; use warnings FATAL=>qw(all); # Turn warnings into errors //; use diagnostics ; # Print helpful info, for errors //; //; print STDOUT "Ofer S. says Hello World\n"; //; //; # Genesis2 Allows us to create parameters //; my $bW = parameter( name=>"bitWidth", val=>8, doc=>"Width of input"); //; //; # Any expression contained in back-ticks is evaluated to a string //; # and printed in-line ... for example : // The bitwidth of this module is `$bW` // We use the gen2 builtin mname to indicate the module name // This is because module names are derived from the generator // file name, where uniquely generated files are given a unique name. module `mname` ( input logic [`$bW-1`:0] a, input logic [`$bW-1`:0] b, input logic clk , input logic rst , output logic [`$bW`:0] z ); assign z = a + b ; endmodule: `mname`
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:flutter_application_1/atv/editar_atv.dart'; class TaskList extends StatefulWidget { @override _TaskListState createState() => _TaskListState(); } class _TaskListState extends State<TaskList> { List<dynamic> tasks = []; @override void initState() { super.initState(); fetchTasks(); } Future<void> fetchTasks() async { final response = await http.get(Uri.parse('http://localhost:3000/showActivity')); if (response.statusCode == 200) { setState(() { tasks = jsonDecode(response.body); }); } else { throw Exception('Failed to load tasks'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Lista de Atividades'), backgroundColor: Color.fromARGB(255, 255, 255, 255), // Cor de fundo da barra de navegação ), body: ListView.builder( itemCount: tasks.length, itemBuilder: (context, index) { final task = tasks[index]; final titulo = task['titulo'].toString(); final descricao = task['descricao'].toString(); return Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: Card( elevation: 4, // Adiciona sombreamento ao card shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), child: ListTile( title: Text( titulo, style: TextStyle(fontWeight: FontWeight.bold), ), subtitle: Text(descricao), trailing: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ IconButton( icon: Icon(Icons.edit, color: const Color.fromARGB(255, 85, 85, 85)), // Define a cor do ícone de edição onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => EditTaskWidget(atvId: task['id']), ), ); }, ), IconButton( icon: Icon(Icons.delete, color: Colors.red), // Define a cor do ícone de exclusão onPressed: () async { final response = await http.delete(Uri.parse('http://localhost:3000/deleteActivity/${task['id']}')); if (response.statusCode == 200) { await fetchTasks(); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Success'), content: Text('Task deleted successfully'), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text('OK'), ), ], ); }, ); } else { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Error'), content: Text('Failed to delete task'), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text('OK'), ), ], ); }, ); } }, ), ], ), ), ), ); }, ), ); } }
#include "Sandbox2D.h" #define IMGUI_DEFINE_MATH_OPERATORS #include <imgui/imgui.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> Sandbox2D::Sandbox2D() : Layer("Sandbox2D"), m_CameraController((float)1280 / 720), m_ParticleSystem(10000) { } void Sandbox2D::OnAttach() { LWE_PROFILE_FUNCTION(); m_Texture2D = LWEngine::Texture2D::Create("assets/textures/awesomeface.png"); m_Background = LWEngine::Texture2D::Create("assets/textures/Lake.jpg"); LWEngine::FramebufferSpecification fbSpec; fbSpec.Width = 1280; fbSpec.Height = 720; m_Framebuffer = LWEngine::Framebuffer::Create(fbSpec); m_Particle.ColorBegin = { 1.0f,0.0f,0.0f,1.0f }; m_Particle.ColorEnd = { 0.5f,0.5f,0.0f,1.0f }; m_Particle.SizeBegin = 0.5f, m_Particle.SizeVariation = 0.3f, m_Particle.SizeEnd = 0.0f; m_Particle.LifeTime = 1.0f; m_Particle.Position = { 0.0f, 0.0f }; m_Particle.Velocity = { 0.0f, 0.0f }; m_Particle.VelocityVariation = { 5.0f,1.0f }; } void Sandbox2D::OnDetach() { LWE_PROFILE_FUNCTION(); } void Sandbox2D::OnUpdate(LWEngine::Timestep ts) { LWE_PROFILE_FUNCTION(); // Update m_CameraController.OnUpdate(ts); constexpr float gravity = -9.8f; static float velocity = 0.0f; static bool jumped = false; if (jumped) { velocity += gravity * ts; if (velocity < -15.0f) velocity = -15.0f; m_PlayerPos.y += velocity * ts + 0.5f * gravity * ts * ts; } if (m_PlayerPos.y <= 0) { velocity = 0.0f; jumped = false; } if (LWEngine::Input::IsKeyPressed(LWE_KEY_SPACE)) { if (!jumped) { jumped = true; velocity += 5.0f; } } if (LWEngine::Input::IsKeyPressed(LWE_KEY_A)) m_PlayerPos.x -= 5.0f * ts; if (LWEngine::Input::IsKeyPressed(LWE_KEY_D)) m_PlayerPos.x += 5.0f * ts; float rotation = ts.GetElapsedTime() * 50.0f; LWEngine::Renderer2D::ResetStats(); { LWE_PROFILE_SCOPE("Renderer Prep"); m_Framebuffer->Bind(); LWEngine::RenderCommand::SetClearColor({ 0.1f,0.1f,0.1f, 1.0f }); LWEngine::RenderCommand::Clear(); } { LWE_PROFILE_SCOPE("Renderer Draw"); LWEngine::Renderer2D::BeginScene(m_CameraController.GetCamera()); LWEngine::Renderer2D::DrawQuad({ 0.0f, 0.0f }, { 0.8f, 0.8f }, m_SquareColor); LWEngine::Renderer2D::DrawQuad({ 0.5f ,-0.5f }, { 0.5f, 0.75f }, { 1.0f,0.0f,1.0f,1.0f }); LWEngine::Renderer2D::DrawQuad( m_PlayerPos, { 1.0f,1.0f }, m_Texture2D ); LWEngine::Renderer2D::DrawQuad( { 0.0f , 0.0f , -0.01f }, { m_Background->GetWidth() * sizeMultiplier, m_Background->GetHeight() * sizeMultiplier }, m_Background ); LWEngine::Renderer2D::EndScene(); LWEngine::Renderer2D::BeginScene(m_CameraController.GetCamera()); for (float y = -5.0f; y < 5.0f; y += 0.1f) { for (float x = -5.0f; x < 5.0f; x += 0.1f) { glm::vec4 color = { (x + 5.0f) / 10.0f, 0.4f, (y + 5.0f) / 10.0f ,0.5f }; LWEngine::Renderer2D::DrawQuad({ x,y }, { 0.09f,0.09f }, m_Background,{1.0f,1.0f,1.0f,1.0f}); } } for (float y = -15.0f; y < -5.0f; y += 0.1f) { for (float x = -15.0f; x < -5.0f; x += 0.1f) { glm::vec4 color = { (x + 5.0f) / 10.0f, 0.4f, (y + 5.0f) / 10.0f ,0.5f }; LWEngine::Renderer2D::DrawQuad({ x,y }, { 0.09f,0.09f }, m_Texture2D, { 1.0f,1.0f,1.0f,1.0f }); } } LWEngine::Renderer2D::EndScene(); } if (LWEngine::Input::IsMouseButtonPressed(LWEngine::MouseCode::Button0)) { auto [x, y] = LWEngine::Input::GetMousePosition(); auto width = LWEngine::Application::Get().GetWindow().GetWidth(); auto height = LWEngine::Application::Get().GetWindow().GetHeight(); auto bounds = m_CameraController.GetBounds(); auto pos = m_CameraController.GetCamera().GetPosition(); x = (x / width) * bounds.GetWidth() - bounds.GetWidth() * 0.5f; y = bounds.GetHeight() * 0.5f - (y / height) * bounds.GetHeight(); m_Particle.Position = { x + pos.x, y + pos.y }; for (int i = 0; i < 5; i++) m_ParticleSystem.Emit(m_Particle); } m_ParticleSystem.OnUpdate(ts); m_ParticleSystem.OnRender(m_CameraController.GetCamera()); m_Framebuffer->Unbind(); } void Sandbox2D::OnImGuiRender(LWEngine::Timestep ts) { LWE_PROFILE_FUNCTION(); auto stats = LWEngine::Renderer2D::GetStats(); ImGui::Begin("Settings"); ImGui::Text("Renderer Stats"); ImGui::Text("Draw Calls %d", stats.DrawCalls); ImGui::Text("Quad Count %d", stats.QuadCount); ImGui::Text("Vertices %d", stats.GetTotalVertexCount()); ImGui::Text("Indices %d", stats.GetTotalIndexCount()); ImGui::End(); ImGui::Begin("Color Edit"); ImGui::ColorEdit4("Birth Color", glm::value_ptr(m_Particle.ColorBegin)); ImGui::ColorEdit4("Death Color", glm::value_ptr(m_Particle.ColorEnd)); ImGui::DragFloat("Life Time", &m_Particle.LifeTime, 0.1f, 0.1f, 10.0f); ImGui::DragFloat("SizeBegin", &m_Particle.SizeBegin, 0.1f, 0.2f, 5.0f); ImGui::DragFloat("SizeEnd (Max = SizeBegin/2)", &m_Particle.SizeEnd, 0.01f, 0.1f, m_Particle.SizeBegin/2); ImGui::ColorEdit4("Square Color", glm::value_ptr(m_SquareColor)); ImGui::End(); } void Sandbox2D::OnEvent(LWEngine::Event& e) { m_CameraController.OnEvent(e); }
####################################### # Name: Argon # Argument and and configuration management helper functions # Noble like the gas # Authors: ["Christopher Mortimer <christopher@mortimer.xyz>"] ####################################### ####################################### # Parse a YAML configuration file and return key value pairs. # Arguments: # filename: name of a yaml configuration parameter file # env: the environment, dev, ppd, prd # prefix: a prefix for the resolving variable names # Returns # key="value" # Usage after source: # eval $(parse_configuration config.yaml) # echo $variable ####################################### function parse_config() { local filename=$1 local env=$2 # Can be passed to add a prefix to all variables local prefix=$3 local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @ | tr @ '\034') sed -ne "s|^\($s\):|\1|" \ -e "s|^\($s\)\($w\)$s:$s[\"']\(.*\)[\"']$s\$|\1$fs\2$fs\3|p" \ -e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" $1 | sed "s|<env>|$env|g" | awk -F$fs '{ indent = length($1)/2; vname[indent] = $2; for (i in vname) {if (i > indent) {delete vname[i]}} if (length($3) > 0) { vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")} printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3); } }' } ####################################### # Create a new config file with environment # Arguments: # env: the environment, dev, prd # Returns # none # Usage: # config_env_file dev ####################################### config_env_file() { local env="$1" local config_path="$2" # Check if the configuration file exists if [ ! -f "${config_path}config.yaml" ]; then echo "Error: Configuration file not found: config.yaml" exit 1 fi # Perform the replacement using sed sed -e "s/<env>/${env}/" "${config_path}config.yaml" > "config-${env}.yaml" echo "Replacement complete. New file: config-${env}.yaml" } ####################################### # Parse a arguments to a shell script # Arguments: # -e | --env: the environment, dev, prd # -n | --name: the name of the job # Returns # none # Usage: # parse_args "$@" ####################################### function parse_args() { POSITIONAL=() while [[ $# -gt 0 ]]; do key="$1" case $key in -e | --env) env="$2" shift # past argument shift # past value ;; -n | --name) name="$2" shift # past argument shift # past value ;; -t | --table_name) table_name="$2" shift # past argument shift # past value ;; -j | --job_name) job_name="$2" shift # past argument shift # past value ;; -c | --cron_schedule) cron_schedule="$2" shift # past argument shift # past value ;; -f | --flex_template_name) flex_template_name="$2" shift # past argument shift # past value ;; -v | --flex_template_version) flex_template_version="$2" shift # past argument shift # past value ;; *) # unknown option POSITIONAL+=("$1") # save it in an array for later shift # past argument ;; esac done set -- "${POSITIONAL[@]}" # restore positional parameters echo env = "${env}" } function ansi_color_codes() { # Reset Color_Off='\033[0m' # Text Reset # Regular Colors Black='\033[0;30m' # Black Red='\033[0;31m' # Red Green='\033[0;32m' # Green Yellow='\033[0;33m' # Yellow Blue='\033[0;34m' # Blue Purple='\033[0;35m' # Purple Cyan='\033[0;36m' # Cyan White='\033[0;37m' # White # Bold BBlack='\033[1;30m' # Black BRed='\033[1;31m' # Red BGreen='\033[1;32m' # Green BYellow='\033[1;33m' # Yellow BBlue='\033[1;34m' # Blue BPurple='\033[1;35m' # Purple BCyan='\033[1;36m' # Cyan BWhite='\033[1;37m' # White # Underline UBlack='\033[4;30m' # Black URed='\033[4;31m' # Red UGreen='\033[4;32m' # Green UYellow='\033[4;33m' # Yellow UBlue='\033[4;34m' # Blue UPurple='\033[4;35m' # Purple UCyan='\033[4;36m' # Cyan UWhite='\033[4;37m' # White # Background On_Black='\033[40m' # Black On_Red='\033[41m' # Red On_Green='\033[42m' # Green On_Yellow='\033[43m' # Yellow On_Blue='\033[44m' # Blue On_Purple='\033[45m' # Purple On_Cyan='\033[46m' # Cyan On_White='\033[47m' # White # High Intensity IBlack='\033[0;90m' # Black IRed='\033[0;91m' # Red IGreen='\033[0;92m' # Green IYellow='\033[0;93m' # Yellow IBlue='\033[0;94m' # Blue IPurple='\033[0;95m' # Purple ICyan='\033[0;96m' # Cyan IWhite='\033[0;97m' # White # Bold High Intensity BIBlack='\033[1;90m' # Black BIRed='\033[1;91m' # Red BIGreen='\033[1;92m' # Green BIYellow='\033[1;93m' # Yellow BIBlue='\033[1;94m' # Blue BIPurple='\033[1;95m' # Purple BICyan='\033[1;96m' # Cyan BIWhite='\033[1;97m' # White # High Intensity backgrounds On_IBlack='\033[0;100m' # Black On_IRed='\033[0;101m' # Red On_IGreen='\033[0;102m' # Green On_IYellow='\033[0;103m' # Yellow On_IBlue='\033[0;104m' # Blue On_IPurple='\033[0;105m' # Purple On_ICyan='\033[0;106m' # Cyan On_IWhite='\033[0;107m' # White }
``` b) Engramas neuronales y teoría de la mente ``` La teoría de la mente integra, pues, gran cantidad de conocimientos. Pero no todos tienen la misma importancia. Destacan con fuerza la fenomenología de la actividad psíquica y del comportamiento, por una parte, y, por otra, la neurología en todas sus vertientes. Es incuestionable que la teoría de la mente que se proponga deberá explicar, en alguna manera, la experiencia fenomenológica de nuestra actividad psíquica y de nuestro comportamiento; esta experiencia constituye el explicandum, aquello que, en definitiva, debe explicar la teoría de la mente: ésta no tiene otro objetivo científico que explicar cómo es posible lo que nosotros advertimos fenomenológicamente. La ciencia surge siempre para explicar los hechos y estos son aquí nuestra experiencia fenomenológica. Pero el hombre es en realidad una entidad psicobiofísica y, por ello, lo biofísico se encuentra en las estructuras neurológicas terminales que conectan inmediatamente con la explicación de la actividad psíquica y del comportamiento. La teoría de la mente deberá construirse teniendo muy en cuenta qué nos dice hoy la neurología sobre el funcionamiento del cerebro y, en consecuencia, cuáles podrían ser las conjeturas para entender cómo el cerebro funda la producción de todo cuanto constituye nuestra experiencia fenomenológica. Más adelante, al concluir este artículo, examinaremos algunas propuestas en teoría de la mente ante, digamos, el tribunal de apelación de los conocimientos neurológicos actuales (y sin olvidar, además, la experiencia fenomenológica como segundo eje de referencia esencial). El examen versará ante todo sobre la congruencia que presentan los dos grandes paradigmas actualmente en disputa, tal como decíamos hace un momento, a saber, el paradigma mecanicista-formalista-conductual y el paradigma evolutivo-funcional-emergentista. Pero antes debemos introducirnos ya en la temática propia de este escrito, ofreciendo una clarificación sumaria de su contenido (2). El engrama como pieza clave de la arquitectura neuronal. La existencia de engramas neuronales no es una especulación sino un hecho empírico incuestionable. Es posible que, a partir del hecho de los engramas, se intente construir una, digamos, “teoría de engramas” que interprete de forma más general cuál es el papel y alcance de los engramas en el funcionamiento psíquico y conductual; esta “teoría” podrá tener entonces quizá algo de especulación, como necesariamente tienen siempre la teorías. Sin embargo, que alguna de estas especulaciones no sea correcta no significa que la actividad de nuestro S.N. no se funde en la formación continua de una enorme cantidad de engramas neuronales. Así, paso a paso, la interpretación general de la forma en que funciona el sistema neuronal apoyándose en la formación de engramas conduce a una “teoría de engramas”, entendida como una de las perspectivas más importantes que nos llevaría a entender hoy la naturaleza del sistema nervioso. Pero, como ocurre siempre en general con nuestros conocimientos neurológicos, la teoría de engramas tiene consecuencias inmediatas sobre la teoría de la mente. Es decir, no puede ser ignorada por la teoría de la mente. Muy al contrario, ésta debe construirse de forma congruente con la teoría de engramas. No hacerlo sería tan grave como construir una teoría de la mente que no estuviera en conformidad con lo que hoy sabemos sobre el sistema nervioso y el funcionamiento del sistema neuronal. Por consiguiente, la teoría de engramas es así pauta para examinar a su luz las modernas teorías de la mente. Decíamos antes que, al menos en lo fundamental, existían dos grandes paradigmas en teoría de la mente: el paradigma mecanicista-formalista-conductual y el paradigma evolutivo- funcional-emergentista. Pues bien, tal como heremos al concluir este artículo, la teoría de engramas puede aplicarse al análisis de estos dos grandes paradigmas; es decir, nos permite examinarlos desde el punto de vista de su congruencia con la teoría de engramas y, en consecuencia, de su mayor o menor congruencia con las evidencias empíricas y las teorías de la neurología de estos momentos.
const express = require("express"); const cors = require("cors"); const { v4: uuid, validate: isUuid } = require('uuid'); const app = express(); app.use(express.json()); app.use(cors()); const repositories = []; app.get("/repositories", (request, response) => { return response.json(repositories); }); app.post("/repositories", (request, response) => { const {title, url, techs} = request.body; const repository = { id: uuid(), title: title, url: url, techs: techs, likes: 0 }; repositories.push(repository); return response.json(repository); }); app.put("/repositories/:id", (request, response) => { const {id} = request.params; const {url, title, techs} = request.body; const repositoryIndex = repositories.findIndex(element => element.id === id); if (repositoryIndex < 0) { return response.status(400).json({error: 'not found!'}); }; const likes = repositories[repositoryIndex].likes; const repository = { id, url, title, techs, likes }; repositories[repositoryIndex] = repository; return response.json(repository); }); app.delete("/repositories/:id", (request, response) => { const {id} = request.params; const repositoryIndex = repositories.findIndex(element => element.id === id); if (repositoryIndex < 0) { return response.status(400).json({error: 'not found!'}); }; repositories.splice(repositoryIndex, 1); return response.status(204).send(); }); app.post("/repositories/:id/like", (request, response) => { const {id} = request.params; const repositoryIndex = repositories.findIndex(element => element.id === id); if (repositoryIndex < 0) { return response.status(400).json({error: 'not found!'}); }; repositories[repositoryIndex].likes ++; response.status(200).json(repositories[repositoryIndex]) }); module.exports = app;
/* HackTM - C++ implementation of Numenta Cortical Learning Algorithm. * Copyright (c) 2010-2011 Gianluca Guida <glguida@gmail.com> * * This software is released under the Numenta License for * Non-Commercial Use. You should have received a copy of the Numenta * License for Non-Commercial Use with this software (usually * contained in a file called LICENSE.TXT). If you don't, you can * download it from * http://numenta.com/about-numenta/Numenta_Non-Commercial_License.txt. */ #ifndef __HACKTM_SPACE_H__ #define __HACKTM_SPACE_H__ #include <cassert> #include <vector> #include <numeric> #include "HackTM.h" namespace hacktm { /* * Space. * * This class defines a space, which can be of any dimension, and * most importantly provides function to map this euclidean, * n-dimensional space to a one-dimensional space (read bitmap) * defined by id_t. * The advantage of this class is that it lets the client to handle * object in multiple dimension without the hassle of handling * vectors. Whose vectors, btw, would tend to easily stress the * already sensible C++ allocator, so this implementation gives also * a noticeable performance gain. */ class Space { public: Space(const Vector &max); inline bool contains(id_t id) const { return id < __size; } inline bool contains(Vector v) const { for (unsigned i = 0; i < __dimension; i++ ) if ( v[i] < 0 || v[i] >= __maxCoordinates[i] ) return false; return true; } inline coord_t getCoord(id_t id, unsigned i) const { return ((id/__idProjector[i]) % __maxCoordinates[i]); } inline id_t getIdFromVector(Vector &v) const { return std::inner_product(v.begin(), v.end(), __idProjector.begin(), 0); } Vector &setVectorFromId(id_t id, Vector &v) const; scalar_t getDistance(id_t id1, id_t id2) const; inline const unsigned getSize() const { return __size; } inline const scalar_t getMaxSide() const { return __maxSide; } inline const unsigned getDimension() const { return __dimension; } inline coord_t getMaxCoord(int i) const { return __maxCoordinates[i]; } inline coord_t getIdProjectorValue(int i) const { return __idProjector[i]; } friend class Introspection; private: unsigned __size; scalar_t __maxSide; Vector __idProjector; Vector __maxCoordinates; const unsigned __dimension; }; /* * SubSpace class. * * This class provides functions to operate on a subspace (defined * by a center and a radius) of a space. It actually provides you * the n-Cube, so the radius is the minimal distance between the * center and the sides, for the euclidean minds. If you accept the * Infinite Norm distance, though, you can assume it's a * sphere. :-) */ class SubSpace { public: SubSpace(const Space *space, id_t center, scalar_t radius); void resize(scalar_t r); inline scalar_t getRadius() const { return __radius; }; inline id_t getMinId() const { return __minId; } inline coord_t getMinCoord(int i) const { return __minSub[i]; } inline coord_t getMaxCoord(int i) const { return __maxSub[i]; } inline const Space *getSpace() const { return __space; } /* * Apply: * * Applies function "F(id_t) to every Id of the subspace. */ template <class F> void apply(F &func) { __apply(getMinId(), getSpace()->getDimension() - 1, func); } template <class F> void __apply(id_t id, const unsigned dim, F &func) { for ( int i = getMinCoord(dim); i < getMaxCoord(dim); i++ ) { if ( dim == 0 ) func(id); else __apply(id, dim - 1, func); id += getSpace()->getIdProjectorValue(dim); } } /* collect * * Given a set of Ids (through an iterator and a function * that returns Ids from the iterator value) it sets the current * subspace as the smallest subspace that contains all the points * collected until now yet not smaller than the current size. */ template <class T, class F> scalar_t collect(T begin, T end, F &func) { /* Recalculate Max and Min. */ for ( T it = begin; it != end; it++ ) for ( unsigned i = 0; i < __space->getDimension(); i++ ) { coord_t coord = __space->getCoord(func(*it), i); __minSub[i] = std::min(coord, __minSub[i]); // +1 because we check for max which is over the end. __maxSub[i] = std::max(coord + 1, __maxSub[i]); } /* Some points might have been cut off by the min/max checks. Rescan to calculate. */ __recalculateSize(); return __radius; } private: void __recalculateSize(); id_t __minId; Vector __minSub; Vector __maxSub; Vector __center; scalar_t __radius; const Space *__space; }; /* * Space Transformation class. * * This function creates a mapping (with some easily fixable limits) * between two different spaces, and provides functions to map * vectors (in form of Ids) and scalars into each other. */ class SpaceTransform { public: SpaceTransform(const Space *x, const Space *y); id_t transformIdForward(id_t iid) const; id_t transformIdBackward(id_t oid) const; inline scalar_t transformScalarForward(scalar_t ival) const { return ival / __maxRatio; } scalar_t transformScalarBackward(scalar_t oval) const { return oval * __maxRatio; } private: const Space *__inputSpace; const Space *__outputSpace; Vector __inOutRatios; unsigned __maxRatio; }; } #endif
#include <iostream> #include <queue> #include <string> using namespace std; int N, M; int maze[101][101]; int visited[101][101]; int dist[101][101]; int dx[4] = { 0,0,1,-1 }; int dy[4] = { 1,-1,0,0 }; queue<pair<int, int>> q; void bfs(int s, int e) { visited[s][e] = 1; q.push(make_pair(s, e)); dist[s][e]++; while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { int next_x = x + dx[i]; int next_y = y + dy[i]; if (next_x >= 0 && next_y >= 0 && next_x < N && next_y < M && !visited[next_x][next_y] && maze[next_x][next_y]) { visited[next_x][next_y] = 1; q.push(make_pair(next_x, next_y)); dist[next_x][next_y] = dist[x][y] + 1; } } } } int main() { cin >> N >> M; for (int i = 0; i < N; i++) { string row; cin >> row; for (int j = 0; j < M; j++) { maze[i][j] = row[j] - '0'; } } bfs(0, 0); cout << dist[N - 1][M - 1]; }
import Head from 'next/head'; import { Container, Row, Col } from 'react-bootstrap'; import pokemon from '../../../../pokemon.json'; import Image from 'next/image'; import axios from 'axios'; const getPokemon = async (key: any, name: any) => { const { data } = await axios.get(`http://localhost:3001/api/pokemon?name=${escape(name)}`); return data; }; export async function getServerSideProps(context: any) { const data = await getPokemon(null, context.params.name); return { props: { data: data, }, }; } const PokemonName = ({ data }: any) => { console.log('服务端输出'); return ( <div> <Head> <title>{(data && data.name.english) || 'Pokemon'}</title> </Head> <Container> {data && ( <> <h1>{data.name.english}</h1> <Row> <Col xs={4}> <Image src={`/pokemon/${data.name.english.toLowerCase().replace(' ', '-')}.jpg`} alt='' width={300} height={300} /> </Col> <Col xs={8}> {Object.entries(data.base).map(([key, value]: any) => ( <Row key={key}> <Col xs={2}>{key}</Col> <Col xs={10}>{value}</Col> </Row> ))} </Col> </Row> </> )} </Container> </div> ); }; export default PokemonName;
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { Schedule } from 'src/app/entities/schedule'; import { ScheduleManagement } from 'src/app/entities/schedule-management'; import { Specialty } from 'src/app/entities/specialty'; import { User } from 'src/app/entities/user'; import { AuthService } from 'src/app/services/auth.service'; import { ModalService } from 'src/app/services/modal.service'; import { SpinnerService } from 'src/app/services/spinner.service'; import { UsersService } from 'src/app/services/users.service'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.scss'] }) export class ProfileComponent implements OnInit { userLogged = this.authService.getAuth(); userRes: any; userBase = new User(); logged: boolean = false; sendSpecialty!: Specialty; schedule: boolean = false; summary: boolean = false; schedulesUser: ScheduleManagement[] = []; scheduleSelected = new ScheduleManagement(); forms: FormGroup; constructor(private authService: AuthService, private userService: UsersService, private modal: ModalService, private fb: FormBuilder, private spinnerService: SpinnerService) { this.forms = new FormGroup({ name: new FormControl(), lastName: new FormControl(), age: new FormControl(), dni: new FormControl(), email: new FormControl() }); } ngOnInit(): void { this.authService.getAuth().subscribe(res => { if (res != null) { this.userService.isLogged = true; this.logged = true; this.userRes = res; this.userService.getUserId(res.uid).subscribe(user => { this.userBase = user[0]; if (this.userBase.specialty) { this.userBase.specialty?.forEach(name => { switch (name.name) { case 'Kinesiologia': name.photoURL = "../../../assets/clinic.png"; break; case 'Kinesiologia': name.photoURL = "../../../assets/dentist.png"; break; case 'Kinesiologia': name.photoURL = "../../../assets/psychiatrist.png"; break; case 'Kinesiologia': name.photoURL = "../../../assets/cardiologist.png"; break; default: name.photoURL = "../../../assets/specialty.png"; break; } }) } this.forms = this.fb.group({ email: [this.userBase.email, Validators.pattern("^[^@]+@[^@]+\.[a-zA-Z]{2,}$")], name: [this.userBase.name, [Validators.minLength(3), Validators.maxLength(20)]], lastName: [this.userBase.lastName, [Validators.minLength(3), Validators.maxLength(20)]], age: [this.userBase.age, [Validators.max(120), Validators.min(18)]], dni: [this.userBase.dni, [Validators.pattern("[0-9]{8}")]], }); this.userService.getScheduleId(this.userBase.uid).subscribe(user => { this.schedulesUser = user; }) }) } else { this.logged = false; } }); } onSubmit() { } user() { console.log(this.userRes); this.modal.modalMessage('Habilitado', 'success'); } setImg(img: string) { this.authService.uploadPhoto(img); } specialtySelector(specialty: Specialty) { this.sendSpecialty = specialty; this.scheduleSelected = this.schedulesUser.filter(fill => fill.specialty?.name == specialty.name)[0]; } scheduleStatus() { this.schedule = !this.schedule; } summaryStatus() { this.summary = !this.summary; } addSchedule(schedule: ScheduleManagement) { console.log(schedule); this.spinnerService.show(); if (this.scheduleSelected) { this.userService.updateSchule(this.scheduleSelected, schedule).then(() => this.modal.modalMessage("Horario cargado correctamente", 'success')).finally(() => this.spinnerService.hide()); } else { this.userService.addSchedule(schedule).then(() => this.modal.modalMessage("Horario cargado correctamente", 'success')).finally(() => this.spinnerService.hide()); } } listSchedule(): Schedule[] | any { if (this.scheduleSelected) { return this.scheduleSelected.schedule; } } }
import React, { useContext, useEffect, useRef, useState } from 'react' import { Button, Col, Form, FormGroup, Input, Label, Row } from 'reactstrap' import validationdata from '../JSON/validation.json' import { Cardcontext } from '../App' import CardComponent from './CardComponent' const FormComponent = () => { let value = useContext(Cardcontext) const fileref = useRef() let [errorobj, seterrorobj] = useState({}) const getBase64 = (file) => new Promise(function (resolve, reject) { let reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result) reader.onerror = (error) => reject('Error: ', error); }) const changedata = async (e) => { if (e.target.name == "image") { value.obj[e.target.name] = await getBase64(e.target.files[0]) } else { value.obj[e.target.name] = e.target.value } value.setobj({ ...value.obj }) // validate(e.target.name) } const save = (e) => { // for (let x of Object.keys(value.obj)) { // validate(x) // } e.preventDefault() if (value.editid == 0) { value.count = value.count + 1 value.obj.id = value.count console.log(value.obj) value.array.push(value.obj) } else { value.editid = 0; value.array.splice(value.array.findIndex(x => x.id == value.editid), 1, value.obj) } value.setobj({ ...value.obj }) value.setarray([...value.array]) value.setcount(value.count) value.setobj({}) value.seteditid(value.editid) fileref.current.value = "" } // const validate = (name) => { // let validationobj = validationdata.find((x) => x.name == name) // let validationerror = validationobj.conditions.find((x) => eval(x.condition)) // if (validationobj) { // if (validationerror) { // errorobj[name] = validationerror.error // } // else { // delete errorobj[name] // } // } // } return ( <div> <div className="container text-bg-dark rounded-3 py-5 my-3"> <h1 className='text-center py-3'>First Form</h1> <Form className=''> <Row> <Col md={6}> <FormGroup> <Label for="title" className='fs-5'> Title </Label> <Input id="title" name="title" type="text" value={value.obj.title || ''} placeholder='Add Title' onChange={changedata} /> <span>{errorobj.title}</span> </FormGroup> </Col> <Col md={6}> <FormGroup> <Label for="subtitle" className='fs-5'> SubTitle </Label> <Input id="subtitle" name="subtitle" type="text" value={value.obj.subtitle || ''} placeholder="Sub Title" onChange={changedata} /> <span>{errorobj.subtitle}</span> </FormGroup> </Col> </Row> <Row> <Col md={6}> <FormGroup> <Label for="image" className='fs-5'> Image </Label> <input id="image" name="image" type="file" placeholder='File' onChange={changedata} ref={fileref} className='form-control' /> <span>{errorobj.image}</span> </FormGroup> </Col> <Col md={6}> <FormGroup> <Label for="button" className='fs-5'> Button </Label> <Input id="button" name="button" type="text" value={value.obj.button || ""} placeholder='Add Button' onChange={changedata} /> </FormGroup> <span>{errorobj.button}</span> </Col> </Row> <Row> <Col md={12}> <FormGroup> <Label for="information" className='fs-5'> Information </Label> <Input id="information" name="information" placeholder="Enter Description" type='textarea' value={value.obj.information || ""} onChange={changedata} /> </FormGroup> <span>{errorobj.information}</span> </Col> </Row> <div className='text-center'> <Button className='' onClick={save}> Sign in </Button> </div> </Form> </div> <CardComponent value={value.array} > <thead> <tr> <th> Sr No. </th> <th> Title </th> <th> SubTitle </th> <th> Image </th> <th> Action </th> </tr> </thead> </CardComponent > </div> ) } export default FormComponent
<%@page import="kr.or.ddit.vo.MemberVO"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <jsp:useBean id="prod" scope="request" type="kr.or.ddit.vo.ProdVO" /> <table> <tr> <th>상품코드</th> <td>${prod.prodId}</td> </tr> <tr> <th>상품명</th> <td>${prod.prodName}</td> </tr> <tr> <th>상품분류</th> <td>${prod.prodLgu}</td> </tr> <tr> <th>거래처</th> <td> <table> <thead> <tr> <th>거래처명</th> <th>담당자</th> <th>소재지</th> </tr> </thead> <tbody> <tr> <td>${prod.buyer.buyerName}</td> <td>${prod.buyer.buyerCharger}</td> <td>${prod.buyer.buyerAdd1}</td> </tr> </tbody> </table> </td> </tr> <tr> <th>구매가</th> <td>${prod.prodCost}</td> </tr> <tr> <th>판매가</th> <td>${prod.prodPrice}</td> </tr> <tr> <th>세일가</th> <td>${prod.prodSale}</td> </tr> <tr> <th>요약정보</th> <td>${prod.prodOutline}</td> </tr> <tr> <th>상세정보</th> <td>${prod.prodDetail}</td> </tr> <tr> <th>이미지경로</th> <td><img src="${pageContext.request.contextPath }/resources/prodImages/${prod.prodImg}"></td> </tr> <tr> <th>재고</th> <td>${prod.prodTotalstock}</td> </tr> <tr> <th>입고일</th> <td>${prod.prodInsdate}</td> </tr> <tr> <th>적정재고</th> <td>${prod.prodProperstock}</td> </tr> <tr> <th>크기</th> <td>${prod.prodSize}</td> </tr> <tr> <th>색상</th> <td>${prod.prodColor}</td> </tr> <tr> <th>배송방법</th> <td>${prod.prodDelivery}</td> </tr> <tr> <th>단위</th> <td>${prod.prodUnit}</td> </tr> <tr> <th>입고량</th> <td>${prod.prodQtyin}</td> </tr> <tr> <th>판매량</th> <td>${prod.prodQtysale}</td> </tr> <tr> <th>마일리지</th> <td>${prod.prodMileage}</td> </tr> <tr> <td colspan="2"> <c:url value="/prod/prodUpdate.do" var="updateURL" > <c:param name="what" value="${prod.prodId }" /> </c:url> <input type="button" class="linkBtn" data-goPage="${updateURL }" value="상품 수정"> </td> </tr> <tr> <th>구매자정보</th> <td> <table> <thead> <tr> <th>구매자명</th> <th>소재지</th> <th>이메일</th> </tr> </thead> <tbody> <c:set var="memberList" value="${prod.memberList }"/> <c:choose> <c:when test="${empty memberList }"> <tr> <td colspan="3">구매자가 없음.</td> </tr> </c:when> <c:otherwise> <c:forEach items="${memberList}" var="member"> <tr> <td>${member.memName }</td> <td>${member.memAdd1 }</td> <td>${member.memMail }</td> </tr> </c:forEach> </c:otherwise> </c:choose> <%-- List<MemberVO> memberList = prod.getMemberList(); if(memberList.isEmpty()){ --%> <!-- <tr> --> <!-- <td colspan="3">구매자가 없음.</td> --> <!-- </tr> --> <%-- }else{ for(MemberVO member : memberList){ --%> <!-- <tr> --> <%-- <td>${member.memName}</td> --%> <%-- <td>${member.memMail}</td> --%> <%-- <td>${member.memAdd1}</td> --%> <!-- </tr> --> <%-- } } --%> </tbody> </table> </td> </tr> </table>
import * as cdk from 'aws-cdk-lib'; import * as apig from 'aws-cdk-lib/aws-apigateway'; import * as cognito from 'aws-cdk-lib/aws-cognito'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as helpers from './helperScripts'; import { Construct } from 'constructs'; export class restGatewayNestedStack extends cdk.NestedStack { gateway: restGateway; constructor(scope: Construct, id: string, description?: string, stageName?: string) { super(scope, id) this.gateway = new restGateway(scope, id + "_G", description, stageName) } } export class restGateway extends apig.RestApi { scope: Construct; id: String; apiGatewayARN: string apiGatewayURL: string knownResources: { [key: string]: apig.Resource } = {}; stageName: string constructor(scope: Construct, id: string, description?: string, stageName: string = "dev") { const props = { description: description ? description : 'API Gateway Construct', deployOptions: { stageName: stageName ? stageName : 'dev', }, }; super(scope, id, props) this.scope = scope; this.id = id; this.apiGatewayURL = this.url; this.stageName = stageName; } addCorsOptions(resource: apig.Resource) { resource.addMethod('OPTIONS', new apig.MockIntegration({ integrationResponses: [{ statusCode: '200', responseParameters: { 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,AuthToken'", 'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,GET,PUT,POST,DELETE'", 'method.response.header.Access-Control-Allow-Credentials': "'false'", 'method.response.header.Access-Control-Allow-Origin': "'*'", }, }], passthroughBehavior: apig.PassthroughBehavior.NEVER, requestTemplates: { "application/json": "{\"statusCode\": 200}" }, }), { methodResponses: [{ statusCode: '200', responseParameters: { 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Methods': true, 'method.response.header.Access-Control-Allow-Credentials': true, 'method.response.header.Access-Control-Allow-Origin': true, }, }] }); } GetAPIGatewayArn() { // return `arn:aws:execute-api:${this.env.region}:${this.env.account}:${this.restApiId}/dev` return `arn:aws:apigateway:${this.env.region}::/restapis/${this.restApiId}/stages/${this.stageName}` } AddCognitoAuthorizer(scope: Construct, id: string, UserPools: cognito.UserPool[]) { const auth = new apig.CognitoUserPoolsAuthorizer(scope, id, { cognitoUserPools: UserPools }) return auth; } AddAPIGAuthorizer(scope: Construct, id: string, authFn: lambda.Function) { const auth = new apig.RequestAuthorizer(scope, id, { handler: authFn, identitySources: [apig.IdentitySource.header('Authorization')] }); return auth; } AddResource(FullPath: string) { //Check if there is already a resource. if (this.knownResources[FullPath] !== undefined) { return this.knownResources[FullPath]; } //Split up the path. //check if the base resources already exist, and then return the last one. const rootPath = this.root; const parts = FullPath.split("/"); let currentResource = this.knownResources[parts[0]]; if (this.knownResources[parts[0]] !== undefined) { currentResource = this.knownResources[parts[0]]; } else { currentResource = rootPath.addResource(parts[0]); this.knownResources[parts[0]] = currentResource; } if (parts.length > 1) { for (let i = 1; i < parts.length; i++) { let currentPath = parts.slice(0, i).join("/"); console.log(currentPath); try { currentResource = currentResource.addResource(parts[i]); this.knownResources[currentPath] = currentResource; } catch { currentResource = this.knownResources[currentPath]; } } } this.addCorsOptions(currentResource); return currentResource; } AddMethodIntegration(integration: apig.AwsIntegration, route: string = "", methodString: string) { const resource = this.AddResource(route); const method = resource.addMethod( methodString, integration,) return true; } AttachWebACL(scope: Construct, id: string) { const webACL = this.GetWebACL(scope, id); return new cdk.aws_wafv2.CfnWebACLAssociation( scope, id + '_CDKWebACLAssoc', { webAclArn: webACL.attrArn, resourceArn: this.GetAPIGatewayArn() } ); } GetWebACL(scope: Construct, id: string) { const wafWebACL = new cdk.aws_wafv2.CfnWebACL(scope, id + "_WebACL", { description: "BasicWAF", defaultAction: { allow: {}, }, scope: "REGIONAL", visibilityConfig: { cloudWatchMetricsEnabled: true, metricName: "WAFACLGLOBAL", sampledRequestsEnabled: true } }); return wafWebACL } ExportConfig() { return { API: { endpoints: [ { name: this.restApiName, endpoint: this.apiGatewayURL, region: this.env.region }, ], } } } }
import { Test, TestingModule } from '@nestjs/testing'; import { OpenaiService } from './openai.service'; import { ConfigModule } from '@nestjs/config'; import { HttpService } from '@nestjs/axios'; import { LoggerModule } from 'nestjs-pino'; import { RequestCacheService } from '../../utils/services/request-cache.service'; import { AxiosResponse } from 'axios'; import { ConfigService } from '@nestjs/config'; import { PrismaService } from '../../db/services/prisma.service'; jest.mock('rxjs', () => { const original = jest.requireActual('rxjs'); return { ...original, lastValueFrom: (providedValue) => new Promise((resolve) => { resolve(providedValue); }), }; }); describe('OpenaiService', () => { let openaiService: OpenaiService; let requestCacheService: RequestCacheService; // This needs to be defined outside of an individual test in order for it to resolve correctly // I think the value is being copied into the instance and referencing this variable doesn't // change the value in mocks inside of tests. const mockMeal = { name: 'meal name', ingredients: [ { name: 'flour', quantity: 0.5, unit: 'cup', }, ], instructions: 'instructions', }; const mockResponse = { data: { choices: [ { message: { content: JSON.stringify({ ...mockMeal }), }, }, ], }, }; const mockPostFunction: jest.Mock = jest .fn() .mockReturnValueOnce(mockResponse as AxiosResponse); beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [ConfigModule, LoggerModule.forRoot()], providers: [ OpenaiService, { provide: HttpService, useValue: { post: mockPostFunction, }, }, { provide: ConfigService, useValue: { get: jest.fn().mockReturnValue('test-api-key'), }, }, RequestCacheService, PrismaService, ], }).compile(); openaiService = module.get<OpenaiService>(OpenaiService); requestCacheService = module.get<RequestCacheService>(RequestCacheService); }); it('should be defined', () => { expect(openaiService).toBeDefined(); }); it('should call sendMessage and return a response', async () => { jest .spyOn(requestCacheService, 'cacheAxiosRequestResponse') .mockImplementation(() => Promise.resolve()); const input = { recipeName: 'Test Recipe', ingredients: ['ingredient1', 'ingredient2'], allergens: ['allergen1'], diets: ['diet1', 'diet2'], }; const response = await openaiService.requestRecipeWithFilters(input); // Verify that sendMessage was called with the expected message content expect(mockPostFunction).toHaveBeenCalledWith( 'https://api.openai.com/v1/chat/completions', { model: 'gpt-3.5-turbo', messages: [ { role: 'system', content: expect.stringContaining( `Please provide a recipe for Test Recipe. The recipe should use some or all of these ingredients: ingredient1, ingredient2. The recipe should not contain these allergens: allergen1. The recipe should fit these diets: diet1, diet2.`, ), }, ], }, { headers: { Authorization: 'Bearer test-api-key', 'Content-Type': 'application/json', }, }, ); // Verify that cacheAxiosRequestResponse was called expect(requestCacheService.cacheAxiosRequestResponse).toHaveBeenCalled(); // Verify that the response is as expected expect(response).toEqual({ name: 'meal name', ingredients: [ { name: 'flour', quantity: 0.5, unit: 'cup', }, ], instructions: 'instructions', }); }); });
package com.charlyj21.colasegura import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayoutMediator class OnBoardingActivity : AppCompatActivity() { private val onBoardingPageChangeCallback = object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { super.onPageSelected(position) when (position){ 0 -> { skipBtn.text = "Omitir" skipBtn.visible() nextBtn.visible() previousBtn.gone() } pagerList.size - 1 -> { skipBtn.text = "Empezar" skipBtn.visible() nextBtn.visible() previousBtn.visible() } else -> { skipBtn.text = "Omitir" skipBtn.visible() nextBtn.visible() previousBtn.visible() } } } } private val pagerList = arrayListOf( Page( "Cola Segura", R.drawable.ic_onboarding_1, R.string.onboarding_desc_1, "#F2D6C2", 50f, 300 ), Page( " Seguridad y Confianza", R.drawable.ic_onboarding_2, R.string.onboarding_desc_2, "#F2D6C2", 35f, 300 ), Page( "Equipo de Trabajo", R.drawable.ic_onboarding_3, R.string.onboarding_desc_3, "#F2D6C2", 35f, 300 ) ) private lateinit var onBoardingViewPager2: ViewPager2 lateinit var skipBtn: Button lateinit var nextBtn: Button lateinit var previousBtn: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_on_boarding) onBoardingViewPager2 = findViewById(R.id.onBoardingViewPager2) skipBtn = findViewById(R.id.skipBtn) nextBtn = findViewById(R.id.nextBtn) previousBtn = findViewById(R.id.previousBtn) onBoardingViewPager2.apply { adapter = OnBoardingAdapter(this@OnBoardingActivity, pagerList) registerOnPageChangeCallback(onBoardingPageChangeCallback) (getChildAt(0) as RecyclerView).overScrollMode = RecyclerView.OVER_SCROLL_NEVER } val tabLayout = findViewById<TabLayout>(R.id.tabLayout) TabLayoutMediator(tabLayout, onBoardingViewPager2) { tab, position -> }.attach() nextBtn.setOnClickListener { if (onBoardingViewPager2.currentItem < onBoardingViewPager2.adapter!!.itemCount - 1){ onBoardingViewPager2.currentItem += 1 } else { homeScreenIntent() } } previousBtn.setOnClickListener { if (onBoardingViewPager2.currentItem > 0){ onBoardingViewPager2.currentItem -= 1 } } skipBtn.setOnClickListener { homeScreenIntent() } } override fun onDestroy() { onBoardingViewPager2.unregisterOnPageChangeCallback(onBoardingPageChangeCallback) super.onDestroy() } private fun homeScreenIntent() { val sharedPreferenceManger = SharedPreferenceManger(this) sharedPreferenceManger.isFirstTime = false val homeIntent = Intent(this, MainActivity::class.java) startActivity(homeIntent) finish() } }
import React, { ChangeEvent, useEffect } from 'react' import FormStyle from "../../../styles/users/_Form.module.scss" import {passwordInput} from "../../../store/RegisterSlice" import { useSelector, useDispatch } from 'react-redux'; import { CheckMarkGold, CheckMarkGray } from '../../Atoms/CheckMark'; const Navigation = (props: any) => { const password = useSelector((state:any) => state.registerInput.password); if (password.length > 0) { return ( <> <div className="py-2 text-gray-500 text-sm "> <p> {(() => { if (password.length >= 8 && password.length <= 12) { return ( <> <span className={`${FormStyle.NavigationIcons}`}> <CheckMarkGold /> </span> </> ); } else { return ( <> <span className={`${FormStyle.NavigationIcons}`}> <CheckMarkGray /> </span> </> ); } } )()} {props.text} </p> </div> </> ) } else { return ( <></> ) } } const Error = (props: any) => { if (props.errorFlag === "true") { if (props.value === "empty" || props.value === "init") { return ( <> <label className={`${FormStyle.error} `}>{props.text}</label> </> ) } else if (props.value === "format-inccorect") { return ( <label className={`${FormStyle.error} `}>8文字以上12文字以下で入力してください</label> ); } else if (props.value === "mismatch") { return ( <label className={`${FormStyle.error} `}>パスワードが一致しません</label> ); } else { return <></> } } else { return <></> } } // { // SetPasswordValue: any, SetPasswordErrorState: any, confirmPasswordValue: any, // SetConfirmPasswordErrorState: any, // passwordErrorState: any, // passwordValue: any, // errorFlag: any, // displayFlag: boolean, // page:string // } export const PasswordInput = (props: any) => { const confirmPassword = useSelector((state:any) => state.registerInput.confirmPassword); const dispatch = useDispatch(); const onChangeHandler = (ev: ChangeEvent<HTMLInputElement>) => { // props.SetPasswordValue(ev.target.value); dispatch(passwordInput(ev.target.value)); if (!(ev.target.value)) { props.SetPasswordErrorState("empty") } else if (ev.target.value.length < 8 || ev.target.value.length > 12) { props.SetPasswordErrorState("format-inccorect") } else { props.SetPasswordErrorState("ok") } if (props.displayFlag == true) { if (ev.target.value !== confirmPassword) { if (props.page === "register") { props.SetConfirmPasswordErrorState("mismatch") } } else if (ev.target.value === confirmPassword) { props.SetConfirmPasswordErrorState("ok") } } } const NavigationDisplay = (props: any) => { if (props.displayFlag === true) { return ( <> <Navigation text="8文字以上16文字以内" /> </> ) } else { return <></> } } return ( <> <div className={`${FormStyle.formMain}`}> <div className={`${FormStyle.labelGroup}`}> <label htmlFor="new-password">パスワード </label> <span className={` ${FormStyle.mark}`}>必須</span> <Error text="パスワードを入力してください" value={props.passwordErrorState} confirmPasswordValue={props.confirmPasswordValue} SetPasswordErrorState={props.SetPasswordErrorState} errorFlag={props.errorFlag} /> </div> <div> <input type="password" className={`${FormStyle.input} ${FormStyle.widthInput}`} id="new-password" onChange={onChangeHandler} placeholder="例)Password123" autoComplete="new-password" /> </div> <NavigationDisplay displayFlag={props.displayFlag} /> </div> </> ) }
import useSWRMutation from "swr/mutation"; import { ConnectionWithId, tryParseConnectionWithId, } from "@/app/types/Connection"; const updateConnection = async ( url: string, { arg }: { arg: ConnectionWithId }, ) => { const response = await fetch(url, { method: "PATCH", body: JSON.stringify(arg), }); if (response.status !== 200) { console.warn( `Failed to delete connection with status code: ${response.status}}`, ); return undefined; } const body = await response.json(); const connection = tryParseConnectionWithId(body); if (!connection) { throw new Error("Failed to parse connection"); } return connection; }; export function useUpdateConnection() { const { trigger } = useSWRMutation("/connections", updateConnection, { populateCache: (connection, connections: ConnectionWithId[]) => connections.map((c: ConnectionWithId) => c.id === connection?.id ? connection : c, ), }); return async (connection: ConnectionWithId) => { await trigger<ConnectionWithId[]>(connection, { optimisticData: (connections) => connections?.map((c: ConnectionWithId) => c.id === connection.id ? connection : c, ) ?? [], }); }; }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* Copyright (c) 2018 Mobify Research & Development Inc. All rights reserved. */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * */ import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import {ampComponent} from 'mobify-amp-sdk/dist/amp-sdk' /** * Card component is used to show content in a card with header and footer */ const Card = ({ className, header, children, footer, hasShadow, hasBorder }) => { const classes = classNames('c-card', { 'c--shadow': hasShadow, 'c--border': hasBorder, }, className) return ( <article className={classes}> <div className="c-card__inner"> {header && <header className="c-card__header"> {header} </header> } <div className="c-card__content"> {children} </div> {footer && <footer className="c-card__footer"> {footer} </footer> } </div> </article> ) } Card.propTypes = { /** * Main content of the card */ children: PropTypes.node, /** * Adds values to the `class` attribute of the root element */ className: PropTypes.string, /** * Footer content of the card */ footer: PropTypes.node, /** * Determines if card has border */ hasBorder: PropTypes.bool, /** * Determines if card has box-shadow */ hasShadow: PropTypes.bool, /** * Header content of the card */ header: PropTypes.node, } export default ampComponent(Card)
import spacy import requests from flask_cors import CORS from flask import Flask, request from youtube_transcript_api import YouTubeTranscriptApi app = Flask(__name__) CORS(app) SMMRY_API_KEY = '<API_KEY>' SMMRY_API_URL = 'http://api.smmry.com/' DEFAULT_ERRORS = { "NO_TRANSCRIPT_FOUND": { "error": "No transcript found" } } class YoutubeSummarizer: def __init__(self, video_id, percent): self.video_id = video_id self.percent = percent self.transcript_string = '' self.transcript_with_sentences = '' self.transcript = '' def summarize(self): return self.get_transcript() def get_transcript(self): video_id = self.video_id transcript = {} try: transcript = YouTubeTranscriptApi.get_transcript( video_id, languages=["en"]) except: return DEFAULT_ERRORS['NO_TRANSCRIPT_FOUND'] self.transcript = transcript transcript_string = " " for line in transcript: transcript_string += line['text'].strip() + " " self.transcript_string = transcript_string return self.identify_sentences() def identify_sentences(self): transcript_string = self.transcript_string nlp = spacy.load("en_core_web_sm") doc = nlp(transcript_string.lower()) transcript_with_sentences = "" num_sentences = 0 for sentence in doc.sents: transcript_with_sentences += sentence.text + ".\n " num_sentences += 1 self.transcript_with_sentences = transcript_with_sentences return self.get_summary(num_sentences) def get_summary(self, num_sentences): transcript = self.transcript_with_sentences percent = self.percent summary_length = round(float(percent) * num_sentences) api_url = ("%s&SM_API_KEY=%s&SM_LENGTH=%s" % (SMMRY_API_URL, SMMRY_API_KEY, summary_length)) response = requests.post(api_url, data={"sm_api.input": transcript}) api_content = response.json()["sm_api_content"] if not api_content: return DEFAULT_ERRORS['NO_TRANSCRIPT_FOUND'] return { "result": api_content } @app.route("/") def summarize(): video_id = request.args.get("video_id") percent_to_summarize = request.args.get("percent") summarizer = YoutubeSummarizer(video_id, percent_to_summarize) summarized_content = summarizer.summarize() return summarized_content if __name__ == "__main__": app.run(host='0.0.0.0')
<template> <div class="flex justify-between"> <h1 class="text-4xl font-black text-gray-800" id="modal-create-account" > Crie uma conta </h1> <button @click="close" class="text-4xl text-gray-600 focus:outline-none" > &times; </button> </div> <div class="mt-16"> <form @submit.prevent="handleSubmit"> <label class="block"> <span class="text-lg font-medium text-gray-800">Nome</span> <input v-model="state.name.value" type="text" :class="{'border-brand-danger' : !!state.name.errorMessage}" class="block w-full px-4 py-3 mt-1 text-lg bg-gray-100 border-2 border-tranparent rounded" placeholder="Jane Doe" > <span v-if="!!state.name.errorMessage" class="block font-medium text-brand-danger"> {{state.name.errorMessage}} </span> </label> <label class="block mt-9"> <span class="text-lg font-medium text-gray-800">E-mail</span> <input v-model="state.email.value" type="email" :class="{'border-brand-danger' : !!state.email.errorMessage}" class="block w-full px-4 py-3 mt-1 text-lg bg-gray-100 border-2 border-tranparent rounded" placeholder="jane.dae@gmail.com" > <span v-if="!!state.email.errorMessage" class="block font-medium text-brand-danger"> {{state.email.errorMessage}} </span> </label> <label class="block mt-9"> <span class="text-lg font-medium text-gray-800">Senha</span> <input v-model="state.password.value" type="password" :class="{'border-brand-danger' : !!state.password.errorMessage}" class="block w-full px-4 py-3 mt-1 text-lg bg-gray-100 border-2 border-tranparent rounded" > <span v-if="!!state.password.errorMessage" class="block font-medium text-brand-danger"> {{state.password.errorMessage}} </span> </label> <button :disabled="state.isLoading" type="submit" :class="{'opacity-50' : state.isLoading}" class="px-8 py-3 mt-10 text-2xl font-bold text-white rounded-full bg-brand-main focus:outline-none transition-all duration-150" > <icon v-if="state.isLoading" name="loading" class="animate-spin"/> <span v-else>Entrar</span> </button> </form> </div> </template> <script> import { reactive } from 'vue' import { useField } from 'vee-validate' import useModal from '../../hooks/useModal' import Icon from '../Icon' import { validateEmptyAndLength3, validateEmptyAndEmail } from '../../utils/validators' import services from '../../services' import { useRouter } from 'vue-router' import { useToast } from 'vue-toastification' export default { components: { Icon }, setup () { const router = useRouter() const modal = useModal() const toast = useToast() const { value: nameValue, errorMessage: nameErrorMessage } = useField('nameValue', validateEmptyAndLength3) const { value: emailValue, errorMessage: emailErrorMessage } = useField('email', validateEmptyAndEmail) const { value: passwordValue, errorMessage: passwordErrorMessage } = useField('password', validateEmptyAndLength3) const state = reactive({ hasErros: false, isLoading: false, name: { value: nameValue, errorMessage: nameErrorMessage }, email: { value: emailValue, errorMessage: emailErrorMessage }, password: { value: passwordValue, errorMessage: passwordErrorMessage } }) async function handleSubmit () { try { toast.clear() // remove the available toasts and put a new one state.isLoading = true const { data, errors } = await services.auth.register({ name: state.name.value, email: state.email.value, password: state.password.value }) if (!errors) { window.localStorage.setItem('token', data.token) router.push({ name: 'Feedbacks' }) modal.close() return } if (errors.status === 400) { toast.error('Ocorreu um erro ao criar a conta!') } state.isLoading = false } catch (error) { state.isLoading = false state.hasErros = !!error toast.error('Ocorreu um erro ao criar a conta!') } } return { state, close: modal.close, handleSubmit } } } </script>
from django.shortcuts import render, get_object_or_404 from .models import Todo from .serializers import TodoSerializer from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status @api_view(["GET", "POST"]) def todo_list(request): if request.method == "GET": todos = Todo.objects.all() serializer = TodoSerializer(todos, many=True) return Response(serializer.data) elif request.method == "POST": serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) @api_view(["GET", "PUT", "PATCH", "DELETE"]) def todo_detail(request, pk): todo = get_object_or_404(Todo, id=pk) serializer = TodoSerializer(todo, data=request.data) if request.method == "GET": serializer = TodoSerializer(todo) return Response(serializer.data) elif request.method == "PUT": if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND) elif request.method == "PATCH": if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND) elif request.method == "DELETE": todo.delete() return Response(status=status.HTTP_204_NO_CONTENT)
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #pragma once #include "SUTEditableTextBox.h" #include "SlateBasics.h" #include "../SUTStyle.h" #if !UE_SERVER class UUTLocalPlayer; class UNREALTOURNAMENT_API SUTChatEditBox : public SUTEditableTextBox { SLATE_BEGIN_ARGS(SUTChatEditBox) : _Style(&SUTStyle::Get().GetWidgetStyle< FEditableTextBoxStyle >("UT.ChatEditBox")) , _HintText() , _Font() , _ForegroundColor() , _MinDesiredWidth( 0.0f ) , _BackgroundColor() , _MaxTextSize(128) {} /** The styling of the textbox */ SLATE_STYLE_ARGUMENT( FEditableTextBoxStyle, Style ) /** Hint text that appears when there is no text in the text box */ SLATE_ATTRIBUTE( FText, HintText ) /** Font color and opacity (overrides Style) */ SLATE_ATTRIBUTE( FSlateFontInfo, Font ) /** Text color and opacity (overrides Style) */ SLATE_ATTRIBUTE( FSlateColor, ForegroundColor ) /** Called whenever the text is changed interactively by the user */ SLATE_EVENT( FOnTextChanged, OnTextChanged ) /** Called whenever the text is committed. This happens when the user presses enter or the text box loses focus. */ SLATE_EVENT( FOnTextCommitted, OnTextCommitted ) /** Minimum width that a text block should be */ SLATE_ATTRIBUTE( float, MinDesiredWidth ) /** The color of the background/border around the editable text (overrides Style) */ SLATE_ATTRIBUTE( FSlateColor, BackgroundColor ) /** The size of the largest string */ SLATE_ARGUMENT(int32, MaxTextSize) SLATE_END_ARGS() void Construct(const FArguments& InArgs, TWeakObjectPtr<UUTLocalPlayer> inPlayerOwner); void SetChangedDelegate(FOnTextChanged inOnTextChanged); void SetCommittedDelegate(FOnTextCommitted inOnTextCommitted); virtual FReply OnFocusReceived( const FGeometry& MyGeometry, const FFocusEvent& InKeyboardFocusEvent ) override; protected: virtual FReply InternalOnKeyDown( const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent ); TSharedPtr<STextBlock> TypeMsg; TWeakObjectPtr<UUTLocalPlayer> PlayerOwner; FText InternalTextBuffer; int32 MaxTextSize; FOnTextChanged ExternalOnTextChanged; FOnTextCommitted ExternalOnTextCommitted; void EditableTextChanged(const FText& NewText); void EditableTextCommited(const FText& NewText, ETextCommit::Type CommitType); EVisibility TypedMsgVis() const; /** @return Border image for the text box based on the hovered and focused state */ const FSlateBrush* GetBorderImage() const; }; #endif
import { Token } from './configs'; export const Actions = [ 'swap', 'collect', 'deposit', 'withdraw', 'borrow', 'repay', 'flashloan', 'liquidate', 'bridge', 'register', 'renew', 'list', 'buy', 'offer', 'trade', 'sow', 'createLiquidityPool', 'lock', 'unlock', 'update', 'useContract', // for calls to smart contracts: DSProxy, Instadapp account, ... 'executeRecipe', // execute recipe on DeFi Saver 'executeTask', // execute task on gelato.network // these actions used for leveraged functional 'leverage', 'increaseShort', 'increaseLong', 'decreaseShort', 'decreaseLong', 'liquidateShort', 'liquidateLong', 'openAccount', 'closeAccount', ] as const; export type KnownAction = (typeof Actions)[number]; export interface EventLogBase { protocol: string; action: KnownAction; contract: string; addresses: Array<string>; readableString: string; tokens: Array<Token>; // should match with tokens tokenAmounts: Array<string>; // some protocol return amount in USD usdAmounts?: Array<string>; } export interface EventLogAction extends EventLogBase { logIndex?: number; addition?: any; subActions?: Array<EventLogBase>; } export interface Transaction { // the blockchain name chain: string; // the blockchain family family: string; // the transaction hash hash: string; // the transaction sender from: string; // the transaction recipient or contract to: string; // the transaction status status: boolean; // timestamp where transaction was executed // on evm chains, we can not timestamp directly from the transaction // we must get it from block data timestamp: number; // block number where the transaction was included // some blockchain like Aptos does not have block // so, this value is the ledger version // for more detail about blocks on Aptos, please check: https://aptos.dev/concepts/blocks blockNumber: number; actions: Array<EventLogAction>; } // this interface will be exactly saved in database export interface EventLogActionDocument { // the blockchain name chain: string; // the blockchain family family: string; // the transaction sender from: string; // the transaction recipient or contract to: string; // the transaction hash transactionHash: string; timestamp: number; blockNumber: number; logIndex: number; // action info protocol: string; action: KnownAction; contract: string; addresses: Array<string>; tokens: Array<Token>; // should match with tokens tokenAmounts: Array<string>; // some protocol return amount in USD usdAmounts?: Array<string>; addition?: any; }
import React from 'react'; import { connect } from 'react-redux'; import { menuItems } from '../config/menu.jsx'; import { domainPath } from '../config/system.jsx'; import { encodeParams } from '../util/http.jsx'; import { logSource } from '../config/common.jsx'; import Select from '../component/select.jsx'; import SearchInput from '../component/input/search.jsx'; import Page from '../component/page.jsx'; import LogList from './log/log.jsx'; import globalStyle from '../public/global.css'; import logStyle from './log.css'; class Log extends React.Component { constructor(props) { super(props); this.defaultOperatorOption = { index: -1, value: '所有', }; // 所有操作人选项 this.state = { currentSource: 'all', // 当前日志来源 currentOperatorId: -1, // 当前操作人ID currentKeyword: '', // 当前搜索关键字 currentOrderField: 'id', // 当前排序字段 currentOrderType: 'desc', // 当前排序方式 maxLogListPageNumber: 1, // 日志列表最大页数 currentLogListPageNumber: 1, // 日志列表当前页号 operators: [this.defaultOperatorOption], // 操作人数据 logs: [], // 日志数据 loading: true, // 载入状态 }; this.fetchOperators = this.fetchOperators.bind(this); this.fetchLogs = this.fetchLogs.bind(this); this.switchSource = this.switchSource.bind(this); this.switchOperator = this.switchOperator.bind(this); this.setKeyword = this.setKeyword.bind(this); this.setOrder = this.setOrder.bind(this); } componentWillMount() { this.props.dispatch({ type: 'SET_ACTIVE_INDEX', activeIndex: menuItems._log.index, }); // 更新选中的二级菜单索引 this.props.dispatch({ type: 'SET_PAGE_TITLE', pageTitle: menuItems._log.name, }); // 更新页头标题 this.fetchLogs(1); } /** * 获取操作人数据 */ fetchOperators() { let url = ''; if (this.state.currentSource === 'user') { url = `${domainPath}/v2/get/api/users`; } else if (this.state.currentSource === 'app') { url = `${domainPath}/v2/get/api/applications`; } else { // 全部来源时不提供操作人列表 this.setState({ operators: [this.defaultOperatorOption], }); return; } const _this = this; const result = fetch(url, { method: 'post', credentials: 'include', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', }, }); result.then(function (response) { // console.log(response); return response.json(); }).then(function (json) { let operators = [_this.defaultOperatorOption]; json.map((operator) => { operators.push({ index: Number.parseInt(operator.id), value: operator.card ? operator.card : operator.name, }); }); _this.setState({ operators: operators, }); }).catch(function (e) { console.log(e); }); } /** * 获取日志数据 * @param page 页数 */ fetchLogs(page) { this.setState({ loading: true, }); const _this = this; const result = fetch(`${domainPath}/v2/get/api/logs`, { method: 'post', credentials: 'include', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', }, body: encodeParams({ 'source': this.state.currentSource, 'operator_id': this.state.currentOperatorId, 'page': page, 'size': 10, 'keyword': this.state.currentKeyword, 'order_field': this.state.currentOrderField, 'order_type': this.state.currentOrderType, }), }); result.then(function (response) { // console.log(response); return response.json(); }).then(function (json) { let logs = []; json.collection.map((log) => { logs.push(log); }); _this.setState({ loading: false, logs: logs, maxLogListPageNumber: json.page, currentLogListPageNumber: page, }); }).catch(function (e) { console.log(e); }); } /** * 切换来源 * @param source 来源信息 */ switchSource(source) { this.setState({ operators: [], currentSource: source.index, currentKeyword: '', }, () => { this.switchOperator(this.defaultOperatorOption); this.fetchOperators(); }); // 切换来源时更新操作人列表 } /** * 切换操作人 * @param operator 操作人信息 */ switchOperator(operator) { this.setState({ currentOperatorId: operator.index, currentKeyword: '', }, () => { this.fetchLogs(1); }); // 切换操作人时更新日志列表 } /** * 设置搜索关键字 * @param keyword 搜索关键字 */ setKeyword(keyword) { this.setState({ currentKeyword: keyword, }, () => { this.fetchLogs(1) }); } /** * 设置排序 * @param field 排序字段 */ setOrder(field) { if (field !== this.state.currentOrderField) { // 不同字段默认升序排列 this.setState({ currentOrderField: field, currentOrderType: 'asc', }, () => { this.fetchLogs(1) }); } else { this.setState({ // 同字段改变排列顺序 currentOrderType: this.state.currentOrderType === 'asc' ? 'desc' : 'asc', }, () => { this.fetchLogs(1) }); } } render() { return ( <div> <div className={logStyle.filter}> <div> <Select width='250' name='source' title='日志来源' index={this.state.currentSource} options={logSource} callback={this.switchSource} /> </div> <div> <Select width='250' name='operatorId' title='操作人' index={this.state.currentOperatorId} options={this.state.operators} callback={this.switchOperator} /> </div> <div className={logStyle.searcher}> <SearchInput title='搜索' width='400' value={this.state.currentKeyword} callback={this.setKeyword} /> </div> </div> <div className={globalStyle.clear}></div> <LogList loading={this.state.loading} logs={this.state.logs} currentOrderField={this.state.currentOrderField} currentOrderType={this.state.currentOrderType} setOrder={this.setOrder} /> <Page maxPageNumber={this.state.maxLogListPageNumber} currentPageNumber={this.state.currentLogListPageNumber} callback={this.fetchLogs} /> </div> ); } } const mapStateToProps = (state) => { return { globalData: state.globalData, }; } export default connect( mapStateToProps )(Log);
//AUTHOR: Nickolas Davidson //COURSE: CPT 167 //PURPOSE: report //CREATEDATE: 09/29/2020 package edu.cpt167.davidson.exercise6; import java.util.Scanner; public class DavidsonMainClass { public static final double TAX_RATE = .075; public static final String DISCOUNT_NAME_MEMBER = "Member"; public static final String DISCOUNT_NAME_SENIOR = "Senior"; public static final String DISCOUNT_NAME_NONE = "No Discount"; public static final String DISCOUNT_NAME_QUIT = "Quit"; public static final double DISCOUNT_RATE_MEMBER = 0.15; public static final double DISCOUNT_RATE_SENIOR = 0.25; public static final double DISCOUNT_RATE_NONE = 0.0; public static final String ITEM_NAME_PREMIUM = "Boat"; public static final String ITEM_NAME_SPECIAL = "Shoes"; public static final String ITEM_NAME_BASIC = "Cooler"; public static final String ITEM_NAME_RETURN = "Return to Main Menu"; public static final double ITEM_PRICE_PREMIUM = 55.95; public static final double ITEM_PRICE_SPECIAL = 24.95; public static final double ITEM_PRICE_BASIC = 15.95; public static final int RESET_VALUE = 0; public static void main(String[] args) { //declare and initialize all variables Scanner input = new Scanner(System.in); String userName = ""; char rateSelection = ' '; char itemSelection = ' '; int howMany = 0; String discountName = ""; double discountRate = 0.0; String itemName = ""; double itemPrice = 0.0; double discountAmount = 0.0; double discountPrice = 0.0; double subTotal = 0.0; double tax = 0.0; double totalCost = 0.0; int memberCount = 0; int seniorCount = 0; int noDiscountCount = 0; double grandTotal = 0.0; int premiumCount = 0; int specialCount = 0; int basicCount = 0; double purchaseAmt = 0.0; //welcome banner displayWelcomeBanner(); //INPUT SECTION userName = getUserName(input); //Prime Read of rate selection rateSelection = validateMainMenu(input); //run-while while (rateSelection != 'Q') { //get and validate item value itemSelection = validateItemMenu(input); while (itemSelection != 'R') { //get and validate how many howMany = validateHowMany(input); //PROCESS SECTION //assignment name if (rateSelection == 'A') { discountName = DISCOUNT_NAME_MEMBER; discountRate = DISCOUNT_RATE_MEMBER; memberCount++; }//END of if else if (rateSelection == 'B') { discountName = DISCOUNT_NAME_SENIOR; discountRate = DISCOUNT_RATE_SENIOR; seniorCount++; }//END of else if else { discountName = DISCOUNT_NAME_NONE; discountRate = DISCOUNT_RATE_NONE; noDiscountCount++; }//END of else //assignment name if (itemSelection == 'A') { itemName = ITEM_NAME_PREMIUM; itemPrice = ITEM_PRICE_PREMIUM; premiumCount++; }//END of if else if(itemSelection == 'B') { itemName = ITEM_NAME_SPECIAL; itemPrice = ITEM_PRICE_SPECIAL; specialCount++; }//END of else if else { itemName = ITEM_NAME_BASIC; itemPrice = ITEM_PRICE_BASIC; basicCount++; }//END of else //increment counter //Assignments discountAmount = itemPrice * discountRate; discountPrice = itemPrice - discountAmount; purchaseAmt = howMany * discountPrice; subTotal = subTotal + purchaseAmt; //DISPLAY item receipt displayItemReceipt(itemName, itemPrice, discountName, discountRate, discountAmount, discountPrice, howMany, purchaseAmt, subTotal); //validate item selection itemSelection = validateItemMenu(input); }//END of while tax = subTotal * TAX_RATE; totalCost = subTotal + tax; grandTotal = grandTotal + totalCost; //display order total displayOrderTotal(userName, subTotal, tax, totalCost); subTotal = RESET_VALUE; //Validate main menu rateSelection = validateMainMenu(input); }//END of while //validate grand total is greater than 0 before displaying final report if (grandTotal > 0.0) { //display final report displayFinalReport(memberCount, seniorCount, noDiscountCount, premiumCount, specialCount, basicCount, grandTotal); }//END of report structure //display farewell message displayFarewellMessage(); //close Scanner input.close(); }//END of main method //get user name //returns value back to main public static String getUserName(Scanner borrowedInput) { String localUserName = ""; System.out.println("To begin, may I have your first name: "); localUserName = borrowedInput.next(); return localUserName; }//END of prompt //Discount menu public static void displayMainMenu() { System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.printf("DISCOUNT MENU\n"); System.out.printf("%-3s%2s%6s%12.1f%1s\n", "[A]", " for ", DISCOUNT_NAME_MEMBER, DISCOUNT_RATE_MEMBER*100, "%"); System.out.printf("%-3s%2s%6s%12.1f%1s\n", "[B]", " for ", DISCOUNT_NAME_SENIOR, DISCOUNT_RATE_SENIOR*100, "%"); System.out.printf("%-3s%2s%8s%7.1f%1s\n", "[C]", " for ", DISCOUNT_NAME_NONE, DISCOUNT_RATE_NONE*100, "%"); System.out.printf("%-3s%2s%3s\n", "[Q]", " to ", DISCOUNT_NAME_QUIT); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("Enter your selection here: "); }//END of menu //requests item from the user and validates the input //before returning the validated value back to main public static char validateMainMenu(Scanner borrowedinput)//Scanner was declared and renamed { char localRateSelection; displayMainMenu(); localRateSelection = borrowedinput.next().toUpperCase().charAt(0); //must validate input while (localRateSelection != 'A' && localRateSelection != 'B' && localRateSelection != 'C' && localRateSelection != 'Q') { System.out.println("\nInvalid discount rate selected"); displayMainMenu(); localRateSelection = borrowedinput.next().toUpperCase().charAt(0); } return localRateSelection; }//END of rate selection VR method //Item menu public static void displayItemMenu() { System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("ITEM MENU"); System.out.printf("%-3s%2s%3s%10s%4.2f\n", "[A]", " for ", ITEM_NAME_PREMIUM, " $ ", ITEM_PRICE_PREMIUM); System.out.printf("%-3s%2s%3s%9s%4.2f\n", "[B]", " for ", ITEM_NAME_SPECIAL, " $ ", ITEM_PRICE_SPECIAL); System.out.printf("%-3s%2s%3s%8s%4.2f\n", "[C]", " for ", ITEM_NAME_BASIC, " $ ", ITEM_PRICE_BASIC); System.out.printf("%-3s%2s%5s\n","[R]", " to ", ITEM_NAME_RETURN); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("Enter your selection here: "); }//END of menu //requests item from the user and validates the input //before returning the validated value back to main public static char validateItemMenu(Scanner borrowedinput) { char localItemSelection; displayItemMenu(); localItemSelection = borrowedinput.next().toUpperCase().charAt(0); //must validate input while (localItemSelection != 'A' && localItemSelection != 'B' && localItemSelection != 'C' && localItemSelection != 'R') { //display error System.out.println("\nInvalid item selected.\n"); displayItemMenu(); localItemSelection = borrowedinput.next().toUpperCase().charAt(0); } return localItemSelection; }//END of item VR method //Requests how many from the user and validates the input //before returning the validated value back to main public static int validateHowMany(Scanner borrowedinput) { int localHowMany;//declared and initialize local variable //Prime Read System.out.println("\nEnter how many you would like: "); localHowMany = borrowedinput.nextInt(); System.out.println(); //validate input while (localHowMany <= 0) { //display error System.out.println("Value cannot be less than 0.\n"); System.out.println("\nPlease enter another amount: "); localHowMany = borrowedinput.nextInt(); } return localHowMany; }//END of how many VR method //Welcome Banner public static void displayWelcomeBanner() { System.out.println("Welcome to our store!"); System.out.println("This will allow you to input"); System.out.println("values and select the right"); System.out.println("item for you and calculate your total!"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); }//END of Welcome Banner //Farewell Message public static void displayFarewellMessage() { System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("This concludes the program"); System.out.println("Thank you for joining us today!"); }//END of farewell message //prints report to console //no value is returned to main public static void displayItemReceipt(String borrowedItemName, double borrowedItemPrice, String borrowedDiscountName, double borrowedDiscountRate, double borrowedDiscountAmount, double borrowedDiscountPrice, int borrowedHowMany, double borrowedPurchaseAmt, double borrowedSubTotal) { //Display item receipt System.out.println("~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~"); System.out.println("Item Report"); System.out.println("~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~"); System.out.printf("%-15s%2s%5s\n", "Item Name", "", borrowedItemName); System.out.printf("%-17s%-5s%3.2f\n", "Original Price", " $ ", borrowedItemPrice); System.out.printf("%-16s%2s%5s\n", "Discount Type", "", borrowedDiscountName); System.out.printf("%-17s%9s%1s\n", "Discount Rate", borrowedDiscountRate*100, "%"); System.out.printf("%-17s%-6s%4.2f\n", "Discount Amount", " $ ", borrowedDiscountAmount); System.out.printf("%-17s%-5s%4.2f\n", "Discounted Price", " $ ", borrowedDiscountPrice); System.out.printf("Quantity %18d%n", borrowedHowMany); System.out.printf("%-17s%-5s%4.2f\n", "Purchase Amount", " $ ", borrowedPurchaseAmt); System.out.printf("%-17s%-5s%4.2f\n", "Subtotal", " $ ", borrowedSubTotal); }//END of item receipt method //prints order report to console //no value returned to main public static void displayOrderTotal(String borrowedUserName , double borrowedSubTotal, double borrowedTax, double borrowedTotalCost) { //Display order report System.out.println("~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~"); System.out.println("Order Report"); System.out.println("~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~"); System.out.printf("%-9s%2s%5s\n", "User", "", borrowedUserName); System.out.printf("%-12s%-6s%4.2f\n", "Subtotal", " $ ", borrowedSubTotal); System.out.printf("%-12s%-7s%4.2f\n", "Tax", " $ ", borrowedTax); System.out.printf("%-12s%-5s%4.2f\n", "Total Cost", " $ ", borrowedTotalCost); System.out.println("~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~"); }//END of order report method //prints final report to console //no value returned to main public static void displayFinalReport(int borrowedMemberCount, int borrowedSeniorCount, int borrowedNoDiscountCount, int borrowedPremiumCount, int borrowedSpecialCount, int borrowedBasicCount, double borrowedGrandTotal) { //display final report System.out.println("~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~"); System.out.println("Final Report"); System.out.println("~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~"); System.out.println("Count of discount types: "); System.out.printf("%-15s%2s%10d\n", "Member Count", "", borrowedMemberCount); System.out.printf("%-15s%2s%10d\n", "Senior Count", "", borrowedSeniorCount); System.out.printf("%-15s%2s%8d\n", "No Discount Count", "", borrowedNoDiscountCount); System.out.println("~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~"); System.out.println("Count of item types: "); System.out.printf("%-15s%2s%10d\n", ITEM_NAME_PREMIUM, "", borrowedPremiumCount); System.out.printf("%-15s%2s%10d\n", ITEM_NAME_SPECIAL, "", borrowedSpecialCount); System.out.printf("%-15s%2s%10d\n", ITEM_NAME_BASIC, "", borrowedBasicCount); System.out.println("~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~"); System.out.printf("%-18s%3s%5.2f\n", "Grand Total", " $ ", borrowedGrandTotal); System.out.println("~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~ ~~~~"); }//END of Final Report method }//END of class
package com.lilu.multithread; import java.util.LinkedList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConsumerProducer2<T> { final private LinkedList<T> list = new LinkedList<>(); final private int MAX = 10; private int count = 0; private Lock lock = new ReentrantLock(); private Condition producer = lock.newCondition(); private Condition consumer = lock.newCondition(); /** * 往队列中生成数据 * * @param t */ public void put(T t) { try { lock.lock(); while (list.size() == MAX) { producer.await(); } list.add(t); ++count; consumer.signalAll(); // 通知消费者 } catch (InterruptedException e) { throw new RuntimeException(e); } finally { lock.unlock(); } } public T get() { T t = null; try { lock.lock(); while (list.size() == 0) { consumer.await(); } t = list.removeFirst(); count--; producer.signalAll(); // 通知生产者继续生产 } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } return t; } public static void main(String[] args) { ConsumerProducer2<String> c = new ConsumerProducer2<>(); // 启动消费者线程 for (int i = 0; i < 5; i++) { new Thread(() -> { for (int j = 0; j < 5; j++) { System.out.println(c.get()); } }, "c" + i).start(); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { throw new RuntimeException(e); } // 启动生产者线程,生产的数量一定要大于消费的数量,否则线程等待 for (int i = 0; i < 6; i++) { new Thread(() -> { for (int j = 0; j < 5; j++) { c.put(Thread.currentThread().getName() + " " + j); } }, "c" + i).start(); } } }
--- title: "Getting Started with Terraform" date: 2023-06-16T08:35:01-06:00 tags: ["software", "infrastructure"] --- In getting moving with Terraform, [you'll want to have an eye on what you're going to do with your state](/posts/terraform-state-management). Proper management and planning is going to be critical for any real project. However, getting familiar with the tool itself is a good starting point in using it. For this post, we'll think only about the fundatmentals of Terraform and just start on deploying infrastructure without worrying about state management. We'll use state, but will just use the default of storing on disk locally. This is not a safe way of managing infrastructure with a team, but it will get us started on using the tool. To illustrate starting with Terraform, I'm just going to create a new Git repository and use it to set up a provider and create some simple resources. The provider I'll use, as an example, is a [provider for Docker](https://registry.terraform.io/providers/kreuzwerker/docker/latest/docs). This provider makes resource types available to be able to pull Docker images from registries and create containers from images. I'll just here play a little bit with creating such resources locally on my machine. I'll likely write more about Docker in the future. For now, it's just an example of something we'll use to create resources and we'll do that via the above mentioned provider in a Terraform configuration. I'll use a POSIX-compatible shell in these examples. This should work in pretty much every environment. It should be straightforward to just use a default terminal (with a default shell or your favorite shell) anywhere other than Windows. If you're using Windows, this will not work with the `cmd` or `Powershell` shells. I generally recommend doing most of your dev work in a Linux distro in [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/) when you're using Windows. If not that, you can still use these commands on Windows using an emulation layer or something of the sort, such as Git Bash. I can write more about these topics at some point in the future. To successfully execute everything in the example, you'll need to have Docker, Git, curl, and Terraform installed. First, a new repository from nothing: ``` sh mkdir sample-docker-infrastrcture cd sample-docker-infrastrcture git init ``` Then, let's add a [gitignore](https://git-scm.com/docs/gitignore) file, approriate for Terraform, so we'll not have inordinate noise in Git status and we'll not risk committing files we don't want in our repository. This downloads a file from offered and maintained by GitHub as a default starting point for a gitignore for Terraform. ``` sh curl --output .gitignore https://raw.githubusercontent.com/github/gitignore/main/Terraform.gitignore git add .gitignore git commit -m "Add gitignore to reduce noise and increase safety" ``` With that overhead out of the way, we're ready to start doing the Terraform things. The first of those will be to set up a provider. To start on that, we'll first need to create a file in which to configure the provider. Let's just make a file called `main.tf`. ``` sh touch main.tf ``` In this new file, we'll set up a provider. We do this with the [HashiCorp configuration language](https://github.com/hashicorp/hcl) ``` terraform terraform { required_providers { docker = { source = "kreuzwerker/docker" version = "3.0.2" } } } provider "docker" { } ``` Generally, you can find good documentation for whatever provider you want to use with Terraform on the [Terraform Registry](https://registry.terraform.io/) site. In this case, we've just lifted the required configuration from the Docker provider from the information on the documentation for that provider (via the purple `Use Provider` button on that site). Terraform requires, after setting up providers, that you initialize your workspace to work with your selected providers. This downloads the providers you have configured, creates a lock file for consistent versioning and execution, and creates a starting point for your state. Had we configured a backend for our state to store it somewhere other than locally, it would go and set up state in that location (and/or read existing state already there). Because we didn't set up a backend, it it here, instead create files on local disk. To initialize, use: ``` sh terraform init ``` If you look at your filesystem in the current directory, you should notice there's a new, hidden, subdirectory created called `.terraform`. You should also see a new, hidden, file called .terraform.lock.hcl. These are expected. It is inside the .terraform directory that the files implementing the provider(s) where downloaded and your state is stored. `git status` should reveal that the only untracked files showing in your repository are the new `main.tf` file you created explicitly, and the lock file created by Terraform when you ran `terraform init`. This is a good place to go ahead and create a commit, having completed an atomic operation in our setup. ``` sh git add main.tf. git add .terraform.lock.hcl git commit -m "Add and initialize Docker provider to enable creating resources with Terraform using Docker with the version pinned for consistent operation" ``` Note that, due to our ignore file, we've commited our Terraform HCL confdiguration and the version lock file, but not any of the provider binaries or any Terraform state. This is as it should be and the reason we set up the ignore file. Now, in the same file (main.tf), go ahead and create a couple resources (below the provider configuration already there). ``` terraform # Pulls the image resource "docker_image" "nginx" { name = "nginx:latest" } # Create a container resource "docker_container" "foo" { image = docker_image.nginx.image_id name = "samplecontainer" } ``` This sample has two blocks, each of them resources. This is essentially what is shown in the documentation as samples for the Docker provider. Executing on this will create two resources. Before we execute on creating these resources, it's a good idea to first use Terraform's plan verb to see what we will create. That looks like this: ``` sh terraform plan ``` The output of that command looks like this: ``` sh Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # docker_container.sample will be created + resource "docker_container" "sample" { + attach = false + bridge = (known after apply) + command = (known after apply) + container_logs = (known after apply) + container_read_refresh_timeout_milliseconds = 15000 + entrypoint = (known after apply) + env = (known after apply) + exit_code = (known after apply) + hostname = (known after apply) + id = (known after apply) + image = (known after apply) + init = (known after apply) + ipc_mode = (known after apply) + log_driver = (known after apply) + logs = false + must_run = true + name = "nginxsample" + network_data = (known after apply) + read_only = false + remove_volumes = true + restart = "no" + rm = false + runtime = (known after apply) + security_opts = (known after apply) + shm_size = (known after apply) + start = true + stdin_open = false + stop_signal = (known after apply) + stop_timeout = (known after apply) + tty = false + wait = false + wait_timeout = 60 } # docker_image.nginx will be created + resource "docker_image" "nginx" { + id = (known after apply) + image_id = (known after apply) + name = "nginx:latest" + repo_digest = (known after apply) } Plan: 2 to add, 0 to change, 0 to destroy. ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now. ``` This is what we expect. Two resources will be created. One will represent the pulling of the image and the other the creation of a container from that imaage. Deploy these resources to Docker, running on your machine, with the following command. `terraform apply` first does a plan, and then it asks for confirmatino that you really want to execute on the plan. You can either give a parameter to the command to run without the prompt, or respond `yes` to the prompt to cause Terraform to actually create (and/or destroy) actual resources. Becauase we started with empty state, indicating resources don't already exist, and there are two resources in the configuration not in that state, the plan indicates the creation of two resources and application of the plan will actually create those resources. ``` sh terraform apply ``` The output will look like this (including having keyed `yes` in response to the prompt): ``` sh Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # docker_container.foo will be created + resource "docker_container" "foo" { + attach = false + bridge = (known after apply) + command = (known after apply) + container_logs = (known after apply) + container_read_refresh_timeout_milliseconds = 15000 + entrypoint = (known after apply) + env = (known after apply) + exit_code = (known after apply) + hostname = (known after apply) + id = (known after apply) + image = (known after apply) + init = (known after apply) + ipc_mode = (known after apply) + log_driver = (known after apply) + logs = false + must_run = true + name = "samplecontainer" + network_data = (known after apply) + read_only = false + remove_volumes = true + restart = "no" + rm = false + runtime = (known after apply) + security_opts = (known after apply) + shm_size = (known after apply) + start = true + stdin_open = false + stop_signal = (known after apply) + stop_timeout = (known after apply) + tty = false + wait = false + wait_timeout = 60 } # docker_image.nginx will be created + resource "docker_image" "nginx" { + id = (known after apply) + image_id = (known after apply) + name = "nginx:latest" + repo_digest = (known after apply) } Plan: 2 to add, 0 to change, 0 to destroy. Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes docker_image.nginx: Creating... docker_image.nginx: Creation complete after 9s [id=sha256:2d21d843073b4df6a03022861da4cb59f7116c864fe90b3b5db3b90e1ce932d3nginx:latest] docker_container.foo: Creating... docker_container.foo: Creation complete after 0s [id=c5c4e317d9b1c0d34185267549db5b357662416fc0f7f764b32e7c956438539d] ``` You should now be able to confirm, using `docker image ls` and `docker container ls` that you have pulled an image and created a container. Now, do one more thing. Let's tear down what we've created. ``` sh terraform destroy ``` The same confrmation will be required. When you give it, the output should look like this: ``` sh docker_image.nginx: Refreshing state... [id=sha256:2d21d843073b4df6a03022861da4cb59f7116c864fe90b3b5db3b90e1ce932d3nginx:latest] docker_container.foo: Refreshing state... [id=c5c4e317d9b1c0d34185267549db5b357662416fc0f7f764b32e7c956438539d] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: - destroy Terraform will perform the following actions: # docker_container.foo will be destroyed - resource "docker_container" "foo" { - attach = false -> null - command = [ - "nginx", - "-g", - "daemon off;", ] -> null - container_read_refresh_timeout_milliseconds = 15000 -> null - cpu_shares = 0 -> null - dns = [] -> null - dns_opts = [] -> null - dns_search = [] -> null - entrypoint = [ - "/docker-entrypoint.sh", ] -> null - env = [] -> null - group_add = [] -> null - hostname = "c5c4e317d9b1" -> null - id = "c5c4e317d9b1c0d34185267549db5b357662416fc0f7f764b32e7c956438539d" -> null - image = "sha256:2d21d843073b4df6a03022861da4cb59f7116c864fe90b3b5db3b90e1ce932d3" -> null - init = false -> null - ipc_mode = "private" -> null - log_driver = "json-file" -> null - log_opts = {} -> null - logs = false -> null - max_retry_count = 0 -> null - memory = 0 -> null - memory_swap = 0 -> null - must_run = true -> null - name = "samplecontainer" -> null - network_data = [ - { - gateway = "172.17.0.1" - global_ipv6_address = "" - global_ipv6_prefix_length = 0 - ip_address = "172.17.0.3" - ip_prefix_length = 16 - ipv6_gateway = "" - mac_address = "02:42:ac:11:00:03" - network_name = "bridge" }, ] -> null - network_mode = "default" -> null - privileged = false -> null - publish_all_ports = false -> null - read_only = false -> null - remove_volumes = true -> null - restart = "no" -> null - rm = false -> null - runtime = "runc" -> null - security_opts = [] -> null - shm_size = 64 -> null - start = true -> null - stdin_open = false -> null - stop_signal = "SIGQUIT" -> null - stop_timeout = 0 -> null - storage_opts = {} -> null - sysctls = {} -> null - tmpfs = {} -> null - tty = false -> null - wait = false -> null - wait_timeout = 60 -> null } # docker_image.nginx will be destroyed - resource "docker_image" "nginx" { - id = "sha256:2d21d843073b4df6a03022861da4cb59f7116c864fe90b3b5db3b90e1ce932d3nginx:latest" -> null - image_id = "sha256:2d21d843073b4df6a03022861da4cb59f7116c864fe90b3b5db3b90e1ce932d3" -> null - name = "nginx:latest" -> null - repo_digest = "nginx@sha256:593dac25b7733ffb7afe1a72649a43e574778bf025ad60514ef40f6b5d606247" -> null } Plan: 0 to add, 0 to change, 2 to destroy. Do you really want to destroy all resources? Terraform will destroy all your managed infrastructure, as shown above. There is no undo. Only 'yes' will be accepted to confirm. Enter a value: yes docker_container.foo: Destroying... [id=c5c4e317d9b1c0d34185267549db5b357662416fc0f7f764b32e7c956438539d] docker_container.foo: Destruction complete after 0s docker_image.nginx: Destroying... [id=sha256:2d21d843073b4df6a03022861da4cb59f7116c864fe90b3b5db3b90e1ce932d3nginx:latest] docker_image.nginx: Destruction complete after 0s Destroy complete! Resources: 2 destroyed. ``` Again, `docker image ls` and `docker container ls` should confirm the destruction of these resources. Don't forget to put your resources into your Git repository so you can create them again and have a record of what you've done. ``` sh git add main.tf git commit -m "Add Docker resources to pull an images and create a container as a sample of what we can do with a Terraform provider" ``` This should get you a rudimentary start on seeing what Terraform can do. I have only scratched the surface here, but it's a start. I'll write more about going further and how you might start to create some real and useful resources, especially using providers for the public clouds and such. There is much more to know.
In Python, a return statement is used to return a value from a function. When a return statement is executed, the function immediately exits, and any subsequent code in the function is not executed. Here's an example of a function that returns the sum of two numbers: def add_numbers(x, y): sum = x + y return sum In this example, the return statement is used to return the value of sum back to the calling code. You can also use return statement without a value to exit a function early. For example, consider the following function that checks if a number is even: def is_even(number): if number % 2 == 0: return True else: return False In this example, if the number is even, the function immediately returns True using the return statement. If the number is odd, it returns False. You can also use the return statement to return multiple values from a function as a tuple. Here's an example: def get_name_and_age(): name = "John" age = 25 return name, age In this example, the function returns a tuple containing the name and age variables. The calling code can then unpack the tuple to access these values separately.
package Graphs; import java.util.*; // Topological is done on Directed Acyclic Graphs // A Java program to print topological // sorting of a graph using indegrees import java.util.ArrayList; // Class to represent a graph class Graph { // No. of vertices int V; // An Array of List which contains // references to the Adjacency List of // each vertex ArrayList<Integer> adj[]; // Constructor public Graph(int V) { this.V = V; adj = new ArrayList[V]; for (int i = 0; i < V; i++) adj[i] = new ArrayList<Integer>(); } // Function to add an edge to graph public void addEdge(int u, int v) { adj[u].add(v); } // prints a Topological Sort of the // complete graph public void topologicalSort() { int indegree[] = new int[V]; for (int i = 0; i < V; i++) { ArrayList<Integer> temp = (ArrayList<Integer>) adj[i]; for (int node : temp) { indegree[node]++; } } Queue<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < V; i++) { if (indegree[i] == 0) q.add(i); } // Initialize count of visited vertices int cnt = 0; // Create a vector to store result // (A topological ordering of the vertices) Vector<Integer> topOrder = new Vector<Integer>(); while (!q.isEmpty()) { int u = q.poll(); topOrder.add(u); for (int node : adj[u]) { // If in-degree becomes zero, // add it to queue if (--indegree[node] == 0) q.add(node); } cnt++; } // Check if there was a cycle if (cnt != V) { System.out.println( "There exists a cycle in the graph"); return; } // Print topological order for (int i : topOrder) { System.out.print(i + " "); } } } class Main { public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); System.out.println( "Following is a Topological Sort"); g.topologicalSort(); } }
/\* This is no longer called by us anymore because it interferes with the pixel manipulation of floor/ceiling texture mapping. https://stackoverflow.com/a/46920541/1645045 https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio sharpenCanvas() { // Set display size (css pixels). let sizew = this.displayWidth; let sizeh = this.displayHeight; this.mainCanvas.style.width = sizew + "px"; this.mainCanvas.style.height = sizeh + "px"; // Set actual size in memory (scaled to account for extra pixel density). let scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas. this.mainCanvas.width = Math.floor(sizew * scale); this.mainCanvas.height = Math.floor(sizeh * scale); // Normalize coordinate system to use css pixels. this.mainCanvasContext.scale(scale, scale); } \*/ // Draws the entire sprite // drawSprite(rayHit) // { // let rc = this.spriteScreenPosition(rayHit.sprite) // this.drawTexturedWall(this.spriteImageData, 0, 0, this.textureSize, this.textureSize, rc.x, rc.y, rc.w, rc.h) // } /\*\* - Draws only the vertical part of the sprite corresponding to the current screen strip \*/ /\* Floor Casting Algorithm: We want to find the location where the ray hits the floor (F) 1. Find the distance of F from the player's "feet" 2. Rotate the distance using the current ray angle to find F relative to the player 3. Translate the F using the player's position to get its world coordinates 4. Map the world coordinates to texture coordinates Step 1 is the most complicated and the following explains how to calculate the floor distance Refer to the diagram below. To get the floor distance relative to the player, we can use similar triangle principle: dy = height between current screen y and center y = y - (displayHeight/2) floorDistance / eyeHeight = currentViewDistance / dy floorDistance = eyeHeight * currentViewDistance / dy current <-view distance-> - +----------------E <-eye ^ | / ^ dy--> | | / | | | / | ray v | / | \ - y |<--eyeHeight \ / | | \ / |<--view | / | plane | / | | / | v F-------------------------------------- Floor bottom <---------- floorDistance ----------> But we need to know the current view distance. The view distance is not constant! In the center of the screen the distance is shortest. But for other angles it changes and is longer. player center ray F | \ | \ <-dx->| ----------x------+-- view plane ----- currentViewDistance \ | ^ | \ | | +-----> \ | center view distance \ | | \ | | \| v O-------------------- We can calculate the current view distance using Pythogaras theorem: x = current strip x dx = distance of x from center of screen dx = abs(screenWidth/2 - x) currentViewDistance = sqrt(dx*dx + viewDist*viewDist) We calculate and save all the view distances in this.viewDistances using createViewDistances() \*/ /\* CREATE RAY ANGLES Calculate and save the ray angles from left to right of screen. screenX <------ +-----+------+ ^ \ | / | \ | / | \ | / | this.viewDist \ | / | \a| / | \|/ | v v tan(a) = screenX / this.viewDist a = atan( screenX / this.viewDist ) \*/ /\* on cell hit - Called when a cell in the grid has been hit by the current ray - - If searching for vertical lines, return true to continue search for next vertical line, - or false to stop searching for vertical lines - - If searching for horizontal lines, return true to continue search for next horizontal line - or false to stop searching for horizontal lines - - @param ray Current RayState - @return true to continue searching for next line, false otherwise \*/
package br.com.salomaotech.genesys.controller.fornecedor; import br.com.salomaotech.genesys.model.fornecedor.FornecedorModelo; import br.com.salomaotech.genesys.view.JFfornecedor; import br.com.salomaotech.sistema.jpa.Repository; import br.com.salomaotech.sistema.swing.PopUp; import org.junit.Test; import static org.junit.Assert.*; public class FornecedorMetodosTest { private final JFfornecedor view = new JFfornecedor(); private FornecedorModelo fornecedorModelo = new FornecedorModelo(); private final FornecedorMetodos fornecedorMetodos = new FornecedorMetodos(view); public FornecedorMetodosTest() { /* simula cadastro de fornecedor */ new Repository(new FornecedorModelo()).deleteTodos(); fornecedorModelo.setNome("Teste"); fornecedorModelo.setCnpj("00.000.000/0001-00"); fornecedorModelo.setCep("75370-000"); fornecedorModelo.setRua("01"); fornecedorModelo.setQuadra("02"); fornecedorModelo.setLote("03"); fornecedorModelo.setNumero("04"); fornecedorModelo.setUf("GO"); fornecedorModelo.setBairro("A"); fornecedorModelo.setCidade("B"); fornecedorModelo.setComplemento("C"); fornecedorModelo.setTelefone("62 0000-0000"); fornecedorModelo.setEmail("abc123@email.com"); fornecedorModelo.setContato("Fulano de tal"); new Repository(fornecedorModelo).save(); } @Test public void testPopularFormulario() { /* popula os dados do modelo na view */ fornecedorMetodos.popularFormulario(fornecedorModelo); /* testa se os dados populados são iguais aos dados no modelo */ System.out.println("Testando classe FornecedorMetodos metodo: popularFormulario"); assertEquals(true, view.getId() == fornecedorModelo.getId()); assertEquals(true, view.jTbasicoNome.getText().equals(fornecedorModelo.getNome())); assertEquals(true, view.jFbasicoCnpj.getText().equals(fornecedorModelo.getCnpj())); assertEquals(true, view.jFenderecoCep.getText().equals(fornecedorModelo.getCep())); assertEquals(true, view.jTenderecoRua.getText().equals(fornecedorModelo.getRua())); assertEquals(true, view.jTenderecoQuadra.getText().equals(fornecedorModelo.getQuadra())); assertEquals(true, view.jTenderecoLote.getText().equals(fornecedorModelo.getLote())); assertEquals(true, view.jTenderecoNumero.getText().equals(fornecedorModelo.getNumero())); assertEquals(true, view.jCenderecoUf.getSelectedItem().toString().equals(fornecedorModelo.getUf())); assertEquals(true, view.jTenderecoBairro.getText().equals(fornecedorModelo.getBairro())); assertEquals(true, view.jTenderecoCidade.getText().equals(fornecedorModelo.getCidade())); assertEquals(true, view.jTenderecoComplemento.getText().equals(fornecedorModelo.getComplemento())); assertEquals(true, view.jTcontatoTelefone.getText().equals(fornecedorModelo.getTelefone())); assertEquals(true, view.jTcontatoEmail.getText().equals(fornecedorModelo.getEmail())); assertEquals(true, view.jTcontato.getText().equals(fornecedorModelo.getContato())); } @Test public void testResetarView() { /* reseta a view */ fornecedorMetodos.resetarView(); /* testa se os dados populados na view foram resetados */ System.out.println("Testando classe FornecedorMetodos metodo: resetarView"); assertEquals(true, view.getId() == 0); assertEquals(true, view.jTbasicoNome.getText().equals("")); assertEquals(true, view.jFbasicoCnpj.getText().equals(" . . / - ")); assertEquals(true, view.jFenderecoCep.getText().equals(" - ")); assertEquals(true, view.jTenderecoRua.getText().equals("")); assertEquals(true, view.jTenderecoQuadra.getText().equals("")); assertEquals(true, view.jTenderecoLote.getText().equals("")); assertEquals(true, view.jTenderecoNumero.getText().equals("")); assertEquals(true, view.jCenderecoUf.getSelectedIndex() == 0); assertEquals(true, view.jTenderecoBairro.getText().equals("")); assertEquals(true, view.jTenderecoCidade.getText().equals("")); assertEquals(true, view.jTenderecoComplemento.getText().equals("")); assertEquals(true, view.jTcontatoTelefone.getText().equals("")); assertEquals(true, view.jTcontatoEmail.getText().equals("")); assertEquals(true, view.jTcontato.getText().equals("")); } @Test public void testHabilitarCampos() { /* é esperado que alguns campos estejam desabilitados */ fornecedorMetodos.habilitarCampos(); /* testa se os campos estão desabilitados */ System.out.println("Testando classe FornecedorMetodos metodo: habilitarCampos Etapa 01"); assertEquals(false, view.jBcadastroExcluir.isEnabled()); /* é esperado que alguns campos estejam habilitados */ fornecedorMetodos.popularFormulario(fornecedorModelo); fornecedorMetodos.habilitarCampos(); /* é esperado que alguns campos estejam habilitados */ System.out.println("Testando classe FornecedorMetodos metodo: habilitarCampos Etapa 02"); assertEquals(true, view.jBcadastroExcluir.isEnabled()); } @Test public void testAddPopUpMenu() { /* adiciona menu de popup */ fornecedorMetodos.addPopUpMenu(); PopUp popUp = new PopUp(); /* testa se os eventos de pop menu foram adicionados */ System.out.println("Testando classe FornecedorMetodos metodo: addPopUpMenu"); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTbasicoNome)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jFbasicoCnpj)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jFenderecoCep)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTenderecoRua)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTenderecoQuadra)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTenderecoLote)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTenderecoNumero)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTenderecoBairro)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTenderecoCidade)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTenderecoComplemento)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTcontatoTelefone)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTcontatoEmail)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTpesquisaNome)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTpesquisaCnpj)); assertEquals(true, popUp.isMenuPopUpAdicionado(view.jTcontato)); } @Test public void testAbrirCadastro() { /* abre o cadastro já realizado no construtor */ fornecedorMetodos.abrirCadastro(fornecedorModelo.getId()); /* testa se os dados populados são iguais aos dados no modelo */ System.out.println("Testando classe FornecedorMetodos metodo: abrirCadastro"); assertEquals(true, view.getId() == fornecedorModelo.getId()); assertEquals(true, view.jTbasicoNome.getText().equals(fornecedorModelo.getNome())); assertEquals(true, view.jFbasicoCnpj.getText().equals(fornecedorModelo.getCnpj())); assertEquals(true, view.jFenderecoCep.getText().equals(fornecedorModelo.getCep())); assertEquals(true, view.jTenderecoRua.getText().equals(fornecedorModelo.getRua())); assertEquals(true, view.jTenderecoQuadra.getText().equals(fornecedorModelo.getQuadra())); assertEquals(true, view.jTenderecoLote.getText().equals(fornecedorModelo.getLote())); assertEquals(true, view.jTenderecoNumero.getText().equals(fornecedorModelo.getNumero())); assertEquals(true, view.jCenderecoUf.getSelectedItem().toString().equals(fornecedorModelo.getUf())); assertEquals(true, view.jTenderecoBairro.getText().equals(fornecedorModelo.getBairro())); assertEquals(true, view.jTenderecoCidade.getText().equals(fornecedorModelo.getCidade())); assertEquals(true, view.jTenderecoComplemento.getText().equals(fornecedorModelo.getComplemento())); assertEquals(true, view.jTcontatoTelefone.getText().equals(fornecedorModelo.getTelefone())); assertEquals(true, view.jTcontatoEmail.getText().equals(fornecedorModelo.getEmail())); assertEquals(true, view.jTcontato.getText().equals(fornecedorModelo.getContato())); } @Test public void testPesquisar() { /* usando filtro: nenhum */ view.jTpesquisaNome.setText(null); view.jTpesquisaCnpj.setText(null); fornecedorMetodos.pesquisar(); System.out.println("Testando classe FornecedorMetodos metodo: pesquisar etapa 01"); assertEquals(true, view.jTresultados.getRowCount() > 0); /* usando filtro: nome */ view.jTpesquisaNome.setText(fornecedorModelo.getNome()); view.jTpesquisaCnpj.setText(null); fornecedorMetodos.pesquisar(); System.out.println("Testando classe FornecedorMetodos metodo: pesquisar etapa 02"); assertEquals(true, view.jTresultados.getRowCount() > 0); /* usando filtro: cnpj */ view.jTpesquisaNome.setText(null); view.jTpesquisaCnpj.setText(fornecedorModelo.getCnpj()); fornecedorMetodos.pesquisar(); System.out.println("Testando classe FornecedorMetodos metodo: pesquisar etapa 03"); assertEquals(true, view.jTresultados.getRowCount() > 0); /* usando filtro: todos */ view.jTpesquisaNome.setText(fornecedorModelo.getNome()); view.jTpesquisaCnpj.setText(fornecedorModelo.getCnpj()); fornecedorMetodos.pesquisar(); System.out.println("Testando classe FornecedorMetodos metodo: pesquisar etapa 04"); assertEquals(true, view.jTresultados.getRowCount() > 0); } @Test public void testSalvar() { /* popula o formulário simulando o preenchimento dos dados */ fornecedorMetodos.popularFormulario(fornecedorModelo); /* salva para que a ID possa ser gerada e popula novamente para pegar a ID de cadastro */ fornecedorModelo = fornecedorMetodos.salvar(); fornecedorMetodos.popularFormulario(fornecedorModelo); /* testa se os dados populados são iguais aos dados no modelo */ System.out.println("Testando classe FornecedorMetodos metodo: salvar"); assertEquals(true, view.getId() == fornecedorModelo.getId()); assertEquals(true, view.jTbasicoNome.getText().equals(fornecedorModelo.getNome())); assertEquals(true, view.jFbasicoCnpj.getText().equals(fornecedorModelo.getCnpj())); assertEquals(true, view.jFenderecoCep.getText().equals(fornecedorModelo.getCep())); assertEquals(true, view.jTenderecoRua.getText().equals(fornecedorModelo.getRua())); assertEquals(true, view.jTenderecoQuadra.getText().equals(fornecedorModelo.getQuadra())); assertEquals(true, view.jTenderecoLote.getText().equals(fornecedorModelo.getLote())); assertEquals(true, view.jTenderecoNumero.getText().equals(fornecedorModelo.getNumero())); assertEquals(true, view.jCenderecoUf.getSelectedItem().toString().equals(fornecedorModelo.getUf())); assertEquals(true, view.jTenderecoBairro.getText().equals(fornecedorModelo.getBairro())); assertEquals(true, view.jTenderecoCidade.getText().equals(fornecedorModelo.getCidade())); assertEquals(true, view.jTenderecoComplemento.getText().equals(fornecedorModelo.getComplemento())); assertEquals(true, view.jTcontatoTelefone.getText().equals(fornecedorModelo.getTelefone())); assertEquals(true, view.jTcontatoEmail.getText().equals(fornecedorModelo.getEmail())); assertEquals(true, view.jTcontato.getText().equals(fornecedorModelo.getContato())); } @Test public void testExcluir() { /* popula os dados do modelo na view */ fornecedorMetodos.popularFormulario(fornecedorModelo); /* testa exclusão */ System.out.println("Testando classe FornecedorMetodos metodo: excluir"); assertEquals(true, fornecedorMetodos.excluir()); } }
namespace MarketVault.Core.Services.Impementations { using MarketVault.Core.Exceptions; using MarketVault.Core.Services.Interfaces; using MarketVault.Infrastructure.Data.Models; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; /// <summary> /// UserService /// </summary> public class UserService : IUserService { /// <summary> /// User manager /// </summary> private readonly UserManager<ApplicationUser> userManager = null!; /// <summary> /// Role manager /// </summary> private readonly RoleManager<IdentityRole> roleManager = null!; /// <summary> /// Logger /// </summary> private readonly ILogger<UserService> logger = null!; /// <summary> /// Constructor, injecting managers and logger (DI) /// </summary> /// <param name="userManager">UserManager</param> /// <param name="roleManager">RoleManager</param> /// <param name="logger">Logger</param> public UserService( UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, ILogger<UserService> logger) { this.roleManager = roleManager; this.userManager = userManager; this.logger = logger; } /// <summary> /// Method to create a given role (Asynchronous) /// </summary> /// <param name="role">IdentityRole</param> /// <returns>Task<IdentityResult> </returns> public async Task<IdentityResult> CreateRoleAsync(IdentityRole role) { logger.LogInformation("Create role async method in user service invoked."); return await this.roleManager.CreateAsync(role); } /// <summary> /// Get users count (Asynchronous) /// </summary> /// <returns>Task<int></returns> public async Task<int> GetUsersCountAsync() { return await this.userManager.Users .CountAsync(); } /// <summary> /// Method to get all users /// </summary> /// <returns>Task<IEnumerable<ApplicationUser>></returns> public async Task<IEnumerable<ApplicationUser>> GetAllUsersAsync() { var users = await this.userManager .Users .Where(u => !String.IsNullOrEmpty(u.PasswordHash)) .ToListAsync(); return users; } /// <summary> /// Method to check if a given user by id is in role(s) (Asynchronous) /// </summary> /// <param name="roles">The roles to check</param> /// <param name="userId">User id to check</param> /// <returns>Task<bool></returns> public async Task<bool> IsInRoleAsync(string[] roles, string userId) { logger.LogInformation("Is in role async method in user service invoked."); logger.LogWarning("Potential user not found exceptions to be thrown."); if (userId == null) { throw new UserNotFoundException("No such user found!"); } var user = await userManager.FindByIdAsync(userId); if (user == null) { throw new UserNotFoundException("No such user found!"); } bool result = false; foreach (string role in roles) { if (await this.userManager.IsInRoleAsync(user, role)) { result = true; break; } } return result; } /// <summary> /// Method to check if a role exists (Asynchronous) /// </summary> /// <param name="role">Role name</param> /// <returns>Task<bool></returns> public Task<bool> RoleExistsAsync(string role) { logger.LogInformation("Role exists async method in user service invoked."); return this.roleManager.RoleExistsAsync(role); } /// <summary> /// Method to update a given role (Asynchronous) /// </summary> /// <param name="role">IdentityRole</param> /// <returns>Task<IdentityResult> </returns> public async Task<IdentityResult> UpdateRoleAsync(IdentityRole role) { logger.LogInformation("Update role async method in user service invoked."); return await this.roleManager.UpdateAsync(role); } /// <summary> /// Method to find and return a user by email (Asynchronous) /// </summary> /// <param name="email">Email to search for</param> /// <returns>Task<ApplicationUser></returns> public async Task<ApplicationUser> FindUserByEmailAsync(string email) { logger.LogInformation("Find user by email async method in user service invoked."); return await this.userManager.FindByEmailAsync(email); } /// <summary> /// Method to find and return a user by id (Asynchronous) /// </summary> /// <param name="id">Id to search for</param> /// <returns>Task<ApplicationUser></returns> public async Task<ApplicationUser> FindUserByIdAsync(string id) { return await this.userManager.FindByIdAsync(id); } /// <summary> /// Method to create a given user (Asynchronous) /// </summary> /// <param name="user">ApplicationUser</param> /// <param name="password">User password</param> /// <returns>Task<IdentityResult></returns> public async Task<IdentityResult> CreateUserAsync(ApplicationUser user, string password) { logger.LogInformation("Create user async method in user service invoked."); var result = await this.userManager.CreateAsync(user, password); return result; } /// <summary> /// Method to update a given user (Asynchronous) /// </summary> /// <param name="user">ApplicationUser</param> /// <returns>Task<IdentityResult> </returns> public async Task<IdentityResult> UpdateUserAsync(ApplicationUser user) { logger.LogInformation("Update user async method in user service invoked."); return await this.userManager.UpdateAsync(user); } /// <summary> /// Method to delete a given user (Asynchronous) /// </summary> /// <param name="user">ApplicationUser</param> /// <returns>Task<IdentityResult> </returns> public async Task<IdentityResult> DeleteUserAsync(ApplicationUser user) { logger.LogInformation("Delete user async method in user service invoked."); return await this.userManager.DeleteAsync(user); } /// <summary> /// Method to add a user to a role (Asynchronous) /// </summary> /// <param name="user">ApplicationUser</param> /// <param name="role">Role</param> /// <returns>Task<IdentityResult> </returns> public async Task<IdentityResult> AddUserToRoleAsync(ApplicationUser user, string role) { logger.LogInformation("Add user to role async method in user service invoked."); return await this.userManager.AddToRoleAsync(user, role); } /// <summary> /// Method to remove a user from a role (Asynchronous) /// </summary> /// <param name="user">ApplicationUser</param> /// <param name="role">Role</param> /// <returns>Task<IdentityResult> </returns> public async Task<IdentityResult> RemoveUserFromRoleAsync(ApplicationUser user, string role) { logger.LogInformation("Remove user from role async method in user service invoked."); return await this.userManager.RemoveFromRoleAsync(user, role); } /// <summary> /// Method to get user full name (Asynchronous) /// </summary> /// <param name="userId">User id</param> /// <returns>Task<string></returns> public async Task<string> GetUserFullNameAsync(string userId) { var user = await this.userManager.FindByIdAsync(userId); if (String.IsNullOrEmpty(user.FirstName) || string.IsNullOrEmpty(user.LastName)) { return "Na"; } var roles = await this.userManager.GetRolesAsync(user); var role = roles.Last(); return user.FirstName + " " + user.LastName + $" ({role})"; } } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE chapter SYSTEM "dtd/dblite.dtd" [ <!ENTITY % Symbols SYSTEM "Symbols.ent"> %Symbols; ]> <chapter id="Errors"> <title>Error messages</title> <indexterm><primary>Errors</primary></indexterm> <simplesect> <variablelist> <varlistentry id="Error01"> <term>Error 01: An error occurred while evaluating power function.</term> <listitem> <para> This error occurs when a number raised to the power of another number resulted in an error. For example (-4)^(-5.1) gives an error, because a negative number cannot be raised to a negative non integer number when calculating with <glossterm linkend="RealNumber">real numbers</glossterm>. </para> </listitem> </varlistentry> <varlistentry id="Error02"> <term>Error 02: Tangent to pi/2+n*pi (90&deg;+n180&deg; in degrees) is undefined.</term> <listitem><para>tan(x) is undefined for x= &pi;/2+&pi;p = 90&deg;+p180&deg;, where p is an integer.</para></listitem> </varlistentry> <varlistentry id="Error03"> <term>Error 03: Fact can only be calculated for positive integers.</term> <listitem><para>fact(x), which calculates the factorial number of x, is only defined for positive integers of x.</para></listitem> </varlistentry> <varlistentry id="Error04"> <term>Error 04: Cannot take logarithm to number equal or less than zero.</term> <listitem> <para> The logarithmic functions ln(x) and log(x) are undefined for x&le;0, when the calculation is done for real numbers. When the calculations are done with complex numbers, x is only undefined at 0. </para> </listitem> </varlistentry> <varlistentry id="Error05"> <term>Error 05: sqrt is undefined for negative numbers.</term> <listitem> <para> sqrt(x) is undefined for x&lt;0, when the calculations are done for real numbers. sqrt(x) is defined for all numbers, when the calculations are done with complex numbers. </para> </listitem> </varlistentry> <varlistentry id="Error06"> <term>Error 06: A part of the evaluation gave a number with an imaginary part.</term> <listitem> <para> This error may occur when calculations are done with real numbers. If a part of the calculation resulted in a number with an imaginary part, the calculation cannot continue. An example of this is: sin(x+&imag;) </para> </listitem> </varlistentry> <varlistentry id="Error07"> <term>Error 07: Division by zero.</term> <listitem> <para> The program tried to divide by zero when calculating. A function is undefined for values where a division by zero is needed. For example the function f(x)=1/x is undefined at x=0. </para> </listitem> </varlistentry> <varlistentry id="Error08"> <term>Error 08: Inverse trigonometric function out of range [-1;1]</term> <listitem> <para> The inverse trigonometric functions asin(x) and acos(x) are only defined in the range [-1;1], and they are not defined for any numbers with an imaginary part. The function atan(x) is defined for all numbers without an imaginary part. This error may also happen if you are trying to take arg(0). </para> </listitem> </varlistentry> <varlistentry id="Error09"> <term>Error 09: The function is not defined for this value.</term> <listitem> <para> This error may occur for functions that are not defined for a specific point. This is for example the case for sign(x) and u(x) at x=0. </para> </listitem> </varlistentry> <varlistentry id="Error10"> <term>Error 10: atanh evaluated at undefined value.</term> <listitem><para>Inverse hyperbolic tangent atanh(x) is undefined at x=1 and x=-1, and not defined outside the interval x=]-1;1[ when calculating with real numbers only.</para></listitem> </varlistentry> <varlistentry id="Error11"> <term>Error 11: acosh evaluated at undefined value.</term> <listitem> <para> Inverse hyperbolic cosine acosh(x) is only defined for x&ge;1 when using <glossterm linkend="RealNumber">real numbers</glossterm>. acosh(x) is defined for all numbers when calculating with <glossterm linkend="ComplexNumber">complex numbers</glossterm>. </para> </listitem> </varlistentry> <varlistentry id="Error12"> <term>Error 12: arg(0) is undefined.</term> <listitem> <para> The argument of zero is undefined because 0 does not have an angle. </para> </listitem> </varlistentry> <varlistentry id="Error13"> <term>Error 13: Evaluation failed.</term> <listitem> <para> This error occurs when a more complicated function like W(z) is evaluated, and the evaluation failed to find an accurate result. </para> </listitem> </varlistentry> <varlistentry id="Error14"> <term>Error 14: Argument produced a function result with total loss of precision.</term> <listitem> <para> An argument to a function call produced a result with total loss of significant digits, such as sin(1E70) which gives an arbitrary number in the range [-1;1]. </para> </listitem> </varlistentry> <varlistentry id="Error15"> <term>Error 15: The custom function/constant '%s' was not found or has the wrong number of arguments.</term> <listitem> <para> A custom function or constant no longer exists. You can either define it again or remove all uses of the symbol. This may also happen if a custom constant has been changed to a function or vice versa, or if the number of arguments to a custom function has been changed. </para> </listitem> </varlistentry> <varlistentry id="Error16"> <term>Error 16: Too many recursive calls</term> <listitem> <para> Too many recursive calls have been executed. This is most likely caused by a function that calls itself recursively an infinite number of times, for example foo(x)=2*foo(x). The error may also occur if you just call too many functions recursively. </para> </listitem> </varlistentry> <varlistentry id="Error17"> <term>Error 17: Overflow: A function returned a value too large to handle.</term> <listitem> <para> A function call resulted in value too large to handle. This for example happens if you try to evaluate sinh(20000) </para> </listitem> </varlistentry> <varlistentry id="Error18"> <term>Error 18: A plugin function failed.</term> <listitem> <para> A custom function in a Python plugin did not return a result. The Python interpreter window may show more detailed information. </para> </listitem> </varlistentry> <varlistentry id="Error50"> <term>Error 50: Unexpected operator. Operator %s cannot be placed here</term> <listitem> <para> An operator +, -, *, / or ^ was misplaced. This can happen if you try entering the function f(x)=^2, and it usually means that you forgot something in front of the operator. </para> </listitem> </varlistentry> <varlistentry id="Error55"> <term>Error 55: Right bracket missing.</term> <listitem> <para> A right bracket is missing. Make sure you have the same number of left and right brackets. </para> </listitem> </varlistentry> <varlistentry id="Error56"> <term>Error 56: Invalid number of arguments supplied for the function '%s'</term> <listitem> <para> You passed a wrong number of arguments to the specified function. Check the <xref linkend="ListOfFunctions" /> to find the required number of arguments the function needs. This error may occur if you for example write sin(x,3). </para> </listitem> </varlistentry> <varlistentry id="Error57"> <term>Error 57: Comparison operator misplaced.</term> <listitem> <para> Only two comparison operators in sequence are allowed. For example "sin(x) &lt; y &lt; cos(x)" is okay while "sin(x) &lt; x &lt; y &lt; cos(x)" is invalid because there are three &lt;-operators in sequence. </para> </listitem> </varlistentry> <varlistentry id="Error58"> <term>Error 58: Invalid number found. Use the format: -5.475E-8</term> <listitem> <para> Something that looked like a number but wasn't has been found. For example this is an invalid number: 4.5E. A number should be on the form nnn.fffEeee where nnn is the whole number part that may be negative. fff is the fraction part that is separated from the integer part with a dot '.'. The fraction part is optional, but either the integer part or the fraction part must be there. E is the exponent separator and must be an 'E' in upper case. eee is the exponent optionally preceded by '-'. The exponent is only needed if the E is there. Notice that 5E8 is the same as 5*10^8. Here are some examples of numbers: <constant>-5.475E-8, -0.55, .75, 23E4</constant> </para> </listitem> </varlistentry> <varlistentry id="Error59"> <term>Error 59: String is empty. You need to enter a formula.</term> <listitem> <para> You didn't enter anything in the box. This is not allowed. You need to enter an expression. </para> </listitem> </varlistentry> <varlistentry id="Error60"> <term>Error 60: Comma is not allowed here. Use dot as decimal separator.</term> <listitem> <para> Commas may not be used as decimal separator. You have to use a '.' to separate the fraction from the integer part. </para> </listitem> </varlistentry> <varlistentry id="Error61"> <term>Error 61: Unexpected right bracket.</term> <listitem> <para> A right bracket was found unexpectedly. Make sure the number of left and right brackets match. </para> </listitem> </varlistentry> <varlistentry id="Error63"> <term>Error 63: Number, constant or function expected.</term> <listitem> <para> A factor, which may be a number, constant, variable or function, was expected. </para> </listitem> </varlistentry> <varlistentry id="Error64"> <term>Error 64: Parameter after constant or variable not allowed.</term> <listitem> <para> Brackets may not be placed after a constant or variable. For example this is invalid: f(x)=x(5). Use f(x)=x*5 instead. </para> </listitem> </varlistentry> <varlistentry id="Error65"> <term>Error 65: Expression expected.</term> <listitem> <para> An expression was expected. This may happen if you have empty brackets: f(x)=sin() </para> </listitem> </varlistentry> <varlistentry id="Error66"> <term>Error 66: Unknown variable, function or constant: %s</term> <listitem> <para> You entered something that looks like a variable, function or constant but is unknown. Note that "x5" is not the same as "x*5". </para> </listitem> </varlistentry> <varlistentry id="Error67"> <term>Error 67: Unknown character: %s</term> <listitem> <para> An unknown character was found. </para> </listitem> </varlistentry> <varlistentry id="Error68"> <term>Error 68: The end of the expression was unexpected.</term> <listitem> <para> The end of the expression was found unexpectedly. </para> </listitem> </varlistentry> <varlistentry id="Error70"> <term>Error 70: Error parsing expression</term> <listitem> <para> An error happened while parsing the function text. The string is not a valid function. </para> </listitem> </varlistentry> <varlistentry id="Error71"> <term>Error 71: A calculation resulted in an overflow.</term> <listitem> <para> An overflow occurred under the calculation. This may happen when the numbers get too big. </para> </listitem> </varlistentry> <varlistentry id="Error73"> <term>Error 73: An invalid value was used in the calculation.</term> <listitem> <para> An invalid value was used as data for the calculation. </para> </listitem> </varlistentry> <varlistentry id="Error74"> <term>Error 74: Not enough points for calculation.</term> <listitem> <para> Not enough data points were provided to calculate the trendline. A polynomial needs at least one more point than the degree of the polynomial. A polynomial of third degree needs at least 4 points. All other functions need at least two points. </para> </listitem> </varlistentry> <varlistentry id="Error75"> <term>Error 75: Illegal name %s for user defined function or constant.</term> <listitem> <para> Names for user defined functions and constants must start with a letter and only contain letters and decimal digits. You cannot use names that are already used by built-in functions and constants. </para> </listitem> </varlistentry> <varlistentry id="Error76"> <term>Error 76: Cannot differentiate recursive function.</term> <listitem> <para> It is not possible to differentiate a recursive function because the resulting function will be infinitely large. </para> </listitem> </varlistentry> <varlistentry id="Error79"> <term>Error 79: Function %s cannot be differentiated.</term> <listitem> <para> The function cannot be differentiated, because some part of the function does not have a first derivative. This is for example the case for arg(x), conj(x), re(x) and im(x). </para> </listitem> </varlistentry> <varlistentry id="Error86"> <term>Error 86: Not further specified error occurred under calculation.</term> <listitem> <para> An error occurred while calculating. The exact cause is unknown. If you get this error, you may try to contact the programmer with a description of how to reproduce the error. Then he might be able to improve the error message or prevent the error from occurring. </para> </listitem> </varlistentry> <varlistentry id="Error87"> <term>Error 87: No solution found. Try another guess or another model.</term> <listitem> <para> The given guess, which may be the default one, did not give any solution. This can be caused by a bad guess, and a better guess may result in a solution. It can also be because the given trendline model doesn't fit the data, in which case you should try another model. </para> </listitem> </varlistentry> <varlistentry id="Error88"> <term>Error 88: No result found.</term> <listitem> <para> No valid result exist. This may for example happen when trying to create a trendline from a point series where it is not possible to calculate a trendline. One reason can be that one of the calculated constants needs to be infinite. </para> </listitem> </varlistentry> <varlistentry id="Error89"> <term>Error 89: An accurate result cannot be found.</term> <listitem> <para> Graph could not calculate an accurate result. This may happen when calculating the numerical integral produced a result with a too high estimated error. </para> </listitem> </varlistentry> <varlistentry id="Error99"> <term>Error 99: Internal error. Please notify the programmer with as much information as possible.</term> <listitem> <para> An internal error happened. This means that the program has done something that is impossible but happened anyway. Please contact the programmer with as much information as necessary to reproduce the problem. </para> </listitem> </varlistentry> </variablelist> </simplesect> </chapter>
package sq.mayv.aladhan.ui.screens.home.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import sq.mayv.aladhan.R @Composable fun DateIndicator( date: String, onPreviousClick: () -> Unit, onNextClick: () -> Unit ) { Row( modifier = Modifier.fillMaxWidth() ) { Card( modifier = Modifier .padding(horizontal = 15.dp) .size(40.dp), colors = CardDefaults.cardColors( containerColor = Color.White ), shape = RoundedCornerShape(5.dp), elevation = CardDefaults.cardElevation(10.dp) ) { IconButton( modifier = Modifier .size(40.dp), onClick = onPreviousClick ) { Icon( painter = painterResource(id = R.drawable.ic_arrow_left), contentDescription = "Left Arrow", tint = colorResource(id = R.color.primary) ) } } Box( modifier = Modifier .height(40.dp) .weight(1f) ) { Text( modifier = Modifier.align(Alignment.Center), text = date, fontSize = 16.sp, textAlign = TextAlign.Center, color = Color.Black ) } Card( modifier = Modifier .padding(horizontal = 15.dp) .size(40.dp), colors = CardDefaults.cardColors( containerColor = Color.White ), shape = RoundedCornerShape(5.dp), elevation = CardDefaults.cardElevation(10.dp) ) { IconButton( modifier = Modifier .size(40.dp), onClick = onNextClick ) { Icon( painter = painterResource(id = R.drawable.ic_arrow_right), contentDescription = "Right Arrow", tint = colorResource(id = R.color.primary) ) } } } }
package com.example.unittesting.utils.quotes import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.room.Room import androidx.test.core.app.ApplicationProvider import app.cash.turbine.test import junit.framework.TestCase.assertEquals import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test class QuotesDaoFlowTest { lateinit var quoteDatabase: QuotesDatabase lateinit var quotesDao: QuotesDao @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() @Before fun setUp() { quoteDatabase = Room.inMemoryDatabaseBuilder( ApplicationProvider.getApplicationContext(), QuotesDatabase::class.java, ).allowMainThreadQueries().build() quotesDao = quoteDatabase.quoteDao() } @After fun tearDown() { quoteDatabase.close() } @Test fun insertQuote_expectedSingleQuote() { runBlocking { val quote = Quote(id = 1, "This is a test quote", "Cheezy Code") quotesDao.insertQuote(quote) val resultViaFirst = quotesDao.getQuotesViaFlow().first() // In case of flows in room db, it continuously gives us updates if anything is changed, due to which it runs infinitely. Since it runs infinitely, toList() method will never be completed. That is why, in case of infinite flows, we test them by asserting its first 1-2 elements. // val resultViaList = quotesDao.getQuotesViaFlow().toList() assertEquals(1, resultViaFirst.size) assertEquals("This is a test quote", resultViaFirst[0].quote) } } @Test fun insertQuote_expectedSingleQuoteViaTurbine() { runBlocking { val quote = Quote(id = 1, "This is a test quote", "Cheezy Code") quotesDao.insertQuote(quote) quotesDao.getQuotesViaFlow().test { // calling await item would give us the first value in the flow. val quotesList = awaitItem() assertEquals(1, quotesList.size) assertEquals("This is a test quote", quotesList[0].quote) } } } @Test fun insertQuote_expectedDoubleQuoteViaTurbine() { runBlocking { val quote = Quote(id = 1, "This is a test quote", "Cheezy Code") val quote2 = Quote(id = 2, "This is a test quote 2", "Cheezy Code") quotesDao.insertQuote(quote) quotesDao.insertQuote(quote2) quotesDao.getQuotesViaFlow().test { // here we inserted to quotes at once, that's why there are 2 items in the flow from start. val quotesList = awaitItem() assertEquals(2, quotesList.size) assertEquals("This is a test quote 2", quotesList[1].quote) } } } @Test fun insertQuote_expectedDoubleQuoteAfterDelay() { runBlocking { val quote = Quote(id = 1, "This is a test quote", "Cheezy Code") val quote2 = Quote(id = 2, "This is a test quote 2", "Cheezy Code") quotesDao.insertQuote(quote) launch { delay(500L) quotesDao.insertQuote(quote2) } quotesDao.getQuotesViaFlow().test { // here we added the other quote after some delay that's why at first the value in flow is 1. val quotesList = awaitItem() assertEquals(1, quotesList.size) // After delay when quote is inserted the flow's second value becomes 2, that's why calling awaitItem second times returns the 2nd value of flow. val quotesList2 = awaitItem() assertEquals(2, quotesList2.size) } } } }
package com.ratatouille.Ratatouille23.user; import com.ratatouille.Ratatouille23.exception.ApiRequestException; import com.ratatouille.Ratatouille23.order.OrderRepository; import com.ratatouille.Ratatouille23.order.OrderResponse; import com.ratatouille.Ratatouille23.order.OrderResponseMapper; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; @Service @RequiredArgsConstructor public class UserService { private final UserRepository repository; private final UserResponseMapper userResponseMapper; private final OrderRepository orderRepository; private final OrderResponseMapper orderResponseMapper; public List<UserResponse> getUsers() { return repository.findAll() .stream() .map(userResponseMapper).collect(Collectors.toList()); } public UserResponse getById(Long id) { return repository .findById(id) .map(userResponseMapper) .orElseThrow(() -> new ApiRequestException(HttpStatus.NOT_FOUND, "User with id " + id + " does not exists!")); } public UserResponse getByFirstName(String firstName) { return repository .findByFirstName(firstName) .map(userResponseMapper) .orElseThrow(() -> new ApiRequestException(HttpStatus.NOT_FOUND, "User with firstName " + firstName + " does not exists!")); } public UserResponse getByLastName(String lastName) { return repository .findByLastName(lastName) .map(userResponseMapper) .orElseThrow(() -> new ApiRequestException(HttpStatus.NOT_FOUND, "User with firstName " + lastName + " does not exists!")); } public UserResponse getByEmail(String email) { return repository .findByEmail(email) .map(userResponseMapper) .orElseThrow(() -> new ApiRequestException(HttpStatus.NOT_FOUND, "User with firstName " + email + " does not exists!")); } public List<UserResponse> getUsersByAttributes(Long id, String firstName, String lastName, String email, Role role) { if (id != null) { return Collections.singletonList(getById(id)); } return repository.searchUsers(firstName, lastName, email, role) .filter(list -> !list.isEmpty()) .map(list -> list .stream() .map(userResponseMapper) .collect(Collectors.toList())) .orElseThrow(() -> new ApiRequestException(HttpStatus.NOT_FOUND, "No user with this criteria found!")); } public Long countUsers(Long id, String firstName, String lastName, String email, Role role) { if (id != null) { return Stream.of(getById(id)).count(); } return repository.countUsers(firstName, lastName, email, role) .orElseThrow(() -> new ApiRequestException(HttpStatus.NOT_FOUND, "No user with this criteria found!")); } public Long createUser(UserRequest userRequest) { Optional<User> userOptional = repository.findByEmail(userRequest.email()); if (userOptional.isPresent()) { throw new ApiRequestException(HttpStatus.BAD_REQUEST,"Email taken!"); } String password = userRequest.password(); if (password == null) { password = "defaultPassword"; } User user = User.builder() .firstName(userRequest.firstName()) .lastName(userRequest.lastName()) .email(userRequest.email()) .password(password) .role(userRequest.role()) .build(); return repository.save(user).getId(); } public void deleteUser(Long id) { boolean exists = repository.existsById(id); if (!exists) { throw new ApiRequestException(HttpStatus.NOT_FOUND, "User with id " + id + " does not exists!"); } repository.deleteById(id); } @Transactional public void updateUser(Long id, UserRequest request) { User user = repository.findById(id).orElseThrow(() -> new ApiRequestException(HttpStatus.NOT_FOUND, "User with id " + id + " does not exists!")); String firstName = request.firstName(); String lastName = request.lastName(); String email = request.email(); Role role = request.role(); if (firstName != null && firstName.length() > 0 && !Objects.equals(user.getFirstName(), firstName)) { user.setFirstName(firstName); } if (lastName != null && lastName.length() > 0 && !Objects.equals(user.getLastName(), lastName)) { user.setLastName(lastName); } if (email != null && email.length() > 0 && !Objects.equals(user.getEmail(), email)) { Optional<User> userOptional = repository.findByEmail(email); if (userOptional.isPresent()) { throw new ApiRequestException(HttpStatus.BAD_REQUEST, "email taken"); } user.setEmail(email); } if (role != Role.ADMIN && role != user.getRole() && user.getRole() != Role.ADMIN) { user.setRole(role); } } public List<OrderResponse> getOrderByUser(Long id) { return orderRepository.findAllByUserId(id) .filter(list -> !list.isEmpty()) .map(list -> list .stream() .map(orderResponseMapper) .collect(Collectors.toList())) .orElseThrow(() -> new ApiRequestException(HttpStatus.NOT_FOUND, "This user has no orders!")); } }
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.webkit; import com.android.internal.R; import android.content.res.AssetManager; import android.net.http.EventHandler; import android.net.http.Headers; import android.util.Log; import android.util.TypedValue; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.Field; /** * This class is a concrete implementation of StreamLoader that uses a * file or asset as the source for the stream. * */ class FileLoader extends StreamLoader { private String mPath; // Full path to the file to load private int mType; // Indicates the type of the load private boolean mAllowFileAccess; // Allow/block file system access // used for files under asset directory static final int TYPE_ASSET = 1; // used for files under res directory static final int TYPE_RES = 2; // generic file static final int TYPE_FILE = 3; private static final String LOGTAG = "webkit"; /** * Construct a FileLoader with the file URL specified as the content * source. * * @param url Full file url pointing to content to be loaded * @param loadListener LoadListener to pass the content to * @param asset true if url points to an asset. * @param allowFileAccess true if this WebView is allowed to access files * on the file system. */ FileLoader(String url, LoadListener loadListener, int type, boolean allowFileAccess) { super(loadListener); mType = type; mAllowFileAccess = allowFileAccess; // clean the Url int index = url.indexOf('?'); if (mType == TYPE_ASSET) { mPath = index > 0 ? URLUtil.stripAnchor( url.substring(URLUtil.ASSET_BASE.length(), index)) : URLUtil.stripAnchor(url.substring( URLUtil.ASSET_BASE.length())); } else if (mType == TYPE_RES) { mPath = index > 0 ? URLUtil.stripAnchor( url.substring(URLUtil.RESOURCE_BASE.length(), index)) : URLUtil.stripAnchor(url.substring( URLUtil.RESOURCE_BASE.length())); } else { mPath = index > 0 ? URLUtil.stripAnchor( url.substring(URLUtil.FILE_BASE.length(), index)) : URLUtil.stripAnchor(url.substring( URLUtil.FILE_BASE.length())); } } private String errString(Exception ex) { String exMessage = ex.getMessage(); String errString = mContext.getString(R.string.httpErrorFileNotFound); if (exMessage != null) { errString += " " + exMessage; } return errString; } @Override protected boolean setupStreamAndSendStatus() { try { if (mType == TYPE_ASSET) { try { mDataStream = mContext.getAssets().open(mPath); } catch (java.io.FileNotFoundException ex) { // try the rest files included in the package mDataStream = mContext.getAssets().openNonAsset(mPath); } } else if (mType == TYPE_RES) { // get the resource id from the path. e.g. for the path like // drawable/foo.png, the id is located at field "foo" of class // "<package>.R$drawable" if (mPath == null || mPath.length() == 0) { Log.e(LOGTAG, "Need a path to resolve the res file"); mLoadListener.error(EventHandler.FILE_ERROR, mContext .getString(R.string.httpErrorFileNotFound)); return false; } int slash = mPath.indexOf('/'); int dot = mPath.indexOf('.', slash); if (slash == -1 || dot == -1) { Log.e(LOGTAG, "Incorrect res path: " + mPath); mLoadListener.error(EventHandler.FILE_ERROR, mContext .getString(R.string.httpErrorFileNotFound)); return false; } String subClassName = mPath.substring(0, slash); String fieldName = mPath.substring(slash + 1, dot); String errorMsg = null; try { final Class<?> d = mContext.getApplicationContext() .getClassLoader().loadClass( mContext.getPackageName() + ".R$" + subClassName); final Field field = d.getField(fieldName); final int id = field.getInt(null); TypedValue value = new TypedValue(); mContext.getResources().getValue(id, value, true); if (value.type == TypedValue.TYPE_STRING) { mDataStream = mContext.getAssets().openNonAsset( value.assetCookie, value.string.toString(), AssetManager.ACCESS_STREAMING); } else { errorMsg = "Only support TYPE_STRING for the res files"; } } catch (ClassNotFoundException e) { errorMsg = "Can't find class: " + mContext.getPackageName() + ".R$" + subClassName; } catch (SecurityException e) { errorMsg = "Caught SecurityException: " + e; } catch (NoSuchFieldException e) { errorMsg = "Can't find field: " + fieldName + " in " + mContext.getPackageName() + ".R$" + subClassName; } catch (IllegalArgumentException e) { errorMsg = "Caught IllegalArgumentException: " + e; } catch (IllegalAccessException e) { errorMsg = "Caught IllegalAccessException: " + e; } if (errorMsg != null) { mLoadListener.error(EventHandler.FILE_ERROR, mContext .getString(R.string.httpErrorFileNotFound)); return false; } } else { if (!mAllowFileAccess) { mLoadListener.error(EventHandler.FILE_ERROR, mContext.getString(R.string.httpErrorFileNotFound)); return false; } mDataStream = new FileInputStream(mPath); mContentLength = (new File(mPath)).length(); } mLoadListener.status(1, 1, 200, "OK"); } catch (java.io.FileNotFoundException ex) { mLoadListener.error(EventHandler.FILE_NOT_FOUND_ERROR, errString(ex)); return false; } catch (java.io.IOException ex) { mLoadListener.error(EventHandler.FILE_ERROR, errString(ex)); return false; } return true; } @Override protected void buildHeaders(Headers headers) { // do nothing. } }
package org.chen.securitydemo.config; import org.chen.securitydemo.controller.CustomAccessDecisionManager; import org.chen.securitydemo.controller.CustomFilterInvocationSecurityMetadataSource; import org.chen.securitydemo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl; import org.springframework.security.config.annotation.ObjectPostProcessor; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; @Configuration public class securityConfig03 extends WebSecurityConfigurerAdapter { @Autowired UserService userService; @Bean PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService); } /** * 角色继承 * @return */ @Bean RoleHierarchy roleHierarchy() { RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); String hierarchy = "ROLE_dba > ROLE_admin \n ROLE_admin > ROLE_user"; roleHierarchy.setHierarchy(hierarchy); return roleHierarchy; } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { @Override public <O extends FilterSecurityInterceptor> O postProcess(O o) { o.setSecurityMetadataSource(cfisms()); o.setAccessDecisionManager(cadm()); return o; } }) .and() .formLogin() .loginProcessingUrl("/login").permitAll() .and() .csrf().disable(); } @Bean CustomFilterInvocationSecurityMetadataSource cfisms(){ return new CustomFilterInvocationSecurityMetadataSource(); } @Bean CustomAccessDecisionManager cadm(){ return new CustomAccessDecisionManager(); } }
#include<iostream> #include<stack> #include<math.h> using namespace std; //MinsSteptoOne int MinStepsTo1(int n){ //Brute Force Recursion //Base Case if(n<=1){ return 0; } int x = MinStepsTo1(n-1); int y = INT32_MAX, z = INT32_MAX; if(n%3 == 0){ y = MinStepsTo1(n/3); } if(n%2 == 0){ z = MinStepsTo1(n/2); } return min(x, min(y, z))+1; } int MinStepsto1(int n, int *arr){ //Memorization //base case if(n<=1){ arr[n] = 0; return 0; } if(arr[n] != -1){ return arr[n]; } int x = MinStepsTo1(n-1); int y = INT32_MAX, z = INT32_MAX; if(n%3 == 0){ y = MinStepsTo1(n/3); } if(n%2 == 0){ z = MinStepsTo1(n/2); } arr[n] = min(x, min(y, z))+1; return arr[n]; } int MinStepsto1(int n){ int arr[n+1]; for(int i=0; i<=n; i++){ arr[i] = -1; } return MinStepsto1(n, arr); } int MinStepto1(int n){ int *arr = new int[n+1]; arr[0] = 0; arr[1] = 0; for(int i=2; i<=n; i++){ int x = arr[i-1]; int y = INT32_MAX; int z = INT32_MAX; if(n%2 == 0){ y = arr[i/2]; } if(n%3 == 0){ z = arr[i/3]; } arr[i] = 1+min(x, min(y, z)); } int ans = arr[n]; delete [] arr; return ans; } //Count StairCase int climbStairs(int n) { if(n<=2){ return n; } int *arr = new int[n+1]; arr[0] = 1; arr[1] = 1; arr[2] = 2; for(int i=3; i<=n; i++){ arr[i] = arr[i-1]+arr[i-2]+arr[i-3]; } int ans = arr[n]; delete [] arr; return ans; } //Minimum Count int MinimumCountB(int n){ //brute force if(n <= 0){ //Base Case; return 0; } int mini = INT32_MAX; for(int i=1; (i*i)<=n; i++){ int sqr = i*i; mini = min(mini, MinimumCountB(n-sqr)); } return mini+1; } int MinimumCountM(int n, int *arr){ //Memorization if(n <= 0){ //Base Case; arr[0] = 0; return 0; } if(arr[n] != -1){ return arr[n]; } int mini = INT32_MAX; for(int i=1; (i*i)<=n; i++){ int sqr = i*i; mini = min(mini, MinimumCountM(n-sqr, arr)); } return mini+1; } int MinimumCountM(int n){ // if(n<=0){ return 0; } int *arr = new int[n+1]; for(int i=0; i<=n; i++){ arr[i] = -1; } int ans = MinimumCountM(n, arr); delete [] arr; return ans; } int MinimumCountDP(int n){ //DP if(n<=1){ return n; } int * arr = new int[n+1]; arr[0] = 0; arr[1] = 1; arr[2] = 2; for(int i=3; i<=n; i++){ int mini = INT32_MAX; for(int j=1; (j*j)<=n; j++){ int sqr = (j*j); mini = min(mini, arr[i-sqr]); } arr[i] = 1+mini; } int ans = arr[n]; delete [] arr; return ans; } //No. of Balanced BTs int Howmanytrees(int h){ //Constrants ka dikkat if(h<=1){ return 1; } int mod = (int)(pow(10, 9))+7; int x = Howmanytrees(h-1); int y = Howmanytrees(h-2); int temp1 = (int)(((long)(x)*x)%mod); int temp2 = (int)((2*(long)(x)*y)%mod); int ans = (temp1 + temp2)%mod; return ans; } int HowManyTrees(int h, int *arr){ //Memorization if(h<=1){ arr[h] = 1; //base case return 1; } if(arr[h] != -1){ return arr[h]; } int mod = (int)(pow(10, 9))+7; int x = HowManyTrees(h-1, arr); int y = HowManyTrees(h-2, arr); int temp1 = (int)(((long)(x)*(long)(x))%mod); int temp2 = (int)((2*(long)(x)*(long)(y))%mod); arr[h] = (temp1 + temp2)%mod; return arr[h]; } int HowManyTrees(int h){ int *arr = new int[h+1]; for(int i=0; i<=h; i++){ arr[i] = -1; } int ans = HowManyTrees(h, arr); delete [] arr; return ans; } long HowmanyTrees(long h){ //DP long *arr = new long[h+1]; arr[0] = 1; arr[1] = 1; for(int i=2; i<=h; i++){ long x = arr[i-1]; long y = arr[i-2]; arr[i] = ((long)(x)*x) + (2*(long)(x)*y); } int ans = arr[h]; delete [] arr; return ans; } int MinCPath(int x, int y, int **arr){ //Incomplete int **memory = new int*[x]; for(int i=0; i<x; i++){ memory[i] = new int[y]; } memory[x-1][y-1]= arr[x-1][y-1]; for(int i=x-1; i>=0; i--){ for(int j = y-1; j>=0; j--){ int mini = INT32_MAX; int a=INT32_MAX, b=INT32_MAX, c=INT32_MAX; if(i+1 < x){ a = memory[i+1][j]; } if(j+1 < y){ b = memory[i][j+1]; } if(i+1 < x && j+1 < y){ c = memory[i+1][j+1]; } mini = min(a, min(b,c)); memory[i][j] = arr[i][j]+mini; } } } int MinCPath(int x, int y, int i, int j, int **arr, int **memory){ //Memorization if(i == x-1 && j==y-1){ memory[i][j] = arr[i][j]; return arr[i][j]; } if(i >= x || j >= y){ return INT32_MAX; } if(memory[i][j] != -1){ return memory[i][j]; } int a = MinCPath(x, y, i+1, j,arr, memory); int b = MinCPath(x, y, i, j+1,arr, memory); int c = MinCPath(x, y, i+1, j+1,arr, memory); memory[i][j] = min(a, min(b,c))+arr[i][j]; return memory[i][j]; } int MinCostPath(int x, int y, int i, int j,int **arr){ //Recursion if(i == x-1 && j==y-1){ return arr[i][j]; } if(i >= x || j >= y){ return INT32_MAX; } int a = MinCostPath(x, y, i+1, j,arr); int b = MinCostPath(x, y, i, j+1,arr); int c = MinCostPath(x, y, i+1, j+1,arr); int ans = min(a, min(b,c))+arr[i][j]; return ans; } int MinCostPath(){ //Initiator int M, N; cin>>M>>N; int **arr = new int*[M]; for(int i=0; i<M; i++){ arr[i] = new int[N]; for(int j=0; j<N; j++){ cin>>arr[i][j]; } } int **memory = new int*[M]; for(int i=0; i<M; i++){ memory[i] = new int[N]; for(int j=0; j<N; j++){ memory[i][j] = -1; } } //int ans = MinCostPath(M, N,0, 0, arr); //return ans; //int ans = MinCPath(M, N, 0, 0, arr, memory); //return ans; int ans = MinCPath(M, N, arr); for(int i=0; i<N; i++){ delete arr[i]; } delete [] arr; for(int i=0; i<N; i++){ delete memory[i]; } delete [] memory; return ans; } int LCS(string s, string t){ if(s.size() == 0 || t.size() == 0){ return 0; } if(s[0] == t[0]){ return 1+LCS(s.substr(1), t.substr(1)); } int a = LCS(s.substr(1), t); int b = LCS(s, t.substr(1)); //int c = LCS(s.substr(1), t.substr(1)); Optional //return max(a, max(b,c)); return max(a, b); } int LCS_mem(string s, string t, int **memory){ //Memorization int n = s.size(); int m = t.size(); if(n == 0 || n == 0){ return 0; } if(memory[n][m] != -1){ return memory[n][m]; } if(s[0] == t[0]){ memory[n][m] = 1+LCS(s.substr(1), t.substr(1)); return memory[n][m]; } int a = LCS(s.substr(1), t); int b = LCS(s, t.substr(1)); //int c = LCS(s.substr(1), t.substr(1)); Optional //return max(a, max(b,c)); memory[n][m] = max(a, b); return memory[n][m]; } int LCS_DP(string s, string t){ int m = s.size()+1; int n = t.size()+1; int **memory = new int*[m]; for(int i=0; i<m; i++){ memory[i] = new int[n]; for(int j=0; j<n; j++){ if(i==0 || j==0){ memory[i][j] = 0; }else{ memory[i][j] = -1; } } } for(int i=1; i<m; i++){ for(int j=1; j<n; j++){ if(s[i] == t[j]){ memory[i][j] = 1+memory[i-1][j-1]; }else{ int a = memory[i][j-1]; int b = memory[i-1][j]; int c = memory[i-1][j-1]; memory[i][j] = max(a, max(b,c)); } } } int ans = memory[m-1][n-1]; for(int i=0; i<m; i++){ delete memory[i]; } delete [] memory; return ans; } int LCS_start(){ string s, t; cin>>s>>t; int **memory = new int*[s.size()+1]; for(int i=0; i<=s.size(); i++){ memory[i] = new int[t.size()+1]; for(int j=0; j<=t.size(); j++){ memory[i][j] = -1; } } //return LCS(s, t); //return LCS_mem(s, t, memory); int ans = LCS_DP(s, t); for(int i=0; i<=t.length(); i++){ delete memory[i]; } delete [] memory; return ans; } //Edit Distance int EditDistance(string s, string t){ if(s.size() == 0 || t.size() == 0){ int m = s.size(), n = t.size(); return max(m, n); } if(s[0] == t[0]){ return EditDistance(s.substr(1), t.substr(1)); } int x = EditDistance(s.substr(1), t)+1; int y = EditDistance(s, t.substr(1))+1; int z = EditDistance(s.substr(1), t.substr(1))+1; return min(x, min(y,z)); } //Memoization int EditDistance_mem(string s, string t, int **memory){ int m = s.size(); int n = t.size(); if(m == 0 || n == 0){ return max(m, n); } if(memory[m][n] != -1){ return memory[m][n]; } int ans; if(s[0] == t[0]){ ans = EditDistance_mem(s.substr(1), t.substr(1), memory); }else{ //Insert int x = EditDistance_mem(s.substr(1), t, memory)+1; //delete int y = EditDistance_mem(s, t.substr(1), memory)+1; //Replace int z = EditDistance_mem(s.substr(1), t.substr(1), memory)+1; ans = min(x, min(y, z)); } memory[m][n] = ans; return ans; } //DP Solution int EditDistance_DP(string s, string t){ int m = s.size(); int n = t.size(); int**dp = new int*[m+1]; for(int i=0; i<=m; i++){ dp[i] = new int[n+1]; } for(int i=0; i<=n; i++){ dp[0][i] = i; } for(int i=1; i<=m; i++){ dp[i][0] = i; } for(int i=1; i<=m; i++){ for(int j=1; j<=n; j++){ if(s[i] == t[j]){ dp[i][j] = dp[i-1][j-1]; }else{ int x = dp[i-1][j]+1; int y = dp[i][j-1]+1; int z = dp[i-1][j-1]+1; dp[i][j] = min(x, min(y,z)); } } } int ans = dp[m][n]; for(int i=0; i<=m; i++){ delete dp[i]; } delete [] dp; return ans; } //Edit Distance starter int EditDistance_st(){ string s, t; cin>>s>>t; int m = s.size(); int n = t.size(); int **memory = new int*[m+1]; for(int i=0; i<=m; i++){ memory[i] = new int[n+1]; for(int j=0; j<=n; j++){ memory[i][j] = -1; } } //return EditDistance(s, t); //int ans = EditDistance_mem(s, t, memory); for(int i=0; i<=t.size(); i++){ delete memory[i]; } delete [] memory; //return ans; return EditDistance_DP(s, t); } int Knapsack(int n, int *w, int *v, int W){ //n - number of variables , w - weight of elements, v- values, //Base Case //W - maxWeight if(n == 0 || W <= 0){ return 0; } if(w[0] > W){ return Knapsack(n-1, w+1, v+1, W); } int smallcase1 = Knapsack(n-1, w+1, v+1, W-w[0])+v[0]; int smallcase2 = Knapsack(n-1, w+1, v+1, W); return max(smallcase1, smallcase2); } int Knapsack_start(){ int n; cin>>n; int w[n]; for(int i=0; i<n; i++){ cin>>w[i]; } int v[n]; for(int i=0; i<n; i++){ cin>>v[i]; } int maxWeight; cin>>maxWeight; return Knapsack(n, w, v, maxWeight); } int main(){ //int n; //cin>>n; //cout<<MinStepsto1(n); //cout<<climbStairs(n); //cout<<MinimumCountB(n)<<endl; //cout<<MinimumCountM(n)<<endl; //cout<<MinimumCountDP(n)<<endl; //cout<<HowmanyTrees(n); //cout<<MinCostPath(); //cout<<LCS_start(); //cout<<EditDistance_st(); cout<<Knapsack_start()<<endl; return 0; } /*int MinStepto1(int n){ //Brute Force if(n == 1){ return 0; } if(n==3 || n==2){ return 1; } if(n%3 == 1){ return MinStepto1(n-1)+1; } if(n%3 == 0){ return MinStepto1(n/3)+1; } if(n%2 == 0){ return MinStepto1(n/2)+1; } return MinStepto1(n-1)+1; } int MinStepto1(int n, int *arr){ //Memorization if(n == 1){ return 0; } if(n==3 || n==2){ return 1; } if(arr[n] != -1){ return 1; } if(n%3 == 1){ arr[n] = MinStepto1(n-1)+1; return arr[n]; } if(n%3 == 0){ arr[n] = MinStepto1(n/3)+1; return arr[n]; } if(n%2 == 0){ arr[n] = MinStepto1(n/2)+1; return arr[n]; } arr[n] = MinStepto1(n-1)+1; return arr[n]; } int MinStepto1t(int n){ int arr[n+1]; for(int i=0; i<=n; i++){ arr[i] = -1; } return MinStepto1(n, arr); } int MinSteptoone(int n, int *arr){ //DP arr[1] = 0; for(int i=2; i<=n; i++){ int x = arr[i-1]; int y = INT32_MAX; int z = INT32_MAX; if(n%2 == 0){ y = arr[i/2]; } if(n%3 == 0){ z = arr[i/3]; } arr[i] = 1+min(x, min(y, z)); } } int MinStepto1t(int n){ int arr[n+1]; for(int i=0; i<=n; i++){ arr[i] = -1; } return MinSteptoone(n, arr); }*/
from http import client import os from routes.text_search import text_search import flask from flask import * from flask_bcrypt import Bcrypt from flask_session import Session from flask_mail import Mail, Message from itsdangerous import URLSafeTimedSerializer, SignatureExpired from model import db , User ,Tracking , Product from config import ApplicationConfig ,configEmail from routes.register import register_user from routes.login import login_user from routes.confirm_email import confirm_user_email from routes.change_password import change_user_password from routes.forgot_password import forgot_user_password from routes.image_search import image_search from routes.text_search import text_search import datetime from urllib.parse import urlparse app = Flask(__name__) app.config['CORS_HEADERS'] = 'application/json' app.config.from_object(ApplicationConfig) bcrypt = Bcrypt(app) server_session = Session(app) mail = Mail(app) app.secret_key = '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' s = URLSafeTimedSerializer('Thisisasecret!-fjvnnjj2@123vvjk45ancnv9*') db.init_app(app) with app.app_context(): db.create_all() @app.route('/register' ,methods = ['GET', 'POST']) def create_user(): resp = register_user( configEmail , app ,request ,bcrypt ,User, jsonify ,db , s , Message ,url_for ,mail , datetime) return resp @app.route('/confirm_email/<token>' , methods=['GET', 'POST']) def confirm_email(token): resp = confirm_user_email(token , s ,User ,db , datetime , SignatureExpired) return resp @app.route('/change_password/<token>', methods=['POST', 'GET']) def change_my_password(token): resp = change_user_password(token ,request , s , User , bcrypt ,db ,render_template) return resp @app.route('/forget_password',methods=["POST"]) def forgot_my_password(): resp = forgot_user_password(configEmail , app , request , s ,Message , url_for , mail , jsonify) return resp @app.route('/login', methods=['POST']) def log_user_in(): resp = login_user(configEmail,app,request,User,bcrypt,jsonify,Message,s,url_for,mail,session,flask) return resp @app.route('/logout', methods=['POST']) def logout(): session.pop("user_id") return "200" @app.route('/image_search', methods=['GET','POST']) def search_by_image(): resp = image_search() return resp @app.route('/text_search', methods=['GET','POST']) def search_by_text(): resp = text_search('phone case') return resp # main driver function if __name__ == '__main__': os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' app.run('localhost', 8080 , debug=True)
import { BrowserRouter, Routes, Route, Link } from "react-router-dom"; import Home from "./pages/Home"; import About from "./pages/About"; import Posts from "./pages/Posts"; import History from "./pages/History"; import PostDetail from "./components/PostDetail"; const App = () => { const posts = [ { id: 1, title: "Title 1", body: "body 1", }, { id: 2, title: "Title 2", body: "body 2", }, { id: 3, title: "Title 3", body: "body 3", }, ]; return ( <BrowserRouter> <header> <Link to="/">Home</Link> <Link to="/about">About</Link> <Link to="/post">Post</Link> </header> <main> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />}> <Route path="history" element={<History />} /> </Route> <Route path="/post" element={<Posts posts={posts} />} /> <Route path="/post/:id" element={<PostDetail posts={posts} />} /> </Routes> </main> </BrowserRouter> ); }; export default App;
--- title: Adicionar marca d'água à seção em documentos do Word linktitle: Adicionar marca d'água à seção em documentos do Word second_title: API GroupDocs.Watermark .NET description: Adicione facilmente marcas d'água a documentos do Word usando GroupDocs.Watermark for .NET. Proteja seu conteúdo com este guia simples. type: docs weight: 15 url: /pt/net/word-processing-watermarkings/add-watermark-section-word-docs/ --- ## Introdução Colocar marcas d'água em seus documentos é uma etapa crucial para proteger seu conteúdo e afirmar a propriedade. Neste tutorial abrangente, orientaremos você no processo de adição de uma marca d'água a uma seção específica em documentos do Word usando GroupDocs.Watermark for .NET. Quer você seja um desenvolvedor ou alguém com conhecimentos básicos de codificação, este guia o ajudará a proteger seus documentos de maneira eficaz. ## Pré-requisitos Antes de mergulhar no tutorial, vamos garantir que você tenha tudo o que precisa para começar: 1. Ambiente de Desenvolvimento: Você deve ter um ambiente de desenvolvimento .NET configurado em sua máquina. Visual Studio é uma escolha popular. 2. GroupDocs.Watermark para .NET: certifique-se de ter a biblioteca GroupDocs.Watermark instalada. Você pode baixá-lo em[aqui](https://releases.groupdocs.com/Watermark/net/). 3. Conhecimento básico de C#: Este guia pressupõe que você tenha um conhecimento básico de programação C#. ## Importar namespaces Para trabalhar com GroupDocs.Watermark em seu projeto .NET, você precisa importar os namespaces necessários. Veja como você faz isso: ```csharp using GroupDocs.Watermark.Options.WordProcessing; using GroupDocs.Watermark.Watermarks; using System.IO; using System; ``` Agora, vamos dividir o processo em etapas detalhadas e fáceis de seguir. ## Etapa 1: configure seu projeto Antes de adicionar uma marca d'água, configure seu projeto corretamente. Comece criando um novo projeto .NET no Visual Studio: 1. Abra o Visual Studio. 2. Crie um novo projeto e selecione "Console App (.NET Core)". 3. Dê um nome ao seu projeto e clique em "Criar". ## Etapa 2: instalar GroupDocs.Watermark Em seguida, você precisa instalar a biblioteca GroupDocs.Watermark. Você pode fazer isso através do Gerenciador de Pacotes NuGet: 1. Clique com o botão direito em seu projeto no Solution Explorer. 2. Selecione "Gerenciar pacotes NuGet". 3. Procure por "GroupDocs.Watermark". 4. Instale o pacote. ## Etapa 3: carregue seu documento Agora é hora de carregar o documento que deseja colocar marca d'água. Veja como você faz isso: ```csharp string documentPath = "Your Document Path"; var loadOptions = new WordProcessingLoadOptions(); using (Watermarker watermarker = new Watermarker(documentPath, loadOptions)) { // Seu código irá aqui } ``` ## Etapa 4: crie a marca d’água Crie uma marca d'água de texto que será aplicada ao seu documento. Esta etapa envolve a especificação do texto, fonte e tamanho: ```csharp TextWatermark watermark = new TextWatermark("Test watermark", new Font("Arial", 19)); ``` ## Etapa 5: definir opções de marca d’água Para adicionar a marca d'água a uma seção específica, você precisa definir as opções de marca d'água: ```csharp WordProcessingWatermarkSectionOptions options = new WordProcessingWatermarkSectionOptions(); options.SectionIndex = 0; // Isso adiciona a marca d'água à primeira seção ``` ## Etapa 6: adicione a marca d'água Com a marca d’água e as opções prontas, agora você pode adicionar a marca d’água ao documento: ```csharp watermarker.Add(watermark, options); ``` ## Etapa 7: salve o documento Por fim, salve o documento com marca d'água no local desejado: ```csharp string outputFileName = Path.Combine("Your Document Directory", Path.GetFileName(documentPath)); watermarker.Save(outputFileName); ``` E é isso! Você adicionou com êxito uma marca d'água a uma seção específica em um documento do Word usando GroupDocs.Watermark for .NET. ## Conclusão Adicionar marcas d’água aos seus documentos é uma maneira simples, mas eficaz de proteger seu conteúdo. Com GroupDocs.Watermark for .NET, você pode facilmente adicionar, personalizar e gerenciar marcas d’água em seus documentos. Siga este guia passo a passo e você rapidamente colocará marcas d'água em seus documentos como um profissional. ## Perguntas frequentes ### Posso personalizar a aparência da marca d’água? Sim, você pode personalizar a fonte, o tamanho, a cor e outras propriedades do texto da marca d’água. ### É possível adicionar marcas d’água de imagem em vez de texto? Absolutamente! GroupDocs.Watermark oferece suporte a marcas d'água de texto e imagem. ### Posso adicionar marcas d'água a outras seções do documento? Sim, alterando o`SectionIndex`, você pode segmentar seções diferentes. ### GroupDocs.Watermark oferece suporte a outros formatos de documento? Sim, suporta vários formatos, incluindo PDF, Excel, PowerPoint e muito mais. ### Existe um teste gratuito disponível para GroupDocs.Watermark? Sim, você pode acessar um teste gratuito[aqui](https://releases.groupdocs.com/).
<!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>portfolio</title> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> </head> <body> <nav class="navbar"> <div class="container"> <div class="row justify-content-between"> <div class="logo"><a href="index.html">Web<span>Developer</span></a></div> <div class="links"> <ul class="menu"> <li class="nav-item"><a href="#home" class="nav-link">Home</a></li> <li class="nav-item"><a href="#about" class="nav-link">About</a></li> <li class="nav-item"><a href="#services" class="nav-link">Services</a></li> <li class="nav-item"><a href="#portfolio" class="nav-link">Portfolio</a></li> <li class="nav-item"><a href="#pricing" class="nav-link">Pricing</a></li> <li class="nav-item"><a href="#contact" class="nav-link">Contact</a></li> </ul> </div> <div class="menu-btn"> <i class="fas fa-bars"></i> </div> </div> </div> </nav> <section class="home-section" id="home"> <ul class="header-social"> <li><a href="https://www.linkedin.com/in/narendra-garg-254455214"><i class="fab fa-linkedin"></i></a></li> <li><a href="https://www.linkedin.com/in/narendra-garg-254455214"><i class="fab fa-instagram"></i></a></li> <li><a href="https://www.linkedin.com/in/narendra-garg-254455214"><i class="fab fa-facebook-f"></i></a></li> <li><a href="https://www.linkedin.com/in/narendra-garg-254455214"><i class="fab fa-twitter"></i></a></li> </ul> <div class="container"> <div class="row align-item-center"> <div class="home-text"> <h4>Hello</h4> <h1>Narendra Garg</h1> <span>Professional Freelancer Web Developer</span> <p>I am a passionate and skilled web developer with expertise in creating dynamic and responsive websites.</p> <a href="#" class="btn btn-1">purchase now</a> </div> <div class="home-image"> <div class="img-box"> <img src="images\IMG_7967_conv-PhotoRoom.png-PhotoRoom-removebg-preview (4).png" alt=""> </div> </div> </div> <div class="header-hero-shape"></div> </div> </section> <section class="about-section section-padding1" id="about"> <div class="container"> <div class="row align-item-center"> <div class="about-content"> <div class="section-title"> <h5 class="sub-title">About</h5> <h3 class="main-title">Why You Hire Me?</h3> </div> <p >I offer comprehensive web development services, from conceptualization to coding and deployment. Whether you need a simple landing page or a complex web application, I can bring your vision to life. I understand the importance of responsive design in today's mobile-first world, ensuring that your website seamlessly adapts to different devices and screen sizes</p> </div> <div class="about-skills"> <div class="skill-item"> <div class="skill-header"> <h6 class="skill-title">UI/UX Design</h6> <div class="skill-percentage"> <p><span class="counter">90</span>%</p> </div> </div> <div class="skill-bar"> <div class="bar-inner"> <div class="bar progree-line progress-line1" data-progress="90%"></div> </div> </div> </div> <div class="skill-item"> <div class="skill-header"> <h6 class="skill-title">Web Developer</h6> <div class="skill-percentage"> <p><span class="counter">95</span>%</p> </div> </div> <div class="skill-bar"> <div class="bar-inner"> <div class="bar progree-line progress-line2" data-progress="95%"></div> </div> </div> </div> <div class="skill-item"> <div class="skill-header"> <h6 class="skill-title">HTML/CSS</h6> <div class="skill-percentage"> <p><span class="counter">80</span>%</p> </div> </div> <div class="skill-bar"> <div class="bar-inner"> <div class="bar progree-line progress-line3" data-progress="80%"></div> </div> </div> </div> <div class="skill-item"> <div class="skill-header"> <h6 class="skill-title">Node.js/Mongodb</h6> <div class="skill-percentage"> <p><span class="counter">85</span>%</p> </div> </div> <div class="skill-bar"> <div class="bar-inner"> <div class="bar progree-line progress-line4" data-progress="85%"></div> </div> </div> </div> </div> </div> </div> </section> <section class="contact-section section-padding1" id="contact"> <div class="container"> <div class="row"> <div class="contact-title "> <h5 class="contact-sub-title">contact</h5> <h3 class="contact-main-title">get in touch</h3> </div> </div> <div class="row"> <div class="phone"> <div class="phone-icon"><i class="fas fa-phone"></i></div> <div class="contact1">Phone</div> <div class="contact2">7909437985</div> </div> <div class="email"> <div class="phone-icon"><i class="fas fa-envelope"></i></div> <div class="contact1">Email</div> <div class="contact2">narendragarg090909@gmail.com</div> </div> <div class="address"> <div class="phone-icon"><i class="fas fa-map-marker-alt"></i></div> <div class="contact1">Address</div> <div class="contact2">Jaipur</div> </div> </div> <div class="row"> <div class="form-1"> <form action="" method="get" class="form-1-1"> <div class="name1"><input type="text" placeholder="Name" required name="Name" autocomplete="on"></div> <div class="email1"><input type="email" placeholder="Email" required name="Email" autocomplete="on"></div> <div class="subject1"><input type="text" placeholder="Subject" required name="Subject" autocomplete="on"></div> </form> </div> <div class="form-2"> <form action="" method="get" class="form-2-2"></form> <div class="message1"><textarea type="text" name="Message" cols="45" rows="7" placeholder="Message" class="message2"></textarea></div> </form> </div> </div> <div class="namaste"><button type="submit" class="btn-2">Submit</button></div> </div> </section> <footer class="footer1"> <div class="copyright">&copy; by<span> Narendra Garg<span></span></div> </footer> <script src="js/main.js"></script> </body> </html>
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>if, unless</h1> <table border="1"> <tr> <th>count</th> <th>username</th> <th>age</th> </tr> <tr th:each="user, userStat : ${users}"> <td th:text="${userStat.count}">1</td> <td th:text="${user.username}">username</td> <td> <span th:text="${user.age}">0</span> <!--조건에안맞으면 span 태그 자체가 출력이 안됨--> <span th:text="'미성년자'" th:if="${user.age lt 20}"></span> <!-- < 작다 --> <span th:text="'미성년자'" th:unless="${user.age ge 20}"></span> <!-- >= 크거나 같다 --> </td> </tr> </table> <h1>switch</h1> <table border="1"> <tr> <th>count</th> <th>username</th> <th>age</th> </tr> <tr th:each="user, userStat : ${users}"> <td th:text="${userStat.count}">1</td> <td th:text="${user.username}">username</td> <td th:switch="${user.age}"> <span th:case="10">10살</span> <span th:case="20">20살</span> <span th:case="*">기타</span> <!-- * 은 만족하는 조건이 없을 때 사용하는 디폴트이다--> </td> </tr> </table> </body> </html>
--- title: Redirects --- Redirect URLs through one of the following methods: - **Rules:** Rules allow you to define how a URL will be redirected through the [URL Redirect feature](/applications/performance/rules/features#url-redirect). This feature is especially useful when URL redirects should only occur under specific conditions. - **CDN-as-Code:** If you are using CDN-as-code, then you may define URL redirects through the [url.url_redirect feature](/applications/performance/cdn_as_code/route_features#redirecting). - **Edge Functions:** Edge Functions allow you to [intelligently redirect URLS](/applications/edge_functions/examples/redirects). - **Location Header:** Include the `Location` response header within a `3xx` response to instruct clients to redirect to a different URL. Alternatively, you can instruct {{ PRODUCT }} to follow a redirect defined within a `Location` header provided by the origin through the [Follow Redirects feature](/applications/performance/rules/features#follow-redirects) ([follow_redirects](/docs/api/core/interfaces/types.Url.html#follow_redirects)). - **Bulk Redirects:** Use this capability to define a list of URLs for which we will return a `3xx` response with a `Location` header set to the desired URL. In addition to managing URL redirects on an individual basis, you may import and export a list of URL redirects. ## Bulk Redirects {/*bulk-redirects*/} This capability allows you to define a list of URLs for which we will return a `3xx` response with a `Location` header set to the desired URL. Manage URL redirects on a per environment basis by either manually adding redirect configurations or by importing a CSV file. **Key information:** - Your redirect configuration is excluded from versioning. This allows you to roll back an environment to a previous version without affecting your URL redirects. <Callout type="tip"> We strongly recommend that you [back up your redirect configuration as a CSV file](#export) and place it under source control. </Callout> - Requests are redirected before being processed by rules. Additionally, once a request is redirected, only features that affect the response can be applied. For example, you may set headers for the `3xx` response sent to the client. - For each redirect, you must define a source and a destination. ![Add a redirect - Source and Destination](/images/v7/performance/redirects-source-destination.png?width=600) Specify either of the following types of URLs when defining the source and destination: - **Absolute:** Specify the protocol, hostname, and relative path. You may also include a query string. **Example:** `https://cdn.example.com/conferences/2023` - **Relative:** Specify a relative path that starts directly after the hostname. You may also include a query string. **Example:** `/conferences/2023` - If the requested URL matches the source URL defined within a redirect configuration, we will return a `3xx` response with a `Location` header set to the destination URL. It is up to the client (e.g., web browser) to follow this redirect. - The source URL must be unique, since we can only redirect a URL to a single location. However, since we support query strings and relative URLs, the requested URL could still potentially match against multiple source URLs. For this reason, {{ PRODUCT }} prefers precise source URLs according to the following order: - Absolute URL with query string - Absolute URL without query string - Relative URL with query string - Relative URL without query string {{ PRODUCT }} will not perform further comparisons once a match is found. This ensures that the request is redirected according to the configuration that is the most precise match. - Redirecting requests to a relative path may result in an invalid URL when fielding requests from various hostnames. Use an absolute URL to ensure that requests are properly redirected. - Define a `3xx` status code for the redirect through the **Response status** option. By default, we return a `301 Moved Permanently` response. - The **Forward query string to redirect location** option determines whether the `Location` header will include or exclude the request's query string. - You may define up to 10,000 redirects per environment. - Once an environment contains 200 or more redirects, you may only manage them by importing CSV file(s). - Changes to your redirect configuration will not take effect until the next deployment. ### CSV Files {/*csv-files*/} You may import or export a comma-separated values (CSV) file containing a list of redirect configurations. This CSV file must contain the following header row: `from,to,status,forwardQueryString` These columns are defined below. - **from:** Required. Identifies a URL that will be redirected. Specify either an absolute or relative URL. - **to:** Required. Identifies the URL to which clients will be redirected. Specify either an absolute or relative URL. - **status:** Determines the `3xx` status code for the response sent to the client. Valid values are: `301 | 302 | 307 | 308` - **forwardQueryString:** A Boolean value that determines whether the `Location` response header will include the request's query string. Valid values are: `true | false` **Sample CSV:** ```csv filename="default-redirects.csv" from,to,status,forwardQueryString /widgets-conference,https://cdn.example.com/conferences/widgets-conference,302,false https://cdn.example.com/bicycles,/transportation/bicycles,,true https://cdn.example.com/images,https://cdn.example.com/resources/images,, ``` Upon importing a CSV file, you may choose whether to replace or append to your existing redirect configuration. **To import redirect configurations (CSV)** 1. Navigate to the **Redirects** page. {{ ENV_NAV }} **Redirects**. 2. Click **Import**. 3. Select a CSV file by clicking **Browse**, navigating to the desired CSV file, selecting it, and then clicking **Open**. 4. Determine whether you will replace or append to your existing redirect configurations. - **Replace:** Select **Override existing list with file content**. - **Append:** Select **Append file content to existing redirects list**. <Callout type="info"> The source URL (`from`) must be unique across all redirect configurations. You will not be allowed to append a CSV file to your existing configuration if doing so will create a redirect configuration with a duplicate source URL. </Callout> 5. Click **Upload redirects**. 6. If you are finished making changes, click **Deploy Now** to deploy your changes to this environment. **<a id="export" />To export redirect configurations (CSV)** 1. Navigate to the **Redirects** page. {{ ENV_NAV }} **Redirects**. 2. Click **Export** to download a CSV file called `default-redirects.csv`. ### Redirect Configuration Administration {/*redirect-configuration-administration*/} You may add, modify, and delete redirect configurations regardless of whether they were added manually or [imported from a CSV file](#csv-files). **To add a redirect** 1. Navigate to the **Redirects** page. {{ ENV_NAV }} **Redirects**. 2. Click **Add a redirect**. 3. From the **Redirect from** option, type the URL that will be redirected. 4. From the **To** option, type the URL to which the `Location` response header will be set. 5. Optional. From the **Response status** option, select the `3xx` status code for the response sent to the client. 6. Optional. Mark the **Forward query string to redirect location** option to allow the request's query string to be included with the destination URL defined within the `Location` response header. Your redirect configuration should now look similar to the following illustration: ![Add a redirect](/images/v7/performance/redirects-add-a-redirect.png?width=600) 7. Click **Add a redirect**. 8. Repeat steps 2 - 7 as needed. 9. If you are finished making changes, click **Deploy Now** to deploy your changes to this environment. **To modify a redirect** 1. Navigate to the **Redirects** page. {{ ENV_NAV }} **Redirects**. 2. Find the desired redirect configuration and then click on it. <Callout type="tip"> Use the search field to filter the list to redirect configurations whose source or destination URL matches the specified value. </Callout> 3. Make the desired changes. 4. Click **Save redirect**. 5. Repeat steps 2 - 4 as needed. 6. If you are finished making changes, click **Deploy Now** to deploy your changes to this environment. **To delete a redirect** 1. Navigate to the **Redirects** page. {{ ENV_NAV }} **Redirects**. 2. Mark each desired redirect. 3. Click **Remove selected redirect(s)**. 4. If you are finished making changes, click **Deploy Now** to deploy your changes to this environment.
import { createComponentRenderer } from '@/__tests__/render'; import { useNDVStore } from '@/stores/ndv.store'; import { createTestingPinia } from '@pinia/testing'; import userEvent from '@testing-library/user-event'; import { fireEvent } from '@testing-library/vue'; import { createPinia, setActivePinia } from 'pinia'; import DropArea from '../DropArea.vue'; const renderComponent = createComponentRenderer(DropArea, { pinia: createTestingPinia(), }); async function fireDrop(dropArea: HTMLElement): Promise<void> { useNDVStore().draggableStartDragging({ type: 'mapping', data: '{{ $json.something }}', dimensions: null, }); await userEvent.hover(dropArea); await fireEvent.mouseUp(dropArea); } describe('DropArea.vue', () => { afterEach(() => { vi.clearAllMocks(); }); it('renders default state correctly and emits drop events', async () => { const pinia = createPinia(); setActivePinia(pinia); const { getByTestId, emitted } = renderComponent({ pinia }); expect(getByTestId('drop-area')).toBeInTheDocument(); await fireDrop(getByTestId('drop-area')); expect(emitted('drop')).toEqual([['{{ $json.something }}']]); }); });
import { TextField,Button, Alert } from '@mui/material'; import React from 'react'; import alert from '../utility/alerts'; import { Navigate } from "react-router-dom"; const RegisterPage = () => { const [redirect, setRedirect] = React.useState(false); const name = React.useRef(); const phone = React.useRef(); const username = React.useRef(); const email = React.useRef(); const password = React.useRef(); const handleSubmit = async (ev) => { ev.preventDefault(); const nameVal= name.current.value; const phoneVal= Number(phone.current.value); const usernameVal= username.current.value; const emailVal= email.current.value; const passwordVal= password.current.value; // const mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; // const usernameFormat = /^[A-Za-z][A-Za-z0-9_]{1,29}$/; // const passwordFormat = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/; // if(nameVal.length<2 || name.length > 50){ // alert('Name should be greater than 1 and less than 50 charector', 'error') // return // } // if(phoneVal<1000000000){ // alert("Invalid Phone Number ", "error") // return // } // if (!mailformat.test(emailVal)) { // alert('Invalid email', 'error') // return // } // if (!usernameFormat.test(usernameVal)) { // alert('Invalid username! first character should be alphabet [A-Za-z] and other characters can be alphabets, numbers or an underscore so, [A-Za-z0-9_].', 'error') // return // } // if (!passwordFormat.test(passwordVal)) { // alert('password should have minimum of eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:', 'error') // return // } // if(usernameVal.length<3 || usernameVal.length>30){ // alert('Username should be graterthan 3 or lessthan equals to 30 charectors', "error") // return // } const response = await fetch(`${import.meta.env.VITE_BASE_URL}/api/v1/auth/register`,{ method:'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ name: nameVal, phone: phoneVal, email:emailVal, username:usernameVal, password:passwordVal}) }) if (response.ok){ const data = await response.json(); alert('User Registered', 'success'); setRedirect(true) } else { const data=await response.json(); alert(data.error,'error') } }; if (redirect) { return <Navigate to={'/login'} /> } return ( <div> <div className="register-page"></div> <div className="register-container"> <div className="register-form"> <h1>Sign Up</h1> <form onSubmit={handleSubmit}> <TextField fullWidth id='filled-basic' label="Full Name" variant='filled' inputRef={name} required autoComplete='true'/> <TextField fullWidth id='filled-basic' label="Phone" type="number" variant='filled' inputRef={phone} required autoComplete='true'/> <TextField fullWidth id='filled-basic' label="email" variant='filled' inputRef={email} required autoComplete='true'/> <TextField fullWidth id='filled-basic' label="Username" variant='filled' inputRef={username} required autoComplete='true'/> <TextField fullWidth id='filled-basic' label="password" type="password" variant='filled' inputRef={password} required autoComplete='true'/> <Button variant="contained" sx={{marginTop:"20px" , width:'100%'}} type='submit'>Sign Up</Button> </form> </div> </div> </div> ) } export default RegisterPage
====== LU04.A03 - Story ====== <WRAP center round todo 60%> Schreiben Sie ein Programm das eine Geschichte erzählt. </WRAP> ===== Auftrag ===== Schreiben Sie ein Programm, das den Benutzer nach dem Namen einer Person und ihrem Beruf fragt. Das Programm gibt dann eine kurze Geschichte aus. Die Ausgabe muss wie unten gezeigt aussehen - beachten Sie, dass der Name und der Beruf von den Eingaben des Benutzers abhängen. <HTML> <iframe src="https://trinket.io/embed/python3/ba900c2e0d?outputOnly=true&start=result" width="100%" height="200" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </HTML> <code> I will tell you a story, but I need some information first. What is the main character called? *Bob* What is their job? *builder* Here is the story: Once upon a time there was Bob, who was a builder. On the way to work, Bob reflected on life. Perhaps Bob will not be a builder forever. </code> Die Übungsvorlage wird mit einer Programmvorlage geliefert, die die Funktion und ihren Aufruf enthält. <code python> def story(): # Write your code here if __name__ == '__main__': story() </code> Hier ein weiteres Beispiel für die Ausgabe: <code> I will tell you a story, but I need some information first. What is the main character called? *Ada* What is their job? *Data scientist* Here is the story: Once upon a time there was Ada, who was a Data scientist. On the way to work, Ada reflected on life. Perhaps Ada will not be a Data scientist forever. </code> ===== Vorgehen ===== - Akzeptiere das GitHub Classroom Assignment im Moodlekurs. - Klone das Repository in PyCharm. - Codiere die Programmlogik in ''main.py''. - Teste dein Programm mit den Testfällen in ''main_test.py''. - Führe einen Commit und einen Push durch. Anmerkung: Kümmern Sie sich im Moment nicht zu sehr um ''if %%__%%name%%__%% == '%%__%%main%%__'%%:''. Wir brauchen es technisch gesehen nicht für dieses Programm, aber es ist eine gute Übung, es einzubauen, und es wird in späteren Übungen klarer werden. ---- <nodisp>GitHub-Repo: https://github.com/templates-python/m319-lu04-a03-story</nodisp> [[https://creativecommons.org/licenses/by-nc-sa/4.0/ch/|{{https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png}}]] (c) Kevin Maurizi Diese Aufgabe ist eine übersetzte und angepasste Aufgabe von [[https://scott3142.uk/|Scott Morgan]], verwendet unter CC BY NC SA.
Docker Installation ----------------------- 1. curl -fsSL https://get.docker.com -o get-docker.sh sh get-docker.sh 2. apt install docker.io -y systemctl restart docker systemctl enable docker.service docker info docker version docker --version docker version --format '{{.Server.Version}}' docker build -t(tag) imagename . docker pull imagename ## To build Docker image using repository reference docker build -t <hub-user>/<repo-name>:<imagetag> <pathof docker file> docker build -t 'venkatondevops/nginxserver:1' . docker push docker login -u <uname> -p <password> <url> docker images docker image ls docker image inspect imagename docker inspect imageid/imagename docker history imageid/imagename ---- to see only layers docker inspect containerid/containername docker rmi -f(force) imageid/imagename docker rmi -f(force) imageid/imagename imageid/imagename imageid/imagename - to delete all docker rmi -f $(docker images -q) docker images -q -- list all image ids docker tag image -- to tag image to the repository docker ps docker container ls docker container ls -a docker ps -a all containers docker ps -aq docker container ls -aq docker start containerid/name docker restart containerid/name docker stop containerid/name docker kill containerid/name docker pause containerid/name docker unpause containerid/name docker system prune -a -- it will remove both unused and dangling images docker images -f dangling=true -- list dangling images docker rmi $(docker images -f dangling=true -q) docker images --quiet --filter=dangling=true | xargs --no-run-if-empty docker rmi docker image prune docker rm -f container-name/container-id docker system prune ---- delte all stoped container, networks, dangling, docker run -d --name contname -p <hostport>:<contport> imageid dockertrustedregistry(Docker enterprise edition) docker rm $(docker ps -aq --filter status="exited") docker rm -f $(docker ps -aq ) what is dangling images in docker. the image which doesnt have repository mapping or tagging docker exec -it <container_name> bash what is port publish or port mapping or port forwording ------------------------------------------------------------- container name and host port should be unique in docker you cannot update the port mapping once container is created Docker Home directory or working directory ----------------------------------------------- var/lib/docker How can we move image from one server to another with out using repo --------------------------------------------------------------------- docker save -o filename.tar imagename/imageid then scp from source to destination docker load -i filename.tar - in desrination difference between docker run and docker create ---------------------------------------------- docker create will only create the container but not run docker run will create and start container Docker container commands --------------------------- docker run --name <containername> -p <hostport>:<containerport> imageName docker create --name <containername> -p <hostport>:<containerport> imageName docker start containername Docker Credential Store ----------------------------- $HOME/.docker/config.json difference between docker kill and stop ------------------------------------ both are used to stop containers but stop will send docker kill will stop the main entrypoint process/program abruptly docker stop will try to stop it gracefully by sending SIGTERM signal to a process to request its termination. It is analogous to Pulling the Plug off Desktop and Shutting down the computer Like pulling the Plug Off means hard power off, docker kill means s direct way to kill my_container, which does not attempt to shut down the process gracefully first. Shutting down the computer means sending a signal to OS for shutting down all the processes where docker stop means sending SIGTERM signal to the running container to stop the processes gracefully. Share telling the docker dont use cache when building docker image -------------------------------------------------------- docker build -t tagname --no-cache imagename Docker Networking ---------------------------------- docker network ls docker inspect containername/id docker network create -d bridge flipkartnetwork docker network create -d(driver) bridge flipkartnetwork docker network inspect flipkartnetwork docker run -d --name webserver --network flipkartnetwork -p 80:80 nginx docker run -d --name mongo --network flipkartnetwork -p 3070:3070 mongo docker network connect networkname containernameinothenetwork docker network disconnect networkname containernameinothenetwork docker network rm networkname is it possible to do the volume mapping for a running container -------------------------------------------------------------- port mapping and volume mapping can not be done for a running containers Docker Volumes -------------------------------------------------------- Bind Mounts - is nothing but a folder/file in the host system or docker server docker volumes are suggestable when we are doing volume mapping rather than bindmount Voulmes - these are persistent volumes Local Volumes Network Volumes docker run -d --name contname -v <volumename/BindMountPath>:<containerpath> --network netwkname image docker volume ls docker volume create -d local <volumename> docker run -d --name contname -v dockervolumename:<containerpath>:ro(read only) --network netwkname image docker run -d --name contname -v dockervolumename:<containerpath>:rw(read write) --network netwkname image Docker plugins ------------------- rexray is the plugin for ebs docker plugin ls docker volume create -d rexray/ebs volumename
import * as Yup from "yup"; type Message = string; type FieldName = string; type FieldValue = FieldValues[FieldName]; type FieldValues = Record<FieldName, any>; type FieldError = { message?: Message; }; type FieldErrors<T extends FieldValues = FieldValues> = { [K in keyof T]: FieldError; }; export type ResolverSuccess<TFieldValues extends FieldValues = FieldValues> = { values: TFieldValues; errors: {}; }; export type ResolverError<TFieldValues extends FieldValues = FieldValues> = { values: {}; errors: FieldErrors<TFieldValues>; }; export type ResolverResult<TFieldValues extends FieldValues = FieldValues> = | ResolverSuccess<TFieldValues> | ResolverError<TFieldValues>; export const yupResolver: YupResolver = <T extends FieldValues>( schema: Yup.ObjectSchema<T> ) => { return async (values) => { try { const validatedValues = await schema.validate(values, { abortEarly: false, }); return { values: validatedValues, errors: {} }; } catch (err) { if (err instanceof Yup.ValidationError) { const errors = err.inner.reduce((acc, error) => { if (error.path) { acc[error.path as keyof typeof errors] = { message: error.message }; } return acc; }, {} as FieldErrors<T>); console.log(errors); return { values: {}, errors }; } throw err; } }; }; export type YupResolver = <T extends Yup.ObjectSchema<any>>( schema: T ) => <TFieldValues extends FieldValues>( values: TFieldValues ) => Promise<ResolverResult<TFieldValues>>;
import "./App.css"; import { Navbar } from "./layouts/NavbarAndFooter/Navbar"; import { Footer } from "./layouts/NavbarAndFooter/Footer"; import { SearchBooksPage } from "./layouts/SearchBooksPage/SearchBooksPage"; import { HomePage } from "./layouts/HomePage/HomePage"; import { Redirect, Route, Switch, useHistory } from "react-router-dom"; import { BookCheckoutPage } from "./layouts/BookCheckoutPage/BookcheckoutPage"; import { oktaConfig } from "./lib/oktaConfig"; import {OktaAuth,toRelativeUrl} from "@okta/okta-auth-js"; import { LoginCallback, Security } from "@okta/okta-react"; import LoginWidget from "./Auth/LoginWidget"; const oktaAuth = new OktaAuth(oktaConfig); export const App = () => { const customAuthHandler = () => { history.push('/login'); } const history = useHistory(); const restoreOriginalUri = async (_oktaAuth: any, originalUri:any) => { history.replace(toRelativeUrl(originalUri || '/',window.location.origin)); }; //d-flex flex-colum min-vh-100 return ( <div className=""> <Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri} onAuthRequired={customAuthHandler}> <Navbar/> <div className="flex-grow-1"> <Switch> <Route path="/" exact> <Redirect to='/home' /> <HomePage /> </Route> <Route path="/home" exact> <HomePage /> </Route> <Route path="/search"> <SearchBooksPage /> </Route> <Route path="/checkout/:bookId"> <BookCheckoutPage/> </Route> <Route path='/login' render={() => <LoginWidget config={oktaConfig}/>}/> <Route path='/login/callback' component={LoginCallback}/> </Switch> </div> <Footer /> </Security> </div> ); }; export default App;
import { createServer } from "http"; import { Server, Socket } from "socket.io"; import AuthController from "../controllers/authController.js"; import ChatMember from "../models/chatMembers.model.js"; import ChatMessage from "../models/chatMessages.model.js"; import Chat from "../models/chats.model.js"; import User from "../models/users.model.js"; import { ChatMessageSchema, ValidateChatMessage } from "../schemas/chatMessage.js"; import AuthorizeSocket from "./middlewares/auth.js"; type srvr = ReturnType<typeof createServer>; interface ServerToClientEvents { 'get chat message': (message: ChatMessageSchema) => void, 'update members': () => void, 'chat removed': () => void, } interface ClientToServerEvents { 'connect to chat': (chatId: number) => void, 'disconnect from chat': (chatId: number) => void, 'leave chat': (chatId: number) => void, 'join chat': (chatId: number) => void, 'remove chat': (chatId: number) => void, 'send chat message': (message: {chatId: number, text: string}, response: (msg: ChatMessageSchema, errorMessage: null | string) => void) => void, } interface InterServerEvents { } interface SocketData { user: {userId: number}, } export function _log(...strs: unknown[]) { console.log('[🌐]',...strs); } export type SocketType = Socket< ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData > // eslint-disable-next-line @typescript-eslint/no-explicit-any export type SocketNext = (err?: any) => void; export default function SocketIOInitialize(server: srvr) { const io = new Server< ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData >(server, { cors: { origin: /http:\/\/localhost:[0-9]+/, }, }); io.use(AuthorizeSocket); io.on('connection', (socket) => { socket.on('connect to chat', async (chatId) => { _log('CHAT:', chatId, socket.id); try { const isAllowed = await AuthController.isMemberOfChat(chatId, socket.data.user.userId); if (isAllowed) socket.join('group chat '+chatId); } catch(err) { return; } }); socket.on('disconnect from chat', async (chatId) => { _log('DISCONNECT CHAT:', chatId, socket.id); socket.leave('group chat '+chatId); }); socket.on('leave chat', async (chatId) => { _log('LEAVE CHAT:', chatId, socket.data.user.userId, socket.data.user); const isAllowed = await AuthController.isMemberOfChat(chatId, socket.data.user.userId); if (!isAllowed) return; try { await ChatMember.destroy({where: { userId: socket.data.user.userId, chatId: chatId, }}); const room = 'group chat '+chatId; socket.broadcast.to(room).emit('update members'); } catch(err) { return; } }); socket.on('remove chat', async (chatId) => { _log('REMOVE CHAT:', chatId, socket.data.user.userId, socket.data.user); const isAllowed = await AuthController.isCreatorOfChat(chatId, socket.data.user.userId); if (!isAllowed) return; try { await Chat.destroy({where: { userId: socket.data.user.userId, chatId: chatId, }}); const room = 'group chat '+chatId; io.to(room).emit('chat removed'); } catch(err) { return; } }); socket.on('join chat', (chatId) => { const room = 'group chat '+chatId; socket.broadcast.to(room).emit('update members'); }); socket.on('send chat message', async (msg, response) => { _log('MESSAGE:', msg, socket.id); if (!socket.rooms.has('group chat '+msg.chatId)) { _log('MESSAGE: Unknown chat'); return response(null, 'Unknown chat'); } const validation = ValidateChatMessage(msg); if (validation) { _log('MESSAGE: Validation failed'); return response(null, 'Message is too long'); } let userDB; try { userDB = await User.findOne({ where: {userId: socket.data.user.userId} }); } catch (err) { if (err.name === 'SequelizeDatabaseError') { _log('MESSAGE: Database failed User'); return response(null, 'User not found'); } return response(null, 'Internal error'); } try { const messageDB = await ChatMessage.create({ chatId: msg.chatId, userId: socket.data.user.userId, text: msg.text, }); const messageReturn: ChatMessageSchema = { messageId: messageDB.messageId, chatId: messageDB.chatId, text: messageDB.text, user: { userId: userDB.userId, avatar: userDB.avatar, nickname: userDB.nickname, }, updatedAt: messageDB.updatedAt, createdAt: messageDB.createdAt, }; const room = 'group chat '+msg.chatId; socket.broadcast.to(room).emit("get chat message", messageReturn); response(messageReturn, null); } catch (err) { if (err.name === 'SequelizeDatabaseError') { _log('MESSAGE: Database failed Message'); return response(null, 'Internal server error'); } return response(null, 'Internal error'); } }); }); return io; }
const OPEN_WEATHER_API_KEY = 'b9f5f022c1e0195a8a3b75d6bf2d2200' export interface OpenWeatherData { name: string main: { feels_like: number humidity: number pressure: number sea_level: number temp: number temp_max: number temp_min: number } weather: { description: string icon: string id: string main: string }[] wind: { deg: number speed: number } } export type OpenWeatherTempScale = 'metric' | 'imperial' export async function fetchOpenWeatherData( city: string, tempScale: OpenWeatherTempScale ): Promise<OpenWeatherData> { const res = await fetch( `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=${tempScale}&appid=${OPEN_WEATHER_API_KEY}` ) if (!res.ok) { throw new Error('City not found') } const OpenWeatherData = await res.json() return OpenWeatherData } export function getWeatherIconSrc(iconCode: string) { return `https://openweathermap.org/img/wn/${iconCode}@2x.png` }
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ReSharper disable CheckNamespace // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable CommentTypo // ReSharper disable IdentifierTypo // ReSharper disable InconsistentNaming // ReSharper disable StringLiteralTypo // ReSharper disable UnusedParameter.Local /* CountdownMemoryOwner.cs -- * Ars Magna project, http://arsmagna.ru */ #region Using directives using System; using System.Buffers; using System.Runtime.CompilerServices; #endregion #nullable enable namespace AM.Memory; /// <summary> /// Encapsulates manual memory management mechanism. Holds /// IMemoryOwner instance goes to GC (link = null) only when /// all owning entities called Dispose() method. This means, /// that only this mechanism should be used for covering /// managed instances. /// </summary> public sealed class CountdownMemoryOwner<T> : IMemoryOwner<T> { #region Properties /// <summary> /// Владеемая память. /// </summary> public Memory<T> Memory { [MethodImpl (MethodImplOptions.AggressiveInlining)] get; private set; } #endregion #region Private members private int _length; private int _offset; private int _owners; private T[]? _arr; private CountdownMemoryOwner<T>? _parent; [MethodImpl (MethodImplOptions.AggressiveInlining)] internal CountdownMemoryOwner<T> Init ( CountdownMemoryOwner<T> parent, int offset, int length, bool defaultOwner = true ) { _owners = defaultOwner ? 1 : 0; _offset = offset; _length = length; _parent = parent; _parent.AddOwner(); Memory = _parent.Memory.Slice (_offset, _length); return this; } [MethodImpl (MethodImplOptions.AggressiveInlining)] internal CountdownMemoryOwner<T> Init ( T[] array, int length ) { _owners = 1; _offset = 0; _length = length; _parent = default; _arr = array; Memory = _arr.AsMemory (0, _length); return this; } #endregion #region Public methods /// <summary> /// Ручное добавление владельца. /// </summary> [MethodImpl (MethodImplOptions.AggressiveInlining)] public void AddOwner() => _owners++; #endregion #region IDisposable members /// <inheritdoc cref="IDisposable.Dispose"/> [MethodImpl (MethodImplOptions.AggressiveInlining)] public void Dispose() { _owners--; if (_owners > 0) { return; } if (_parent != default) { _parent.Dispose(); _parent = default; } else { ArrayPool<T>.Shared.Return (_arr!); } Pool<CountdownMemoryOwner<T>>.Return (this); } #endregion }
import Select from '@/components/ui/Select' import CreatableSelect from 'react-select/creatable' import type { InputActionMeta, ActionMeta } from 'react-select' type Option = { value: string label: string color: string } const colourOptions = [ { value: 'ocean', label: 'Ocean', color: '#00B8D9' }, { value: 'blue', label: 'Blue', color: '#0052CC' }, { value: 'purple', label: 'Purple', color: '#5243AA' }, { value: 'red', label: 'Red', color: '#FF5630' }, { value: 'orange', label: 'Orange', color: '#FF8B00' }, { value: 'yellow', label: 'Yellow', color: '#FFC400' }, { value: 'green', label: 'Green', color: '#36B37E' }, { value: 'forest', label: 'Forest', color: '#00875A' }, { value: 'slate', label: 'Slate', color: '#253858' }, { value: 'silver', label: 'Silver', color: '#666666' }, ] const Creatable = () => { const handleChange = ( newValue: Option | Option[] | null, actionMeta: ActionMeta<Option> ) => { console.group('Value Changed') console.log(newValue) console.log(`action: ${actionMeta.action}`) console.groupEnd() } const handleInputChange = ( inputValue: string, actionMeta: InputActionMeta ) => { console.group('Input Changed') console.log(inputValue) console.log(`action: ${actionMeta.action}`) console.groupEnd() } return ( <div> <Select<Option> isClearable placeholder="Type something..." componentAs={CreatableSelect} options={colourOptions} onChange={handleChange} onInputChange={handleInputChange} /> </div> ) } export default Creatable
import { Component, Inject, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Location } from '@angular/common'; import { SaloniService } from 'src/app/Services/saloni.service'; import { User } from 'src/app/Models/User'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; @Component({ selector: 'app-nuovo-cliente', templateUrl: './nuovo-cliente.component.html', styleUrls: ['./nuovo-cliente.component.scss'] }) export class NuovoClienteComponent implements OnInit { form: FormGroup; submitted = false; alert: boolean = false; alertText: string = ''; loading = false; gruppo: string = ''; salone: string = ''; user: User; constructor(private loc: Location, private saloni: SaloniService, private formBuilder: FormBuilder, private route: Router, public dialogRef: MatDialogRef<NuovoClienteComponent>, @Inject(MAT_DIALOG_DATA) public userPubblico: User) { this.gruppo = localStorage.getItem('GruppoCliente'); this.salone = localStorage.getItem('SaloneCliente'); this.user=userPubblico; } ngOnInit() { this.form = this.formBuilder.group({ nome: ['', Validators.required], cognome: ['', Validators.required], phone: ['', [Validators.required, Validators.minLength(8), Validators.pattern("^[0-9]*$")]], email: ['', [Validators.required,]],// Validators.email }); } // convenience getter for easy access to form fields get f() { return this.form.controls; } onSubmit() { // stop here if form is invalid //this.form.invalid || if (this.f.email.value === '' || this.f.nome.value === '' || this.f.cognome.value === '' || this.f.phone.value === '') { alert('Tutti i campi sono obbligatori'); return; } this.submitted = true; this.loading = true; this.user.gruppo = this.gruppo; this.user.salone = this.salone; this.user.email = this.f.email.value; this.user.nome = this.f.nome.value; this.user.cognome = this.f.cognome.value; this.user.cell = this.f.phone.value; this.saloni.addUserClienteFromPlanner(this.user).subscribe( (data: User) => { if (data.errorMessage !== null && data.errorMessage !== '') { this.loading = false; this.alert = true; this.alertText = data.errorMessage; } else { console.log(data); this.user.id=data.id; //localStorage.setItem("UserCliente", JSON.stringify(data)); this.dialogRef.close(this.user); } }, error => { this.alert = true; this.alertText = "Impossibile raggiungere il server" this.loading = false; }); } removeAlert() { this.alert = false; } back() { this.loc.back(); } }
@extends('layouts.app') @section('content') <div class="flex justify-center"> <div class="w-8/12 bg-white p-6 rounded-lg"> <div class="mb-4"> <a href="{{route('users.posts', $post->user)}}" class="font-bold">{{$post->user->name}}</a><span class="text-gray-600 text-sm"> {{$post->created_at->diffForHumans()}}</span> <p class="mb-2">{{$post->body}}</p> &nbsp; <hr/> <div class="flex items-center"> @auth @if(!$post->likedBy(auth()->user())) <form action="{{route('posts.likes', $post->id)}}" method="post" class="mr-1"> @csrf <button type="submit" class="text-blue-500">Like</button> </form> @else <form action="{{route('posts.likes', $post->id)}}" method="post" class="mr-1"> @method('DELETE') @csrf <button type="submit" class="text-blue-500">Unlike</button> </form> @endif <form action="" method="post" class="mr-1"> @csrf <button type="submit" class="text-blue-500">Edit</button> </form> @can('delete',$post) <form action="{{route('posts.destroy',$post->id)}}" method="post" class="mr-1"> @method('DELETE') @csrf <button type="submit" class="text-blue-500">Delete</button> </form> @endcan @endauth <span>{{$post->likes->count()}} {{Str::plural('like', $post->likes->count())}}</span> </div> </div> </div> </div> @endsection
#pragma once #include "piola_kirchhoff.h" namespace flesh { struct BaseMaterial { double lambda; // Lame's first parameter double mu; // Lame's second parameter virtual ~BaseMaterial() = default; virtual void compute_piola_kirchhoff_stress( Eigen::Matrix3d const& F, Eigen::Matrix3d& P) const = 0; virtual void compute_piola_kirchhoff_stress_differential( Eigen::Matrix3d const& F, Eigen::Matrix3d const& dF, Eigen::Matrix3d& P, Eigen::Matrix9x9d& dPdF) const = 0; virtual void precompute() = 0; auto get_piola_kirchhoff_fn() const { return [this](Eigen::Matrix3d const& F, Eigen::Matrix3d& P) { compute_piola_kirchhoff_stress(F, P); }; } auto get_piola_kirchhoff_differential_fn() const { return [this](Eigen::Matrix3d const& F, Eigen::Matrix3d const& dF, Eigen::Matrix3d& P, Eigen::Matrix9x9d& dP) { compute_piola_kirchhoff_stress_differential(F, dF, P, dP); }; } }; }
import { Link } from 'react-router-dom'; import { motion } from 'framer-motion'; type BaseProps = { addBase: (base: string) => void; pizza: { base: string; toppings: string[] | []; } } const Base = ({ addBase, pizza }: BaseProps) => { const bases = ['Classic', 'Thin & Crispy', 'Thick Crust']; return ( <motion.div className="base container" initial={{ x: '100vw' }} animate={{ x: 0 }} transition={{ delay: 0.5, type: 'spring' }} > <h3>Step 1: Choose Your Base</h3> <ul> {bases.map(base => { let spanClass = pizza.base === base ? 'active' : ''; return ( <motion.li key={base} onClick={() => addBase(base)} whileHover={{ scale: 1.3, originX: 0, color: '#f8e112' }} transition={{ type: 'spring', stiffness: 300 }} > <span className={spanClass}>{base}</span> </motion.li> ) })} </ul> {!!pizza.base && ( <motion.div className="next" initial={{ x: '-100vw' }} animate={{ x: 0 }} transition={{ stiffness: 120, type: 'spring' }} > <Link to="/toppings"> <motion.button whileHover={{ scale: 1.1, textShadow: '0 0 2px rgb(255,255,255)', boxShadow: '0 0 4px rgb(255,255,255)', }} >Next</motion.button> </Link> </motion.div> )} </motion.div> ) } export default Base;
import { MOCKED_URLS, handlerOverrides } from '@/mocks/handlers'; import { server } from '@/mocks/server'; import { modelToJsonApi } from '@datx/jsonapi'; import { flightsFactory } from '__mocks__/factories'; import { axe } from 'jest-axe'; import { HttpResponse, http } from 'msw'; import { render, screen, waitForElementToBeRemoved } from 'test-utils'; import { Flights } from './Flights'; describe('Flights', () => { beforeEach(() => { server.use(handlerOverrides.activeCurrentSession); }); it('should be accessible', async () => { server.use(http.get(MOCKED_URLS.Flights, () => HttpResponse.json({ data: [] }, { status: 200 }))); const { container } = render(<Flights />); await waitForElementToBeRemoved(() => screen.queryByText('Loading...')); const results = await axe(container); expect(results).toHaveNoViolations(); }); it('should render loading state', () => { server.use( http.get(MOCKED_URLS.Flights, () => { // @ts-expect-error fix typing in @datx/test-data-factory return HttpResponse.json(flightsFactory(5, { map: modelToJsonApi }), { status: 200 }); }) ); render(<Flights />); expect(screen.getByText('Loading...')).toBeInTheDocument(); }); it('should render error state', async () => { server.use(http.get(MOCKED_URLS.Flights, () => HttpResponse.json({ error: 'Error' }, { status: 404 }))); render(<Flights />); await waitForElementToBeRemoved(() => screen.queryByText('Loading...')); expect(screen.getByText('error')).toBeInTheDocument(); }); it('should render 10 flights', async () => { const flightName = 'Air Force One'; server.use( http.get(MOCKED_URLS.Flights, () => { // @ts-expect-error fix typing in @datx/test-data-factory const data = flightsFactory(10, { map: modelToJsonApi, overrides: { name: flightName } }); return HttpResponse.json({ data }, { status: 200 }); }) ); render(<Flights />); await waitForElementToBeRemoved(() => screen.queryByText('Loading...')); expect(screen.getAllByRole('heading', { name: flightName })).toHaveLength(10); }); });
import React from 'react'; import Stack from '@mui/material/Stack'; import Tooltip from '@mui/material/Tooltip'; import Typography from '@mui/material/Typography'; import Box from '@mui/material/Box'; import IconButton from '@mui/material/IconButton'; import _round from 'lodash/round'; import { styled, useTheme } from '@mui/material/styles'; import Iconify from 'src/components/iconify'; import ProductCounterField from 'src/components/product-counter-field'; import ProductPrices from 'src/components/product-prices'; import useCheckout from 'src/hooks/use-checkout'; import { ICheckoutProduct } from 'src/context/checkout-context'; import Image from 'src/components/image'; import { useResponsive } from 'src/hooks/use-responsive'; interface Props { product: ICheckoutProduct; readOnly?: boolean; } const ImagePreview: any = styled(Image)({ height: '90px', width: '78px', minWidth: '78px', overflow: 'unset', '& > span': { height: { xs: '105px !important', sm: '100%' }, width: { xs: '78px !important', sm: '100%' }, }, }); export default ({ product, readOnly = false }: Props) => { const theme = useTheme(); const smUp = useResponsive('up', 'sm'); const { removeProduct } = useCheckout(); const onRemoveProductClick = () => removeProduct(product.productId, product.size); return ( <Stack direction='row' spacing={2} sx={{ p: 2, '& + &': { borderTop: `1px solid ${theme.palette.divider}` } }} > <ImagePreview disabledEffect src={product.imageSrc} /> <Stack direction='column' sx={{ width: { xs: 'calc(100vw - 48px - 78px)', md: 'calc(100% - 16px - 78px)', }, position: 'relative', }} spacing={1}> <Stack direction='row' justifyContent='space-between' alignItems='flex-start' spacing={1}> <Tooltip title={product.title}> <Typography sx={{ typography: 'body2', width: readOnly ? 'calc(100% - 8px)' : 'calc(100% - 36px - 8px)', fontWeight: 'bold', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', }}>{product.title}</Typography> </Tooltip> {!readOnly && ( <Box sx={{ position: 'absolute', top: '-5px', right: '1px' }}> <Tooltip title='Видалити товар'> <IconButton color='primary' onClick={onRemoveProductClick}> <Iconify icon='material-symbols:close' /> </IconButton> </Tooltip> </Box> )} </Stack> <Stack direction='row' spacing={1}> <Typography variant='body2'>Розмір:</Typography> <Typography variant='subtitle2' sx={{ fontWeight: 'bold' }}>{product.size}</Typography> </Stack> <Stack direction={smUp ? 'row' : 'column'} alignItems="flex-start" justifyContent='space-between' spacing={1}> <ProductCounterField type='checkout' productId={product.productId} productSize={product.size} quantity={product.quantity} readOnly={readOnly} /> <ProductPrices size='small' oldPrice={_round(product.quantity * product.oldPrice, 2)} price={_round(product.quantity * product.price, 2)} /> </Stack> </Stack> </Stack> ); };
package com.indy8.petplanner.clients; import com.indy8.petplanner.config.ClientMapper; import com.indy8.petplanner.dataaccess.ClientRepository; import com.indy8.petplanner.domain.Client; import jakarta.websocket.server.PathParam; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import java.util.ArrayList; import java.util.List; @RestController public class ClientsController { private final ClientRepository clientRepository; private final ClientMapper clientMapper; public ClientsController(ClientRepository clientRepository, ClientMapper clientMapper) { this.clientRepository = clientRepository; this.clientMapper = clientMapper; } @GetMapping("/client") public List<ClientByIdResponse> getAllClients() { var dbResult = clientRepository.findAll(); var response = new ArrayList<ClientByIdResponse>(); for(var client : dbResult) { response.add(this.clientMapper.mapClientToClientByIdResponse(client)); } return response; } @GetMapping("/client/{id}") public ClientByIdResponse getClientById(@PathVariable Integer id) { var dbResult = clientRepository.findById(id); if(dbResult.isEmpty()) { throw new ResponseStatusException( HttpStatus.NOT_FOUND, "client not found" ); } return this.clientMapper.mapClientToClientByIdResponse(dbResult.get()); } @PostMapping("/client") public CreateNewClientResponse createNewClient(@RequestBody CreateNewClientRequest createNewClientRequest) { var client = this.clientMapper.mapCreateNewClientRequestToClient(createNewClientRequest); clientRepository.save(client); return this.clientMapper.mapClientToCreateNewClientResponse(client); } @PutMapping("/client/{id}") public UpdateClientResponse updateClient(@RequestBody UpdateClientRequest updateClientRequest, @PathVariable Integer id) { var dbResult = clientRepository.findById(id); if(dbResult.isEmpty()) { throw new ResponseStatusException( HttpStatus.NOT_FOUND, "client not found" ); } var client = dbResult.get(); updateClient(updateClientRequest, client); clientRepository.save(client); return this.clientMapper.mapClientToUpdateClientResponse(client); } private static void updateClient(UpdateClientRequest updateClientRequest, Client client) { client.setFirstName(updateClientRequest.getFirstName()); client.setLastName(updateClientRequest.getLastName()); client.setPhoneNumber(Long.parseLong(updateClientRequest.getPhoneNumber())); client.setEmail(updateClientRequest.getEmail()); client.setAddress(updateClientRequest.getAddress()); client.setCity(updateClientRequest.getCity()); client.setState(updateClientRequest.getState()); client.setZip(Integer.parseInt(updateClientRequest.getZip())); } @DeleteMapping("/client/{id}") public ResponseEntity<String> deleteClient(@PathVariable Integer id) { var dbResult = clientRepository.findById(id); if(dbResult.isEmpty()) { throw new ResponseStatusException( HttpStatus.NOT_FOUND, "client not found" ); } clientRepository.delete(dbResult.get()); return new ResponseEntity<>("client deleted", HttpStatus.OK); } }
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Abstract class for the link transformations plugins * * @package PhpMyAdmin-Transformations * @subpackage Link */ if (! defined('PHPMYADMIN')) { exit; } /* Get the transformations interface */ require_once 'libraries/plugins/TransformationsPlugin.class.php'; /* For PMA_Transformation_globalHtmlReplace */ require_once 'libraries/transformations.lib.php'; /** * Provides common methods for all of the link transformations plugins. * * @package PhpMyAdmin */ abstract class ImageLinkTransformationsPlugin extends TransformationsPlugin { /** * Gets the transformation description of the specific plugin * * @return string */ public static function getInfo() { return __( 'Displays a link to download this image.' ); } /** * Does the actual work of each specific transformations plugin. * * @param string $buffer text to be transformed * @param array $options transformation options * @param string $meta meta information * * @return string */ public function applyTransformation($buffer, $options = array(), $meta = '') { // must disable the page loader, see // https://wiki.phpmyadmin.net/pma/Page_loader#Bypassing_the_page_loader $transform_options = array ( 'string' => '<a class="disableAjax"' . ' target="_new" href="transformation_wrapper.php' . $options['wrapper_link'] . '" alt="[__BUFFER__]">[BLOB]</a>' ); return PMA_Transformation_globalHtmlReplace( $buffer, $transform_options ); } /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ /** * Gets the transformation name of the specific plugin * * @return string */ public static function getName() { return "ImageLink"; } } ?>
package ace; import ace.AceMacro; import ace.types.*; import ace.types.AceLangRule; import haxe.Constraints.Function; import haxe.extern.EitherType; /** * Helpers for building syntax highlighter rules easier. * @author YellowAfterlife */ class AceHighlightTools { public static var jsThisAsRule(get, never):AceLangRule; private static inline function get_jsThisAsRule():AceLangRule { return js.Lib.nativeThis; } public static function rule(tk:AceLangRuleTokenInit, rx:String, ?next:AceLangRuleNextInit):AceLangRule { return { token: tk, regex: rx, next: next }; } public static function rtk(type:String, value:String):AceToken { return { type: type, value: value }; } public static function rdef(tk:Dynamic):AceLangRule { return cast { defaultToken: tk }; } public static function rpush(tk:Dynamic, rx:String, push:AceLangRuleNextInit):AceLangRule { return { token: tk, regex: rx, push: push }; } public static function rmatch(mt:AceLangRuleMatch, rx:String, ?next:AceLangRuleNextInit):AceLangRule { return { onMatch: mt, regex: rx, next: next }; } /** * ["a", "t1", "b", "t2"] -> { token: ["t1","t2"], regex: "(a)(b)" } */ public static function rulePairs(pairs_rx_tk:Array<String>, ?next:String):AceLangRule { var rs = ""; var i = 0; var tokens = []; while (i < pairs_rx_tk.length) { rs += "(" + pairs_rx_tk[i] + ")"; tokens.push(pairs_rx_tk[i + 1]); i += 2; } return { token: tokens, regex: rs, next: next }; } public static function rawRulePairs(pairs_rx_tk:Array<String>, ?next:String):AceLangRule { var rs = ""; var i = 0; var tokens = []; while (i < pairs_rx_tk.length) { rs += pairs_rx_tk[i]; tokens.push(pairs_rx_tk[i + 1]); i += 2; } return { token: tokens, regex: rs, next: next }; } public static function rpushPairs(pairs_rx_tk:Array<String>, push:AceLangRuleNextInit):AceLangRule { var rs = ""; var i = 0; var tokens = []; while (i < pairs_rx_tk.length) { rs += "(" + pairs_rx_tk[i] + ")"; tokens.push(pairs_rx_tk[i + 1]); i += 2; } return { token: tokens, regex: rs, push: push }; } public static function rulePairsExt(rule:HighlightTools_rpairs):AceLangRule { var pairs = rule.pairs; var isRaw = false; if (pairs != null) { AceMacro.jsDelete(rule.pairs); } else { pairs = rule.rawPairs; if (pairs != null) { isRaw = true; AceMacro.jsDelete(rule.rawPairs); } else throw "Why call rulePairsExt without pairs/rawPairs"; } // var tokens = []; var regex = ""; var i = 0, n = pairs.length; while (i < n) { regex += isRaw ? pairs[i] : '(' + pairs[i] + ')'; if (i + 1 < n) tokens.push(pairs[i + 1]); i += 2; } if (rule.onPairMatch != null) { rule.onMatch = function(value:String, currentState:AceLangRuleState, stack:Array<String>, line:String, row:Int):Array<AceToken> { if (!cast value) return []; var values = jsThisAsRule.splitRegex.exec(value); if (value == null) return cast "text"; var tokens = []; var types = jsThisAsRule.tokenArray; for (i in 0 ... types.length) { var val = values[i + 1]; if (val != null) tokens.push(rtk(types[i], val)); } return (cast js.Lib.nativeThis:HighlightTools_rpairs).onPairMatch(tokens, currentState, stack, line, row); } rule.tokenArray = tokens; } else rule.token = tokens; rule.regex = regex; return rule; } public static function rpop2(c:AceLangRuleState, st:Array<AceLangRuleState>):AceLangRuleState { st.shift(); st.shift(); return AceMacro.jsOr(st.shift(), "start"); } } typedef HighlightTools_rpairs = { > AceLangRule, ?pairs:Array<String>, ?rawPairs:Array<String>, ?onPairMatch:(tokens:Array<AceToken>, currentState:AceLangRuleState, stack:Array<String>, line:String, row:Int)->Array<AceToken> }
/** \file main.c * \brief Program driver * * Executes commands given via the command line. * * Use `t64fix --help` for builtin help. */ /* t64fix - a small tool to correct T64 tape image files Copyright (C) 2016-2021 Bas Wassink <b.wassink@ziggo.nl> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <stdbool.h> #include "base.h" #include "optparse.h" #include "prg.h" #include "t64types.h" #include "t64.h" /** \brief Quiet mode flag * * If set, no output is sent to stdout, error messages are still sent to stderr. */ static bool quiet = 0; /** \brief Path to fixed file with -o */ static const char *outfile = NULL; /** \brief Extract program file * * This variable is the index of the program file to extract */ static long extract = -1; /** \brief Extract all files */ static bool extract_all = 0; /** \brief T64 archive to create */ static const char *create_file = NULL; /** \brief Command line options */ static const option_decl_t options[] = { { 'q', "quiet", &quiet, OPT_BOOL, "don't output to anything on stdout" }, { 'e', "extract", &extract, OPT_INT, "extract program file" }, { 'o', "output", &outfile, OPT_STR, "write fixed file to <outfile>" }, { 'x', "extract-all", &extract_all, OPT_BOOL, "extract all program files" }, { 'c', "create", &create_file, OPT_STR, "create T64 image from a list of PRG files" }, { 0, NULL, NULL, 0, NULL } }; /** \brief Print help output prologue * * Prints some usage examples on stdout. */ static void help_prologue(void) { printf("Examples:\n\n"); printf(" Inspect t64 file for errors:\n"); printf(" t64fix demos.t64\n"); printf(" Fix t64 file and save as new file:\n"); printf(" t64fix demos.t64 -o demos-fixed.t64\n"); printf(" Extract all files as .PRG files:\n"); printf(" t64fix -x demos.t64\n"); printf(" Extract a single .PRG file at index 2:\n"); printf(" t64fix -e 2 demos.t64\n"); printf(" Create t64 file:\n"); printf(" t64fix -c awesome.t64 rasterblast.prg freezer.prg\n"); } /** \brief Print error message on stderr * * If an error of T64_ERR_IO occured, the C library's errno and strerror() is * printed as well. */ static void print_error(void) { fprintf(stderr, "t64fix: error %d: %s", t64_errno, t64_strerror(t64_errno)); if (t64_errno == T64_ERR_IO) { fprintf(stderr, " (%d: %s)\n", errno, strerror(errno)); } else { putchar('\n'); } } /** \brief Open image and print error on stderr * * Open a t64 image and print an error message on stderr on failure. * * \param[in] path path to t64 file * * \return t64 image or `NULL` on failure */ static t64_image_t *open_image_wrapper(const char *path) { t64_image_t *image = t64_open(path, quiet); if (image == NULL) { print_error(); } return image; } /** \brief Create t64 file and write .PRG file(s) to it * * \param[in] args list of .PRG files * \param[in] nargs number of .PRG files in \a args * * \return bool */ static bool cmd_create(const char **args, int nargs) { t64_image_t *image; if (nargs < 1) { fprintf(stderr, "t64fix: error: `--create` requested but no input file(s) " "given.\n"); return false; } image = t64_create(create_file, args, nargs, quiet); if (image != NULL) { if (!t64_write(image, create_file)) { fprintf(stderr, "t64fix: error: failed to write image '%s'\n", create_file); print_error(); t64_free(image); return false; } t64_free(image); } else { fprintf(stderr, "t64fix: error: failed to create image.\n"); print_error(); return false; } return true; } /** \brief Verify t64 file, optionally write fixed file * * Verify t64 file and write fixed file to host when `--outfile` was used. * * \param[in] path path to t64 file * * \return true if image OK, false if not OK or when an I/O error occurred */ static bool cmd_verify(const char *path) { t64_image_t *image; bool status = false; /* open image */ image = open_image_wrapper(path); if (image != NULL) { /* verify image */ status = t64_verify(image, quiet); if (!quiet) { t64_dump(image); } /* write image to host? */ if (outfile != NULL) { if (!t64_write(image, outfile)) { status = false; if (!quiet) { print_error(); } } } t64_free(image); } return status; } /** \brief Extract a single file from a t64 file * * \param[in] path path to t64 file * * \return bool */ static bool cmd_extract_indexed(const char *path) { t64_image_t *image; bool status = false; /* attempt to extract file from image */ image = open_image_wrapper(path); if (image != NULL) { /* fix the image quietly so `real_end_addr` is properly set */ t64_verify(image, true); status = prg_extract(image, (int)extract, quiet); if (!status) { print_error(); } t64_free(image); } return status; } /** \brief Extract all .PRG files from a t64 file * * \param[in] path path to t64 file * * \return bool */ static bool cmd_extract_all(const char *path) { t64_image_t *image; bool status = false; image = open_image_wrapper(path); if (image != NULL) { /* fix the image quietly so `real_end_addr` is properly set */ t64_verify(image, true); status = prg_extract_all(image, quiet); t64_free(image); } return status; } /** \brief Program driver * * \param[in] argc argument count * \param[in] argv argument vector * * \return EXIT_SUCCESS or EXIT_FAILURE */ int main(int argc, char *argv[]) { const char **args; int result; /* optparse result */ bool status; /* command status */ optparse_init(options, "t64fix", VERSION); optparse_set_prologue(help_prologue); if (argc < 2) { /* display help and exit */ optparse_help(); optparse_exit(); return EXIT_FAILURE; } /* parse command line options */ result = optparse_exec(argc, argv); base_debug("optparse_exec() = %d\n", result); if (result == OPT_EXIT_ERROR) { optparse_exit(); return EXIT_FAILURE; } else if (result < 0) { /* --help or --version */ optparse_exit(); return EXIT_SUCCESS; } else if (result == 0) { fprintf(stderr, "t64fix: no input or output file(s) given, aborting\n"); optparse_exit(); return EXIT_FAILURE; } /* get list of non-option command line args */ args = optparse_args(); base_debug("args[0] = '%s'\n", args[0]); /* handle commands: */ if (create_file != NULL) { /* --create <outfile> <prg-files> */ status = cmd_create(args, result); } else if (extract >= 0) { /* --extract <index> */ status = cmd_extract_indexed(args[0]); } else if (extract_all) { /* --extract-all */ status = cmd_extract_all(args[0]); } else { /* assume verify */ status = cmd_verify(args[0]); } /* clean up */ optparse_exit(); return status ? EXIT_SUCCESS : EXIT_FAILURE; }
#!/usr/bin/python import argparse import os import torch import torch.optim as optim import torch.nn as nn from torch.autograd import Variable import torchvision import torchvision.datasets as datasets import torchvision.transforms as transforms from tensorboard_logger import configure, log_value from models import Generator, Discriminator, FeatureExtractor from utils import Visualizer parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, default='cifar100', help='cifar10 | cifar100 | folder') parser.add_argument('--dataroot', type=str, default='./data', help='path to dataset') parser.add_argument('--workers', type=int, default=2, help='number of data loading workers') parser.add_argument('--batchSize', type=int, default=16, help='input batch size') parser.add_argument('--imageSize', type=int, default=15, help='the low resolution image size') parser.add_argument('--upSampling', type=int, default=2, help='low to high resolution scaling factor') parser.add_argument('--nEpochs', type=int, default=100, help='number of epochs to train for') parser.add_argument('--lrG', type=float, default=0.00001, help='learning rate for generator') parser.add_argument('--lrD', type=float, default=0.0000001, help='learning rate for discriminator') parser.add_argument('--cuda', action='store_true', help='enables cuda') parser.add_argument('--nGPU', type=int, default=1, help='number of GPUs to use') parser.add_argument('--netG', type=str, default='', help="path to netG (to continue training)") parser.add_argument('--netD', type=str, default='', help="path to netD (to continue training)") parser.add_argument('--out', type=str, default='checkpoints', help='folder to output model checkpoints') opt = parser.parse_args() print(opt) try: os.makedirs(opt.out) except OSError: pass if torch.cuda.is_available() and not opt.cuda: print("WARNING: You have a CUDA device, so you should probably run with --cuda") transform = transforms.Compose([transforms.RandomCrop(opt.imageSize*opt.upSampling), transforms.ToTensor()]) normalize = transforms.Normalize(mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225]) scale = transforms.Compose([transforms.ToPILImage(), transforms.Scale(opt.imageSize), transforms.ToTensor(), transforms.Normalize(mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225]) ]) if opt.dataset == 'folder': # folder dataset dataset = datasets.ImageFolder(root=opt.dataroot, transform=transform) elif opt.dataset == 'cifar10': dataset = datasets.CIFAR10(root=opt.dataroot, download=True, transform=transform) elif opt.dataset == 'cifar100': dataset = datasets.CIFAR100(root=opt.dataroot, download=True, transform=transform) assert dataset dataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batchSize, shuffle=True, num_workers=int(opt.workers)) netG = Generator(6, opt.upSampling) #netG.apply(weights_init) if opt.netG != '': netG.load_state_dict(torch.load(opt.netG)) print netG netD = Discriminator() #netD.apply(weights_init) if opt.netD != '': netD.load_state_dict(torch.load(opt.netD)) print netD # For the content loss feature_extractor = FeatureExtractor(torchvision.models.vgg19(pretrained=True)) print feature_extractor content_criterion = nn.MSELoss() adversarial_criterion = nn.BCELoss() target_real = Variable(torch.ones(opt.batchSize,1)) target_fake = Variable(torch.zeros(opt.batchSize,1)) # if gpu is to be used if opt.cuda: netG.cuda() netD.cuda() feature_extractor.cuda() content_criterion.cuda() adversarial_criterion.cuda() target_real = target_real.cuda() target_fake = target_fake.cuda() optimG = optim.Adam(netG.parameters(), lr=opt.lrG) optimD = optim.SGD(netD.parameters(), lr=opt.lrD, momentum=0.9, nesterov=True) configure('logs/' + opt.dataset + '-' + str(opt.batchSize) + '-' + str(opt.lrG) + '-' + str(opt.lrD), flush_secs=5) visualizer = Visualizer() inputsG = torch.FloatTensor(opt.batchSize, 3, opt.imageSize, opt.imageSize) # Pre-train generator print 'Generator pre-training' for epoch in range(50): for i, data in enumerate(dataloader): # Generate data inputs, _ = data # Downsample images to low resolution for j in range(opt.batchSize): inputsG[j] = scale(inputs[j]) inputs[j] = normalize(inputs[j]) # Generate real and fake inputs if opt.cuda: inputsD_real = Variable(inputs.cuda()) inputsD_fake = netG(Variable(inputsG).cuda()) else: inputsD_real = Variable(inputs) inputsD_fake = netG(Variable(inputsG)) ######### Train generator ######### netG.zero_grad() lossG_content = content_criterion(inputsD_fake, inputsD_real) lossG_content.backward() # Update generator weights optimG.step() # Status and display print('[%d/%d][%d/%d] Loss_G: %.4f' % (epoch, 50, i, len(dataloader), lossG_content.data[0],)) visualizer.show(inputsG, inputsD_real.cpu().data, inputsD_fake.cpu().data) log_value('G_pixel_loss', lossG_content.data[0], epoch) torch.save(netG.state_dict(), '%s/netG_pretrain_%d.pth' % (opt.out, epoch)) print 'Adversarial training' for epoch in range(opt.nEpochs): for i, data in enumerate(dataloader): # Generate data inputs, _ = data # Downsample images to low resolution for j in range(opt.batchSize): inputsG[j] = scale(inputs[j]) inputs[j] = normalize(inputs[j]) # Generate real and fake inputs if opt.cuda: inputsD_real = Variable(inputs.cuda()) inputsD_fake = netG(Variable(inputsG).cuda()) else: inputsD_real = Variable(inputs) inputsD_fake = netG(Variable(inputsG)) ######### Train discriminator ######### netD.zero_grad() # With real data outputs = netD(inputsD_real) D_real = outputs.data.mean() lossD_real = adversarial_criterion(outputs, target_real) lossD_real.backward() # With fake data outputs = netD(inputsD_fake.detach()) # Don't need to compute gradients wrt weights of netG (for efficiency) D_fake = outputs.data.mean() lossD_fake = adversarial_criterion(outputs, target_fake) lossD_fake.backward() # Update discriminator weights optimD.step() ######### Train generator ######### netG.zero_grad() real_features = Variable(feature_extractor(inputsD_real).data) fake_features = feature_extractor(inputsD_fake) lossG_content = content_criterion(fake_features, real_features) lossG_adversarial = adversarial_criterion(netD(inputsD_fake).detach(), target_real) lossG_total = 0.006*lossG_content + 1e-3*lossG_adversarial lossG_total.backward() # Update generator weights optimG.step() # Status and display print('[%d/%d][%d/%d] Loss_D: %.4f Loss_G (Content/Advers): %.4f/%.4f D(x): %.4f D(G(z)): %.4f' % (epoch, opt.nEpochs, i, len(dataloader), (lossD_real + lossD_fake).data[0], lossG_content.data[0], lossG_adversarial.data[0], D_real, D_fake,)) visualizer.show(inputsG, inputsD_real.cpu().data, inputsD_fake.cpu().data) log_value('G_content_loss', lossG_content.data[0], epoch) log_value('G_advers_loss', lossG_adversarial.data[0], epoch) log_value('D_advers_loss', (lossD_real + lossD_fake).data[0], epoch) # Do checkpointing torch.save(netG.state_dict(), '%s/netG_epoch_%d.pth' % (opt.out, epoch)) torch.save(netD.state_dict(), '%s/netD_epoch_%d.pth' % (opt.out, epoch))
--- description: "Simple Way to Make Tasty PULAO. (FRIED BASMATI RICE). JON STYLE" title: "Simple Way to Make Tasty PULAO. (FRIED BASMATI RICE). JON STYLE" slug: 974-simple-way-to-make-tasty-pulao-fried-basmati-rice-jon-style date: 2022-02-07T14:21:20.735Z image: https://img-global.cpcdn.com/recipes/c466fec2e606c30f/680x482cq70/pulao-fried-basmati-rice-jon-style-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/c466fec2e606c30f/680x482cq70/pulao-fried-basmati-rice-jon-style-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/c466fec2e606c30f/680x482cq70/pulao-fried-basmati-rice-jon-style-recipe-main-photo.jpg author: Ola Cook ratingvalue: 4.6 reviewcount: 49490 recipeingredient: - "1 cup basmati rice" - "1 tbsp. Clarified butter or vegetable oil" - "1 minced garlic clove" - "1 tsp. Minced ginger" - "1 tsp. Cardamon seeds" - "1 and 34 cups boiling water" - "1/4 tsp. Salt or to your own taste" - "1 medium size yellow onion cut in rings" recipeinstructions: - "Place the basmati rice in a bowl and wash it with cold water. The water will be cloudy because the starch will come out, pour off the water. Repeat 2 more times and strain it." - "Heat up a sauce pan with batter or oil and fry the ginger, garlic and cardamon together. Add rice and fry for about 6 minutes." - "Add boiling water, salt and cook at low flame for 18 minutes." - "In the mean time, heat an skillet with 1 tablespoon butter and brown the onions, season it with a bit salt." - "Once the rice is cook serve it immediately with brown onions on top. https://youtu.be/iKsbZQEGv0Y" categories: - Recipe tags: - pulao - fried - basmati katakunci: pulao fried basmati nutrition: 172 calories recipecuisine: American preptime: "PT34M" cooktime: "PT55M" recipeyield: "1" recipecategory: Lunch --- ![PULAO. (FRIED BASMATI RICE). JON STYLE](https://img-global.cpcdn.com/recipes/c466fec2e606c30f/680x482cq70/pulao-fried-basmati-rice-jon-style-recipe-main-photo.jpg) Hello everybody, hope you are having an amazing day today. Today, I will show you a way to make a distinctive dish, pulao. (fried basmati rice). jon style. One of my favorites. For mine, I am going to make it a little bit unique. This will be really delicious. PULAO. (FRIED BASMATI RICE). JON STYLE is one of the most well liked of current trending meals in the world. It's appreciated by millions every day. It is easy, it is fast, it tastes yummy. PULAO. (FRIED BASMATI RICE). JON STYLE is something which I have loved my entire life. They're fine and they look fantastic. To get started with this recipe, we must first prepare a few ingredients. You can cook pulao. (fried basmati rice). jon style using 8 ingredients and 5 steps. Here is how you cook it. <!--inarticleads1--> ##### The ingredients needed to make PULAO. (FRIED BASMATI RICE). JON STYLE: 1. Make ready 1 cup basmati rice 1. Prepare 1 tbsp. Clarified butter or vegetable oil 1. Get 1 minced garlic clove 1. Prepare 1 tsp. Minced ginger 1. Prepare 1 tsp. Cardamon seeds 1. Take 1 and 3/4 cups boiling water 1. Make ready 1/4 tsp. Salt or to your own taste 1. Get 1 medium size yellow onion, cut in rings <!--inarticleads2--> ##### Instructions to make PULAO. (FRIED BASMATI RICE). JON STYLE: 1. Place the basmati rice in a bowl and wash it with cold water. The water will be cloudy because the starch will come out, pour off the water. Repeat 2 more times and strain it. 1. Heat up a sauce pan with batter or oil and fry the ginger, garlic and cardamon together. - Add rice and fry for about 6 minutes. 1. Add boiling water, salt and cook at low flame for 18 minutes. 1. In the mean time, heat an skillet with 1 tablespoon butter and brown the onions, season it with a bit salt. 1. Once the rice is cook serve it immediately with brown onions on top. - https://youtu.be/iKsbZQEGv0Y So that's going to wrap this up with this special food pulao. (fried basmati rice). jon style recipe. Thank you very much for your time. I am confident that you will make this at home. There is gonna be more interesting food at home recipes coming up. Don't forget to save this page in your browser, and share it to your family, colleague and friends. Thanks again for reading. Go on get cooking!
// Project identifier: 43DE0E0C4C76BFAA6D8C2F5AEAE0518A9C42CF4E #ifndef SORTEDPQ_H #define SORTEDPQ_H #include <algorithm> #include <iostream> #include <utility> #include "Eecs281PQ.h" // A specialized version of the priority queue ADT that is implemented with an // underlying sorted array-based container. // Note: The most extreme element should be found at the end of the // 'data' container, such that traversing the iterators yields the elements in // sorted order. template <typename TYPE, typename COMP_FUNCTOR = std::less<TYPE>> class SortedPQ : public Eecs281PQ<TYPE, COMP_FUNCTOR> { // This is a way to refer to the base class object. using BaseClass = Eecs281PQ<TYPE, COMP_FUNCTOR>; public: // Description: Construct an empty PQ with an optional comparison functor. // Runtime: O(1) explicit SortedPQ(COMP_FUNCTOR comp = COMP_FUNCTOR()) : BaseClass{comp} { // TODO: Implement this function, or verify that it is already done } // SortedPQ // Description: Construct a PQ out of an iterator range with an optional // comparison functor. // Runtime: O(n log n) where n is number of elements in range. template <typename InputIterator> SortedPQ(InputIterator start, InputIterator end, COMP_FUNCTOR comp = COMP_FUNCTOR()) : BaseClass{comp}, data(start, end) { // TODO: Implement this function updatePriorities(); } // SortedPQ // Description: Destructor doesn't need any code, the data vector will // be destroyed automatically. virtual ~SortedPQ() { } // ~SortedPQ() // Description: Add a new element to the PQ. // Runtime: O(n) virtual void push(const TYPE& val) { // TODO: Implement this function auto it = std::upper_bound(data.begin(), data.end(), val, this->compare); data.insert(it, val); } // push() // Description: Remove the most extreme (defined by 'compare') element from // the PQ. // Note: We will not run tests on your code that would require it to pop an // element when the PQ is empty. Though you are welcome to if you are // familiar with them, you do not need to use exceptions in this project. // Runtime: Amortized O(1) virtual void pop() { // TODO: Implement this function data.pop_back(); } // pop() // Description: Return the most extreme (defined by 'compare') element of // the vector. This should be a reference for speed. It MUST // be const because we cannot allow it to be modified, as that // might make it no longer be the most extreme element. // Runtime: O(1) virtual const TYPE& top() const { // TODO: Implement this function // These lines are present only so that this provided file compiles. return data.back(); } // top() // Description: Get the number of elements in the PQ. // This has been implemented for you. // Runtime: O(1) virtual std::size_t size() const { return data.size(); } // size() // Description: Return true if the PQ is empty. // This has been implemented for you. // Runtime: O(1) virtual bool empty() const { return data.empty(); } // empty() // Description: Assumes that all elements inside the PQ are out of order and // 'rebuilds' the PQ by fixing the PQ invariant. // Runtime: O(n log n) virtual void updatePriorities() { // TODO: Implement this function std::sort(data.begin(), data.end(), this->compare); } // updatePriorities() private: // Note: This vector *must* be used for your PQ implementation. std::vector<TYPE> data; // TODO: Add any additional member functions you require here. // You are NOT allowed to add any new member variables. }; // SortedPQ #endif // SORTEDPQ_H
import React from "react"; import "./Navbar.css"; import { Link } from "react-router-dom"; import { useLogout } from "../../hooks/useLogout"; import { useAuthContext } from "../../hooks/useAuthContext"; import topshelfLogo from "../../assets/topshelfLogo.png"; import BrowseDropdown from "./BrowseDropdown"; function Navbar() { const [dropdownVisible, setDropdownVisible] = React.useState(false); const [showBrowseDropdown, setShowBrowseDropdown] = React.useState(false); const [profilePicture, setProfilePicture] = React.useState(topshelfLogo); const { logout } = useLogout(); const { state } = useAuthContext(); const handleLogout = () => { logout(); }; const handleDropdown = () => { setDropdownVisible((prevDropdown) => !prevDropdown); }; const handleBrowseMenu = () => { setShowBrowseDropdown((prevShow) => !prevShow); }; React.useEffect(() => { if (state.user?.avatar) { setProfilePicture(state.user?.avatar + "?" + new Date().getTime()); } else { setProfilePicture(topshelfLogo); } }, [state.user?.avatar]); return ( <> <div className="navbar"> <div className="navbar-wrapper"> <div className="left"> <Link className="link" to="/"> {" "} <img className="logo" src="/images/logo.png" /> </Link> </div> <div className="center"> <input type="text" className="searchBar" placeholder="Search for a card, brand, etc." ></input> </div> <div className="right"> <div className="browse" onClick={handleBrowseMenu}> Browse </div> <Link className="link" to="/auctions"> <img className="navbar__streams" src="images/streaming.png" /> </Link> <div className="sell"> <Link className="link" to="/sell"> Sell </Link> </div> {state.user && ( <> <Link className="cart" to="/cart"> <img className="navbar__cart" src="/images/shoppingCart.png" /> </Link> <div className="notification"> <img className="navbar__notification__bell" src="images/notificationBell.png" /> <span className="notificationNumber">0</span> </div> <div> <div className="profile__cirle" onClick={handleDropdown}> <img className="profile__circle__img" src={profilePicture} /> {dropdownVisible && ( <div className="profile__dropdown__container"> <div>View Channel</div> <div> <Link className="profile" to="/profile"> View Profile </Link> </div> <div>View Channel</div> <div className="dropdown__logout" onClick={handleLogout} > {" "} <span> <i class="bi bi-box-arrow-left"></i> </span> Log Out </div> </div> )} </div> </div> </> )} {!state.user && ( <> <button className="loginButton"> <Link className="link" to="/login"> Log In </Link> </button> <button className="registerButton"> <Link className="link" to="/register"> Register </Link> </button> </> )} </div> </div> </div> {showBrowseDropdown && <BrowseDropdown />} </> ); } export default Navbar;
<template> <div> <v-card class="custom-card-user border-grey"> <v-card-text> <v-row> <v-col md="12" sm="12" lg="12" text-md-left> <div class="row"> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.numero_cedeao"> <p class="info-profil"><span>Numéro CEDEAO : </span>{{detailparrainage.numero_cedeao}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.prenom"> <p class="info-profil"><span>Prénom : </span>{{detailparrainage.prenom}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.nom"> <p class="info-profil"><span>Nom : </span>{{detailparrainage.nom}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.date_naissance"> <p class="info-profil"><span>Date de naissance : </span>{{detailparrainage.date_naissance}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.lieu_naissance"> <p class="info-profil"><span>Lieu de naissance : </span>{{detailparrainage.lieu_naissance}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.lieu_naissance"> <p class="info-profil"><span>Lieu de naissance : </span>{{detailparrainage.lieu_naissance}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.taille"> <p class="info-profil"><span>Taille : </span>{{detailparrainage.taille}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.sexe"> <p class="info-profil"><span>Sexe : </span>{{detailparrainage.sexe}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.numero_electeur"> <p class="info-profil"><span>Numéro d'electeur : </span>{{detailparrainage.numero_electeur}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.centre_vote"> <p class="info-profil"><span>Centre de vote : </span>{{detailparrainage.centre_vote}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.bureau_vote"> <p class="info-profil"><span>Bureau de vote : </span>{{detailparrainage.bureau_vote}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.numero_cin"> <p class="info-profil"><span>CIN : </span>{{detailparrainage.numero_cin}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.telephone"> <p class="info-profil"><span>Téléphone : </span>{{detailparrainage.telephone}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.region"> <p class="info-profil"><span>Région : </span>{{detailparrainage.region}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.departement"> <p class="info-profil"><span>Département : </span>{{detailparrainage.departement}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.commune"> <p class="info-profil"><span>Commune : </span>{{detailparrainage.commune}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.prenom_responsable"> <p class="info-profil"><span>Prénom du responsable : </span>{{detailparrainage.prenom_responsable}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.nom_responsable"> <p class="info-profil"><span>Nom du responsable : </span>{{detailparrainage.nom_responsable}}</p> </div> <div class="col-md-4 my-0 py-0" v-if="detailparrainage.telephone_responsable"> <p class="info-profil"><span>Téléphone du responsable : </span>{{detailparrainage.telephone_responsable}}</p> </div> </div> </v-col> </v-row> </v-card-text> </v-card> </div> </template> <script> import { mapMutations, mapGetters } from 'vuex' export default { mounted: function() { this.getDetail(this.id) }, computed: mapGetters({ detailparrainage:'parrainages/detailparrainage' }), data () { return { id : this.$nuxt._route.params.id, apiUrl : process.env.baseUrl, LigneFinancementInputs:[], } }, methods: { getDetail(id){ this.progress=true this.$msasApi.$get('/parrainages/'+id) .then(async (response) => { this.$store.dispatch('parrainages/getDetail',response.data) }).catch((error) => { this.$toast.error(error?.response?.data?.message).goAway(3000) console.log('Code error ++++++: ', error?.response?.data?.message) }).finally(() => { console.log('Requette envoyé ') }); //console.log('total items++++++++++',this.paginationparrainage) }, submitForm(){ alert('Formulaire soumis') }, retour(){ this.$router.push('/parrainages'); }, findAnneeName (id) { return this.listannees.filter(item => item.id === parseInt(id))[0] }, findMonnaieName (id) { return this.listmonnaies.filter(item => item.id === parseInt(id))[0] }, findDimensionName (id) { return this.listdimensions.filter(item => item.id === parseInt(id))[0] }, findStructureName (id) { return this.liststructures.filter(item => item.id === parseInt(id))[0] }, findTypeStructureName (id) { return this.listsources.filter(item => item.id === parseInt(id))[0] }, findRegionName (id) { return this.listregions.filter(item => item.id === parseInt(id))[0] }, findPilierName (id) { return this.listpiliers.filter(item => item.id === parseInt(id))[0] }, findAxeName (id_pilier,id_axe) { return this.listpiliers.filter(item => item.id === parseInt(id_pilier))[0]?.axes.filter(item => item.id === parseInt(id_axe))[0] }, }, } </script>
import bisect from typing import * class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: self.max_time = max(endTime) self.sorted_start_times = sorted(list(set(startTime))) self.starttime_dict = {} for i in range(len(startTime)): self.starttime_dict[startTime[i]] = self.starttime_dict.get(startTime[i], []) + [(endTime[i], profit[i])] self.memo = {} print(self.starttime_dict) return self.dp(min(startTime)) def dp(self, curr_time): if curr_time >= self.max_time: return 0 elif curr_time in self.memo: return self.memo[curr_time] take_curr_time = float('-inf') if curr_time in self.starttime_dict: for possible_end_time, possible_profit in self.starttime_dict[curr_time]: curr_profit = possible_profit + self.dp(possible_end_time) take_curr_time = max(take_curr_time, curr_profit) next_time = self.get_next_time(curr_time) drop_curr_time = self.dp(next_time) answer = max(take_curr_time, drop_curr_time) self.memo[curr_time] = answer return answer def get_next_time(self, curr_time): temp = bisect.bisect_right(self.sorted_start_times, curr_time) if temp == len(self.sorted_start_times): return float('inf') return self.sorted_start_times[bisect.bisect_right(self.sorted_start_times, curr_time)] startTime = [1,2,3,3] endTime = [3,4,5,6] profit = [50,10,40,70] solution = Solution() print(solution.jobScheduling(startTime, endTime, profit))
import React from 'react'; import { Weather } from '../../types'; const convertToCelsius = (f: string | number) => { return ( ((+f - 32) * .5556).toFixed(1) ); }; type CurrentWeatherProps = { time?: Date; weather?: Weather; }; export default function CurrentWeather(props: CurrentWeatherProps) { if (!props.weather) { return ( <div className='weather-report'> <WeatherItemLoading icon='thermostat' subject='Loading...' /> <WeatherItemLoading icon='water_drop' subject='Loading...' /> <WeatherItemLoading icon='air' subject='Loading...' /> <WeatherItemLoading icon='flag' subject='Loading...' /> {/* <WeatherItemLoading icon='water_drop' subject='Loading...' /> <WeatherItemLoading icon='opacity' subject='Loading...' /> */} <WeatherItemLoading icon='light_mode' subject='Loading...' /> <WeatherItemLoading icon='speed' subject='Loading...' /> <CreditsItem /> </div> ); } let tempFeel; if (props.weather.imperial.temp >= 70) { tempFeel = props.weather.imperial.heatIndex; } else if (props.weather.imperial.temp <= 61) { tempFeel = props.weather.imperial.windChill; } else { tempFeel = props.weather.imperial.temp; } return ( <div className='weather-report'> <WeatherItem icon='thermostat' subject='Temperature' temp={props.weather.imperial.temp || '0'} tempFeel={tempFeel} unit='imperial' /> <WeatherItem subject='Rain Gage' icon='water_drop' rain={props.weather.imperial.precipTotal || '0'} rainRate={props.weather.imperial.percipRate || '0'} unit='imperial' /> <WeatherItem subject='Wind' icon='air' unit='imperial' windGust={props.weather.imperial.windGust || '0'} windSpeed={props.weather.imperial.windSpeed || '0'} /> <WeatherItem subject='Wind Direction' icon='flag' unit='imperial' windDir={props.weather.winddir || 0} /> {/* <WeatherItem subject='Humidity' icon='water_drop' humidity={props.weather.humidity || '0'} unit='imperial' error={ props.weather.humidity === 1 ? 'Hardware malfunction.' : undefined } /> <WeatherItem subject='Dew Point' icon='opacity' dewPoint={props.weather.imperial.dewpt || '0'} unit='imperial' /> */} <WeatherItem subject='UV Index' icon='light_mode' unit='imperial' uv={props.weather.uv || '0'} /> <WeatherItem subject='Air Pressure' icon='speed' pressure={props.weather.imperial.pressure || '0'} unit='imperial' /> <CreditsItem /> </div> ); } const CreditsItem = () => { return ( <div className='credits'> <h2>Website Credits</h2> <span aria-hidden='true' className='material-icons-outlined'> live_help </span> <p> API by <a href={'https://www.wunderground.com/'}>Wunderground</a> </p> <p> Website by <a href={'https://www.becky.dev/'}>Becky Pollard</a> </p> </div> ); }; type WeatherItemLoadingProps = { icon: string; subject: string; }; const WeatherItemLoading = (props: WeatherItemLoadingProps) => { return ( <div className='item'> <h2>{props.subject}</h2> <span aria-hidden='true' className={`material-icons${props.icon !== 'flag' ? '-outlined' : ''}`} > {props.icon} </span> <p>0</p> </div> ); }; type WeatherItemProps = { dewPoint?: number | string; error?: string; humidity?: number | string; icon: string; pressure?: number | string; rain?: number | string; rainRate?: number | string; subject: string; temp?: number | string; tempFeel?: number | string; unit: 'imperial' | 'metric'; uv?: number | string; windGust?: number | string; windSpeed?: number | string; windDir?: number; }; const WeatherItem = (props: WeatherItemProps) => { const windDirection = (dir: number) => { if ((dir > 349 && dir <= 360) || dir <= 11) { //N return 'N'; } else if (dir > 11 && dir <= 34) { //NNE return 'NNE'; } else if (dir > 34 && dir <= 56) { //NE return 'NE'; } else if (dir > 56 && dir <= 79) { //ENE return 'ENE'; } else if (dir > 79 && dir <= 101) { //E return 'E'; } else if (dir > 101 && dir <= 124) { //ESE return 'ESE'; } else if (dir > 124 && dir <= 146) { //SE return 'SE'; } else if (dir > 146 && dir <= 169) { //SSE return 'SSE'; } else if (dir > 169 && dir <= 191) { //S return 'S'; } else if (dir > 191 && dir <= 214) { //SSW return 'SSW'; } else if (dir > 214 && dir <= 236) { //SW return 'SW'; } else if (dir > 236 && dir <= 259) { //WSW return 'WSW'; } else if (dir > 259 && dir <= 281) { //W return 'W'; } else if (dir > 281 && dir <= 304) { //WNW return 'WNW'; } else if (dir > 304 && dir <= 326) { //NW return 'NW'; } else if (dir > 326 && dir <= 349) { //NNW return 'NW'; } return 'ERROR'; }; return ( <div className={props.error ? 'item itemError' : 'item'}> <h2>{props.subject}</h2> <span aria-hidden='true' className={`material-icons${props.icon !== 'flag' ? '-outlined' : ''}`} > {props.icon} </span> {props.temp && props.tempFeel ? ( <> <p>{`${props.temp}°F / ${convertToCelsius(props.temp)}°C`}</p> <p>{`feels like ${props.tempFeel}°F or ${convertToCelsius( props.temp )}°C`}</p> </> ) : null} {props.rain && props.rainRate ? ( <> <p>{`${props.rain} in`}</p> <p> {props.rainRate !== '0' ?? `at a rate of ${props.rainRate} in/hr`} </p> </> ) : null} {props.humidity && !props.error ? <p>{`${props.humidity}%`}</p> : null} {props.windGust && props.windSpeed ? ( <> <p>{`${props.windSpeed} mph`}</p> <p> {props.windSpeed !== '0' ? `with ${props.windGust} mph gusts` : 'No wind'} </p> </> ) : null} {props.windDir ? ( <> <p>{`${windDirection(props.windDir)}`}</p> </> ) : null} {props.pressure ? ( <> <p>{`${props.pressure} in`}</p> </> ) : null} {props.uv ? ( <> <p>{`${props.uv}`}</p> </> ) : null} {props.dewPoint ? ( <> <p>{`${props.dewPoint}°F / ${convertToCelsius(props.dewPoint)}°C`}</p> </> ) : null} {props.error ? <p className='itemErrorText'>{props.error}</p> : null} </div> ); };
<template> <h1>Button示例</h1> <h2>不同样式(props: theme)</h2> <div> <Button>default</Button> <Button theme="button">button</Button> <Button theme="primary">primary</Button> <Button theme="danger">danger</Button> <Button theme="link">link</Button> <Button theme="text">text</Button> </div> <h2>不同大小(props: size)</h2> <div> <Button>默认</Button> <Button size="small">small</Button> <Button size="big">big</Button> </div> <div> <Button theme="primary">默认</Button> <Button theme="primary" size="small">small</Button> <Button theme="primary" size="big">big</Button> </div> <h2>Disabled(props: disabled)</h2> <div> <Button>default</Button> <Button :disabled="true">禁用</Button> <Button :disabled="false">不禁用</Button> </div> <h2>Loading(props: loading)</h2> <div> <Button>default</Button> <Button :loading="true">加载中</Button> <Button :loading="false">加载完成</Button> </div> </template> <script lang="ts"> import Button from '../../lib/Button.vue' export default { name: 'ButtonDemo', components: { Button }, setup () { } } </script> <style lang="scss" scoped> </style>
<template> <a-modal :visible="visible" title="新增格组件" cancelText="取消" okText="提交" @ok="submit" @cancel="cancel" > <a-form ref="formRef" :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol" > <a-form-item label="Primary key" name="id"> <a-input v-model:value ="formState.id" /> </a-form-item> <a-form-item label="名称" name="name"> <a-input v-model:value ="formState.name" /> </a-form-item> <a-form-item label="英文名" name="nameEn"> <a-input v-model:value ="formState.nameEn" /> </a-form-item> <a-form-item label="组件内容" name="content"> <a-input v-model:value ="formState.content" /> </a-form-item> <a-form-item label="工作空间" name="spaceId"> <a-input v-model:value ="formState.spaceId" /> </a-form-item> <a-form-item label="版本号" name="revision"> <a-input v-model:value ="formState.revision" /> </a-form-item> <a-form-item label="排序" name="sort"> <a-input v-model:value ="formState.sort" /> </a-form-item> <a-form-item label="删除表示(0:No,1:Yes)" name="deleted"> <a-input v-model:value ="formState.deleted" /> </a-form-item> <a-form-item label="租户编号" name="tenantId"> <a-input v-model:value ="formState.tenantId" /> </a-form-item> </a-form> </a-modal> </template> <script> import { message } from 'ant-design-vue'; import { edit } from "@/api/module/apitableComponent"; import { defineComponent, reactive, ref, toRaw, watch } from "vue"; export default defineComponent({ props: { visible: { type: Boolean, }, record: { type: Object, } }, emit: ["close"], setup(props, context) { const formRef = ref(); const formState = reactive({}); watch(props, (props) => { formState.id = props.record.id formState.name = props.record.name formState.nameEn = props.record.nameEn formState.content = props.record.content formState.spaceId = props.record.spaceId formState.revision = props.record.revision formState.sort = props.record.sort formState.deleted = props.record.deleted formState.tenantId = props.record.tenantId }) const formRules = { name: [ { required: true, message: '请输入名称', trigger: 'blur'} ], code: [ { required: true, message: '请输入编号', trigger: 'blur'} ] }; const editKey = "add"; const submit = (e) => { message.loading({ content: '提交中...', key: editKey }); formRef.value .validate() .then(() => { edit(toRaw(formState)).then((response)=>{ if(response.success){ message.success({ content: '保存成功', key: editKey, duration: 1 }).then(()=>{ cancel(); }); }else{ message.success({ content: '保存失败', key: editKey, duration: 1 }).then(()=>{ cancel(); }); } }); }) .catch(error => { console.log('error', error); }); }; const cancel = (e) => { formRef.value.resetFields(); context.emit("close", false); }; return { submit, cancel, formRef, formState, formRules, labelCol: { span: 6 }, wrapperCol: { span: 18 }, }; }, }); </script>
package com.dariomartin.kotlinexample.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.dariomartin.kotlinexample.R import com.dariomartin.kotlinexample.domain.model.Forecast import com.dariomartin.kotlinexample.domain.model.ForecastList import com.dariomartin.kotlinexample.utils.ctx import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.item_forecast.view.* /** * Created by megamedia on 24/5/18. */ class ForecastListAdapter(private val weekForecast: ForecastList, private val itemClick: (Forecast) -> Unit) : RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.ctx).inflate(R.layout.item_forecast, parent, false) return ViewHolder(view, itemClick) } override fun getItemCount(): Int = weekForecast.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindForecast(weekForecast[position]) } class ViewHolder(val view: View, private val itemClick: (Forecast)->Unit) : RecyclerView.ViewHolder(view) { fun bindForecast(forecast: Forecast) { with(forecast) { Picasso.with(itemView.context).load(iconUrl).into(itemView.icon) itemView.dateText.text = date itemView.descriptionText.text = description itemView.maxTemperatureText.text = "${high}º" itemView.minTemperatureText.text = "${low}º" itemView.setOnClickListener { itemClick(this) } } } } }
//GLOBAL * { padding: 0; margin: 0; box-sizing: border-box; outline: none; } //COLOR $purple-color: #b61984; $dark-color: #181818; $white-color: #fff; $teacher-list-bg: #dcd1f3; //FONT SIZE $fs-normal: 16px; // FONT-WEIGHT $fw-400: 400; $fw-600: 600; $fw-700: 700; $fw-800: 800; body { position: relative; background-color: $white-color; line-height: 1.8rem; font: { family: 'Montserrat', sans-serif; weight: $fw-400; size: $fs-normal; } } //FONT MIXIN @mixin font-set($size, $weight) { font: { size: $size; weight: $weight; } } //BACKGROUND MIXIN @mixin bg-mixin($image, $position) { position: absolute; display: block; content: ""; width: 100%; height: 100%; top: 0; left: 0; background-repeat: no-repeat; background-size: 100%; background-image: url($image); background-position: $position; } //BUTTON MIXIN @mixin button($height) { display: inline-block; height: $height; line-height: $height; background-color: $purple-color; text-align: center; border-radius: 25px; color: $white-color; font-size: .9rem; border: 1px solid $purple-color; padding: 0 1rem; outline: none; transition: all .5s; &:hover { color: $purple-color; background-color: $white-color; } } //HEADER header { position: absolute; top: 0; left: 0; width: 100%; z-index: 1; transition: all 1s; } // NAVBAR $navbar-height: 90px; nav { transition: height .5s; } .navbar { .navbar-collapse { flex-grow: unset; .navbar-nav { z-index: 2; .nav-item { padding: 0 1rem; } .nav-link { @include font-set(.8rem, $fw-600); } @media (max-width:600px) { background-color: $white-color; } } button { @include button(45px); @media (max-width: 600px) { display: none; } } a { color: $dark-color; text-decoration: none; }; a:hover { color: $purple-color; }; } .socialIcon { @media (max-width: 600px) { display: none; } } } .scrollShow { position: fixed; top: 0; left: 0; z-index: 10; background-color: $white-color; border-bottom: 2px solid rgba(0, 0, 0, .1); display: block; .navbar-brand { visibility: hidden; height: 0; } nav { padding-top: 8px; margin-top: 0; margin: auto; height: 3rem; } } //ABOUT US .aboutus { position: relative; background-image: url(../img/yellow_top_wave_01.png); background-repeat: no-repeat; background-size: 100%; @media (max-width: 600px) { padding-top: 7rem; } @media (min-width: 600px) { padding-top: 5rem; } .aboutInnerLeft { h5 { @include font-set(1.1rem, $fw-600); color: $purple-color; } p { @include font-set(3.5rem, $fw-700); line-height: 3.5rem; } } .aboutInnerRight { img { max-width: 100%; } } } .aboutus::after { @include bg-mixin("../img/Violet_top_left_wave.png", left bottom); z-index: -1; } //TEACHER LIST .teacherlist { position: relative; background-color: $teacher-list-bg; padding-bottom: 15px; .listItem { z-index: 1; } .card { margin-bottom: 2rem; border-radius: 1rem; overflow: hidden; transition: all .5s ease .1s; border: unset; min-height: 362px; .card-title { @include font-set(.75rem, $fw-600); color: $purple-color; text-transform: uppercase; } .card-name { @include font-set(1.4rem, $fw-700); } p { font: { family: "Roboto",Arial,Helvetica,sans-serif; size: .9rem; } line-height: 1.5rem; color: $dark-color; } img { transition: all 1s; } img:hover { transform: scale(105%); } } .card:hover { box-shadow: 0px 0px 15px 10px rgba(0, 0, 0, .1); } } .teacherlist::after { @include bg-mixin("../img/Wave_White_bottom_right_shape_01.png", left bottom); } //FIND COURSE .findcourse { z-index: 1; @mixin inputConfig { width: 100%; border-radius: 25px; border: 1px solid rgba(0, 0, 0, .2); @include font-set(.65rem, $fw-600); padding-left: 25px; } @mixin iConfig { position: absolute; left: 8px; top: 50%; transform: translateY(-50%); display: block; color: $purple-color; font-size: .9rem; } .findLeft { img { max-width: 100%; } } .findRight { .findRightInner { width: 80%; margin: auto; border-radius: 25px; background-color: $white-color; box-shadow: 1px 1px 10px rgba(0, 0, 0, .1); h1 { @include font-set(2rem, $fw-700); text-transform: capitalize; } } .findForm { max-width: 100%; .formItem { flex: 1 0 50%; max-width: 49%; input { @include inputConfig(); } i { @include iConfig(); } } .iconPosition { select { @include inputConfig(); height: 36px; } textarea { @include inputConfig(); max-height: 90px; } i { @include iConfig(); } i:last-of-type { top: 10px; left: 10px; transform: unset; } } div { margin-bottom: 15px; } } button { @include button(48px); text-transform: uppercase; padding: 0 3rem; } } } .findcourse::after { @include bg-mixin("../img/accent_bottom_wave_01.png", left bottom); z-index: -1; } //FOOTER footer { background-image: url(../img/footer_background.jpg); background-repeat: no-repeat; background-size: cover; min-height: 500px; color: $white-color; .footerInner { max-width: 80%; } .footerItem { font-family: "Roboto", Arial, Helvetica, sans-serif; button { @include button(48px); @include font-set(.9rem, $fw-600); text-transform: uppercase; family: 'Montserrat', sans-serif; padding: 0 2rem; background-color: $white-color; color: $purple-color; border: 1px solid $white-color; &:hover { background-color: $purple-color; color: $white-color; } } input { @include font-set(.9rem, $fw-400); text-align: center; border: 1px solid $purple-color; background-color: transparent; border-radius: 25px; color: $white-color; height: 48px; transition: all .5s; &::placeholder { color: $white-color; } &:focus { border-color: $white-color; } } } h2 { @include font-set(1.55rem, $fw-700); } ul { margin: 2rem 0; li { list-style-type: none; line-height: 2rem; @include font-set(.9rem, $fw-400); span { padding-left: .3rem; } } } .footerSocial { a { color: $white-color; margin: 0 .2rem; text-decoration: none; } } .footerQuickLinks { a { color: $white-color; text-decoration: none; border-bottom: 1px solid $purple-color; @include font-set(.9rem, $fw-400); line-height: 2rem; } a:hover { opacity: .8; } } @media (max-width: 600px) { background-position: center; } @media (min-width: 600px) { background-position: center; } }
--- title: Teaching R with Pokémon Go data date: 2018-11-04 slug: r-train-pkmn categories: - rmarkdown - rstudio - tidyverse - videogames --- ![](resources/pkmns.png){fig-alt="A badly hand-drawn image of the Pokémon Caterpie, Clefairy, Geodude, Nidoran, Pikachu, Ponyta and Weedle." width="100%"} ## tl;dr I wrote and delivered a [basic intro](https://matt-dray.github.io/beginner-r-feat-pkmn/) to R and RStudio for some colleagues of mine. ## You teach me and I'll teach you I wrote [in a recent post](https://www.rostrum.blog/2018/09/24/knitting-club/) about [some training materials I wrote for teaching R Markdown](https://matt-dray.github.io/knitting-club/). Now I'm sharing another thing I made: [Beginner R and RStudio Training (featuring Pokémon!)](https://matt-dray.github.io/beginner-r-feat-pkmn/). It's an introduction to R, RStudio, R Projects, directory structure and the tidyverse. It uses [Pokémon Go](http://origin.pokemongo.com/)[^pogo] data that I collected myself.[^draytasets] You can: * [visit the page where the training is hosted](https://matt-dray.github.io/beginner-r-feat-pkmn/) * [look at the source on GitHub](https://github.com/matt-dray/beginner-r-feat-pkmn) * [access a 'follow along' R script prepared by a colleague](https://github.com/matt-dray/beginner-r-feat-pkmn/blob/master/beginner-r-feat-pkmn_follow-along.R) It's pretty rudimentary in content and design but it got the job done. I'm unlikely to update it any time soon. Feel free to use all of it, parts of it, or even [fork it on GitHub and improve it](https://github.com/matt-dray/beginner-r-feat-pkmn). ## Other materials Why didn't I just use materials that are already out there? Well, I find it easier to teach material that I know well and that's particularly true for things I've written myself. Also I couldn't find any Pokémon-themed guides, so it was obviously inevitable. Below are some other training materials to consider. I'm certain some of these will be out of date over time, or better things will emerge, but I'm unlikely to come back and update this post in the meantime. ### Starting with R and RStudio * [Software Carpentry's Programming with R](http://swcarpentry.github.io/r-novice-inflammation/) * [Swirl](http://swirlstats.com/) teaches you R interactively, from within RStudio itself * Further information about R Projects is available from the [RStudio Support pages](https://support.rstudio.com/hc/en-us/articles/200526207-Using-Projects) * [Starting data analysis/wrangling with R: Things I wish I'd been told](http://reganmian.net/blog/2014/10/14/starting-data-analysiswrangling-with-r-things-i-wish-id-been-told/) by Stian Håklev * [Basics of 'tidy' data and the 'tidyverse' of packages](http://rpubs.com/aelhabr/tidyverse-basics) ### Going further * [Data wrangling, exploration, and analysis with R](http://stat545.com/) from STAT 545 at the Uni of British Columbia * [Online learning from RStudio](https://www.rstudio.com/online-learning/): R Programming, Shiny, R Markdown and Data Science * An [exhaustive Quora question](https://www.quora.com/What-are-some-good-resources-for-learning-R-1) with links to resources ### Data Science in R * [An Introduction to Statistical and Data Sciences via R](http://moderndive.com/) by ModernDive * [R for Data Science](http://r4ds.had.co.nz/) and [exercise solutions](https://jrnold.github.io/r4ds-exercise-solutions/) ### Getting help * [RStudio cheat sheets](https://www.rstudio.com/resources/cheatsheets/), including help with {readr}, {dplyr} and {ggplot2} * Often it helps to produce a small [reproducible example](https://www.tidyverse.org/help/#reprex) (a 'reprex') of your code if you run into trouble * [Getting help with R](https://support.rstudio.com/hc/en-us/articles/200552336-Getting-Help-with-R) page of resources from RStudio * Explore questions and answers tagged as `r` on [StackOverflow](https://stackoverflow.com/questions/tagged/r) ## Environment {.appendix} <details><summary>Session info</summary> ```{r sessioninfo, eval=TRUE, echo=FALSE} cat("Last rendered:", format(Sys.time(), usetz = TRUE)); sessionInfo() ``` </details> [^pogo]: Add me as a friend on Pokémon Go. Friend code: `9572 6464 0472`. [^draytasets]: The data are available in [my 'draytasets' GitHub repository](https://github.com/matt-dray/draytasets) and in [the `pkmn_go` function in my {dray} package](https://matt-dray.github.io/dray/).
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } #root { width: 100vw; height: 100vh; background-color: #333; } #root>header { width: 100vw; height: 10vh; background-color: coral; display: flex; justify-content: center; align-items: center; } #root>header>ul { list-style-type: none; display: flex; justify-content: center; align-items: center; flex-direction: row; } #root>header>ul>li { width: 100px; height: 30px; cursor: pointer; } #root>header>ul>li:hover { background-color: #ccc; } #root>main { width: 100vw; height: 90vh; background-color: rosybrown; } #root>main>section { position:absolute; width: inherit; height: inherit; visibility: hidden; } /* <!-- ? position:absolute * 임의의 <section> 태그들이 모두 하나로 겹치도록 포지션 값을 부여했다. --> */ #root>main>section:nth-child(1){background-color: aquamarine;} #root>main>section:nth-child(2){background-color: darkgray;} #root>main>section:nth-child(3){background-color: cornflowerblue;} #root>main>section:nth-child(4){background-color: darkslategray;} #root>main>section:nth-child(5){background-color: darkkhaki;} /* <!-- ? section 태그 간의 구분을 위해 임시로 색깔 부여 --> */ </style> </head> <body> <div id="root"> <header> <ul> <li data-hash="page-1">menu-1</li> <li data-hash="page-2">menu-2</li> <li data-hash="page-3">menu-3</li> <li data-hash="page-4">menu-4</li> <li data-hash="page-5">menu-5</li> </ul> </header> <main id="main"> <section data-hash="page-1">section-1</section> <section data-hash="page-2">section-2</section> <section data-hash="page-3">section-3</section> <section data-hash="page-4">section-4</section> <section data-hash="page-5">section-5</section> </main> </div> <!-- ? data-hash * 사용자 정의 속성 노드인 data-*을 활용하여 메뉴부분인 <li> 태그와 페이지 성격인 <section> 두개의 데이터를 쌍(pair)으로 맞추어 * 마크업을 진행했다. * 위와 같은 사례로 작업을 진행하는 경우는 한쪽이 갯수가 맞지 않거나, 한 쌍이 되지 않았을때의 오류가 산재하기 때문에 위와같은 구조로 작업하기보다는 * 일반적으로 하나의 객체 데이터를에서 <li>에 해당하는 데이터 따로, <section>에 해당 하는 데이터 따로 한 뿌리를 놓고 동적으로 만드는 것이 일반적이다. * 정적타입 문서를 조작하는 예시를 든 이유는 실무에서 '정적문서를 다루어야만' 해야 하는 경우가 존재하기 때문이다. * 동적으로 작성 vs 정적문서 데이터 식별 모두 초기 작업만 다르고 'data-*'을 활용했다는 점을 주요 개념으로 확인할 것 --> <script> const root = document.getElementById("root"); // #root const main = document.getElementById("main"); // <main> const menuContainer = document.querySelector('#root > header > ul'); // <ul> for(let i = 0; i < main.children.length; i++) { main.children[i].style.visibility = "hidden"; } // <section> 태그에 해당하는 요소를 모두 visibility = "hidden"; 스타일을 적용했다. // visibility:hidden; vs display:none; // visibility:hidden;는 보이는지 여부 '만' 결정하는 속성으로, 문서에서 요소가 사라지진 않는다. // diplay:none;은 마치 문서에 존재하지 않는 것처럼 완전히 안보이게 하기때문에 레이아웃에서조차 사라진다. menuContainer.addEventListener('click', function (event) { let getHashValue = event.target.dataset.hash; /* <!-- ? conatiner에 이벤트를 설치한 것을 확인 ? event object를 통해 위의 문서에서 마크업 하였던 data-*의 값을 추출 한 것을 확인 * id, hash, src, type, alt, name 기타등등 '식별'이 가능 한 것이라면 무엇이든 가능한 점을 연습할 것 --> */ console.log(getHashValue); for(let i = 0; i < main.children.length; i++) { /* <!-- ? 위의 클릭이벤트는 if문 보다도 먼저 for() 반복문을 실행한 점을 중점적으로 확인 할 것 * click 이벤트가 행사하는 알고리즘은 위의 지역변수로 선언한 getHashValue라는 변수에 특정 값을 대입한 것과 * 반복문을 실행하는것 * 단 두가지만 실행하는 역할을 하며 아래의 for()문 안에 작성되어있는 if()문과는 관련성이 없다. * for() 문을 먼저 실행해야할지 if()문을 먼저실행해야 할지 헷갈리는 부분은 * for() 문이 실행해야 하는 것과 * click이 실행해야 하는 것이 헷갈리기 때문이다. * 각각의 '절차'만 본다면 click event는 if()문과 아무런 관련이 없다. --> */ if(getHashValue === main.children[i].dataset.hash) { main.children[i].style.visibility = "visible"; } else { main.children[i].style.visibility = "hidden"; } /* <!-- ? 모든 <section> 태그를 click 이 발생할때마다 계속 for()문을 통해 순회하는 점을 확인한다. * 이벤트 vs if()을 통한 스타일링 판단 * 이 두가지를 구분 할 것 ? <li> 태그 에 새겨진 date-hash 값과 동일한 <section> 태그만 '보이게' 나머지 는 안보이게 처리가 된다. * 이벤트가 일어날때마다 <section> 태그는 검사를 전체적으로 다시한다. * data-hash의 짝이 맞는 데이터만 보이게 되는 인터렉션을 구현 한다. * 일반 사용자는 페이지 하나에서 '요소 한개만' 보이는 방식이라는 것을 알아차리기 어려우며, 마치 페이지 전환이 된 것처럼 인식하게 된다. * 두번째 특징으로는 '페이지를 최초 로딩' 할때 모든 데이터가 로드(적재) 되었기 때문에, * 페이지를 이동하는 것 과 같은 '연출'에서 새로운 로딩이 발생하지 않는다. 즉 사용자 경험에서 웹사이트가 빠르게 대응 하는 것처럼 느껴진다. * * 이러한 방식을 구체화시키고, 바닐라스크립트(기본형) 작성의 불편함을 간소화 하기 위해 프론트엔드 프레임워크들이 등장했다. * --> */ } }); </script> </body> </html>
import 'package:flutter/material.dart'; class ErrorBox extends StatelessWidget { const ErrorBox({Key? key, this.message}) : super(key: key); final String? message; @override Widget build(BuildContext context) { if (message == null) { return Container(); } else { return Container( decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.all( Radius.circular(8), ), ), padding: EdgeInsets.all(8), child: Row( children: [ Icon( Icons.error_outline, color: Colors.white, size: 40, ), SizedBox( width: 10, ), Expanded( child: Text( 'Oops! $message. Por favor, tente novamente.', textAlign: TextAlign.justify, style: TextStyle( color: Colors.white, fontSize: 14, ), ), ), ], ), ); } } }
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2024/1/4 21:12 # @Author : Laiyong(Archie) Cheng # @Site : # @File : 08_基础时间线柱状图开发.py # @Software: PyCharm from pyecharts.charts import Bar, Timeline from pyecharts.options import LabelOpts from pyecharts.globals import ThemeType # 使用Bar构建基础柱状图 bar1 = Bar() # 添加x轴的数据 bar1.add_xaxis(["中国", "美国", "英国"]) # 添加y轴的数据 bar1.add_yaxis("GDP", [30, 30, 20], label_opts=LabelOpts(position="right")) # 反转xy轴 bar1.reversal_axis() # 使用Bar构建基础柱状图 bar2 = Bar() # 添加x轴的数据 bar2.add_xaxis(["中国", "美国", "英国"]) # 添加y轴的数据 bar2.add_yaxis("GDP", [50, 50, 50], label_opts=LabelOpts(position="right")) # 反转xy轴 bar2.reversal_axis() # 使用Bar构建基础柱状图 bar3 = Bar() # 添加x轴的数据 bar3.add_xaxis(["中国", "美国", "英国"]) # 添加y轴的数据 bar3.add_yaxis("GDP", [70, 70, 60], label_opts=LabelOpts(position="right")) # 反转xy轴 bar3.reversal_axis() # 构建时间线对象 timeline = Timeline( {"theme": ThemeType.LIGHT} ) # 在时间线内添加柱状图对象 timeline.add(bar1, "点1") timeline.add(bar2, "点2") timeline.add(bar3, "点3") # 自动播放设置 timeline.add_schema( play_interval=1000, # 自动播放的时间间隔, 单位毫秒 is_timeline_show=True, # 是否在自动播放的时候,显示时间线 is_auto_play=True, # 是否自动播放 is_loop_play=True # 是否循环自动播放 ) # 绘图是用时间线对象绘图, 而不是 bar 对象了 timeline.render("基础时间线柱状图.html")
/* eslint-disable react/no-unstable-nested-components */ import React from 'react'; import { Collapse } from 'antd'; import { useRouter } from 'next/router'; import classNames from 'classnames'; import AddressCard from 'components/AddressCard'; import Icon, { EIconColor, EIconName } from 'components/Icon'; import Drawer from 'components/Drawer'; import { Paths } from 'routers'; import { TUserNavigationProps } from './UserNavigation.types'; const { Panel } = Collapse; const UserNavigation: React.FC<TUserNavigationProps> = ({ visible, onClose, }) => { const isDrawerStyle = typeof visible === 'boolean'; const router = useRouter(); const dataNavigationOptions = [ { key: 'myAccount', activePaths: [Paths.Profile, Paths.Address, Paths.Password], navTitle: 'HỒ SƠ CÁ NHÂN', title: 'Tài khoản của tôi', icon: EIconName.MapPointShopdi, children: [ { key: 'profile', link: Paths.Profile, activePaths: [Paths.Profile], title: 'Hồ sơ', }, { key: 'address', link: Paths.Address, activePaths: [Paths.Address], title: 'Địa chỉ', }, { key: 'password', link: Paths.Password, activePaths: [Paths.Password], title: 'Đổi mật khẩu', }, ], }, { key: 'shopdiCoin', activePaths: [ Paths.Wallet, Paths.ChargeCoin, Paths.TransferCoin, Paths.ChargeCoinTransferInformation, ], link: Paths.Wallet, navTitle: 'SHOPDI COIN', title: 'Shopdi Xu', icon: EIconName.ShopdiCoin, children: [], }, { key: 'history', activePaths: [Paths.History], link: Paths.History, navTitle: 'LỊCH SỬ MUA HÀNG', title: 'Lịch sử', icon: EIconName.ClockShopdi, children: [], }, { key: 'order', activePaths: [Paths.Orders], link: Paths.Orders, navTitle: 'ĐƠN HÀNG CỦA TÔI', title: 'Đơn hàng', icon: EIconName.OrderShopdi, children: [], }, { key: 'returnManagement', activePaths: [Paths.Return], link: Paths.Return, navTitle: 'QUẢN LÝ ĐỔI TRẢ', title: 'Quản lý đổi trả', icon: EIconName.BoxShopdi, children: [], }, { key: 'notification', activePaths: [Paths.Notifications], link: Paths.Notifications, navTitle: 'THÔNG BÁO', title: 'Thông báo', icon: EIconName.NotificationShopdi, children: [], }, { key: 'review', activePaths: [Paths.Reviews], link: Paths.Reviews, navTitle: 'ĐÁNH GIÁ', title: 'Đánh giá của tôi', icon: EIconName.StarShopdi, children: [], }, { key: 'refer', activePaths: [], navTitle: 'GIỚI THIỆU', title: 'Giới thiệu bạn mới', icon: EIconName.ReferShopdi, children: [], }, ]; const activeOptions = dataNavigationOptions.find((option) => option.activePaths.includes(router.pathname), ); const handleNavigate = (data: any): void => { if (data.link) { router.push(data.link); } }; const renderUserNavigationWrapper = (): React.ReactElement => ( <div className="UserNavigation-wrapper"> <AddressCard headerTitle={activeOptions?.navTitle} radius> <Collapse defaultActiveKey={activeOptions?.key || ''} expandIcon={(): React.ReactElement => ( <Icon name={EIconName.AngleDown} color={EIconColor.EBONY_CLAY} /> )} expandIconPosition="right" > {dataNavigationOptions.map((item) => { const isEmpty = item.children.length === 0; return ( <Panel className={classNames({ 'UserNavigation-empty': isEmpty })} disabled={!item.link && isEmpty} key={item.key} header={ <div className="UserNavigation-header"> <div className={classNames( 'UserNavigation-item d-flex align-items-center', { active: item.activePaths.includes(router.pathname), }, )} onClick={(): void => handleNavigate(item)} > <Icon name={item.icon} /> <span>{item.title}</span> </div> </div> } > {isEmpty ? ( <></> ) : ( <div className="UserNavigation-body"> {item.children.map((subItem) => ( <div className={classNames( 'UserNavigation-item d-flex align-items-center', { active: subItem.activePaths.includes( router.pathname, ), }, )} onClick={(): void => handleNavigate(subItem)} > <span>{subItem.title}</span> </div> ))} </div> )} </Panel> ); })} </Collapse> </AddressCard> </div> ); return isDrawerStyle ? ( <Drawer className="UserNavigation UserNavigationDrawer" visible={visible} onClose={onClose} placement="left" > {renderUserNavigationWrapper()} </Drawer> ) : ( <div className="UserNavigation">{renderUserNavigationWrapper()}</div> ); }; export default UserNavigation;
%../../../../../logics/hlm% [ $~"Natural numbers" = $../Natural/"Natural numbers", $~number = $../Natural/number, $~sum = $../Natural/sum ] /** * @remarks This is essentially the standard definition of integers as equivalence classes of pairs of natural numbers. We just use a notation that highlights the role of the two numbers in each pair. This notation is later justified by `$"Actual difference equals formal difference"`). * * Since an equality definition for each constructor is always part of a construction, we do not need to build the equivalence classes explicitly, they are implicit in the choice of the equality definition. * * When defining a construction, another set can be embedded in the newly defined set, so in this case, we embed the natural numbers. Note that they are also embedded in the cardinal numbers. * * @references * https://en.wikipedia.org/wiki/Integer * * https://mathworld.wolfram.com/Integer.html * * https://proofwiki.org/wiki/Definition:Integer * * https://ncatlab.org/nlab/show/integer * * https://coq.inria.fr/library/Coq.ZArith.BinInt.html (but uses a different encoding as an inductive data type with three constructors) * * https://leanprover-community.github.io/mathlib_docs/init/data/int/basic.html#int (but uses a different encoding as an inductive data type with two constructors) */ $Integers: %Construction { $difference(n,m: %Element($~"Natural numbers")): %Constructor { notation = $Parens( body = $Operator( symbol = $ConstructorName(name = '-'), operands = [n, m], space = '' ), style = '()' ), equalityDefinition = { leftParameters = #(n,m: %Element($~"Natural numbers")), rightParameters = #("n'","m'": %Element($~"Natural numbers")), definition = [%equals( $~sum(m = n, n = "m'"), $~sum(m = "n'", n = m) )] }, rewrite = { value = $difference(a = n, b = m), theorem = $"Actual difference equals formal difference" } } notation = 'ℤ', embedding = { parameter = #(x: %Element($~"Natural numbers")), target = $Integers.difference( n = x, m = $~number(value = 0) ), wellDefinednessProof = { parameters = #( x,y: %Element($~"Natural numbers"), _1: %Constraint(%equals( $Integers.difference( n = x, m = $~number(value = 0) ), $Integers.difference( n = y, m = $~number(value = 0) ) )) ), goal = %equals(x, y), steps = #( _: %Consider(_1), _: %UseDef(result = %equals( $~sum( m = x, n = $~number(value = 0) ), $~sum( m = y, n = $~number(value = 0) ) )), _: %Unfold ) } } }
<template> <div class="space-y-10 divide-y divide-gray-900/10"> <div class="grid grid-cols-1 gap-x-8 gap-y-8 md:grid-cols-3"> <div class="px-4 sm:px-0"> <h2 class="text-base font-semibold leading-7 text-gray-900"> Product Licenses </h2> <p class="mt-1 text-sm leading-6 text-gray-600"> See your license subscriptions, and register for more. Keep an eye on your renewal dates. </p> </div> <div class="bg-white shadow-sm ring-1 ring-gray-900/5 sm:rounded-xl md:col-span-2" > <div class="py-4 text-center"> <div v-if="hasKoorPro && hasKoorTrial"> You have everything. Thanks for being a great customer. </div> <a v-if="!hasKoorTrial" @click="startFreeTrial" class="rounded-md bg-indigo-600 mx-3 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white" >Start Free Trial</a > <a v-if="!hasKoorPro" @click="subscribeToPro" class="rounded-md bg-emerald-500 mx-3 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-emerald-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white" >Subscribe to Pro</a > </div> </div> </div> <div class="py-8"> <ul role="list" class="grid grid-cols-1 gap-x-6 gap-y-8 lg:grid-cols-2"> <li v-for="license in licenses" :key="license.license_key" class="overflow-hidden rounded-xl border border-gray-200" > <div class="flex items-center gap-x-4 border-b border-gray-900/5 bg-gray-50 p-6" > <XMarkIcon v-if="calcStatus(license) === 'Expired'" class="h-12 w-12 text-red-900" aria-hidden="true" /> <CheckBadgeIcon v-else class="h-12 w-12 text-green-900" aria-hidden="true" /> <div class="text-sm font-medium leading-6 text-gray-900"> {{ license.products.name }} </div> </div> <dl class="-my-3 divide-y divide-gray-100 px-6 py-4 text-sm leading-6" > <div class="flex justify-between gap-x-4 py-3"> <dt class="text-gray-500">Description:</dt> <dd class="text-gray-700 text-right"> {{ license.products.description }} </dd> </div> <div class="flex justify-between gap-x-4 py-3"> <dt class="text-gray-500">License Key:</dt> <dd class="text-gray-700 text-right"> {{ license.license_key }} </dd> </div> <div class="flex justify-between gap-x-4 py-3"> <dt class="text-gray-500">Storage Nodes:</dt> <dd class="text-gray-700"> {{ license.nodes }} </dd> </div> <div class="flex justify-between gap-x-4 py-3"> <dt class="text-gray-500">Renewal Date:</dt> <dd class="text-gray-700"> <time :datetime="license.expires_on">{{ license.expires_on }}</time> <div :class="[ statusStyleLookup[calcStatus(license)], 'rounded-md py-1 px-2 text-xs font-medium ring-1 ring-inset', ]" > {{ calcStatus(license) }} </div> </dd> </div> </dl> </li> </ul> </div> </div> </template> <script setup> import { CheckBadgeIcon, XMarkIcon } from '@heroicons/vue/20/solid' const props = defineProps(['customerId']) const nodes = ref(4) const licenses = ref([]) const client = useSupabaseClient() const user = useSupabaseUser() // let { data } = await client // .from('licenses') // .select( // license_key, // nodes, // created_at, // expires_on, // products(name, description, product_key) // ) // .eq('created_by', user.value.id) // FIXME: use calculated to cache const calcStatus = (license) => { if (license) { const now = new Date().getTime() const expiration = new Date(license.expires_on).getTime() console.log('compare dates', now, expiration) if (now <= expiration) { return 'Active' } else { return 'Expired' } } else { return 'no license' } } let { data: licenseData, error } = await client.from('licenses').select(` license_key, nodes, created_at, expires_on, products(name, description, product_key) `) licenses.value = licenseData console.log('licenses', JSON.stringify(licenseData)) const statusStyleLookup = { Active: 'text-green-700 bg-green-50 ring-green-600/20', Expired: 'text-red-700 bg-red-50 ring-red-600/10', } // for reference // const licenses = [ // { // license_key: 'abc123-09876', // nodes: 4, // created_at: '2023-09-07T16:58:08.17586+00:00', // expires_on: '2024-09-07', // products: { // name: 'Koor Trial', // description: 'For running Koor on up to 4 data nodes. Limited support.', // product_key: 'KOOR_TRIAL', // }, // }, // ] const hasKoorTrial = computed(() => { return licenses.value.find( (license) => license.products.product_key === 'KOOR_TRIAL' ) }) const hasKoorPro = computed(() => { return licenses.value.find( (license) => license.products.product_key === 'KOOR_PRO' ) }) const startFreeTrial = async () => { console.log('Starting free trial if not already going') await createLicense('KOOR_TRIAL', 4) } const subscribeToPro = async () => { // FIXME: ask for number of nodes - or let Koor employee update once payment is received console.log('Gather number of nodes, and notify Koor team to follow up') await createLicense('KOOR_PRO', 4) } // FIXME: this should be in a database function, safe from hackers const createLicense = async (productKey, nodes) => { // find customer ID let { data: customer, error2 } = await client .from('customers') .select('id') .eq('created_by', user.value.id) .single() console.log('customer', customer) const customerId = customer.id // find product ID let { data: product, error1 } = await client .from('products') .select('id') .eq('product_key', productKey) .single() console.log('product', product) const productId = product.id const licenseKey = genLicenseKey(20) const expiresOn = new Date() expiresOn.setFullYear(expiresOn.getFullYear() + 1) const { data, error } = await client .from('licenses') .insert([ { customer_id: customerId, product_id: productId, license_key: licenseKey, nodes: nodes, expires_on: expiresOn, created_by: user.value.id, }, ]) .select() } function genLicenseKey(length) { let result = '' const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' const charactersLength = characters.length let counter = 0 while (counter < length) { result += characters.charAt(Math.floor(Math.random() * charactersLength)) counter += 1 } return result } </script>
/* * Copyright 2023 Pieter van den Hombergh {@code <pieter.van.den.hombergh@gmail.com>}. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.homberghp.jsonconverters; import io.github.homberghp.recordmappers.RecordMapper; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static java.util.stream.Collectors.joining; import java.util.stream.IntStream; /** * * @author Pieter van den Hombergh {@code <pieter.van.den.hombergh@gmail.com>} */ public class JSONConverter<R extends Record> { final RecordMapper<R, ?> mapper; private JSONConverter(Class<R> forRecord) { this.mapper = RecordMapper.mapperFor( forRecord ); } private static final ConcurrentMap<Class<? extends Record>, JSONConverter> cache = new ConcurrentHashMap<>(); public static JSONConverter forRecord(Class<? extends Record> forRecord) { return cache.computeIfAbsent( forRecord, JSONConverter::new ); } public String toJSON(R r) { Object[] params = mapper.deconstruct( r ); List<RecordMapper.EditHelper> editHelpers = mapper.editHelpers(); String collect = IntStream.range( 0, editHelpers.size() ) .mapToObj( i -> jsonQuote( editHelpers.get( i ).fieldName(), params[ i ] ) ) .collect( joining( ", " ) ); return "{ " + collect + " }"; } static String jsonQuote(String name, Object value) { boolean dontQuote = null == value || value instanceof Number || value instanceof Boolean; return "\"" + name + "\":" + ( dontQuote ? Objects.toString( value ) : "\"" + Objects.toString( value ) + "\"" ); } public R fromJSON(String json) { Map<String, Object> params = Map.of(); return mapper.construct( params ); } }
""" Created on August 19,2023 @author: Nicolás Peña Mogollón - María Camila Lozano Gutiérrez """ from co.edu.unbosque.model.TreeNode import TreeNode class BinaryTree: def insert(self, root, key): """ Crea un nuevo nodo con el valor dado y lo inserta en el árbol en relación al nodo actual. Si el nodo actual es nulo, se crea un nuevo nodo con el valor y se devuelve. Si el valor es menor que el valor actual del nodo, se llama al método recursivamente para el subárbol izquierdo; de lo contrario, para el subárbol derecho. :param root: raiz del arbol :param key: valor entrnate :return: raiz del arbol ordenado """ if not root: return TreeNode(key) if key < root.val: root.left = self.insert(root.left, key) else: root.right = self.insert(root.right, key) root.height = 1 + max(self.get_height(root.left), self.get_height(root.right)) balance = self.get_balance(root) if balance > 1: if key < root.left.val: return self.rotate_right(root) else: root.left = self.rotate_left(root.left) return self.rotate_right(root) if balance < -1: if key > root.right.val: return self.rotate_left(root) else: root.right = self.rotate_right(root.right) return self.rotate_left(root) return root def get_height(self, root): """ Metodo que calcula la altura del nodo :param root: raiz del arbol :return: nodo y """ if not root: return 0 return root.height def get_balance(self, root): """ Metodo que calcula el factor de balance del arbol :param root: raiz del arbol :return: nodo y """ if not root: return 0 return self.get_height(root.left) - self.get_height(root.right) def rotate_left(self, z): """ Realiza una rotación hacia la izquierda en el árbol con el nodo z como pivote. El nodo Y se convierte en el nuevo nodo raíz del subárbol, Z pasa a ser el hijo izquierdo. El antiguo hijo izquierdo de Y se convierte en el hijo derecho de Z. Se actualizan las alturas de z y y para mostrar los cambios, se devuelve y, que ahora es el nodo raíz del subárbol. :return: nodo y """ if not z: return z # Manejar el caso en que z es None y = z.right if not y: return z # Manejar el caso en que y es None T2 = y.left y.left = z z.right = T2 z.height = 1 + max(self.get_height(z.left), self.get_height(z.right)) y.height = 1 + max(self.get_height(y.left), self.get_height(y.right)) return y def rotate_right(self, y): """ Realiza una rotación hacia la derecha en el árbol con el nodo Y como pivote. El nodo X se convierte en el nuevo nodo raíz del subárbol y Y pasa a ser su hijo derecho. El antiguo hijo derecho de x se convierte en el nuevo hijo izquierdo de y. Luego, se actualizan las alturas de Y y X para mostrar los cambios y devuelver x como nuevo nodo raíz del subárbol. :param y: y """ if not y: return y # Manejar el caso en que y es None x = y.left if not x: return y # Manejar el caso en que x es None T2 = x.right x.right = y y.left = T2 y.height = 1 + max(self.get_height(y.left), self.get_height(y.right)) x.height = 1 + max(self.get_height(x.left), self.get_height(x.right)) return x def in_order_traversal(self, root): """ Realiza un recorrido en orden del árbol y devuelve una lista de valores en orden ascendente. Utiliza una pila para realizar el recorrido, comienza en la raíz y avanza hacia el nodo de la izquierda mientras apila apilandolos. Luego, desapila un nodo, agrega su valor a la lista resultante y se mueve al nodo derecho. :param root: raiz del nodo :return:lista ascendente """ result = [] if root: result += self.in_order_traversal(root.left) result.append(root.val) result += self.in_order_traversal(root.right) return result
//fa riferimento alle risposte della pagina precedente const risposteDate = localStorage.getItem('risposte'); // divide in un array le risposte in stringa const arrayRisposte = risposteDate.split(','); //viariabile globale let ctxGrafico; // costanti HTML let documentRisultatoPositivo = document.querySelector('#correct p'); let documentRisultatoNegativo = document.querySelector('#wrong p'); let documentPercentualePositiva = document.querySelector('#correct h3 span'); let documentPercentualeNegativa = document.querySelector('#wrong h3 span'); let documentGrafico = document.getElementById('graficoCanvas'); let documentScrittaGrafico_h4 = document.querySelector('#scritteGrafico h4') let documentScrittaGrafico_span = document.querySelector('#scritteGrafico_span') let documentScrittaGrafico_p = document.querySelector('#scritteGrafico p') let documentBtn = document.querySelector('.risultato_footer input') //disabilita i tooltips Chart.defaults.global.tooltips.enabled = false; //oggetto per il grafico chart.js let myData = []; let chart = new Chart(documentGrafico, { type: 'doughnut', data: { datasets: [{ data: myData, backgroundColor: ['#d20094', '#00FFFF'], borderWidth: 0, }] }, options: { maintainAspectRatio: false, hover: { mode: null }, animation: { duration: 2000, }, cutoutPercentage: 75, tooltips: { enabled: true, // Abilita i tooltip callbacks: { label: function (tooltipItem, data) { // Ottieni il valore del segmento attuale var value = data.datasets[0].data[tooltipItem.index]; if (tooltipItem.index === 0) { return "Wrong " + value * 100 + '%'; } else { return "Correct " + value * 100 + '%'; } } } } }, }); //visualizza dati delle risposte date divise in sbagliate e giuste (in percentuali) function stampa() { let iPositivo = 0; let iNegativo = 0; //calcola gli indici delle risposte arrayRisposte.forEach(risposta => { if (iPositivo == 0) { documentRisultatoPositivo.innerText = `0/10 questions` } if (risposta === 'true') { iPositivo++; } else { iNegativo++; } }); documentRisultatoPositivo.innerText = `${iPositivo}/${arrayRisposte.length} questions` documentRisultatoNegativo.innerText = `${iNegativo}/${arrayRisposte.length} questions` //transforma il calcolo in percentuale e aggiorna il grafico iPositivo = (iPositivo / arrayRisposte.length) * 100; iNegativo = (iNegativo / arrayRisposte.length) * 100; documentPercentualePositiva.innerText = `${iPositivo}%`; documentPercentualeNegativa.innerText = `${iNegativo}%`; myData = [iNegativo / 100, iPositivo / 100]; chart.data.datasets[0].data = myData; chart.update(); //in base al risultato ottenuto viene inviato l'esito positivo o negativo if (iPositivo >= 60) { documentScrittaGrafico_h4.innerText = 'Congratulations!' documentScrittaGrafico_span.innerText = 'You passed the exam' documentScrittaGrafico_p.innerText = `We'll send you the certificare in few minutes. Check your email (including promotions / spam folder)` const count = 600, defaults = { origin: { y: 0.7 }, }; function fire(particleRatio, opts) { confetti( Object.assign({}, defaults, opts, { particleCount: Math.floor(count * particleRatio), }) ); } fire(0.25, { spread: 26, startVelocity: 55, }); fire(0.2, { spread: 60, }); fire(0.35, { spread: 100, decay: 0.91, scalar: 0.8, }); fire(0.1, { spread: 120, startVelocity: 25, decay: 0.92, scalar: 1.2, }); fire(0.1, { spread: 120, startVelocity: 45, }); } else { documentScrittaGrafico_h4.innerText = 'Oh sorry!' documentScrittaGrafico_span.innerText = 'You failed the exam' documentScrittaGrafico_span.style.color = "#d20094"; documentScrittaGrafico_p.innerText = `The teacher will get in touch with you to understand your mistakes, you will definitely improve in the future.` } } //ottiene canvas function init() { ctxGrafico = documentGrafico.getContext('2d'); stampa(); } //richiama init con l'evento load addEventListener('load', init); //cambio pagina al click dell'utente che porta alla pagina feedback documentBtn.addEventListener('click', function (e) { e.preventDefault; window.location.href = 'risultatoDomande.html'; });
import React, { Component } from 'react' import Loader from '../../Loader/Loader'; // import { Link } from "react-router-dom"; // const image = window.location.origin + "/Assets/no-data.svg"; export class Shippingcost extends Component { constructor() { super(); this.state = { shipping: [], loading: false, weight: "", incity: "", outcity: "", shippingId: "" }; this.modalRef = React.createRef(); this.closeRef = React.createRef(); } host = process.env.REACT_APP_API_URL; async componentDidMount() { let url = `${this.host}/api/shipping/shippingcalc`; this.setState({ loading: true }); let data = await fetch(url); data = await data.json(); this.setState({ loading: false, shipping: data }); } handleEdit = (id) => { this.modalRef.current.click(); let shippingcost = this.state.shipping.find((cost) => cost._id === id); this.setState({ weight: shippingcost.weight, incity: shippingcost.incity, outcity: shippingcost.outcity, shippingId: shippingcost._id }); }; handleSubmit = async () => { const { weight, incity, outcity, shippingId } = this.state; const shippingcalc = { "weight": weight, "incity": incity, "outcity": outcity, } this.setState({ loading: true }); await fetch(`${this.host}/api/shipping/editshippingcalc/${shippingId}`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify(shippingcalc), }); let url = `${this.host}/api/shipping/shippingcalc`; let uProducts = await fetch(url); let pro = await uProducts.json(); this.setState({ shipping: pro, loading: false }); }; onChange = (e) => { this.setState({ [e.target.name]: e.target.value }); } handleDelete = async (id) => { this.setState({ loading: true }); await fetch(`${this.host}/api/shipping/deleteshippingcalc/${id}`, { method: "DELETE", headers: { "Content-Type": "application/json", }, }); let url = `${this.host}/api/shipping/shippingcalc`; let uProducts = await fetch(url); let pro = await uProducts.json(); this.setState({ shipping: pro, loading: false }); } render() { return ( <>{this.state.loading ? <Loader /> : <> <div className="main" id="main"> <div className="container-fluid"> <div className="my-3 d-flex justify-content-center"> <div> <h3 className='text-center'>Shipping Cost</h3> </div> {/* <Link to="/admin/addshippingcost" className="btn btn-sm btn-success ">Add Shipping Cost</Link> */} </div> <table className='table'> <thead> <tr> <th colSpan="1" >Sr.</th> <th colSpan="1" className="text-center">Weight Category(Kg)</th> <th colSpan="1" className="text-center">Intercity</th> <th colSpan="1" className="text-center">Out of city</th> <th colSpan="1" className="text-center">Actions</th> </tr> </thead> <tbody> {this.state.shipping.map((cost) => { return ( <tr key={cost._id}> <td>{this.state.shipping.indexOf(cost) + 1}</td> <td className="text-center">{cost.weight === 'half' ? `0.5 Kg` : cost.weight === 'one' ? `1.0 Kg` : cost.weight === 'greater' ? `Additional Kg` : null}</td> <td className="text-center">{cost.incity}</td> <td className="text-center">{cost.outcity}</td> <td className="text-center align-middle"> <span title="Edit" style={{ cursor: "pointer" }} onClick={() => this.handleEdit(cost._id)}>Edit</span> {/* &nbsp; | &nbsp; */} {/* <span title="Delete" style={{ cursor: "pointer" }} onClick={() => this.handleDelete(cost._id)}>Delete</span> */} </td> </tr> ); })} </tbody> </table> {/* {this.state.shipping.length === 0 && <div className='no_data'> <img className='no_data-img' src={image} alt='No Data' ></img> </div>} */} </div> </div> <button ref={this.modalRef} type="button" className="btn btn-primary d-none" data-bs-toggle="modal" data-bs-target="#exampleModal" > Launch demo modal </button> <div className="modal fade" id="exampleModal" tabIndex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div className="modal-dialog modal-lg"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLabel"> Edit Shipping Cost </h5> <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div className="modal-body"> <form noValidate method="post" className="card py-4 px-4 rounded needs-validation g-3" > <div className="row mb-2"> <div className="form-group col-sm-3"> <label htmlFor="weight">Weight Category</label> <input disabled required type="text" className="form-control" id="weight" name="weight" onChange={this.onChange} value={this.state.weight === "greater" ? "More than 1 kg" : this.state.weight + ' kg'} /> </div> <div className="col-sm-3"> <div className="form-group"> <label htmlFor="incity">Intercity</label> <div className="input-group"> <input required type="number" className="form-control" id="incity" name="incity" onChange={this.onChange} value={this.state.incity} /> </div> </div> </div> <div className="col-sm-3"> <div className="form-group"> <label htmlFor="outofcity">Out of City</label> <div className="input-group"> <input required type="number" min={1} className="form-control" id="outcity" name="outcity" onChange={this.onChange} value={this.state.outcity} /> </div> </div> </div> </div> </form> </div> <div className="modal-footer"> <button className="btn btn-secondary" type="button" data-bs-dismiss="modal" aria-label="Close" > Close </button> <button onClick={() => this.handleSubmit()} type="button" data-bs-dismiss="modal" className="btn btn-primary"> Save changes </button> </div> </div> </div> </div> </> } </>) } } export default Shippingcost
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% if title %} <title>CH Portal-{{ title }}</title> {% else %} <title>CH Portal</title> {% endif %} <link type="text/css" href="{{ url_for('static',filename='CSS/bootstrap.min.css') }}" rel="stylesheet"> <link type="text/css" href="{{ url_for('static',filename='CSS/main.css') }}" rel="stylesheet"> {# <link type="text/css" href="{{ url_for('static',filename='CSS/bootstrap3.4.min.css') }}" rel="stylesheet">#} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel"> <div class="container"> <div class="nav navbar-nav my-sm-auto ms-0"> <a class="navbar-brand my-sm-auto" href="{{ url_for('index') }}"><img class="img-fluid img-thumbnail site-logo-img" src="{{ url_for('static',filename='logo/CH.png') }}" alt="mdo"></a> </div> <button class="navbar-toggler me-0" type="button" data-bs-toggle="collapse" data-bs-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav me-auto me-0"> <a class="nav-pills nav-link" href="{{ url_for('index') }}">主页</a> <a class="nav-pills nav-link" href="/">相册</a> <a class="nav-pills nav-link" href="{{ url_for('about') }}">关于</a> <a class="nav-pills nav-link" href="{{ url_for('users') }}">用户</a> </div> <!-- Navbar Right Side --> <div class="nav navbar-nav mr-auto mr-0"> {% if current_user.is_authenticated %} <a class="nav-pills nav-link" href="{{ url_for('account') }}">欢迎【{{ current_user.username }}】<img class='rounded-circle' src="{{ url_for('static',filename='icon/'+current_user.image_file) }}" alt="mdo" width="20" height="20" class="rounded-circle"></a> <a class="nav-pills nav-link" href="{{ url_for('logout') }}">登出</a> <a class="nav-pills nav-link" href="{{ url_for('new_post') }}">我要发帖</a> {% else %} <a class="nav-pills nav-link" href="{{ url_for('login') }}">登录</a> <a class="nav-pills nav-link" href="{{ url_for('register') }}">注册</a> {% endif %} </div> </div> </div> </nav> </header> <main role="main" class="container"> {#主显示区域#} <div class="row"> <div class="col-md-10"> {# flash message 代码#} {% with messages = get_flashed_messages(with_categories=True) %} {% if messages %} {% for category,message in messages %} <div class="alert alert-{{ category }}"> {{ message }} </div> {% endfor %} {% endif %} {% endwith %} {% block content %}{% endblock %} </div> {% block side_nav %} {% endblock side_nav %} {#以下为侧边栏位#} {# <div class="col-md-2">#} {# <div class="content-section">#} {# <h3>导航栏</h3>#} {# <p class='text-muted'>这里可以写你想要的内容#} {# <ul class="list-group">#} {# <li class="list-group-item list-group-item-light">最新文章</li>#} {# <li class="list-group-item list-group-item-light">公告</li>#} {# <li class="list-group-item list-group-item-light">日历</li>#} {# <li class="list-group-item list-group-item-light">其他</li>#} {# </ul>#} {# </p>#} {# </div>#} {# </div>#} </div> </main> <script src="{{ url_for('static',filename='JS/bootstrap.bundle.js') }}" type="text/javascript"></script> {#<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"#} {# integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r"#} {# crossorigin="anonymous"></script>#} {#<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.min.js"#} {# integrity="sha384-Rx+T1VzGupg4BHQYs2gCW9It+akI2MM/mndMCy36UVfodzcJcF0GGLxZIzObiEfa"#} {# crossorigin="anonymous"></script>#} </body> </html>
from vixengram.internationalization.i18n import ProxyLanguage from routers.common.urls import Urls from vixengram.api import BotAPI from vixengram.filters.command import CommandFilter from vixengram.keyboards.buttons import KeyboardButton from vixengram.keyboards.inline_keyboard import InlineKeyboard from vixengram.routing import Router from vixengram.types.telegram_type import MessageObject router = Router( title="Common router", ) @router.message(CommandFilter(["кто", "who"])) async def who_me(bot: BotAPI, message: MessageObject): string = f"Я думаю, ты - {message.from_.first_name} {message.from_.last_name}, бяка!" await bot.answer(string) @router.message(CommandFilter("start")) async def start(bot: BotAPI, lang: ProxyLanguage): await bot.send_animation(animation_url=Urls.animation_url) await bot.answer(await lang("common.start_text")) @router.message(CommandFilter("help")) async def help_menu(bot: BotAPI, lang: ProxyLanguage): kb = InlineKeyboard() await kb.row(KeyboardButton(await lang("common.open_help_menu"), "help_menu")) await kb.row( KeyboardButton(await lang("common.help_ru"), "lang_to_ru"), KeyboardButton(await lang("common.help_en"), "lang_to_en") ) await bot.answer(text=await lang("common.help_menu"), reply_markup=kb) @router.message(CommandFilter("mediasoft")) async def mediasoft_info(bot: BotAPI, lang: ProxyLanguage): await bot.answer(await lang("common.mediasoft_info"))