text
stringlengths
184
4.48M
#include <iostream> #include <vector> #include <queue> using namespace std; int N, M; vector<int> *A; int *B; void BFS(int n) { bool *visited = new bool[N + 1](); queue<int> q; visited[n] = true; q.push(n); while (!q.empty()) { int temp = q.front(); q.pop(); for (int i : A[temp]) { if (visited[i]) continue; B[i]++; visited[i] = true; q.push(i); } } delete[] visited; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> N >> M; A = new vector<int>[N + 1]; for (int i = 1; i <= N; i++) { A[i] = vector<int>(); } for (int i = 0; i < M; i++) { int s, e; cin >> s >> e; A[s].push_back(e); } B = new int[N + 1](); for (int i = 1; i <= N; i++) { BFS(i); } int max = 0; for (int i = 1; i <= N; i++) { max = std::max(max, B[i]); } for (int i = 1; i <= N; i++) { if (max == B[i]) { cout << i << " "; } } delete[] A; delete[] B; return 0; }
/** * The transform property applies a 2D or 3D transformation to an element. * * @mixin * @section CSS Helpers * @param $arguments accepts any transform css property * @example * @include transform(scale(1,1.5)); */ @mixin transform($arguments) { @include vendor-prefix('transform', $arguments); } /** * Transform-origin. This property allows you to change the position of transformed elements. * * @mixin * @section CSS Helpers * @param $params accepts any transform css property * @example * @include transform-origin(30%, 35%); */ @mixin transform-origin($params) { @include vendor-prefix('transform-origin', $params); } /** * Transform-style. Let the transformed child elements preserve the 3D transformations. * * @mixin * @section CSS Helpers * @param $style accepts 'flat', 'preserve-3d', 'initial', 'inherit' * @example * @include transform-style(flat); */ @mixin transform-style($style: preserve-3d) { @include vendor-prefix('transform-style', $style); }
import { HiOutlineExternalLink } from "react-icons/hi"; import { GiClick } from "react-icons/gi" import { useState } from "react"; function PortfolioCard({project, onPopup}) { const [expandDetails, setExpandDetails] = useState(false) function handleClick(){ onPopup(project) } function handleExpandDetails(){ setExpandDetails(!expandDetails) } const languageList = project.languages.map(language => { return <li key={language}>{language}</li> }) const skillList = project.skills.map(skill => { return <li key={skill}>{skill}</li> }) return ( <div className="relative w-full sm:w-3/4 mx-auto bg-white flex flex-col md:flex-row" > <div className="w-full md:w-4/5 flex items-center justify-center border border-slate-800 p-4 relative" > <img onClick={handleClick} className="link" src={project.image} alt="preview of project"/> <GiClick className="absolute text-slate-800 right-2 bottom-2 md:hidden w-6 h-6" /> </div> <div className={`w-full md:w-1/5 flex flex-col border border-slate-800 translate-all duration-300 transform ${expandDetails ? 'h-auto p-4' : 'max-h-0 md:max-h-screen overflow-hidden p-0 md:p-4'} `}> <div className="h-4/5 flex flex-col gap-y-2 justify-evenly"> <h3>Languages:</h3> <ul className="text-left"> {languageList} </ul> <h3>Skills Acquired:</h3> <ul className="text-left"> {skillList} </ul> </div> <div className="flex items-center md:justify-center h-1/5 w-full mx-auto md:py-6 justify-end mt-2 md:mt-0 md:flex-col"> <a href={project.git} className='link w-full flex items-center hover:bg-tertiary hover:border hover:border-slate-800 group justify-center'> <h4 className=" mx-2 group-hover:text-slate-800">GitHub</h4> <HiOutlineExternalLink className=" group-hover:text-slate-800 w-5 h-5" /> </a> <a href={project.demo} className="link w-full flex items-center hover:bg-tertiary hover:border hover:border-slate-800 group justify-center"> <h4 className=" mx-2 group-hover:text-slate-800 ">Demo</h4> <HiOutlineExternalLink className=" group-hover:text-slate-800 w-5 h-5" /> </a> </div> </div> <h4 onClick={handleExpandDetails} className="absolute md:hidden bottom-0 px-2 bg-white border border-slate-800 right-1/2 translate-y-1/2 translate-x-1/2">Details</h4> </div> ) } export default PortfolioCard;
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class VersaoResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable */ public function toArray($request) { return [ 'id' => $this->id, 'nome' => $this->nome, 'abreviacao' => $this->abreviacao, 'idiomas' => new IdiomaResource($this->whenLoaded('idiomas')), 'livros' => new LivrosCollection($this->whenLoaded('livros')), "links" => [ [ 'rel' => 'Alterar versao', 'type' => 'PUT', 'link' => route('versao.update', $this->id), ], [ 'rel' => 'Excluir versao', 'type' => 'DELETE', 'link' => route('versao.destroy', $this->id), ], ] ]; } }
Rationale --------- There are no raw sources for the testcases, everything is generated programatically from C code. This avoids the need for a parser for a testcase language, better models the standard use as an API, and extends more easily to families of generated testcases. Layout ------ Each of the testcases has a .cc generator in the cogen directory. The tests target in the makefile will ensure that these are up to date. For each cogens/BASENAME.cc an executable called cogens/BASENAME will be created. This can then be executed to create output for the different target machines. The tests target in the Makefile will try and generate: results/BASENAME-orig.dot The SimpleMachine source in the testcase results/BASENAME-orig.pdf As above results/BASENAME-arm.dot Compiled to ARM instructions results/BASENAME-arm.pdf As above results/BASENAME-arm-regs.dot Compiled to ARM instructions and registers results/BASENAME-arm-regs.pdf As above results/BASENAME-arm.asm Codeworks compatible ARM code results/BASENAME-x86.dot Compiled to x86-64 instructions results/BASENAME-x86.pdf As above results/BASENAME-x86-regs.dot Compiled to x86-64 instructions and registers results/BASENAME-x86-regs.pdf As above Testcases --------- Each of the simple operation types has a range of testcases that vary the sizes of the operands. The cases that use operands smaller than the word size of the target architecture should combine operands in an appropriate way to improve efficiency. The cases that use operands larger than the word size of the target architecture should split the operands into appropriate pieces. In all cases the appropriate split / merge of operands is one that allows a sequence of instructions with equivalent semantics. The xor testcases are interesting because the instruction is a piece-wise application of a binary operator; operands can be split into arbitrary partitions without introducing any dependencies. The merge operation is simply concatenation. The add testcases can also be decomposed into arbitrary partitions, but a dependency on the carry is introduced between each pair of operands in a split. Merging of the operands eliminates the carry dependency. The motivation for the mul testcases is to examine the trade-off between register pressure and memory traffic that results from different traversal orders in the accumulation of the partial products. The hamw testcase shows the sum operation; a generalisation of the add operation to an arbitrary number of inputs. There are several well-known hacks for computing this function using few instructions, the research question behind this testcase is can a split/merge operation on sums and a conversion between sum-2/add create a search problem with a strong enough bias to find these efficient formulations? Issues ------ There is nowhere in the code/docs that defines the semantics of the instructions that we use. There is no form of validity checking to enforce the semantics. There is no definite list of what can or cannot be used in any of the machines. The only place that the semantics are exposed is implicity in the translation functions. The simple machine should avoid the use of carry flags, although every machine that we compile directly onto will use them they are an artifact of the implementation and should be avoided in the source language. Each use of an instruction that modifies an architecturally unique and unnamed carry flag introduces a sequential dependency into the instruction stream and breaks the declarative dataflow in the program. The sensible way to enforce validity is to have a series of well-defined points for the block where it is valid relative to the semantics of one particular machine. This implies that each block must hold a reference to a particular machine that defines it. The only exception will be during construction of blocks, which is deferred to the translation functions that map from the semantics of one machine to another. If we stick a machine in the block that is passed as an initialiser then it becomes impossible to use a default constructor for a block... would this be a problem later? There are limited uses for arrays of blocks... jump tables and some representations of CFGs... As these will be used sparingly we can tolerate arrays of pointers where necessary and use explicit initialisation...
import 'package:ditonton/domain/entities/search_result.dart'; import 'package:equatable/equatable.dart'; class SearchResultModel extends Equatable { SearchResultModel({ this.isMovie, this.adult, this.originalTitle, this.video, required this.backdropPath, required this.genreIds, required this.id, required this.overview, required this.popularity, required this.posterPath, required this.releaseDate, required this.voteAverage, required this.voteCount, required this.title, }); final String? backdropPath; final List<int> genreIds; final int id; final String overview; final double popularity; final String? posterPath; final String? releaseDate; final double voteAverage; final int voteCount; final String? title; final bool? isMovie; final bool? adult; final String? originalTitle; final bool? video; factory SearchResultModel.fromJson(Map<String, dynamic> json) => SearchResultModel( backdropPath: json["backdrop_path"], genreIds: List<int>.from(json["genre_ids"].map((x) => x)), id: json["id"], overview: json["overview"], popularity: json["popularity"].toDouble(), posterPath: json["poster_path"], releaseDate: json["release_date"], voteAverage: json["vote_average"].toDouble(), voteCount: json["vote_count"], title: json["original_name"]); Map<String, dynamic> toJson() => { "adult": adult, "backdrop_path": backdropPath, "genre_ids": List<dynamic>.from(genreIds.map((x) => x)), "id": id, "overview": overview, "popularity": popularity, "poster_path": posterPath, "release_date": releaseDate, "vote_average": voteAverage, "vote_count": voteCount, "title": title }; SearchResult toEntity() { return SearchResult( isMovie: false, adult: false, originalTitle: this.originalTitle, video: false, backdropPath: this.backdropPath, genreIds: this.genreIds, id: this.id, overview: this.overview, popularity: this.popularity, posterPath: this.posterPath, releaseDate: this.releaseDate, voteAverage: this.voteAverage, voteCount: this.voteCount, title: title); } @override List<Object?> get props => [ backdropPath, genreIds, id, overview, popularity, posterPath, releaseDate, voteAverage, voteCount, ]; }
import { createContext, useState, useMemo } from 'react'; //create a context, with createContext api export const employeesContext = createContext(); const EmployeesProvider = (props) => { // this state will be shared with all components const [allEmployees, setAllEmployees] = useState([ { firstName: 'Test-Prénom', lastName: 'Test-Nom', dateOfBirth: '01/01/2010', startDate: '01/09/2022', street: '15 Street Bridge', city: 'Denver', state: 'CO', zipCode: '80012', department: 'Sales', }, ]); const value = useMemo( () => ({ allEmployees, setAllEmployees, }), [allEmployees, setAllEmployees] ); return ( // this is the provider providing state <employeesContext.Provider value={value}> {props.children} </employeesContext.Provider> ); }; export default EmployeesProvider;
#lang zuo (require "harness.zuo") (alert "processes") (define zuo.exe (hash-ref (runtime-env) 'exe)) (define answer.txt (build-path tmp-dir "answer.txt")) ;; check process without redirection, inculding multiple processes (let () (define echo-to-file.zuo (build-path tmp-dir "echo-to-file.zuo")) (let ([out (fd-open-output echo-to-file.zuo :truncate)]) (fd-write out (~a "#lang zuo\n" (~s '(let* ([args (hash-ref (runtime-env) 'args)] [out (fd-open-output (car args) :truncate)]) (fd-write out (cadr args)))))) (fd-close out)) (let ([ht (process zuo.exe echo-to-file.zuo (list answer.txt "anybody home?"))]) (check (hash? ht)) (check (= 1 (hash-count ht))) (check (handle? (hash-ref ht 'process))) (let ([p (hash-ref ht 'process)]) (check (handle? p)) (check (process-wait p) p) (check (process-wait p p p) p) (check (handle? p)) (check (process-status p) 0)) (let ([in (fd-open-input answer.txt)]) (check (fd-read in eof) "anybody home?") (fd-close in))) (define answer2.txt (build-path tmp-dir "answer2.txt")) (let ([ht1 (process zuo.exe echo-to-file.zuo answer.txt "one")] [ht2 (process zuo.exe (list echo-to-file.zuo answer2.txt) "two")]) (define p1 (hash-ref ht1 'process)) (define p2 (hash-ref ht2 'process)) (define pa (process-wait p1 p2)) (define pb (process-wait (if (eq? p1 pa) p2 p1))) (check (or (and (eq? p1 pa) (eq? p2 pb)) (and (eq? p1 pb) (eq? p2 pa)))) (check (process-status p1) 0) (check (process-status p2) 0) (check (process-wait p1) p1) (check (process-wait p2) p2) (define pc (process-wait p1 p2)) (check (or (eq? pc p1) (eq? pc p2))) (let ([in (fd-open-input answer.txt)]) (check (fd-read in eof) "one") (fd-close in)) (let ([in (fd-open-input answer2.txt)]) (check (fd-read in eof) "two") (fd-close in)))) ;; check setting the process directory and environment variables (let ([path->absolute-path (lambda (p) (if (relative-path? p) (build-path (hash-ref (runtime-env) 'dir) p) p))]) (define runtime-to-file (~a "#lang zuo\n" (~s `(let* ([out (fd-open-output ,(path->absolute-path answer.txt) :truncate)]) (fd-write out (~s (cons (hash-ref (runtime-env) 'dir) (hash-ref (runtime-env) 'env)))))))) (let ([ht (process zuo.exe "" (hash 'stdin 'pipe))]) (check (hash? ht)) (check (= 2 (hash-count ht))) (check (handle? (hash-ref ht 'process))) (check (handle? (hash-ref ht 'stdin))) (fd-write (hash-ref ht 'stdin) runtime-to-file) (fd-close (hash-ref ht 'stdin)) (process-wait (hash-ref ht 'process)) (check (process-status (hash-ref ht 'process)) 0) (let () (define in (fd-open-input answer.txt)) (define dir+env (car (string-read (fd-read in eof)))) (fd-close in) (check (car dir+env) (hash-ref (runtime-env) 'dir)) (check (andmap (lambda (p) (define p2 (assoc (car p) (cdr dir+env))) (and p2 (equal? (cdr p) (cdr p2)))) (hash-ref (runtime-env) 'env))))) (let* ([env (list (cons "HELLO" "there"))] [ht (process zuo.exe "" (hash 'stdin 'pipe 'dir tmp-dir 'env env))]) (fd-write (hash-ref ht 'stdin) runtime-to-file) (fd-close (hash-ref ht 'stdin)) (process-wait (hash-ref ht 'process)) (check (process-status (hash-ref ht 'process)) 0) (let () (define in (fd-open-input answer.txt)) (define dir+env (car (string-read (fd-read in eof)))) (fd-close in) (define (dir-identity d) (hash-ref (stat d #t) 'inode)) (check (dir-identity (car dir+env)) (dir-identity tmp-dir)) (check (andmap (lambda (p) (define p2 (assoc (car p) (cdr dir+env))) (and p2 (equal? (cdr p) (cdr p2)))) env))))) ;; make sure that the file descriptor for one process's pipe isn't ;; kept open by a second process (let () (define ht1 (process zuo.exe "" (hash 'stdin 'pipe 'stdout 'pipe))) (define ht2 (process zuo.exe "" (hash 'stdin 'pipe))) (define in1 (hash-ref ht1 'stdin)) (fd-write in1 "#lang zuo 'hello") (fd-close in1) (check (fd-read (hash-ref ht1 'stdout) eof) "'hello\n") (process-wait (hash-ref ht1 'process)) (fd-close (hash-ref ht1 'stdout)) (define in2 (hash-ref ht2 'stdin)) (fd-write in2 "#lang zuo") (fd-close in2) (process-wait (hash-ref ht2 'process)) (void)) ;; check transfer of UTF-8 arguments and related (define (check-process-arg arg) (define p (process (hash-ref (runtime-env) 'exe) "" arg (hash 'stdin 'pipe 'stdout 'pipe))) (define to (hash-ref p 'stdin)) (fd-write to "#lang zuo (displayln (hash-ref (runtime-env) 'args))") (fd-close to) (define from (hash-ref p 'stdout)) (define s (fd-read from eof)) (process-wait (hash-ref p 'process)) (check s (~a"(" arg ")\n"))) (check-process-arg "\316\273") (check-process-arg "a b c") (check-process-arg "a \"b\" c") (check-process-arg "a \"b c") (check-process-arg "a \\b c")
import React, { useState } from "react"; export default function ContactForm() { const [fullname, setFullname] = useState(""); const [email, setEmail] = useState(""); const [subject, setSubject] = useState(""); const [message, setMessage] = useState(""); // Form validation const [errors, setErrors] = useState({ fullname: false, email: false, subject: false, message: false, }); // Setting button text const [buttonText, setButtonText] = useState("Send"); const [showSuccessMessage, setShowSuccessMessage] = useState(false); const [showFailureMessage, setShowFailureMessage] = useState(false); const handleValidation = () => { let tempErrors = { fullname: false, email: false, subject: false, message: false, }; let isValid = true; if (fullname.length <= 0) { tempErrors.fullname = true; isValid = false; } if (email.length <= 0) { tempErrors.email = true; isValid = false; } if (subject.length <= 0) { tempErrors.subject = true; isValid = false; } if (message.length <= 0) { tempErrors.message = true; isValid = false; } setErrors({ ...tempErrors }); console.log("errors", errors); return isValid; }; // const [form, setForm] = useState(false); const handleSubmit = async (e: React.SyntheticEvent<HTMLFormElement>) => { e.preventDefault(); let isValidForm = handleValidation(); if (isValidForm) { setButtonText("Sending"); const res = await fetch("/api/sendgrid", { body: JSON.stringify({ email: email, fullname: fullname, subject: subject, message: message, }), headers: { "Content-Type": "application/json", }, method: "POST", }); const { error } = await res.json(); if (error) { console.log(error); setShowSuccessMessage(false); setShowFailureMessage(true); setButtonText("Send"); // Reset form fields setFullname(""); setEmail(""); setMessage(""); setSubject(""); return; } setShowSuccessMessage(true); setShowFailureMessage(false); setButtonText("Send"); // Reset form fields setFullname(""); setEmail(""); setMessage(""); setSubject(""); } console.log(fullname, email, subject, message); }; return ( <div className=""> <form onSubmit={handleSubmit} className="grid grid-cols-1"> <h1 className="text-2xl font-bold mb-5 text-center">Send a message</h1> <label htmlFor="fullname" className="text-gray-500"> Full name<span className="text-red-500">*</span> </label> <input type="text" value={fullname} onChange={(e) => { setFullname(e.target.value); }} name="fullname" className="border-b py-2 pl-4 focus:outline-none focus:rounded-md focus:ring-1 ring-black text-black" /> {errors?.fullname && ( <p className="text-red-500">Fullname cannot be empty.</p> )} <label htmlFor="email" className="text-gray-500 mt-4"> E-mail<span className="text-red-500">*</span> </label> <input type="email" name="email" value={email} onChange={(e) => { setEmail(e.target.value); }} className="border-b py-2 pl-4 focus:outline-none focus:rounded-md focus:ring-1 ring-black text-black" /> {errors?.email && ( <p className="text-red-500">Email cannot be empty.</p> )} <label htmlFor="subject" className="text-gray-500 mt-4"> Subject<span className="text-red-500">*</span> </label> <input type="text" name="subject" value={subject} onChange={(e) => { setSubject(e.target.value); }} className="border-b py-2 pl-4 focus:outline-none focus:rounded-md focus:ring-1 ring-black text-black" /> {errors?.subject && ( <p className="text-red-500">Subject cannot be empty.</p> )} <label htmlFor="message" className="text-gray-500 mt-4"> Message<span className="text-red-500">*</span> </label> <textarea name="message" value={message} onChange={(e) => { setMessage(e.target.value); }} className="border-b py-2 pl-4 focus:outline-none focus:rounded-md focus:ring-1 ring-black text-black" ></textarea> {errors?.message && ( <p className="text-red-500">Message body cannot be empty.</p> )} <div className="flex flex-row items-center justify-center"> <button type="submit" className="px-10 mt-8 py-2 bg-black text-white font-light rounded-md text-lg items-center" > {buttonText} </button> </div> <div className="text-center"> {showSuccessMessage && ( <p className="text-green-500 font-semibold text-sm my-2"> Thankyou! Your Message has been delivered. </p> )} {showFailureMessage && ( <p className="text-red-500"> Oops! Something went wrong, please try again. </p> )} </div> </form> </div> ); }
library(raster) library(tidyverse) # european_coordinates.csv contains all site locatiosn for BGEMS across Europe locations <- read.csv("Data/Sites/european_coordinates.csv", header = T) # In locations columns are ordered latitude then longitude # R requires columns to be the other way around i.e. long (x) then lat (y) coordinates <- mutate(locations, longitude1 = longitude, latitude1 = latitude) # Remove orignal lat long columns coordinates <- subset(coordinates, select=-c(longitude, latitude)) # Rename lat1 and long1 # Remove all sites not in England # Remove Warton Cragg site as not used in analysis coordinates <- coordinates %>% rename(latitude = latitude1, longitude = longitude1) %>% filter (country == "England", name != "Warton Crag LNR") # Turn coordinates into spatial points dataframe # coordinates gets a spatial point data frame using columns 5 (long) and 6 (lat) # of the dataframe coordinates # proj4string = CRS(etc) tells R which coordinate reference system to use # Unlikely to plot without information # Using WGS84 CRS # Code to ut in CRS() available at: # http://spatialreference.org/ref/epsg/wgs-84/ # http://spatialreference.org/ref/epsg/wgs-84/proj4/ coordinates <- SpatialPointsDataFrame( coordinates[, 5:6], coordinates, proj4string = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs") ) # Check whether working # Plot shows locations of points plot(coordinates) # Create matrix of distances (meters) between pairs of sites site_distances <- pointDistance(coordinates, coordinates, allpairs = T, lonlat = TRUE) site_distances # Convert into a dataframe site_distances <- as.data.frame(site_distances) # Add row names and column names to matrix colnames(site_distances) <- c(as.character(coordinates$code)) rownames(site_distances) <- c(as.character(coordinates$code)) # Divide matrix by 1000 to get distance in KM instead of M site_distances <- site_distances/ 1000 # Write matrix to a csv #write.csv(site_distances, "Outputs/site_distance_matrix.csv") # Convert row names into the 1st column of the dataframe site_distances <- rownames_to_column(site_distances, var = "site_1") # Gather dataframe together so that instead of matrix, dataframe is long list # Reduce to three rows, site 1, site 2 and distance between sites in meters site_distances <- site_distances %>% gather(site_2, distance, LC:WW) # Create list of site names site_list <- unique(site_distances$site_1) # Create empty dataframe site_distances_arranged <- NULL # For loop rearranges dataframe so that the distances are ordered for each site # i.e. arranged highest to lowest distances between LC and all other sites # followed by highest to lowest distances between AU and all other sites for (i in site_list){ df <- site_distances %>% filter(site_1 == i) %>% arrange(distance) site_distances_arranged = rbind(site_distances_arranged, df) } site_distances_arranged # Detach raster package as overwrites some dplyr commands e.g. select detach(package:raster, unload = TRUE)
webgrid dynamic column demo Controller code ------------------- public class HomeController : Controller { public ActionResult Index() { DataTable dt = new DataTable(); dt.Columns.Add("Section", typeof(string)); dt.Columns.Add("Q1", typeof(string)); dt.Columns.Add("Q2", typeof(string)); dt.Columns.Add("Q3", typeof(string)); dt.Columns.Add("Q4", typeof(string)); dt.Columns.Add("FY1", typeof(string)); dt.Columns.Add("FYCheck1", typeof(string)); dt.Columns.Add("Q5", typeof(string)); dt.Columns.Add("Q6", typeof(string)); dt.Columns.Add("Q7", typeof(string)); dt.Columns.Add("Q8", typeof(string)); dt.Columns.Add("FY2", typeof(string)); dt.Columns.Add("FYCheck2", typeof(string)); dt.Rows.Add(new Object[]{ "Section", "1Q 2010", "2Q 2010", "3Q 2010", "4Q 2010", "2010 FY", "2010 FYCheck", "1Q 2011", "2Q 2011", "3Q 2011", "4Q 2011", "2011 FY", "2011 FYCheck", }); dt.Rows.Add(new Object[]{ "Consensus Model", "22.31", "20.11", "55.60", "78.11", "10.12", "11.11", "99.13", "45.20", "77.30", "45.11", "41.78", "98.10", }); dt.Rows.Add(new Object[]{ "Operational Metrics", "22.31", "20.11", "55.60", "78.11", "10.12", "11.11", "99.13", "45.20", "77.30", "45.11", "41.78", "98.10", }); dt.Rows.Add(new Object[]{ "Key Financials", "22.31", "20.11", "55.60", "78.11", "10.12", "11.11", "99.13", "45.20", "77.30", "45.11", "41.78", "98.10", }); List<WebGridColumn> columns = new List<WebGridColumn>(); foreach (DataColumn col in dt.Columns) { columns.Add(new WebGridColumn() { ColumnName = col.ColumnName, Header = col.ColumnName }); } ViewBag.Columns = columns; //Converting datatable to dynamic list var dns = new List<dynamic>(); dns = ConvertDatatableToList(dt); ViewBag.Total = dns; return View(); } public List<dynamic> ConvertDatatableToList(DataTable dt) { var data = new List<dynamic>(); foreach (var item in dt.AsEnumerable()) { // Expando objects are IDictionary<string, object> IDictionary<string, object> dn = new ExpandoObject(); foreach (var column in dt.Columns.Cast<DataColumn>()) { dn[column.ColumnName] = item[column]; } data.Add(dn); } return data; } } HTML portion ------------------ @model System.Data.DataTable @using System.Data @{ ViewBag.Title = "Home Page"; } <style> table { font-family: verdana,arial,sans-serif; font-size: 11px; color: #333333; border-width: 1px; border-color: #999999; border-collapse: collapse; width: 80% !important; max-width: 80% !important; } table th { background: #b5cfd2; border-width: 1px; padding: 8px; border-style: solid; border-color: #999999; } table td { background: #dcddc0; border-width: 1px; padding: 8px; border-style: solid; border-color: #999999; } .foot { text-align: center; } </style> @{ List<dynamic> obj1 = new List<dynamic>(); obj1 = ViewBag.Total; var grid = new WebGrid(obj1); } <br /><br /><br /> @*displayHeader: false hide header*@ @grid.GetHtml(displayHeader: false, columns: ViewBag.Columns, tableStyle: "table", footerStyle: "foot")
import { useState, useEffect, useCallback } from "react"; import useVariablesStoreInfo from "../../utils/info/useVariablesStoreInfo"; export default function useCountResize(framesWidth: number) { // Переменная значения высоты столбиков. 2 - примерное значение, чтобы фреймы занимали ровно одну страницу const { framesHeightConst } = useVariablesStoreInfo(); // Количество столбиков const [colNum, setColNum] = useState( Math.round(window.innerWidth / framesWidth / framesHeightConst), ); // Примерное количество столбиков в длину const [lineNum, setLineNum] = useState(Math.round(window.innerHeight / framesWidth)); const windowHandler = useCallback(() => { setColNum(Math.round(window.innerWidth / framesWidth / framesHeightConst)); setLineNum(Math.round(window.innerHeight / framesWidth)); }, [framesWidth]); useEffect(() => { window.addEventListener("resize", windowHandler); }, [windowHandler]); return { colNum, lineNum }; }
<div class="company-profile"> <div class="profile-header"> <div class="profile-img"> @if ($user->profile_picture == null) <img src="/images/profiles/default_image_company.png" alt=""> @else <img src="/storage/{{ $user->profile_picture }}" alt=""> @endif </div> <div class="profile-info-desktop-wrapper"> <div class="profile-info"> <div class="info"> <h1 class="title-2">{{ $user->name }}</h1> <p class="subtitle">{{ $extraInfo->location }}</p> </div> </div> <!-- Display "Redigera" if the logged-in user's ID matches the profile ID --> @if ($user->id === Auth::id()) <a href="{{ route('edit-profile') }}">Ändra profil</a> @endif </div> <!-- Display save-button if the logged-in user's ID does not match the profile ID --> @if ($user->id !== Auth::id()) <div class="save"> <livewire:like-button :userId="$user->id" /> </div> @endif </div> <div class="profile-main"> <div class="desktop-selection"> <div class="main-section"> <h2 class="title-4">Om oss</h2> @if ($user->description == null) <p class="description-placeholder">Den här användaren har inte skrivit någon beskrivning ännu.</p> @else <p>{!! nl2br($user->description) !!}</p> @endif </div> <div class="divider"></div> <div class="main-section"> <h2 class="title-4">Vad vi jobbar med</h2> <div class="technologies"> @foreach ($user->technologies as $technology) <div class="technology">{{ $technology->name }}</div> @endforeach </div> </div> <div class="divider"></div> </div> <div class="main-section contact"> <h2 class="title-4">Kontakt</h2> <ul> @php $contactInfo = [ [ 'value' => $user->phone, 'label' => $user->phone, 'href' => '', 'icon' => '/images/icons/phone.svg', ], [ 'value' => $user->email, 'label' => $user->email, 'href' => '', 'icon' => '/images/icons/mail.svg', ], [ 'value' => $user->website, 'label' => $user->website, 'href' => $user->website, 'icon' => '/images/icons/website.svg', ], [ 'value' => $user->linkedin, 'label' => $user->name, 'href' => $user->linkedin, 'icon' => '/images/icons/linkedin.svg', ], [ 'value' => $user->facebook, 'label' => '@' . $user->facebook, 'href' => 'https://www.instagram.com/' . $user->facebook, 'icon' => '/images/icons/instagram.svg', ], ]; @endphp @foreach ($contactInfo as $info) @if ($info['value']) <li> <div class="contact-icon"><img src="{{ $info['icon'] }}" alt=""></div> <a href="{{ $info['href'] }}">{{ $info['label'] }}</a> </li> @endif @endforeach </ul> </div> </div>
<div class="container-fluid" style= "margin-top: 60px"> <div class= "row"> <input class="form-control me-2" type="search" (input)="search($event.target.value)" name= "searchproduct" placeholder="What would you like to buy today?" [(ngModel)]= "searchProduct" aria-label="Search"> </div> </div> <div class="row" style= "margin-top: 50px;"> <div class="col-3"> <ul class= "list-group"> <!-- <li class="list-group-item active" aria-current= "true" style="background-color:green" (click)= "allCategory()"> --> <!-- All Categories</li> --> <a class="list-group-item" *ngFor= "let category of categories | keyvalue" routerLink = "/" [queryParams]="{category: category.value}">{{category.key}} </a> </ul> </div> <div class="col-9 click"> <div class="row"> <ng-container *ngFor= "let product of filteredProducts; let productIndex= index"> <div class="card col-5" style= "margin-right: 10px;margin-bottom: 10px;" (click)="productInformation()"> <img src= "{{product.imageUrl}}" class="card-img-top" style= "height: 200px;"> <div class="card-body"> <br> <h5> {{product.productName}} </h5> <h5 style= "opacity: 0.7;">{{product.price|currency:"INR":"symbol"}}</h5> <div class="row"> <button class="btn btn-secondary" *ngIf= "!product.isAddedtocart" (click)= "addtocart(productIndex)"> Add to Cart </button> </div> <div class="input-group mb-3" *ngIf= "product.isAddedtocart"> <span class="input-group-text" (click)= decreaseCount(productIndex)>-</span> <input type="text" class="form-control" placeholder="{{product.quantity}}" aria-label="Amount (to the nearest dollar)"> <span class="input-group-text" (click)= increaseCount(productIndex)>+</span> </div> </div> </div> </ng-container> </div> </div> </div>
<?php namespace App\Service; use App\Form\Model\PlayerDto; use App\Service\PlayerManager; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use App\Form\Type\PlayerFormType; use App\Constants\HttpRequestsConstants; class PlayerRequestProcessor extends AbstractController { private $playerManager; private $httpRequestsConstants; public function __construct(PlayerManager $playerManager, HttpRequestsConstants $httpRequestsConstants) { $this->playerManager = $playerManager; $this->httpRequestsConstants = $httpRequestsConstants; } public function findAllPlayersProcessor() { $Players = $this->playerManager->findAll(); return $this->json([ "data" => $Players, ]); } public function findPlayerClubProcessor(Request $request) { $pag = $request->get("pag"); $id_club = $request->get("id_club"); $name = $request->get("player"); $players_club = $this->playerManager->findByPlayerClub( $id_club, $name, $pag ); if (!$players_club) { return $this->json([ "code" => $this->httpRequestsConstants::HTTP_OK, "message" => "Not found", "errors" => "", ]); } return $this->json([ "code" => $this->httpRequestsConstants::HTTP_OK, "message" => "", "errors" => "", "data" => $players_club, ]); } public function createPlayerProcessor(Request $request) { $playerDto = new PlayerDto(); $form = $this->createForm(PlayerFormType::class, $playerDto); $form->handleRequest($request); $budget = $this->playerManager->getBudgetByClub( $playerDto->salary, $playerDto->id_club ); if ($form->isSubmitted() && $form->isValid()) { if ($budget > $playerDto->salary) { try { $player = $this->playerManager->create(); $player->setIdClub($playerDto->id_club); $player->setName($playerDto->name); $player->setSalary($playerDto->salary); $player->setEmail($playerDto->email); $this->playerManager->save($player); return $this->json([ "code" => $this->httpRequestsConstants::HTTP_OK, "message" => "Player successfully created", "errors" => "", "data" => $player, ]); } catch (\Exception $e) { return $this->json([ "code" => $this->httpRequestsConstants::HTTP_BAD_REQUEST, "message" => "Validation Failed", "errors" => $e->getMessage(), ]); } } else { return $this->json([ "code" => $this->httpRequestsConstants::HTTP_BAD_REQUEST, "message" => "Validation Failed", "errors" => 'The club no longer has a budget ($' . $budget . ")", ]); } } return $this->json([ "data" => $form, ]); } public function deletePlayerProcessor(Request $request) { $player_id = $request->get("id"); $player = $this->playerManager->find($player_id); if ($player) { try { $this->playerManager->delete($player); return $this->json([ "code" => $this->httpRequestsConstants::HTTP_OK, "message" => "Player successfully deleted", "errors" => "", "data" => $player, ]); } catch (\Throwable $th) { return $this->json([ "code" => $this->httpRequestsConstants::HTTP_BAD_REQUEST, "message" => "Validation Failed", "errors" => $th->getMessage(), ]); } } } }
/* Solaris Trusted Extensions GNOME desktop library. Copyright (C) 2007 Sun Microsystems, Inc. All Rights Reserved. Copyright (c) 2020, Dynamic Systems, Inc. The contents of this library are subject to the terms of the GNU Lesser General Public License version 2 (the "License") as published by the Free Software Foundation. You may not use this library except in compliance with the License. You should have received a copy of the License along with this library; see the file COPYING. If not,you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html or by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. See the License for specific language governing permissions and limitations under the License. */ #ifndef SEL_CONFIG_H #define SEL_CONFIG_H #include <tsol/label.h> /* * The various label combinations * Note: The bottom bits specify the il relationship and * the top bits specify the sl relationship */ typedef enum { DGSL = 0, /* SrcSL > DstSL */ EQSL = 4, /* SrcSL = DstSL */ UGSL = 8, /* SrcSL < DstSL */ DJSL = 12, /* SrcSL # DstSL */ DGIL = 0, /* SrcIL > DstIL */ EQIL = 1, /* SrcIL = DstIL */ UGIL = 2, /* SrcIL < DstIL */ DJIL = 3 /* SrcIL # DstIL */ } TransferParts; typedef enum { DGSL_DGIL = DGSL + DGIL, DGSL_EQIL = DGSL + EQIL, DGSL_UGIL = DGSL + UGIL, DGSL_DJIL = DGSL + DJIL, EQSL_DGIL = EQSL + DGIL, EQSL_EQIL = EQSL + EQIL, EQSL_UGIL = EQSL + UGIL, EQSL_DJIL = EQSL + DJIL, UGSL_DGIL = UGSL + DGIL, UGSL_EQIL = UGSL + EQIL, UGSL_UGIL = UGSL + UGIL, UGSL_DJIL = UGSL + DJIL, DJSL_DGIL = DJSL + DGIL, DJSL_EQIL = DJSL + EQIL, DJSL_UGIL = DJSL + UGIL, DJSL_DJIL = DJSL + DJIL } TransferType; /* * this is the auto confirm structure * * This structure is loaded from the /etc/gnome/sel_config or * /usr/gnome/sel_config file. It controls the action of the selection * manager and the file manager drag and drop confirmer. * There is an entry for the 16 possible types of transfer based * upon the source label and destination label. * * For each combination the entry has the following options: * * do_auto_confirm = true -> confirm transfer without displaying confirmer * (note: user must still have proper authorizations) * false -> display confirmer before processing transfer * auto_confirm_label = specifies the IL to use if auto_confirm is true. * 's' = use IL of source data (sel_mgr) * use IL of source file (nautilus) * 'd' = use IL of destination window (sel_mgr) * use IL of destination directory (nautilus) * * If ILs are being hidden, it is possible that the IL can be * invalid but would not be displayed for the user to correct. * The hidden_il_action field specifies the action to be taken * in that case. * * hidden_il_action = See explanation below. * 'c' = show confirmer with ILs displayed * (nautilus and sel_mgr) - default * 'd' = use IL of destination window (sel_mgr) * use IL of destination directory (nautilus) * 'l' = set IL to admin_low (sel_mgr and nautilus) * * When ILs are hidden for a user, it is possible that the IL can be * invalid for the destination. If an auto-confirm is being processed * the auto_confirm_label setting will be used if it results in an IL * that is valid. If that is invalid, the hidden_il_label setting will * be used. If it is not an auto-confirm and the IL would be invalid * for the destination, the hidden_il_label setting will be used to * set the hidden IL. If the IL is still invalid after the hidden_il_label * setting is used, the transfer will not be allowed. */ #define TS_IL_FROM_DST 1 #define TS_IL_ADLOW 2 #define TS_IL_CONFIRM 3 typedef struct { int do_auto_confirm[16]; /* one for each transfer type */ int do_auto_cancel[16]; int hidden_il_action; /* see defines above for values */ } AutoConfirm; #define MAX_AUTO_REPLY 50 /* max no. of auto reply settings */ /* * auto reply structure */ typedef struct { int enabled; int count; char *selection[MAX_AUTO_REPLY]; /* this is malloced as required */ } AutoReply; /* Function Prototypes */ extern int tsol_load_sel_config(AutoConfirm *confirm, AutoReply *reply); extern TransferType tsol_check_transfer_type( bslabel_t *src_sl, bslabel_t *dst_sl); #endif
import { Component, OnInit } from '@angular/core'; import { MatDialog, MatDialogConfig } from '@angular/material/dialog'; import { PageEvent } from '@angular/material/paginator'; import { Sort } from '@angular/material/sort'; import { Router } from '@angular/router'; import { DateTimeFormat } from 'src/app/core/Utils/date-time-format'; import { SnackBarAlert } from 'src/app/core/Utils/snack-bar-alert'; import { AlertModalComponent } from 'src/app/core/alert-modal/alert-modal.component'; import { Customer } from 'src/app/customer/models/customer'; import { Contract } from '../Models/contract'; import { ContractStatusDescription } from '../Models/contractStatus.enum'; import { AddContractComponent } from '../add-contract/add-contract.component'; import { ContractService } from '../contract.service'; @Component({ selector: 'app-contract-list', templateUrl: './contract-list.component.html', styleUrls: ['./contract-list.component.scss'], }) export class ContractListComponent implements OnInit { public contractList: Array<Contract> = []; customers: Customer[] = []; totalElements: number = 0; contracts: Contract[] = []; loading: boolean | undefined; orderBy: string = 'code'; statusContract = ContractStatusDescription; statusClass: string = ''; namecpfCnpjCustomer: string = ''; nameOrCpfCnpjCustomer: string = ''; constructor( private contractService: ContractService, private router: Router, private snackBar: SnackBarAlert, private dialog: MatDialog, private dateTimeFormat: DateTimeFormat ) {} ngOnInit(): void { this.getContractList({ page: '0', size: '5', order: this.orderBy }); } private getContractList(request: any) { this.loading = true; this.contractService.getContractList(request).subscribe( (data) => { this.contracts = data['content']; this.totalElements = data['totalElements']; this.loading = false; }, (error) => { this.loading = false; } ); } nextPage(event: PageEvent) { const request: any = {}; request['page'] = event.pageIndex.toString(); request['size'] = event.pageSize.toString(); request['order'] = this.orderBy; this.getContractList(request); } public addContract() { this.dialog .open(AddContractComponent, {}) .afterClosed() .subscribe((result: boolean) => { this.getContractList({ page: '0', size: '5', order: this.orderBy }); }); } public deleteContract(idContract: number) { const dialogRef = this.dialog.open(AlertModalComponent, { data: { title: 'ATENÇÃO!', body: 'Tem certeza que deseja remover o contrato?', }, }); dialogRef.afterClosed().subscribe((result: boolean) => { if (result) { this.contractService.deleteContract(idContract).subscribe( (resp) => { this.snackBar.successSnackBar('Contrato excluído com sucesso!'); this.contracts = this.contracts.filter((contract) => { return idContract !== contract.id; }); }, (error) => this.snackBar.alertSnackBar(error.error.message) ); } }); } public viewContract(idContract: number) { this.router.navigate(['contract', idContract]); } sortData(sort: Sort) { const data = this.contracts.slice(); if (!sort.active || sort.direction === '') { this.contracts = data; return; } this.contracts = data.sort((a, b) => { const isAsc = sort.direction === 'asc'; const isDesc = sort.direction === 'desc'; switch (sort.active) { case 'code': return compare(a.code, b.code, isAsc); default: return 0; } }); } setDateTime(dateTime: Date, onlyDate: boolean) { return this.dateTimeFormat.setDateTimeBrazil(dateTime, onlyDate); } setClassPerStatus(c: Contract) { if (this.statusContract.get(c.contractStatus) == 'Aguardando') { return 'btn btn-info btn-sm'; } else if (this.statusContract.get(c.contractStatus) == 'Iniciando') { return 'btn btn-primary btn-sm'; } else if (this.statusContract.get(c.contractStatus) == 'Ativo') { return 'btn btn-success btn-sm'; } else if (this.statusContract.get(c.contractStatus) == 'Suspenso') { return 'btn btn-warning btn-sm'; } else if (this.statusContract.get(c.contractStatus) == 'Cancelado') { return 'btn btn-danger btn-sm'; } else return 'btn btn-light btn-sm'; } // public getAllCustomerByNameOrCpfCnpj( // nameOrCpfCnpj: string, // request: any | null // ) { // if (nameOrCpfCnpj == '' || nameOrCpfCnpj == null) { // this.contractService.getCustomerList({ // page: '0', // size: '5', // order: this.orderBy, // }); // return; // } // if (!request) { // request = { // page: '0', // size: '5', // order: this.orderBy, // }; // } // this.loading = true; // this.contractService // .getAllCustomerByNameOrCpfCnpj(nameOrCpfCnpj, request) // .subscribe( // (data) => { // this.customers = data['content']; // this.totalElements = data['totalElements']; // this.loading = false; // }, // (error) => { // this.loading = false; // } // ); // } public addCustomerToContract(idCustomer: number, idContract: number) { this.contractService .addCustomerToContract(idCustomer, idContract) .subscribe( (success) => { if (success) { this.snackBar.successSnackBar( 'Cliente adicionado ao contrato com sucesso!' ); } else { this.snackBar.alertSnackBar( 'Erro ao adicionar o cliente ao contrato' ); } }, (error) => { this.snackBar.errorSnackBar(error); } ); } public getAllContractByNameCustomer( nameOrCpfCnpjCustomer: string, request: any | null ) { if (nameOrCpfCnpjCustomer == '' || nameOrCpfCnpjCustomer == null) { this.getContractList({ page: '0', size: '5', order: this.orderBy }); return; } if (!request) { request = { page: '0', size: '5', order: this.orderBy, }; } this.loading = true; this.contractService .getAllContractByNameOrCpfCnpjCustomer(nameOrCpfCnpjCustomer, request) .subscribe( (data) => { this.contracts = data['content']; this.totalElements = data['totalElements']; this.loading = false; }, (error) => { this.loading = false; } ); } } function compare(a: number | string, b: number | string, isAsc: boolean) { return (a < b ? -1 : 1) * (isAsc ? 1 : -1); } function getAllContractByNameCustomer( nameCustomer: any, string: any, request: any, arg3: number ) { throw new Error('Function not implemented.'); }
<?php declare(strict_types=1); namespace FpDbTest; use Exception; class ServiceLocator { private array $loaded = []; public function __construct( private array $config, private array $afterCreateServiceHooks ) { } /** * @template T * @param class-string<T> $serviceName * @return T * @throws Exception */ public function get(string $serviceName): object { if ($this->loaded[$serviceName] ?? null) { return $this->loaded[$serviceName]; } $this->loaded[$serviceName] = $this->newInstance($serviceName); if (is_callable($this->afterCreateServiceHooks[$serviceName] ?? null)) { $this->afterCreateServiceHooks[$serviceName]($this); } return $this->loaded[$serviceName]; } /** * @template T * @param class-string<T> $serviceName * @return T * @throws Exception */ private function newInstance(string $serviceName): object { if (!is_callable($this->config[$serviceName] ?? null)) { throw new Exception( sprintf( 'Service declaration not found for %s', $serviceName ) ); } return $this->config[$serviceName]($this); } }
import {observer} from 'mobx-react'; import React, {useEffect, useState} from 'react'; import {Text, TouchableOpacity, View} from 'react-native'; import DropDownPicker from 'react-native-dropdown-picker'; import {Dropdown} from 'react-native-element-dropdown'; import AntDesign from 'react-native-vector-icons/AntDesign'; import Ionicons from 'react-native-vector-icons/Ionicons'; import {Colors} from '../../../../constants/color.const'; import RouteNames from '../../../../constants/route-names.const'; import styles from '../../screens/AddGroupProductScreen/styles/style'; import * as sl from '../../services/storage-location.service'; interface IProps { navigation?: any; groupId: string; fnUpdateStorageLocationId: (id: string) => void; } const StorageLocationDropdownPicker: React.FC<IProps> = ({ navigation, groupId, fnUpdateStorageLocationId, }) => { const [value, setValue] = useState(''); const [items, setItems] = useState< { label: string; value: string; }[] >([]); const [isFocus, setIsFocus] = useState(false); useEffect(() => { search(''); }, []); const search = async (text: string) => { // Get items from API const resp = await sl.getStorageLocationPaginated({ groupId: groupId, searchBy: ['name'], search: text, limit: 100, filter: { 'timestamp.deletedAt': '$eq:$null', }, sortBy: ['name:ASC', 'timestamp.createdAt:ASC'], }); // Set items for the dropdown const items = resp.data .map(item => ({ label: item.name || '', value: item.id || '', })) .filter(item => item.label !== ''); setItems(items); }; return ( <View style={{ width: '100%', display: 'flex', flexDirection: 'column', // alignItems: 'flex-end', backgroundColor: Colors.background.white, borderRadius: 10, }}> <View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 10, }}> <Text style={{ width: '90%', textAlign: 'left', color: Colors.title.orange, fontWeight: 'bold', fontSize: 16, marginBottom: 10, }}> Vị trí lưu trữ </Text> {navigation && ( <TouchableOpacity onPress={() => navigation.navigate(RouteNames.ADD_STORAGE_LOCATION, {}) }> <Ionicons name="add-circle-outline" size={24} color={Colors.text.orange} /> </TouchableOpacity> )} </View> <Dropdown containerStyle={{ width: '100%', }} placeholderStyle={{ color: Colors.text.lightgrey, fontSize: 14, }} itemTextStyle={{ color: Colors.text.grey, fontSize: 14, }} data={items} search maxHeight={300} labelField="label" valueField="value" placeholder={!isFocus ? 'Chọn vị trí lưu trữ ...' : '...'} searchPlaceholder="Tìm kiếm ..." value={value} onFocus={() => setIsFocus(true)} onBlur={() => setIsFocus(false)} onChange={item => { setValue(item.value); setIsFocus(false); fnUpdateStorageLocationId(item.value); }} /> </View> ); }; export default observer(StorageLocationDropdownPicker);
#if !defined(P67_TLV_H) #define P67_TLV_H 1 #include "err.h" #include <stdint.h> #include <limits.h> #include "cmn.h" #include "net.h" /* p67 tlv fragment: message can contain 0 - N such TLV fragments. |---|---|--------------------------------------| | 1 | 1 | 0 - 255 | |---|---|--------------------------------------| | | | | | | | | ------> [ VALUE: length specified by VLENGTH ] | | | -----> [ VLENGTH : 1 byte value length, allowed values e [0, 255] ] | ---> [ KEY: 1 byte key. ] KEY + VLENGTH fields create HEADER */ #define P67_TLV_KEY_LENGTH 1 #define P67_TLV_VLENGTH_LENGTH 1 #define p67_tlv_header_fields() \ uint8_t tlv_key[P67_TLV_KEY_LENGTH]; \ uint8_t tlv_vlength; typedef struct p67_tlv_header { p67_tlv_header_fields() } p67_tlv_header_t; p67_cmn_static_assert(p67_tlv_header_t, sizeof(p67_tlv_header_t) == 2); #define P67_TLV_HEADER_LENGTH \ (P67_TLV_VLENGTH_LENGTH + P67_TLV_KEY_LENGTH) #define P67_TLV_VALUE_MIN_LENGTH 0 #define P67_TLV_FRAGMENT_MIN_LENGTH \ (P67_TLV_KEY_LENGTH + P67_TLV_VLENGTH_LENGTH + P67_TLV_VALUE_MIN_LENGTH) #define P67_TLV_VALUE_MAX_LENGTH UCHAR_MAX #define P67_TLV_FRAGMENT_MAX_LENGTH \ (P67_TLV_KEY_LENGTH + P67_TLV_VALUE_LENGTH_LENGTH + P67_TLV_VALUE_MAX_LENGTH) // p67_err // p67_tlv_get_next_fragment( // const unsigned char ** msg, int * msgl, // unsigned char * key, // unsigned char * value, unsigned char * vlength) // __nonnull((1, 2)); p67_err p67_tlv_next( const p67_pckt_t ** msg, int * msgl, const p67_tlv_header_t ** header, const p67_pckt_t ** value); int p67_tlv_add_fragment( unsigned char * msg, int msgl, const unsigned char * key, const unsigned char * value, unsigned char vlength); p67_err p67_tlv_pretty_print_fragment( const p67_tlv_header_t * header, const unsigned char * value); const p67_pckt_t * p67_tlv_get_arr( const p67_tlv_header_t * __restrict__ const hdr, const p67_pckt_t * __restrict__ const value, const int expected_length); const char * p67_tlv_get_cstr( const p67_tlv_header_t * __restrict__ const hdr, const p67_pckt_t * __restrict__ const value); #endif
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation // MARK: - ParsingManager extension to help parse json file into Core Data objects the app saves locally extension ApplicationDataManager { func parseJsonObjectIntoCoreData(jsonObject: [String: AnyObject]) { parseNotificiations(jsonObject) parseGroups(jsonObject) parseChallengeTasks(jsonObject) parseChallenges(jsonObject) parseTypes(jsonObject) parseDetails(jsonObject) parsePOIs(jsonObject) parseFavoritedPOIs(jsonObject) parseUsers(jsonObject) parseInvitations(jsonObject) parseAds(jsonObject) isDoneLoading = true } private func parseNotificiations(jsonObject: [String: AnyObject]) { guard let notificationsArray = jsonObject["notifications"] as? [[String: AnyObject]] else { print("Data parser: Notifications data not recieved or malformed") return } for notificationDictionary in notificationsArray { guard let managedNotification = createManagedObject("Notification") else { return } managedNotification.setValue(notificationDictionary["id"] as! Int, forKey: "id") managedNotification.setValue(notificationDictionary["title"], forKey: "title") managedNotification.setValue(notificationDictionary["message"], forKey: "message") managedNotification.setValue(notificationDictionary["unread"] as! String == "true", forKey: "unread") managedNotification.setValue(notificationDictionary["type"] as! String, forKey: "type") managedNotification.setValue(NSDate(timeIntervalSince1970: notificationDictionary["timestamp"] as! NSTimeInterval), forKey: "timestamp") saveToCoreData() } } private func parseGroups(jsonObject: [String: AnyObject]) { guard let groupsArray = jsonObject["groups"] as? [[String: AnyObject]] else { print("Data parser: Groups data not recieved or malformed") return } for groupDictionary in groupsArray { guard let managedGroup = createManagedObject("Group") else { return } managedGroup.setValue(groupDictionary["id"], forKey: "id") managedGroup.setValue(groupDictionary["name"], forKey: "name") saveToCoreData() } } private func parseChallengeTasks(jsonObject: [String: AnyObject]) { guard let challengeTasksArray = jsonObject["challengeTasks"] as? [[String: AnyObject]] else { print("Data parser: Challenge Tasks data not recieved or malformed") return } for challengeTaskDictionary in challengeTasksArray { guard let managedChallengeTask = createManagedObject("ChallengeTask") else { return } managedChallengeTask.setValue(challengeTaskDictionary["id"], forKey: "id") managedChallengeTask.setValue(challengeTaskDictionary["name"], forKey: "name") saveToCoreData() } } private func parseChallenges(jsonObject: [String: AnyObject]) { guard let challengesArray = jsonObject["challenges"] as? [[String: AnyObject]] else { print("Data parser: Challenges data not recieved or malformed") return } for challengeDictionary in challengesArray { guard let managedChallenge = createManagedObject("Challenge") else { return } managedChallenge.setValue(challengeDictionary["id"], forKey: "id") managedChallenge.setValue(challengeDictionary["name"], forKey: "name") managedChallenge.setValue(challengeDictionary["details"], forKey: "details") managedChallenge.setValue(challengeDictionary["image_url"], forKey: "image_url") managedChallenge.setValue(challengeDictionary["point_value"], forKey: "point_value") managedChallenge.setValue(challengeDictionary["thumbnail_url"], forKey: "thumbnail_url") let tasksNeeded = Set(fetchFromCoreData("ChallengeTask", ids: challengeDictionary["tasks_needed"] as! [Int])) managedChallenge.setValue(tasksNeeded, forKey: "tasks_needed") saveToCoreData() } } private func parseTypes(jsonObject: [String: AnyObject]) { guard let typesArray = jsonObject["types"] as? [[String: AnyObject]] else { print("Data parser: Type data not recieved or malformed") return } for typeDictionary in typesArray { guard let managedType = createManagedObject("Type") else { return } managedType.setValue(typeDictionary["id"], forKey: "id") managedType.setValue(typeDictionary["name"], forKey: "name") managedType.setValue(typeDictionary["image_name"], forKey: "image_name") managedType.setValue(typeDictionary["pin_image_name"], forKey: "pin_image_name") saveToCoreData() } } private func parseDetails(jsonObject: [String: AnyObject]) { guard let detailsArray = jsonObject["details"] as? [[String: AnyObject]] else { print("Data parser: Detail data not recieved or malformed") return } for detailDictionary in detailsArray { guard let managedDetail = createManagedObject("Detail") else { return } managedDetail.setValue(detailDictionary["id"], forKey: "id") managedDetail.setValue(detailDictionary["message"], forKey: "message") managedDetail.setValue(detailDictionary["image_name"], forKey: "image_name") saveToCoreData() } } private func parsePOIs(jsonObject: [String: AnyObject]) { guard let POIsArray = jsonObject["POIs"] as? [[String: AnyObject]] else { print("Data parser: POIs data not recieved or malformed") return } for POIDictionary in POIsArray { guard let managedPOI = createManagedObject("POI") else { return } managedPOI.setValue(POIDictionary["id"], forKey: "id") managedPOI.setValue(POIDictionary["coordinate_x"], forKey: "coordinate_x") managedPOI.setValue(POIDictionary["coordinate_y"], forKey: "coordinate_y") managedPOI.setValue(POIDictionary["description"], forKey: "description_detail") managedPOI.setValue(POIDictionary["name"], forKey: "name") managedPOI.setValue(POIDictionary["picture_url"], forKey: "picture_url") managedPOI.setValue(POIDictionary["thumbnail_url"], forKey: "thumbnail_url") managedPOI.setValue(POIDictionary["wait_time"], forKey: "wait_time") managedPOI.setValue(POIDictionary["height_requirement"], forKey: "height_requirement") let types = Set(fetchFromCoreData("Type", ids: POIDictionary["types"] as! [Int])) managedPOI.setValue(types, forKey: "types") let details = Set(fetchFromCoreData("Detail", ids: POIDictionary["details"] as! [Int])) managedPOI.setValue(details, forKey: "details") saveToCoreData() } } private func parseFavoritedPOIs(jsonObject: [String: AnyObject]) { guard let FavoritedPOIsArray = jsonObject["favoritedPOIs"] as? [[String: AnyObject]] else { print("Data parser: POIs data not recieved or malformed") return } for FavoritedPOIDictionary in FavoritedPOIsArray { guard let managedFavoritedPOI = createManagedObject("FavoritedPOI") else { return } managedFavoritedPOI.setValue(FavoritedPOIDictionary["id"], forKey: "id") managedFavoritedPOI.setValue(FavoritedPOIDictionary["complete"], forKey: "complete") let poi_favorited = fetchFromCoreData("POI", id: FavoritedPOIDictionary["poi_favorited"] as! Int) managedFavoritedPOI.setValue(poi_favorited, forKey: "poi_favorited") saveToCoreData() } } private func parseUsers(jsonObject: [String: AnyObject]) { guard let UsersArray = jsonObject["users"] as? [[String: AnyObject]] else { print("Data parser: Users data not recieved or malformed") return } for userDictionary in UsersArray { guard let managedUser = createManagedObject("User") else { return } managedUser.setValue(userDictionary["id"], forKey: "id") managedUser.setValue(userDictionary["device_id"], forKey: "device_id") managedUser.setValue(userDictionary["email"], forKey: "email") managedUser.setValue(userDictionary["first_name"], forKey: "first_name") managedUser.setValue(userDictionary["last_name"], forKey: "last_name") managedUser.setValue(userDictionary["phone_number"], forKey: "phone_number") managedUser.setValue(userDictionary["picture_url"], forKey: "picture_url") managedUser.setValue(userDictionary["current_location_x"], forKey: "current_location_x") managedUser.setValue(userDictionary["current_location_y"], forKey: "current_location_y") let challengesCompleted = Set(fetchFromCoreData("Challenge", ids: userDictionary["challenges_completed"] as! [Int])) managedUser.setValue(challengesCompleted, forKey: "challenges_completed") let tasksCompleted = Set(fetchFromCoreData("ChallengeTask", ids: userDictionary["tasks_completed"] as! [Int])) managedUser.setValue(tasksCompleted, forKey: "tasks_completed") let notificationsRecieved = Set(fetchFromCoreData("Notification", ids: userDictionary["notifications_recieved"] as! [Int])) managedUser.setValue(notificationsRecieved, forKey: "notifications_recieved") let group = fetchFromCoreData("Group", id: userDictionary["group"] as! Int) managedUser.setValue(group, forKey: "group") let favorites = Set(fetchFromCoreData("FavoritedPOI", ids: userDictionary["favorites"] as! [Int])) managedUser.setValue(favorites, forKey: "favorites") saveToCoreData() } } private func parseInvitations(jsonObject: [String: AnyObject]) { guard let invitationsArray = jsonObject["invitations"] as? [[String: AnyObject]] else { print("Data parser: Invitations data not recieved or malformed") return } for invitationDictionary in invitationsArray { guard let managedInvitation = createManagedObject("Invitation"), let epochTimeSent = invitationDictionary["timestamp_sent"] as? NSTimeInterval, let epochTimeToMeet = invitationDictionary["timestamp_to_meet"] as? NSTimeInterval, let senderId = invitationDictionary["sender"] as? Int, let locationId = invitationDictionary["location"] as? Int else { return } managedInvitation.setValue(invitationDictionary["id"], forKey: "id") managedInvitation.setValue(NSDate(timeIntervalSince1970: epochTimeSent) , forKey: "timestamp_sent") managedInvitation.setValue(NSDate(timeIntervalSince1970: epochTimeToMeet) , forKey: "timestamp_to_meet") guard let location = fetchFromCoreData("POI", id: locationId) else { return } managedInvitation.setValue(location, forKey: "location") guard let sender = fetchFromCoreData("User", id: senderId) else { return } managedInvitation.setValue(sender, forKey: "sender") let recipients = Set(fetchFromCoreData("User", ids: invitationDictionary["recipients"] as! [Int])) managedInvitation.setValue(recipients, forKey: "recipients") saveToCoreData() } } private func parseAds(jsonObject: [String: AnyObject]) { guard let adsArray = jsonObject["ads"] as? [[String: AnyObject]] else { print("Data parser: Ads data not recieved or malformed") return } for adDictionary in adsArray { guard let managedAd = createManagedObject("Ad") else { return } managedAd.setValue(adDictionary["id"], forKeyPath: "id") managedAd.setValue(adDictionary["name"], forKeyPath: "name") managedAd.setValue(adDictionary["thumbnail_url"], forKeyPath: "thumbnail_url") managedAd.setValue(adDictionary["details"], forKeyPath: "details") saveToCoreData() } } }
// components/classic/music/index.js import {classicBeh} from '../classic-beh' const mMgr = wx.getBackgroundAudioManager() Component({ /** * 组件的属性列表 */ behaviors: [classicBeh], properties: { src:String, content: String }, /** * 组件的初始数据 */ data: { playing:false, pauseSrc: 'images/[email protected]', playSrc: 'images/[email protected]', }, attached:function() { this._recoverStatus() this._monitorSwitch() }, //组件销毁生命周期函数 detached:function() { //mMgr.stop() }, /** * 组件的方法列表 */ methods: { onPlay:function(event) { if(!this.data.playing){ this.setData({ playing: true }) mMgr.title = this.properties.src mMgr.src = this.properties.src }else { this.setData({ playing: false }) mMgr.pause() } }, _recoverStatus:function() { if(mMgr.paused){ this.setData({ playing:false }) return } if(mMgr.src === this.properties.src){ this.setData({ playing:true }) } }, _monitorSwitch:function(){ //播放音乐 mMgr.onPlay(() => { this._recoverStatus() }) //暂停音乐 mMgr.onPause(() => { this._recoverStatus() }) //关闭音乐 mMgr.onStop(() => { this._recoverStatus() }) //一首音乐自动播放完成 mMgr.onEnded(() => { this._recoverStatus() }) } } })
<section class="hero-is-info"> <h1>新規登録画面</h1> </section> <div class="column is-5"> <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <%= render "devise/shared/error_messages", resource: resource %> <div class="field"> <%= f.label :username, class: "label" %> <p class="control-has-icons-left"> <%= f.text_field :name, autofocus: true, autocomplete: "email", :placeholder => "name", class: "input" %> <span class="icon is-small is-left"> <i class="fas fa-user"></i> </span> </p> </div> <div class="field"> <%= f.label :email, class: "label" %> <p class="control-has-icons-left"> <%= f.email_field :email, autofocus: true, autocomplete: "email", :placeholder => "email", class: "input" %> <span class="icon is-small is-left"> <i class="fas fa-envelope"></i> </span> </p> </div> <div class="field"> <%= f.label :password, class: "label" %> <% if @minimum_password_length %> <em>(<%= @minimum_password_length %> 文字以上)</em> <% end %> <p class="control-has-icons-left"> <%= f.password_field :password, autocomplete: "new-password", :placeholder => "password", class: "input" %> <span class="icon is-small is-left"> <i class="fas fa-lock"></i> </span> </p> </div> <div class="field"> <%= f.label :password_confirmation, class: "label" %> <p class="control-has-icons-left"> <%= f.password_field :password_confirmation, autocomplete: "new-password", :placeholder => "password confirmation", class: "input" %> <span class="icon is-small is-left"> <i class="fas fa-lock"></i> </span> </p> </div> <div class="actions"> <%= f.submit "新規登録", class: "button is-success", id: "newaccount"%> </div> <% end %> <%#= render "devise/shared/links" %> </div>
<h1>{{getTitle()}}</h1> <div class="alert alert-danger" role="alert" *ngIf="errorMessage"> {{errorMessage}} </div> <!--<div class="alert alert-warning" role="warning"> <p>Form Status: {{ listForm.status }}</p> </div>--> <form (ngSubmit)="onSubmit()" [formGroup]="listForm"> <div class="form-group"> <label for="name">Name</label> <input [(ngModel)]="name" type="text" class="form-control" id="name" name="name" placeholder="Name" formControlName="name" minlength="2"> </div> <div class="form-group"> <label for="backgroundColor">Color</label> <div style="display:flex"> <ngx-colors ngx-colors-trigger formControlName="color" [(ngModel)]="backgroundColor" [palette]="colorPalette"></ngx-colors> <div class="form-control ml-3">{{backgroundColor}}</div> </div> </div> <div class="form-group"> <label for="textColor">Text color</label> <div style="display:flex"> <ngx-colors ngx-colors-trigger formControlName="textcolor" [(ngModel)]="textColor" [palette]="colorPalette"></ngx-colors> <div class="form-control ml-3">{{textColor}}</div> </div> </div> <h2>Preview:</h2> <div class="list-example"> <div class="col-lg-4 col-md-6 col-xs-12 list mb-3 pb-3" [ngStyle]="colors(backgroundColor, textColor)"> <div class="row my-3 align-items-center justify-content-around px-3" > <h1 class="col-8 m-0">{{name}}</h1> <button type="button" class="btn btn-success col-auto"><i class="fas fa-edit"></i></button> <button type="button" class="btn btn-danger col-auto"><i class="far fa-trash-alt"></i></button> </div> <div class="items"> <label> <span> <strong>Item 1</strong><span> - a short description</span> <small class="d-block text-muted"> <svg class="bi me-1" width="1em" height="1em"> <use xlink:href="#calendar-event"></use> </svg> date </small> </span> </label> </div> <div class="items"> <label> <span> <strong>Item 1</strong><span> - a short description</span> <small class="d-block text-muted"> <svg class="bi me-1" width="1em" height="1em"> <use xlink:href="#calendar-event"></use> </svg> date </small> </span> </label> </div> <div class="items"> <label> <span> <strong>Item 1</strong><span> - a short description</span> <small class="d-block text-muted"> <svg class="bi me-1" width="1em" height="1em"> <use xlink:href="#calendar-event"></use> </svg> date </small> </span> </label> </div> </div> </div> <button type="submit" class="btn btn-primary" *ngIf="isAdd" [disabled]="!listForm.valid || isSubmitted">Add new list</button> <button type="submit" class="btn btn-primary" *ngIf="isEdit" [disabled]="!listForm.valid || isSubmitted">Save</button> </form>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/content" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:focusableInTouchMode="true"> <include layout="@layout/toolbar_progress"/> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white"> <LinearLayout android:id="@+id/content_input" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:orientation="vertical"> <com.devabit.takestock.ui.widget.CircleImageView android:id="@+id/profile_image_view" android:layout_width="96dp" android:layout_height="96dp" android:layout_gravity="center" android:src="@drawable/ic_placeholder_user_96dp" app:civ_border_width="2dp" app:civ_border_color="@color/colorPrimary" app:civ_edit_icon="@drawable/ic_edit_circle_purple_dark_24dp"/> <android.support.design.widget.TextInputLayout android:id="@+id/user_name_input_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp"> <android.support.design.widget.TextInputEditText android:id="@+id/user_name_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/profile_editor_activity_user_name" android:enabled="false" android:imeOptions="actionNext" android:inputType="textCapSentences" android:maxLength="30" android:paddingStart="8dp" android:paddingEnd="8dp"/> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/email_input_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"> <android.support.design.widget.TextInputEditText android:id="@+id/email_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:enabled="false" android:hint="@string/profile_editor_activity_email" android:imeOptions="actionNext" android:inputType="textEmailAddress" android:paddingStart="8dp" android:paddingEnd="8dp"/> </android.support.design.widget.TextInputLayout> <CheckBox android:id="@+id/email_subscription_check_box" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:textAppearance="@android:style/TextAppearance.Small" android:text="@string/profile_editor_activity_email_subscription" android:textColor="@color/grey_600"/> <android.support.design.widget.TextInputLayout android:id="@+id/password_input_layout" android:layout_width="match_parent" android:layout_height="wrap_content" app:passwordToggleEnabled="false" android:layout_marginTop="16dp"> <android.support.design.widget.TextInputEditText android:id="@+id/password_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/profile_editor_activity_password" android:inputType="textPassword" android:focusable="false" android:clickable="true" android:paddingStart="8dp" android:paddingEnd="8dp"/> </android.support.design.widget.TextInputLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="@string/my_business" android:textAppearance="@style/TextAppearance.Small.AllCaps.Gold"/> <android.support.design.widget.TextInputLayout android:id="@+id/business_name_input_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"> <android.support.design.widget.TextInputEditText android:id="@+id/business_name_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/business_name" android:imeOptions="actionNext" android:inputType="textCapSentences" android:paddingStart="8dp" android:paddingEnd="8dp"/> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/postcode_input_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"> <android.support.design.widget.TextInputEditText android:id="@+id/postcode_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/postcode" android:imeOptions="actionNext" android:inputType="text" android:maxLength="10" android:paddingStart="8dp" android:paddingEnd="8dp"/> </android.support.design.widget.TextInputLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:paddingStart="8dp" android:paddingEnd="8dp" android:textAppearance="@android:style/TextAppearance.Small" android:text="@string/type_of_business" style="@style/TextViewGrey" android:id="@+id/textView"/> <Spinner android:id="@+id/business_type_spinner" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:background="@null" tools:listitem="@layout/item_spinner"/> <TextView android:id="@+id/business_subtype_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:paddingStart="8dp" android:paddingEnd="8dp" android:textAppearance="@android:style/TextAppearance.Small" android:text="@string/business_subtype" style="@style/TextViewGrey"/> <Spinner android:id="@+id/business_subtype_spinner" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:background="@null" tools:listitem="@layout/item_spinner"/> <android.support.design.widget.TextInputLayout android:id="@+id/vat_number_input_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"> <android.support.design.widget.TextInputEditText android:id="@+id/vat_number_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/vat_number" android:imeOptions="actionNext" android:inputType="number" android:maxLength="10" android:paddingStart="8dp" android:paddingEnd="8dp"/> </android.support.design.widget.TextInputLayout> </LinearLayout> </ScrollView> </LinearLayout>
import axios, {AxiosError} from '../../src/index' import NProgress from 'nprogress' import 'nprogress/nprogress.css' import qs from 'qs' /* document.cookie= 'a=1' const instance = axios.create({ xsrfCookieName: 'XSRF-TOKEN-D', xsrfHeaderName: 'X-XSRF-TOKEN-D' }) instance.get('/more/get').then(res => { console.log(res) }) */ /* const instance = axios.create() function calculatePercentage (loaded:number,total:number) { return Math.floor(loaded * 1.0) / total } function loadProgressBar (){ const setupStartProgress = () =>{ instance.interceptors.request.use(config=>{ NProgress.start() return config }) } const setUpdateProgress = () =>{ const update = (e:ProgressEvent)=>{ console.log(e) NProgress.set(calculatePercentage(e.loaded,e.total)) } instance.defaults.onDownloadProgress = update instance.defaults.onUploadProgress = update } const setupStopProgress = () => { instance.interceptors.response.use(response=>{ NProgress.done() return response },error=>{ NProgress.done() return Promise.reject(error) }) } setupStartProgress() setUpdateProgress() setupStopProgress() } loadProgressBar() const downloadEl = document.getElementById('download') downloadEl!.addEventListener('click', e => { instance.get('https://img.mukewang.com/5cc01a7b0001a33718720632.jpg') }) const uploadEl = document.getElementById('upload') uploadEl!.addEventListener('click', e => { const data = new FormData() const fileEl = document.getElementById('file') as HTMLInputElement if (fileEl.files) { data.append('file', fileEl.files[0]) instance.post('/more/upload', data) } }) */ /* axios.post('/more/post',{ a:1 },{ auth:{ username:'George', password:'gg520' } }).then(res=>{ console.log(res) }) */ /*axios.get('/more/304').then(res=>{ console.log(res) }).catch((e: AxiosError)=>{ console.log(e.message) }) axios.get('/more/304',{ validateStatus(status){ return status>=200 &&status<400 } }).then(res=>{ console.log(res) })*/ /*axios.get('/more/get', {params: new URLSearchParams('a=b&c=d')}).then(res => console.log(res)) axios.get('/more/get', {params: {a: 1, b: 2, c: [1, 3, 4, 5]}}).then(res => console.log(res)) const instance = axios.create({ paramsSerializer(params) { return qs.stringify(params, {arrayFormat: 'brackets'}) } }) instance.get('/more/get', {params: {a: 1, b: 2, c: [1, 3, 4, 5]}}).then(res => console.log(res))*/ /* const instance = axios.create({ baseURL: 'https://img.mukewang.com/' }) instance.get('5cc01a7b0001a33718720632.jpg') instance.get('https://img.mukewang.com/szimg/5becd5ad0001b89306000338-360-202.jpg') */ function getA() { return axios.get('/more/A') } function getB() { return axios.get('/more/B') } axios.all([getA(), getB()]) .then(axios.spread(function(resA, resB) { console.log(resA.data) console.log(resB.data) })) axios.all([getA(), getB()]) .then(([resA, resB]) => { console.log(resA.data) console.log(resB.data) }) const fakeConfig = { baseURL: 'https://www.baidu.com/', url: '/user/12345', params: { idClient: 1, idTest: 2, testString: 'thisIsATest' } } console.log(axios.getUri(fakeConfig))
= Define a Function that Flattens Data in a List ifndef::env-site,env-github[] include::_attributes.adoc[] endif::[] :keywords: studio, anypoint, transform, transformer, format, aggregate, rename, split, filter convert, xml, json, csv, pojo, java object, metadata, dataweave, data weave, datamapper, dwl, dfl, dw, output structure, input structure, map, mapping When presented with nested structures of data, you might need to reduce (or "flatten") the data in them to produce a simpler output. //LINK TO DW 1.0 EXAMPLES: include::partial$dataweave1-links.adoc[tag=dataweave1Examples] This DataWeave example flattens the data in the `interests` and `contenttypes` arrays with the function that is defined in the header, and it only outputs `contenttypes` when it is not empty. The example uses these functions: * `map` to go through a set elements in the input. * `reduce` to flatten the arrays. * `if` to conditionally display a field. * `splitBy` to parse the input. [[ex01]] .DataWeave Script: [source,dataweave,linenums] ---- include::partial$cookbook-dw/define-function-to-flatten-list/transform.dwl[] ---- .Input JSON Payload: [source,json,linenums] ---- include::partial$cookbook-dw/define-function-to-flatten-list/inputs/payload.json[] ---- .Output [source,json,linenums] ---- include::partial$cookbook-dw/define-function-to-flatten-list/out.json[] ---- == Related Examples * xref:dataweave-cookbook-use-constant-directives.adoc[Use Constant Directives] * xref:dataweave-cookbook-conditional-list-reduction-via-function.adoc[Conditionally Reduce a List through a Function] * xref:dataweave-cookbook-define-a-custom-addition-function.adoc[Define a Custom Addition Function] * xref:dataweave-cookbook-pass-functions-as-arguments.adoc[Pass Functions as Arguments] == See Also * xref:dataweave-selectors.adoc[DataWeave Selectors] * xref:dataweave-cookbook.adoc[DataWeave Cookbook]
import { Injectable } from '@nestjs/common'; import { Prisma } from '@prisma/client'; import { CreateRouteDTO } from '../dto/route.create.dto'; import { FindRouteDTO } from '../dto/route.find.dto'; import { FindOneRouteDTO } from '../dto/route.findone.dto'; import { UpdateRouteDTO } from '../dto/route.update.dto'; import { Route } from '../types'; @Injectable() export class RouteMapper { public fromRouteToRouteCreateInput( route: CreateRouteDTO, userId: string, ): Prisma.RouteCreateInput { const mappedPoints = this.mapPointsToConnectArray(route.points); const mappedCategories = this.mapCategoriesToConnectArray(route.categories); if (route.images !== undefined) { const mappedImages = this.mapImagesToConnectArray(route.images); return { name: route.name, description: route.description, short_description: route.short_description, user: { connect: { id: userId } }, points: { connect: mappedPoints }, images: { connect: mappedImages }, categories: { connect: mappedCategories }, country: { connect: { id: route.country } }, }; } return { name: route.name, description: route.description, short_description: route.short_description, user: { connect: { id: userId } }, points: { connect: mappedPoints }, categories: { connect: mappedCategories }, country: { connect: { id: route.country } }, }; } public fromAdminRouteToRouteCreateInput( route: CreateRouteDTO, userId: string, ): Prisma.RouteCreateInput { const mappedPoints = this.mapPointsToConnectArray(route.points); const mappedCategories = this.mapCategoriesToConnectArray(route.categories); if (route.images !== undefined) { const mappedImages = this.mapImagesToConnectArray(route.images); return { name: route.name, description: route.description, short_description: route.short_description, user: { connect: { id: '1a225a3c-ef37-455e-abe5-475ac664a6c2' } }, points: { connect: mappedPoints }, images: { connect: mappedImages }, categories: { connect: mappedCategories }, country: { connect: { id: route.country } }, }; } return { name: route.name, description: route.description, short_description: route.short_description, user: { connect: { id: '1a225a3c-ef37-455e-abe5-475ac664a6c2' } }, points: { connect: mappedPoints }, categories: { connect: mappedCategories }, country: { connect: { id: route.country } }, }; } public fromRouteFindToRouteFindArgs( params: FindRouteDTO, ): Prisma.RouteFindManyArgs { return { take: params.take, skip: params.skip, orderBy: params.orderBy, include: params.include, where: params.where, }; } public fromOneRouteFindToRouteFindArgs( routeId: string, params: FindOneRouteDTO, ): Prisma.RouteFindFirstArgs { return { where: { id: routeId }, include: params.include, }; } public fromRouteUpdateToRouteUpdateInput( route: UpdateRouteDTO, ): Prisma.RouteUpdateInput { return { name: route.name, description: route.description, short_description: route.short_description, }; } public isolateUserData(findResult: Route[]) { return this.mapUserDataInFindResult(findResult); } public convertUsersToEmails(followers) { return followers.map((follower) => { return follower.follower.email; }); } private mapUserDataInFindResult(findResult: Route[]) { return findResult.map( (item) => (item = { ...item, user: { id: item.user.id, email: item.user.email, role: item.user.role, }, }), ); } private mapPointsToConnectArray(pointsArray: Array<string>) { return pointsArray.map((item) => ({ id: item })); } private mapImagesToConnectArray(imagesArray: string[]) { return imagesArray.map((image) => ({ id: image })); } private mapCategoriesToConnectArray(categoriesArray: string[]) { return categoriesArray.map((category) => ({ id: category })); } }
package com.dsceltic.mvisample.feature import com.dsceltic.mvisample.base.ViewEvent import com.dsceltic.mvisample.base.ViewSideEffect import com.dsceltic.mvisample.base.ViewState class OrderSummaryContract { sealed class Event: ViewEvent { data class setQuantity(val quantity: Int) : Event() data class setFlavor(val flavor: String) : Event() data class setDate(val date: String) : Event() object reset : Event() object onBackPress : Event() } data class State( val quantity: Int, val flavor: String, val date: String, val price: String, val pickupOptions: List<String> ) : ViewState sealed class Effect: ViewSideEffect { sealed class Navigation: Effect(){ object Back : Navigation() } } }
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package br.com.softsaj.configuration.controller; import java.net.URI; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import br.com.softsaj.configuration.models.Anuncio; import br.com.softsaj.configuration.models.Cor; import br.com.softsaj.configuration.services.AnuncioService; /** * * @author Marcos */ @CrossOrigin("http://localhost:4200") @RestController @RequestMapping("/anuncios") public class AnuncioController { @Autowired private AnuncioService vs; @GetMapping public ResponseEntity<List<Anuncio>> getAll() { List<Anuncio> movies = vs.findAll(); return new ResponseEntity<>(movies, HttpStatus.OK); } //GEt Anuncio @GetMapping("/Anuncio/{id}") public ResponseEntity<?> getCienfiloById (@PathVariable("id") Long id ,@RequestParam("token") String token) { Anuncio Anuncio = null; try { Anuncio = vs.findAnuncioById(id); } catch (Exception e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_GATEWAY); } return new ResponseEntity<>(Anuncio, HttpStatus.OK); } @GetMapping("/Anuncio/usuario/{email}") public ResponseEntity<List<Anuncio>> findByEmail (@PathVariable("email") String email ,@RequestParam("token") String token) { List<Anuncio> movies = vs.findByEmail(email); return new ResponseEntity<>(movies, HttpStatus.OK); } @PostMapping("/Anuncio/add") public ResponseEntity<Anuncio> addAnuncio(@RequestBody Anuncio movie, @RequestParam("token") String token) { Anuncio Anuncio = new Anuncio(); if(vs.Exists(movie.getVendedor())) { try { Anuncio newAnuncio = vs.findAnuncioById(movie.getId()); newAnuncio.setTitulo(movie.getTitulo()); newAnuncio.setSubtitulo(movie.getSubtitulo()); Anuncio = vs.addAnuncio(newAnuncio); }catch(Exception e) { } }else { Anuncio = vs.addAnuncio(movie); } URI uri = ServletUriComponentsBuilder. fromCurrentRequest().path("/Anuncio/{id}").buildAndExpand(movie.getId()).toUri(); return new ResponseEntity<>(Anuncio, HttpStatus.CREATED); } //Update nome,telefone,idade,foto; @PutMapping("/Anuncio/update/{id}") public ResponseEntity<Anuncio> updateAnuncio(@PathVariable("id") Long id, @RequestBody Anuncio newAnuncio ,@RequestParam("token") String token) throws Exception { Anuncio Anuncio = vs.findAnuncioById(id); //Anuncio.setNome(newAnuncio.getNome()); //c//inefilo.setTelefone(newAnuncio.getTelefone()); //Anuncio.setIdade(newAnuncio.getIdade()); //Anuncio.setFoto(newAnuncio.getFoto()); Anuncio updateAnuncio = vs.updateAnuncio(Anuncio);//s return new ResponseEntity<>(updateAnuncio, HttpStatus.OK); } @Transactional @DeleteMapping("/delete/{id}") public ResponseEntity<?> deleteAnuncio(@PathVariable("id") Long id ,@RequestParam("token") String token) { vs.deleteAnuncio(id); return new ResponseEntity<>(HttpStatus.OK); } }
import CustomImage from "@/components/Image"; import { useGetPokemonByID } from "@/service/pokemon-api"; import { Col, Row } from "antd"; import Table, { ColumnsType } from "antd/es/table"; import { useEffect, useState } from "react"; import { useLocation } from "react-router-dom"; interface DataType { key: React.Key; hight: number; weight: number; hp: number; attack: number; defense: number; speed: number; types: any[]; abilities: any[]; } const Detail = () => { const location = useLocation(); const idPath: any = location?.state; const pokemonDetail = useGetPokemonByID(idPath); const [dataSource, setDataSource] = useState<any[]>([]); const url = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${idPath}.png`; useEffect(() => { const stats = pokemonDetail?.data?.stats?.reduce((perv: any, curr: any) => { return { ...perv, [curr.stat.name]: curr.base_stat }; }, {}); setDataSource([ { key: idPath, height: pokemonDetail?.data?.height || 0, weight: pokemonDetail?.data?.weight || 0, hp: stats?.hp, attack: stats?.attack, defense: stats?.defense, speed: stats?.speed, types: pokemonDetail?.data?.types || [], abilities: pokemonDetail?.data?.abilities || [], }, ]); }, [pokemonDetail?.data]); const columns: ColumnsType<DataType> = [ { title: "Hight", dataIndex: "height", fixed: "left", }, { title: "Weight", dataIndex: "weight", fixed: "left", }, { title: "HP", dataIndex: "hp", fixed: "left", }, { title: "Attack", dataIndex: "attack", fixed: "left", }, { title: "Defense", dataIndex: "defense", fixed: "left", }, { title: "Speed", dataIndex: "speed", fixed: "left", }, { title: "Type", dataIndex: "types", fixed: "left", render: (data: any[]) => { return data?.map((item) => { return <Col key={item?.type?.name}>{item?.type?.name}</Col>; }); }, }, { title: "Abilities", dataIndex: "abilities", fixed: "left", render: (data: any[]) => { return data?.map((item) => { return <Col key={item?.ability?.name}>{item?.ability?.name}</Col>; }); }, }, ]; return ( <div> <div style={{ height: "200px", width: "auto" }}> <CustomImage src={url} /> </div> <h1> {pokemonDetail?.data?.name}</h1> <Row gutter={[12, 12]} justify={"center"} style={{ marginTop: "50px" }}> <Col> <Row> <Col span={12} offset={6}> <Row gutter={[6, 6]} justify={"center"}> <Table columns={columns} dataSource={dataSource} bordered size="middle" scroll={{ x: "calc(700px + 20%)" }} pagination={false} /> </Row> </Col> </Row> </Col> </Row> </div> ); }; export default Detail;
package com.yc.mysql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 帮助访问数据库 */ public class DBHelper { //因为静态块在整个程序运行时,只运行一次,而且是在程序加载到虚拟机的时候 static { try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 执行增删改 * @param sql * @param params * @return * @throws SQLException */ public int doUpdate(String sql,List<Object> params) throws SQLException{ Connection con=getCon(); PreparedStatement stmt=con.prepareStatement(sql); if(params!=null && params.size()>0){ for(int i=0;i<params.size();i++){ stmt.setString(i+1, params.get(i).toString()); } } int r=stmt.executeUpdate(); closeAll(null,stmt,con); return r; } /** * 获取与数据库的链接 * @return * @throws SQLException */ public Connection getCon() throws SQLException{ Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","study40","a"); return con; } /** * 关闭与数据库的链接 * @param rs * @param pstmt * @param con */ public void closeAll(ResultSet rs,PreparedStatement pstmt,Connection con){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(pstmt!=null){ try { pstmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(con!=null){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 统计查询 * @param sql * @param params * @return * @throws SQLException */ public double selectFunc(String sql,List<Object> params) throws SQLException{ double result=0; Connection con=getCon(); PreparedStatement stmt=con.prepareStatement(sql); if(params!=null && params.size()>0){ for(int i=0;i<params.size();i++){ stmt.setString(i+1, params.get(i).toString()); } } ResultSet rs=stmt.executeQuery(); if(rs.next()){ result=rs.getDouble(1); } closeAll(rs,stmt,con); return result; } /** * 通用的查询,查询的结果为 List<Map<String,String>> <br/> * Map<String,String>对应的一条数据 <br/> * @param sql * @param params * @return * @throws SQLException */ public List<Map<String,String>> select(String sql,List<Object> params) throws SQLException{ List<Map<String,String>> list=new ArrayList<Map<String,String>>(); Connection con=getCon(); PreparedStatement stmt=con.prepareStatement(sql); if(params!=null && params.size()>0){ for(int i=0;i<params.size();i++){ stmt.setString(i+1, params.get(i).toString()); } } ResultSet rs=stmt.executeQuery(); ResultSetMetaData rsmd=rs.getMetaData(); //通过元数据来知道有多少列 int cc=rsmd.getColumnCount(); List<String> columnNames=new ArrayList<String>(); for(int i=0;i<cc;i++){ String cn=rsmd.getColumnName(i+1); columnNames.add(cn); //存好列名 } //循环所有的结果集记录 while(rs.next()){ //每一条数据就是一个Map对象 Map<String,String> map=new HashMap<String,String>(); //循环每条记录所有的列名 for(int i=0;i<columnNames.size();i++){ String cn=columnNames.get(i); //列名 String value=rs.getString(cn); //根据列名取值 map.put(cn, value); //存到map中, 键(列名) 值(值) } list.add(map); } closeAll(rs,stmt,con); return list; } }
from tensorflow import keras import tensorflow as tf import pickle import os import numpy as np def make_transfer_module(model): model2 = keras.Sequential() model2.add(keras.layers.Conv1D(256, 3, weights=model.layers[0].get_weights(), activation=tf.nn.relu, trainable=False)) model2.add(keras.layers.Conv1D(128, 9, activation=tf.nn.relu, weights=model.layers[1].get_weights(), trainable=False)) model2.add(keras.layers.Flatten()) model2.add(keras.layers.Dense(256, activation=tf.nn.relu, weights=model.layers[3].get_weights(), trainable=False)) return model2 def make_none_marked_model(model_base): model = keras.Sequential() model.add(model_base) model.add(keras.layers.Dense(64, activation=tf.nn.relu)) model.add(keras.layers.Dense(2, activation=tf.nn.softmax)) model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) return model def make_train_array(fold_ind, nim_fold, basedir, samps_prefix, cvorder): """ Generates an array of samples for training from within the training set. Recall that in this case, the order of samples loaded in the with statement below follows cvorder. :param fold_ind: index of the fold to consider :param nim_fold: number of images available for verification per fold :param basedir: directory containing an array of samples for transfer training :param samps_prefix: the prefix used in sample file names """ with open(os.path.join(basedir, samps_prefix + str(fold_ind) + '.p'), 'rb') as f: train_array = pickle.load(f) tr = [] tr_labs = [] for t_ind in range(len(train_array)): if t_ind not in range(fold_ind * nim_fold, (fold_ind + 1) * nim_fold): tr.extend(train_array[t_ind]) mark_ind, im_ind = fcn_mark_im_ind(cvorder[t_ind], 30) if mark_ind == 2: lab = 0 else: lab = 1 tr_labs.extend([lab for _ in range(len(train_array[t_ind]))]) return tr, tr_labs, train_array def fcn_mark_im_ind(im_ind_raw, n_img): """ Calculates the mark an image index based on the total image index For example, im_ind_raw is 52 and n_img is 30, then mark_ind is 1 and im_ind is 22 """ mark_ind = int(im_ind_raw/n_img) im_ind = im_ind_raw - mark_ind * n_img return mark_ind, im_ind def make_trained_transfer_nets(pdir, model_prefix, nim_fold, sampledir, samps_prefix, cvorder, dirout): """ Iterates across each fold, generates an updated binary network and saves the new network :param pdir: Directory containing trained binary models :param model_prefix: Prefix used to name pretrained binary model files :param nim_fold: number of images available for verification per fold :param sampledir: directory containing an array of samples for transfer training :param samps_prefix: the prefix used in sample file names :param cvorder: order of images called for cross validation :param dirout: directory in which to save retrained models """ fmod_name_base = os.path.join(pdir, model_prefix) tf.config.run_functions_eagerly(True) if nim_fold == 0: n_fold = 1 else: n_fold = int(cvorder / nim_fold) for fold_ind in range(n_fold): print("Currently evaluating fold number {}".format(fold_ind)) mod = keras.models.load_model(fmod_name_base + str(fold_ind) + '.h5', compile=False) temp_model = make_transfer_module(mod) tr, tr_labs, train_array = make_train_array(fold_ind, nim_fold, sampledir, samps_prefix, cvorder) # tr consists of samples selected by the classification network # we now pad those samples so that half of the total samples are unmarked while np.mean(tr_labs) > 0.5: none_im_ind = np.random.randint(0, 30) # This makes sure that none samples are not drawn from the validation set while none_im_ind + 60 in cvorder[fold_ind * nim_fold:(fold_ind + 1) * nim_fold]: none_im_ind = np.random.randint(0, 30) tr_ind = np.where(cvorder == none_im_ind + 60)[0][0] tr.extend(train_array[tr_ind]) tr_labs.extend([0 for _ in range(len(train_array[tr_ind]))]) tr = np.array(tr) tr_labs = np.array(tr_labs, dtype=int) nm_model = make_none_marked_model(temp_model) history = nm_model.fit(np.expand_dims(tr, axis=2), tr_labs, epochs=10) nm_model.save(os.path.join(dirout, 'binarynet_' + str(fold_ind) + '.h5')) with open(os.path.join(dirout, 'binaryhist_' + str(fold_ind) + '.h5'), 'wb') as f: pickle.dump(history.history, f)
<?php session_start(); include "messages.php"; ?> <?php include "header.php"; ?> <?php include "conn.php"; // Fetch farmers with pending fertilizer applications $query = "SELECT a.firstname, a.lastname, f.amount, f.created_at, f.delivered FROM authentication a INNER JOIN fertilizer f ON a.grower_no = f.grower_no WHERE f.delivered = 'Yes'"; $result = mysqli_query($conn, $query); // Check if the query was successful if ($result) { // Initialize an empty array to store the farmers $farmers = array(); // Fetch each row and add it to the farmers array while ($row = mysqli_fetch_assoc($result)) { $farmers[] = $row; } // Free the result set mysqli_free_result($result); } else { // Query execution failed $farmers = array(); // Set an empty array if no farmers found or an error occurred } // Close the database connection $conn->close(); ?> <body> <!-- Preloader - style you can find in spinners.css --> <div class="preloader"> <div class="lds-ripple"> <div class="lds-pos"></div> <div class="lds-pos"></div> </div> </div> <!-- Main wrapper - style you can find in pages.scss --> <div id="main-wrapper" data-layout="vertical" data-navbarbg="skin5" data-sidebartype="full" data-sidebar-position="absolute" data-header-position="absolute" data-boxed-layout="full"> <?php include "navbar.php"; ?> <?php include "sidebar_admin.php"; ?> <div class="page-wrapper"> <!-- Bread crumb and right sidebar toggle --> <div class="page-breadcrumb"> <div class="row align-items-center"> <div class="col-md-6 col-8 align-self-center"> <h3 class="page-title mb-0 p-0">Delivered Fertilizer Applications</h3> <?php $messages = get_messages(); foreach ($messages as $message) { echo '<div class="alert alert-' . $message['type'] . '">' . $message['message'] . '</div>'; } ?> <div class="d-flex align-items-center"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="./dashboard_admin.php">Home</a></li> <li class="breadcrumb-item active" aria-current="page">Pending Fertilizer Applications</li> </ol> </nav> </div> </div> </div> </div> <div class="container-fluid"> <!-- Start Page Content --> <div class="row"> <!-- column --> <div class="col-sm-12"> <div class="card"> <div class="card-body"> <h4 class="card-title">Farmers with Pending Fertilizer Applications</h4> <h6 class="card-subtitle"></h6> <div class="table-responsive"> <table class="table user-table no-wrap" id="recordtable"> <thead> <tr> <th class="border-top-0">#</th> <th class="border-top-0">Firstname</th> <th class="border-top-0">Lastname</th> <th class="border-top-0">Quantity</th> <!-- <th class="border-top-0">No of Bags</th> --> <th class="border-top-0">Date Applied</th> </tr> </thead> <tbody> <?php $index = 1; foreach ($farmers as $farmer) { echo "<tr>"; echo "<td>{$index}</td>"; echo "<td>{$farmer['firstname']}</td>"; echo "<td>{$farmer['lastname']}</td>"; echo "<td>{$farmer['amount']}</td>"; // echo "<td>" . ($farmer['amount'] / 100) . "</td>"; echo "<td>{$farmer['created_at']}</td>"; echo "</tr>"; $index++; } ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <!-- footer --> <?php include "footer.php"; ?> </div> </div> <script src="../../assets/plugins/jquery/dist/jquery.min.js"></script> <!-- Bootstrap tether Core JavaScript --> <script src="../../assets/plugins/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="../js/app-style-switcher.js"></script> <!--Wave Effects --> <script src="../js/waves.js"></script> <!--Menu sidebar --> <script src="../js/sidebarmenu.js"></script> <!--Custom JavaScript --> <script src="../js/custom.js"></script> <script src="../../assets/plugins/datatable.js"></script> <script> $(document).ready(function () { $('[data-toggle="tooltip"]').tooltip(); }); </script> </body> </html>
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strjoin.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abassibe <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/24 15:50:47 by abassibe #+# #+# */ /* Updated: 2018/03/14 04:19:01 by abassibe ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *ft_strjoin(char const *s1, char const *s2) { char *join; int i; int j; if (!s1 || !s2 || !(join = ft_strnew((int)ft_strlen(s1) + (int)ft_strlen(s2) + 1))) return (NULL); i = 0; j = 0; while (s1[i]) { join[i] = s1[i]; i++; } while (s2[j]) { join[i + j] = s2[j]; j++; } return (join); }
package cli import ( "fmt" "strings" "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" "bitbucket.org/decimalteam/go-node/x/validator/internal/types" ) // GetQueryCmd returns the cli query commands for this module func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { // Group validator queries under a subcommand validatorQueryCmd := &cobra.Command{ Use: types.ModuleName, Short: "Querying commands for the validator module", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } validatorQueryCmd.AddCommand(flags.GetCommands( GetCmdQueryDelegation(queryRoute, cdc), GetCmdQueryDelegations(queryRoute, cdc), GetCmdQueryUnbondingDelegation(queryRoute, cdc), GetCmdQueryUnbondingDelegations(queryRoute, cdc), GetCmdQueryValidator(queryRoute, cdc), GetCmdQueryValidators(queryRoute, cdc), GetCmdQueryValidatorDelegations(queryRoute, cdc), GetCmdQueryValidatorUnbondingDelegations(queryRoute, cdc), GetCmdQueryParams(queryRoute, cdc), GetCmdQueryPool(queryRoute, cdc), GetCmdQueryDelegatedCoins(queryRoute, cdc))...) return validatorQueryCmd } // GetCmdQueryValidator implements the validator query command. func GetCmdQueryValidator(storeName string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "validator [validator-addr]", Short: "Query a validator", Long: strings.TrimSpace( fmt.Sprintf(`Query details about an individual validator. Example: $ %s query validator validator dxvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, version.ClientName, ), ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) addr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } res, _, err := cliCtx.QueryStore(types.GetValidatorKey(addr), storeName) if err != nil { return err } if len(res) == 0 { return fmt.Errorf("No validator found with address %s ", addr) } validator, err := types.UnmarshalValidator(cdc, res) if err != nil { return err } return cliCtx.PrintOutput(validator) }, } } // GetCmdQueryValidators implements the query all validators command. func GetCmdQueryValidators(storeName string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "validators", Short: "Query for all validators", Args: cobra.NoArgs, Long: strings.TrimSpace( fmt.Sprintf(`Query details about all validators on a network. Example: $ %s query validator validators `, version.ClientName, ), ), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) resKVs, _, err := cliCtx.QuerySubspace([]byte{types.ValidatorsKey}, storeName) if err != nil { return err } var validators types.Validators for _, kv := range resKVs { validator, err := types.UnmarshalValidator(cdc, kv.Value) if err != nil { return err } validators = append(validators, validator) } return cliCtx.PrintOutput(validators) }, } } // GetCmdQueryValidatorUnbondingDelegations implements the query all unbonding delegatations from a validator command. func GetCmdQueryValidatorUnbondingDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "unbonding-delegations-from [validator-addr]", Short: "Query all unbonding delegatations from a validator", Long: strings.TrimSpace( fmt.Sprintf(`Query delegations that are unbonding _from_ a validator. Example: $ %s query validator unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, version.ClientName, ), ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) valAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } bz, err := cdc.MarshalJSON(types.NewQueryValidatorParams(valAddr)) if err != nil { return err } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorUnbondingDelegations) res, _, err := cliCtx.QueryWithData(route, bz) if err != nil { return err } var ubds types.UnbondingDelegationResponse cdc.MustUnmarshalJSON(res, &ubds) return cliCtx.PrintOutput(ubds) }, } } // GetCmdQueryDelegation the query delegation command. func GetCmdQueryDelegation(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegation [delegator-addr] [validator-addr] [coin]", Short: "Query a delegation based on address and validator address", Long: strings.TrimSpace( fmt.Sprintf(`Query delegations for an individual delegator on an individual validator. Example: $ %s query validator delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, version.ClientName, ), ), Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) delAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } valAddr, err := sdk.ValAddressFromBech32(args[1]) if err != nil { return err } coin := args[2] bz, err := cdc.MarshalJSON(types.NewQueryBondsParams(delAddr, valAddr, coin)) if err != nil { return err } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegation) res, _, err := cliCtx.QueryWithData(route, bz) if err != nil { return err } var resp types.DelegationResponse if err := cdc.UnmarshalJSON(res, &resp); err != nil { return err } return cliCtx.PrintOutput(resp) }, } } // GetCmdQueryDelegations implements the command to query all the delegations // made from one delegator. func GetCmdQueryDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegations [delegator-addr]", Short: "Query all delegations made by one delegator", Long: strings.TrimSpace( fmt.Sprintf(`Query delegations for an individual delegator on all validators. Example: $ %s query validator delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p `, version.ClientName, ), ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) delAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } bz, err := cdc.MarshalJSON(types.NewQueryDelegatorParams(delAddr)) if err != nil { return err } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorDelegations) res, _, err := cliCtx.QueryWithData(route, bz) if err != nil { return err } var resp types.DelegationResponse if err := cdc.UnmarshalJSON(res, &resp); err != nil { return err } return cliCtx.PrintOutput(resp) }, } } // GetCmdQueryValidatorDelegations implements the command to query all the // delegations to a specific validator. func GetCmdQueryValidatorDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegations-to [validator-addr]", Short: "Query all delegations made to one validator", Long: strings.TrimSpace( fmt.Sprintf(`Query delegations on an individual validator. Example: $ %s query validator delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, version.ClientName, ), ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) valAddr, err := sdk.ValAddressFromBech32(args[0]) if err != nil { return err } bz, err := cdc.MarshalJSON(types.NewQueryValidatorParams(valAddr)) if err != nil { return err } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorDelegations) res, _, err := cliCtx.QueryWithData(route, bz) if err != nil { return err } var resp types.DelegationResponse if err := cdc.UnmarshalJSON(res, &resp); err != nil { return err } return cliCtx.PrintOutput(resp) }, } } // GetCmdQueryUnbondingDelegation implements the command to query a single // unbonding-delegation record. func GetCmdQueryUnbondingDelegation(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "unbonding-delegation [delegator-addr] [validator-addr]", Short: "Query an unbonding-delegation record based on delegator and validator address", Long: strings.TrimSpace( fmt.Sprintf(`Query unbonding delegations for an individual delegator on an individual validator. Example: $ %s query validator unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj `, version.ClientName, ), ), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) valAddr, err := sdk.ValAddressFromBech32(args[1]) if err != nil { return err } delAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } bz, err := cdc.MarshalJSON(types.NewQueryBondsParams(delAddr, valAddr, "")) if err != nil { return err } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryUnbondingDelegation) res, _, err := cliCtx.QueryWithData(route, bz) if err != nil { return err } var resp types.UnbondingDelegations if err := cdc.UnmarshalJSON(res, &resp); err != nil { return err } return cliCtx.PrintOutput(resp) }, } } // GetCmdQueryUnbondingDelegations implements the command to query all the // unbonding-delegation records for a delegator. func GetCmdQueryUnbondingDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "unbonding-delegations [delegator-addr]", Short: "Query all unbonding-delegations records for one delegator", Long: strings.TrimSpace( fmt.Sprintf(`Query unbonding delegations for an individual delegator. Example: $ %s query validator unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p `, version.ClientName, ), ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return err } bz, err := cdc.MarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)) if err != nil { return err } route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorUnbondingDelegations) res, _, err := cliCtx.QueryWithData(route, bz) if err != nil { return err } var ubds types.UnbondingDelegations if err = cdc.UnmarshalJSON(res, &ubds); err != nil { return err } return cliCtx.PrintOutput(ubds) }, } } // GetCmdQueryPool implements the pool query command. func GetCmdQueryPool(storeName string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "pool", Args: cobra.NoArgs, Short: "Query the current validator pool values", Long: strings.TrimSpace( fmt.Sprintf(`Query values for amounts stored in the validator pool. Example: $ %s query validator pool `, version.ClientName, ), ), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) bz, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/pool", storeName), nil) if err != nil { return err } var pool types.Pool if err := cdc.UnmarshalJSON(bz, &pool); err != nil { return err } return cliCtx.PrintOutput(pool) }, } } // GetCmdQueryParams implements the params query command. func GetCmdQueryParams(storeName string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "params", Args: cobra.NoArgs, Short: "Query the current validator parameters information", Long: strings.TrimSpace( fmt.Sprintf(`Query values set as validator parameters. Example: $ %s query validator params `, version.ClientName, ), ), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) route := fmt.Sprintf("custom/%s/%s", storeName, types.QueryParameters) bz, _, err := cliCtx.QueryWithData(route, nil) if err != nil { return err } var params types.Params cdc.MustUnmarshalJSON(bz, &params) return cliCtx.PrintOutput(params) }, } } // GetCmdQueryDelegatedCoins implements the delegated coins query command. func GetCmdQueryDelegatedCoins(storeName string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegated_coins", Args: cobra.NoArgs, Short: "Query the delegated coins", Long: strings.TrimSpace( fmt.Sprintf(`Query delegated coins. Example: $ %s query validator delegated_coins `, version.ClientName, ), ), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) route := fmt.Sprintf("custom/%s/%s", storeName, types.QueryDelegatedCoins) bz, _, err := cliCtx.QueryWithData(route, nil) if err != nil { return err } var coins sdk.Coins cdc.MustUnmarshalJSON(bz, &coins) return cliCtx.PrintOutput(coins) }, } } // GetCmdQueryDelegatedCoin implements the delegated coin query command. func GetCmdQueryDelegatedCoin(storeName string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegated_coin [symbol]", Args: cobra.NoArgs, Short: "Query the delegated coin", Long: strings.TrimSpace( fmt.Sprintf(`Query delegated coin. Example: $ %s query validator delegated_coin coin1 `, version.ClientName, ), ), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) route := fmt.Sprintf("custom/%s/%s", storeName, types.QueryDelegatedCoins) bz, _, err := cliCtx.QueryWithData(route, nil) if err != nil { return err } var coins sdk.Coins cdc.MustUnmarshalJSON(bz, &coins) return cliCtx.PrintOutput(coins) }, } }
import { expect, test } from '@playwright/test'; test('Landing Page', async ({ page }) => { await page.goto('/'); await expect(page).toHaveTitle(/Holidaze/); await expect(page.locator('h1')).toContainText('Holidaze'); await expect(page.locator('h2').first()).toContainText('Your Gateway to Unforgettable Getaways'); }); test('logging in as a venue manager', async ({ page }) => { const username = process.env.PLAYWRIGHT_USERNAME!; const password = process.env.PLAYWRIGHT_PASSWORD!; if (!username || !password) { throw new Error('Please provide .env PLAYWRIGHT_USERNAME and PLAYWRIGHT_PASSWORD'); } await page.goto('/'); await page.getByRole('link', { name: 'Log in' }).click(); await page.getByPlaceholder('email').fill(username); await page.getByPlaceholder('password').fill(password); await page.getByRole('button', { name: 'Log in ☀️' }).click(); await expect(page.getByText('Welcome back venue_manager! 👋').first()).toBeVisible(); await expect(page.getByRole('heading', { name: 'Holidaze' })).toBeVisible(); await expect(page.getByRole('heading', { name: 'Your Gateway to Unforgettable' })).toBeVisible(); await page.getByRole('banner').getByRole('button').click(); await page.getByRole('menuitem', { name: 'Profile' }).click(); await expect(page.getByRole('heading', { name: 'venue_manager' })).toBeVisible(); }); test('Login page', async ({ page }) => { await page.goto('/login'); await page.getByRole('button', { name: 'Log in ☀️' }).click(); await expect(page.getByText('Invalid email')).toBeVisible(); await page.getByPlaceholder('email').fill('[email protected]'); await page.getByRole('button', { name: 'Log in ☀️' }).click(); await expect(page.getByText('Invalid username or password')).toBeVisible(); }); test('Registration page', async ({ page }) => { await page.goto('/register'); await page.getByText('Name').click(); await test.step('assert that the form is visible', async () => { await expect(page.getByPlaceholder('name')).toBeVisible(); await expect(page.getByPlaceholder('email')).toBeVisible(); await expect(page.getByPlaceholder('password', { exact: true })).toBeVisible(); await expect(page.getByPlaceholder('repeat password')).toBeVisible(); await expect(page.getByText("I'm a venue manager")).toBeVisible(); await expect(page.getByRole('button', { name: 'Register ☀️' })).toBeVisible(); await expect(page.getByText('Already have an account?')).toBeVisible(); await expect(page.getByRole('link', { name: 'Login' })).toBeVisible(); }); await test.step('form gives validation errors', async () => { await page.getByRole('button', { name: 'Register ☀️' }).click(); await expect(page.getByText('Name must be at least 3 characters')).toBeVisible(); await expect(page.getByText('Invalid email')).toBeVisible(); await expect(page.getByText('Password must be at least 8')).toBeVisible(); await page.getByPlaceholder('name').fill('123'); await page.getByPlaceholder('email').fill('[email protected]'); await expect(page.getByText('Only @stud.noroff.no emails are allowed')).toBeVisible(); }); }); test('Venue Details Page', async ({ page }) => { await page.goto('/venues/38683eef-e534-4cf2-84cc-abdc5447b12b'); // playwright test page await test.step('assert that the venue details are visible', async () => { await expect(page.getByRole('heading', { name: 'playwright test venue' })).toBeVisible(); await test.step('badges', async () => { await expect(page.getByText('2 guests')).toBeVisible(); await expect(page.locator('div').filter({ hasText: /^wifi$/ })).toBeVisible(); await expect(page.locator('div').filter({ hasText: /^parking$/ })).toBeVisible(); await expect(page.locator('div').filter({ hasText: /^breakfast$/ })).toBeVisible(); await expect(page.locator('div').filter({ hasText: /^pets$/ })).toBeVisible(); }); await test.step('description', async () => { await expect(page.getByText('this text is for testing')).toBeVisible(); }); await expect(page.getByRole('heading', { name: 'What this place offers' })).toBeVisible(); await expect(page.getByRole('heading', { name: 'About the Owner' })).toBeVisible(); await expect(page.getByRole('link', { name: 'venue_manager' })).toBeVisible(); await test.step('booking card, not logged in', async () => { await expect(page.getByRole('heading', { name: '$50/night' })).toBeVisible(); await expect( page.locator('div').filter({ hasText: /^Please log in or register to book this venue$/ }) ).toBeVisible(); }); }); });
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=1.0, user-scalable=no"> <link rel="stylesheet" href="style.css"> <link rel="shortcut icon" href="../../img/icon.png" type="image/x-icon"> <title>Editar perfil</title> </head> <body> <?php include('../../connection.php'); session_start(); if (!isset($_SESSION["Cod_Usuario"])) { header("Location: /kabo/"); exit(); } $ERROR = ''; $sql = "SELECT u.Nome, u.Email, u.Senha, u.CPF, u.Dt_Nascimento, u.Genero, u.Imagem, e.CEP, e.Logradouro, e.Numero, e.Bairro, e.Estado, e.Cidade FROM Usuario u INNER JOIN Endereco e ON u.fk_Cod_Endereco = e.Cod_Endereco WHERE u.Cod_Usuario = '{$_SESSION['Cod_Usuario']}'"; $result = $conn->query($sql); $row = $result->fetch_assoc(); $Nome = $row['Nome']; $Email = $row['Email']; $Senha = $row['Senha']; $CPF = $row['CPF']; $Dt_Nascimento = $row['Dt_Nascimento']; $Genero = $row['Genero']; $CEP = $row['CEP']; $Logradouro = $row['Logradouro']; $Numero = $row['Numero']; $Bairro = $row['Bairro']; $Estado = $row['Estado']; $Cidade = $row['Cidade']; $imgPerfil = $row['Imagem']; if (isset($_GET['senha_excluir'])) { $sqlS = "SELECT Senha FROM Usuario WHERE Cod_Usuario = '{$_SESSION['Cod_Usuario']}'"; $resultS = $conn->query($sqlS); $rowS = $resultS->fetch_assoc(); if ($rowS['Senha'] == md5($_GET['senha_excluir'])) { if ($_SESSION['Tipo_Usuario'] == 1) { $ERROR = 'Não é possível deletar contas administadoras'; } else { $sql = "DELETE FROM Usuario WHERE Cod_Usuario = {$_SESSION['Cod_Usuario']}"; $conn->query($sql); session_destroy(); header("Location: /kabo/"); exit(); } } else { $ERROR = 'Senha Incorreta'; } } ?> <script> // Máscara para o CEP function maskCEP(cep) { return cep.trim().replace(/^(\d{5})(\d{3})$/, '$1-$2') } // API correios function buscarCEP(cep) { // Verifica se o CEP possui o formato correto if (/^\d{5}-\d{3}$/.test(cep)) { // Faz a requisição para a API do ViaCEP fetch(`https://viacep.com.br/ws/${cep}/json/`) .then(response => response.json()) .then(data => { if (!data.erro) { // Preenche os campos de endereço com os dados retornados pela API document.getElementById('logradouro').value = data.logradouro; document.getElementById('bairro').value = data.bairro; document.getElementById('cidade').value = data.localidade; document.getElementById('estado').value = data.uf; } else { showDialog('Erro', 'CEP não encontrado'); } }) .catch(error => console.error('Erro ao buscar CEP:', error)); } } // Função para mostrar a imagem selecionada na edição do perfil function validaImagem(input) { var caminho = input.value; if (caminho) { var comecoCaminho = (caminho.indexOf('\\') >= 0 ? caminho.lastIndexOf('\\') : caminho.lastIndexOf('/')); var nomeArquivo = caminho.substring(comecoCaminho); if (nomeArquivo.indexOf('\\') === 0 || nomeArquivo.indexOf('/') === 0) { nomeArquivo = nomeArquivo.substring(1); } var extensaoArquivo = nomeArquivo.indexOf('.') < 1 ? '' : nomeArquivo.split('.').pop(); if (extensaoArquivo != 'gif' && extensaoArquivo != 'png' && extensaoArquivo != 'jpg' && extensaoArquivo != 'jpeg') { input.value = ''; showDialog('Erro', "É preciso selecionar um arquivo de imagem (gif, png, jpg ou jpeg)"); } } else { input.value = ''; showDialog('Erro', "Selecione um caminho de arquivo válido"); } if (input.files && input.files[0]) { var arquivoTam = input.files[0].size / 1024 / 1024; if (arquivoTam < 16) { var reader = new FileReader(); reader.onload = function(e) { document.getElementById(`imagemCadastro`).style.visibility = "visible"; document.getElementById(`imagemCadastro`).setAttribute('src', e.target.result); }; reader.readAsDataURL(input.files[0]); } else { input.value = ''; showDialog('Erro', "O arquivo precisa ser uma imagem com menos de 16 MB"); } } else { document.getElementById(`imagemCadastro`).setAttribute('src', '#'); } } </script> <main> <section class="box"> <span id="X" onclick="voltarPagina()"><a href="../">&times;</a></span> <div class="alinharelementos"> <a href="../../"><img src="../../img/logo_neon.png" alt="logo" id="logo"></a> </div> <div class="alinharelementosescrita"> <p id="elemento1">Editar perfil</p> <p id="elemento2">Edite seu nome, e-mail, senha, CEP e interesses</p> </div> <form id="form1" name="form1" method="post" action="edit_php.php" onsubmit="return verificar()" enctype="multipart/form-data"> <div class="espacodentrobox"> <div class="div_input_imagem"> <label for="input_file" class="label_input_file">Foto perfil</label> <input type="file" id="input_file" class="input_file" name="imgPerfil" onchange="validaImagem(this);"> <?php if ($imgPerfil != null) { $imagemBase64 = base64_encode($imgPerfil); ?> <img src="data:image/jpeg;base64,<?php echo $imagemBase64 ?>" id="imagemCadastro" class="imagePreview" alt="Foto perfil"> <?php ;} else {?> <img src="" id="imagemCadastro" class="imagePreview" alt="Foto perfil" style="visibility: hidden;"> <?php ;} ?> </div> <input type="text" name="txtNome" value="<?php echo $Nome ?>" maxlength="100" id="primeiroinput" placeholder="Nome" class="campocheio" required> <input type="text" placeholder="CPF" id="cpf" name="txtCPF" value="<?php echo $CPF ?>" maxlength="14" class="campomedio" readonly> <select name="selectGenero" id="genero" class="campomedio" required> <option value="genero">Gênero</option> <option value="M" <?php if ($Genero == 'M') echo 'selected'; ?>>Masculino</option> <option value="F" <?php if ($Genero == 'F') echo 'selected'; ?>>Feminino</option> <option value="O" <?php if ($Genero == 'O') echo 'selected'; ?>>Outro</option> </select> <input type="date" placeholder="Data de nascimento" id="nascimento" name="dateData_Nasc" value="<?php echo date('Y-m-d', strtotime($Dt_Nascimento)) ?>" class="campomedio" readonly> <input type="text" placeholder="CEP" id="CEP" name="txtCEP" value="<?php echo $CEP ?>" oninput="this.value = maskCEP(this.value); buscarCEP(this.value);" maxlength="9" class="campomedio" required> <input type="text" placeholder="Logradouro" id="logradouro" name="txtLogradouro" value="<?php echo $Logradouro ?>" class="campocheio" maxlength="150" required> <input type="text" placeholder="Bairro" id="bairro" name="txtBairro" value="<?php echo $Bairro ?>" class="campomedio" maxlength="50" required> <input type="number" placeholder="Numero" id="numero" name="txtNumero" value="<?php echo $Numero ?>" class="campomedio" oninput="limitarNumero(this)" min="0" required> <input type="text" placeholder="Cidade" id="cidade" name="txtCidade" value="<?php echo $Cidade ?>" class="campomedio" maxlength="50" required> <input type="text" placeholder="Estado" id="estado" name="txtEstado" value="<?php echo $Estado ?>" class="campomedio" maxlength="2" required> <input type="email" name="email" id="email" value="<?php echo $Email ?>" placeholder="E-mail" maxlength="100" class="campocheio" readonly> <input type="password" name="txtSenhaAtual" value="" id="senhaAtual" placeholder="Digite a senha atual" class="campocheio" maxlength="20" required> <p id="bntTrocarSenha">Trocar senha</p> <div class="esconder"> <p id="regraSenha">A senha deve ter ao menos uma letra maiúscula e minúscula e um número. Ao todo, no mínimo oito caracteres.</p> <input type="password" name="txtSenhaNova" value="" id="senhaNova" placeholder="Digite a nova senha" class="campocheio" maxlength="20" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"> <input type="password" name="txtSenha" value=""id="senhaConfirmar" placeholder="Confirme a nova senha" class="campocheio" maxlength="20" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"> </div> <script> document.getElementById('bntTrocarSenha').addEventListener('click', function() { var divEsconder = document.querySelector('.esconder'); divEsconder.style.display = 'block'; var camposSenha = divEsconder.querySelectorAll('input[type=password]'); for (var i = 0; i < camposSenha.length; i++) { camposSenha[i].required = true; } }); </script> </div> <div id="botoes"> <input type="button" value="Excluir conta" id="excluirsubmit"> <input type="submit" value="Atualizar" id="enviarsubmit"> </div> <span id="erro_senha"><?php echo $ERROR ?></span> </form> <p id="folhascopy"><a href="../../">&copy;Kabo</a></p> </section> <div id="popup" class="popup"> <span class="close" id="closePopup">&times;</span> <div id="titulo_div"> <div class="popup-content"> <span id="titulo">Excluir</span> <form action="" id="form_senha" method="get"> <div style="display: flex; align-items: center;"> <input type="password" id="senha_excluir" name="senha_excluir" placeholder="Confirme com sua senha" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" required> </div> <input type="submit" value="Excluir" id="botao_excluir_popup"> </form> </div> </div> </div> </main> <dialog id="dialogErro"> <h3 id="dialogTitulo">Erro</h3> <p id="avisoDialog"></p> <button id="botaoDialog">Ok</button> </dialog> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/core.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/md5.js"></script> <script> // função modal function showDialog(titulo, texto) { var dialog = document.querySelector('#dialogErro'); var dialogTitulo = document.querySelector('#dialogTitulo'); var avisoDialog = document.querySelector('#avisoDialog'); var botaoDialog = document.querySelector('#botaoDialog'); dialogTitulo.textContent = titulo; avisoDialog.textContent = texto; botaoDialog.textContent = 'Ok'; botaoDialog.onclick = function() { dialog.classList.add('fadeOut'); setTimeout(function() { dialog.close(); dialog.classList.remove('fadeOut'); }, 201); }; dialog.classList.remove('fadeOut'); dialog.showModal(); } const txtSenhaAtual = document.getElementById('senhaAtual') const txtSenhaNova = document.getElementById('senhaNova') const txtSenhaConfirmar = document.getElementById('senhaConfirmar') const txtNome = document.getElementById('primeiroinput') const txtCEP = document.getElementById('CEP') const txtLogradouro = document.getElementById('logradouro') const txtBairro = document.getElementById('bairro') const txtCidade = document.getElementById('cidade') const txtestado = document.getElementById('estado') const email = document.getElementById('email') function limitarNumero(input) { var maxLength = 5; var valor = input.value; if (valor.length > maxLength) { input.value = valor.slice(0, maxLength); } } function verificar() { if (isNomeValido(txtNome.value)) { if (isCEPValido(txtCEP.value)) { if (isEmailValido(email.value)) { if (isNomeValido(txtLogradouro.value)) { if (isNomeValido(txtBairro.value)) { if (isNomeValido(txtCidade.value)) { if (isNomeValido(txtestado.value)) { if (CryptoJS.MD5(txtSenhaAtual.value).toString() === '<?php echo $row['Senha']; ?>') { if (txtSenhaNova.value === txtSenhaConfirmar.value) { return true; } else { showDialog('Erro', 'As senhas não combinam!') return false } } else { showDialog('Erro', 'Senha atual incorreta!') return false } } else { showDialog('Erro', 'Estado inválido!') return false } } else { showDialog('Erro', 'Cidade inválido!') return false } } else { showDialog('Erro', 'Bairro inválido!') return false } } else { showDialog('Erro', 'Logradouro inválido!') return false } } else { showDialog('Erro', 'Email inválido!') return false } } else { showDialog('Erro', 'CEP inválido!') return false } } else { showDialog('Erro', 'Nome inválido!') return false } } function isNomeValido(nome) { const reN = /^\w*[a-zA-ZÀ-ú\s]+$/ return reN.test(nome) } function isCEPValido(cep) { const reCE = /^\d{5}-\d{3}$/ return reCE.test(cep) } function isEmailValido(email) { const reEM = /^\w.+@\w{3}.*\.\w{2,3}$/ return reEM.test(email) } document.getElementById("excluirsubmit").addEventListener("click", function() { document.getElementById("popup").style.display = "block"; }); document.getElementById("closePopup").addEventListener("click", function() { document.getElementById("popup").style.display = "none"; }); document.getElementById("botao_excluir_popup").addEventListener("click", function() { document.getElementById("popup").style.display = "none"; }); function voltarPagina() { window.history.back(); } </script> </body> </html>
import axios from "axios" import { useEffect, useState } from "react" import { useParams, useNavigate } from "react-router-dom" import styled from "styled-components" import { colors } from "../components/Pokemon" const PokemonDetail = () => { const { id } = useParams() const [data, setData] = useState([]) const [img, setImg] = useState('') const [types, setType] = useState([]) const [ability, setAbility] = useState([]) const [stats, setStats] = useState([]) let navigate = useNavigate() const fetchPoke = () => { axios.get(`https://pokeapi.co/api/v2/pokemon/${id}`) .then(response => { setData(response.data) setImg(response.data.sprites.front_default) setType(response.data.types) setAbility(response.data.abilities) setStats(response.data.stats) }) } useEffect(fetchPoke, [id]) function arrow(item) { if (item === "left" && id !== "1") { navigate(`/pokemons/${Number(id) - 1}`) } if (item === "right" && id !== "100") { navigate(`/pokemons/${Number(id) + 1}`) } } return ( <Wrapper> <i className="fa fa-chevron-left" onClick={() => arrow("left")}></i> <div className="main"> <img className="img__animated" src="https://icon-library.com/images/pokeball-icon-png/pokeball-icon-png-5.jpg" alt="" /> <div className="top"> <i onClick={() => navigate("/pokemons")} className="fa fa-home" aria-hidden="true"></i> <h2>{data.name}</h2> <b>#{data.id}</b> </div> <div className="image_back"> <img className="poke-img" src={img} alt="" /> </div> <div className="types"> { types.map(item => <p key={Math.random()}>{item.type.name}</p>) } </div> <div className="about"> <h3>About</h3> <span> <p>height: {data.height}m</p> <p>weight: {data.weight}kg</p> </span> </div> <div className="abilities"> <h3>Abilities</h3> <span> { ability.map(item => <p key={Math.random()}>{item.ability.name}</p>) } </span> </div> <div className="stats"> <h3>Base Stats</h3> <div className="stats__main"> <div className="stats__name"> { stats.map(item => <p key={Math.random()}>{item.stat.name}</p>) } </div> <span></span> <div className="stats__progress"> { stats.map((item) => <div key={Math.random()} className="progresses"> <p>{item.base_stat} %</p> <div className="progress"> <div className="progress__bar" style={{ width: item.base_stat + "%" }}> <div className="progress__bar-back"></div> </div> </div> </div> ) } </div> </div> </div> </div> <i className="fa fa-chevron-right" onClick={() => arrow("right")}></i> </Wrapper > ) } export default PokemonDetail; const Wrapper = styled.div` .main { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 700px; width: 450px; background: lightblue; padding: 25px; border-radius: 16px; .top { display: flex; align-items: center; justify-content: space-between; color: white; text-transform: uppercase; b{ font-size: 36px; } img { width: 30px; cursor: pointer; } } .about, .abilities { text-align: center; color: #A43E9E; margin-top: 10px; span { display: flex; justify-content: center; gap: 20px; p { font-size: 18px; font-weight: 500; font-family: 'Courier New', Courier, monospace; } } } h3 { color: #74CB48; font-size: 24px; } .stats { color: #70559B; font-weight: 500; margin-top: 10px; h3 { text-align: center; } .stats__main { margin-top: 20px; display: flex; align-items: center; justify-content: center; gap: 10px; font-size: 14px; .stats__name { text-align: right; p { margin-bottom: 10px; } } span { height: 160px; width: 1.5px; background-color: #fff; } .progresses { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; .progress { width: 200px; height: 4px; background-color: white; border-radius: 2px; margin-left: 10px; overflow: hidden; @media (max-width: 700px) { width: 150px; } .progress__bar { height: 100%; .progress__bar-back { border-radius: 2px; height: 100%; background: linear-gradient(to left, #74CB48, #A43E9E); animation-name: progress; animation-duration: 1s; animation-timing-function: linear; animation-iteration-count: 1; } } } } } } @keyframes progress { 0% { width: 0; } 100% { width: 100%; } } @keyframes imgShow { 0% { transform: translateY(0px) ; } 50% { transform: translateY(8px) ; } 100% { transform: translateY(0px) ; } } .image_back { border-radius: 50%; width: 140px; margin: 20px auto; .poke-img { display: block; margin: 20px auto; animation-name: imgShow; animation-duration: 2s; animation-timing-function: linear; animation-iteration-count: infinite; width: 170px; } } @media (max-width: 700px) { width: 100%; height: 100%; border-radius: 0; border: none; } .types { margin-top: 10px; display: flex; align-items: center; justify-content: center; gap: 10px; p { border-radius: 3px; color: white; font-size: 12px; padding: 4px 8px; :nth-child(1) { background: ${({ types }) => colors["grass"]}; } :nth-child(2) { background: ${({ types }) => colors["poison"]}; } } } .img__animated { position: absolute; width: 130px; opacity: 0.2; right: 10px; top: 20px; animation-name: img__animated; animation-duration: 8s; animation-timing-function: linear; animation-iteration-count: infinite; } @keyframes img__animated { 0% { transform: rotate(0deg) ; } 100% { transform: rotate(360deg) ; } } i{ font-size: 36px; color: white; } } i{ cursor: pointer; color: white; font-size: 36px; } .fa-chevron-left { position: absolute; top: 50%; left: 33%; transform: translate(-50%, -50%); } .fa-chevron-right { position: absolute; top: 50%; left: 67%; transform: translate(-50%, -50%); } `
import { Box, Button, Chip, Typography } from "@mui/joy"; import React from "react"; import { useColorScheme } from "@mui/joy/styles"; import { useEffect, useState } from "react"; import { BountyApplication } from "@/types"; import axios from "axios"; import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; import { formatTimestamp, shortenAddress } from "@/functions"; import Avatar from "@/utils/Avatar"; import { IoMdCheckmark, IoMdClose } from "react-icons/io"; import { useAppContext } from "@/context/AppContext"; interface ApplicationCardProps extends BountyApplication { bountyId: string; issuer: `0x${string}`; refetch: () => void; acceptedHunter: `0x${string}` | null; } export default function ApplicationCard(application: ApplicationCardProps) { const { mode } = useColorScheme(); const { address, acceptApplication, declineApplicantion } = useAppContext(); const [common, setCommon] = useState("#ffffff"); const [applicationMessage, setApplicationMessage] = useState(""); const [isCreator, setIsCreator] = useState(false); const [accepting, setAccepting] = useState(false); const [declining, setDeclining] = useState(false); useEffect(() => { setIsCreator(application.issuer === address); }, [application.issuer, address]); useEffect(() => { const fetchApplicationMessage = async () => { const { data } = await axios.get( `https://ipfs.io/ipfs/${application.applicationMessage}` ); setApplicationMessage(data); }; fetchApplicationMessage(); }, [application.applicationMessage]); useEffect(() => { if (mode === "light") { setCommon("#ffffff"); } else { setCommon("neutral.900"); } }, [mode]); const acceptApplicant = async (address: `0x${string}`) => { setAccepting(true); await acceptApplication(application.bountyId, address); application.refetch(); setAccepting(false); }; const declineApplicant = async (address: `0x${string}`) => { setDeclining(true); await declineApplicantion(application.bountyId, address); application.refetch(); setDeclining(false); }; return ( <Box px={3} py={1} my={2} borderRadius={"md"} bgcolor={common}> <Box> <Box display={"flex"} alignItems={"center"} justifyContent={"space-between"} > <Box display={"flex"} alignItems={"center"} gap={".5rem"} my={3}> <Box display={"flex"} alignItems={"center"} gap={".5rem"}> <Avatar address={application.hunter} /> <Typography level="body-sm"> {shortenAddress(application.hunter)} </Typography> </Box> {application.acceptedHunter === application.hunter && ( <Chip startDecorator={<IoMdCheckmark />} size="sm" color="primary" > Accepted </Chip> )} {application.status === "rejected" && ( <Chip startDecorator={<IoMdCheckmark />} size="sm" color="danger"> Rejected </Chip> )} </Box> {isCreator && !application.acceptedHunter && application.status !== "rejected" && ( <Box display={"flex"} alignItems={"center"} gap={".5rem"}> <Button variant="soft" color="danger" onClick={() => declineApplicant(application.hunter)} loading={declining} disabled={declining} > <IoMdClose size={20} color="#000z" /> </Button> <Button variant="solid" color="primary" startDecorator={<IoMdCheckmark />} onClick={() => acceptApplicant(application.hunter)} loading={accepting} disabled={accepting} > Accept Application </Button> </Box> )} </Box> <Typography> Applied {formatTimestamp(application.timestamp)} </Typography> </Box> <ReactMarkdown remarkPlugins={[remarkGfm]}> {applicationMessage.replace(/^(.*)$/gm, "$1 ")} </ReactMarkdown> </Box> ); }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* cb_game_init.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lduthill <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/01/29 22:34:26 by lduthill #+# #+# */ /* Updated: 2024/02/08 00:46:01 by lduthill ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../include/cub3d.h" /* ft_game(t_map *map) ** - Initialize the game ** - Set the display size */ void ft_game(t_map *map) { map->game->dis_w = WIDTH; map->game->dis_h = HEIGHT; map->game->width = ft_get_longuest(map->map); map->game->height = ft_len_tab(map->map); ft_beggin(map->game, map); } /* ft_get_longuest(char **map) ** - Get the longuest line of the map ** - Return the longuest line */ int ft_get_longuest(char **map) { unsigned int check; unsigned int i; check = ft_strlen(map[0]); i = 0; while (map[i]) { if (check < ft_strlen(map[i])) check = ft_strlen(map[i]); i++; } return (check); } /* ft_beggin(t_game *game, t_map *map) ** - Initialize the game ** - Set the mlx and the window ** - Set the texture ** - Draw the map ** - Set the hooks */ void ft_beggin(t_game *game, t_map *map) { game->mlx = mlx_init(); game->win = mlx_new_window(game->mlx, game->dis_w, game->dis_h, "Cobe3D"); ft_get_draw_texture(game, map); map->error = ft_draw_map(game, map); if (map->error > 0) return (ft_free_texture(map)); mlx_loop_hook(game->mlx, ft_hooks, map); mlx_hook(game->win, 17, 1, ft_exit, map); mlx_hook(game->win, 2, 1, ft_controls, map); mlx_loop(game->mlx); }
import { describe, it, expect } from 'vitest' import { render, screen, fireEvent } from '@testing-library/vue'; import PokemonSearch from '../components/PokemonSearch.vue'; describe.concurrent('Homepage Pokemon Search component', async () => { it('renders the pokemon search component', async () => { render(PokemonSearch); const form = await screen.findByRole('form'); const input = await screen.findByPlaceholderText(/Search a pokemon/i); expect(form.tagName).toBe('FORM'); expect(input.tagName).toBe('INPUT'); }) it('form action attribute should update according to user input', async () => { render(PokemonSearch); const form = await screen.findByRole('form'); const input = await screen.findByPlaceholderText(/Search a pokemon/i); await fireEvent.update(input, 'pikachu'); expect(form.action).toBe('/pokemon/pikachu'); await fireEvent.update(input, 'rayquaza'); expect(form.action).toBe('/pokemon/rayquaza'); }) })
from typing import List from pikachu.general import read_smiles from raichu.substrate import TerpeneCyclaseSubstrate from raichu.representations import ( MacrocyclizationRepresentation, TailoringRepresentation, IsomerizationRepresentation, MethylShiftRepresentation, ) from raichu.reactions.general_tailoring_reactions import ( dephosphorylation, oxidative_bond_formation, double_bond_reduction, ) from raichu.cluster.base_cluster import Cluster from raichu.reactions.general_tailoring_reactions import ( double_bond_shift, reductive_bond_breakage, addition ) class TerpeneCluster(Cluster): def __init__( self, cyclase_name: str, precursor: str, cyclase_type: str = None, macrocyclisations: List[MacrocyclizationRepresentation] = None, double_bond_isomerisations: List[IsomerizationRepresentation] = None, methyl_shifts: List[MethylShiftRepresentation] = None, tailoring_representations: List[TailoringRepresentation] = None, ) -> None: super().__init__(tailoring_representations, macrocyclisations) self.cyclase_name = cyclase_name self.cyclase_type = cyclase_type self.precursor = precursor self.isomerization_representations = double_bond_isomerisations self.methyl_shift_representations = methyl_shifts self.chain_intermediate = None self.tailored_product = None self.final_product = None self.terpene = True def create_precursor(self) -> None: substrate = TerpeneCyclaseSubstrate(self.precursor) self.chain_intermediate = read_smiles(substrate.smiles) def do_double_bond_isomerization(self): if not self.isomerization_representations: return initialized_isomerization_atoms = self.initialize_modification_sites( [ isomerization_representation.modification_sites for isomerization_representation in self.isomerization_representations ] ) for atoms in initialized_isomerization_atoms: if len(atoms) < 4: continue old_double_bond_atom1 = self.chain_intermediate.get_atom(atoms[0]) old_double_bond_atom2 = self.chain_intermediate.get_atom(atoms[1]) new_double_bond_atom1 = self.chain_intermediate.get_atom(atoms[2]) new_double_bond_atom2 = self.chain_intermediate.get_atom(atoms[3]) if len(set(atoms)) == len(atoms): raise ValueError( "The bonds need to be adjacent to perform a double bond shift." ) self.chain_intermediate = double_bond_shift( self.chain_intermediate, old_double_bond_atom1, old_double_bond_atom2, new_double_bond_atom1, new_double_bond_atom2, ) def do_methyl_shift(self): if not self.methyl_shift_representations: return initialized_methyl_shift_atoms = self.initialize_modification_sites( [ methyl_shift_representation.modification_sites for methyl_shift_representation in self.methyl_shift_representations ] ) for atoms in initialized_methyl_shift_atoms: if len(atoms) != 2: continue transferred_c = atoms[0] # Assert its actually a methyl group assert [atom.type for atom in transferred_c.neighbours].count("H") == 3 source = None source = [ atom for atom in transferred_c.neighbours if atom.type != "H" ][0] assert source destination_c = atoms[1] assert destination_c.has_neighbour("H") assert transferred_c.type == "C" and destination_c.type == "C" self.chain_intermediate = reductive_bond_breakage(source, transferred_c, self.chain_intermediate) self.chain_intermediate = addition(destination_c, "C", self.chain_intermediate) self.chain_intermediate.refresh_structure(find_cycles=True) def do_macrocyclization(self, sequential=True): initialized_macrocyclization_atoms = self.initialize_macrocyclization() self.cyclic_intermediates.append(self.chain_intermediate.deepcopy()) self.do_double_bond_isomerization() self.do_methyl_shift() if self.cyclase_type != "Class_2": self.chain_intermediate = dephosphorylation(self.chain_intermediate) for ( macrocyclization_atoms, cyclisation_type, ) in initialized_macrocyclization_atoms: atom1 = self.chain_intermediate.get_atom(macrocyclization_atoms[0]) atom2 = self.chain_intermediate.get_atom(macrocyclization_atoms[1]) found_bond = False for atom in [atom1, atom2]: if found_bond and any( [neighbour.type == "H" for neighbour in atom.neighbours] ): break for bond in atom.bonds: if bond.type == "double": self.chain_intermediate = double_bond_reduction( *bond.neighbours, self.chain_intermediate ) found_bond = True break self.chain_intermediate = oxidative_bond_formation( atom1, atom2, self.chain_intermediate ) self.cyclic_intermediates.append(self.chain_intermediate.deepcopy()) self.cyclic_product = self.chain_intermediate
/* Name : PricingRequestPendingNotifyBatch Author : Date : 27 October, 2016 Description : This batch class use for send notificatin notification email to vendor when the pricing request has been pending for more than 14 days */ global class PricingRequestPendingNotifyBatch implements Database.Batchable<sObject>{ // start method of Batch process global Database.QueryLocator start(Database.BatchableContext BC){ // assign default days if not specified in custom setting. Integer day; TMinus_Setting__c tmSetting = TMinus_Setting__c.getValues('T-MinusProjectAutoCreation'); if(tmSetting != null && tmSetting.Pricing_Request_Pending_Notify_Days__c!=null){ day = (Integer)tmSetting.Pricing_Request_Pending_Notify_Days__c; } String dtExpr = 'LAST_N_DAYS:'+day; //@Faheem Ali for ITM-1966 on 21st Sept' 2022 using contact email instead of user email if email is sent to community user //ADD-USERCONTACTEMAIL added Owner.Username in the query //@Tarun 13-09-2023, ITM-2893 (hotelStatusToStopEmailsLabel) Filter added in query List<String> hotelStatusToStopEmailsLabel = (Label.Hotel_Status_To_Stop_Emails.equalsIgnoreCase('BLANK')) ? new List<String>() : Label.Hotel_Status_To_Stop_Emails.toLowerCase().split(','); String query = 'SELECT Id, Owner.name,OwnerId,Owner.Username, Account.hotel_status__c from Task'; query += ' Where Subject=\'Pricing notification sent to vendor\' and IsScheduled__c = false and Status !=\'Completed\' AND Account.hotel_status__c NOT IN :hotelStatusToStopEmailsLabel' ; If(day !=0 && day != null){ query += ' and createdDate < '+dtExpr; } return Database.getQueryLocator(query); } // execute mehod of Batch process global void execute(Database.BatchableContext BC, List<sObject> batch){ List<Messaging.SingleEmailMessage> massEmailList = new List<Messaging.SingleEmailMessage>(); List<Task> listTask = (List<Task>) batch; Id templateId = [Select id from emailtemplate where developerName = 'Pricing_request_pending_14_days_notification' limit 1].Id; String orgWideId = ''; OrgWideEmailAddress[] orgWideAdd = [select Id from OrgWideEmailAddress where displayname =: Label.Bandwidth_system_email]; if(orgWideAdd.size()>0){ orgWideId = orgWideAdd.get(0).Id; } list<task> updateTaskList = new list<task>(); //@Faheem Ali for ITM-1966 on 21st Sept' 2022 using contact email instead of user email if email is sent to community user //ADD-USERCONTACTEMAIL List<String> userNames = new List<String>(); for(Task task : listTask){ userNames.add(task.Owner.Username); } Map<String, String> usrContactEmails = ProjectUtility.getUserOrContactEmails(userNames); for(Task taskRc : listTask){ // get single email message and add it to list //@Faheem Ali for ITM-1966 on 21st Sept' 2022 using contact email instead of user email if email is sent to community user //DEL-USEREMAIL //massEmailList.add(emailtoVendors(taskRc,templateId,orgWideId)); //ADD-USERCONTACTEMAIL massEmailList.add(emailtoVendors(taskRc,templateId,orgWideId,usrContactEmails)); // update to task as isSchedueled true updateTaskList.add(new task(id=taskRc.id, IsScheduled__c = true)); } if(massEmailList.size()>0){ // sending mass email at final EmailExceptionHandler.sendEmail(massEmailList);//@Kartik 26 April,2021 - ITM-1696 Email Bounce Error Handling update updateTaskList; } } // finish method of Batch process global void finish(Database.BatchableContext BC){ } //@Faheem Ali for ITM-1966 on 21st Sept' 2022 using contact email instead of user email if email is sent to community user //ADD-USERCONTACTEMAIL //private static Messaging.SingleEmailMessage emailtoVendors(Task taskRc, Id templateId, String orgWideId){ private static Messaging.SingleEmailMessage emailtoVendors(Task taskRc, Id templateId, String orgWideId, Map<String, String> usrContactEmails){ Messaging.SingleEmailMessage mail = Messaging.renderStoredEmailTemplate(templateId, taskRc.OwnerId, taskRc.Id); mail.setTargetObjectId(taskRc.OwnerId); //@Faheem Ali for ITM-1966 on 21st Sept' 2022 using contact email instead of user email if email is sent to community user //ADD-USERCONTACTEMAIL if(usrContactEmails.containsKey(taskRc.Owner.Username)) mail.setToAddresses(new List<String>{usrContactEmails.get(taskRc.Owner.Username)}); //DEL-USEREMAIL mail.setTreatTargetObjectAsRecipient(false); mail.setSaveAsActivity(false); if(string.isNotBlank(orgWideId)){ mail.setOrgWideEmailAddressId(orgWideId); } return mail; } }
using BusinessLayer.Implementations; using BusinessLayer.Interfaces; using DataAccesLayer.Implementations; using DataAccesLayer; using DataAccesLayer.Interface; using Domain.DT; using Domain.Entidades; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; using Moq; using SignalR; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Intrinsics.X86; using System.Text; using System.Threading.Tasks; using WebApi_PUB_PV.Controllers; using WebApi_PUB_PV.Models; using DataAccesLayer.Models; namespace Testing_PV { public class Test_Pedido { private PedidoController pedidoController; private DTPedido pedidoValido; private DTPedido pedidoInvalido; private Mock<IDAL_Pedido> mockDal; private Mock<IDAL_Casteo> mockCasteo; private Mock<IDAL_FuncionesExtras> mockFunciones; private B_Pedido bl; private int id_pedidoValido; private int id_pedidoInvalido; private int id_Mesa; [SetUp] public void Configuracion() { // Inicializa mockDal = new Mock<IDAL_Pedido>(); mockCasteo = new Mock<IDAL_Casteo>(); mockFunciones = new Mock<IDAL_FuncionesExtras>(); bl = new(mockDal.Object, mockCasteo.Object, mockFunciones.Object); // Crea una instancia de Pedido con el servicio var _hub = new Mock<IHubContext<ChatHub>>(); pedidoController = new PedidoController(bl,_hub.Object); pedidoValido = new DTPedido { id_Pedido = 0, valorPedido = 540, pago = false, username = "[email protected]", id_Cli_Preferencial = 0, id_Mesa = 2, estadoProceso = true, fecha_ingreso = new DateTime(), numero_movil = "", tipo = 0, list_IdProductos = { } }; pedidoInvalido = new DTPedido { id_Pedido = -1, valorPedido = 411, pago = false, username = "[email protected]", id_Cli_Preferencial = 0, id_Mesa = 9, estadoProceso = true, fecha_ingreso = new DateTime(), numero_movil = "", tipo = 0, list_IdProductos = { } }; id_pedidoValido = 7; id_pedidoInvalido = -1; id_Mesa = 1; } [Test] public async Task Agregar_ReturnOk() { // Configura el mock para simular que el usuario existe mockFunciones.Setup(fu => fu.existeUsuario(It.IsAny<string>())) .Returns(true); MensajeRetorno mensajeRetorno = new MensajeRetorno { status = true, mensaje = "El Pedido se guardo Correctamente" }; mockDal.Setup(bl => bl.set_Pedido(pedidoValido)).Returns(true); var result = await pedidoController.Post(pedidoValido) as OkObjectResult; Assert.IsNotNull(result); Assert.AreEqual(200, result.StatusCode); Assert.IsNotNull(result.Value); Assert.IsInstanceOf<StatusResponse>(result.Value); Assert.AreEqual(mensajeRetorno.status, ((StatusResponse)result.Value).StatusOk); string expectedMessage = mensajeRetorno.mensaje; string actualMessage = ((StatusResponse)result.Value).StatusMessage; Assert.IsTrue(actualMessage.Contains(expectedMessage)); } [Test] public async Task Agregar_ReturnBadRequest() { // Configura el mock para simular que el pedido existe mockFunciones.Setup(fu => fu.existePedido(It.IsAny<int>())) .Returns(true); MensajeRetorno mensajeRetorno = new MensajeRetorno { status = false, mensaje = "Ya existe un pedido con los datos ingresados" }; mockDal.Setup(bl => bl.set_Pedido(pedidoInvalido)).Returns(false); var result = await pedidoController.Post(pedidoInvalido) as BadRequestObjectResult; Assert.IsNotNull(result); Assert.AreEqual(400, result.StatusCode); Assert.IsNotNull(result.Value); Assert.IsInstanceOf<StatusResponse>(result.Value); Assert.AreEqual(mensajeRetorno.status, ((StatusResponse)result.Value).StatusOk); Assert.AreEqual(mensajeRetorno.mensaje, ((StatusResponse)result.Value).StatusMessage); } [Test] public void Modificar_ReturnOk() { // Configura el mock para simular que el pedido existe mockFunciones.Setup(fu => fu.existePedido(It.IsAny<int>())) .Returns(true); // Configura el mock para simular que el usuarioe xiste mockFunciones.Setup(fu => fu.existeUsuario(It.IsAny<string>())) .Returns(true); // Configura el mock para simular que la mesa existe mockFunciones.Setup(fu => fu.existeMesa(It.IsAny<int>())) .Returns(true); MensajeRetorno mensajeRetorno = new MensajeRetorno { status = true, mensaje = "El Pedido se actualizo Correctamente" }; mockDal.Setup(bl => bl.update_Pedido(pedidoValido)).Returns(true); var result = pedidoController.Put(pedidoValido) as OkObjectResult; Assert.IsNotNull(result); Assert.AreEqual(200, result.StatusCode); Assert.IsNotNull(result.Value); Assert.IsInstanceOf<StatusResponse>(result.Value); Assert.AreEqual(mensajeRetorno.status, ((StatusResponse)result.Value).StatusOk); Assert.AreEqual(mensajeRetorno.mensaje, ((StatusResponse)result.Value).StatusMessage); } [Test] public void Modificar_ReturnBadRequest() { // Configura el mock para simular que el pedido no existe mockFunciones.Setup(fu => fu.existePedido(It.IsAny<int>())) .Returns(false); MensajeRetorno mensajeRetorno = new MensajeRetorno { status = false, mensaje = "No existe un pedido con los datos ingresados" }; mockDal.Setup(bl => bl.update_Pedido(pedidoInvalido)).Returns(false); var result = pedidoController.Put(pedidoInvalido) as BadRequestObjectResult; Assert.IsNotNull(result); Assert.AreEqual(400, result.StatusCode); Assert.IsNotNull(result.Value); Assert.IsInstanceOf<StatusResponse>(result.Value); Assert.AreEqual(mensajeRetorno.status, ((StatusResponse)result.Value).StatusOk); Assert.AreEqual(mensajeRetorno.mensaje, ((StatusResponse)result.Value).StatusMessage); } [Test] public void Eliminar_ReturnOk() { MensajeRetorno mensajeRetorno = new MensajeRetorno { status = true, mensaje = "El Pedido se dio de baja correctamente" }; mockDal.Setup(bl => bl.baja_Pedido(id_pedidoValido)).Returns(true); var result = pedidoController.BajaPedido(id_pedidoValido) as OkObjectResult; Assert.IsNotNull(result); Assert.AreEqual(200, result.StatusCode); Assert.IsNotNull(result.Value); Assert.IsInstanceOf<StatusResponse>(result.Value); Assert.AreEqual(mensajeRetorno.status, ((StatusResponse)result.Value).StatusOk); Assert.AreEqual(mensajeRetorno.mensaje, ((StatusResponse)result.Value).StatusMessage); } [Test] public void Eliminar_ReturnBadRequest() { MensajeRetorno mensajeRetorno = new MensajeRetorno { status = false, mensaje = "Exepción no controlada" }; mockDal.Setup(bl => bl.baja_Pedido(id_pedidoInvalido)).Returns(false); var result = pedidoController.BajaPedido(id_pedidoInvalido) as BadRequestObjectResult; Assert.IsNotNull(result); Assert.AreEqual(400, result.StatusCode); Assert.IsNotNull(result.Value); Assert.IsInstanceOf<StatusResponse>(result.Value); Assert.AreEqual(mensajeRetorno.status, ((StatusResponse)result.Value).StatusOk); Assert.AreEqual(mensajeRetorno.mensaje, ((StatusResponse)result.Value).StatusMessage); } [Test] public void Finalizar_ReturnOk() { MensajeRetorno mensajeRetorno = new MensajeRetorno { status = true, mensaje = "El Pedido se finalizo correctamente" }; mockDal.Setup(bl => bl.finalizar_Pedido(id_pedidoValido)).Returns(true); var result = pedidoController.finalizarPedido(id_pedidoValido) as OkObjectResult; Assert.IsNotNull(result); Assert.AreEqual(200, result.StatusCode); Assert.IsNotNull(result.Value); Assert.IsInstanceOf<StatusResponse>(result.Value); Assert.AreEqual(mensajeRetorno.status, ((StatusResponse)result.Value).StatusOk); Assert.AreEqual(mensajeRetorno.mensaje, ((StatusResponse)result.Value).StatusMessage); } [Test] public void Finalizar_ReturnBadRequest() { MensajeRetorno mensajeRetorno = new MensajeRetorno { status = false, mensaje = "Exepción no controlada" }; mockDal.Setup(bl => bl.finalizar_Pedido(id_pedidoInvalido)).Returns(false); var result = pedidoController.finalizarPedido(id_pedidoInvalido) as BadRequestObjectResult; Assert.IsNotNull(result); Assert.AreEqual(400, result.StatusCode); Assert.IsNotNull(result.Value); Assert.IsInstanceOf<StatusResponse>(result.Value); Assert.AreEqual(mensajeRetorno.status, ((StatusResponse)result.Value).StatusOk); Assert.AreEqual(mensajeRetorno.mensaje, ((StatusResponse)result.Value).StatusMessage); } [Test] public void ListarPedidos_Validar() { var DC = new DataContext(); var dal = new DAL_Pedido(DC); var cast = new DAL_Casteo(); var fun = new DAL_FuncionesExtras(DC, cast); var bl = new B_Pedido(dal, cast, fun); var _hub = new Mock<IHubContext<ChatHub>>(); var pedidoController2 = new PedidoController(bl, _hub.Object); // Act var result = pedidoController2.Get(); // Assert Assert.IsNotNull(result); Assert.IsInstanceOf<List<DTPedido>>(result); // Verifica que ninguno de los elementos en la lista sea null Assert.IsTrue(result.TrueForAll(pedido => pedido != null)); } [Test] public void GetPedido_ReturnsCorrectPedido() { // Arrange var idPedido = 1; // Simula la respuesta esperada desde DAL y Casteo var expectedDTPedido = new DTPedido { /* propiedades esperadas */ }; mockDal.Setup(d => d.get_Pedido(idPedido)).Returns(new Pedidos()); mockCasteo.Setup(c => c.CastDTPedido(It.IsAny<Pedidos>())).Returns(expectedDTPedido); // Act var result = pedidoController.GetPedido(idPedido); // Assert Assert.IsNotNull(result); Assert.AreEqual(expectedDTPedido, result); } [Test] public void ListarPedidosActivos_Validar() { var DC = new DataContext(); var dal = new DAL_Pedido(DC); var cast = new DAL_Casteo(); var fun = new DAL_FuncionesExtras(DC, cast); var bl = new B_Pedido(dal, cast, fun); var _hub = new Mock<IHubContext<ChatHub>>(); var pedidoController2 = new PedidoController(bl, _hub.Object); // Act var result = pedidoController2.GetActivos(); // Assert Assert.IsNotNull(result); Assert.IsInstanceOf<List<DTPedido>>(result); // Verifica que ninguno de los elementos en la lista sea null Assert.IsTrue(result.TrueForAll(pedido => pedido != null)); } [Test] public void ListarPedidosMesa_Validar() { var DC = new DataContext(); var dal = new DAL_Pedido(DC); var cast = new DAL_Casteo(); var fun = new DAL_FuncionesExtras(DC, cast); var bl = new B_Pedido(dal, cast, fun); var _hub = new Mock<IHubContext<ChatHub>>(); var pedidoController2 = new PedidoController(bl, _hub.Object); // Act var result = pedidoController2.GetPedidosPorMesa(id_Mesa); // Verifica que ninguno de los elementos en la lista sea null Assert.IsTrue(result.TrueForAll(pedido => pedido != null)); Assert.IsNotNull(result); Assert.IsTrue(result.TrueForAll(result => result != null)); Assert.IsTrue(result.TrueForAll(result => result.id_Mesa == id_Mesa)); Assert.IsInstanceOf<List<DTPedido>>(result); } [Test] public void ListarPedidosTipo_Validar() { var DC = new DataContext(); var dal = new DAL_Pedido(DC); var cast = new DAL_Casteo(); var fun = new DAL_FuncionesExtras(DC, cast); var bl = new B_Pedido(dal, cast, fun); var _hub = new Mock<IHubContext<ChatHub>>(); var pedidoController2 = new PedidoController(bl, _hub.Object); var tipo = (Domain.Enums.Categoria)1; // Act var result = pedidoController2.GetPedidosPorTipo(tipo); // Verifica que ninguno de los elementos en la lista sea null Assert.IsTrue(result.TrueForAll(pedido => pedido != null)); Assert.IsNotNull(result); Assert.IsTrue(result.TrueForAll(result => result != null)); Assert.IsTrue(result.TrueForAll(result => result.tipo == tipo)); Assert.IsInstanceOf<List<DTPedido>>(result); } } }
## API Aluraflix `Descrição:` Este projeto foi desenvolvido com o objetivo de aprimorar minhas habilidades em PHP/Laravel, focando na criação de uma API Rest. Este projeto atende aos requisitos do desafio Alura Challenge-05, conhecido como 'AluraFlix'.. Trata-se de um sistema CRUD que permite às pessoas postar e assistir a vídeos sob demanda. `Tecnologias:` - PHP 8.2 - Laravel 8 - MySQL - Docker ## Funcionamento e Endpoints Para utilizar a API e acessar a maioria de seus endpoints, é necessário realizar a autenticação, se registrando com um email, name (nome), senha (password) e confirmação de senha (password_confirmation), a senha deve conter 8 caracteres, uma letra maiuscula, um numero e um caracter especial, usando o seguinte endpoint: `POST: /api/registrar` ```json { "name": "Fulano de Tal", "email": "[email protected]", "password": "Pass123*", "password_confirmation": "Pass123*" } ``` Resposta esperada: ```json "1|cileIpbIzdj3yJNws2zRU5oRkY03PgTeFSbezr4X" ``` O token retornado deve ser utilizado nas requisições no cabeçalho de 'Authorization' como um Bearer token. ## Usuarios Depois de criado um novo usuario no sistema, ele pode manipular os recursos relacionados a usuarios com os seguintes endpoints: - `POST: /api/login` - Retorna token de autenticação valido Exemplo de uso: ```json { "email": "[email protected]", "password": "Pass123*" } ``` Resposta esperada: ```json "1|cileIpbIzdj3yJNws2zRU5oRkY03PgTeFSbezr4X" ``` **Requer autenticação!** - `GET: /api/usuarios` - Retonar de forma paginada todos os usuarios - `GET: /api/usuarios/<id do usuario>` - Retorna usuario informado no ID - `PATCH: /api/usuarios` - Atualiza name (nome) do usuario atual Exemplo de uso: ```json { "name": "Ciclano de Tal" } ``` Retorno esperado: ```json { "id": 1, "name": "Ciclano de Tal", "email": "[email protected]", "email_verified_at": null, "created_at": "2024-01-07T14:29:48.000000Z", "updated_at": "2024-01-07T15:06:33.000000Z" } ``` - `DELETE: /api/usuario` - Deleta registro do usuario atual Para deletar o registro do usuario autenticado atual é preciso fornecer a senha correta do usuario e uma confirmação da senha. Exemplo de uso: ```json { "password": "Test123*", "password_confirmation": "Test123*" } ``` Retorno esperado é o status '204 no content'. ## Categorias **Requer autenticação!** As categorias são usadas para classificar os vídeos, organizando-os e facilitando a busca e navegação na API. Aqui estão todos os endpoints relacionados aos recursos de Categoria: - `GET: /api/categorias` - Retorna todas as categorias Salvas Retorna de forma paginada todas as categorias armazenadas no banco de dados. - `POST: /api/categorias` - Cria nova categoria Deve ser fornecido um título em caixa alta e uma cor hexadecimal válida em CSS. Exemplo de uso: ```json { "titulo": "LIVRE", "cor": "Ffffff" } ``` retorno esperado: ```json { "mensagem": "Categoria criada com sucesso: /api/categoria/1", "data": { "titulo": "LIVRE", "cor": "Ffffff", "updated_at": "2024-01-07T14:42:04.000000Z", "created_at": "2024-01-07T14:42:04.000000Z", "id": 1 } } ``` - `GET: /api/categorias/<id da categoria>` - Obtem uma categoria especifica por ID Retorna um JSON da categoria informada como id na url. Caso não exista, será retornado o status '404 not found'. - `PUT: /api/categorias/<id da categoria>` - Atualiza uma categoria É possivel atualizar o titulo ou a cor de uma categoria, caso um destes atributos não seja especificado então não será atualizado. Exemplo de uso: ```json { "cor": "008000" } ``` Retorno esperado: ```json { "id": 1, "titulo": "LIVRE", "cor": "008000", "created_at": "2024-01-07T14:42:04.000000Z", "updated_at": "2024-01-07T14:58:14.000000Z" } ``` - `GET: /api/categorias/<id da categoria>/videos` - Obtem videos por categoria Retorna de forma paginada todos os videos relacionados a categoria informada. - `DELETE: /api/categorias/<id da categoria>` - Deleta categira do banco de dados ## Videos Endpoints para manipular os recursos de videos: - `GET: /api/videos/free` - Retona lista de 5 videos diarios Todos os dias serão retornados 5 videos aleatorios para serem consumidos de forma livre, sem a necessidade de autenticação na API. **Requer autenticação!** - `GET: /api/videos` - Retona paginação de videos - `GET: /api/videos/<id do video>` - Retorna video informado por ID - `GET: /api/videos?search=<pesquisa do usuario>` - Retorna videos relacionados a pesquisa Esse endpoint retorna de forma paginada todos os videos cujo o titulo estiver relacionado a pesquisa fornecida pelo usuario na url no parametro 'search'. - `POST: /api/videos` - Cria novo registro de video Para criar um novo registro de video deve ser fornecido de forma obrigatoria um titulo, uma descrição e uma url valida. Sempre que se cria um novo registro, não é necessario fornecer um 'categoria_id'. Caso não informado, a categoria atribuida será a 'LIVRE' de id = 1. Exemplo de uso: ```json { "titulo": "Carnaval", "descricao": "Teste", "url": "https://www.youtube.com/watch?v=zWGBfUgSpH8&ab_channel=Gaveta", "categoria_id": 1 } ``` - `PUT: /api/videos/<id do video>` - Atualiza video infromado por ID O que pode ser atualizado são titulo, descrição, url e categoria. Caso algum atributo não seja informado será mantida a informação original. Caso tente atualizar a categoria para uma categoria que não existe será retornada resposta status '400 bad request'. Exemplo de uso: ```json { "categoria_id": 2 } ``` Retorno esperado: ```json { "titulo": "Carnaval", "descricao": "Teste", "url": "https://www.youtube.com/watch?v=zWGBfUgSpH8&ab_channel=Gaveta", "categoria_id": 2 } ``` - `DELETE: /api/videos/<id do video>` - Deleta video do banco de dados Retorno esperado é de status '204 no content'.
export class HTMLCampusParser { private static bde_fromsrc(img_src: string) { let text = ''; if (img_src.length > 0) { const list_src = img_src.split('/'); if (list_src.length >= 3) { text = list_src[list_src.length - 2] + list_src[list_src.length - 1]; } } return text; } static bde_get_answer(type: number, document: HTMLElement) { if (type == 0) { const jsondata = []; const listelems = document.querySelectorAll( 'div.answer input[type="checkbox"]', ) as unknown as HTMLInputElement[]; if (listelems.length > 0) { for (let i = 0; i < listelems.length; i++) { const thischecked = listelems[i].checked; let thisvalue = listelems[i].parentNode?.textContent ?.trim() .toLowerCase(); if (thisvalue?.length == 0) { const elemimg = listelems[i].parentNode?.querySelector('img'); if (elemimg) { thisvalue = this.bde_fromsrc(elemimg.src); } } const item = { checked: thischecked, value: thisvalue }; jsondata.push(item); } } return JSON.stringify(jsondata) || ''; } else if (type == 1) { const jsondata = []; const listtext = document.querySelectorAll('table.answer td.text'); const listselect = document.querySelectorAll( 'table.answer select', ) as unknown as HTMLSelectElement[]; if (listtext.length > 0 && listtext.length == listselect.length) { for (let i = 0; i < listtext.length; i++) { let thistext = listtext[i].textContent?.trim().toLowerCase(); if (thistext?.length == 0) { const elemimg = listtext[i].parentNode?.querySelector('img'); if (elemimg) { thistext = this.bde_fromsrc(elemimg.src); } } const thisvalue = listselect[i].options[ listselect[i].selectedIndex ].text .trim() .toLowerCase(); const item = { text: thistext, value: thisvalue }; jsondata.push(item); } } return JSON.stringify(jsondata) || ''; } else if (type == 2) { const jsondata = []; const listelems = document.querySelectorAll( 'div.answer input[type="radio"]', ) as unknown as HTMLInputElement[]; if (listelems.length > 0) { for (let i = 0; i < listelems.length; i++) { const thischecked = listelems[i].checked; let thisvalue = listelems[i].parentNode?.textContent ?.trim() .toLowerCase(); if (thisvalue?.length == 0) { const elemimg = listelems[i].parentNode?.querySelector('img'); if (elemimg) { thisvalue = this.bde_fromsrc(elemimg.src); } } const item = { checked: thischecked, value: thisvalue }; jsondata.push(item); } } return JSON.stringify(jsondata) || ''; } else if (type == 3) { const jsondata = { text: '' }; const el = document.querySelector( 'span.answer input[type="text"]', ) as unknown as HTMLInputElement; if (el) { jsondata.text = el.value; } return JSON.stringify(jsondata) || ''; } else if (type == 4) { const jsondata = []; const listli = document.querySelectorAll( 'div.answer.ordering li', ) as unknown as HTMLInputElement[]; if (listli.length > 0) { for (let i = 0; i < listli.length; i++) { const thistext = listli[i].textContent?.trim().toLowerCase(); const item = { text: thistext }; jsondata.push(item); } } return JSON.stringify(jsondata) || ''; } else if (type == 5) { const jsondata = []; const listTR = document.querySelectorAll( 'table.answer tr', ) as unknown as HTMLInputElement[]; if (listTR.length > 0) { for (let i = 0; i < listTR.length; i++) { const nodeTDText = listTR[i].querySelector('td.text'); const nodeLI = listTR[i].querySelector( 'td.control.visibleifjs li[data-id]', ); if (nodeTDText && nodeLI) { const thistext = nodeTDText.textContent?.trim().toLowerCase(); const thisvalue = nodeLI.textContent?.trim().toLowerCase(); const item = { text: thistext, value: thisvalue }; jsondata.push(item); } } } return JSON.stringify(jsondata) || ''; } } //this is used to fill answers only static bde_mainfunc(answerData: string, type: number, document: HTMLElement) { try { const jsonArr = JSON.parse(answerData); let answerElements; if (type == 0) { //https://campus.fa.ru/mod/quiz/view.php?id=186319 checkbox images answerElements = document.querySelectorAll( 'div.answer input[type="checkbox"]', ) as NodeListOf<HTMLInputElement>; for (const box of answerElements) { const checkboxValue = box.parentNode?.textContent?.trim().toLowerCase() || this.bde_fromsrc(box.parentNode?.querySelector('img')?.src || ''); const state = jsonArr.find( (e: any) => e.value == checkboxValue, )?.checked; if (state == box.checked) continue; box.checked = state; } } else if (type == 1) { //https://campus.fa.ru/mod/quiz/attempt.php?attempt=1020486&cmid=483589&page=2 select example const answerTexts = document.querySelectorAll('table.answer td.text'); answerElements = document.querySelectorAll( 'table.answer select', ) as NodeListOf<HTMLSelectElement>; for (let i = 0; i < answerTexts.length; i++) { const text = answerTexts[i].textContent?.trim().toLowerCase() || this.bde_fromsrc(answerTexts[i].querySelector('img')?.src || ''); const value = jsonArr.find((e: any) => e.text == text)?.value; const optionIndex = Array.from(answerElements[i].options).findIndex( (e: any) => e.text.trim().toLowerCase() == value, ); //check if update is needed if (answerElements[i].selectedIndex == optionIndex) continue; answerElements[i].selectedIndex = optionIndex; } } else if (type == 2) { answerElements = document.querySelectorAll( 'div.answer input[type="radio"]', ) as NodeListOf<HTMLInputElement>; if ( Array.from(answerElements) .map((e: any) => e.checked) .some((e) => e) ) return; //check if already answered const checkedValue = jsonArr.find((e: any) => e.checked)?.value; let checkedRadio = Array.from(answerElements).find( (e: any) => e.parentNode?.textContent?.trim().toLowerCase() == checkedValue, ); if (!checkedRadio) checkedRadio = Array.from(answerElements).find( (e: any) => this.bde_fromsrc(e.parentNode?.querySelector('img')?.src) == checkedValue, ); //image radio checkedRadio!.checked = true; } else if (type == 3) { answerElements = document.querySelector( 'span.answer input[type="text"]', ) as HTMLInputElement; if (answerElements.value) return; // check if already answered answerElements.value = jsonArr['text']; } } catch (error) { console.log(error); } } }
/* Sưu tầm bởi @nguyenvanhieuvn Thực hành nhiều bài tập hơn tại https://luyencode.net/ */ #include<stdio.h> #include<conio.h> #include<math.h> #define MAX 100 void NhapMang(int a[][MAX], int &dong, int &cot) { //Nhập số dòng do { printf("\nNhap vao so dong: "); // Cách tà đạo: scanf("dong =%d",&dong); // Lúc nhập phải viết thêm chữ ( dong = ) ở khung console scanf("%d",&dong); if(dong < 1 || dong > MAX) { printf("\nSo dong khong hop le. Xin kiem tra lai!"); } }while(dong < 1 || dong > MAX); //Nhập số cột do { printf("\nNhap vao so cot: "); scanf("%d",&cot); if(cot < 1 || cot > MAX) { printf("\nSo cot khong hop le. Xin kiem tra lai!"); } }while(cot < 1 || cot > MAX); for(int i = 0; i < dong; i++) { for(int j = 0; j < cot; j++) { printf("\nNhap a[%d][%d] = ", i, j); scanf("%d", &a[i][j]); } } } void XuatMang(int a[][MAX], int dong, int cot) { for(int i = 0; i < dong; i++) { for(int j = 0; j < cot; j++) { printf("%4d", a[i][j]); } printf("\n\n"); } } int TimPhanTuLonNhatDongICotJ(int a[][MAX], int dong, int cot, int i, int j) { int Max = a[i][0]; // Tìm phần tử lớn nhất dòng i for(int k = 1; k < dong; k++) { Max = (Max < a[i][k]) ? a[i][k] : Max; } // Tìm phần tử lớn nhất cột j for(int k = 0; k < cot; k++) { Max = (Max < a[k][j]) ? a[k][j] : Max; } return Max; } void XayDungMaTranB(int a[][MAX], int dong, int cot, int b[][MAX]) { for(int i = 0; i < dong; i++) { for(int j = 0; j < cot; j++) { b[i][j] = TimPhanTuLonNhatDongICotJ(a, dong, cot, i, j); } } } int main() { int a[MAX][MAX],b[MAX][MAX], dong, cot; NhapMang(a, dong, cot); XuatMang(a, dong, cot); XayDungMaTranB(a, dong, cot, b); printf("\nMa tran b[i][j] = lon nhat dong i, cot j cua ma tran A \n"); XuatMang(b, dong, cot); getch(); return 0; }
class Node: def __init__(self, name, type_): self.name = name self.type = type_ self.inputs = {} self.output = None self.certainty = None def set_input(self, value, port, certainty): self.inputs[port] = (value, certainty) def compute_output(self): if self.type == 'adder': values, certainties = zip(*self.inputs.values()) self.output = sum(values) self.certainty = min(certainties) # Assuming the minimum certainty for simplicity elif self.type == 'multiplier': values, certainties = zip(*self.inputs.values()) self.output = values[0] * values[1] self.certainty = min(certainties) return self.output class Circuit: def __init__(self): self.nodes = {} self.connections = [] def add_node(self, name, type_): self.nodes[name] = Node(name, type_) def add_connection(self, from_node, to_node, port): self.connections.append((from_node, to_node, port)) def request_value(self, node): value = float(input(f"Please enter a value for node {node}: ")) certainty = float(input("Enter Certainty Factor for node (0.0 to 1.0): ")) certainty = max(0.0, min(1.0, certainty)) # Clamp certainty to [0.0, 1.0] return value, certainty def evaluate(self, node): if self.nodes[node].type == 'input': value, certainty = self.request_value(node) self.nodes[node].set_input(value, 1, certainty) self.nodes[node].output = value # Direct input to output for input nodes self.nodes[node].certainty = certainty else: for from_node, to_node, port in self.connections: if to_node == node and from_node not in self.nodes[node].inputs: self.evaluate(from_node) output = self.nodes[from_node].output certainty = self.nodes[from_node].certainty self.nodes[to_node].set_input(output, port, certainty) self.nodes[node].compute_output() def query_node(self): node = input("Which node are you interested in? (a-j or q to quit): ") if node == 'q': return False if node in self.nodes: self.evaluate(node) print(f"The output value at node {node} is {self.nodes[node].output} with a certainty of {self.nodes[node].certainty}") else: print("Node not found.") return True # Example usage circuit = Circuit() # Adding nodes and their types nodes_info = { 'a': 'input', 'b': 'input', 'c': 'input', 'd': 'input', 'e': 'adder', 'f': 'adder', 'g': 'multiplier', 'i': 'output', 'j': 'output' } for node, type_ in nodes_info.items(): circuit.add_node(node, type_) # Adding connections connections_info = [ ('a', 'f', 1), ('b', 'e', 1), ('c', 'e', 2), ('d', 'g', 2), ('e', 'f', 2), ('e', 'g', 1), ('f', 'i', 1), ('g', 'j', 1) ] for from_node, to_node, port in connections_info: circuit.add_connection(from_node, to_node, port) # Interactive query while circuit.query_node(): pass
/* 374. Guess Number Higher or Lower We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num), which returns 3 possible results: -1: The number I picked is lower than your guess (i.e. pick < num). 1: The number I picked is higher than your guess (i.e. pick > num). 0: The number I picked is equal to your guess (i.e. pick == num). Return the number that I picked. Example 1: Input: n = 10, pick = 6 Output: 6 Example 2: Input: n = 1, pick = 1 Output: 1 Example 3: Input: n = 2, pick = 1 Output: 1 */ /** * Forward declaration of guess API. * @param num your guess * @return -1 if num is lower than the guess number * 1 if num is higher than the guess number * otherwise return 0 * int guess(int num); */ public class Solution extends GuessGame { public int guessNumber(int n) { int l=1,r=n,mid=1; while(l<=r){ mid=l+(r-l)/2; if(guess(mid)==0) return mid; else if(guess(mid)==-1) r=mid-1; else l=mid+1; } return -1; } }
import React, { useState } from "react"; import "./deliveryForm.style.css"; const defaultDeliveryData = { firstName: "", lastName: "", street: "", city: "", zipcode: "", state: "", mobilePhone: "", workPhone: "", deliveryDate: "", isSignatureRequired: false, }; const DeliveryForm = () => { const [deliveryData, setDeliveryData] = useState(defaultDeliveryData); const [signature, setSignature] = useState(""); const onSubmitHandler = (e) => { console.log(deliveryData); e.preventDefault(); if (deliveryData.isSignatureRequired) { setSignature(`${deliveryData.firstName} ${deliveryData.lastName}`); } else { setSignature(""); } }; const onChangeHandler = (e) => { setDeliveryData({ ...deliveryData, [e.target.name]: e.target.value }); }; const onCheckedHandler = (e) => { setDeliveryData({ ...deliveryData, isSignatureRequired: e.target.checked, }); }; return ( <div className="delivery-form-container"> <div className="delivery-form-box"> {deliveryData.isSignatureRequired && ( <p className="signed">{signature}</p> )} <h1>Delivery Confirmation Form</h1> <form onSubmit={onSubmitHandler}> <label forHtml="firstName">Name:</label> <div className="input-fields medium-input"> <input name="firstName" placeholder="First name" onChange={onChangeHandler} /> <input name="lastName" placeholder="Last name" onChange={onChangeHandler} /> </div> <label forHtml="street">Address:</label> <div className="input-fields long-input"> <input name="street" placeholder="Street" onChange={onChangeHandler} /> <input name="city" placeholder="City" onChange={onChangeHandler} /> </div> <label></label> <div className="input-fields medium-input"> <input name="zipcode" placeholder="Zip Code" onChange={onChangeHandler} /> <input name="state" placeholder="State" onChange={onChangeHandler} /> </div> <label forHtml="mobilePhone">Phone number:</label> <div className="input-fields medium-input"> <input name="mobilePhone" type="number" placeholder="Mobile" onChange={onChangeHandler} /> <input name="workPhone" type="number" placeholder="Work" onChange={onChangeHandler} /> </div> <label forHtml="deliveryDate">Date of delivery</label> <div className="input-fields long-input"> <input name="deliveryDate" type="date" onChange={onChangeHandler} /> <div className="signature"> <input name="isSignatureRequired" type="checkbox" onChange={onCheckedHandler} /> <label forHtml="isSignatureRequired">Signature</label> </div> </div> <br /> <div className="sendBtn"> <button className="pushable" type="submit"> <span className="shadow"></span> <span className="edge"></span> <span className="front">Send</span> </button> </div> </form> </div> </div> ); }; export default DeliveryForm;
import React from 'react'; import PropTypes from 'prop-types'; import {useTranslation} from 'react-i18next'; import JContentConstants from '~/JContent/JContent.constants'; import {Download, Lock, Typography} from '@jahia/moonstone'; import {shallowEqual, useSelector} from 'react-redux'; import {useNodeChecks, useNodeInfo} from '@jahia/data-helper'; import {ACTION_PERMISSIONS} from '../../../actions/actions.constants'; import styles from './EmptyDropZone.scss'; import clsx from 'clsx'; import {DisplayAction} from '@jahia/ui-extender'; import {getButtonRenderer} from '~/utils/getButtonRenderer'; const ButtonRenderer = getButtonRenderer({labelStyle: 'short', defaultButtonProps: {className: styles.button, size: 'big'}}); const EmptyDropZone = ({component: Component, isCanDrop, uploadType, selector}) => { const currentState = useSelector(selector, shallowEqual); const {t} = useTranslation('jcontent'); const permissions = useNodeChecks({ path: `/sites/${currentState.site}`, language: currentState.language }, { requiredSitePermission: [ACTION_PERMISSIONS.uploadFilesAction, ACTION_PERMISSIONS.importAction] }); // Check lock status for node const nodeInfo = useNodeInfo( {path: currentState.path}, {getLockInfo: true, getIsNodeTypes: ['jmix:markedForDeletion']}, {fetchPolicy: 'network-only'} ); if (permissions.loading || nodeInfo.loading) { return 'Loading...'; } if (nodeInfo.node?.lockOwner) { let lockReason; if (nodeInfo.node['jmix:markedForDeletion']) { lockReason = t('label.contentManager.contentStatus.markedForDeletion'); } else { lockReason = t('label.contentManager.lockedBy', {userName: nodeInfo.node.lockOwner.value}); } return ( <Component data-type="emptyZone" className={styles.emptyZone}> <Typography variant="heading"> {t('jcontent:label.contentManager.fileUpload.locked')} { lockReason ? `: ${lockReason}` : ''} </Typography> <Lock/> </Component> ); } if (currentState.mode === 'category') { return ( <Component data-type="emptyZone" className={styles.emptyZone}> <Typography variant="heading">{t('jcontent:label.categoryManager.noSubCategory')}</Typography> <DisplayAction actionKey="createContent" render={ButtonRenderer} path={currentState.path} nodeTypes={['jnt:category']}/> </Component> ); } if (uploadType === JContentConstants.mode.UPLOAD && permissions.node.site.uploadFilesAction) { return ( <Component data-type="upload" className={clsx(styles.dropZone, isCanDrop && styles.dropZoneEnabled)}> {!isCanDrop && <Typography variant="heading">{t('jcontent:label.contentManager.fileUpload.dropMessage')}</Typography>} {isCanDrop && <Typography variant="heading">{t('jcontent:label.contentManager.fileUpload.drop')}</Typography>} <Download/> </Component> ); } if (uploadType === JContentConstants.mode.IMPORT && permissions.node.site.importAction) { return ( <Component data-type="import" className={clsx(styles.dropZone, isCanDrop && styles.dropZoneEnabled)}> {!isCanDrop && <Typography variant="heading">{t('jcontent:label.contentManager.import.dropMessage')}</Typography>} {isCanDrop && <Typography variant="heading">{t('jcontent:label.contentManager.import.drop')}</Typography>} <Download/> </Component> ); } return ( <Component data-type="emptyZone" className={styles.emptyZone}> <Typography variant="heading">{t('jcontent:label.contentManager.fileUpload.nothingToDisplay')}</Typography> <Typography>{t('jcontent:label.contentManager.fileUpload.nothingToDisplay2')}</Typography> </Component> ); }; EmptyDropZone.propTypes = { component: PropTypes.string.isRequired, uploadType: PropTypes.string, isCanDrop: PropTypes.bool, selector: PropTypes.func }; EmptyDropZone.defaultProps = { selector: state => ({ site: state.site, language: state.language, path: state.jcontent.path, mode: state.jcontent.mode }) }; export default EmptyDropZone;
using Newtonsoft.Json; namespace DHLClient { /// <summary> /// Requests used for creating or updating a trade entity detail /// </summary> public class TradeEntityDetailRequestModel { #region Public Properties /// <summary> /// The postal address details /// </summary> [JsonRequired] [JsonProperty("postalAddress")] public ShipperDetailRequestModel? PostalAddress { get; set; } /// <summary> /// The contact information /// </summary> [JsonRequired] [JsonProperty("contactInformation")] public ShipmentContactInformationRequestModel? ContactInformation { get; set; } /// <summary> /// The business party type /// </summary> /// <example>business</example> [JsonProperty("typeCode")] [JsonConverter(typeof(BusinessPartyToStringJsonConverter))] public BusinessPartyType? TypeCode { get; set; } /// <summary> /// The registration number details /// </summary> [JsonProperty("registrationNumbers")] public IEnumerable<EntityProfileRegistrationNumberRequestModel>? RegistrationNumbers { get; set; } #endregion #region Constructors /// <summary> /// Default constructor /// </summary> public TradeEntityDetailRequestModel() : base() { } #endregion } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { LoginComponent } from './featured/public/login/login.component'; import { CatalogComponent } from './featured/private/catalog/catalog.component'; import { CreateComponent } from './featured/private/create/create.component'; import { DetailsComponent } from './featured/private/details/details.component'; import { ProfileComponent } from './featured/private/profile/profile.component'; import { RegisterComponent } from './featured/public/register/register.component'; import { PaymentSuccessfullComponent } from './featured/private/payment-successfull/payment-successfull.component'; import { PaymentUnsuccessfullComponent } from './featured/private/payment-unsuccessfull/payment-unsuccessfull.component'; import { HomeComponent } from './featured/private/home/home.component'; import {TestComponent} from "./core/components/test/test.component"; const routes: Routes = [ { path: '', pathMatch: 'full', redirectTo: '/home', }, { path: 'login', pathMatch: 'full', component: LoginComponent, }, { path: 'register', pathMatch: 'full', component: RegisterComponent, }, { path: 'catalog', pathMatch: 'full', component: CatalogComponent, }, { path: 'profile/:id', pathMatch: 'full', component: ProfileComponent, }, { path: 'createOffer', pathMatch: 'full', component: CreateComponent, }, { path: 'offerDetails/:id', pathMatch: 'full', component: DetailsComponent, }, { path: 'successfulPayment', pathMatch: 'full', component: PaymentSuccessfullComponent, }, { path: 'unsuccessfulPayment', pathMatch: 'full', component: PaymentUnsuccessfullComponent, }, { path: 'home', pathMatch: 'full', component: HomeComponent, }, { path: 'test', pathMatch: 'full', component: TestComponent, }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
import 'package:admin/apis/permissions.dart'; import 'package:admin/models/permissions/permissions.dart'; import 'package:admin/screens/permissions/edit_dialog.dart'; import 'package:admin/utils/colors.dart'; import 'package:admin/utils/toast.dart'; import 'package:admin/utils/widgets/common.dart'; import 'package:flutter/material.dart'; class PermissionTile extends StatelessWidget { final PermissionDetails permission; final Function onDelete; const PermissionTile( {super.key, required this.permission, required this.onDelete}); @override Widget build(BuildContext context) { return ListTile( key: ValueKey(permission.id), leading: Icon( Icons.security, color: Theme.of(context).colorScheme.secondary, ), title: Text(permission.name, style: Theme.of(context) .textTheme .titleMedium! .copyWith(fontWeight: FontWeight.bold)), subtitle: Wrap( spacing: 10, runSpacing: 5, children: [ SubTextWithIcon(icon: Icons.category, text: permission.category), SubTextWithIcon( icon: Icons.description, text: permission.description), ], ), trailing: IconButton( icon: const Icon( Icons.delete, ), onPressed: () { showDialog( context: context, builder: (context) => AlertDialog( title: const Text('Delete Permission'), content: Text( 'Are you sure you want to delete `${permission.name}` permission?'), actions: <Widget>[ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('Cancel'), ), TextButton( onPressed: () async { final res = await PermissionService.deletePermission(permission.id); if (res.error.isNotEmpty) { MyToast.error(res.error); return; } else { MyToast.success("Permission deleted successfully!"); } onDelete(); // ignore: use_build_context_synchronously Navigator.of(context).pop(); }, child: const Text( 'Delete', style: TextStyle(color: AppColors.error), ), ), ], ), ); }, ), onTap: () { showDialog( context: context, builder: (context) => EditPermissionDialog(permission: permission), ); }, ); } }
import { useColorMode, Flex, Box } from "@chakra-ui/react"; import styled from "@emotion/styled"; import DarkModeSwitch from "./DarkModeSwitch"; const NavContainer = ({ children }) => { const { colorMode } = useColorMode(); const bgColor = { light: "#FBEAEB", dark: "#4831D4", }; const navHoverBg = { light: "gray.100", dark: "gray.300", }; const color = { light: "black", dark: "white", }; const StickNav = styled(Flex)` position: sticky; z-index: 10; top: 0; transition: height 0.5s, line-height 0.5s; `; return ( <Box bg={[colorMode]}> <StickNav flexDirection="row" justifyContent="flex-end" alignItems="flex-end" maxWidth={["330", "400", "450"]} as="nav" px={[2, 6, 6]} py={2} mb={[0, 0, 8]} ms="auto" > <DarkModeSwitch /> </StickNav> <Flex as="main" justifyContent="center" flexDirection="column" bg={bgColor[colorMode]} color={color[colorMode]} px={[0, 4, 4]} mt={[4, 8, 8]} > {children} </Flex> </Box> ); }; export default NavContainer;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - BillingManagementWebApp</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/bootstrap-zephyr.css" /> <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/BillingManagementWebApp.styles.css" asp-append-version="true" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> </head> <body> <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container-fluid"> <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">BillingManagementWebApp</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a> </li> @if (User.Identity.IsAuthenticated) { <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="User" asp-action="Index">User</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Flat" asp-action="Index">Flat</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Due" asp-action="Index">Due</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Invoice" asp-action="Index">Invoice</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Message" asp-action="Index">Message</a> </li> } <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> </li> </ul> <div> @if (User.Identity.IsAuthenticated) { <a id="btn-logout" class="btn btn-outline-secondary text-md-end" asp-controller="Login" asp-action="logout">Logout</a> } else { <a id="btn-login" class="btn btn-success text-md-end" asp-controller="Login" asp-action="Index">Login</a> } </div> </div> </div> </nav> </header> <div class="container"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> &copy; 2023 - BillingManagementWebApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> </div> </footer> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @await RenderSectionAsync("Scripts", required: false) <script> $(document).ajaxError(function (event, xhr, settings) { if (xhr.status === 401) { var responseJSON = xhr.responseJSON; var isTokenExpired = responseJSON && responseJSON.error === 'token_expired'; if (isTokenExpired) { refreshToken(); } } }); function refreshToken() { $.ajax({ url: '/refreshToken', method: 'GET', success: function (response) { retryFailedRequest(); }, error: function (xhr) { var responseJSON = xhr.responseJSON; var errorMessage = responseJSON && responseJSON.error_message; console.log('Refresh token request failed:', errorMessage); window.location.href = '/Login'; } }); } function retryFailedRequest() { var originalRequest = JSON.parse(sessionStorage.getItem('originalRequest')); $.ajax(originalRequest); } </script> </body> </html>
<!DOCTYPE html> <html lang="ko"> <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>css_font</title> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300&display=swap" rel="stylesheet"> <style> * { margin: 0; padding: 0; font-family: 'Noto Sans KR', sans-serif; } #header { padding: 2vw; border-bottom: 1px dashed #dedede; } #header h1 { font-size: 4vw; margin-bottom: 2vw; } #header nav ul li { list-style: none; display: inline; } #header nav ul li a { text-decoration: none; color: #000; border: 1px solid #000; padding: 0.1vw 1vw 0.3vw 1vw; display: inline-block; } #header nav ul li a:hover { background-color: #000; color: #fff; } /* 컨텐츠 */ #contents { padding: 2vw; } #contents .menu { border-bottom: 1px dashed #dedede; padding-bottom: 2vw; } #contents .menu ul li { list-style: none; display: inline; } #contents .menu ul li a { text-decoration: none; color: #000; border: 1px solid #000; background-color: #000; color: #fff; padding: 0.1vw 1vw 0.3vw 1vw; word-break: keep-all; margin-top: 0.7vw; margin-bottom: 0.7vw; display: inline-block; } .article { padding: 2vw 0; line-height: 1.6; } .article h2 { font-weight: normal; margin-bottom: 10px; } .article h3 { font-weight: normal; margin-bottom: 10px; } .article p { margin-bottom: 10px; } .article .table { width: 100%; border-spacing: 0; border-collapse: collapse; margin-bottom: 10px; } .article .table tr th { border: 1px solid #dedede; padding: 10px; font-weight: normal; background-color: #f5f5f5; } .article .table tr td { border: 1px solid #dedede; padding: 10px; } .article .table .center { text-align: center; } .article .box { background-color: #ededed; padding: 10px; } /* 미디어 쿼리 */ @media (max-width: 800) { #header { padding: 16px; } #header h1 { font-size: 40px; } #header nav ul li a { padding: 5px 10px; font-size: 18px; } #contents { padding: 16px; } } </style> </head> <body> <header id="header"> <h1>CSS</h1> <nav> <ul> <li><a href="">기초</a></li> <li><a href="">주제</a></li> <li><a href="">알파벳</a></li> </ul> </nav> </header> <section id="contents"> <nav class="menu"> <ul> <li><a href="font.html">font-size</a></li> <li><a href="">#</a></li> <li><a href="#">#</a></li> </ul> </nav> <article class="article"> <h2>font-size</h2> <h1>css <br>문자 크기 속성 기본 크기는 16px</h1> <br> <h1>px <br>해상도에 따라 달라지는 기본 단위</h1> <p class="box">font-size : 12px;</p> <br> <h1>% <br>부모 요소의 글자 크기를 100% 기준으로 계산한 %단위</h1> <p class="box">font-size : 150%;</p> <p>기본 단위에 150%가 된다</p> <br> <h1>em <br>부모 요소의 글자 100%를 기준으로 계산한 1/100단위</h1> <p class="box">font-size : 1.5em;</p> <br> <h1>rem <br>rem은 em과 비슷하지만 부모 요소가 아닌 "최상위 요소"로써의 크기로 100%기준으로 계산</h1> <p class="box">font-size : 1.5rem;</p> <br> <h1>vw, vh <br> vw는 뷰포트 너비 값의 1/100 단위 <br> vh는 뷰포트 높이 값의 1/100 단위 </h1> <p class="box">font-size : 10vw;</p> </article> </section> </body> </html>
from pydantic import BaseModel class ActionBase(BaseModel): title: str description: str class ActionCreate(ActionBase): pass class Action(ActionBase): id: int lover_id: int | None = None class Config: orm_mode = True class LoverBase(BaseModel): email: str class LoverCreate(LoverBase): hashed_password: str class Lover(LoverBase): id: int is_active: bool actions: list[Action] = [] class Config: orm_mode = True
import React, { useEffect, useState } from 'react' import StartupList from '../components/StartupList'; import { getAllStartups, getStartupByIndustry,searchStartups } from '../services/api'; import FilterStartups from '../components/FilterStartups'; import SearchStartups from '../components/SearchStartups'; import Navbar from '../components/Navbar'; import { Spinner } from 'flowbite-react'; function Home() { const [startupData, setStartupData] = useState([]); const [filterData,setFilterData]=useState([]); const [loading,setLoading]=useState(true); //fetching all startup const getStartup = async () => { try{ setLoading(true) const data = await getAllStartups(); setStartupData(data); setFilterData(data) }catch(err){ console.error('Error fetching all startups:', err); }finally{ setLoading(false); } } useEffect(() => { getStartup(); }, []); //filtering startup by industry name const handleFilterData = async (industry) => { try { const data = await getStartupByIndustry(industry); setFilterData(data) } catch (err) { console.error('Error filtering startups by industry:', err); } } //searching startup const handleSearch=async (query)=>{ try{ const data=await searchStartups(query); setFilterData(data); }catch(err){ console.error('Error handling search:', err); } } if(loading){ return <Spinner aria-label="Left-aligned spinner example" size="xl" /> } return ( <div className='w-full'> <Navbar /> { Array.isArray(startupData) && Array.isArray(filterData) && <div className='flex flex-row gap-11'> <FilterStartups startupData={startupData} handleFilterData={handleFilterData} /> <div className='flex-grow-1'> <SearchStartups handleSearch={handleSearch}/> <StartupList startupData={filterData} /> </div> </div> } {!Array.isArray(startupData) && <p className='text-3xl text-red-900 font-bold'>Start the server</p>} </div> ) } export default Home
import cv2 from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.image import Image from kivy.uix.label import Label from kivy.graphics.texture import Texture from kivy.clock import Clock from kivy.config import Config import os import numpy as np # Configura la anchura y altura deseadas de la ventana Config.set('graphics', 'width', '600') # Ajustar según necesidad Config.set('graphics', 'height', '600') # Ajustar según necesidad class KivyCamera(BoxLayout): def __init__(self, **kwargs): super(KivyCamera, self).__init__(**kwargs) self.orientation = 'vertical' self.fps = 30 # Ajustar el tamaño de Image self.image = Image(size_hint=(1, 0.85)) # Ajusta esto según necesites self.add_widget(self.image) self.status_label = Label(text='Estado del Reconocimiento: Reconociendo...', size_hint=(1, 0.05)) self.add_widget(self.status_label) self.recognize_face = True Clock.schedule_interval(self.update, 1.0 / self.fps) self.camera = cv2.VideoCapture(0) self.detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') self.face_recognizer = cv2.face.LBPHFaceRecognizer_create() if os.path.exists('trained_model.xml'): self.face_recognizer.read('trained_model.xml') else: self.train_recognizer() def update(self, dt): ret, frame = self.camera.read() if not ret: return frame = cv2.rotate(frame, cv2.ROTATE_180) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = self.detector.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: roi_gray = gray[y:y+h, x:x+w] label, confidence = self.face_recognizer.predict(roi_gray) if label == 0 and confidence < 80: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) self.status_label.text = 'Estado del Reconocimiento: ¡Rostro Reconocido!' else: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2) self.status_label.text = 'Estado del Reconocimiento: Rostro Desconocido' frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) buf = frame.tostring() texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='rgb') texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte') self.image.texture = texture def train_recognizer(self): faces, ids = [], [] for image in os.listdir('train_images/0'): img_path = os.path.join('train_images/0', image) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) faces.append(img) ids.append(0) self.face_recognizer.train(faces, np.array(ids)) self.face_recognizer.save('trained_model.xml') self.status_label.text = 'Modelo de reconocimiento facial entrenado y guardado.' class KivyCVApp(App): def build(self): return KivyCamera() def on_stop(self): if hasattr(self.root, 'camera'): self.root.camera.release() if __name__ == '__main__': KivyCVApp().run()
package com.zoola.tutorial.model; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.persistence.*; import lombok.*; @AllArgsConstructor @Data @Entity @NoArgsConstructor @Schema(description = "Tutorial model") @Table(name = "tutorials") public class Tutorial { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Schema(accessMode = Schema.AccessMode.READ_ONLY, description = "Tutorial ID", example = "123") private Long id; @Column(name = "title") @Schema(description = "Tutorial title", example = "Swagger Tutorial") private String title; @Column(name = "description") @Schema(description = "Tutorial description", example = "Learn how to use Swagger") private String description; @Column(name = "published") @Schema(description = "Whether or not a Tutorial is published", example = "true") private boolean published; public Tutorial(String title, String description, boolean published) { this.title = title; this.description = description; this.published = published; } }
package it.unicam.cs.asdl2324.mp1; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.ConcurrentModificationException; import java.util.HashSet; /** * Questa classe MyMultiset implementa tutte le funzionalità dell'interfaccia Multiset * attraverso l'utilizzo di una tabella hash con liste di collisioni implementata internamente * (cioé senza l'utilizzo di strutture dati fornite dalla Java SE). * La tabella Hash con liste di collisioni è una struttura dati che soddisfa i requisiti di implementazione, * in quanto non garantisce una struttura in cui i siano dati ordinati né propiamente indicizzati. * Questa classe implementa pertanto tutte le operazioni base dall'interfaccia (add, remove, setCount, cointains, count) * in un tempo Θ(1 + α), dove α è il fattore di carico della tabella, che è dato dal rapporto * tra gli elementi effettivamente allocati e la grandezza della tabella. * * La tabella Hash è implementata attraverso un array di una classe interna chiamata Element. * La classe interna Element rappresenta l'elemento nel multiset e contiene il puntatore * all'oggetto E e un intero che rappresenta il numero di occorrenze di questo elemento nel multiinsieme. * Inoltre dispone di un puntatore di tipo Element che è definito come il successivo della lista di collisione. * Nel caso due elementi diversi dovessero generare la stessa chiave hash verrebbero * concanenati nella rispettiva lista di collisione. * La funzione di hashing (consulatare @computeHash) è implementata attraverso il metodo della * moltiplicazione: floor(m * (k*A-floor(k*A))) dove k è la chiave cioé l'hashCode generato * dall'elemento E, e A è un valore consigliato dalla letturatura per rendere la funzione di hashing * uniforme e indipendente, pari a (sqrt(5) - 1)/2; ed m è la dimensione della tabella. * * La tabella è allocata di partenza con dimensione pari ad 8, * ed è in grado di raddoppiare le sue dimensioni quando il fattore di carico * supera un valore soglia pari a 0.75 (3/4 della tabella). * L'operazione di ampliamento è attuata dal metodo privato @extends: * e mantiene sempre un valore delle dimensioni pari a una * potenza di 2 come previsto dal metodo della moltiplicazione. * L'operazione di rehashing e copia degli elementi nella nuova tabella ha * pertanto un costo lineare pari a Θ(n). * * Questa implementazione garantisce pertanto una notevole efficienza in termini di tempo * per tutte le operazioni base dell'interfaccia. * Dal punto di vista dello spazio occupato in memoria occupa sempre uno spazio * pari a Θ(K), dove K è la dimensione dell'array. * K è inizialmente pari ad 8 e la funzione per l'estensione ha un costo lineare. * * * * @author Luca Tesei (template) CAMILLETTI SAMUELE [email protected] (implementazione) * * @param <E> * il tipo degli elementi del multiset */ @SuppressWarnings({"unchecked"}) public class MyMultiset<E> implements Multiset<E> { // Fattore di carico indice del limite soglia da superare per estendere le dim. della tabella private static final double LOAD_FACTOR = 0.75; // Dimensione di partenza della tabella hash private static final int DEFAULT_DIM = 8; // Costante consigliata dalla letteratura per hash con metodo della moltiplicazione private static final double A_VALUE = (Math.sqrt(5) - 1)/2; // N. modifiche usato per l'iteratore fail-fast private int numeroModifiche; // Array di elementi del multinsieme usato per implementare l'hash set private Element<E>[] hashTable; // Numero di elementi "virtuali" cioè che prende conto anche delle occorrenze di ogni elemento private int nElementi; // Numero di elementi effettivamente allocati (necessario per calcolare il fattore di carico della tabella) private int nElementiEffettivo; // Dimensione attuale tabella private int msize; private static class Element<E>{ private E item; // Elemento private int occorrenze; // N. di occorrenze presenti dell'elemento private Element<E> next;// Puntatore al successivo elemento della lista di collisioni Element(E item, int occorrenze, Element<E> next) { this.item = item; this.occorrenze = occorrenze; this.next = next; } } private class Itr implements Iterator<E> { private Element<E> lastRet; // ultimo elemento ritornato private Element<E> temp; // sentinella private Element<E> next; // successivo della sentinella // intero per tenere traccia della posizione nella tabella private int index; // intero per tenere traccia di quante occorrenze manchino all'elemento su cui si sta iterando private int occorrenza; // var di appoggio per le modifiche attese private int numeroModificheAtteso; private Itr() { // Salvo le modifiche this.numeroModificheAtteso = MyMultiset.this.numeroModifiche; // se il n. di elementi è maggiore di 0 if(nElementi > 0) { // trovo la prima occorrenza nella tabella while(MyMultiset.this.hashTable[this.index] == null && this.index < msize) this.index++; this.temp = MyMultiset.this.hashTable[this.index]; this.occorrenza = this.temp.occorrenze; if(temp.next == null) { // se non ha collisioni // trovo la prima occorrenza nella tabella while(++this.index < MyMultiset.this.msize && MyMultiset.this.hashTable[this.index] == null); if(this.index != MyMultiset.this.msize) next = MyMultiset.this.hashTable[this.index]; // se è l'indice non ha superato la dim. della tabella else next = null; // altrimenti non ha un successore ed è l'unico elemento } else next = temp.next; // se ha collisioni è l'elemento successivo nella lista di collisioni } // altrimenti i puntatori non sono inizializzati: questa assegnazione è possibile in quanto l'iteratore è failfast else { this.temp = null; this.next = null; } } @Override public boolean hasNext() { // Se il puntatore non è null o se le occorrenze non sono terminate return this.next != null || this.occorrenza > 0; } @Override public E next() { // controllo concorrenza if (this.numeroModificheAtteso != MyMultiset.this.numeroModifiche) { throw new ConcurrentModificationException("Lista modificata durante l'iterazione"); } // controllo hasNext() if (!hasNext()) throw new NoSuchElementException("Richiesta di next quando hasNext è falso"); if(this.occorrenza > 1) { this.occorrenza--; // se ci sono ancora più di 1 occorrenza, diminuisco return this.temp.item; // e ritorno } lastRet = this.temp; // salvo il valore che verrà ritornato this.occorrenza--; // diminuisco le occorrenze rimaste // se ha un successivo if(this.next != null) { // prendo il successivo per la prossima iterazione this.temp = this.next; // aggiorno le occorrenze this.occorrenza = this.temp.occorrenze; // ha un successivo nella lista di collisioni if(next.next != null) this.next = this.next.next; // non ha un successivo nella lista di collisioni else { // trovo la prima occorrenza nella tabella while(++this.index < MyMultiset.this.msize && MyMultiset.this.hashTable[this.index] == null); if(this.index != MyMultiset.this.msize) next = MyMultiset.this.hashTable[this.index]; // se è l'indice non ha superato la dim. della tabella else next = null; // altrimenti non ha un successore ed è l'unico elemento rimasto } } // ritorno il valore che inizialmente aveva la sentinella temp return this.lastRet.item; } } /** * Crea un multiset vuoto. */ public MyMultiset() { this.hashTable = (Element<E>[])new Element[DEFAULT_DIM]; // creo un array di dimensione standard 8 this.nElementi = 0; this.nElementiEffettivo = 0; this.numeroModifiche = 0; this.msize = DEFAULT_DIM; } @Override public int size() { return this.nElementi; } @Override public int count(Object element) { if(element == null) throw new NullPointerException("Elemento inesistente."); Element<E> temp; // sentinella // controllo se esiste almeno un elemento con quell'hash if((temp = this.hashTable[computeHash((E) element)]) != null) { // scorro lista colllisioni dalla testa fino all'ultimo o finché non lo trovo while(!(temp.item.equals(element)) && temp.next != null) temp = temp.next; // se non l'ho trovato if(!(temp.item.equals(element))) return 0; // se l'ho trovato else return temp.occorrenze; } else return 0; } @Override public int add(E element, int occurrences) { if(element == null) throw new NullPointerException("Elemento inesistente."); if(occurrences < 0) throw new IllegalArgumentException("Numero di occorrenze negativo non consentito."); // se la tabella ha superato la soglia del fattore di carico, estendo if((this.nElementiEffettivo/this.msize) > LOAD_FACTOR) this.extend(); Element<E> temp; // sentinella int oldOccorrenze = 0; // var di appoggio per le occorrenze precedenti // controllo se presente if(this.contains(element)) { // se lo contiene so già che lo troverò temp = this.hashTable[computeHash(element)]; // scorro lista collisioni while(!(temp.item.equals(element)) && temp.next != null) temp = temp.next; // verifico che la dimensione non sia superiore alla soglia massima per un intero if(!checkMax((long)temp.occorrenze + occurrences)) { oldOccorrenze = temp.occorrenze; temp.occorrenze += occurrences; // aumento di occurences il n. occorrenze dell'elemento } else throw new IllegalArgumentException("Limite fisico per un intero di occorrenze raggiunto."); if(oldOccorrenze != temp.occorrenze) this.numeroModifiche++; // se le occorrenze sono cambiate } // se non presente else { if(occurrences == 0) return 0; // se le occorrenze da aggiungere sono 0 non aggiungo il nuovo elemento if(this.hashTable[computeHash(element)] != null) { // se non supera il limite di occorrenze lo aggiungo immediatamente come slot dopo "la testa" nella lista di collisioni if(!checkMax((long) occurrences)) { Element<E> newElement = new Element<E>(element, occurrences, this.hashTable[computeHash(element)].next); this.hashTable[computeHash(element)].next = newElement; } else throw new IllegalArgumentException("Limite fisico per un intero di occorrenze raggiunto."); } else { // verifico che la dimensione non sia superiore alla soglia massima per un intero if(!checkMax(occurrences)) this.hashTable[computeHash(element)] = new Element<E>(element, occurrences, null); else throw new IllegalArgumentException("Limite fisico per un intero di occorrenze raggiunto."); } this.numeroModifiche++; this.nElementiEffettivo++; } this.nElementi += occurrences; return oldOccorrenze; } @Override public void add(E element) { this.add(element, 1); } @Override public int remove(Object element, int occurrences) { if(element == null) throw new NullPointerException("Elemento inesistente."); if(occurrences < 0) throw new IllegalArgumentException("Numero di occorrenze negativo non consentito."); Element<E> temp; // sentinella Element<E> prec; // precedente di temp int oldOccorrenze = 0; // var di appoggio per le occorrenze precedenti // controllo se è presente if(this.contains(element)) { // salvo il valore con quell'hash (testa della lista di collisione) temp = this.hashTable[computeHash((E) element)]; prec = temp; // il precedente coincide con la testa // scorro lista collisioni, sapendo che prima o poi lo troverò while(!(temp.item.equals(element))) { prec = temp; temp = temp.next; } oldOccorrenze = temp.occorrenze; // se va rimosso if(occurrences >= temp.occorrenze) { // se è la testa della lista di collisione if(this.hashTable[computeHash((E) element)] == temp) { if(temp.next == null) this.hashTable[computeHash((E) element)] = null; // cella tabella hash libera // altrimenti, primo elemento della lista delle collisioni diventa testa della cella hash else this.hashTable[computeHash((E) element)] = temp.next; } // è un elemento della lista di collisioni else { prec.next = temp.next; } this.numeroModifiche++; } // se vanno solo diminuite le occorrenze else { temp.occorrenze -= occurrences; if(oldOccorrenze != temp.occorrenze) this.numeroModifiche++; } // Se l'elemento è stato rimosso rimuovo solo le "vecchie" occorrenze if(occurrences > oldOccorrenze) this.nElementi -= oldOccorrenze; else this.nElementi -= occurrences; // altrimenti se sono diminuite tolgo quelle rimosse } return oldOccorrenze; } @Override public boolean remove(Object element) { if(element == null) throw new NullPointerException("Elemento inesistente."); Element<E> temp; // sentinella Element<E> prec; // precedente di temp // controllo se è presente if(this.contains(element)) { // salvo il valore con quell'hash (testa della lista di collisione) temp = this.hashTable[computeHash((E) element)]; prec = temp; // il precedente coincide con la testa // scorro lista collisioni, sapendo che prima o poi lo troverò while(!(temp.item.equals(element))) { prec = temp; temp = temp.next; } // se va rimosso if(temp.occorrenze == 1) { if(this.hashTable[computeHash((E) element)] == temp) { // è la testa della lista di collisione if(temp.next == null) this.hashTable[computeHash((E) element)] = null; // cella hash libera // primo elemento della lista delle collisioni diventa testa della cella hash else this.hashTable[computeHash((E) element)] = temp.next; } // è un elemento della lista di collisioni else { prec.next = temp.next; } } // se vanno diminuite le occorrenze else { temp.occorrenze -= 1; } this.nElementi--; this.numeroModifiche++; return true; } else return false; } @Override public int setCount(E element, int count) { if(element == null) throw new NullPointerException("Elemento inesistente."); if(count < 0) throw new IllegalArgumentException("Numero di occorrenze negativo non consentito."); Element<E> temp; // sentinella int oldOccorrenze = 0; // controllo se presente if(this.contains(element)) { // se lo contiene so già che lo troverò temp = this.hashTable[computeHash(element)]; // scorro lista collisioni while(!(temp.item.equals(element)) && temp.next != null) temp = temp.next; if(!checkMax((long)temp.occorrenze + count)) { oldOccorrenze = temp.occorrenze; temp.occorrenze = count; // aumento di 1 il n. occorrenze dell'elemento } else throw new IllegalArgumentException("Limite fisico per un intero di occorrenze raggiunto."); if(oldOccorrenze != temp.occorrenze) this.numeroModifiche++; // se le occorrenze sono cambiate } else { this.add(element, count); } this.nElementi -= oldOccorrenze; this.nElementi += count; return oldOccorrenze; } @Override public Set<E> elementSet() { Set<E> retSet = new HashSet<E>(); // set di appoggio Element<E> temp; // sentinella for(int i=0; i<this.msize; i++) { // scorro l'hash table temp = this.hashTable[i]; // prendo l'elemento di indice // scorro dal primo eventuale l'elemento l'intera lista di collisioni while(temp != null){ retSet.add(temp.item); temp = temp.next; } } return retSet; } @Override public Iterator<E> iterator() { return new Itr(); } @Override public boolean contains(Object element) { if(element == null) throw new NullPointerException("Elemento inesistente."); Element<E> temp; // sentinella if((temp = this.hashTable[computeHash((E) element)]) != null) { // scorro lista while(!(element.equals(temp.item)) && temp.next != null) temp = temp.next; // se non lo trovo if(!(element.equals(temp.item))) return false; // se lo trovo else return true; } else return false; } @Override public void clear() { // resetto i dati inizializzati dal costruttore this.hashTable = (Element<E>[])new Element[DEFAULT_DIM]; this.nElementi = 0; this.nElementiEffettivo = 0; this.numeroModifiche++; this.msize = DEFAULT_DIM; } @Override public boolean isEmpty() { return this.nElementi == 0; } /* * Due multinsiemi sono uguali se e solo se contengono esattamente gli * stessi elementi (utilizzando l'equals della classe E) con le stesse * molteplicità. * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (!(obj instanceof MyMultiset)) return false; MyMultiset<?> other = (MyMultiset<?>) obj; // Controllo se entrambe liste vuote if (this.nElementi == 0) { if (other.nElementi != 0) return false; else return true; } // Liste non vuote, scorro gli elementi di entrambe Iterator<E> thisIterator = this.iterator(); Iterator<?> otherIterator = other.iterator(); while (thisIterator.hasNext() && otherIterator.hasNext()) { E o1 = thisIterator.next(); // uso il polimorfismo di Object perché non conosco il tipo ? Object o2 = otherIterator.next(); // il metodo equals che si usa è quello della classe E if (!o1.equals(o2)) return false; } // Controllo che entrambe le liste siano terminate return !(thisIterator.hasNext() || otherIterator.hasNext()); } /* * Da ridefinire in accordo con la ridefinizione di equals. * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int hashCode = 1; Iterator<E> thisIterator = this.iterator(); // uso l'iterator di questa classe while (thisIterator.hasNext()) { E e = thisIterator.next(); hashCode = 31 * hashCode + e.hashCode(); } return hashCode; } /* * Metodo per il calcolo della chiave * * */ private int computeHash(E element) { // metodo della moltiplicazione floor(m * partefrazionaria(key * A)) return (int)Math.floor(this.msize * (element.hashCode()*A_VALUE - Math.floor((element.hashCode()*A_VALUE)))); } /* * Metodo per check delle occorrenze * Utilizzo un cast a long per verificare che il valore superi la soglia costante massima per * un intero. * */ private boolean checkMax(long occurrences) { return (long) occurrences > Integer.MAX_VALUE; } /* * Metodo per estensione dimensione array * * */ private void extend() { Element<E>[] oldHash = this.hashTable; this.hashTable = (Element<E>[])new Element[this.msize*2]; // alloco una nuova tabella dalla dimensione doppia Element<E> temp, next; int oldSize = this.msize; // salvo le vecchie dimensioni this.msize = this.msize * 2; // radoppio le dim della tabella for(int i=0; i<oldSize; i++) { // scorro l'hash table temp = oldHash[i]; // prendo l'elemento di indice next = oldHash[i]; // scorro dal primo eventuale elemento l'intera lista di collisioni while(temp != null){ int hash = computeHash(temp.item); next = temp.next; temp.next = null; if(this.hashTable[hash] != null) { // se l'indice non è libero // attacco dopo la testa temp.next = this.hashTable[hash].next; this.hashTable[hash].next = temp; } else // altrimenti va nella posizione corrispondente al risultato della funzione hash this.hashTable[hash] = temp; temp = next; } } } }
import Container from "./../../UI/Container"; import rate1 from "../../Assets/rate4.svg"; import rate2 from "../../Assets/rate.svg"; import ava1 from "../../Assets/ava1.jpg"; import ava2 from "../../Assets/ava2.jpg"; import Card from "./../../UI/Card"; import Paragraph from "./../../UI/Paragraph"; import classes from "./People.module.css"; import { memo } from "react"; const content = [ { id: 1, title: "Good Service", rate: rate1, description: "Donec placerat nulla egestas vulputate convallis. Sed quis lorem luctus justo placerat placerat. Cras ut libero eget tortor varius rhoncus. Integer eu porttitor sapien, a fermentum sapien. Cras bibendum laoreet justo, id commodo ipsum. Nullam volutpat, orci tempus tempus luctus, mi ligula eleifend sapien, ac auctor arcu mi id nibh. Donec lacinia tristique pharetra", name: "Barry Derrickson", avatar: ava1, }, { id: 2, title: "Professional Doctors", rate: rate2, description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet risus finibus, sagittis odio non, sollicitudin tellus. Aliquam finibus rhoncus pulvinar. Vestibulum viverra quis orci eu tincidunt. Praesent ullamcorper metus nec egestas lobortis. Donec porta feugiat luctus. Curabitur tincidunt turpis non purus suscipit lobortis.", name: "Kate Coleman", avatar: ava2, }, ]; function People() { return ( <section> <Container> <div className={classes.people}> {content.map((item) => ( <Card key={item.id}> <div className={classes.content}> <div className={classes.people__head}> <h3>{item.title}</h3> <span> <img src={item.rate} alt="rate" /> </span> </div> <Paragraph>{item.description}</Paragraph> <div className={classes.people__avatar}> <span> <img src={item.avatar} alt="avatar" /> </span> <span>{item.name}</span> </div> </div> </Card> ))} </div> </Container> </section> ); } export default memo(People);
import { Body, Controller, HttpCode, HttpStatus, Post, UseGuards, UsePipes, } from '@nestjs/common'; import { GetCurrentUser, GetCurrentUserId, Public, } from '@Src/common/decorators'; import { RtGuard } from '@Src/common/guards'; import { PasswordValidationPipe } from '@Src/common/pipes'; import { LogInDto, RegisterDto } from '../dto'; import { AuthService } from '../service/auth.service'; @Controller('auth') export class AuthController { constructor(private readonly authService: AuthService) {} @Public() @Post('local/register') @UsePipes(new PasswordValidationPipe()) @HttpCode(HttpStatus.CREATED) registerLocal(@Body() registerDto: RegisterDto) { return this.authService.registerLocal(registerDto); } @Public() @Post('local/logIn') @HttpCode(HttpStatus.OK) logInLocal(@Body() logInDto: LogInDto) { return this.authService.logInLocal(logInDto); } @Post('logOut') @HttpCode(HttpStatus.OK) logOut(@GetCurrentUserId() userId: number) { return this.authService.logOut(userId); } @Public() @UseGuards(RtGuard) @Post('refresh') @HttpCode(HttpStatus.OK) refreshTokens( @GetCurrentUserId() userId: number, @GetCurrentUser('refreshToken') refreshToken: string, ) { return this.authService.refreshTokens(userId, refreshToken); } }
import React, { useState, PropsWithChildren, useEffect, useReducer, useMemo, useContext, } from "react"; import * as R from "ramda"; import { CharSheet, ErrorDescription } from "../domain"; import { getCharSheetFromLS, saveCharSheetInLS, } from "../infrastructure/lsDbService"; import { CombinedRootService, ErrorDescriptionService, } from "../application/ports"; import { CombinedGenericService } from "../../generic/application/ports"; import { CombinedCtDService } from "../../ctd/application/ports"; import { CombinedVtMService } from "../../vtm/application/ports"; import { CombinedMiscService } from "../../misc/application/ports"; import { miscActions } from "../../misc/services/actions"; import { genericActions } from "../../generic/services/actions"; import { vtmActions } from "../../vtm/services/actions"; import { ctdActions } from "../../ctd/services/actions"; import { hh2Actions } from "../../hh2/services/actions"; import { CombinedHH2Service } from "../../hh2/application/ports"; import { initialCharSheet } from "./initialValues"; import { getLimits } from "./getLimits"; import { CompositeReducer } from "./CompositeReducer"; import { rootActions } from "./actions"; type TakeActions<Reducer> = Reducer extends CompositeReducer<any, infer T> ? T : never; type TakeActionPairs<R extends { type: string; props: any }> = R extends unknown ? [R["type"], R["props"]] : never; type MergeTuples<T extends { type: string; props: any }> = { [key in TakeActionPairs<T> as key[0]]: (...rest: key[1]) => void; }; export interface StateStore extends CombinedRootService, CombinedGenericService, CombinedCtDService, CombinedVtMService, CombinedMiscService, CombinedHH2Service, ErrorDescriptionService {} // @ts-ignore const StoreContext = React.createContext<StateStore>({}); export const useStore = () => useContext(StoreContext); interface ProviderProps {} const reducer = new CompositeReducer<CharSheet>() .assign(rootActions) .assign(miscActions) .assign(genericActions) .assign(vtmActions) .assign(ctdActions) .assign(hh2Actions); export const Provider: React.FC<PropsWithChildren<ProviderProps>> = ({ children, }) => { const [initialized, setInitialized] = useState(false); const [charSheet, dispatch] = useReducer(reducer.reduce, initialCharSheet); const limits = useMemo(() => { return getLimits(charSheet); }, [charSheet.preset, charSheet.profile.generation]); useEffect(() => { dispatch({ type: "setState", props: ["bloodPerTurn", String(limits.bloodPerTurnLimit)], }); }, [limits.bloodPerTurnLimit]); useEffect(() => { saveCharSheetInLS(charSheet); }, [charSheet]); const [errorDescription, setErrorDescription] = useState<ErrorDescription | null>(null); const functions = useMemo(() => { return Object.keys(reducer.actionMap).reduce((acc, el) => { // @ts-ignore acc[el] = function (...rest: any[]) { // @ts-ignore dispatch({ type: el, props: [...rest] }); }; return acc; }, {} as MergeTuples<TakeActions<typeof reducer>>); }, [dispatch]); if (!initialized) { setInitialized(true); const cs = getCharSheetFromLS(); if (cs !== null) { functions.setCharSheet(cs); } } const value: StateStore = { ...charSheet, ...functions, limits, charSheet, errorDescription, setErrorDescription, }; return ( <StoreContext.Provider value={value}>{children}</StoreContext.Provider> ); };
<?php namespace App\Http\Controllers; use PHPUnit\Util\Type; use App\Models\Tingkat; use App\Models\Kelas; use App\Models\Kecamatan; use App\Models\Kriteria; use App\Models\SubKriteria; use App\Models\Kelurahan; use App\Models\Siswa; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; class SiswaController extends Controller { // public function index(Type $var = null) // { // $siswa = Siswa::get(); // return view('siswa', ['siswa' => $siswa]); // } public function create() { $tingkat = Tingkat::get(); $kelas = Kelas::get(); $kecamatan = Kecamatan::get(); $kelurahan = Kelurahan::get(); return view('add.siswa-add', ['kecamatan' => $kecamatan, 'kelurahan' => $kelurahan, 'tingkat' => $tingkat, 'kelas' => $kelas]); } public function store(Request $request) { // dd($request->all()); $rules = []; $messages = []; $rules['nama'] = 'unique:siswa|max:50|required'; $messages['nama.unique'] = 'Nama siswa sudah ada!'; $messages['nama.max'] = 'Nama siswa tidak boleh lebih dari :max karakter!'; $messages['nama.required'] = 'Nama siswa wajib diisi!'; $rules['nis'] = 'unique:siswa|max:50|required'; $messages['nis.unique'] = 'NIS sudah ada!'; $messages['nis.max'] = 'NIS tidak boleh lebih dari :max karakter!'; $messages['nis.required'] = 'NIS wajib diisi!'; $rules['jk'] = 'required'; $messages['jk.required'] = 'Jenis Kelamin dipilih!'; $rules['tgl_lahir'] = 'required'; $messages['tgl_lahir.required'] = 'Tanggal lahir wajib diisi!'; $rules['tingkat_id'] = 'required'; $messages['tingkat_id.required'] = 'Tingkat wajib dipilih!'; $rules['kelas_id'] = 'required'; $messages['kelas_id.required'] = 'Kelas wajib dipilih!'; $rules['kecamatan_id'] = 'required'; $messages['kecamatan_id.required'] = 'Kecamatan wajib dipilih!'; $rules['kelurahan_id'] = 'required'; $messages['kelurahan_id.required'] = 'Kelurahan wajib dipilih!'; $request->validate($rules, $messages); $arrayAdd = []; $arrayAdd = $request; $kasus = Siswa::create($arrayAdd->all()); if ($kasus) { Session::flash('succMessage', 'Siswa berhasil ditambahkan!'); } else { Session::flash('errMessage', 'Siswa gagal ditambahkan!'); } return redirect('/siswa_kriteria'); } public function edit($id) { // dd($id); $siswa = Siswa::findOrFail($id); $tingkat = Tingkat::with(['tingkat_kelas.kelas'])->get(); $kelas = Kelas::get(); $kecamatan = Kecamatan::get(); $kelurahan = Kelurahan::get(); $jk = ['Laki - Laki', 'Perempuan']; // dd($tingkat); return view('edit.siswa-edit', ['siswa' => $siswa, 'kecamatan' => $kecamatan, 'jk' => $jk, 'kelurahan' => $kelurahan, 'tingkat' => $tingkat, 'kelas' => $kelas]); } public function update(Request $request, $id) { $rules = []; $messages = []; $siswa = Siswa::findOrFail($id); if ($request->nama != $siswa->nama) { $rules['nama'] = 'unique:siswa|max:50|required'; $messages['nama.unique'] = 'Nama Siswa Sudah ada!'; $messages['nama.required'] = 'Siswa wajib Diisi!'; $messages['nama.max'] = 'Nama Siswa tidak boleh lebih dari :max karakter!'; } if ($request->nis != $siswa->nis) { $rules['nis'] = 'unique:siswa|required'; $messages['nis.unique'] = 'NIS Sudah ada!'; $messages['nis.required'] = 'NIS wajib Diisi!'; } $rules['jk'] = 'required'; $messages['jk.required'] = 'Jenis kelamin wajib diisi!'; $rules['tgl_lahir'] = 'required'; $messages['tgl_lahir.required'] = 'Tanggal wajib diisi!'; $rules['tingkat_id'] = 'required'; $messages['tingkat_id.required'] = 'Jurusan wajib dipilih!'; $rules['kelas_id'] = 'required'; $messages['kelas_id.required'] = 'Jurusan wajib dipilih!'; $rules['kecamatan_id'] = 'required'; $messages['kecamatan_id.required'] = 'Kecamatan wajib dipilih!'; $rules['kelurahan_id'] = 'required'; $messages['kelurahan_id.required'] = 'Kelurahan wajib diisi!'; $request->validate($rules, $messages); $result = $siswa->update($request->all()); if ($result) { Session::flash('succMessage', 'Siswa berhasil diubah!'); } else { Session::flash('errMessage', 'Siswa gagal diubah!'); } return redirect('/siswa_kriteria'); } public function destroy($id) { $kecamatan = Siswa::findOrFail($id); $result = $kecamatan->delete(); if ($result) { Session::flash('succMessage', 'Siswa berhasil dihapus!'); } else { Session::flash('errMessage', 'Siswa gagal dihapus!'); } return redirect('/siswa_kriteria'); } public function request() { $siswa = Siswa::with(['siswa_kriteria.kriteria'])->get(); $kriteria = Kriteria::get(); return response()->json([$siswa, $kriteria]); } }
{-# LANGUAGE QuasiQuotes #-} -- | Tests for m command. module Functional.Commands.Empty ( tests, ) where import Data.HashSet qualified as HashSet import Functional.Prelude import SafeRm.Backend.Default.Utils qualified as Default.Utils import SafeRm.Data.Metadata qualified as Metadata -- NOTE: These tests currently rely on internal details for the trash -- structure (see the usage of Default.Utils). If we ever get a non-compliant -- backend, this will have to change. tests :: IO TestEnv -> TestTree tests testEnv = testGroup "Empty Command" [ emptyTrash testEnv', emptyTrashTwice testEnv', emptyNoForce testEnv', missingInfoForcesDelete testEnv', missingPathsForcesDelete testEnv' ] where testEnv' = appendTestDir "empty" <$> testEnv emptyTrash :: IO TestEnv -> TestTree emptyTrash getTestEnv = testCase "Empties trash" $ do testEnv <- getTestEnv usingReaderT testEnv $ appendTestDirM "emptyTrash" $ do testDir <- getTestDir let filesToDelete = (testDir </>!) <$> ["f1", "f2", "f3"] dirsToDelete = (testDir </>!) <$> ["dir1", "dir2", "dir4"] fileLinkToDelete = testDir </> [osp|file-link|] dirLinkToDelete = testDir </> [osp|dir-link|] linksToDelete = [fileLinkToDelete, dirLinkToDelete] delArgList <- withSrArgsPathsM ["delete"] (filesToDelete <> dirsToDelete <> linksToDelete) -- setup -- test w/ a nested dir createDirectories (dirsToDelete <> [testDir </>! "dir2/dir3", testDir </>! "dir4"]) -- test w/ a file in dir createFiles ((testDir </>! "dir2/dir3/foo") : filesToDelete) createSymlinks [F fileLinkToDelete, D dirLinkToDelete, F $ testDir </>! "dir4" </>! "link"] assertPathsExist (filesToDelete ++ dirsToDelete) assertSymlinksExist linksToDelete runSafeRm delArgList -- file assertions assertPathsDoNotExist (filesToDelete ++ dirsToDelete) -- trash structure assertions delExpectedIdxSet <- mkPathDataSetM [ ("f1", PathTypeFile, 5), ("f2", PathTypeFile, 5), ("f3", PathTypeFile, 5), ("dir1", PathTypeDirectory, 5), ("dir2", PathTypeDirectory, 15), ("dir4", PathTypeDirectory, 10), ("dir-link", PathTypeSymbolicLink, 5), ("file-link", PathTypeSymbolicLink, 5) ] (delIdxSet, delMetadata) <- runIndexMetadataM assertSetEq delExpectedIdxSet delIdxSet delExpectedMetadata @=? delMetadata assertFdoDirectorySizesM ["dir1", "dir2", "dir4"] -- EMPTY emptyArgList <- withSrArgsM ["empty", "-f"] runSafeRm emptyArgList -- file assertions assertPathsDoNotExist (filesToDelete ++ dirsToDelete) -- trash structure assertions (emptyIdxSet, emptyMetadata) <- runIndexMetadataM assertSetEq emptyExpectedIdxSet emptyIdxSet emptyExpectedMetadata @=? emptyMetadata assertFdoDirectorySizesM [] where delExpectedMetadata = mkMetadata 8 7 0 55 emptyExpectedIdxSet = HashSet.empty emptyExpectedMetadata = Metadata.empty emptyTrashTwice :: IO TestEnv -> TestTree emptyTrashTwice getTestEnv = testCase "Calling empty twice does not error" $ do testEnv <- getTestEnv usingReaderT testEnv $ appendTestDirM "emptyTrashTwice" $ do emptyArgs <- withSrArgsM ["empty", "-f"] runSafeRm emptyArgs runSafeRm emptyArgs emptyNoForce :: IO TestEnv -> TestTree emptyNoForce getTestEnv = testCase "Empties w/ no response deletes nothing" $ do testEnv <- getTestEnv usingReaderT testEnv $ appendTestDirM "emptyNoForce" $ do testDir <- getTestDir let fileDeleteNames = show @Int <$> [1 .. 5] fileDeletePaths = (testDir </>!) <$> fileDeleteNames delArgList <- withSrArgsPathsM ["delete"] fileDeletePaths -- setup -- test w/ a file in dir createFiles fileDeletePaths assertPathsExist fileDeletePaths runSafeRm delArgList -- file assertions assertPathsDoNotExist fileDeletePaths -- trash structure assertions delExpectedIdxSet <- mkPathDataSetM [ ("1", PathTypeFile, 5), ("2", PathTypeFile, 5), ("3", PathTypeFile, 5), ("4", PathTypeFile, 5), ("5", PathTypeFile, 5) ] (delIdxSet, delMetadata) <- runIndexMetadataM assertSetEq delExpectedIdxSet delIdxSet delExpectedMetadata @=? delMetadata -- EMPTY emptyArgList <- withSrArgsM ["empty"] runSafeRm emptyArgList -- trash structure assertions (emptyIdxSet, emptyMetadata) <- runIndexMetadataM assertSetEq delExpectedIdxSet emptyIdxSet delExpectedMetadata @=? emptyMetadata where delExpectedMetadata = mkMetadata 5 5 0 25 missingInfoForcesDelete :: IO TestEnv -> TestTree missingInfoForcesDelete getTestEnv = testCase "empty --force overwrites bad directory (no info.)" $ do testEnv <- getTestEnv usingReaderT testEnv $ appendTestDirM "missingInfoForcesDelete" $ do testDir <- getTestDir let trashDir = testDir </> pathDotTrash filesToDelete = (testDir </>!) <$> ["f1", "f2", "f3"] dirsToDelete = (testDir </>!) <$> ["dir1", "dir2"] delArgList <- withSrArgsPathsM ["delete"] (filesToDelete <> dirsToDelete) -- setup -- test w/ a nested dir createDirectories (dirsToDelete <> [testDir </>! "dir2/dir3"]) -- test w/ a file in dir createFiles ((testDir </>! "dir2/dir3/foo") : filesToDelete) assertPathsExist (filesToDelete ++ dirsToDelete) -- delete files runSafeRm delArgList -- file assertions assertPathsDoNotExist (filesToDelete ++ dirsToDelete) -- trash structure assertions delExpectedIdxSet <- mkPathDataSetM [ ("f1", PathTypeFile, 5), ("f2", PathTypeFile, 5), ("f3", PathTypeFile, 5), ("dir1", PathTypeDirectory, 5), ("dir2", PathTypeDirectory, 15) ] (delIdxSet, delMetadata) <- runIndexMetadataM assertSetEq delExpectedIdxSet delIdxSet delExpectedMetadata @=? delMetadata -- delete info dir, leaving trash dir in bad state clearDirectory (trashDir </> Default.Utils.pathInfo) emptyArgList <- withSrArgsM ["empty", "-f"] runSafeRm emptyArgList assertPathsExist $ fmap (trashDir </>) [Default.Utils.pathInfo, Default.Utils.pathFiles] -- trash structure assertions (emptyIdxSet, emptyMetadata) <- runIndexMetadataM assertSetEq emptyExpectedIdxSet emptyIdxSet emptyExpectedMetadata @=? emptyMetadata where delExpectedMetadata = mkMetadata 5 4 0 35 emptyExpectedIdxSet = HashSet.empty emptyExpectedMetadata = Metadata.empty missingPathsForcesDelete :: IO TestEnv -> TestTree missingPathsForcesDelete getTestEnv = testCase "empty --force overwrites bad directory (no paths/)" $ do testEnv <- getTestEnv usingReaderT testEnv $ appendTestDirM "missingPathsForcesDelete" $ do testDir <- getTestDir let trashDir = testDir </> pathDotTrash filesToDelete = (testDir </>!) <$> ["f1", "f2", "f3"] dirsToDelete = (testDir </>!) <$> ["dir1", "dir2"] delArgList <- withSrArgsPathsM ["delete"] (filesToDelete <> dirsToDelete) -- setup -- test w/ a nested dir createDirectories (dirsToDelete <> [testDir </>! "dir2/dir3"]) -- test w/ a file in dir createFiles ((testDir </>! "dir2/dir3/foo") : filesToDelete) assertPathsExist (filesToDelete ++ dirsToDelete) -- delete files runSafeRm delArgList -- file assertions assertPathsDoNotExist (filesToDelete ++ dirsToDelete) -- trash structure assertions delExpectedIdxSet <- mkPathDataSetM [ ("f1", PathTypeFile, 5), ("f2", PathTypeFile, 5), ("f3", PathTypeFile, 5), ("dir1", PathTypeDirectory, 5), ("dir2", PathTypeDirectory, 15) ] (delIdxSet, delMetadata) <- runIndexMetadataM assertSetEq delExpectedIdxSet delIdxSet delExpectedMetadata @=? delMetadata -- delete info dir, leaving trash dir in bad state clearDirectory (trashDir </> Default.Utils.pathFiles) emptyArgList <- withSrArgsM ["empty", "-f"] runSafeRm emptyArgList -- file assertions assertPathsDoNotExist (filesToDelete ++ dirsToDelete) assertPathsExist $ fmap (trashDir </>) [Default.Utils.pathInfo, Default.Utils.pathFiles] -- trash structure assertions (emptyIdxSet, emptyMetadata) <- runIndexMetadataM assertSetEq emptyExpectedIdxSet emptyIdxSet emptyExpectedMetadata @=? emptyMetadata where delExpectedMetadata = mkMetadata 5 4 0 35 emptyExpectedIdxSet = HashSet.empty emptyExpectedMetadata = Metadata.empty
import { twMerge } from "tailwind-merge"; import { useController } from "react-hook-form"; import { addCommas } from "_utils"; const MyInput = ({ control, errorMessage, className, isRequired = false, ...props }) => { const { field } = useController({ name: props.name || "", control, defaultValue: "", }); return ( <div className=""> <label htmlFor={props.id || props.name} className=" mb-2 text-sm font-semibold text-black flex items-center gap-1" > {props.label} {isRequired && ( <span className="text-red-500 font-normal">(*)</span> )} </label> <div> <input {...field} {...props} onChange={ props.formatNumber ? (e) => { let formattedValue = addCommas( e.target.value ); field.onChange(formattedValue); } : field.onChange } className={twMerge( "bg-white rounded-lg border-gray-300 w-full p-2 text-xs lg:text-sm font-light border focus:border-none", className )} /> </div> {errorMessage && ( <div className="text-sm text-red-500">{errorMessage}</div> )} </div> ); }; export default MyInput;
import axios from 'axios'; import React, { useState } from 'react'; import { useFormik } from 'formik'; import { Button, Form, FloatingLabel } from 'react-bootstrap'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { useRollbar } from '@rollbar/react'; import useAuth from './hooks/useAuth'; import routes from '../utils/routes'; import useNetErrToast from './hooks/useNetErrToast'; const AuthForm = () => { const rollbar = useRollbar(); const [authFailed, setAuthFailed] = useState(false); const [errorText, setErrorText] = useState(''); const navigate = useNavigate(); const auth = useAuth(); const { t } = useTranslation(); const displayNetErr = useNetErrToast(); const formik = useFormik({ initialValues: { username: '', password: '', }, /* eslint-disable functional/no-expression-statements, consistent-return */ onSubmit: async (values) => { setAuthFailed(false); try { const response = await axios.post(routes.loginPath(), values, { headers: { 'Content-Type': 'application/json', }, }); const { token, username } = response.data; localStorage.setItem('token', token); localStorage.setItem('username', username); navigate('/'); auth.logIn(); } catch (e) { formik.setSubmitting(false); if (e.isAxiosError && e.response.status === 401) { setAuthFailed(true); setErrorText(t('feedback.errorAuth')); return errorText; } const user = values.username; rollbar.error('Error login', e, { user }); displayNetErr(); } }, }); /* eslint-enable */ return ( <Form className="col-12 col-md-6 mt-3 mt-mb-0" onSubmit={formik.handleSubmit}> <h1 className="text-center mb-4">{t('main.signin')}</h1> <fieldset disabled={formik.isSubmitting}> <FloatingLabel controlId="username" label={t('forms.nickname')} className="mb-3" > <Form.Control type="text" placeholder={t('forms.username')} isInvalid={authFailed} required onChange={formik.handleChange} value={formik.values.username} /> </FloatingLabel> <FloatingLabel controlId="password" label={t('forms.password')} className="mb-4" > <Form.Control type="password" placeholder={t('forms.password')} isInvalid={authFailed} required onChange={formik.handleChange} value={formik.values.password} /> <Form.Control.Feedback type="invalid">{errorText}</Form.Control.Feedback> </FloatingLabel> <Button variant="outline-primary" className="w-100 mb-3" type="submit">{t('buttons.signin')}</Button> </fieldset> </Form> ); }; export default AuthForm;
/** * 版权所有(C),LHWMS项目组,2017,所有权利保留。 * * 项目名: hoist * 文件名: Swagger2.java * 模块说明: * 修改历史: * 2017年5月16日 - Jing - 创建。 */ package com.hd123.zjlh.wcs; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author Jing * */ @Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.hd123.zjlh.wcs")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("WCS-提升机命令模拟器") .termsOfServiceUrl("http://www.hd123.com/") .contact("wujing") .version("1.0") .build(); } }
import { Text, View, useColorScheme, StyleSheet } from "react-native"; interface SectionProps { children: React.ReactNode; title: string } export function Section({ children, title } : SectionProps) { const isDarkMode = useColorScheme() === 'dark'; return ( <View style={styles.container}> <Text style={[ styles.title, { color: isDarkMode ? "#FFF" : "#000", }, ]}> {title} </Text> <Text style={[ styles.description, { color: isDarkMode ? "#CCC" : "#000", }, ]}> {children} </Text> </View> ); } const styles = StyleSheet.create({ container: { marginTop: 32, paddingHorizontal: 24, }, title: { fontSize: 24, fontWeight: '600', }, description: { marginTop: 8, fontSize: 18, fontWeight: '400', }, });
import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import './index.css' import { Provider } from 'react-redux' import store from './store' import HomePage from './pages' import ProductPage from './pages/product' import CartPage from './pages/cart' import AuthPage from './pages/auth' import { BrowserRouter, Routes, Route } from 'react-router-dom' import AuthProtected from './components/auth/AuthProtected' import AccountPage from './pages/account' import ProductDetail from './pages/ProductDetail' ReactDOM.createRoot(document.getElementById('root')).render( <React.StrictMode> {/* <Provider store={store}> */} <BrowserRouter> <Routes> <Route path='/' element={ <Provider store={store}> <App /> </Provider> }> <Route index element={<HomePage />} /> <Route path='/products' element={<ProductPage />} /> <Route path='/products/:id' element={<ProductDetail />} /> <Route path='carts' element={ <AuthProtected> <CartPage /> </AuthProtected> } /> <Route path='auth' element={<AuthPage />} /> <Route path='account' element={ <AuthProtected> <AccountPage /> </AuthProtected> } /> </Route> <Route path='*' element={<h1>404 page not found</h1>} /> </Routes> </BrowserRouter> {/* </Provider> */} </React.StrictMode> )
import {Pessoa} from '@/pessoa/pessoa' import {describe, test, expect} from 'bun:test' describe('Pessoa', () => { const dados = {nome: 'João', email: 'joã[email protected]'} const pessoa = new Pessoa(dados); test('Instanciar pessoa', () => { expect(pessoa).toMatchObject(dados) }) test('Alterar perfil de pessoa', () => { pessoa.alterarPerfil() expect(pessoa.admin).toBeTruthy() pessoa.alterarPerfil() expect(pessoa.admin).toBeFalsy() }) test('Testar com nome inválido', () => { expect(() => { new Pessoa({nome: 'jao', email: '[email protected]'}); }).toThrow(new Error('Nome deve possuir no mínimo 3 caracteres.')) }) test('Testar com email inválido', () => { expect(() => { new Pessoa({nome: 'João', email: 'joão.email.com'}); }).toThrow(new Error('Email inválido.')) }) })
import { ethers } from "hardhat"; import { SampleAccount__factory } from "../typechain-types"; import { SafeProtocolRegistry__factory } from "../typechain-types"; import { IntentPlugin__factory } from "../typechain-types"; import type { BigNumberish, BytesLike, AddressLike } from "ethers"; import SafeProtocolManagerAbi from "../abis/SafeProtocolManager.json"; import IntentPlugin from "../abis/IntentPlugin.json"; enum SupportedChainId { POLYGON = 137, MAINNET = 1, CELO = 42220 } type ATOStruct = { Operation: BigNumberish; minTokenIn: BigNumberish; maxTokenIn: BigNumberish; minTokenOut: BigNumberish; maxTokenOut: BigNumberish; tokenInAddress: AddressLike; tokenOutAddress: AddressLike; sourceChainId: number; destinationChainId: number; }; type UserIntent = { sender: AddressLike; intent: ATOStruct[]; nonce: BigNumberish; } (async () => { const sampleATO: ATOStruct = { Operation: ethers.toBigInt(1), minTokenIn: ethers.toBigInt(1), maxTokenIn: ethers.toBigInt(5), minTokenOut: ethers.toBigInt(5), maxTokenOut: ethers.toBigInt(10), tokenInAddress: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", tokenOutAddress: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F", sourceChainId: SupportedChainId.POLYGON, destinationChainId: SupportedChainId.CELO, }; const sampleUserIntent: UserIntent = { sender: "", intent: [sampleATO], nonce: ethers.toBigInt(0), }; const provider = ethers.provider; const userSigner = await provider.getSigner(0); const userAddress = await userSigner.getAddress(); const globalOwner = await provider.getSigner(1); const globalOwnerAddress = await globalOwner.getAddress(); console.log("Deploying registry contract..."); const registryDeployment = await ethers.deployContract( "SafeProtocolRegistry", [globalOwnerAddress] ); await registryDeployment.waitForDeployment(); const registryAddress = registryDeployment.target; console.log("Registry deployed to:", registryAddress); // get random address console.log("Deploying other boiler plate contracts..."); const randomAddress1 = ethers.Wallet.createRandom().address; const [sampleAccount, protocolManager, intentPlugin] = await Promise.all([ ethers.deployContract("SampleAccount", [userAddress]).then((d) => d.target), ethers .deployContract("SafeProtocolManager", [ globalOwnerAddress, registryAddress, ]) .then((d) => d.target), ethers .deployContract("IntentPlugin", [randomAddress1]) .then((d) => d.target), ]); console.log("Deployed contracts..."); // need to add module to the registry console.log("Adding module to registry..."); const registryInstance = SafeProtocolRegistry__factory.connect( String(registryAddress), globalOwner ); const addModuleTxn = await registryInstance.addModule(intentPlugin, 1); // passing 1 because module is a plugin type console.log("Module added to registry", addModuleTxn.hash); const txnData = new ethers.Interface( SafeProtocolManagerAbi.abi ).encodeFunctionData("enablePlugin", [String(intentPlugin), 1]); const abiCoder = new ethers.AbiCoder; const appendedCallData = abiCoder.encode( ['bytes', 'bytes'], [txnData, String(sampleAccount)] ); const enablePluginTxn = { to: protocolManager, data: appendedCallData, value: 0 }; // fund sampleAccount contract console.log("Funding sampleAccount contract..."); // funding wallet with 1 ether const fundTxn = await userSigner.sendTransaction({ to: sampleAccount, value: ethers.parseEther("1.0"), data: "0x", }); console.log("funded sampleAccount with 1 eth"); console.log("Txn hash:", fundTxn.hash); console.log("Enable plugin with necessary execute permission..."); const SampleAccountInstance = SampleAccount__factory.connect(String(sampleAccount), userSigner); const enableAccountTxn = await SampleAccountInstance.execTransaction( enablePluginTxn.to, enablePluginTxn.value, enablePluginTxn.data, 0, { gasLimit: 1000000 } ); console.log('Enabled intent plugin ', enableAccountTxn.hash); const intentPluginInstance = IntentPlugin__factory.connect( String(intentPlugin), userSigner ); sampleUserIntent.sender = String(sampleAccount); console.log("Paying fees for intent execution..."); console.log("Sample Intent formed", sampleUserIntent); const executeIntentTxnData = new ethers.Interface(IntentPlugin.abi).encodeFunctionData( 'payFeesAndExecuteIntent', [ String(protocolManager), String(sampleAccount), sampleUserIntent ] ); const txn = await SampleAccountInstance.execTransaction( String(sampleAccount), "0", executeIntentTxnData, 0, { gasLimit: 1000000 } ); console.log("Intent is now valid for execution", txn.hash); })();
package vsla.userManager.address; import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import java.time.LocalDateTime; @Entity @Table(name = "addresses") @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "address_id") private Long addressId; @Column(nullable = false) private String region; @Column(name = "zone", nullable = false) private String zone; @Column(nullable = false) private String woreda; @Column(nullable = false) private String kebele; @CreationTimestamp @Column(name = "created_at") @JsonIgnore private LocalDateTime createdAt; @JsonIgnore @UpdateTimestamp @Column(name = "updated_at") private LocalDateTime updatedAt; }
package CLIPlugins; import AutomatonSimulator.Automaton; import AutomatonSimulator.AutomatonUtil; import Main.Storable; import java.util.ArrayList; import java.util.Stack; /** * Checks if an {@link Automaton} accepts a given string. * @author fabian * @since 15.06.16 */ public class AutomatonCheckStringPlugin extends CLIPlugin { private boolean errorFlag = false; @Override public String[] getNames() { return new String[]{"csa", "check-string-automaton"}; } @Override public boolean checkParameters(String[] parameters) { if(parameters.length < 1) { System.out.println("Please enter a string as parameter for this command!"); return false; } return true; } @Override public String getHelpText() { return "Checks if a given string is accepted by the loaded automaton. Takes a string surrounded by quotation marks as parameter."; } @Override public Storable execute(Storable object, String[] parameters) { errorFlag = false; if(object == null) { System.out.println("Please use 'la', or 'load-automaton' to load an automaton before using this command!"); errorFlag = true; return null; } Automaton automaton = (Automaton) object; ArrayList<String> automatonInput = new ArrayList<>(); for(String parameter : parameters) { parameter = parameter.replaceAll("\\s+",""); parameter = parameter.replaceAll("\"", ""); if(parameter.length() > 0) { automatonInput.add(parameter); } } boolean accepted = AutomatonUtil.checkInput(automaton, automatonInput); Stack<String> takenWay = AutomatonUtil.getTakenWay(); String word = ""; int i = 0; for(String string : takenWay) { if(!string.contains("epsilon") && !string.contains("lambda")) { word += automatonInput.get(i) + " "; i++; } if(word.endsWith(" ")) { System.out.println(string + " \"" + word.substring(0, word.length() - 1) + "\""); } else { System.out.println(string + " \"" + word + "\""); } } if (accepted) { System.out.println("\nThe automaton accepts the given input!"); } else { System.out.println("\nThe automaton doesn't accept the given input!"); } return null; } @Override public Class inputType() { return Automaton.class; } @Override public Class outputType() { return null; } @Override public boolean errorFlag() { return errorFlag; } }
// // TaskManager.swift // WeeklyReportSwiftUI // // Created by @Ryan on 2023/8/10. // import Foundation import SwiftUI import AVFoundation class TaskManager: ObservableObject { static let shared: TaskManager = TaskManager() let impactSoft = UIImpactFeedbackGenerator(style: .soft) let impactLight = UIImpactFeedbackGenerator(style: .light) let impactMedium = UIImpactFeedbackGenerator(style: .medium) let impactHeavy = UIImpactFeedbackGenerator(style: .heavy) // AppStorage Site @AppStorage("asProjectArray") var asProjectArray: [String] = [] @AppStorage("asMeetingArray") var asMeetingArray: [String] = [] @AppStorage("asProgramArray") var asProgramArray: [String] = [] @AppStorage("asDayOffArray") var asDayOffArray: [String] = [] @AppStorage("asProjectItemArray") var asProjectItemArray: [String] = [] @AppStorage("asMeetingItemArray") var asMeetingItemArray: [String] = [] @AppStorage("asProgramItemArray") var asProgramItemArray: [String] = [] @AppStorage("asDayOffItemArray") var asDayOffItemArray: [String] = [] @Published var projectArray: [String] = ["專案一", "專案二", "專案三"] @Published var meetingArray: [String] = ["會議一", "會議二", "會議三"] @Published var programArray: [String] = ["程式一", "程式二", "程式三"] @Published var dayOffArray: [String] = ["特休假", "病假", "事假", "颱風假"] @Published var projectItemArray: [String] = ["進度追蹤", "文件整理", "問題統計", "系統展示"] @Published var meetingItemArray: [String] = ["與會", "製作會議紀錄", "系統展示"] @Published var programItemArray: [String] = ["修正邏輯問題", "修正UI介面", "修正bug", "修正閃退原因"] @Published var dayOffItemArray: [String] = ["回診", "預約看診", "私事處理", "家中有事處理"] @Published var selectedProjectItems: [String] = [] @Published var selectedMeetingItems: [String] = [] @Published var selectedProgramItems: [String] = [] @Published var selectedDayOffItems: [String] = [] @Published var otherDescription: String = "" @Published var currentDate: Date = Date() @Published var fetchedDateValues: [DateValue] = [] @Published var selectedDateValue: DateValue = DateValue(day: 0, date: Date()) let moodIconInfos: [Int: IconInfo] = [ 1: IconInfo(imageName: "1SoHappy", imageString: "開心", imageColor: Color.red), 2: IconInfo(imageName: "2Happy", imageString: "笑死", imageColor: Color.orangeColor), 3: IconInfo(imageName: "3OK", imageString: "不錯", imageColor: Color.SecondaryYellow), 4: IconInfo(imageName: "4Normal", imageString: "好喔", imageColor: Color.greenColor), 5: IconInfo(imageName: "5Angry", imageString: "怒怒", imageColor: Color.purpleBlueColor), 6: IconInfo(imageName: "6Sad", imageString: "難過", imageColor: Color.navyColor), 7: IconInfo(imageName: "7Shocked", imageString: "驚嚇", imageColor: Color.purpleColor) ] @Published var currentMonth: Int = 0 @Published var fetchedSqlTasks: [Task] = [] @Published var selectedWeekStartDate: Date = Date() @Published var fetchedSelectedWeekTasks: [Task] = [] @Published var sortedWeekTasks: [[Task]] = [[]] @Published var sortedWeekTaskString: [[String]] = [[]] @Published var selectedTask: Task = Task(taskCategory: "", taskTitle: "", taskDescription: "", taskProgress: 0, taskStartDate: Date(), taskEndDate: Date(), taskMoodLevel: 4) @Published var isEditing: Bool = false @Published var savedTaskStartDate: Date? = nil @Published var savedTaskEndDate: Date? = nil @Published var weekSlider: [[DateValue]] = [] @Published var needUpdate: Bool = false @Published var isSaving: Bool = false @Published var showSelections: Bool = false @AppStorage("mondayMorningDetails") var mondayMorningDetails: String = "" @AppStorage("mondayAfternoonDetails") var mondayAfternoonDetails: String = "" @AppStorage("tuesdayMorningDetails") var tuesdayMorningDetails: String = "" @AppStorage("tuesdayAfternoonDetails") var tuesdayAfternoonDetails: String = "" @AppStorage("wednesdayMorningDetails") var wednesdayMorningDetails: String = "" @AppStorage("wednesdayAfternoonDetails") var wednesdayAfternoonDetails: String = "" @AppStorage("thursdayMorningDetails") var thursdayMorningDetails: String = "" @AppStorage("thursdayAfternoonDetails") var thursdayAfternoonDetails: String = "" @AppStorage("fridayMorningDetails") var fridayMorningDetails: String = "" @AppStorage("fridayAfternoonDetails") var fridayAfternoonDetails: String = "" @AppStorage("combineProject") var combineProject: Bool = true @AppStorage("combineMeeting") var combineMeeting: Bool = false @AppStorage("combineProgram") var combineProgram: Bool = true @AppStorage("combineDayOffs") var combineDayOffs: Bool = false init() { fetchedSqlTasks = SQLiteCommands.getAllTasks() // fetchedSelectedWeekTasks = SQLiteCommands.getTasksForWeek(of: Date()) initAppStorageData() print("fetchedSqlTasks: \(fetchedSqlTasks.count)") } func initAppStorageData() { if asProjectArray == [] { asProjectArray = projectArray } else { projectArray = asProjectArray } if asMeetingArray == [] { asMeetingArray = meetingArray } else { meetingArray = asMeetingArray } if asProgramArray == [] { asProgramArray = programArray } else { programArray = asProgramArray } if asDayOffArray == [] { asDayOffArray = dayOffArray } else { dayOffArray = asDayOffArray } if asProjectItemArray == [] { asProjectItemArray = projectItemArray } else { projectItemArray = asProjectItemArray } if asMeetingItemArray == [] { asMeetingItemArray = meetingItemArray } else { meetingItemArray = asMeetingItemArray } if asProgramItemArray == [] { asProgramItemArray = programItemArray } else { programItemArray = asProgramItemArray } if asDayOffItemArray == [] { asDayOffItemArray = dayOffItemArray } else { dayOffItemArray = asDayOffItemArray } } func firstCharacter(of string: String) -> String? { return string.first.map(String.init) } func removeFirstCharacter(from string: String) -> String { guard string.count >= 3 else { return string // 或者根據你的需要返回一個錯誤或其他值 } let index = string.index(string.startIndex, offsetBy: 1) return String(string[index...]) } func getIconInfo(from intValue: Int) -> IconInfo? { return moodIconInfos[intValue] } func fetchCurrentWeek(_ date: Date = .init()) -> [DateValue] { let calendar = Calendar.current let startOfDate = calendar.startOfDay(for: date) var week: [DateValue] = [] let weekForDate = calendar.dateInterval(of: .weekOfMonth, for: startOfDate) guard let startOfWeek = weekForDate?.start else { return [] } (0..<7).forEach { index in if let weekday = calendar.date(byAdding: .day, value: index, to: startOfWeek) { let day = calendar.component(.day, from: weekday) // Filter pains that match the current weekday let tasksForDay = fetchedSqlTasks.filter { calendar.isDate($0.taskStartDate, inSameDayAs: weekday) } week.append(DateValue(day: day, date: weekday, tasks: tasksForDay)) } } return week } func createNextWeek(_ lastDate: Date) -> [DateValue] { let calendar = Calendar.current let startOfLastDate = calendar.startOfDay(for: lastDate) guard let nextDate = calendar.date(byAdding: .day, value: 1, to: startOfLastDate) else { return [] } return fetchCurrentWeek(nextDate) } func createPreviousWeek(_ firstDate: Date) -> [DateValue] { let calendar = Calendar.current let startOfFirstDate = calendar.startOfDay(for: firstDate) guard let previousDate = calendar.date(byAdding: .day, value: -1, to: startOfFirstDate) else { return [] } return fetchCurrentWeek(previousDate) } func getCurrentMonth() -> Date { let calendar = Calendar.current guard let currentMonth = calendar.date(byAdding: .month, value: self.currentMonth, to: Date()) else { return Date() } return currentMonth } func extractChinessWeek(date: Date) -> String { let formatter = DateFormatter() formatter.locale = Locale(identifier: "zh_Hant_TW") // 使用繁體中文 formatter.dateFormat = "EEEE" var result = formatter.string(from: date) result = result.replacingOccurrences(of: "星期", with: "週") return result } func extractDate(date: Date, format: String) -> String { let formatter = DateFormatter() formatter.dateFormat = format return formatter.string(from: date) } func firstDayOfCurrentMonth(from date: Date) -> Date? { let calendar = Calendar.current guard let firstDayOfMonth = calendar.date(from: calendar.dateComponents([.year, .month], from: date)) else { return nil } return calendar.date(byAdding: .month, value: 0, to: firstDayOfMonth) } func firstDayOfPreviousMonth(from date: Date) -> Date? { let calendar = Calendar.current guard let firstDayOfMonth = calendar.date(from: calendar.dateComponents([.year, .month], from: date)) else { return nil } return calendar.date(byAdding: .month, value: -1, to: firstDayOfMonth) } func firstDayOfNextMonth(from date: Date) -> Date? { let calendar = Calendar.current guard let firstDayOfMonth = calendar.date(from: calendar.dateComponents([.year, .month], from: date)) else { return nil } return calendar.date(byAdding: .month, value: 1, to: firstDayOfMonth) } func filterTasks(from allTasks: [Task], basedOn date: Date) -> [Task] { let startDate = date.startOfWeek.addingDays(1) let endDate = startDate.addingDays(5) return allTasks.filter { task in task.taskStartDate > startDate && task.taskEndDate < endDate }.sorted(by: { $0.taskStartDate < $1.taskStartDate }) } func combine(strings: [String]) -> String { // 過濾掉空字串 let filteredStrings = strings.filter { !$0.isEmpty } switch filteredStrings.count { case 0: return " " case 1: return filteredStrings[0] case 2: return filteredStrings.joined(separator: "及") default: let allButLast = filteredStrings.dropLast().joined(separator: "、") return "\(allButLast)及\(filteredStrings.last!)" } } func split(combinedString: String) -> [String] { let components = combinedString.components(separatedBy: "及") switch components.count { case 1: return components case 2: return components.first!.components(separatedBy: "、") + [components.last!] default: return combinedString.components(separatedBy: "、") } } func splitAndCombineTasks(for weekTasks: [Task]) -> [[Task]] { var dailyTasks: [[Task]] = Array(repeating: [], count: 5) // 五個空陣列對應於一週的五天 for task in weekTasks { // 得到該任務所在週的天數 (0-4) guard let day = Calendar.current.dateComponents([.weekday], from: task.taskStartDate).weekday, day >= 2, day <= 6 else { continue } let taskIndex = day - 2 // 查看是否已有相同的 taskCategory 和 taskTitle 的任務存在於該天 if let existingTaskIndex = dailyTasks[taskIndex].firstIndex(where: { $0.taskCategory != "\(combineProject ? "" : "專案")" && $0.taskCategory != "\(combineMeeting ? "" : "會議")" && $0.taskCategory != "\(combineProgram ? "" : "程式")" && $0.taskCategory != "\(combineDayOffs ? "" : "休假")" && $0.taskCategory == task.taskCategory && $0.taskTitle == task.taskTitle }) { // 分解現有任務和新任務的 taskDescription let existingDescriptions = split(combinedString: dailyTasks[taskIndex][existingTaskIndex].taskDescription) let newDescriptions = split(combinedString: task.taskDescription) // 合併並移除重複項 let combinedDescriptions = Array(Set(existingDescriptions + newDescriptions)) // 更新該任務的 taskDescription dailyTasks[taskIndex][existingTaskIndex].taskDescription = combine(strings: combinedDescriptions) } else { dailyTasks[taskIndex].append(task) } } return dailyTasks } func generateDescriptionStrings(from tasksByDay: [[Task]]) -> [[String]] { return tasksByDay.map { tasksForOneDay in // 對於一天的任務,區分為上午和下午 let morningTasks = tasksForOneDay.filter { task in guard let hour = Calendar.current.dateComponents([.hour], from: task.taskStartDate).hour else { return false } return hour < 12 } let afternoonTasks = tasksForOneDay.filter { task in guard let hour = Calendar.current.dateComponents([.hour], from: task.taskStartDate).hour else { return false } return hour >= 12 } // 根據每個任務生成描述字串 let morningStrings = morningTasks.map { task in return "[\(task.taskTitle)] \(task.taskDescription)" } let afternoonStrings = afternoonTasks.map { task in return "[\(task.taskTitle)] \(task.taskDescription)" } // 使用 " / " 將描述字串組合起來 return [morningStrings.joined(separator: " / "), afternoonStrings.joined(separator: " / ")] } } func saveDetailsToAppStorage(descriptionsForWeek: [[String]]) { guard descriptionsForWeek.count >= 5 else { return } // 確保有五天的描述 mondayMorningDetails = descriptionsForWeek[0][0] mondayAfternoonDetails = descriptionsForWeek[0][1] tuesdayMorningDetails = descriptionsForWeek[1][0] tuesdayAfternoonDetails = descriptionsForWeek[1][1] wednesdayMorningDetails = descriptionsForWeek[2][0] wednesdayAfternoonDetails = descriptionsForWeek[2][1] thursdayMorningDetails = descriptionsForWeek[3][0] thursdayAfternoonDetails = descriptionsForWeek[3][1] fridayMorningDetails = descriptionsForWeek[4][0] fridayAfternoonDetails = descriptionsForWeek[4][1] } func delayedImpactOccurred(impactStyle: UIImpactFeedbackGenerator.FeedbackStyle, delaySec: Double) { DispatchQueue.main.asyncAfter(deadline: .now() + delaySec) { UIImpactFeedbackGenerator(style: impactStyle).impactOccurred() } } }
# Transparent Modbus/TCP Slave This directory contains an implementation superseding all those found on `../mb-{emitter,gateway,server}`. Instead of directly interfacing with a LoRa-capable radio (i.e. the RFM9x) we instead chose to leverage a commercial Modbus-to-LoRa bridge converter. This piece of equipment works in such a way that any incoming Modbus RTU frames are radiated over LoRa **as long as** the destination Slave ID is not `1` (i.e. the ID of the bridge itself). In fact, Slave ID `1` is leveraged by the bridge itself for its configuration. This scheme makes the querying of remote Modbus-enabled devices over LoRa transparent: one just needs to query a Slave ID other than `1` and the RTU frame will be radiated for other bridges to pick it up. Queried data will be inserted into memory area serving as the Modbus Slave's registers. This will be queried over TCP by a remote industrial-grade PLC implementing a Modbus/TCP client. The register addresses where data is served is fully configurable through command-line flags. This implementation is **currently deployed** on the water quality control hub at Guadalajara's EDAR on a Raspberry Pi 4 reachable on IPv4 address `192.168.240.4`. The implementation is running headlessly as a SystemD unit defined on `mb-master.service`. The applicable and interesting options are explicitly defined on the `ExecStart` clause, which would make the appropriate invocation: /bin/mb-master --local-mb-bind-address 0.0.0.0 --local-mb-bind-port 502 \ --remote-mb-enable --remote-mb-serial-dev /dev/ttyUSB0 --remote-mb-timeout 60 \ --udp-enable --udp-bind-address 0.0.0.0 ## Compilation In order to ease compilation, this implementation includes a `Taskfile` offering the following targets: - `mac`: Builds the application for macOS machines. - `arm`: Builds the application for ARM devices such as the Raspberry Pi 4. Running any target is a mater of invoking `task <target-name>`. ## Debugging In order to test data insertion we included a piece of code exposing a UDP socket. We leaned towards UDP because it is much easier to manage than TCP and it can be leveraged with tools such as `nc(1)`. Once can invoke the application and then insert data with: # Run the server on another terminal: we'll bind the UDP socket to 127.0.0.1:1503 $ ./bin/mb-master-mac --remote-mb-enable=false # And then fire up netcat (in UDP mode): you can type stuff on the session that opens up. $ nc -u 127.0.0.1 1503 {"deviceId": "geonosis", "data": 5} The data insertion will be reflected on the logs! On top of that, one can use the `mb-query` tool to verify data can be retrieved: $ mb-query tcp --host 127.0.0.1 --port 1502 readHolding <register-address> What's more, address `0` contains static value `0xABCD`: $ mb-query tcp --host 127.0.0.1 --port 1502 readHolding 0 Data for address 0x0: Decimal -> 43981 Hex -> 0xabcd Octal -> 0125715
import * as React from "react"; import { Link, useLocation } from "react-router-dom"; import { ROUTES } from "../../routes"; import { capitalize } from "../../utils/function"; import { NavbarLink } from "../partials/navbarlink"; export interface NavbarState { currentSite: string; } export interface NavbarProps { site?: string; location?: any; } export function Navbar(props: NavbarProps) { const currentLocation = useLocation(); const [state, setState] = React.useState<NavbarState>({ currentSite: "" }); const navbarBgClass = " cui-box-shadow-remove"; const downloadBtnCls = state.currentSite ? "cui-shade" : "cui-shade"; function getCurrentPage() { let split = currentLocation.pathname.split('/'); let curr = ""; if (split.length > 1) { if (split.length >= 4 && split[2].toLowerCase().match("component")) { curr = capitalize(split[3]); } else { curr = capitalize(split[1]) } } return curr; } React.useEffect(() => { setState({ currentSite: getCurrentPage() }) }, [currentLocation]) return ( <nav className={"cui-navbar cui-sticky layout-navigation navbar-background-accent cui-dark " + navbarBgClass}> <div className="cui-navbar-left cui-width-1-1 cui-width-auto--m cui-flex cui-middle cui-between" id="navbar-left"> <ul> {state.currentSite && <li><Link className="cui-icon app-icon" cui-icon="app_icon" to="/"></Link></li>} <li><span>{state.currentSite}</span></li> </ul> <ul className="cui-hidden--m"> <li><a className="cui-icon cui-padding cui-button " cui-icon="menu" cui-open="target: #app-offcanvas"></a></li> </ul> </div> <ul className="cui-navbar-right cui-unhidden--m"> <li><NavbarLink class="cui-navbar-item" url={ROUTES['home'].uri} name={ROUTES['home'].name} /></li> <li><NavbarLink class="cui-navbar-item" url={ROUTES['overview'].uri} name={ROUTES['overview'].name} /></li> <li><NavbarLink class="cui-navbar-item" url={ROUTES['docs'].uri} name={ROUTES['docs'].name} /></li> <li><NavbarLink class="cui-navbar-item" url={ROUTES['icons'].uri} name={ROUTES['icons'].name} /></li> <li><NavbarLink class="cui-navbar-item" url={ROUTES['about'].uri} name={ROUTES['about'].name} /></li> <li><Link to={ROUTES['download'].uri} className={"cui-button cui-rounded " + downloadBtnCls}>Download</Link></li> <li><Link className="cui-icon cui-button cui-circle cui-padding" cui-icon="search" to={ROUTES['search'].uri}></Link></li> </ul> </nav> ) }
package CACTestCases; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import util.TestBase; import util.TestUtils; public class SignIn extends TestBase { private String email; private String pw1; private String userName; private String email1; private String pw; private String userName1; private String invalidPw; private String invalidADUsername; private String UserID; private String validPw; private String invalidUserID; @Parameters({"testEnv"}) @BeforeMethod public void parseJson(String testEnv) throws Exception { File path = null; File classpathRoot = new File(System.getProperty("user.dir")); if (testEnv.equalsIgnoreCase("StagingData")) { path = new File(classpathRoot, "stagingData/data.conf.json"); } else { path = new File(classpathRoot, "prodData/data.conf.json"); } JSONParser parser = new JSONParser(); JSONObject config = (JSONObject) parser.parse(new FileReader(path)); JSONObject envs = (JSONObject) config.get("AD_ValidLogin"); email = (String) envs.get("email"); pw1 = (String) envs.get("pw1"); userName = (String) envs.get("userName"); email1 = (String) envs.get("email1"); pw = (String) envs.get("pw"); userName1 = (String) envs.get("userName1"); invalidPw = (String) envs.get("invalidPw"); invalidADUsername = (String) envs.get("invalidADUsername"); UserID = (String) envs.get("UserID"); validPw = (String) envs.get("validPw"); invalidUserID = (String) envs.get("invalidUserID"); } @Parameters ({"testEnv"}) public static void login (String testEnv, String testVal) throws InterruptedException, FileNotFoundException, IOException, ParseException { File path = null; File classpathRoot = new File(System.getProperty("user.dir")); if(testEnv.equalsIgnoreCase("StagingData")) { path = new File(classpathRoot, "stagingData/data.conf.json"); }else { path = new File(classpathRoot, "prodData/data.conf.json"); } JSONParser parser = new JSONParser(); JSONObject config = (JSONObject) parser.parse(new FileReader(path)); JSONObject envs = (JSONObject) config.get(testVal); String email = (String) envs.get("email"); String bioSmartUser = System.getProperty("adminUsername", email); String pw = (String) envs.get("pw"); String userPw = System.getProperty("adminPassword", pw); TestUtils.testTitle("Login with username: (" + bioSmartUser + ") and password: (" + userPw + ")"); Assert.assertEquals(getDriver().getTitle(), "SIMROP | Login"); // Select Login mode getDriver().findElement(By.id("loginMode")).click(); new Select(getDriver().findElement(By.id("loginMode"))).selectByVisibleText("Biosmart"); Thread.sleep(500); getDriver().findElement(By.id("email")).clear(); getDriver().findElement(By.id("email")).sendKeys(bioSmartUser); getDriver().findElement(By.id("password")).clear(); getDriver().findElement(By.id("password")).sendKeys(userPw); getDriver().findElement(By.id("login-btn")).click(); Thread.sleep(1000); } @Parameters ({"testEnv"}) @Test public void blacklistedUserLoginTest(String testEnv) throws Exception { WebDriverWait wait = new WebDriverWait(getDriver(), waitTime); login(testEnv, "Blacklisted_User"); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("strong"))); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Your account was Blacklisted. Please contact support."); } @Parameters ({"testEnv"}) @Test public void deactivatedUserLoginTest(String testEnv) throws Exception { WebDriverWait wait = new WebDriverWait(getDriver(), waitTime); login(testEnv, "Deactivated_User"); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("strong"))); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Your account was deactivated. Please contact support."); } @Parameters ({"testEnv"}) @Test public void nonExistingEmailLoginTest(String testEnv) throws Exception { WebDriverWait wait = new WebDriverWait(getDriver(), waitTime); login(testEnv, "Invalid_Email_Password"); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("strong"))); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Invalid username or password entered."); } @Test public void emptyInputFieldTest() throws InterruptedException { TestUtils.testTitle("Login with empty fields"); List<String> validationMessages = new ArrayList<>(); validationMessages.add("Please fill out this field."); validationMessages.add("Please fill in this field."); // Select Login mode getDriver().findElement(By.id("loginMode")).click(); new Select(getDriver().findElement(By.id("loginMode"))).selectByVisibleText("Biosmart"); Thread.sleep(500); getDriver().findElement(By.id("email")).clear(); getDriver().findElement(By.id("email")).sendKeys(""); getDriver().findElement(By.id("login-btn")).click(); WebElement email = getDriver().findElement(By.name("email")); TestUtils.assertValidationMessage(validationMessages, email, "Email"); getDriver().findElement(By.id("email")).sendKeys("[email protected]"); getDriver().findElement(By.id("password")).clear(); getDriver().findElement(By.id("password")).sendKeys(""); getDriver().findElement(By.id("login-btn")).click(); WebElement password = getDriver().findElement(By.name("password")); TestUtils.assertValidationMessage(validationMessages, password, "Password"); } @Parameters ("testEnv") @Test (groups = { "Regression" }) public void validEmailPasswordLoginTest(String testEnv) throws InterruptedException, FileNotFoundException, IOException, ParseException { login(testEnv, "valid_Admin_Login"); Assert.assertEquals(getDriver().getTitle(), "SIMROP | Dashboard"); TestUtils.assertSearchText("XPATH", "(//a[contains(text(),'ADMIN')])[2]", "ADMIN"); } @Parameters ("testEnv") @Test (groups = { "Regression" }) public void declineTermsAndConditionsLoginTest(String testEnv) throws Exception { WebDriverWait wait = new WebDriverWait(getDriver(), waitTime); login(testEnv, "TermsAndConditionsLogin"); try { if (getDriver().findElement(By.xpath("//h1")).isDisplayed()) { Assert.assertEquals(getDriver().getTitle(), "SIMROP | T&Cs"); TestUtils.assertSearchText("XPATH", "//h1", "TERMS AND CONDITIONS"); TestUtils.testTitle("Decline Terms and Conditions"); TestUtils.scrollUntilElementIsVisible("ID", "disagree-btn"); Thread.sleep(500); getDriver().findElement(By.id("disagree-btn")).click(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("strong"))); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Terms and Conditions must be accepted"); Thread.sleep(500); } } catch (Exception e) { testInfo.get().info("<b> SIMROP TERMS AND CONDITIONS SETTING IS TURNED OFF </b>"); Assert.assertEquals(getDriver().getTitle(), "SIMROP | Dashboard"); TestUtils.assertSearchText("XPATH", "(//a[contains(text(),'ADMIN')])[2]", "ADMIN"); logOutTest(testEnv); } } @Parameters ("testEnv") @Test (groups = { "Regression" }) public void logOutTest(String testEnv) throws Exception { WebDriverWait wait = new WebDriverWait(getDriver(), waitTime); TestUtils.testTitle("Logout"); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@id='navbarDropdownMenuLink']/i"))); Thread.sleep(1000); getDriver().findElement(By.xpath("//a[@id='navbarDropdownMenuLink']/i")).click(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//a[contains(@href, '/simrop/logout?language=en_US')])[2]"))); Thread.sleep(1000); getDriver().findElement(By.xpath("(//a[contains(@href, '/simrop/logout?language=en_US')])[2]")).click(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email"))); TestUtils.assertSearchText("CSSSELECTOR", "h4.text-dark", "Login"); Thread.sleep(500); } @Parameters ({"testEnv"}) @Test (groups = { "Regression" }) public void erorrMessagesValidationTest(String testEnv) throws InterruptedException, FileNotFoundException, IOException, ParseException { // Login with Active Directory user but select Biosmart as Auth mode and biosmart email TestUtils.testTitle("Login with Active Directory user but select Biosmart as Auth mode and biosmart email: " + email); getDriver().findElement(By.id("loginMode")).click(); new Select(getDriver().findElement(By.id("loginMode"))).selectByVisibleText("Biosmart"); Thread.sleep(500); getDriver().findElement(By.id("email")).clear(); getDriver().findElement(By.id("email")).sendKeys(email); getDriver().findElement(By.id("password")).clear(); getDriver().findElement(By.id("password")).sendKeys(pw1); getDriver().findElement(By.id("login-btn")).click(); Thread.sleep(1000); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Your allowed Login Mode is Active Directory. Your AD Username is; " + userName); Thread.sleep(500); // Login with Active Directory user but select Biosmart as Auth mode and Active Directory user name TestUtils.testTitle("Login with Active Directory user but select Biosmart as Auth mode and Active Directory user name: " + userName); getDriver().findElement(By.id("loginMode")).click(); new Select(getDriver().findElement(By.id("loginMode"))).selectByVisibleText("Biosmart"); Thread.sleep(500); getDriver().findElement(By.id("email")).clear(); getDriver().findElement(By.id("email")).sendKeys(userName); getDriver().findElement(By.id("password")).clear(); getDriver().findElement(By.id("password")).sendKeys(pw); getDriver().findElement(By.id("login-btn")).click(); Thread.sleep(1000); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Your allowed Login Mode is Active Directory. Your AD Username is; " + userName); Thread.sleep(500); // Login with Active Directory user but select Active Directory as Auth mode and Biosmart email TestUtils.testTitle("Login with Active Directory user but select Active Directory as Auth mode and Biosmart email: " + email); getDriver().findElement(By.id("loginMode")).click(); new Select(getDriver().findElement(By.id("loginMode"))).selectByVisibleText("Active Directory"); Thread.sleep(500); getDriver().findElement(By.id("email")).clear(); getDriver().findElement(By.id("email")).sendKeys(email); getDriver().findElement(By.id("password")).clear(); getDriver().findElement(By.id("password")).sendKeys(pw1); getDriver().findElement(By.id("login-btn")).click(); Thread.sleep(1000); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Your allowed Login Mode is Active Directory. Your AD Username is; " + userName); Thread.sleep(500); // Login with Biosmart user but select Active Directory as Auth mode and Active Directory username TestUtils.testTitle("Login with Biosmart user but select Active Directory as Auth mode and Active Directory username: " + userName1); getDriver().findElement(By.id("loginMode")).click(); new Select(getDriver().findElement(By.id("loginMode"))).selectByVisibleText("Active Directory"); Thread.sleep(500); getDriver().findElement(By.id("email")).clear(); getDriver().findElement(By.id("email")).sendKeys(userName1); getDriver().findElement(By.id("password")).clear(); getDriver().findElement(By.id("password")).sendKeys(pw1); getDriver().findElement(By.id("login-btn")).click(); Thread.sleep(1000); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Your allowed Login Mode is Biosmart. Your email address is; " + email1); Thread.sleep(500); // Login with Biosmart user but select Active Directory as Auth mode and Biosmart email TestUtils.testTitle("Login with Biosmart user but select Active Directory as Auth mode and Biosmart email: " + email1); getDriver().findElement(By.id("loginMode")).click(); new Select(getDriver().findElement(By.id("loginMode"))).selectByVisibleText("Active Directory"); Thread.sleep(500); getDriver().findElement(By.id("email")).clear(); getDriver().findElement(By.id("email")).sendKeys(email1); getDriver().findElement(By.id("password")).clear(); getDriver().findElement(By.id("password")).sendKeys(pw1); getDriver().findElement(By.id("login-btn")).click(); Thread.sleep(1000); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Your allowed Login Mode is Biosmart. Your email address is; " + email1); Thread.sleep(500); // Login with Biosmart user but select Biosmart as Auth mode and Active Directory username TestUtils.testTitle("Login with Biosmart user but select Biosmart as Auth mode and Active Directory username: " + userName1); getDriver().findElement(By.id("loginMode")).click(); new Select(getDriver().findElement(By.id("loginMode"))).selectByVisibleText("Biosmart"); Thread.sleep(500); getDriver().findElement(By.id("email")).clear(); getDriver().findElement(By.id("email")).sendKeys(userName1); getDriver().findElement(By.id("password")).clear(); getDriver().findElement(By.id("password")).sendKeys(pw1); getDriver().findElement(By.id("login-btn")).click(); Thread.sleep(1000); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Your allowed Login Mode is Biosmart. Your email address is; " + email1); Thread.sleep(500); } @Parameters ("testEnv") @Test (groups = { "Regression" }) public void activeDirectoryValidLoginTest(String testEnv) throws Exception { String adUsername = System.getProperty("adminUsername", userName); String userPw = System.getProperty("adminPassword", pw); TestUtils.testTitle("Login with valid username: (" + adUsername + ") and password: (" + userPw + ")"); Assert.assertEquals(getDriver().getTitle(), "SIMROP | Login"); adSignInTest(adUsername, userPw); Assert.assertEquals(getDriver().getTitle(), "SIMROP | Dashboard"); TestUtils.assertSearchText("XPATH", "(//a[contains(text(),'ADMIN')])[2]", "ADMIN"); } public void adSignInTest(String adUsername, String pw) throws InterruptedException { // Select Login mode getDriver().findElement(By.id("loginMode")).click(); new Select(getDriver().findElement(By.id("loginMode"))).selectByVisibleText("Active Directory"); Thread.sleep(500); getDriver().findElement(By.id("email")).clear(); getDriver().findElement(By.id("email")).sendKeys(adUsername); getDriver().findElement(By.id("password")).clear(); getDriver().findElement(By.id("password")).sendKeys(pw); getDriver().findElement(By.id("login-btn")).click(); Thread.sleep(1000); } @Parameters ("testEnv") @Test (groups = { "Regression" }) public void adLoginValidationTest() throws InterruptedException { WebDriverWait wait = new WebDriverWait(getDriver(), waitTime); List<String> validationMessages = new ArrayList<>(); validationMessages.add("Please fill out this field."); validationMessages.add("Please fill in this field."); // Login with valid AD username and invalid password TestUtils.testTitle("Login with valid AD username: (" + userName + ") and invalid password: (" + invalidPw + ")"); adSignInTest(userName, invalidPw); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("strong"))); TestUtils.assertSearchText("CSSSELECTOR", "strong", "You entered an invalid username or password."); // Login with invalid AD username and valid password TestUtils.testTitle("Login with invalid AD username: (" + invalidADUsername + ") and valid password: (" + pw + ")"); adSignInTest(invalidADUsername, pw); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("strong"))); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Invalid username or password entered."); // Login with empty AD username and valid password TestUtils.testTitle("Login with empty AD username: ( ) and valid password: (" + pw + ")"); adSignInTest("", pw); WebElement email = getDriver().findElement(By.name("email")); TestUtils.assertValidationMessage(validationMessages, email, "Email"); // Login with valid AD username and empty password TestUtils.testTitle("Login with valid AD username: (" + userName + ") and empty password: ( )"); adSignInTest(userName, ""); WebElement password = getDriver().findElement(By.name("password")); TestUtils.assertValidationMessage(validationMessages, password, "Password"); // Login with empty AD username and empty password TestUtils.testTitle("Login with empty AD username: ( ) and empty password: ( )"); adSignInTest("", ""); WebElement emaill = getDriver().findElement(By.name("email")); TestUtils.assertValidationMessage(validationMessages, emaill, "Email"); // Login with invalid AD username and invalid password TestUtils.testTitle("Login with invalid AD username: (" + invalidADUsername + ") and invalid password: (" + invalidPw + ")"); adSignInTest(invalidADUsername, invalidPw); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("strong"))); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Invalid username or password entered."); } @Parameters ("testEnv") @Test (groups = { "Regression" }) public void userIDValidLoginTest(String testEnv) throws Exception { String userID = System.getProperty("adminUsername", UserID); String userPw = System.getProperty("adminPassword", validPw); TestUtils.testTitle("Login with valid User ID: (" + userID + ") and valid password: (" + userPw + ")"); Assert.assertEquals(getDriver().getTitle(), "SIMROP | Login"); userIDSignInTest(userID, userPw); Assert.assertEquals(getDriver().getTitle(), "SIMROP | Dashboard"); TestUtils.assertSearchText("XPATH", "(//a[contains(text(),'ADMIN')])[2]", "ADMIN"); } public void userIDSignInTest(String userID, String pw) throws InterruptedException { // Select Login mode getDriver().findElement(By.id("loginMode")).click(); new Select(getDriver().findElement(By.id("loginMode"))).selectByVisibleText("Biosmart"); Thread.sleep(500); getDriver().findElement(By.id("email")).clear(); getDriver().findElement(By.id("email")).sendKeys(userID); getDriver().findElement(By.id("password")).clear(); getDriver().findElement(By.id("password")).sendKeys(pw); getDriver().findElement(By.id("login-btn")).click(); Thread.sleep(1000); } @Parameters ("testEnv") @Test (groups = { "Regression" }) public void userIDValidationTest(String testEnv) throws Exception { WebDriverWait wait = new WebDriverWait(getDriver(), waitTime); List<String> validationMessages = new ArrayList<>(); validationMessages.add("Please fill out this field."); validationMessages.add("Please fill in this field."); // Login with valid UserID and invalid password TestUtils.testTitle("Login with valid UserID: (" + UserID + ") and invalid password: (" + invalidPw + ")"); userIDSignInTest(UserID, invalidPw); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("strong"))); TestUtils.assertSearchText("CSSSELECTOR", "strong", "You entered an invalid username or password."); // Login with invalid UserID and valid password TestUtils.testTitle("Login with invalid UserID: (" + invalidUserID + ") and valid password: (" + pw + ")"); userIDSignInTest(invalidUserID, pw); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("strong"))); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Please enter a valid user Id format (user ID)"); // Login with empty UserID and valid password TestUtils.testTitle("Login with empty UserID: ( ) and valid password: (" + pw + ")"); userIDSignInTest("", pw); WebElement email = getDriver().findElement(By.name("email")); TestUtils.assertValidationMessage(validationMessages, email, "Email"); // Login with valid UserID and empty password TestUtils.testTitle("Login with valid UserID: (" + UserID + ") and empty password: ( )"); userIDSignInTest(UserID, ""); WebElement password = getDriver().findElement(By.name("password")); TestUtils.assertValidationMessage(validationMessages, password, "Password"); // Login with empty UserID and empty password TestUtils.testTitle("Login with empty UserID: ( ) and empty password: ( )"); userIDSignInTest("", ""); WebElement emaill = getDriver().findElement(By.name("email")); TestUtils.assertValidationMessage(validationMessages, emaill, "Email"); // Login with invalid UserID and invalid password TestUtils.testTitle("Login with invalid UserID: (" + invalidUserID + ") and invalid password: (" + invalidPw + ")"); userIDSignInTest(invalidUserID, invalidPw); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("strong"))); TestUtils.assertSearchText("CSSSELECTOR", "strong", "Please enter a valid user Id format (user ID)"); } }
#' Plot forecast over seasonal history #' #' Plot forecast over the historical seasonal data. #' #' Using a `forecasts_geom` of "line" is more useful for less zig-zaggy #' forecasts. This generally means small values of `n_closest`. Using "point" #' is good for zig-zaggy forecasts, because in these cases, "line" yeilds a #' spiky blob. #' #' @param forecast tibble. Output of [hot_deck_forecast()]. #' @param historical_data tsibble. The data. #' @param observation_col_name string. The observation column name. #' @param filter_past_forecasts bool. Filter forecasts before `lubdridate::today()`? #' @param forecasts_geom string. The geom to use for the forecasts on the ggplot #' @param title string. The title. #' @param x_lab string. The x-axis label. #' @param y_lab string. The y-axis label. #' @param caption string. The figure caption. #' #' @examples #' data = append_lead(hotdeckts::SUGG_temp, observation) #' fc = hot_deck_forecast(data, #' observation, #' times = 5, #' h = 20, #' window_back = 20, #' window_fwd = 20, #' n_closest = 5) #' plot_forecast(fc, data) #' #' @export plot_forecast = function(forecast, historical_data, observation_col_name = "observation", filter_past_forecasts = FALSE, forecasts_geom = c("line", "point"), title = "Forecast", x_lab = "Day of Year", y_lab = "Observation", caption = ggplot2::waiver()) { # data setup historical_data_index = tsibble::index(historical_data) historical_data = historical_data %>% dplyr::mutate( doy = lubridate::yday({{ historical_data_index }}), yr = lubridate::year({{ historical_data_index }}) ) # TODO: meta, .env forecast = forecast %>% dplyr::mutate( doy = lubridate::yday(datetime), yr = lubridate::year(datetime) ) if (filter_past_forecasts) { forecast = forecast %>% dplyr::filter(datetime >= lubridate::today()) } mean_fc = forecast %>% dplyr::group_by(doy) %>% dplyr::summarise(avg_pred = mean(forecast, na.rm = TRUE)) latest_obs = historical_data %>% dplyr::slice_tail() # forecasts geom types forecasts_geom = match.arg(forecasts_geom) fcs_as_lines = ggplot2::geom_line( data = forecast, mapping = ggplot2::aes( x = doy, y = forecast, color = as.factor(simulation_num) ), show.legend = FALSE, linewidth = 0.25 ) fcs_as_points = ggplot2::geom_point( data = forecast, mapping = ggplot2::aes( x = doy, y = forecast, color = as.factor(simulation_num) ), show.legend = FALSE, alpha = 0.3, size = 0.25 ) fc_geom = if (forecasts_geom == "line") fcs_as_lines else fcs_as_points # plotting ggplot2::ggplot() + fc_geom + ggplot2::geom_line( data = historical_data, mapping = ggplot2::aes( x = doy, y = .data[[observation_col_name]], group = as.factor(yr) ), show.legend = FALSE, alpha = 0.5 ) + ggplot2::geom_point( data = latest_obs, mapping = ggplot2::aes( x = doy, y = .data[[observation_col_name]] ), color = "red" ) + ggplot2::geom_line( data = mean_fc, mapping = ggplot2::aes( x = doy, y = avg_pred ), color = "red" ) + ggplot2::xlab(x_lab) + ggplot2::ylab(y_lab) + ggplot2::labs(caption = caption) + ggplot2::ggtitle(title) } #' Shiny forecast plotter #' #' Widget to play around with forecasting parameters. #' #' Currently, this widget doesn't allow for vectors to be passed to those #' forecasting parameters that can take vectors (`window_*`, `n_closest`). #' #' @param .data tsibble. The data. #' @param .observation symbol. The observation column of `.data`. #' @param samplers list. Any samplers you want to have to option to use. #' @param covariate_forecasts optional tsibble. #' Simulated sample paths of covariates. #' @param title optional string. Plot title. #' #' @examples #' data = append_lead(hotdeckts::SUGG_temp, observation) #' #shiny_visualize_forecast(data, date, observation) #' #' #' @export shiny_visualize_forecast <- function(.data, .observation, samplers = list(lead = sample_lead(), diff = sample_diff()), covariate_forecasts = NULL, title = ggplot2::waiver()) { if (!requireNamespace("shiny", quietly = TRUE)) { stop( "Package \"shiny\" version (>= 1.8.1) must be installed to use this function.", call. = FALSE ) } ui <- shiny::fluidPage( shiny::titlePanel("Widget to play around with forecasting parameters."), shiny::sidebarLayout( sidebarPanel = shiny::sidebarPanel( shiny::selectInput(inputId = "sampler", label = "sampler", choices = names(samplers), selected = names(samplers)[[1]]), shiny::numericInput(inputId = "times", label = "times", min = 1, max = 1000, value = 5, step = 1), shiny::numericInput(inputId = "h", label = "h", min = 1, max = 1000, value = 30, step = 1), shiny::numericInput(inputId = "window_back", label = "window_back", min = 1, max = 1000, value = 20, step = 1), shiny::numericInput(inputId = "window_fwd", label = "window_fwd", min = 1, max = 1000, value = 20, step = 1), shiny::numericInput(inputId = "n_closest", label = "n_closest", min = 1, max = 1000, value = 5, step = 1), shiny::selectInput(inputId = "fc_geom_type", label = "Forecast paths display type", choices = c("line", "point"), selected = "line",), shiny::actionButton(inputId = "calculate", label = "Calculate", disabled = TRUE), shiny::actionButton(inputId = "recalculate", label = "Recalculate") ), mainPanel = shiny::mainPanel( shiny::plotOutput( outputId = "forecastPlot", height = "450px", ) ) ) ) server <- function(input, output, session) { counter = shiny::reactiveVal(value = 0, label = "counter") # for caching safe = shiny::reactiveVal(value = TRUE, label = "safe") geom_trigger = shiny::reactiveVal(value = 0, label = "geom_trigger") # If you change a param: # - reset counter # - make calculate enabled, recalculate disabled # - no longer "safe" shiny::observe({ counter(0) # switch disabled shiny::updateActionButton(inputId = "calculate", disabled = FALSE) shiny::updateActionButton(inputId = "recalculate", disabled = TRUE) # no longer safe; would mis-cache if `fc_geom_type` were changed safe(FALSE) }) %>% shiny::bindEvent(input$sampler, input$times, input$h, input$window_back, input$window_fwd, input$n_closest, ignoreInit = TRUE) # If you click "recalculate", increment the counter shiny::observe({ new_val = counter() + 1 counter(new_val) # triggers this reactive, `counter` }) %>% shiny::bindEvent(input$recalculate) # If you click "calculate": # - make calculate disabled # - make recalculate enabled # - make safe == TRUE shiny::observe({ shiny::updateActionButton(inputId = "calculate", disabled = TRUE) shiny::updateActionButton(inputId = "recalculate", disabled = FALSE) safe(TRUE) }) %>% shiny::bindEvent(input$calculate) # Only trigger renderer if safe shiny::observe({ if (isTRUE(safe())) { new_val = geom_trigger() + 1 geom_trigger(new_val) } }) %>% shiny::bindEvent(input$fc_geom_type) forecast = shiny::reactive({ hot_deck_forecast(.data, .observation = {{ .observation }}, times = input$times, h = input$h, window_back = input$window_back, window_fwd = input$window_fwd, n_closest = input$n_closest, sampler = samplers[[input$sampler]], covariate_forecasts = covariate_forecasts) }) %>% shiny::bindCache(names(.data), dim(.data), input$times, input$h, input$window_back, input$window_fwd, input$n_closest, input$sampler, covariate_forecasts, counter()) %>% shiny::bindEvent(input$calculate, input$recalculate) output$forecastPlot <- shiny::renderPlot({ fc = forecast() plot_forecast(forecast = fc, historical_data = .data, observation_col_name = rlang::as_name(rlang::ensym(.observation)), forecasts_geom = input$fc_geom_type, title = title, filter_past_forecasts = FALSE) }) %>% shiny::bindCache(names(.data), dim(.data), input$times, input$h, input$window_back, input$window_fwd, input$n_closest, input$sampler, covariate_forecasts, input$fc_geom_type, counter()) %>% shiny::bindEvent(input$calculate, input$recalculate, geom_trigger()) } shiny::shinyApp(ui = ui, server = server) } #' Plot CRPSes of CV #' #' Plot the CRPSes of cross validation output. #' #' @param arg_list list. The `$arg_list` element in grid search output. #' @param cv_crps_out The output of [calc_cv_crps()] applied to the relevant #' grid search output's element. #' @param ymax optional numeric. The plots' y max. plot_cv_crps <- function(arg_list, cv_crps_out, ymax = NULL) { plt = cv_crps_out %>% ggplot2::ggplot() + ggplot2::geom_line( mapping = ggplot2::aes(x = h, y = score, color = as.factor(k)) ) + ggplot2::ggtitle(paste("wf", sum(arg_list$window_fwd), "wb", sum(arg_list$window_back), "nc", arg_list$n_closest, "sa_name", arg_list$sa_name)) + ggplot2::guides(color=ggplot2::guide_legend(title="k")) + ggplot2::ylab("CRPS") plt = if (is.null(ymax)) plt else { plt + ggplot2::ylim(0, ymax) } show(plt) } #' Plot CRPSes of grid search #' #' Plot the CRPSes of grid search output along h. #' #' The title of the plot is the various parameter values, where #' - "wf" = window_forward #' - "wb" = window_back #' - "nc" = n_closest #' - "sa_name" = sa_name #' For the first wf, wb, and nc, if you provided a vector, then the #' sum of that vector is used as the value. #' #' @param grid_out output from [grid_search_hot_deck_cv()]. #' @param observation_col_name string. The observation column name from your data. #' @param ymax optional numeric. The plots' y max. #' #' @examples #' grid = build_grid( #' h = 2, #' n_closest = c(5, 10), #' # even if you only use a single `build_window_args()`, wrap in `list()` #' window_args = list(build_window_args(20)), #' # also need to wrap in list #' sampler_args = list( #' build_sampler_args(sa_name = "nxt", #' sampler = sample_lead(), # remember to call! #' appender = append_lead) #' ) #' ) #' out = grid_search_hot_deck_cv(hotdeckts::SUGG_temp, #' .observation = observation, #' grid = grid) #' plot_grid_search_crps(out, "observation", 5) #' #' @export plot_grid_search_crps <- function(grid_out, observation_col_name = "observation", ymax = NULL) { gs_crps = grid_out %>% purrr::map(\(x) c(x, list(crps = calc_cv_crps(x$cv_out, rlang::as_name(rlang::ensym(observation_col_name)))))) gs_crps %>% purrr::walk(\(x) plot_cv_crps(x$arg_list, x$crps, ymax = ymax)) } #' Plot CV forecasts #' #' Plot the k forecasts for a CV. #' #' @param data tsibble. The data. #' @param arg_list list. The `$arg_list` element in grid search output. #' @param cv_out list. The `$cv_out` element in grid search output. #' @inheritParams plot_grid_search_forecasts plot_cv_forecasts = function(data, arg_list, cv_out, observation_col_name, window_back, window_fwd, forecasts_geom) { datetime_col_name = tsibble::index_var(data) plts = list() k_vals = cv_out$forecasts %>% dplyr::distinct(k) %>% dplyr::pull() for (k_val in k_vals) { k_fc = cv_out$forecasts %>% dplyr::filter(k == .env$k_val) mindt = k_fc %>% dplyr::select(datetime) %>% dplyr::slice_min(order_by = datetime) %>% dplyr::first() %>% dplyr::pull() - window_back maxdt = k_fc %>% dplyr::select(datetime) %>% dplyr::slice_max(order_by = datetime) %>% dplyr::first() %>% dplyr::pull() + window_fwd data_part = data %>% tsibble::filter_index(as.character(mindt) ~ as.character(maxdt)) td_min_t = data %>% dplyr::pull(observation) %>% min() td_max_t = data %>% dplyr::pull(observation) %>% max() # forecasts geom types fcs_as_lines = ggplot2::geom_line( data = k_fc, mapping = ggplot2::aes( x = datetime, y = forecast, color = as.factor(simulation_num) ), show.legend = FALSE, linewidth = 0.25 ) fcs_as_points = ggplot2::geom_point( data = k_fc, mapping = ggplot2::aes( x = datetime, y = forecast, color = as.factor(simulation_num) ), show.legend = FALSE, alpha = 0.3, size = 0.25 ) fc_geom = if (forecasts_geom == "line") fcs_as_lines else fcs_as_points plt = ggplot2::ggplot() + fc_geom + ggplot2::geom_line( data = data_part, mapping = ggplot2::aes( x = .data[[datetime_col_name]], y = .data[[observation_col_name]] ) ) + ggplot2::ggtitle(paste("k =", k_val, "wf", sum(arg_list$window_fwd), "wb", sum(arg_list$window_back), "nc", sum(arg_list$n_closest), "sa_name", arg_list$sa_name)) plts[[k_val]] = plt } plts } #' Plot grid search forecasts #' #' Plot the forecasts produced by [grid_search_hot_deck_cv()]. #' #' Using a `forecasts_geom` of "line" is more useful for less zig-zaggy #' forecasts. This generally means small values of `n_closest`. Using "point" #' is good for zig-zaggy forecasts, because in these cases, "line" yeilds a #' spiky blob. #' #' @param grid_out output from [grid_search_hot_deck_cv()]. #' @param .data tsibble. Your data. #' @param observation_col_name string. The observation column name. #' @param window_back positive integer. How many days back to include #' of the .data. #' @param window_fwd positive integer. How many days forward to include #' of the .data. #' @param forecasts_geom string. The geom to use for the forecasts on the ggplot #' #' @examples #' grid = build_grid( #' h = 2, #' n_closest = c(5, 10), #' # even if you only use a single `build_window_args()`, wrap in `list()` #' window_args = list(build_window_args(20)), #' # also need to wrap in list #' sampler_args = list( #' build_sampler_args(sa_name = "nxt", #' sampler = sample_lead(), # remember to call! #' appender = append_lead) #' ) #' ) #' out = grid_search_hot_deck_cv(hotdeckts::SUGG_temp, #' .observation = observation, #' grid = grid) #' suppressWarnings(plot_grid_search_forecasts(out, hotdeckts::SUGG_temp)) #' #' @export plot_grid_search_forecasts <- function(grid_out, .data, observation_col_name = "observation", window_back = 120, window_fwd = 120, forecasts_geom = c("line", "point")) { forecasts_geom = match.arg(forecasts_geom) gs_crps = grid_out %>% purrr::map(\(x) c(x, list(crps = calc_cv_crps(x$cv_out, rlang::as_name(rlang::ensym(observation_col_name)))))) gs_crps %>% purrr::map(\(x) plot_cv_forecasts(.data, x$arg_list, x$cv_out, observation_col_name = observation_col_name, window_back = window_back, window_fwd = window_fwd, forecasts_geom = forecasts_geom)) %>% purrr::pmap(\(...) rlang::list2(...)) %>% purrr::flatten() %>% purrr::walk(\(plt) show(plt)) }
import { Formik, Field, ErrorMessage, FormikHelpers } from 'formik'; import TextField from '@mui/material/TextField'; import Box from '@mui/material/Box'; import Typography from '@mui/material/Typography'; import Container from '@mui/material/Container'; import LockIcon from '../../assets/icons/lock-icon.component'; import { InputAdornment, Paper, useTheme, Button, Fade } from '@mui/material'; import UserIcon from '../../assets/icons/user-icon.component'; import { login as loginReducer } from '../../redux/user/auth/auth-slice'; import { loginValidationSchema } from '../../schemas'; import { useNavigate } from 'react-router-dom'; import EyeIcon from '../../assets/icons/eye-icon.component'; import { useEffect, useState } from 'react'; import { useDispatch } from 'react-redux'; import { useLoginMutation } from '../../redux/user/auth/authApi'; export default function Login() { useEffect(() => { document.title = "Login Page"; }, []); const navigate = useNavigate(); const initialValues = { username: '', password: '' }; const [loginMutation, { isLoading }] = useLoginMutation(); const dispatch = useDispatch(); const [displayPassword, setDisplayPassword] = useState(false); const theme = useTheme(); const handleLogin = async ( values: { username: string; password: string; }, formikProps: FormikHelpers<typeof initialValues> ) => { try { const response = await loginMutation(values).unwrap(); const [, tokenPayloadEncoded] = response.authentication.split('.'); const tokenPayload = JSON.parse(atob(tokenPayloadEncoded)); dispatch(loginReducer({ user:tokenPayload, token: response.authentication })); if (response.userType === 'Admin') { navigate('/admin/cities'); } else if (response.userType === 'User') { navigate('/home'); } } catch (error: any) { console.error('Login failed:', error); if (error?.response?.status === 400) { formikProps.setErrors({ password: 'Invalid username or password' }); } else if (error?.response?.status === 401) { formikProps.setErrors({ password: 'Unauthorized' }); } else { formikProps.setErrors({ password: 'Something went wrong' }); } } } function handlePasswordDispaly(): void { setDisplayPassword(!displayPassword); } return <Fade in={true} timeout={1000}> <Paper elevation={0} sx={{ height: '100vh', display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}> <Container component="main" maxWidth="sm" sx={{ width: '100vw' }}> <Box sx={{ display: 'flex', flexDirection: 'column' }}> <Box> <Typography color="primary.main" component="span" variant="h5" sx={{ fontWeight: 'bold' }}> SIGN IN{' '} </Typography> <Typography component="span" variant="h5" color="primary.light" sx={{ fontWeight: 'bold' }}> NOW! </Typography> </Box> <Formik initialValues={initialValues} validationSchema={loginValidationSchema} onSubmit={handleLogin} > {(formikProps) => ( <form onSubmit={formikProps.handleSubmit} noValidate> <Field as={TextField} sx={{ marginBlock: 1 }} type="text" placeholder="Username" name="username" fullWidth autoFocus autoComplete="username" InputProps={{ startAdornment: ( <InputAdornment position="start"> <UserIcon color="#999" /> </InputAdornment> ) }} data-testid="username-field" /> <ErrorMessage name="username" component="div" > {msg => <div style={{ color: theme.palette.error.dark }}>{msg}</div>} </ErrorMessage> <Field as={TextField} sx={{ marginBlock: 1 }} type={displayPassword ? "text" : "password"} placeholder="Password" name="password" fullWidth data-testid= "password-field" autoComplete="current-password" inputProps={{ datatestid : "password-field" }} InputProps={{ startAdornment: ( <InputAdornment position="start"> <LockIcon color="#999" /> </InputAdornment> ), endAdornment: ( <InputAdornment position="end" onClick={handlePasswordDispaly} sx={{ cursor: 'pointer' }} data-testid="password-toggle-button"> <EyeIcon /> </InputAdornment> ), }} /> <ErrorMessage name="password" component="div" > {msg => <div style={{ color: theme.palette.error.dark }}>{msg}</div>} </ErrorMessage> <Button type="submit" fullWidth variant="outlined" sx={{ mt: 3, fontWeight: 'bold', height: '40px', fontSize: '1.1rem' }} data-testid="login-button" > { formikProps.isSubmitting || isLoading ? 'Loading...' : 'Sign In' } </Button> </form> )} </Formik> </Box> </Container> </Paper> </Fade> ; }
local UITabMenu = Object:extend() function UITabMenu:new(tabs) self.x, self.y = 0, 0 self.curTab = 1 self.font = Paths.font("assets/fonts/vcr.ttf", 12) self.width = 300 self.height = 400 self.tabHeight = 20 self.tabs = tabs end function UITabMenu:resize(w, h) self.width = w self.height = h end function UITabMenu:update(dt) local x, y if love.system.getOS() == "Windows" or love.system.getOS() == "Linux" or love.system.getOS() == "OS X" then x, y = push.toGame(love.mouse.getX(), love.mouse.getY()) else -- get touch position x, y = push.toGame(love.touch.getPosition(1)) end for i, tab in ipairs(self.tabs) do local tabX = self.x + (i-1) * ((self.width/#self.tabs) + 1) local tabY = self.y + 2 if x >= tabX and x <= tabX + (self.width/#self.tabs) and y >= tabY and y <= tabY + self.tabHeight then if love.mouse.isDown(1) or next(love.touch.getTouches()) ~= nil then self.curTab = i end end end end function UITabMenu:draw() love.graphics.push() for i, tab in ipairs(self.tabs) do local x = self.x + (i-1) * ((self.width/#self.tabs) + 1) local y = self.y + 2 love.graphics.setColor(i == self.curTab and {0.7, 0.7, 0.7, 1} or {0.45, 0.45, 0.45, 1}) love.graphics.rectangle("fill", x, y, (self.width/#self.tabs), self.tabHeight) love.graphics.setColor(1, 1, 1, 1) love.graphics.setFont(self.font) local textWidth = self.font:getWidth(tab.label) local textHeight = self.font:getHeight(tab.label) love.graphics.print(tab.label, x + ((self.width/#self.tabs) - textWidth) / 2, y + (self.tabHeight - textHeight) / 2) end love.graphics.setColor(0.7, 0.7, 0.7, 1) love.graphics.rectangle("fill", self.x, self.y + self.tabHeight, self.width + (#self.tabs-1), self.height, 4, 4) love.graphics.pop() end return UITabMenu
//modo oscuro let toggle = document.getElementById('toggle'); let label_toggle = document.getElementById('label_toggle'); toggle.addEventListener('change', (event)=>{ let checked=event.target.checked; document.body.classList.toggle('dark'); if(checked==true){ label_toggle.innerHTML= '<i class="gg-sun"></i>'; label_toggle.style.color = "#85C1E9"; } else{ label_toggle.innerHTML= '<i class="gg-moon"></i>'; label_toggle.style.color = "rebeccapurple"; } }); // ----- seleccion de elemento ---- // const encriptar = document.querySelector(".Encriptar"); const textoEncriptado = document.querySelector("#texto"); const aviso = document.querySelector(".texto-aviso"); const respuesta = document.querySelector("#txt-enviado"); const copiar = document.querySelector(".Copiar"); const desencriptar = document.querySelector(".Desencriptar"); // ----- boton de encriptar ---- // encriptar.addEventListener("click", e=>{ e.preventDefault(); let texto = textoEncriptado.value; let txt = texto.normalize("NFD").replace(/[$\.¿\?~!\¡@#%^&*()_|}\{[\]>\<:"`;,\u0300-\u036f']/g, ""); if(texto == ""){ aviso.style.background = "#0A3871"; aviso.style.color = "#FFFF"; aviso.style.fontWeight = "800"; aviso.textContent = "¡El campo no debe estar vacio!"; setTimeout(()=>{ aviso.removeAttribute("style"); },1500); } else if(texto !== txt){ aviso.style.background = "#0A3871"; aviso.style.color = "#FFFF"; aviso.style.fontWeight = "800"; aviso.textContent = "¡No debe terner acentos y caracteres especiales!"; setTimeout(()=>{ aviso.removeAttribute("style"); },1500); } else if(texto !== texto.toLowerCase()){ aviso.style.background = "#0A3871"; aviso.style.color = "#FFFF"; aviso.style.fontWeight = "800"; aviso.textContent = "¡El texto debe ser todo en minuscula!"; setTimeout(()=>{ aviso.removeAttribute("style"); },1500); } else{ texto = texto.replace(/e/mg, "enter"); texto = texto.replace(/i/mg, "imes"); texto = texto.replace(/a/mg, "ai"); texto = texto.replace(/o/mg, "ober"); texto = texto.replace(/u/mg, "ufat"); respuesta.innerHTML = texto; } }) // ---- boton de Desencriptar ----// desencriptar.addEventListener("click", e=>{ e.preventDefault(); let texto = textoEncriptado.value; let txt = texto.normalize("NFD").replace(/[$\.¿\?~!\¡@#%^&*()_|}\{[\]>\<:"`;,\u0300-\u036f']/g, ""); if(texto == ""){ aviso.style.background = "#0A3871"; aviso.style.color = "#FFFF"; aviso.style.fontWeight = "800"; aviso.textContent = "¡El campo no debe estar vacio!"; setTimeout(()=>{ aviso.removeAttribute("style"); },1500); } else if(texto !== txt){ aviso.style.background = "#0A3871"; aviso.style.color = "#FFFF"; aviso.style.fontWeight = "800"; aviso.textContent = "¡No debe terner acentos y caracteres especiales!"; setTimeout(()=>{ aviso.removeAttribute("style"); },1500); } else if(texto !== texto.toLowerCase()){ aviso.style.background = "#0A3871"; aviso.style.color = "#FFFF"; aviso.style.fontWeight = "800"; aviso.textContent = "¡El texto debe ser todo en minuscula!"; setTimeout(()=>{ aviso.removeAttribute("style"); },1500); } else{ texto = texto.replace(/enter/mg, "e"); texto = texto.replace(/imes/mg, "i"); texto = texto.replace(/ai/mg, "a"); texto = texto.replace(/ober/mg, "o"); texto = texto.replace(/ufat/mg, "u"); respuesta.innerHTML = texto; copiar.style.Visibility = "inherit"; } }) // ---- boton de Copiar ----// copiar.addEventListener("click", e=>{ e.preventDefault(); let Copiar = respuesta; Copiar.select(); document.execCommand("copy"); })
package offer.special; /** * 剑指 Offer II 098. 路径的数目 * * 一个机器人位于一个 m x n网格的左上角 (起始点在下图中标记为 “Start” )。 * 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish” )。 * 问总共有多少条不同的路径 * * 1 <= m, n <= 100 * 题目数据保证答案小于等于 2 * 10e9 */ public class O098 { public static void main(String[] args) { System.out.println(uniquePaths(3,7)); } private static int uniquePaths(int m, int n) { int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) { dp[i][0] = 1; } for (int i = 0; i < n; i++) { dp[0][i] = 1; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m-1][n-1]; } }
/** * The code defines a public class called "Card" in the package "com.example.memorygame". * The class has two private instance variables: "suit" and "faceName". * The class has a constructor that takes in a suit and faceName as parameters and sets them using the corresponding setter methods. * The class has getter and setter methods for the suit and faceName variables. * The class has a method called "getValidSuits" that returns a list of valid suits. * The class has a method called "getValidFaceNames" that returns a list of valid face names. * The class has a toString method that returns a string representation of the card. * The class has a getValue method that returns the numerical value of the card. * The class has a method called "getImage" that returns an image that represents the card. * The class has a method called "getBackOfCardImage" that returns an image of the back of the card. */ package com.example.memorygame; import javafx.scene.image.Image; import java.util.Arrays; import java.util.List; public class Card { private String suit; private String faceName; public Card(String suit, String faceName) { setSuit(suit); setFaceName(faceName); } public String getSuit() { return suit; } public static List<String> getValidSuits() { return Arrays.asList("hearts","diamonds","clubs","spades"); } /** * valid suits are "hearts","diamonds","clubs","spades" */ public void setSuit(String suit) { suit = suit.toLowerCase(); if (getValidSuits().contains(suit)) this.suit = suit; else throw new IllegalArgumentException(suit + " invalid, must be one of "+getValidSuits()); } public String getFaceName() { return faceName; } public static List<String> getValidFaceNames() { return Arrays.asList("2","3","4","5","6","7","8","9","10","jack","queen","king","ace"); } public void setFaceName(String faceName) { faceName = faceName.toLowerCase(); if (getValidFaceNames().contains(faceName)) this.faceName = faceName; else throw new IllegalArgumentException(faceName + " is invalid, must be one of "+getFaceName()); } public String toString() { return faceName + " of " + suit; } public int getValue() { return getValidFaceNames().indexOf(faceName) + 2; } /** * This method will return an Image that represents the Card */ public Image getImage() { String pathName = "images/"+faceName+"_of_"+suit+".png"; return new Image(Card.class.getResourceAsStream(pathName)); } public Image getBackOfCardImage() { return new Image(Card.class.getResourceAsStream("images/back_of_card.png")); } }
import { createSlice } from '@reduxjs/toolkit' import axios from 'axios' export const photoSlice = createSlice({ name: 'photo', initialState: { photos: [], isAdding: false, photoErrorMsg: null, isLoading: false }, reducers: { photoLoaded: (state, action) => { state.photos = action.payload state.isLoading = false }, photoLoadError: (state) => { state.photoErrorMsg = "Something went wrong" state.isLoading = false }, photoAddSuccess: (state, action) => { state.value += action.payload }, photoLoading: (state) => { state.isLoading = true }, }, }) // Action creators are generated for each case reducer function export const { photoLoaded, photoLoadError, photoAddSuccess, photoLoading } = photoSlice.actions export const selectPhotoErrorMsg = (state) => state.photo.photoErrorMsg export const selectPhotos = (state) => state.photo.photos export const selectPhotoLoading = (state) => state.photo.isLoading export const loadPhotos = (category, photoId) => async (dispatch) => { dispatch(photoLoading()) let url = null if (category !== null) url = "https://photo-gallery-7dab5-default-rtdb.firebaseio.com/photos.json?" + 'orderBy="category"&equalTo="' + category + '"' else if (photoId !== null) url = "https://photo-gallery-7dab5-default-rtdb.firebaseio.com/photos/" + photoId + ".json?" else url = "https://photo-gallery-7dab5-default-rtdb.firebaseio.com/photos.json" await axios.get(url) .then(response => dispatch(photoLoaded(Object.entries(response.data)))) .catch(err => dispatch(photoLoadError(err))) } export default photoSlice.reducer
/*************************************************************************** * Copyright (C) 2007 by Jablonkai Tamás * * [email protected] * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "dictionarywidget.h" #include <QtCore/QTime> #include <QtWidgets/QUndoStack> #include "dictionarymanager.h" #include "searchmodel.h" class SearchCommand : public QUndoCommand { public: SearchCommand(const QString &prev, const int &prevI, const QString &s, const int &i, DictionaryWidget *w) : prevText(prev), prevIndex(prevI), text(s), index(i), widget(w) {} virtual void undo() { if (prevIndex <= 1) widget->search(prevText, prevIndex); } virtual void redo() { widget->search(text, index); } private: QString prevText; int prevIndex; QString text; int index; DictionaryWidget *widget; }; DictionaryWidget::DictionaryWidget() : prevText(""), prevIndex(100) { ui.setupUi(this); undoStack = new QUndoStack(this); filterModel = new QSortFilterProxyModel(this); filterModel->setFilterCaseSensitivity(Qt::CaseInsensitive); filterModel->setDynamicSortFilter(true); filterModel->setSortLocaleAware(true), filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); ui.treeView->setModel(filterModel); searchModel = new SearchModel(this); searchModel->setFilterCaseSensitivity(Qt::CaseInsensitive); filterModel->setSourceModel(searchModel); connect(ui.lineEdit, SIGNAL(returnPressed()), this, SLOT(slotSearch())); connect(ui.searchButton, SIGNAL(clicked()), this, SLOT(slotSearch())); connect(ui.filteringCheckBox, SIGNAL(toggled(bool)), this, SLOT(slotFiltering(bool))); connect(ui.filterComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(slotFilter())); connect(ui.filterLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(slotFilter())); connect(ui.treeView, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(slotItemActivated(const QModelIndex&))); connect(ui.backwardButton, SIGNAL(clicked()), undoStack, SLOT(undo())); connect(ui.forwardButton, SIGNAL(clicked()), undoStack, SLOT(redo())); connect(undoStack, SIGNAL(canUndoChanged(bool)), ui.backwardButton, SLOT(setEnabled(bool))); connect(undoStack, SIGNAL(canRedoChanged(bool)), ui.forwardButton, SLOT(setEnabled(bool))); ui.filterWidget->setVisible(false); } void DictionaryWidget::search(const QString &s, const int &i) { ui.lineEdit->setText(s); ui.comboBox->setCurrentIndex(i); searchModel->setFilterKeyColumn(i); searchModel->setFilterRegExp(QRegExp(s, Qt::CaseInsensitive, QRegExp::Wildcard)); n = searchModel->rowCount();//d.size(); } void DictionaryWidget::updateWidget() { if (this->isVisible()) updateDictionary(); } void DictionaryWidget::showEvent(QShowEvent*) { updateDictionary(); } void DictionaryWidget::slotSearch() { if (!DictionaryManager::instance()->activeDictionary()) return; QTime time; time.start(); QString text = ui.lineEdit->text(); int index = ui.comboBox->currentIndex(); undoStack->push(new SearchCommand(prevText, prevIndex, text, index, this)); prevText = text; prevIndex = index; emit statusBarMessage(tr("The number of results: %1 (Within %2 sec)").arg(n).arg(time.elapsed() / 1000.0f), 0); } void DictionaryWidget::slotFiltering(bool b) { b ? slotFilter() : filterModel->setFilterRegExp(0); } void DictionaryWidget::slotFilter() { filterModel->setFilterKeyColumn(ui.filterComboBox->currentIndex()); filterModel->setFilterRegExp(QRegExp(ui.filterLineEdit->text(), Qt::CaseInsensitive, QRegExp::Wildcard)); } void DictionaryWidget::slotItemActivated(const QModelIndex &index) { ui.comboBox->setCurrentIndex(index.column()); ui.lineEdit->setText(index.data().toString()); slotSearch(); ui.filterLineEdit->clear(); slotFilter(); } void DictionaryWidget::updateDictionary() { undoStack->clear(); prevIndex = 100; ui.comboBox->clear(); ui.lineEdit->clear(); ui.filterComboBox->clear(); ui.filterLineEdit->clear(); searchModel->setSourceModel(0); DictionaryModel *dict = DictionaryManager::instance()->activeDictionary(); if (!dict) return; searchModel->setSourceModel(dict); ui.comboBox->addItem(QString("%1 -> %2").arg(dict->oLang()).arg(dict->tLang())); ui.comboBox->addItem(QString("%1 -> %2").arg(dict->tLang()).arg(dict->oLang())); ui.filterComboBox->addItem(QString("%1").arg(dict->oLang())); ui.filterComboBox->addItem(QString("%1").arg(dict->tLang())); }
import React from "react"; import { Fragment, useState } from "react"; import { Dialog, Transition } from "@headlessui/react"; import { Formik, Form, Field, ErrorMessage, useField } from "formik"; import * as Yup from "yup"; import { GetRate, HandleCreateRate, HandleEditRate } from "@/redux/action/rate"; import { CloseLoader, OpenLoader } from "@/redux/action/loader"; import { toast } from "react-toastify"; import { useDispatch } from "react-redux"; const AddRate = ({ open, setOpen, editrate }) => { const dispatch = useDispatch(); const initialValues = { date: editrate ? editrate.date : "", msRate: editrate ? editrate.msRate : "", hsdRate: editrate ? editrate.hsdRate : "", }; const validationSchema = Yup.object({ date: Yup.string().required("Date is required"), msRate: Yup.string().required("MS Rate is required"), hsdRate: Yup.string().required("HSD Rate is required"), }); const HandleData = async (values) => { try { dispatch(OpenLoader(true)); await dispatch( editrate?._id ? HandleEditRate(editrate._id, values) : HandleCreateRate(values) ) .then(async (result) => { if (result?.payload?.status === 201 || 200) { toast(result?.payload?.data.message, { hideProgressBar: true, autoClose: 3000, type: "success", }); await dispatch(GetRate(1)); setOpen(false); dispatch(CloseLoader(false)); } else { dispatch(CloseLoader(false)); toast(result?.payload?.data.message, { hideProgressBar: true, autoClose: 3000, type: "error", }); } }) .catch((err) => { dispatch(CloseLoader(false)); console.log(err, "Edit ERROR"); }); } catch (err) { dispatch(CloseLoader(false)); console.log(err, "Edit ERROR"); } }; return ( <div> <Transition.Root show={open} as={Fragment}> <Dialog as="div" className="relative z-[999]" onClose={setOpen}> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-200" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black dark:bg-gray-500/[75%] bg-opacity-75 transition-opacity" /> </Transition.Child> <div className="fixed inset-0 z-10 overflow-y-auto"> <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0"> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" enterTo="opacity-100 translate-y-0 sm:scale-100" leave="ease-in duration-200" leaveFrom="opacity-100 translate-y-0 sm:scale-100" leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" > <Dialog.Panel className="relative transform dark:bg-[#0c1a32] rounded-lg bg-white text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-2xl "> <Dialog.Title as="h3" className="text-base font-semibold border-b px-4 py-4 leading-6 dark:text-white text-gray-900" > Add Today Rate </Dialog.Title> <div className="px-4 py-4 space-y-3"> <Formik initialValues={initialValues} validationSchema={validationSchema} enableReinitialize={true} onSubmit={(values) => HandleData(values)} > {(formik) => { return ( <Form> <div className="flex mb-6 items-center grid grid-cols-3"> <span className="col-span-1 dark:text-gray-100 text-[14px] text-gray-700"> Date </span> <div className="col-span-2"> <Field id="date" name="date" type="Date" className="block w-full text-[14px] py-1.5 px-6 text-[#6e6e6e] rounded-md border border-[#f0f1f5] focus:border-orange transition duration-300 focus:outline-none focus:ring-0 shadow-none rounded-md bg-white dark:text-gray-300 dark:bg-[#20304c]" /> <div style={{ color: "red" }}> <ErrorMessage name="date" component="span" className="error text-[13px] font-medium leanding-[20px] text-red500" /> </div> </div> </div> <div className="flex mb-6 items-center grid grid-cols-3"> <span className="col-span-1 dark:text-gray-100 text-[14px] text-gray-700"> MS Rate </span> <div className="col-span-2"> <Field id="msRate" name="msRate" type="number" placeholder="Enter MS Rate" className="block w-full text-[14px] py-1.5 px-6 text-[#6e6e6e] rounded-md border border-[#f0f1f5] focus:border-orange transition duration-300 focus:outline-none focus:ring-0 shadow-none rounded-md bg-white dark:text-gray-300 dark:bg-[#20304c]" /> <div style={{ color: "red" }}> <ErrorMessage name="msRate" component="span" className="error text-[13px] font-medium leanding-[20px] text-red500" /> </div> </div> </div> <div className="flex mb-6 items-center grid grid-cols-3"> <span className="col-span-1 dark:text-gray-100 text-[14px] text-gray-700"> HSD Rate </span> <div className="col-span-2"> <Field id="hsdRate" name="hsdRate" type="number" placeholder="Enter HSD Rate" className="block w-full text-[14px] py-1.5 px-6 text-[#6e6e6e] rounded-md border border-[#f0f1f5] focus:border-orange transition duration-300 focus:outline-none focus:ring-0 shadow-none rounded-md bg-white dark:text-gray-300 dark:bg-[#20304c]" /> <div style={{ color: "red" }}> <ErrorMessage name="hsdRate" component="span" className="error text-[13px] font-medium leanding-[20px] text-red500" /> </div> </div> </div> <div className="flex justify-end"> <button type="submit" className="bg-orange text-white px-4 py-2.5 rounded" > Save </button> </div> </Form> ); }} </Formik> </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition.Root> </div> ); }; export default AddRate;
import VacancyService from "../services/vacancy.js"; class Vacancy { async getByUser(req, res) { try { const userId = req.user._id; const vacancies = await VacancyService.getByFitler({ creator: userId, }); res.json(vacancies); } catch (e) { res.status(e.status).json(e.message); console.log(e); } } async getByFitler(req, res) { try { const filter = req.body || {}; const user = req.user const vacancies = await VacancyService.getByFitler(filter, user); res.json(vacancies); } catch (e) { res.status(e.status).json(e.message); console.log(e); } } async getById(req, res) { try { const vacancyId = req.params.id; const candidate = req.user const vacancy = await VacancyService.getById(vacancyId, candidate); res.json(vacancy); } catch (e) { res.status(e.status).json(e.message); console.log(e); } } async create(req, res) { try { const { name, detailedDescription, salaryRange = null, specialty, experience, shortDescription, } = req.body; const creator = req.user._id; const newVacancy = await VacancyService.create({ name, salaryRange, creator, specialty, experience, shortDescription, detailedDescription, }); res.json(newVacancy); } catch (e) { res.status(e.status).json(e.message); console.log(e); } } async update(req, res) { try { const payload = req.body; const updated = await VacancyService.update(payload); res.json(updated); } catch (e) { res.status(e.status).json(e.message); console.log(e); } } async apply(req, res) { try { const cv = req.file; const { coverLetter = "" } = req.body const { vacancyId } = req.params; const { user } = req; await VacancyService.apply(vacancyId, user._id, cv, coverLetter); res.sendStatus(200); } catch (e) { res.status(e.status).json(e.message); console.log(e); } } async searchByKeyword(req, res) { try { const searchTerm = req.params.searchTerm; const vacancies = await VacancyService.search({ $or: [ { name: { $regex: searchTerm, $options: 'i' } }, { shortDescription: { $regex: searchTerm, $options: 'i' } }, { detailedDescription: { $regex: searchTerm, $options: 'i' } } ] }); if (vacancies.length === 0) { res.status(404).json({ error: 'No vacancies found' }); return; } res.json(vacancies); } catch (e) { console.log(e); res.status(500).json({ error: 'Internal server error' }); } } } export default new Vacancy();
package io.realworld.api import io.realworld.api.models.entities.* import io.realworld.api.models.requests.AuthRequest import io.realworld.api.models.requests.UpsertArticleRequest import io.realworld.api.models.requests.UserUpdateRequest import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Test class MediumClientTest { private val mediumClient=MediumClient @Test fun `get articles`(){ runBlocking { val article=mediumClient.mediumAPI.getArticles() assertNotNull(article.body()?.articles) } } @Test fun `register and login`(){ val authRequest=AuthRequest( AuthData("[email protected]", "asdf1234$#@!") ) runBlocking{ val userAuth=mediumClient.mediumAPI.loginUser(authRequest) val token =userAuth.body()?.user?.token mediumClient.token=token // updating User val updateRequest =UserUpdateRequest( UserUpdateData(null,"[email protected]",null,"Karan1628","asdf1234") ) val updatedUser=mediumClient.mediumAuthAPI.updateUser(updateRequest) //Getting user Profile of Someone val getProfile=mediumClient.mediumAuthAPI.getProfile( "Karate22" ) //Follow and Unfollow user val followUser=mediumClient.mediumAuthAPI.followUser("Karate22") //Get Feed Article val feedArticles=mediumClient.mediumAuthAPI.getArticleFeed() //Create and Update article val articleRequest=UpsertArticleRequest( ArticleData(title = "Article on Conduit ", description= "Test Article", body = """ This is a testing article, Which means it is created while testing phase """.trimIndent() ,tagList = listOf("test", "dragon")) ) val comments=mediumClient.mediumAuthAPI.deleteComment("cass-7ydkyl",86170) val favoriteArticle=mediumClient.mediumAuthAPI.removeFavorite("bla-bla-2-dz465e") assertNotNull(favoriteArticle.body()?.article) assertNotNull(feedArticles.body()?.articles) assertNotNull(followUser.body()?.profile) assertNotNull(updatedUser.body()?.user) assertEquals("Karan1628",updatedUser.body()?.user?.username) assertNotNull(getProfile.body()?.profile) } } }
import 'package:flutter/material.dart'; import 'package:audioplayers/audioplayers.dart'; void main() => runApp(App()); class App extends StatelessWidget { const App({Key? key}) : super(key: key); void playSound(int value) { final player = AudioCache(); player.play('note$value.wav'); } Expanded buildKey(int num, MaterialColor color) { return Expanded( child: TextButton( onPressed: () { playSound(num); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all(color) ), child: const Text(''), ), ); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.black, body: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ buildKey(1, Colors.red), buildKey(2, Colors.orange), buildKey(3, Colors.yellow), buildKey(4, Colors.green), buildKey(5, Colors.teal), buildKey(6, Colors.blue), buildKey(7, Colors.purple), ], ), ), ), ); } }
'use client' import React, { useState } from 'react' import Input from '../inputs/Input' import Modal from './Modal' import { FieldValues, SubmitHandler, useForm } from 'react-hook-form' import { toast } from 'react-hot-toast'; import { useRouter } from 'next/navigation' import useTaskCreationModal from '@/app/hooks/useTaskCreationModal' import axios from 'axios'; const TaskCreationModal = () => { const router = useRouter() const TaskCreationModal = useTaskCreationModal() const [isLoading, setIsLoading] = useState(false) const { register, handleSubmit, formState: { errors, }, reset, } = useForm<FieldValues>({ defaultValues: { title: '', description: '', state: 'Pending' } }); const onSubmit: SubmitHandler<FieldValues> = (data) => { setIsLoading(true); axios.post('/api/task', data) .then(() => { toast.success('Task created!'); router.refresh(); reset(); TaskCreationModal.onClose(); }) .catch(() => { toast.error('Something went wrong.'); }) .finally(() => { setIsLoading(false); }) } const bodyContet = ( <div className='p-2 flex flex-col gap-3'> <Input id='title' disabled={isLoading} errors={errors} register={register} label='Title' type='text' required /> <Input id='description' disabled={isLoading} errors={errors} register={register} label='Description' type='text' required big /> </div> ) return ( <Modal title='New Task' isOpen={TaskCreationModal.isOpen} actionLabel='Create' disabled={isLoading} body={bodyContet} onClose={TaskCreationModal.onClose} onSubmit={handleSubmit(onSubmit)} secondaryActionLabel='Cancel' secondaryAction={TaskCreationModal.onClose} /> ) } export default TaskCreationModal
// PS3-Backup-Manager // Copyright (C) 2010 - Metagames // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef COVERCACHETHREAD_H #define COVERCACHETHREAD_H #include <QObject> #include <QThread> #include <QString> #include <QStringList> #include <QDir> #include <QFile> #include <QMutex> #include <QWaitCondition> #include <QHttp> #include <QImage> #include <QUrl> #include <QBuffer> #include <QDebug> class CoverCacheThread : public QThread { Q_OBJECT public: CoverCacheThread(QString base, QString dir, QObject *parent=0) : QThread(parent), aborted(false), http(new QHttp), coverBase(base), cacheDir(dir) { http->moveToThread(parent->thread()); this->connect(this, SIGNAL(finished()), this, SLOT(threadFinished_Slot())); } void setIDList(QStringList list) { mutex.lock(); IDList.clear(); IDList = list; mutex.unlock(); } void abort() { mutex.lock(); aborted = true; mutex.unlock(); coverCachedCondition.wakeAll(); } // reimp! void run() { mutex.lock(); aborted = false; mutex.unlock(); //qDebug() << "CoverCacheThread start!"; //qDebug() << "coverBase=" << coverBase; //qDebug() << "cacheDir=" << cacheDir; foreach (QString gameID, IDList) { if (checkAborted()) { http->abort(); break; } download(gameID); } this->quit(); } signals: void finished(bool aborted); private slots: void threadFinished_Slot() { emit finished(checkAborted()); } void httpRequestFinished_Slot(int id, bool error) { if (id == httpRequestID) { if (!checkAborted()) { if (error) { //qDebug() << "failed to download" << coverID; } else { //qDebug() << "cover download OK" << coverID; QImage img; img.loadFromData(httpBytes); if (!(img.format() == QImage::Format_Invalid)) { QDir().mkpath(cacheDir); //qDebug() << "saving cover to" << cacheDir + coverID + ".PNG"; QFile file(cacheDir + coverID + ".PNG"); file.open(QIODevice::WriteOnly | QIODevice::Truncate); file.write(httpBytes); file.close(); } } } httpBuffer->close(); delete httpBuffer; coverCachedCondition.wakeAll(); } } private: bool aborted; QHttp *http; QString coverBase; QString cacheDir; QString coverID; QMutex mutex; QWaitCondition coverCachedCondition; QStringList IDList; QBuffer *httpBuffer; QByteArray httpBytes; int httpRequestID; bool checkAborted() { mutex.lock(); bool res = aborted; mutex.unlock(); return res; } void download(QString gameID) { //qDebug() << "download request! gameID=" << gameID; this->disconnect(http, SIGNAL(requestFinished(int,bool)),this, SLOT(httpRequestFinished_Slot(int,bool))); http->abort(); http->close(); http->deleteLater(); http = new QHttp; http->moveToThread(this->parent()->thread()); this->connect(http, SIGNAL(requestFinished(int,bool)),this, SLOT(httpRequestFinished_Slot(int,bool))); coverID = gameID; // check if cover is in cache bool isCoverCached = isCoverInCache(gameID); //qDebug() << "isCoverCached=" << isCoverCached; if (!isCoverCached) { QUrl url(coverBase + gameID + ".PNG"); // quick warn if url invalid (not abortive !!!) if (!url.isValid()) qDebug() << "Invalid url given to cover downloader!"; //qDebug() << "Downloading cover at" << url.toString(); httpBuffer = new QBuffer(&httpBytes); httpBuffer->open(QIODevice::WriteOnly); http->setHost(url.host()); httpRequestID = http->get(url.path(), httpBuffer); //qDebug() << "download req for" << url.toString() << "sent!"; coverCachedCondition.wait(&mutex); } } bool isCoverInCache(QString gameID) { return QFile::exists(cacheDir + gameID + ".PNG"); } }; #endif // COVERCACHETHREAD_H
"""Vectorizer and optimization. """ # pylint: disable=E1135,E1101 from multiprocessing import Pool from operator import itemgetter from time import time import numpy as np from sklearn import pipeline from sklearn import metrics from sklearn.preprocessing import LabelEncoder from sklearn.feature_extraction import DictVectorizer from sklearn.model_selection import GridSearchCV from sklearn.model_selection import cross_val_predict from sklearn.model_selection import train_test_split from .featurizer import Featurizer from .containers import Pipe, _chain class Vectorizer(object): """Small text mining vectorizer. The purpose of this class is to provide a small set of methods that can operate on the data provided in the Experiment class. It can load data from an iterator or .csv, and guides that data along a set of modules such as the feature extraction, tf*idf function, SVD, etc. It can be controlled through a settings dict that is provided in conf. Parameters ---------- features : list of Featurizer classes. preprocessor: Preprocessor class. parser: Parser class. """ def __init__(self, features, preprocessor=None, parser=None, n_jobs=None): """Start pipeline modules.""" self.featurizer = Featurizer(features, preprocessor, parser) self.hasher = DictVectorizer() self.encoder = LabelEncoder() self.n_jobs = n_jobs def _vectorize(self, data, func): """Send the data through all applicable steps to vectorize.""" if isinstance(data, list) and hasattr(data[0], 'source'): data = _chain(data) if self.n_jobs != 1: p = Pool(processes=self.n_jobs) D, y = zip(*p.map(self.featurizer.transform, data)) p.close() p.join() del p else: D, y = zip(*map(self.featurizer.transform, data)) # NOTE: these _can't_ be put in p.map because `fit` overwrites in iter X = getattr(self.hasher, func)(D) y = getattr(self.encoder, func)(y) if len(set(y)) != 1 else '' if len(y): return X, y else: return X def fit_transform(self, data): """Adhere to sklearn API.""" return self._vectorize(data, func='fit_transform') def transform(self, data): """Adhere to sklearn API.""" return self._vectorize(data, func='transform') class Evaluator(object): def __init__(self, **kwargs): """Set all relevant settings, run experiment. Parameters ---------- test_data : list of, or single iterator Example: [CSV("/somedir/test.csv", label=1, text=2)] This works similar to the train_data. However, when a test set is provided, the performance of the model will also be measured on this test data. Omesa will dump a classification report for you. test_size : float Example: 0.3 As opposed to a test FILE, one can also provide a test proportion, after which a certain amount of instances will be held out from the training data to test on. scoring: string detailed_train: bool cv: int proportions: int """ self.__dict__.update(kwargs) self.__dict__['cv'] = self.__dict__.get('cv', 5) self.res = {} self.scores = {} def _run_proportions(self, sets, exp): """Repeats run and proportionally increases the amount of data.""" X, Xi, y, yi = sets self.res['prop'] = {} for i in range(1, exp.batches): prop = (1 / exp.batches) * (exp.batches - i) exp.log.slice((1 - prop, )) Xp, _, yp, _ = train_test_split(X, y, train_size=prop, stratify=y) clff = self.grid_search(Xp, yp, self.scoring, exp.seed).fit(Xp, yp) tres = cross_val_predict(clff, Xp, yp, cv=5, n_jobs=-1) # FIXME: this is going to break with any other metric tscore = metrics.f1_score(yp, tres, average=self.average) score = metrics.f1_score(yi, clff.predict(Xi), average=self.average) print("\n Result: {0}".format(score)) self.res['prop'].update( {1 - prop: {'train': tscore, 'test': score}}) def best_model(self): """Choose best parameters of trained classifiers.""" # FIXME: I think this can be deprecated score_sum, highest_score = {}, 0 for score, estim in self.scores.values(): score_sum[score] = estim if score > highest_score: highest_score = score print("\n #--------- Grid Results -----------") print("\n Best scores: {0}".format( {str(dict(y.steps)['clf'].__class__.__name__): round(x, 3) for x, y in score_sum.items()})) return highest_score, score_sum[highest_score] def grid_search(self, pln, X, y, seed): """Choose a classifier based on settings.""" clfs, pipes = [], [] for pipe in pln: pipe.check(seed) if pipe.idf == 'clf': clfs.append(pipe) else: pipes.append(pipe) for i, clf in enumerate(clfs): grid = {pipe.idf + '__' + k: v for pipe in pipes for k, v in pipe.parameters.items()} grid.update({'clf__' + k: v for k, v in clf.parameters.items()}) print("\n #-------- Classifier {0} ----------".format(i + 1)) print("\n", "Clf: ", str(clf.skobj)) print("\n", "Grid: ", grid) grid = GridSearchCV( pipeline.Pipeline([(pipe.idf, pipe.skobj) for pipe in pipes] + [('clf', clf.skobj)]), scoring=self.scoring, param_grid=grid, n_jobs=-1 if not hasattr(pipe.skobj, 'n_jobs') else 1) print("\n Starting Grid Search...") grid.fit(X, y) print(" done!") self.scores[clf] = (grid.best_score_, grid.best_estimator_) score, clf = self.best_model() self.scores['best'] = score return clf def evaluate(self, exp): """Split data, fit, transfrom features, tf*idf, svd, report.""" t1 = time() exp.seed = 42 exp.nj = -1 exp.test_size = 0.3 if not hasattr(exp, 'test_size') else exp.test_size np.random.RandomState(exp.seed) # report features if hasattr(exp.pln[0], 'features'): exp.log.head(exp.pln.features, exp.name, exp.seed) # stream data to features X, y = exp.vec.fit_transform(exp.data) # if no test data, split if not hasattr(self, 'test_data'): X, Xi, y, yi = train_test_split( X, y, test_size=exp.test_size, stratify=y) else: Xi, yi = exp.vec.transform(self.test_data) av = self.average # grid search and fit best model choice exp.pln = self.grid_search(exp.pln, X, y, exp.seed) print("\n Training model...") exp.pln.fit(X, y) print(" done!") labs = exp.vec.encoder.classes_ exp.log.data('sparse', 'train', X) # if user wants to report more than best score, do another CV on train # if hasattr(self, 'detailed_train'): sco = cross_val_predict(exp.pln, X, y, cv=self.cv, n_jobs=exp.nj) self.res['train'] = exp.log.report('train', y, sco, av, labs) exp.log.data('sparse', 'test', Xi, dump=True) res = exp.pln.predict(Xi) self.res['test'] = exp.log.report('test', yi, res, av, labs) if hasattr(self, 'proportions'): self._run_proportions((X, Xi, y, yi), exp) print("\n # ------------------------------------------ \n") t2 = time() dur = round(t2 - t1, 1) self.res['dur'] = dur print("\n Experiment took {0} seconds".format(dur)) exp.store() print("\n" + '-' * 10, "\n")
// get elements const rockButton = document.getElementById("rock") const paperButton = document.getElementById('paper') const sissorsButton = document.getElementById("sissors") const replayButton = document.querySelector(".replay") const movesContainer = document.querySelector(".moves") const playerMove = document.getElementById("player-move") const computerMove = document.getElementById("computer-move") const text = document.getElementById("title") const myScore = document.getElementById("player-score") const computerScore = document.getElementById("computer-score") rockButton.addEventListener("click", ()=>game(0)) paperButton.addEventListener("click", ()=>game(1)) sissorsButton.addEventListener("click", ()=>game(2)) replayButton.addEventListener("click", ()=>toggleShowMoves()) const score={ mine:0, opponent:0 } const moveMapping = [{ value:"rock", weak:"paper" }, { value:"paper", weak:"sissors" }, { value:"sissors", weak:"rock" }] function toggleShowMoves(){ movesContainer.classList.toggle('hide') replayButton.classList.toggle('show') } function toggleShake(shake){ if(shake){ playerMove.classList.add('wait-move') computerMove.classList.add('wait-move') } else{ playerMove.classList.remove('wait-move') computerMove.classList.remove('wait-move') } } function game(move){ const moveObject = moveMapping[move] const opponentMoveIndex = Math.floor(Math.random()*3) toggleShowMoves() toggleShake(true) const opponentMoveObject = moveMapping[opponentMoveIndex] let textValue = "" if(opponentMoveObject.value===moveObject.value){ textValue="It's a draw" } // player win else if(moveObject.value === opponentMoveObject.weak){ score.mine+=1 textValue="You win" } // computer win else{ score.opponent+=1 textValue="You loose" } function result(){ toggleShake(false) playerMove.src = "assets/images/"+moveObject.value+".png" computerMove.src = "assets/images/"+opponentMoveObject.value+".png" text.innerText=textValue myScore.innerText=score.mine computerScore.innerText=score.opponent } setTimeout(result, 800) }
<audio title="02 _ 先利其器:如何高效学习eBPF?" src="https://static001.geekbang.org/resource/audio/53/88/537f61ba8a3d61e614d242b2fefe7388.mp3" controls="controls"></audio> <p>你好,我是倪朋飞。</p><p>上一讲,我们一起了解了 eBPF 的发展历程、基本原理和主要应用场景。eBPF 来源于 Linux 内核子系统 Berkeley Packet Filter (BPF),最早用于提升网络包过滤的性能。后来,随着 BPF 技术的逐步完善,它的应用范围从内核空间扩展到了用户空间,并逐步在网络、可观测以及安全等方面获得了大量的应用。</p><p>了解过这些的你,很可能遇到了我曾经有过的疑惑:作为 Linux 内核的一部分,eBPF 这么底层的技术,到底该如何学习才能更高效地掌握它?</p><p>这是初学者经常遇到的问题:在学习 eBPF 的知识和原理时,找不到正确的方法,只是照着网络上并不全面的片段文章操作,或者直接去啃内核的源码,这样往往事倍功半。甚至,还可能被海量的信息淹没,失去了持续学习的信心,“从入门到放弃” 。那么今天,我们就一起来看看,怎么才能高效且深入地学习 eBPF。</p><h2>学习这门课需要什么基础?</h2><p>首先,在学习 eBPF 之前你要明白,eBPF 是 Linux 的一部分,它所有的应用都需要在 Linux 系统中完成(虽然 Windows 也已经支持了 eBPF,但暂时不够成熟)。所以,我希望你<strong>至少熟练掌握一种 Linux 系统(比如 Ubuntu、RHEL)的基本使用方法</strong>,包括:</p><!-- [[[read_end]]] --><ul> <li>熟悉 Linux 系统常用命令的使用方法;</li> <li>熟悉 Linux 系统常用软件包的安装方法;</li> <li>了解 Linux 系统常用的网络工具和基本的网络排错方法。</li> </ul><p>因为这门课的核心在于 eBPF,所以在后续的内容中,我不会详细介绍这些基本的 Linux 系统使用方法。所以,你需要提前掌握这些基本知识。这样,接下来我在讲解 eBPF 时,你就更容易理解背后的工作原理和详细使用方法,也更容易明白每一步实践操作的具体含义。</p><p>其次,由于 eBPF 是内核的一部分,在实际使用 eBPF 时,大都会涉及一些内核接口的编程。所以,我希望你<strong>有一定的编程基础(比如 C 语言和 Python 语言),并了解如何从源代码编译和运行 C 程序。</strong>以 C 语言和 Python 语言为例,主要包括:</p><ul> <li>了解 C 语言和 Python 语言的基本语法格式,并能够看懂简单的 C 语言和 Python 语言程序;</li> <li>了解 C 语言程序的编译方法,并了解 make、gcc 等常用编译工具的基本使用方法;</li> <li>了解 C 语言和 Python 语言程序的调试方法,并能够借助日志、调试器等,在程序出错时排查问题的原因。</li> </ul><p>虽然这些内容看起来可能会很难,并且内容很多,但实际上任何一本 C 语言和 Python 语言的入门书籍都会讲到这些基本知识,这里我推荐适合编程入门者的 《C 程序设计语言》和《Python 编程:从入门到实践》(如果你更喜欢用视频的方式学习,也可以在 B 站中找到很多入门的视频教程)。</p><p>了解了 C 语言和 Python 语言的编程基础,我在后续讲解 eBPF 和 Linux 内核相关的编程接口时,你就能够更好地理解这些编程接口的原理,也更容易通过编程把 eBPF 变成自己的武器。</p><p>最后,虽然 eBPF 是 Linux 内核的一部分,其编程接口也通常涉及一定的内核原理,但<strong>在刚开始学习时,我并不建议你深入去学习内核的源码</strong>。就像我在《Linux 性能优化实战》专栏中提到的那样:学习一门新的技术时,你并不需要了解所有与这门技术相关的细节,只要了解这个技术的基本原理,并建立起整个技术的全局观,你就可以掌握这个技术的核心。</p><h2>学习 eBPF,重点是什么?</h2><p>在开篇词里,我已经提过这一点:学习一门新技术,最快的方法就是理解原理的同时配合大量的实践,eBPF 也不例外。因而,我们学习 eBPF 的重中之重就是:</p><ul> <li>理解 eBPF 的基本原理;</li> <li>掌握 eBPF 的编程接口;</li> <li>通过实践把 eBPF 应用到真正的工作场景中。</li> </ul><p>这门课会针对不同场景,把这三个重点方面给你讲清楚,也希望你一定要花时间和心思来消化它们。</p><p>其实,如果你之前学习过我的上一个专栏《Linux 性能优化实战》,你就已经把 eBPF 用到了性能优化的场景中。作为最灵活的动态追踪方法,<a href="https://github.com/iovisor/bcc">BCC</a> 包含的所有工具都是基于 eBPF 开发的。如下图(图片来自 <a href="https://www.brendangregg.com/Perf/bcc_tracing_tools.png">www.brendangregg.com</a>)所示,BCC 提供了贯穿内核各个子系统的动态追踪工具:</p><p><img src="https://static001.geekbang.org/resource/image/82/f3/82d8912ebdc2815e29b6dc754a5f03f3.png?wh=1500x1050" alt="图片" title="BCC 工具大全"></p><p>所有的这些工具都是开源的,它们其实也是学习 eBPF 最好的参考资料。<strong>你可以先把这些工具用起来,然后通过源码了解它们的工作原理,最后再尝试扩展这些工具,增加自己的想法。</strong></p><p>但是切记,BCC 等工具并不是学习的全部。工具只是解决问题的手段,关键还是背后的工作原理。只有掌握了 eBPF 的核心原理,并且结合具体实践融会贯通,你才能真正掌握它们。</p><p>最后,为了让你对 eBPF 有个全面的认识,我画了一张思维导图,里面涵盖了 eBPF 的所有学习重点,这门课中也基本都会讲到。你可以把这张图保存或者打印下来,每学会一部分,就在上面做标记,这样就能更好地记录并把握自己的学习进度。</p><p><img src="https://static001.geekbang.org/resource/image/03/9a/030c0c56a9d210690c75770fe6761f9a.jpg?wh=1920x2355" alt="图片"></p><h2>怎么学习更高效?</h2><p>前面,我给你讲了 eBPF 的学习重点,接下来我再跟你分享几个学习技巧。掌握了这些技巧,你可以学习得更轻松。</p><p><strong>技巧一:虽然对内核源码的理解很重要,但切记,不要陷入内核的实现细节中。</strong></p><p>eBPF 的学习和使用绕不开对内核源码的理解和应用,但并不是说学习 eBPF 就一定要掌握所有的内核源码。实际上,如果你一开始就陷入了内核的具体实现细节中,很可能会因为巨大的困难而产生退意。</p><p>你要记得,学习 eBPF 的目的并不是掌握内核,而是利用 eBPF 这个强大的武器去解决网络、观测、排错以及安全等实际的问题。因而,对初学者来说,掌握 eBPF 的基本原理以及编程接口才是学习的重点。最后再强调一遍,学习时要分清主次,不要陷入内核的实现细节中。</p><p><strong>技巧二:边学习边实践,并大胆借鉴开源项目。</strong></p><p>eBPF 的基本原理当然重要,但只懂原理而不动手实战,并不能真正掌握 eBPF。只有用 eBPF 解决了实际的问题,eBPF 才真正算是你的武器。</p><p>得益于开源软件,无论在 Linux 内核中还是在 GitHub 等开源网站上,你都可以找到大量基于 eBPF 的开源案例。在动手实践 eBPF 时,你可以大胆借鉴它们的思路,学习开源社区中解决同类问题的办法。</p><p><strong>技巧三:多交流、多思考,并参与开源社区讨论。</strong></p><p>作为一个实践性很强,并且在飞速发展的技术,eBPF 的功能特性还在快速迭代中。同时,由于新技术总有一个成熟的过程,在开始接触和应用 eBPF 时,我们也需要留意它在不同内核版本中的限制。</p><p>所以,我希望你在学习 eBPF 的过程中,做到多交流、多思考。你可以随时在评论区给我留言,写下自己的疑问、思考和总结,和我还有其他的学习者一起讨论切磋。看到优秀的开源项目时,你也可以去参与贡献,和开源社区的大拿们共同完善 eBPF 生态。</p><h2>小结</h2><p>今天,我带你一起梳理了高效学习 eBPF 的方法,并分享了一些我在学习 eBPF 时整理的技巧。</p><p>相对于其他技术来说,eBPF 是一个更接近 Linux 底层的技术。虽然学习它之前不需要你掌握内核的开发,但由于 eBPF 的应用总是伴随着大量的开发过程,你最好可以先熟悉 Linux 系统的基本使用方法,以及 C、Python 等语言的基础编程。</p><p>在学习 eBPF 技术时,你也不需要掌握所有相关技术的细节,只要重点把握 eBPF 基本原理和编程接口,再配合大量的工作实践,你就可以完全掌握 eBPF 技术。</p><p>当然了,eBPF 还处在飞速发展的过程中,多了解开源社区的进展和最新应用案例,多参与开源社区讨论,可以帮你更深刻地理解 eBPF 的核心原理,同时更好地把握 eBPF 未来的发展方向。</p><h2>思考题</h2><p>这一讲和上一讲的内容,都是为我们后续的学习做准备的,你可以把它们当作课前的热身环节。从下一讲开始,我们就要正式进入 eBPF 的世界了。所以,我想请你聊一聊:</p><ol> <li>你之前有没有了解过基于 eBPF 的开源项目,可以和同学们分享你觉得优秀的项目吗?</li> <li>在学习和使用 eBPF 时,你有哪些心得,又遇到过哪些问题?欢迎在评论区分享。</li> </ol><p>今天的内容就结束了,欢迎把它分享给你的同事和朋友,我们下一讲见。</p> <style> ul { list-style: none; display: block; list-style-type: disc; margin-block-start: 1em; margin-block-end: 1em; margin-inline-start: 0px; margin-inline-end: 0px; padding-inline-start: 40px; } li { display: list-item; text-align: -webkit-match-parent; } ._2sjJGcOH_0 { list-style-position: inside; width: 100%; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; margin-top: 26px; border-bottom: 1px solid rgba(233,233,233,0.6); } ._2sjJGcOH_0 ._3FLYR4bF_0 { width: 34px; height: 34px; -ms-flex-negative: 0; flex-shrink: 0; border-radius: 50%; } ._2sjJGcOH_0 ._36ChpWj4_0 { margin-left: 0.5rem; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; padding-bottom: 20px; } ._2sjJGcOH_0 ._36ChpWj4_0 ._2zFoi7sd_0 { font-size: 16px; color: #3d464d; font-weight: 500; -webkit-font-smoothing: antialiased; line-height: 34px; } ._2sjJGcOH_0 ._36ChpWj4_0 ._2_QraFYR_0 { margin-top: 12px; color: #505050; -webkit-font-smoothing: antialiased; font-size: 14px; font-weight: 400; white-space: normal; word-break: break-all; line-height: 24px; } ._2sjJGcOH_0 ._10o3OAxT_0 { margin-top: 18px; border-radius: 4px; background-color: #f6f7fb; } ._2sjJGcOH_0 ._3klNVc4Z_0 { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; -webkit-box-align: center; -ms-flex-align: center; align-items: center; margin-top: 15px; } ._2sjJGcOH_0 ._10o3OAxT_0 ._3KxQPN3V_0 { color: #505050; -webkit-font-smoothing: antialiased; font-size: 14px; font-weight: 400; white-space: normal; word-break: break-word; padding: 20px 20px 20px 24px; } ._2sjJGcOH_0 ._3klNVc4Z_0 { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; -webkit-box-align: center; -ms-flex-align: center; align-items: center; margin-top: 15px; } ._2sjJGcOH_0 ._3Hkula0k_0 { color: #b2b2b2; font-size: 14px; } </style><ul><li> <div class="_2sjJGcOH_0"><img src="https://static001.geekbang.org/account/avatar/00/0f/5e/96/a03175bc.jpg" class="_3FLYR4bF_0"> <div class="_36ChpWj4_0"> <div class="_2zFoi7sd_0"><span>莫名</span> </div> <div class="_2_QraFYR_0">曾基于 BPF 做过一个容器平台的链路追踪系统,分解出单个请求在服务端经过的节点、网络设备、耗时等信息,便于快速定位网络抖动时主要延迟的具体发生点。<br><br>遇到最多的是内核版本差异引起的各类编译问题,要么跑不起来,要么运行结果不符合预期。尤其 4.9 内核问题很多,5.x 版本的内核自己在测试环境用一用还行,线上的内核版本相对会保守,几年前 3.10 的占比很高。不过好消息是,新机器的内核一般都直接使用 4.x,甚至 5.x。BPF 落地生产环境的环境阻力小了很多。<br><br>如果公司的环境暂时还不能应用 BPF 技术,不妨碍先进行知识储备,自己先玩起来,等到真正被需要的时候就可以发挥作用了。</div> <div class="_10o3OAxT_0"> <p class="_3KxQPN3V_0">作者回复: 很赞的分享,谢谢!欢迎分享更多的实践经验。</p> </div> <div class="_3klNVc4Z_0"> <div class="_3Hkula0k_0">2022-01-19 19:04:47</div> </div> </div> </div> </li> <li> <div class="_2sjJGcOH_0"><img src="http://thirdwx.qlogo.cn/mmopen/vi_32/1PyKtnO7QRIP8mlcGNu4wpYVjOo6ZZ7pNIxbmRSYK0KvbcXPVcsiba4ibo1GTjQrRYibiaPxrrTPtlGnzoDEP7tDBQ/132" class="_3FLYR4bF_0"> <div class="_36ChpWj4_0"> <div class="_2zFoi7sd_0"><span>ermaot</span> </div> <div class="_2_QraFYR_0">从倪老师的linux性能篇,了解到了ebpf,就买了《bpf之巅》自学了一阵,现在居然倪老师也出了ebpf的课程,果断入手,希望认识能更上一个台阶</div> <div class="_10o3OAxT_0"> <p class="_3KxQPN3V_0">作者回复: 嗯嗯,这本书不错,我们一起加油!</p> </div> <div class="_3klNVc4Z_0"> <div class="_3Hkula0k_0">2022-01-19 11:47:51</div> </div> </div> </div> </li> <li> <div class="_2sjJGcOH_0"><img src="https://static001.geekbang.org/account/avatar/00/0f/43/32/3eeac151.jpg" class="_3FLYR4bF_0"> <div class="_36ChpWj4_0"> <div class="_2zFoi7sd_0"><span>ranger</span> </div> <div class="_2_QraFYR_0">正在接触混沌工程和其中一款开源产品chaos-mesh,一个基于bpf实现的内核故障注入的模块bpfki</div> <div class="_10o3OAxT_0"> <p class="_3KxQPN3V_0">作者回复: 👍 欢迎在留言区分享你的学习和实践经验。</p> </div> <div class="_3klNVc4Z_0"> <div class="_3Hkula0k_0">2022-01-30 15:38:29</div> </div> </div> </div> </li> <li> <div class="_2sjJGcOH_0"><img src="https://static001.geekbang.org/account/avatar/00/23/52/66/3e4d4846.jpg" class="_3FLYR4bF_0"> <div class="_36ChpWj4_0"> <div class="_2zFoi7sd_0"><span>includestdio.h</span> </div> <div class="_2_QraFYR_0">第一次接触bpf是通过老师的 linux性能优化专栏,然后看到老师有推荐性能之巅这本书,果断入手并断断续续看完了,目前实际工作中还没有接触过ebpf,因此也无从入手,希望通过专栏能收获更多</div> <div class="_10o3OAxT_0"> <p class="_3KxQPN3V_0">作者回复: 感谢对专栏的支持,其实我们性能优化专栏里面已经用了很多的ebpf工具,这门课之后我们就可以自己按需来构建自己的性能优化工具了</p> </div> <div class="_3klNVc4Z_0"> <div class="_3Hkula0k_0">2022-01-19 14:21:19</div> </div> </div> </div> </li> <li> <div class="_2sjJGcOH_0"><img src="https://static001.geekbang.org/account/avatar/00/27/f6/78/84513df0.jpg" class="_3FLYR4bF_0"> <div class="_36ChpWj4_0"> <div class="_2zFoi7sd_0"><span>秋名山犬神</span> </div> <div class="_2_QraFYR_0">想知道下k8s中的哪些功能是老师贡献的</div> <div class="_10o3OAxT_0"> <p class="_3KxQPN3V_0">作者回复: k8s开源的,所有贡献Github上面都可以搜到😊</p> </div> <div class="_3klNVc4Z_0"> <div class="_3Hkula0k_0">2022-01-24 21:05:31</div> </div> </div> </div> </li> </ul>
<script setup lang="ts"> import { h, ref } from 'vue'; import { CloseCircleOutlined } from '@ant-design/icons-vue'; import { reactive } from 'vue'; type MenuItem = { id: string, name: string, path: string } let menuList: MenuItem[] = reactive([]) let selectedMenu = ref('') let show = ref(false) const showMenu = () => { show.value = true } const closeMenu = () => { show.value = false } const handleMenuItemClick = (menuItem: MenuItem) => { if (selectedMenu.value === menuItem.id) { return } selectedMenu.value = menuItem.id } const clearSelectedMenu = () => { selectedMenu.value = '' } const getMenuList = () => { menuList.splice(0) menuList.push( ...[ { name: 'test 1', path: 'test 1', id: 'test 1' }, { name: 'test 2', path: 'test 2', id: 'test 2' }, { name: 'test 3', path: 'test 3', id: 'test 3' }, { name: 'test 4', path: 'test 4', id: 'test 4' }, { name: 'test 5', path: 'test 5', id: 'test 5' } ] ) } const init = () => { getMenuList() } init() defineExpose({ showMenu, closeMenu, clearSelectedMenu }); </script> <template> <a-config-provider :theme="{ token: { colorPrimary: '#5c6065', }, }" > <div :class="PREFIX_NAME_WRAPPER('menu-cloak')" v-show="show" @click="closeMenu"></div> <div :class="[PREFIX_NAME_WRAPPER('menu'), show ? 'show' : '']"> <div class="filter-div"> <div class="header-part"> <a-button class="close-btn" type="primary" shape="circle" :icon="h(CloseCircleOutlined)" @click="closeMenu" /> </div> <div class="content-part vertical-scroll"> <div :class="['menu-item', selectedMenu === menuItem.id && 'active']" v-for="menuItem in menuList" :key="menuItem.id" @click="() => handleMenuItemClick(menuItem)" > {{ menuItem.name }} </div> </div> </div> </div> </a-config-provider> </template> <style scoped lang="scss"> .#{PREFIX_NAME_WRAPPER(menu-cloak)} { position: absolute; width: 100%; height: 100%; background-color: rgba(114, 112, 112, .3); top: 0; backdrop-filter: blur(20px); } .#{PREFIX_NAME_WRAPPER(menu)} { position: absolute; height: 100%; width: 300px; left: -300px; background-color: $menu-background-color; border: 1px solid $base-border-color; top: 0; border-radius: 0 8px 8px 0; box-sizing: border-box; padding: 10px; overflow: hidden; transition: 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94); $header-part-height: 80px; $content-part-height: calc(100% - #{$header-part-height}); .filter-div { content: ""; width: 100%; height: 100%; position: relative; backdrop-filter: blur(20px); } &.show { left: 0; } .header-part { width: 100%; height: $header-part-height; .close-btn { float: right; } } .content-part { width: 100%; height: $content-part-height; .menu-item { $menu-item-height: 50px; $active-box-shadow: inset 0px 0px 12px -1px rgba(255,255,255,0.15); $active-box-shadow-light: inset 0px 0px 12px -1px rgba(255,255,255,0.5); width: 100%; height: $menu-item-height; line-height: $menu-item-height; text-indent: 10px; cursor: pointer; border: 1px solid rgba(0,0,0,0); border-bottom: 1px solid $base-border-color; transition: .1s; user-select: none; &:hover { background: rgba(189, 189, 189, .12); box-shadow: $active-box-shadow; border-radius: 4px; } &.active { animation: menu-item-active 4s ease-in-out infinite; border-radius: 4px; background: rgba(189, 189, 189, .12); } @keyframes menu-item-active { 0% { box-shadow: $active-box-shadow; } 35% { box-shadow: $active-box-shadow-light; } 80% { box-shadow: $active-box-shadow; } 100% { box-shadow: $active-box-shadow; } } } } } </style>
// // MapView.swift // Africa // // Created by Artem Talko on 23.07.2023. // import SwiftUI import MapKit struct MapView: View { @State private var region: MKCoordinateRegion = { var mapCoordinates = CLLocationCoordinate2D(latitude: 6.600286, longitude: 16.4) var mapZoomLevel = MKCoordinateSpan(latitudeDelta: 70.0, longitudeDelta: 70.0) var mapRegion = MKCoordinateRegion(center: mapCoordinates, span: mapZoomLevel) return mapRegion }() let location: [NationalParkLocation] = Bundle.main.decode("locations.json") var body: some View { //MARK: 1 BASIC MAP //Map(coordinateRegion: $region) //MARK: 2 ADVANCED MAP Map(coordinateRegion: $region, annotationItems: location, annotationContent: { item in //MapMarker(coordinate: item.location, tint: .accentColor) MapAnnotation(coordinate: item.location) { MapAnnotationView(location: item) } })//Anotation .overlay( HStack(alignment: .center, spacing: 12) { Image("compass") .resizable() .scaledToFit() .frame(width: 48, height: 48, alignment: .center) VStack(alignment: .leading, spacing: 3) { HStack { Text("Latitude:") .font(.footnote) .fontWeight(.bold) .foregroundColor(.accentColor) Spacer() Text("\(region.center.latitude)") .font(.footnote) .fontWeight(.bold) } HStack { Text("Longitude:") .font(.footnote) .fontWeight(.bold) .foregroundColor(.accentColor) Spacer() Text("\(region.center.longitude)") .font(.footnote) .fontWeight(.bold) } Divider() } }//: HSTACK .padding(.vertical, 12) .padding(.horizontal, 16) .background( Color.black .cornerRadius(8) .opacity(0.6) ) .padding() , alignment: .top ) } } struct MapView_Previews: PreviewProvider { static var previews: some View { MapView() } }