text
stringlengths
184
4.48M
package com.example.clinic.service.impl; import com.example.clinic.domain.DoctorsEntity; import com.example.clinic.dto.DoctorsDto; import com.example.clinic.filter.DoctorsFilter; import com.example.clinic.repository.DoctorsRepository; import com.example.clinic.service.DoctorsService; import jakarta.persistence.EntityManagerFactory; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; @Service @Slf4j public class DoctorsServiceImpl implements DoctorsService { @Autowired private DoctorsRepository repository; @Autowired private ModelMapper modelMapper; @Override public DoctorsDto getById(UUID id) { DoctorsEntity entity = repository.findById(id).orElseThrow(); return modelMapper.map(entity, DoctorsDto.class); } @Override public List<DoctorsDto> findAll() { List<DoctorsEntity> entities = repository.findAll(); return entities.stream() .map(entity -> modelMapper.map(entity, DoctorsDto.class)) .collect(Collectors.toList()); } @Override public List<DoctorsDto> findByFilter(DoctorsFilter filter) { List<DoctorsEntity> entities = repository.findAll(filter); return entities.stream() .map(entity -> modelMapper.map(entity, DoctorsDto.class)) .collect(Collectors.toList()); } @Override public String save(DoctorsDto dto) { DoctorsEntity entity = modelMapper.map(dto, DoctorsEntity.class); return String.valueOf(repository.save(entity).getId()); } @Override public String delete(UUID id) { DoctorsEntity entity = repository.findById(id).orElseThrow(); repository.delete(entity); return "Объект удалён!"; } @Override public String update(DoctorsDto dto) { Optional<DoctorsEntity> entityOptional = repository.findById(dto.getId()); if (entityOptional.isPresent()) { DoctorsEntity entity = entityOptional.get(); DoctorsEntity dtoToEntity = modelMapper.map(dto, DoctorsEntity.class); entity.setFio(dtoToEntity.getFio()); entity.setSpec(dtoToEntity.getSpec()); entity.setHiringDate(dtoToEntity.getHiringDate()); entity.setPhone(dtoToEntity.getPhone()); entity.setAddress(dtoToEntity.getAddress()); repository.save(entity); return "Объект обновлён!"; } return "Объект не найден!"; } @Override public DoctorsEntity getByIdEntity(UUID id) { return repository.findById(id).orElseThrow(); } }
import React, { useState } from "react"; import DashboardNavbar from "./DashboardNavbar"; import { Container, Row, Col } from "react-bootstrap"; import Form from "react-bootstrap/Form"; import { FiEdit } from "react-icons/fi"; import { faUpload } from "@fortawesome/free-solid-svg-icons"; import "react-toastify/dist/ReactToastify.css"; import { ToastContainer, toast } from "react-toastify"; import axios from "axios"; import { apiUrl } from "../../data/env"; function AddFilter() { const [fetchedCategories, setFetchedCategories] = React.useState([]); React.useEffect(() => { const id = toast.loading("Fetching Data... Please Wait!"); axios .get(`${apiUrl}/api/v1/category`) .then((res) => { setFetchedCategories(res.data.data); console.log(res.data.data); toast.update(id, { render: "Successfully Fetched Data!", type: "success", isLoading: false, autoClose: 2000, }); }) .catch((err) => { console.log(err); toast.update(id, { render: err.response?.data?.message || "Error! Try Again & See Console", type: "error", isLoading: false, autoClose: 3500, }); }); }, []); // hooks for post request const [selectedCategory, setSelectedCategory] = React.useState(""); const [filterName, setFilterName] = React.useState(""); const [priorityNum, setPriorityNum] = React.useState(1); const [showInNavbar, setShowInNavbar] = React.useState("true"); const [showInFilterbar, setShowInFilterbar] = React.useState("false"); const [selectedFile, setSelectedFile] = useState(null); const [uploadImg, setUploadImg] = useState(false); const handleFileChange = (event) => { const file = event.target.files[0]; setSelectedFile(file); setUploadImg(true); }; const handleUploadImage = (pId) => { const id = toast.loading("Uploading Image..."); let formData = new FormData(); formData.append("image", selectedFile); axios .post(`${apiUrl}/api/v1/filter/imageUpload?filterId=${pId}`, formData) .then((res) => { console.log(res.data); console.log("uploaded image"); // alert("successfully uploaded image!"); // return 'success'; toast.update(id, { render: "Uploaded Sub-Collection Image Successfully!", type: "success", isLoading: false, autoClose: 2000, }); setUploadImg(false); }) .catch((err) => { console.log(err); toast.update(id, { render: err.response?.data?.message || "Image Upload Error! See more using console!", type: "error", isLoading: false, autoClose: 3000, }); }); }; const handleSubmitNewFilter = (e) => { e.preventDefault(); const id = toast.loading("Please wait..."); const token = localStorage.getItem("token"); const config = { headers: { Authorization: `Bearer ${token}` }, }; const payload = { name: filterName, priority: priorityNum, categoryId: selectedCategory, showNavbar: showInNavbar === "true" ? true : false, showFilterbar: showInFilterbar === "true" ? true : false, }; axios .post(`${apiUrl}/api/v1/filter`, payload, config) .then((res) => { if (uploadImg) handleUploadImage(res.data.data._id); // setIsLoadingState(false); console.log(res.data); toast.update(id, { render: "Created Sub Collection Successfully", type: "success", isLoading: false, autoClose: 3000, }); setFilterName(""); setPriorityNum(1); setShowInFilterbar("false"); setShowInNavbar("true"); setSelectedCategory(""); }) .catch((err) => { console.log(err); toast.update(id, { render: err.response?.data?.message || "Error Occured! See more using console!", type: "error", isLoading: false, autoClose: 3000, }); }); console.log(payload); }; return ( <div> <DashboardNavbar /> <div> <div class=" mt-24 absolute lg:left-[260px] z-5"> <Container class=""> <h2 class="font-bold text-xl">Add Sub Collection</h2> <Row class=""> <Col md={4}> <Form.Group as={Col} controlId="" sm={4} className=" mt-3"> <div class="border rounded-md w-[20rem] h-[13rem] flex flex-col justify-center items-center"> <input type="file" id="fileInput" accept="image/png, image/jpeg" class="text-center" style={{ display: "none" }} onChange={handleFileChange} /> <label htmlFor="fileInput"> <FiEdit icon={faUpload} class="text-2xl text-center " style={{ cursor: "pointer", margin: "0 auto" }} /> <span>Upload an Image</span> <br /> </label> {selectedFile && ( <p class="w-75">Selected File: {selectedFile.name}</p> )} </div> </Form.Group> {/* <Row> <Col> <Form.Group as={Col} controlId="" sm={4} className=""> <Form.Label class="text-[#707070] font-semibold py-2"></Form.Label> <Form.Control type="text" style={{ height: "40px", width: "45px" }} /> <div class="absolute text-center " style={{ marginTop: -28 }} > <p class=" px-3 text-[#707070]"> <FiEdit /> </p> </div> </Form.Group> </Col> <Col> <Form.Group as={Col} controlId="" sm={4} className=""> <Form.Label class="text-[#707070] font-semibold py-2"></Form.Label> <Form.Control type="text" style={{ height: "40px", width: "45px" }} /> <div class="absolute text-center " style={{ marginTop: -28 }} > <p class=" px-3 text-[#707070]"> <FiEdit /> </p> </div> </Form.Group> </Col> <Col> <Form.Group as={Col} controlId="" sm={4} className=""> <Form.Label class="text-[#707070] font-semibold py-2"></Form.Label> <Form.Control type="text" style={{ height: "40px", width: "45px" }} /> <div class="absolute text-center " style={{ marginTop: -28 }} > <p class=" px-3 text-[#707070]"> <FiEdit /> </p> </div> </Form.Group> </Col> <Col> <Form.Group as={Col} controlId="" sm={4} className=""> <Form.Label class="text-[#707070] font-semibold py-2"></Form.Label> <Form.Control type="text" style={{ height: "40px", width: "45px" }} /> <div class="absolute text-center " style={{ marginTop: -28 }} > <p class=" px-3 text-[#707070]"> <FiEdit /> </p> </div> </Form.Group> </Col> </Row> */} </Col> <Col md={8}> <Form> <Row className="mb-3 lg:px-16 mt-3"> <Form.Group as={Col} controlId=""> <Form.Label class="text-[#707070] font-semibold py-2"> Select Collection </Form.Label> <Form.Select onChange={(e) => setSelectedCategory(e.target.value)} aria-label="Default select example" > <option></option> {fetchedCategories?.map((cat) => ( <option key={cat._id} value={cat._id}> {cat.name} </option> ))} </Form.Select> </Form.Group> <Form.Group as={Col} controlId=""> <Form.Label class="text-[#707070] font-semibold py-2"> Name </Form.Label> <Form.Control type="text" value={filterName} onChange={(e) => setFilterName(e.target.value)} /> </Form.Group> {/* <Form.Group as={Col} controlId=""> <Form.Label class="text-[#707070] font-semibold py-2"> Alternate Name </Form.Label> <Form.Control type="text" value={filterAlternateName} onChange={(e) => setFilterAlternateName(e.target.value)} /> </Form.Group> */} </Row> <Row className="mb-3 lg:px-16 mt-3"> <Form.Group as={Col} controlId=""> <Form.Label class="text-[#707070] font-semibold py-2"> Priority Number </Form.Label> <Form.Control type="number" min={1} value={priorityNum} onChange={(e) => setPriorityNum(Number(e.target.value))} /> </Form.Group> <Form.Group as={Col} controlId=""> <Form.Label class="text-[#707070] font-semibold py-2"> Show in Navbar </Form.Label> <Form.Select value={showInNavbar} onChange={(e) => setShowInNavbar(e.target.value)} aria-label="Default select example" > <option value={"true"}>Yes</option> <option value={"false"}>No</option> </Form.Select> </Form.Group> <Form.Group as={Col} controlId=""> <Form.Label class="text-[#707070] font-semibold py-2"> Show in Filterbar </Form.Label> <Form.Select value={showInFilterbar} onChange={(e) => setShowInFilterbar(e.target.value)} aria-label="Default select example" > <option value={"true"}>Yes</option> <option value={"false"}>No</option> </Form.Select> </Form.Group> </Row> {/* <Row className="mb-3 lg:px-16 mt-3"> <Form.Group as={Col} controlId="" md={2}> <Form.Label class="text-[#707070] font-semibold py-2"> New Options </Form.Label> <Form.Control type="text" value={typedOption} onChange={(e) => setTypedOption(e.target.value)} /> </Form.Group> <Form.Group as={Col} controlId=""> <button class="rounded-1 p-2 mt-[4rem] bg-[#bd9229] text-white" onClick={(e) => { e.preventDefault(); setOptionsArray((arr) => [...arr, typedOption]); setTypedOption(""); }} > Add Option </button> </Form.Group> <Form.Group as={Col} controlId="" md={4} style={{ marginTop: 15 }} > <Form.Label class="text-[#707070] font-semibold py-2"> Current Options </Form.Label> <Form.Select onChange={(e) => setSelectedOption(e.target.value)} aria-label="Default select example" > <option value={""}></option> {optionsArray?.map((opt, i) => ( <option key={i} value={opt}> {opt} </option> ))} </Form.Select> </Form.Group> <Form.Group as={Col} controlId=""> <button class="rounded-1 p-2 text-white" style={{ marginTop: 37 }} onClick={(e) => { e.preventDefault(); if (optionsArray.length >= 1) { const newArr = [...optionsArray]; newArr.splice( optionsArray.indexOf(selectedOption), 1 ); setOptionsArray(newArr); setSelectedOption(""); } }} > {" "} <RiDeleteBinLine class="text-[#707070] mt-[1rem] text-2xl" /> </button> </Form.Group> </Row> */} </Form> </Col> </Row> <button onClick={handleSubmitNewFilter} class="rounded-1 p-2 w-32 font-semibold mt-4 bg-[#bd9229] text-white" > Submit </button> </Container> </div> </div> <ToastContainer position="top-center" /> </div> ); } export default AddFilter;
#include <iostream> #include <vector> #include <algorithm> using namespace std; const int MAX_N = 100010; const int MAX_M = 200010; int n, m; vector<int> adj[MAX_N]; int deg[MAX_N]; int edges[MAX_M][2]; int weight[MAX_M]; pair<int, int> witems[MAX_M]; void read_input(){ cin >> n >> m; for (int i = 0 ; i < n ; i++){ deg[i] = 0; } for (int i = 0 ; i < m ; i++){ int u, v, w, fix; cin >> u >> v >> w >> fix; u--; v--; adj[u].push_back(v); adj[v].push_back(u); deg[u]++; deg[v]++; edges[i][0] = u; edges[i][1] = v; if (fix == 1){ w = 0; } weight[i] = w; witems[i].first = w; witems[i].second = i; } } int parents[MAX_N]; int ranks[MAX_N]; void init_union_find() { for (int i = 0 ; i < n ; i++) { parents[i] = i; ranks[i] = 0; } } int find(int u) { while(parents[u] != u) { u = parents[u]; } return u; } void union_set(int pu, int pv) { if (ranks[pu] < ranks[pv]) { parents[pu] = pv; } else if (ranks[pv] < ranks[pu]) { parents[pv] = pu; } else { parents[pu] = pv; ranks[pv]++; } } int kruskal(){ int result = 0; init_union_find(); //sort sort(witems, witems + m); for (int i = 0 ; i < m ; i++){ int w = witems[i].first; //weight int e = witems[i].second; //edges int u = edges[e][0]; int v = edges[e][1]; int pu = find(u); int pv = find(v); if (pu != pv){ //use edge e in the MST union_set(pu, pv); result += w; } } return result; } int main(){ read_input(); int result = kruskal(); cout << result << "\n"; } /* 5 6 1 3 5 1 1 2 8 1 2 4 3 0 3 4 6 0 5 3 7 1 5 4 1 1 5 6 1 3 5 0 1 2 8 1 2 4 3 0 3 4 6 1 5 3 7 0 5 4 1 0 5 6 1 3 5 0 1 2 8 0 2 4 3 0 3 4 6 0 5 3 7 0 5 4 1 0 */
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CHPP_PLATFORM_SYNC_H_ #define CHPP_PLATFORM_SYNC_H_ #include <pthread.h> #include <stdint.h> #include "chpp/mutex.h" #ifdef __cplusplus extern "C" { #endif struct ChppNotifier { pthread_cond_t cond; // Condition variable struct ChppMutex mutex; // Platform-specific mutex uint32_t signal; }; /** * Platform implementation of chppNotifierInit() */ void chppPlatformNotifierInit(struct ChppNotifier *notifier); /** * Platform implementation of chppNotifierDeinit() */ void chppPlatformNotifierDeinit(struct ChppNotifier *notifier); /** * Platform implementation of chppNotifierGetSignal() */ uint32_t chppPlatformNotifierGetSignal(struct ChppNotifier *notifier); /** * Platform implementation of chppNotifierWait() */ uint32_t chppPlatformNotifierWait(struct ChppNotifier *notifier); /** * Platform implementation of chppNotifierTimedWait() */ uint32_t chppPlatformNotifierTimedWait(struct ChppNotifier *notifier, uint64_t timeoutNs); /** * Platform implementation of chppNotifierSignal() */ void chppPlatformNotifierSignal(struct ChppNotifier *notifier, uint32_t signal); static inline void chppNotifierInit(struct ChppNotifier *notifier) { chppPlatformNotifierInit(notifier); } static inline void chppNotifierDeinit(struct ChppNotifier *notifier) { chppPlatformNotifierDeinit(notifier); } static inline uint32_t chppNotifierGetSignal(struct ChppNotifier *notifier) { return chppPlatformNotifierGetSignal(notifier); } static inline uint32_t chppNotifierWait(struct ChppNotifier *notifier) { return chppPlatformNotifierWait(notifier); } static inline uint32_t chppNotifierTimedWait(struct ChppNotifier *notifier, uint64_t timeoutNs) { return chppPlatformNotifierTimedWait(notifier, timeoutNs); } static inline void chppNotifierSignal(struct ChppNotifier *notifier, uint32_t signal) { chppPlatformNotifierSignal(notifier, signal); } #ifdef __cplusplus } #endif #endif // CHPP_PLATFORM_SYNC_H_
from dataclasses import dataclass from enum import Flag from typing import Dict, List, Optional import zoti_graph.core as ty from zoti_graph.util import SearchableEnum, default_init, default_repr class Dir(Flag, metaclass=SearchableEnum): """ Bitwise flags denoting port directions. """ NONE = 0 # : 00 (for init) IN = 1 # : 01 OUT = 2 # : 10 SIDE = 3 # : 11 class Port(ty.Port): """Container for port entry.""" kind: Dir port_type: Dict data_type: Dict @default_init def __init__(self, name, kind, port_type={}, data_type={}, mark={}, _info={}, **kwargs): pass @default_repr def __repr__(self): pass def is_event(self): return self.kind and self.kind != Dir.SIDE def is_side(self): return self.kind == Dir.SIDE def has_dir_in(self): return self.kind & Dir.IN != Dir.NONE def has_dir_out(self): return self.kind & Dir.OUT != Dir.NONE class Edge(ty.Edge): """Container for edge entry.""" edge_type: Dict @default_init def __init__(self, edge_type, mark, _info, **kwargs): pass @default_repr def __repr__(self): pass class CompositeNode(ty.Node): """Container for composite node entry""" @default_init def __init__(self, name, parameters={}, mark={}, _info={}, **kwargs): pass @default_repr def __repr__(self): pass class SkeletonNode(ty.Node): """Container for a skeleton node entry""" type: str @default_init def __init__(self, name, type, parameters={}, mark={}, _info={}, **kwargs): pass @default_repr def __repr__(self): pass class PlatformNode(ty.Node): """Container for platform node entry""" target: Dict @default_init def __init__(self, name, target, parameters={}, mark={}, _info={}, **kwargs): pass @default_repr def __repr__(self): pass class ActorNode(ty.Node): """Container for actor node entry""" @dataclass(eq=False) class FSM: inputs: List[str] expr: Dict[str, Dict] preproc: Optional[str] = None states: Optional[List[str]] = None scenarios: Optional[Dict[str, str]] = None detector: Optional[FSM] @default_init def __init__(self, name, parameters={}, mark={}, detector=None, _info={}, **kwargs): pass @default_repr def __repr__(self): pass class KernelNode(ty.Node): """Container for kernel node entry""" extern: str @default_init def __init__(self, name, extern="", parameters={}, mark={}, _info={}, **kwargs): pass @default_repr def __repr__(self): pass class BasicNode(ty.Node): """Container for primitive node entry""" type: str @default_init def __init__(self, name, type, parameters={}, mark={}, _info={}, **kwargs): pass @default_repr def __repr__(self): pass BASE_GRAPHVIZ_STYLE = { "edges": { "all": (lambda edge, src, dst, info_f: { "arrowtail": "diamond" if isinstance(src, Port) and src.is_side() else "none", "arrowhead": "diamond" if isinstance(dst, Port) and dst.is_side() else "normal", "dir": "both", "label": info_f(edge) if info_f else "" }) }, "ports": { "all": (lambda port, info_f: { "shape": "hexagon" if port.is_side() else "rarrow", "label": port.name + (f": {info_f(port)}" if info_f is not None else "") }) }, "leafs": { "BasicNode": (lambda node, ports, info_f, pinfo_f: { "label": "", "shape": "doublecircle", "style": "filled", "width": 0.3, "height": 0.3, "fillcolor": "yellow", } if node.type == "SYSTEM" else { "label": "", "shape": "invtriangle", "width": 0.4, "height": 0.25, "style": "filled", "fillcolor": "black", } if node.type == "DROP" else { "label": node.type, "shape": "oval", "fillcolor": "green" }), "all": (lambda node, ports, info_f, pinfo_f: { "shape": "record", "style": "rounded", "label": "{" + ' | '.join([f"<{idp}> {p.name}: {pinfo_f(p) if pinfo_f is not None else ''}" for idp, p in ports if p.kind == Dir.IN]) + "} | {" + node.name + (f"({node._info['old-name']})" if node._info.get("old-name") else "") + (f": {info_f(node)}" if info_f is not None else "") + " | {" + ' | '.join([f"<{idp}> {p.name}: {pinfo_f(p) if pinfo_f is not None else ''}" for idp, p in ports if p.kind == Dir.SIDE]) + "} } | {" + ' | '.join([f"<{idp}> {p.name}: {pinfo_f(p) if pinfo_f is not None else ''}" for idp, p in ports if p.kind == Dir.OUT]) + "}" }) }, "composites": { "PlatformNode": (lambda node, info_f: { "label": node.name + (f"({node._info['old-name']})" if node._info.get("old-name") else "") + (f": {info_f(node)}" if info_f is not None else f": node.target['platform']"), }), "ActorNode": (lambda node, info_f: { "style": "rounded", "label": node.name + (f"({node._info['old-name']})" if node._info.get("old-name") else "") + (f": {info_f(node)}" if info_f is not None else ""), }), "SkeletonNode": (lambda node, info_f: { "style": "bold", "label": node.name + (f"({node._info['old-name']})" if node._info.get("old-name") else "") + f": {node.type}", }), "all": (lambda node, info_f: { "style": "dashed", "label": node.name + (f"({node._info['old-name']})" if node._info.get("old-name") else "") + (f": {info_f(node)}" if info_f is not None else ""), }), } }
#!/usr/bin/python3 """ N-Queens Puzzle """ import sys def is_safe(board, row, col, N): """ >> Check for queens in the same column. """ for i in range(row): if board[i] == col or \ board[i] - i == col - row or \ board[i] + i == col + row: return False return True def solve_nqueens(N): if N < 4: print("N must be at least 4") sys.exit(1) solutions = [] def backtrack(row, board): if row == N: solutions.append(board[:]) return for col in range(N): if is_safe(board, row, col, N): board[row] = col backtrack(row + 1, board) backtrack(0, [-1] * N) return solutions def main(): if len(sys.argv) != 2: print("Usage: nqueens N") sys.exit(1) try: N = int(sys.argv[1]) except ValueError: print("N must be a number") sys.exit(1) if N < 4: print("N must be at least 4") sys.exit(1) solutions = solve_nqueens(N) for solution in solutions: print([[i, solution[i]] for i in range(N)]) if __name__ == "__main__": main()
import React, {useEffect, useState} from "react"; import { Link } from "react-router-dom"; import Doctor from "./../images/doctor.jpg" const Card = ({ name, username, id, guardarElemento}) => { const cardData = { id, name, username }; const [guardado, setGuardado] = useState(false); useEffect(()=> { const cardsGuardadas = JSON.parse(localStorage.getItem('favCards')) if (cardsGuardadas && cardsGuardadas.find((c)=>c.id ===id)) { setGuardado(true); } }, [id]) return ( <> <div className="card"> <Link to={`/Dentist/${id}`} className="linkCard"> <img src={Doctor} alt="icono doctor" className="imagen"></img> </Link> <p>{name}</p> <p>{username}</p> {guardado ? <button onClick={()=>guardarElemento(cardData)} disabled={guardado}>Guardado</button> : <button onClick={()=>guardarElemento(cardData)}>Agrega favorito</button> } </div> </> ); }; export default Card;
package entities; import java.io.Serializable; import java.util.List; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.ManyToMany; @Entity public class Role implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; @ManyToMany(mappedBy = "roles",fetch = FetchType.EAGER) private List<User> users; public Role() { } public Role(String name) { super(); this.name = name; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Role [id=" + id + ", name=" + name + ", users=" + users + "]"; } }
from collections import namedtuple from datetime import datetime, time from django import forms from django.utils.dateparse import parse_datetime from django.utils.encoding import force_str from django.utils.translation import gettext_lazy as _ from .conf import settings from .constants import EMPTY_VALUES from .utils import handle_timezone from .widgets import ( BaseCSVWidget, CSVWidget, DateRangeWidget, LookupChoiceWidget, RangeWidget ) class RangeField(forms.MultiValueField): widget = RangeWidget def __init__(self, fields=None, *args, **kwargs): if fields is None: fields = ( forms.DecimalField(), forms.DecimalField()) super().__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: return slice(*data_list) return None class DateRangeField(RangeField): widget = DateRangeWidget def __init__(self, *args, **kwargs): fields = ( forms.DateField(), forms.DateField()) super().__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: start_date, stop_date = data_list if start_date: start_date = handle_timezone( datetime.combine(start_date, time.min), False ) if stop_date: stop_date = handle_timezone( datetime.combine(stop_date, time.max), False ) return slice(start_date, stop_date) return None class DateTimeRangeField(RangeField): widget = DateRangeWidget def __init__(self, *args, **kwargs): fields = ( forms.DateTimeField(), forms.DateTimeField()) super().__init__(fields, *args, **kwargs) class IsoDateTimeRangeField(RangeField): widget = DateRangeWidget def __init__(self, *args, **kwargs): fields = ( IsoDateTimeField(), IsoDateTimeField()) super().__init__(fields, *args, **kwargs) class TimeRangeField(RangeField): widget = DateRangeWidget def __init__(self, *args, **kwargs): fields = ( forms.TimeField(), forms.TimeField()) super().__init__(fields, *args, **kwargs) class Lookup(namedtuple('Lookup', ('value', 'lookup_expr'))): def __new__(cls, value, lookup_expr): if value in EMPTY_VALUES or lookup_expr in EMPTY_VALUES: raise ValueError( "Empty values ([], (), {}, '', None) are not " "valid Lookup arguments. Return None instead." ) return super().__new__(cls, value, lookup_expr) class LookupChoiceField(forms.MultiValueField): default_error_messages = { 'lookup_required': _('Select a lookup.'), } def __init__(self, field, lookup_choices, *args, **kwargs): empty_label = kwargs.pop('empty_label', settings.EMPTY_CHOICE_LABEL) fields = (field, ChoiceField(choices=lookup_choices, empty_label=empty_label)) widget = LookupChoiceWidget(widgets=[f.widget for f in fields]) kwargs['widget'] = widget kwargs['help_text'] = field.help_text super().__init__(fields, *args, **kwargs) def compress(self, data_list): if len(data_list) == 2: value, lookup_expr = data_list if value not in EMPTY_VALUES: if lookup_expr not in EMPTY_VALUES: return Lookup(value=value, lookup_expr=lookup_expr) else: raise forms.ValidationError( self.error_messages['lookup_required'], code='lookup_required') return None class IsoDateTimeField(forms.DateTimeField): """ Supports 'iso-8601' date format too which is out the scope of the ``datetime.strptime`` standard library # ISO 8601: ``http://www.w3.org/TR/NOTE-datetime`` Based on Gist example by David Medina https://gist.github.com/copitux/5773821 """ ISO_8601 = 'iso-8601' input_formats = [ISO_8601] def strptime(self, value, format): value = force_str(value) if format == self.ISO_8601: parsed = parse_datetime(value) if parsed is None: # Continue with other formats if doesn't match raise ValueError return handle_timezone(parsed) return super().strptime(value, format) class BaseCSVField(forms.Field): """ Base field for validating CSV types. Value validation is performed by secondary base classes. ex:: class IntegerCSVField(BaseCSVField, filters.IntegerField): pass """ base_widget_class = BaseCSVWidget def __init__(self, *args, **kwargs): widget = kwargs.get('widget') or self.widget kwargs['widget'] = self._get_widget_class(widget) super().__init__(*args, **kwargs) def _get_widget_class(self, widget): # passthrough, allows for override if isinstance(widget, BaseCSVWidget) or ( isinstance(widget, type) and issubclass(widget, BaseCSVWidget)): return widget # complain since we are unable to reconstruct widget instances assert isinstance(widget, type), \ "'%s.widget' must be a widget class, not %s." \ % (self.__class__.__name__, repr(widget)) bases = (self.base_widget_class, widget, ) return type(str('CSV%s' % widget.__name__), bases, {}) def clean(self, value): if value in self.empty_values and self.required: raise forms.ValidationError(self.error_messages['required'], code='required') if value is None: return None return [super(BaseCSVField, self).clean(v) for v in value] class BaseRangeField(BaseCSVField): # Force use of text input, as range must always have two inputs. A date # input would only allow a user to input one value and would always fail. widget = CSVWidget default_error_messages = { 'invalid_values': _('Range query expects two values.') } def clean(self, value): value = super().clean(value) assert value is None or isinstance(value, list) if value and len(value) != 2: raise forms.ValidationError( self.error_messages['invalid_values'], code='invalid_values') return value class ChoiceIterator: # Emulates the behavior of ModelChoiceIterator, but instead wraps # the field's _choices iterable. def __init__(self, field, choices): self.field = field self.choices = choices def __iter__(self): if self.field.empty_label is not None: yield ("", self.field.empty_label) if self.field.null_label is not None: yield (self.field.null_value, self.field.null_label) yield from self.choices def __len__(self): add = 1 if self.field.empty_label is not None else 0 add += 1 if self.field.null_label is not None else 0 return len(self.choices) + add class ModelChoiceIterator(forms.models.ModelChoiceIterator): # Extends the base ModelChoiceIterator to add in 'null' choice handling. # This is a bit verbose since we have to insert the null choice after the # empty choice, but before the remainder of the choices. def __iter__(self): iterable = super().__iter__() if self.field.empty_label is not None: yield next(iterable) if self.field.null_label is not None: yield (self.field.null_value, self.field.null_label) yield from iterable def __len__(self): add = 1 if self.field.null_label is not None else 0 return super().__len__() + add class ChoiceIteratorMixin: def __init__(self, *args, **kwargs): self.null_label = kwargs.pop('null_label', settings.NULL_CHOICE_LABEL) self.null_value = kwargs.pop('null_value', settings.NULL_CHOICE_VALUE) super().__init__(*args, **kwargs) def _get_choices(self): return super()._get_choices() def _set_choices(self, value): super()._set_choices(value) value = self.iterator(self, self._choices) self._choices = self.widget.choices = value choices = property(_get_choices, _set_choices) # Unlike their Model* counterparts, forms.ChoiceField and forms.MultipleChoiceField do not set empty_label class ChoiceField(ChoiceIteratorMixin, forms.ChoiceField): iterator = ChoiceIterator def __init__(self, *args, **kwargs): self.empty_label = kwargs.pop('empty_label', settings.EMPTY_CHOICE_LABEL) super().__init__(*args, **kwargs) class MultipleChoiceField(ChoiceIteratorMixin, forms.MultipleChoiceField): iterator = ChoiceIterator def __init__(self, *args, **kwargs): self.empty_label = None super().__init__(*args, **kwargs) class ModelChoiceField(ChoiceIteratorMixin, forms.ModelChoiceField): iterator = ModelChoiceIterator def to_python(self, value): # bypass the queryset value check if self.null_label is not None and value == self.null_value: return value return super().to_python(value) class ModelMultipleChoiceField(ChoiceIteratorMixin, forms.ModelMultipleChoiceField): iterator = ModelChoiceIterator def _check_values(self, value): null = self.null_label is not None and value and self.null_value in value if null: # remove the null value and any potential duplicates value = [v for v in value if v != self.null_value] result = list(super()._check_values(value)) result += [self.null_value] if null else [] return result
package qs.mp.demo.boundary; import io.quarkus.security.Authenticated; import jakarta.annotation.security.RolesAllowed; import jakarta.enterprise.context.RequestScoped; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.SecurityContext; import org.jboss.logging.Logger; @Path("/demo") @RequestScoped public class DemoResource { @Inject Logger LOG; @GET @Path("/hello") @Authenticated public String hello() { LOG.info("hello"); return "Hello from RESTEasy Reactive"; } @GET @Path("permit-all") @Authenticated @Produces(MediaType.TEXT_PLAIN) public String hello(@Context SecurityContext ctx) { return getResponseString(ctx); } @GET @Path("roles-allowed") @RolesAllowed({ "User" }) @Produces(MediaType.TEXT_PLAIN) public String helloRolesAllowed(@Context SecurityContext ctx) { return getResponseString(ctx); } private String getResponseString(SecurityContext ctx) { LOG.info("getResponseString"); String name; if (ctx.getUserPrincipal() == null) { name = "anonymous"; } else { name = ctx.getUserPrincipal().getName(); } return "Hallo " + name; } }
/** * @license * Copyright (c) 2018 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ import { html, property, customElement, TemplateResult, css } from 'lit-element'; import { IronOverlayBehaviorImpl } from '@polymer/iron-overlay-behavior/iron-overlay-behavior.js'; import { mixinBehaviors } from '@polymer/polymer/lib/legacy/class.js'; import './cart-modal.scss'; import { useLightDom } from '../use-lightdom'; class CartModal extends mixinBehaviors([IronOverlayBehaviorImpl], useLightDom) { render() { return html` <div class="layout-horizontal"> <h1 class="label">Success! You've added this item to your cart.</h1> </div> <div class="actions"> <a href="/cart"> <mwc-button class="mdc-button checkout" @click=${this.close}> Checkout </mwc-button> </a> <span> <mwc-button class="mdc-button close" @click=${this.close}> Continue </mwc-button> </span> </div> `; } static get properties() { return { withBackdrop: { type: Boolean, value: true } }; } ready() { super.ready(); this.setAttribute('role', 'dialog'); this.setAttribute('aria-modal', 'true'); this.addEventListener('transitionend', e => this._transitionEnd(e)); this.addEventListener('iron-overlay-canceled', e => this._onCancel(e)); this.addEventListener('opened-changed', () => {}); document.addEventListener('add-cart', e => this.open()); } _renderOpened() { this.restoreFocusOnClose = true; this.backdropElement.style.display = 'none'; this.classList.add('opened'); } _renderClosed() { this.classList.remove('opened'); } _onCancel(e) { // Don't restore focus when the overlay is closed after a mouse event if (e.detail instanceof MouseEvent) { this.restoreFocusOnClose = false; } } _transitionEnd(e) { if (e.target !== this || e.propertyName !== 'transform') { return; } if (this.opened) { this._finishRenderOpened(); } else { this._finishRenderClosed(); this.backdropElement.style.display = ''; } } get _focusableNodes() { return [this.$.viewCartAnchor, this.$.closeBtn]; } refit() {} notifyResize() {} } customElements.define('remi-cart-modal', CartModal);
import PokeCard from "../PokeCard/PokeCard"; import Spinner from "../Spinner/Spinner"; import { selectAllPokemons } from "../../services/pokemonApi"; import { setPokemons, setCurrentPage } from "../../redux/slices/PokemonSlice"; import { useDispatch, useSelector } from "react-redux"; import { useEffect } from "react"; import "./PokeList.css"; let pokemondata = []; function PokeList() { const { currentPage, page } = useSelector((state) => state.pokemonStore); const dispatch = useDispatch(); pokemondata = useSelector(selectAllPokemons); /* PAGINATION */ const paginationPokemon = () => { return pokemondata.slice(currentPage, currentPage + 12); }; /* PAGINATION */ const next = () => { dispatch(setCurrentPage(12)); }; const prev = () => { dispatch(setCurrentPage(-12)); }; /* PAGINATION */ useEffect(() => { if (pokemondata.length > 0) { dispatch(setPokemons(pokemondata)); } }), [pokemondata]; let content; if (pokemondata.length === 0) { content = <Spinner></Spinner>; } else { content = paginationPokemon() ?.slice() .map((pokemon) => ( <PokeCard key={pokemon.id} id={pokemon.id} name={pokemon.name} imgUrl={pokemon.imgUrl} typeOne={pokemon.typeOne} typeTwo={pokemon.typeTwo}></PokeCard> )); } return ( <> <div className='pagination'> {currentPage > 11 ? ( <button onClick={prev} className='pagination__button pagination__button-left'></button> ) : ( <div></div> )} {/* <h2>Page {page}</h2> */} {currentPage <= pokemondata.length - 12 ? ( <button onClick={next} className='pagination__button pagination__button-right'></button> ) : ( <div></div> )} </div> <main className='main__container'>{content}</main> </> ); } export default PokeList;
use crate::common::random::Random; use crate::model::board::Board; use crate::model::expansion_result::ExpansionResult; use crate::model::tree::Tree; use crate::model::types::TreeNodeIndex; use crate::move_generator::legal_moves::generate_moves; use crate::move_generator::make_move::make_move; pub fn expand( tree: &mut Tree, node_index: TreeNodeIndex, board: Board, random: &mut Random, ) -> ExpansionResult { let mut board = board; let node = tree.get_node_mut(node_index); if node.evaluation.is_conclusive() || node.is_not_visited() { return ExpansionResult { board, node_index }; } debug_assert!(node.child_indices.is_empty()); let moves = generate_moves(&mut board); for m in moves { let mut new_board = board.clone(); make_move(&mut new_board, &m); tree.add_node(new_board, m.clone(), node_index); } let node_index = *random .pick_element(&tree.get_node(node_index).child_indices) .expect( "there must be an expanded node if the parent was inconclusive", ); let last_move = tree.get_node(node_index).last_move; make_move(&mut board, &last_move); ExpansionResult { board, node_index } } #[cfg(test)] mod test { use crate::model::board::Board; use crate::model::board_evaluation::BoardEvaluation; use crate::model::r#move::Move; use crate::model::types::square_names::*; use super::*; #[test] fn it_does_not_expand_a_conclusive_node() { let mut tree = Tree::new(Board::new()); tree.get_node_mut(0).score.wins_white = 1; tree.get_node_mut(0).evaluation = BoardEvaluation::WinWhite; let mut random = Random::from_seed(111); assert_eq!( expand(&mut tree, 0, Board::new(), &mut random), ExpansionResult { board: Board::new(), node_index: 0 }, ); assert_eq!(tree.get_size(), 1); } #[test] fn it_does_not_expand_a_node_which_has_no_visits() { let mut tree = Tree::new(Board::new()); let mut random = Random::from_seed(111); assert_eq!( expand(&mut tree, 0, Board::new(), &mut random), ExpansionResult { board: Board::new(), node_index: 0 }, ); assert_eq!(tree.get_size(), 1); } #[test] #[should_panic] #[cfg(debug_assertions)] fn it_panics_when_trying_to_expand_a_node_with_children() { let mut tree = Tree::new(Board::new()); let mut random = Random::from_seed(111); tree.add_node(Board::new(), Move::from_to(0, 0), 0); tree.get_node_mut(0).score.wins_white = 1; expand(&mut tree, 0, Board::new(), &mut random); } #[test] fn it_expands_a_node_with_exactly_one_visit() { let mut tree = Tree::new(Board::new()); let mut random = Random::from_seed(111); tree.get_node_mut(0).score.wins_white = 1; expand(&mut tree, 0, Board::new(), &mut random); assert_eq!(tree.get_size(), 21); } #[test] fn it_expands_a_node_and_returns_an_updated_board() { let mut tree = Tree::new(Board::new()); let mut random = Random::from_seed(111); tree.add_node(Board::new(), Move::from_to(E2, E3), 0); tree.add_node(Board::new(), Move::from_to(F7, F6), 1); tree.add_node(Board::new(), Move::from_to(D1, H5), 2); tree.get_node_mut(3).score.wins_white = 1; assert_eq!( expand( &mut tree, 3, Board::from_fen( "rnbqkbnr/ppppp1pp/5p2/7Q/8/4P3/PPPP1PPP/RNB1KBNR b KQkq - 1 2", ), &mut random, ), ExpansionResult { board: Board::from_fen("rnbqkbnr/ppppp2p/5pp1/7Q/8/4P3/PPPP1PPP/RNB1KBNR w KQkq - 0 3"), node_index: 4, } ); assert_eq!(tree.get_size(), 5); } }
// Copyright 2021 The Brave Authors. All rights reserved. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. import BraveUI import Foundation import Strings import SwiftUI import UIKit enum CryptoTab: Equatable, Hashable, CaseIterable { case portfolio case activity case accounts case market @ViewBuilder var tabLabel: some View { switch self { case .portfolio: Label(Strings.Wallet.portfolioPageTitle, braveSystemImage: "leo.coins") case .activity: Label(Strings.Wallet.activityPageTitle, braveSystemImage: "leo.activity") case .accounts: Label(Strings.Wallet.accountsPageTitle, braveSystemImage: "leo.user.accounts") case .market: Label(Strings.Wallet.marketPageTitle, braveSystemImage: "leo.discover") } } } struct CryptoTabsView<DismissContent: ToolbarContent>: View { @ObservedObject var cryptoStore: CryptoStore @ObservedObject var keyringStore: KeyringStore var toolbarDismissContent: DismissContent @State private var isShowingMainMenu: Bool = false @State private var isTabShowingSettings: [CryptoTab: Bool] = CryptoTab.allCases.reduce( into: [CryptoTab: Bool]() ) { $0[$1] = false } @State private var isShowingSearch: Bool = false @State private var isShowingBackup: Bool = false @State private var isShowingAddAccount: Bool = false @State private var fetchedPendingRequestsThisSession: Bool = false @State private var selectedTab: CryptoTab = .portfolio @Environment(\.walletActionDestination) private var walletActionDestination: Binding<WalletActionDestination?> private var isConfirmationButtonVisible: Bool { if case .transactions(let txs) = cryptoStore.pendingRequest { return !txs.isEmpty } return cryptoStore.pendingRequest != nil } var body: some View { TabView(selection: $selectedTab) { NavigationView { PortfolioView( cryptoStore: cryptoStore, keyringStore: keyringStore, networkStore: cryptoStore.networkStore, portfolioStore: cryptoStore.portfolioStore ) .navigationTitle(Strings.Wallet.wallet) .navigationBarTitleDisplayMode(.inline) .transparentUnlessScrolledNavigationAppearance() .toolbar { sharedToolbarItems } .background(settingsNavigationLink(for: .portfolio)) } .navigationViewStyle(.stack) .tabItem { CryptoTab.portfolio.tabLabel } .tag(CryptoTab.portfolio) NavigationView { TransactionsActivityView( store: cryptoStore.transactionsActivityStore, networkStore: cryptoStore.networkStore ) .navigationTitle(Strings.Wallet.wallet) .navigationBarTitleDisplayMode(.inline) .applyRegularNavigationAppearance() .toolbar { sharedToolbarItems } .background(settingsNavigationLink(for: .activity)) } .navigationViewStyle(.stack) .tabItem { CryptoTab.activity.tabLabel } .tag(CryptoTab.activity) NavigationView { AccountsView( store: cryptoStore.accountsStore, cryptoStore: cryptoStore, keyringStore: keyringStore, walletActionDestination: walletActionDestination ) .navigationTitle(Strings.Wallet.wallet) .navigationBarTitleDisplayMode(.inline) .applyRegularNavigationAppearance() .toolbar { sharedToolbarItems } .background(settingsNavigationLink(for: .accounts)) } .navigationViewStyle(.stack) .tabItem { CryptoTab.accounts.tabLabel } .tag(CryptoTab.accounts) NavigationView { MarketView( cryptoStore: cryptoStore, keyringStore: keyringStore ) .navigationTitle(Strings.Wallet.wallet) .navigationBarTitleDisplayMode(.inline) .applyRegularNavigationAppearance() .toolbar { sharedToolbarItems } .background(settingsNavigationLink(for: .market)) } .navigationViewStyle(.stack) .tabItem { CryptoTab.market.tabLabel } .tag(CryptoTab.market) } .introspectTabBarController(customize: { tabBarController in let appearance = UITabBarAppearance() appearance.configureWithOpaqueBackground() appearance.backgroundColor = UIColor(braveSystemName: .containerBackground) tabBarController.tabBar.standardAppearance = appearance tabBarController.tabBar.scrollEdgeAppearance = appearance }) .overlay( alignment: .bottomTrailing, content: { if isConfirmationButtonVisible { Button { cryptoStore.isPresentingPendingRequest = true } label: { Image(braveSystemName: "leo.notification.dot") .font(.system(size: 18)) .foregroundColor(.white) .frame(width: 36, height: 36) .background( Color(uiColor: .braveBlurpleTint) .clipShape(Circle()) ) } .accessibilityLabel(Text(Strings.Wallet.confirmTransactionsTitle)) .padding(.trailing, 16) .padding(.bottom, 100) } } ) .onAppear { // If a user chooses not to confirm/reject their requests we shouldn't // do it again until they close and re-open wallet if !fetchedPendingRequestsThisSession { // Give the animation time DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { self.fetchedPendingRequestsThisSession = true self.cryptoStore.prepare(isInitialOpen: true) } } } .ignoresSafeArea() .background( Color.clear .sheet(isPresented: $cryptoStore.isPresentingAssetSearch) { AssetSearchView( keyringStore: keyringStore, cryptoStore: cryptoStore, userAssetsStore: cryptoStore.portfolioStore.userAssetsStore ) } ) .sheet(isPresented: $isShowingMainMenu) { MainMenuView( selectedTab: selectedTab, isShowingSettings: Binding( get: { self.isTabShowingSettings[selectedTab, default: false] }, set: { isActive, _ in self.isTabShowingSettings[selectedTab] = isActive } ), isShowingBackup: $isShowingBackup, isShowingAddAccount: $isShowingAddAccount, keyringStore: keyringStore ) .background( Color.clear .sheet( isPresented: Binding( get: { isShowingBackup }, set: { newValue in if !newValue { // dismiss menu if we're dismissing backup from menu isShowingMainMenu = false } isShowingBackup = newValue } ) ) { NavigationView { BackupWalletView( password: nil, keyringStore: keyringStore ) } .navigationViewStyle(.stack) .environment(\.modalPresentationMode, $isShowingBackup) .accentColor(Color(.braveBlurpleTint)) } ) .background( Color.clear .sheet( isPresented: Binding( get: { isShowingAddAccount }, set: { newValue in if !newValue { // dismiss menu if we're dismissing add account from menu isShowingMainMenu = false } isShowingAddAccount = newValue } ) ) { NavigationView { AddAccountView( keyringStore: keyringStore, networkStore: cryptoStore.networkStore ) } .navigationViewStyle(StackNavigationViewStyle()) } ) } } @ToolbarContentBuilder private var sharedToolbarItems: some ToolbarContent { ToolbarItemGroup(placement: .navigationBarTrailing) { if selectedTab == .portfolio { Button { cryptoStore.isPresentingAssetSearch = true } label: { Label(Strings.Wallet.searchTitle, systemImage: "magnifyingglass") .labelStyle(.iconOnly) .foregroundColor(Color(.braveBlurpleTint)) } } Button { self.isShowingMainMenu = true } label: { Label( Strings.Wallet.otherWalletActionsAccessibilityTitle, braveSystemImage: "leo.more.horizontal" ) .labelStyle(.iconOnly) .foregroundColor(Color(.braveBlurpleTint)) } .accessibilityLabel(Strings.Wallet.otherWalletActionsAccessibilityTitle) } toolbarDismissContent } private func settingsNavigationLink(for tab: CryptoTab) -> some View { NavigationLink( destination: Web3SettingsView( settingsStore: cryptoStore.settingsStore, networkStore: cryptoStore.networkStore, keyringStore: keyringStore ), isActive: Binding( get: { self.isTabShowingSettings[tab, default: false] }, set: { isActive, _ in self.isTabShowingSettings[tab] = isActive } ) ) { Text(Strings.Wallet.settings) } .hidden() } }
#include "variadic_functions.h" #include <stdlib.h> #include <stdio.h> #include <stdarg.h> /** * print_numbers - print numbers * @separator: string to be printed between numbers * @n: number of integers passed to the fonction */ void print_numbers(const char *separator, const unsigned int n, ...) { unsigned int i; int x = 0; va_list num; va_start(num, n); for (i = 0; i < n; i++) { x = va_arg(num, unsigned int); printf("%d", x); if (i < (n - 1) && separator) { printf("%s", separator); } } printf("\n"); va_end(num); }
import * as React from 'react'; import AppBar from '@mui/material/AppBar'; import Box from '@mui/material/Box'; import CssBaseline from '@mui/material/CssBaseline'; import Divider from '@mui/material/Divider'; import Drawer from '@mui/material/Drawer'; import IconButton from '@mui/material/IconButton'; import InboxIcon from '@mui/icons-material/MoveToInbox'; import List from '@mui/material/List'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import MailIcon from '@mui/icons-material/Mail'; import MenuIcon from '@mui/icons-material/Menu'; import Toolbar from '@mui/material/Toolbar'; import { Button, CircularProgress } from '@mui/material'; import HomeIcon from '@mui/icons-material/Home'; import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings'; import ReviewsIcon from '@mui/icons-material/Reviews'; import { Route, Switch, useHistory, useRouteMatch } from 'react-router'; import useAuth from '../../../hooks/useAuth/useAuth'; import MyOrder from '../MyOrder/MyOrder'; import MakeAdmin from "../MakeAdmin/MakeAdmin" import DashboardHome from "../DashboardHome/DashboardHome" import { NavLink } from 'react-router-dom'; import ManageOrder from '../ManageOrder/ManageOrder'; import ReviewsWrite from '../ReviewsWrite/ReviewsWrite'; import ManageProduct from '../ManageProduct/ManageProduct'; import RiceBowlTwoToneIcon from '@mui/icons-material/RiceBowlTwoTone'; import ShoppingBagTwoToneIcon from '@mui/icons-material/ShoppingBagTwoTone'; import WorkspacesTwoToneIcon from '@mui/icons-material/WorkspacesTwoTone'; import AdminRoute from '../../AdminRoute/AdminRoute'; import AddCircleIcon from '@mui/icons-material/AddCircle'; import AddNewCycle from '../AddNewCycle/AddNewCycle'; import PaymentSharpIcon from '@mui/icons-material/PaymentSharp'; import Payment from '../Payment/Payment'; const drawerWidth = 240; const Dashboard = (props) => { let { path, url } = useRouteMatch(); const [databaseUser, setDatabaseUser] = React.useState(null); const history = useHistory(); const {user, logOut} = useAuth(); React.useEffect(()=>{ if(user){ fetch(`https://boiling-island-95834.herokuapp.com/users/${user.email}`) .then(res => res.json()) .then(data => setDatabaseUser(data)) } },[user]); const { window } = props; const [mobileOpen, setMobileOpen] = React.useState(false); const handleDrawerToggle = () => { setMobileOpen(!mobileOpen); }; const handelLink = (path) => { history.push(path); } const drawer = ( <div> <Toolbar /> <Divider /> <List> { databaseUser ? <> <ListItem as={NavLink} to={`${url}/main`} activeClassName='active-dashboard' > <ListItemIcon> <HomeIcon className="dashboard-icon" /> </ListItemIcon> <ListItemText sx={{fontWeight:"bold"}} primary="Dashboard" className="dashboard-menu-list" /> </ListItem> { databaseUser?.userRole?.toLowerCase() === "admin" ? <ListItem as={NavLink} to={`${url}/manage-order`} activeClassName='active-dashboard' > <ListItemIcon> <WorkspacesTwoToneIcon className="dashboard-icon" /> </ListItemIcon> <ListItemText sx={{fontWeight:"bold"}} primary="Manage Order" className="dashboard-menu-list" /> </ListItem> : <ListItem as={NavLink} to={`${url}/my-order`} activeClassName='active-dashboard' > <ListItemIcon> <ShoppingBagTwoToneIcon className="dashboard-icon" /> </ListItemIcon> <ListItemText sx={{fontWeight:"bold"}} primary="My Order" className="dashboard-menu-list" /> </ListItem> } { databaseUser.userRole !== 'admin' && <ListItem as={NavLink} to={`${url}/payment`} activeClassName='active-dashboard' > <ListItemIcon> <PaymentSharpIcon className="dashboard-icon" /> </ListItemIcon> <ListItemText sx={{fontWeight:"bold"}} primary="Payment" className="dashboard-menu-list" /> </ListItem> } { databaseUser?.userRole === "admin" && <ListItem as={NavLink} to={`${url}/make-admin`} activeClassName='active-dashboard' > <ListItemIcon> <AdminPanelSettingsIcon className="dashboard-icon" /> </ListItemIcon> <ListItemText sx={{fontWeight:"bold"}} primary="Make Admin" className="dashboard-menu-list" /> </ListItem> } { databaseUser?.userRole ==="admin" && <ListItem as={NavLink} to={`${url}/manage-products`} activeClassName='active-dashboard' > <ListItemIcon> <RiceBowlTwoToneIcon className="dashboard-icon" /> </ListItemIcon> <ListItemText sx={{fontWeight:"bold"}} primary="Manage Products" className="dashboard-menu-list" /> </ListItem> } { databaseUser?.userRole === "admin" && <ListItem as={NavLink} to={`${url}/add-new-bike`} activeClassName='active-dashboard' > <ListItemIcon> <AddCircleIcon className="dashboard-icon" /> </ListItemIcon> <ListItemText sx={{fontWeight:"bold"}} primary="Add a Cycle" className="dashboard-menu-list" /> </ListItem> } <ListItem as={NavLink} to={`${url}/reviews`} activeClassName='active-dashboard' > <ListItemIcon> <ReviewsIcon className="dashboard-icon" /> </ListItemIcon> <ListItemText sx={{fontWeight:"bold"}} primary="Write Reviews" className="dashboard-menu-list" /> </ListItem> </> : <Box sx={{ display: 'flex', justifyContent:"center", py:5 }}> <CircularProgress sx={{width:"20px"}} /> </Box> } </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon> {index % 2 === 0 ? <InboxIcon /> : <MailIcon />} </ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </div> ); const container = window !== undefined ? () => window().document.body : undefined; return ( <> <Box sx={{ display: 'flex' }}> <CssBaseline /> <AppBar position="fixed" sx={{ width: { sm: `calc(100% - ${drawerWidth}px)` }, ml: { sm: `${drawerWidth}px` }, }} > <Toolbar> <IconButton color="inherit" aria-label="open drawer" edge="start" onClick={handleDrawerToggle} sx={{ mr: 2, display: { sm: 'none' } }} > <MenuIcon /> </IconButton> <Box sx={{flexGrow:1}}> <Box sx={{display:"flex", justifyContent:"flex-end"}}> <Button onClick={()=> handelLink("/home")} variant="initial">Home</Button> { user ? <Button onClick={()=> logOut("/")} variant="initial">Log Out</Button> : <Button onClick={()=> handelLink("/login")} variant="initial">LogIn</Button> } </Box> </Box> </Toolbar> </AppBar> <Box component="nav" sx={{ width: { sm: drawerWidth }, flexShrink: { sm: 0 } }} aria-label="mailbox folders" > <Drawer container={container} variant="temporary" open={mobileOpen} onClose={handleDrawerToggle} ModalProps={{ keepMounted: true, // Better open performance on mobile. }} sx={{ display: { xs: 'block', sm: 'none' }, '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth }, }} > {drawer} </Drawer> <Drawer variant="permanent" sx={{ display: { xs: 'none', sm: 'block' }, '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth }, }} open > {drawer} </Drawer> </Box> <Box component="main" sx={{ flexGrow: 1, p: 3, width: { sm: `calc(100% - ${drawerWidth}px)` } }} > <Toolbar /> <Switch> <Route exact path={`${path}`}> <DashboardHome /> </Route> <Route exact path={`${path}/main`}> <DashboardHome /> </Route> <Route path={`${path}/my-order`}> <MyOrder /> </Route> <Route path={`${path}/payment`}> <Payment /> </Route> <AdminRoute path={`${path}/manage-order`}> <ManageOrder /> </AdminRoute> <AdminRoute path={`${path}/make-admin`}> <MakeAdmin /> </AdminRoute> <Route path={`${path}/reviews`}> <ReviewsWrite /> </Route> <AdminRoute path={`${path}/manage-products`}> <ManageProduct /> </AdminRoute> <AdminRoute path={`${path}/add-new-bike`}> <AddNewCycle /> </AdminRoute> </Switch> </Box> </Box> </> ); } export default Dashboard;
import scrapy from scrapy.http import HtmlResponse from items import JobparserItem class SjruSpider(scrapy.Spider): name = 'sjru' allowed_domains = ['superjob.ru'] start_urls = ['https://www.superjob.ru/vacancy/search/?keywords=python&geo%5Bt%5D%5B0%5D=4'] def parse(self, response): links = response.xpath("//div[@class='f-test-search-result-item']//a[contains(@class, 'icMQ_')]/@href").getall() next_page = response.xpath("//a[@rel='next']/@href").get() if next_page: yield response.follow(next_page, callback=self.parse) for link in links: yield response.follow(link, callback=self.parse_vacancy) def parse_vacancy(self, response: HtmlResponse): vac_name = response.xpath("//h1/text()").get() vac_salary = response.xpath("//div[contains(@class, 'test-address')]/parent::div/span//text()").getall() vac_url = response.url yield JobparserItem(name=vac_name, salary=vac_salary, url=vac_url)
import React, { useEffect, useState } from "react"; import { ReactComponent as SearchIcon } from "assets/icons/search.svg"; import { fetchMovies } from "api"; import { createPortal } from "react-dom"; import Overlay from "components/overlay"; import { useSearchParams } from "react-router-dom"; function SearchInput({ setData }) { const [loading, setLoading] = useState(false); const [searchParams, setSearchParams] = useSearchParams(); const [searchValue, setSearchValue] = useState(""); const handleSubmit = async (e) => { e.preventDefault(); setLoading(true); const { data } = await fetchMovies({ search: searchValue, page: 1 }); setSearchParams((prevSearchParams) => { const newSearchParams = new URLSearchParams(prevSearchParams); newSearchParams.set("search", searchValue); newSearchParams.set("page", newSearchParams.get("page") || 1); return newSearchParams; }); setData(data); setTimeout(() => { setLoading(false); //set little bit late to showcase loading }, 100); }; useEffect(() => { if (searchParams.get("search")) { setSearchValue(searchParams.get("search")); } }, []); return ( <> <form onSubmit={handleSubmit} className="mt-5 flex justify-center"> <div className="relative"> <div className="absolute inset-y-0 left-0 flex items-center pl-6 pointer-events-none"> <SearchIcon className="w-4.5 h-4.5 fill-primary" /> </div> <input id="search" value={searchValue} onChange={(e) => setSearchValue(e.target.value)} type="search" className="block lg:w-[512px] w-full rounded-2xl pt-4.5 pb-4 pl-14 pr-6 text-slate-100 text-base md:text-lg lg:text-xl border border-transparent placeholder-[#475569] bg-slate-900 focus:border-sky-200" placeholder="Search for your next movie." required /> </div> </form> {loading && createPortal(<Overlay />, document.body)} </> ); } export default SearchInput;
// import { Link } from 'react-router-dom' import React from 'react'; import Faq from "../Faq/index"; import { useNavigate } from "react-router-dom"; import "../../globals.css"; import { BookOpenIcon, ClockIcon, ChatBubbleBottomCenterIcon, FingerPrintIcon, } from "@heroicons/react/24/outline"; // import ChatbotAI from '../../components/chatbotAI' const features = [ { name: "CBT Sessions", description: "With our bot, KelvinAI, we offer a guider to walk you through Cognitive Behavioral Therapy sessions.", icon: ChatBubbleBottomCenterIcon, }, { name: "Journaling", description: "We provide a journaling feature to help you track your thoughts and feelings, and identify patterns in your behavior.", icon: BookOpenIcon, }, { name: "Meditation Timer", description: "Our meditation timer and guides help you to practice mindfulness and reduce stress and anxiety.", icon: ClockIcon, }, { name: "Personalized Dashboard", description: "We offer a personalized dashboard to help you track your progress and set goals for your mental health journey.", icon: FingerPrintIcon, }, ]; export default function Template() { const navigate = useNavigate(); return ( <main> <section id="HeroSection" className="bg-white py-12 lg:py-36"> <div className="container grid items-center justify-center gap-4 px-4 text-center md:gap-8 lg:px-6"> <svg className="hidden md:absolute md:block left-0 xl:right-24 inset-0 z-10 h-full w-full stroke-gray-300 [mask-image:radial-gradient(100%_100%_at_top_right,white,transparent)]" aria-hidden="true" > <defs> <pattern id="0787a7c5-978c-4f66-83c7-11c213f99cb7" width={200} height={200} x="50%" y={-1} patternUnits="userSpaceOnUse" > <path d="M.5 200V.5H200" fill="none" /> </pattern> </defs> <rect width="100%" height="100%" strokeWidth={0} fill="url(#0787a7c5-978c-4f66-83c7-11c213f99cb7)" /> </svg> <div className="space-y-2 mx-auto flex flex-col gap-4 justify-center items-center"> <h1 className="z-10 font-bold tracking-tighter text-5xl md:text-7xl lg:text-7xl"> Free Mental Health Support </h1> <p className="z-10 mx-auto font-medium max-w-2xl text-gray-600 md:text-xl lg:text-base xl:text-xl dark:text-gray-400 mt-11"> Explore our comprehensive library of resources designed to improve your mental well-being without the cost barrier. </p> </div> </div> </section> <section id="MissionStatement z-50"> <div className="bg-white py-24 sm:py-32"> <div className="mx-auto max-w-7xl px-6 lg:px-8"> <div className="mx-auto grid max-w-2xl grid-cols-1 items-start gap-x-8 gap-y-16 sm:gap-y-24 lg:mx-0 lg:max-w-none lg:grid-cols-2"> <div className="lg:pr-4"> <div className="relative overflow-hidden rounded-3xl bg-gray-900 px-6 pb-9 pt-64 shadow-2xl sm:px-12 lg:max-w-lg lg:px-8 lg:pb-8 xl:px-10 xl:pb-10"> <img className="absolute inset-0 h-full w-full object-cover brightness-125 saturate-0" src="https://images.unsplash.com/photo-1630569267625-157f8f9d1a7e?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2669&q=80" alt="" /> <div className="absolute inset-0 bg-gray-900 mix-blend-multiply" /> <div className="absolute left-1/2 top-1/2 -ml-16 -translate-x-1/2 -translate-y-1/2 transform-gpu blur-3xl" aria-hidden="true" > <div className="aspect-[1097/845] w-[68.5625rem] bg-gradient-to-tr from-[#ff4694] to-[#776fff] opacity-40" style={{ clipPath: "polygon(74.1% 44.1%, 100% 61.6%, 97.5% 26.9%, 85.5% 0.1%, 80.7% 2%, 72.5% 32.5%, 60.2% 62.4%, 52.4% 68.1%, 47.5% 58.3%, 45.2% 34.5%, 27.5% 76.7%, 0.1% 64.9%, 17.9% 100%, 27.6% 76.8%, 76.1% 97.7%, 74.1% 44.1%)", }} /> </div> <figure className="relative isolate"> <blockquote className="mt-6 text-xl font-semibold leading-8 text-white"> <p> “Studies have found CBT to be very effective for treating less severe forms of depression, anxiety, post-traumatic stress disorder (PTSD), and other conditions.” </p> </blockquote> <figcaption className="mt-6 text-sm leading-6 text-gray-300"> <strong className="font-semibold text-white"> Gerald Gartlehner (June 2017) </strong> {"\n"} <br></br> Physician, health scientiest, and clinical epidemiologist. </figcaption> </figure> </div> </div> <div> <div className="text-base leading-7 text-gray-700 lg:max-w-lg"> <p className="text-base font-semibold leading-7 text-indigo-600"> Our Mission </p> <h1 className="mt-2 text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl"> Make mental health accessible. </h1> <div className="max-w-xl"> <p className="mt-6"> Therapy has been proven to be an effective way to improve mental health and well-being. However, the cost of therapy can be a barrier for many people. Our mission is to provide free mental health resources to everyone, regardless of their financial situation. </p> <p className="mt-8"> We provide educational content on mental health and therapy strategies, aiming to educate and empower individuals to take control of their mental health. Additionally, we offer services such as cognitive behavioral therapy, meditation timers, and journaling prompts. </p> <p className="mt-8"></p> </div> </div> <div className="mt-10 flex"> <a href="#" className="text-base font-semibold leading-7 text-indigo-600" > {" "} <span aria-hidden="true" onClick={() => { navigate("/dashboard"); }} > Get Started &rarr; </span> </a> </div> </div> </div> </div> </div> </section> <div className="bg-white py-24 sm:py-32"> <div className="mx-auto max-w-7xl px-6 lg:px-8"> <div className="mx-auto max-w-2xl lg:text-center"> <h2 className="text-base font-semibold leading-7 text-indigo-600"></h2> <p className="mt-2 text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl"> Resources to help you thrive. </p> <p className="mt-6 text-lg leading-8 text-gray-600"> On our services page, you can find a variety of resources used to assist in mental wellness. </p> </div> <div className="mx-auto mt-16 max-w-2xl sm:mt-20 lg:mt-24 lg:max-w-4xl"> <dl className="grid max-w-xl grid-cols-1 gap-x-8 gap-y-10 lg:max-w-none lg:grid-cols-2 lg:gap-y-16"> {features.map((feature) => ( <div key={feature.name} className="relative pl-16"> <dt className="text-base font-semibold leading-7 text-gray-900"> <div className="absolute left-0 top-0 flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-600"> <feature.icon className="h-6 w-6 text-white" aria-hidden="true" /> </div> {feature.name} </dt> <dd className="mt-2 text-base leading-7 text-gray-600"> {feature.description} </dd> </div> ))} </dl> </div> </div> </div> <Faq /> <section style={{ height: "20vh" }} className="w-full flex justify-center items-center" > {" "} <span aria-hidden="true" className="cursor-pointer" onClick={() => { navigate("/dashboard"); }} > Get Started &rarr; </span> </section> </main> ); }
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:roadcare/pages/login/auth_page.dart'; import 'package:roadcare/pages//user/report_detail_page.dart'; import 'package:roadcare/services/auth_service.dart'; class HomePage extends StatefulWidget { HomePage({super.key}); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { final user = FirebaseAuth.instance.currentUser!; static const LatLng _center = LatLng(3.252161672150421, 101.73425857314945); Set<Marker> _markers = {}; String _selectedStatus = 'All'; // Initial filter value @override void initState() { super.initState(); _fetchReports(_selectedStatus); } void _fetchReports(String statusFilter) async { QuerySnapshot querySnapshot; if (statusFilter == 'All') { querySnapshot = await FirebaseFirestore.instance.collection('reports').get(); } else { querySnapshot = await FirebaseFirestore.instance.collection('reports').where('status', isEqualTo: statusFilter).get(); } setState(() { _markers = querySnapshot.docs.map((doc) { var data = doc.data() as Map<String, dynamic>; return Marker( markerId: MarkerId(doc.id), position: LatLng(data['latitude'], data['longitude']), infoWindow: InfoWindow( title: data['status'], snippet: 'Severity: ${data['severity']}', onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => ReportDetailPage( imageUrl: data['imageUrl'], status: data['status'], severity: data['severity'], description: data['description'] ?? '', ), )); }, ), icon: data['status'] == 'Fixed' ? BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen) // Use green for "Fixed" : BitmapDescriptor.defaultMarker, ); }).toSet(); }); } void _onFilterChanged(String? newValue) { if (newValue != null) { setState(() { _selectedStatus = newValue; }); _fetchReports(newValue); } } void signUserOut(BuildContext context) async { try { // Use AuthService to sign out from both Firebase and Google await AuthService().signOut(); // Navigate to the login screen and remove all routes from the stack Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => AuthPage()), (Route<dynamic> route) => false, ); } catch (error) { print("Error signing out: $error"); // Optionally, show an error message to the user } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: SizedBox( width: 70, height: 70, child: Image.asset('lib/images/IIUMRoadCareLogo.png'), ), centerTitle: true, actions: [ IconButton( onPressed: () => signUserOut(context), icon: const Icon(Icons.logout), ), ], ), body: Stack( children: [ GoogleMap( initialCameraPosition: CameraPosition( target: _center, zoom: 16, ), markers: _markers, ), Positioned( top: 10, right: 10, child: Material( elevation: 8.0, borderRadius: BorderRadius.circular(8), child: Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8), ), child: DropdownButton<String>( value: _selectedStatus, items: <String>['All', 'Pending', 'Fixed'].map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text(value), ); }).toList(), onChanged: _onFilterChanged, underline: Container(), isDense: true, iconSize: 24, ), ), ), ) ], ), ); } }
<?php namespace frontend\modules\admin\models; use yii\base\Model; use yii\data\ActiveDataProvider; use app\models\Brands as BrandsModel; /** * Brands represents the model behind the search form of `app\models\Brands`. */ class Brands extends BrandsModel { /** * {@inheritdoc} */ public function rules() { return [ [['id'], 'integer'], [['Brand', 'Label'], 'safe'], ]; } /** * {@inheritdoc} */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = BrandsModel::find(); // add conditions that should always apply here $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } // grid filtering conditions $query->andFilterWhere([ 'id' => $this->id, ]); $query->andFilterWhere(['like', 'Brand', $this->Brand]) ->andFilterWhere(['like', 'Label', $this->Label]); return $dataProvider; } }
import {Body, Controller, Get, Post, Req, Res} from "@nestjs/common"; import {Request, Response} from "express"; import {UsersService, LoginException, AuthInfo} from "./users.service"; export interface LoginResponse { type: "error" | "success"; content: string; } export interface LoginDto { login?: string; password?: string; } export interface LogoutResponse { type: "success"; } @Controller("api/users") export class UsersController { constructor(private readonly usersService: UsersService) {} @Post("login") public async login(@Res({passthrough: true}) res: Response, @Body() body: LoginDto): Promise<LoginResponse> { const login: string = body.login ?? ""; const password: string = body.password ?? ""; try { await this.usersService.login({ login, password, onAuth: (id, token) => { res.cookie("Auth-Id", id); res.cookie("Auth-Token", token); } }); return {type: "success", content: ""}; } catch (error) { if (error instanceof LoginException) return {type: "error", content: error.message}; else throw error; } } @Post("logout") public logout(@Res({passthrough: true}) res: Response): LogoutResponse { res.clearCookie("Auth-Id"); res.clearCookie("Auth-Token"); return {type: "success"}; } @Get("auth") public getAuthInfo(@Req() req: Request): Promise<AuthInfo> { const id: number = Number(req.cookies["Auth-Id"] ?? 0); const token: string = req.cookies["Auth-Token"] ?? ""; return this.usersService.getAuthInfo({id, token}); } }
// contracts/GLDToken.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.5; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20SnapshotUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/presets/ERC20PresetMinterPauserUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; contract TestToken is ERC20PresetMinterPauserUpgradeable, ERC20SnapshotUpgradeable, OwnableUpgradeable { function initializeToken(uint256 initialSupply) public initializer { __Ownable_init(); __ERC20Snapshot_init(); __ERC20PresetMinterPauser_init("Shadow Coder Project", "TEST"); _mint(msg.sender, initialSupply); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override ( ERC20SnapshotUpgradeable, ERC20PresetMinterPauserUpgradeable ) { super._beforeTokenTransfer(from, to, amount); } function createSnapshot() public virtual returns (uint256) { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to snapshot" ); return _snapshot(); } }
from contextlib import asynccontextmanager from typing import AsyncIterator from fastapi import FastAPI from apps.dataset_processor.db_service import DatasetDbService from apps.dataset_processor.router import router as dataset_router from config.main import settings @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: await DatasetDbService().initialize_database() yield app = FastAPI( lifespan=lifespan, debug=settings.DEBUG, title=settings.PROJECT_NAME, description=f'{settings.PROJECT_NAME} API documentation', docs_url='/swagger', redoc_url=None, version='v1', ) app.include_router(dataset_router)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> div { width: 300px; height: 100px; margin: 10px; padding: 10px; border: 10px solid green; } .box-cb { box-sizing: content-box; /*content 박스 기준으로 박스 사이즈 결정하겠다는 것*/ } .box-bb { box-sizing: border-box; /*border까지 포함한 걸 기준으로 박스 사이즈 결정하겠다는 것*/ } /*f12눌러 개발자모드로 봐서 상세 속성 보기*/ /*px 단위*/ /*퍼센트(백분율). 부모 요소를 기준으로 상대값 결정*/ </style> </head> <body> <div class="box-cb">CSS 박스 모델- content-box</div> <div class="box-bb">CSS 박스 모델- border-box</div> <div style="width: 100%; height: 200px; background-color: green"> <div style=" width: 50%; max-width: 900px; min-width: 200px; height: 50%; background-color: red; " ></div> <!--최대,최소 크기 지정 가능--> </div> </body> </html>
package com.bwell.sampleapp.repository import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.bwell.BWellSdk import com.bwell.common.models.domain.user.Person import com.bwell.common.models.responses.BWellResult import com.bwell.common.models.responses.OperationOutcome import com.bwell.common.models.responses.Status import com.bwell.sampleapp.R import com.bwell.sampleapp.model.ActivityListItems import com.bwell.sampleapp.model.DataConnectionCategoriesListItems import com.bwell.sampleapp.model.HealthJourneyList import com.bwell.sampleapp.model.HealthJourneyListItems import com.bwell.sampleapp.model.HealthSummaryList import com.bwell.sampleapp.model.HealthSummaryListItems import com.bwell.sampleapp.model.LabsList import com.bwell.sampleapp.model.LabsListItems import com.bwell.sampleapp.model.SuggestedActivitiesLIst import com.bwell.sampleapp.model.SuggestedDataConnectionsCategoriesList import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class Repository(private val applicationContext: Context) { private val suggestedActivitiesLiveData = MutableLiveData<SuggestedActivitiesLIst>() val suggestedActivities: LiveData<SuggestedActivitiesLIst> get() = suggestedActivitiesLiveData private val suggestedDataConnectionsCategoriesLiveData = MutableLiveData<SuggestedDataConnectionsCategoriesList>() val suggestedDataConnectionsCategories: LiveData<SuggestedDataConnectionsCategoriesList> get() = suggestedDataConnectionsCategoriesLiveData private val labsLiveData = MutableLiveData<LabsList>() val labs: LiveData<LabsList> get() = labsLiveData private val healthJourneyLiveData = MutableLiveData<HealthJourneyList>() val healthJourney: LiveData<HealthJourneyList> get() = healthJourneyLiveData suspend fun saveUserProfile(person: Person): Flow<BWellResult<Person>?> = flow { var operationOutcome: BWellResult<Person>? = BWellSdk.user?.updateProfile(person) emit(operationOutcome) } suspend fun fetchUserProfile(): Flow<BWellResult<Person>?> = flow { val profileData = BWellSdk.user?.getProfile() if(profileData?.operationOutcome?.status==Status.SUCCESS){ emit(profileData) } } suspend fun registerDeviceToken(deviceToken: String): Flow<OperationOutcome?> = flow { try { val outcome: OperationOutcome? = BWellSdk.device?.registerDeviceToken(deviceToken) emit(outcome) } catch (e: Exception) { // Handle exceptions } } suspend fun unregisterDeviceToken(deviceToken: String): Flow<OperationOutcome?> = flow { try { val outcome: OperationOutcome? = BWellSdk.device?.deregisterDeviceToken(deviceToken) emit(outcome) } catch (e: Exception) { // Handle exceptions } } suspend fun getActivitiesSuggestionList() { val suggestionsList = mutableListOf<ActivityListItems>() suggestionsList.add( ActivityListItems( applicationContext.getString(R.string.connect_your_care_providers), applicationContext.getString( R.string.your_healthcare_providers_store_lots_of_important_information_about_your_health ), R.drawable.circle ) ) suggestionsList.add( ActivityListItems( applicationContext.getString(R.string.build_your_care_team), applicationContext.getString( R.string.having_a_team_of_healthcare_providers_you_trust_helps_you_get_the_best_care_possible ), R.drawable.plus_icon ) ) suggestionsList.add( ActivityListItems( applicationContext.getString(R.string.build_your_care_team), applicationContext.getString( R.string.having_a_team_of_healthcare_providers_you_trust_helps_you_get_the_best_care_possible ), R.drawable.ic_placeholder ) ) suggestionsList.add( ActivityListItems( applicationContext.getString(R.string.build_your_care_team), applicationContext.getString( R.string.having_a_team_of_healthcare_providers_you_trust_helps_you_get_the_best_care_possible ), R.drawable.vaccine_icon ) ) suggestionsList.add( ActivityListItems( applicationContext.getString(R.string.build_your_care_team), applicationContext.getString( R.string.having_a_team_of_healthcare_providers_you_trust_helps_you_get_the_best_care_possible ), R.drawable.circle ) ) suggestionsList.add( ActivityListItems( applicationContext.getString(R.string.find_a_primary_care_provider_you), applicationContext.getString( R.string.a_primary_care_provider_is_a_healthcare_professional_who_helps ), R.drawable.vaccine_icon ) ) val activityList = SuggestedActivitiesLIst(suggestionsList) suggestedActivitiesLiveData.postValue(activityList) } suspend fun getDataConnectionsCategoriesList() { val suggestionsList = mutableListOf<DataConnectionCategoriesListItems>() // Category A suggestionsList.add( DataConnectionCategoriesListItems( "Insurance", R.drawable.circle, "Get your claims and financials, plus a record of the providers you see from common insurance plans and Medicare." ) ) suggestionsList.add( DataConnectionCategoriesListItems( "Providers", R.drawable.plus_icon, "See your core health info, such as provider visit summaries, diagnosis, treatment history, prescriptions, and labs." ) ) suggestionsList.add( DataConnectionCategoriesListItems( "Clinics, Hospitals and Health Systems", R.drawable.ic_placeholder, "See your core health info, such as your diagnosis, procedures, treatment history, prescriptions, and labs." ) ) suggestionsList.add( DataConnectionCategoriesListItems( "Labs", R.drawable.vaccine_icon, "View your lab results to track your numbers over time." ) ) val activityList = SuggestedDataConnectionsCategoriesList(suggestionsList) suggestedDataConnectionsCategoriesLiveData.postValue(activityList) } suspend fun getLabsList() { val suggestionsList = mutableListOf<LabsListItems>() // Category A suggestionsList.add( LabsListItems( "SARS-cov+SARS-cov-2(Covid-19) Ag [Presence] in Respiratory specimen by rapid immunoassay", "26/10/2023","Detected" ) ) suggestionsList.add( LabsListItems( "Blood Group", "26/10/2023","Group AB" ) ) suggestionsList.add( LabsListItems( "Rh in Blood", "26/10/2023","Positive" ) ) suggestionsList.add( LabsListItems( "UROBILINOGEN", "26/10/2023","0.3 mg/dl" ) ) val activityList = LabsList(suggestionsList) labsLiveData.postValue(activityList) } suspend fun getHealthJourneyList() { val suggestionsList = mutableListOf<HealthJourneyListItems>() // Category A suggestionsList.add( HealthJourneyListItems( "Connect Your Care Providers", R.drawable.vaccine_icon, "Get all your health data from different provider portals in one place" ,R.drawable.baseline_keyboard_arrow_right_24 ) ) suggestionsList.add( HealthJourneyListItems( "Build Your Care Team", R.drawable.circle, "Keep a list of all the providers you've seen",R.drawable.baseline_keyboard_arrow_right_24 ) ) suggestionsList.add( HealthJourneyListItems( "Find a Primary Care Provider You Can Trust", R.drawable.plus_icon, "A primary care provider is a partner in your health",R.drawable.baseline_keyboard_arrow_right_24 ) ) suggestionsList.add( HealthJourneyListItems( "Live a Heart Healthy Lifestyle", R.drawable.ic_placeholder, "Habits to build into your everyday life to keep your heart and blood vessels healthy",R.drawable.baseline_keyboard_arrow_right_24 ) ) val activityList = HealthJourneyList(suggestionsList) healthJourneyLiveData.postValue(activityList) } }
import { useEffect, useState, useMemo } from "react"; import "react-datepicker/dist/react-datepicker.css"; import "./style/style.scss"; import CatItems from "./components/CatItems"; import CatFilter from "./components/CatFilter"; function App() { const [cashbackData, setCashbackData] = useState({}); // cashback const [infoLoading, setInfoLoading] = useState(false); // cashback loading const [isEmpty, setIsEmpty] = useState(false); // is empty data const [filter, setFilter] = useState({ query: "" }); // filter cashback // -------------- functions ---------------- const fetchCashback = async (url) => { setInfoLoading(true); try { const response = await fetch(url); const data = await response.json(); setCashbackData(data); setIsEmpty(Object.keys(data).length === 0); setInfoLoading(false); } catch (error) { console.error("Произошла ошибка при выполнении запроса:", error); setIsEmpty(true); setInfoLoading(false); } }; const generateUrl = (date) => { const year = date.getFullYear(); const month = date.getMonth() + 1; const apiUrl = `https://abc-peregrinusss.squidass.com/api/cashbacks/${year}.${month}`; return apiUrl; }; const searchedCashback = useMemo(() => { const result = {}; Object.keys(cashbackData).forEach((key) => { const cashbackList = cashbackData[key].cashbacks; const filteredItems = cashbackList.filter((item) => { const lowercaseQuery = filter.query.toLowerCase(); const categoryData = item.category.name.toLowerCase(); return categoryData.includes(lowercaseQuery); }); if (filteredItems.length > 0) { result[key] = { cashbacks: filteredItems, cards: cashbackData[key].cards || [], }; } }); setIsEmpty(Object.keys(result).length === 0); return result; }, [filter.query, cashbackData]); // -------------- /functions ---------------- // set current month and data useEffect(() => { const dateNow = new Date(); const apiUrl = generateUrl(dateNow); fetchCashback(apiUrl); }, []); return ( <div className="cat"> <div id="bg-wrap"> <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice"> <defs> <radialGradient id="Gradient1" cx="50%" cy="50%" fx="0.441602%" fy="50%" r=".5" > <animate attributeName="fx" dur="190.4s" values="0%;3%;0%" repeatCount="indefinite" ></animate> <stop offset="0%" stopColor="rgba(255, 0, 255, 1)"></stop> <stop offset="100%" stopColor="rgba(255, 0, 255, 0)"></stop> </radialGradient> <radialGradient id="Gradient2" cx="50%" cy="50%" fx="2.68147%" fy="50%" r=".5" > <animate attributeName="fx" dur="134s" values="0%;3%;0%" repeatCount="indefinite" ></animate> <stop offset="0%" stopColor="rgba(255, 255, 0, 1)"></stop> <stop offset="100%" stopColor="rgba(255, 255, 0, 0)"></stop> </radialGradient> <radialGradient id="Gradient3" cx="50%" cy="50%" fx="0.836536%" fy="50%" r=".5" > <animate attributeName="fx" dur="121.6s" values="0%;3%;0%" repeatCount="indefinite" ></animate> <stop offset="0%" stopColor="rgba(0, 255, 255, 1)"></stop> <stop offset="100%" stopColor="rgba(0, 255, 255, 0)"></stop> </radialGradient> <radialGradient id="Gradient4" cx="50%" cy="50%" fx="4.56417%" fy="50%" r=".5" > <animate attributeName="fx" dur="128.8s" values="0%;5%;0%" repeatCount="indefinite" ></animate> <stop offset="0%" stopColor="rgba(0, 255, 0, 1)"></stop> <stop offset="100%" stopColor="rgba(0, 255, 0, 0)"></stop> </radialGradient> <radialGradient id="Gradient5" cx="50%" cy="50%" fx="2.65405%" fy="50%" r=".5" > <animate attributeName="fx" dur="137.2s" values="0%;5%;0%" repeatCount="indefinite" ></animate> <stop offset="0%" stopColor="rgba(0,0,255, 1)"></stop> <stop offset="100%" stopColor="rgba(0,0,255, 0)"></stop> </radialGradient> <radialGradient id="Gradient6" cx="50%" cy="50%" fx="0.981338%" fy="50%" r=".5" > <animate attributeName="fx" dur="142.8s" values="0%;5%;0%" repeatCount="indefinite" ></animate> <stop offset="0%" stopColor="rgba(255,0,0, 1)"></stop> <stop offset="100%" stopColor="rgba(255,0,0, 0)"></stop> </radialGradient> </defs> <rect x="13.744%" y="1.18473%" width="100%" height="100%" fill="url(#Gradient1)" transform="rotate(334.41 50 50)" > <animate attributeName="x" dur="100.8s" values="25%;0%;25%" repeatCount="indefinite" ></animate> <animate attributeName="y" dur="117.6s" values="0%;25%;0%" repeatCount="indefinite" ></animate> <animateTransform attributeName="transform" type="rotate" from="0 50 50" to="360 50 50" dur="39.2s" repeatCount="indefinite" ></animateTransform> </rect> <rect x="-2.17916%" y="35.4267%" width="100%" height="100%" fill="url(#Gradient2)" transform="rotate(255.072 50 50)" > <animate attributeName="x" dur="128.8s" values="-25%;0%;-25%" repeatCount="indefinite" ></animate> <animate attributeName="y" dur="142.4s" values="0%;50%;0%" repeatCount="indefinite" ></animate> <animateTransform attributeName="transform" type="rotate" from="0 50 50" to="360 50 50" dur="57.6s" repeatCount="indefinite" ></animateTransform> </rect> <rect x="9.00483%" y="14.5733%" width="100%" height="100%" fill="url(#Gradient3)" transform="rotate(139.903 50 50)" > <animate attributeName="x" dur="140s" values="0%;25%;0%" repeatCount="indefinite" ></animate> <animate attributeName="y" dur="67.2s" values="0%;25%;0%" repeatCount="indefinite" ></animate> <animateTransform attributeName="transform" type="rotate" from="360 50 50" to="0 50 50" dur="43.2s" repeatCount="indefinite" ></animateTransform> </rect> </svg> </div> <h1 className="cat__title"> <svg xmlns="http://www.w3.org/2000/svg" enableBackground="new 0 0 32 32" version="1.1" viewBox="0 0 32 32" > <g id="Layer_1" /> <g id="Layer_2"> <g> <path className="filled" d=" M20,14L20,14c-1.1,0-2-0.9-2-2V8c0-1.1,0.9-2,2-2h0c1.1,0,2,0.9,2,2v4C22,13.1,21.1,14,20,14z" fill="none" stroke="#000000" strokeLinecap="round" strokeLinejoin="round" strokeMiterlimit="10" strokeWidth="2" /> <g> <circle className="filled" cx="25.5" cy="6.5" r="1.5" /> </g> <g> <circle className="filled" cx="29.5" cy="13.5" r="1.5" /> </g> <line className="filled" fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" x1="30" x2="25" y1="6" y2="14" /> <path d=" M15,6H4C2.9,6,2,6.9,2,8v16c0,1.1,0.9,2,2,2h24c1.1,0,2-0.9,2-2v-7" fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" /> <line fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" x1="6" x2="8" y1="20" y2="20" /> <line fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" x1="12" x2="14" y1="20" y2="20" /> <line fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" x1="18" x2="20" y1="20" y2="20" /> <line fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" x1="24" x2="26" y1="20" y2="20" /> <line fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" x1="2" x2="15" y1="10" y2="10" /> </g> </g> </svg> cashback </h1> <CatFilter filter={filter} setFilter={setFilter} generateUrl={generateUrl} fetchCashback={fetchCashback} /> <CatItems data={searchedCashback} loading={infoLoading} isEmpty={isEmpty} /> </div> ); } export default App;
import { useEffect, useState } from 'react'; import './App.css'; import List from "./components/list/List"; import Form from "./components/form/Form"; import { Sub } from "./types" interface AppStates { subs: Array<Sub> subsNumber: number } const INITIAL_STATE = [{ nick: "sid", subMonths: 3, avatar: "https://i.pravatar.cc/150?u=sid", description: "Sid hace de mod a veces" }, { nick: "sergio", subMonths: 7, avatar: "https://i.pravatar.cc/150?u=aergio" } ] function App() { const [subs, setSubs] = useState<AppStates["subs"]>([]); /* const [newSubsNumber, setNewSubsNumber] = useState<AppStates["subsNumber"]>(0) */ useEffect(() => { setSubs(INITIAL_STATE) }, []) const handleNewSub = (newSub: Sub): void => { setSubs(subs => [...subs, newSub]) } return ( <div className="App"> <h1>Mis subs</h1> <List subs={subs}/> <Form onNewSub={handleNewSub} /> </div> ); } export default App;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Array</title> </head> <body> <h1>Belajar Javascript yokk</h1> <p>Array nih ya yg hari ini kita bahas</p> <script> let temansekelas = [ "Joni Gudel", "Soni Tulung", "Edi Yunani", "Mimin Item", "Edward Beki", "Koh Acong" ]; // Dibuat dengan menggunakan kurung siku // dan setiap elemennya dipisahkan dengan tanda koma // setiap elemen dwakili dengan nomor index // nomor index dimulai dengan nomor 0 console.log(temansekelas[0]); // cara menambahkan elemen array saat variabelnya // sudah dibuat temansekelas[6] = "Alti Bewok"; console.log(temansekelas[6]); // Mencampur tipe data ke dalam array let teman = [ 9, "Joni Gudel", "Soni Tulung", "Edi Yunani", "Mimin Item", "Edward Beki", "Koh Acong", [ "Alti Brewok", "Suharso", "Yoyok" ] ]; // Didalam array bisa diisi dengan array lagi // Cara mengakses array di dalam array nya adalah sebagai berikut // contoh kita akan mengakses yoyok // maka caranya sebagai berikut console.log(teman[7][2]); // Property dan methods untuk array // length console.log(temansekelas.length); // Apabila ada array didalam sebuah array, maka itu // diitungnya sebagai satu elmen // nomor index untuk tiap elemen diawali dengan angka 0 // Oleh karena itu, apabila jumlah seluruh elemen adalah // 8 maka elemen terakhir diberi nomor index 7 // Dari sini kita bisa mengakses elemen terakhir dengan // menulis seperti ini console.log(teman[teman.length - 1]); let pets = [ "Kucing", "Anjing", "Marmut" ]; console.log(pets.length); // Menghasilkan 3 sesuai dengan jumlah elemen // Method push() // Method ini akan menambahkan elemen baru ke dalam urutan terakhir pada array. Jadi anda tidak perlu mengetahui terlebih dahulu berapa jumlah elemen dalam sebuah array sebelum menambah elemen baru kedalamnya pets.push("Kura - Kura"); pets.push("Kelinci"); pets.push("Ikan"); console.log(pets.length); // Akan menghasilkan 6 karena sudah ditambahkan dengan // method push() const arr = [2,4,6]; arr.push(arr.push(arr.pop())); // Hasilnya [2,4,6,3] // arr.push mengembalikan length array console.log(arr); // Mengakses elemen terakhir array dengan cara console.log(pets[pets.length - 1]); // Menghasilkan ikan // Method unshift() // Digunakan untuk menambahkan elemen di bagian awal // arrays, jadi dapat disimpulkan method ini merupakan kebalikan dari push() console.log(pets[0]); // Menghasilkan kucing pets.unshift("Hamster"); console.log(pets[0]); // Menghasilkan Hamster // Method pop() // Digunakan untuk menghapus elemen terakhir pada sebuah array. tidak hanya itu saja tapi juga menghasilkan nilai, yaitu elemen yang dihapus tersebut. // Elemen itu akan dihapus begitu saja // Elemen tersebut bisa disimpan kedalam variabel terpisah // Elemen tersebut bisa dipindahkan ke bagian awal sebauh array // Apabila ingin hanya menghapus elemen terakhir saja maka let pets2 = [ "Kucing", "Anjing", "Marmut" ] console.log(pets2[pets2.length - 1]); // Menghasilkan marmut pets2.pop(); console.log(pets2[pets2.length - 1]); // Menghasilkan Anjing karena sudah dihapus elemen terakhirnya // Apabila ingin dipindahkan ke variabel terpisah maka let pets3 = [ "Kucing", "Anjing", "Marmut" ] console.log(pets3[pets3.length - 1]); // Menghasilkan marmut let hewan = pets3.pop(); console.log(hewan); // Menghasilkan Marmut // Karena method pop() ini menyimpan elemen marmut // Apabila ingin meletakkan elemen terakhir ke posisi pertama let pets4 = [ "Kucing", "Anjing", "Marmut" ]; console.log(pets4[0]); // Menghasilkan Kucing pets4.unshift(pets4.pop()); console.log(pets4[0]); // Menghasilkan Marmut // Method Shift // Merupakan kebalikan dari method pop() // Tapi yang dihapus adalah elemen pertama dari array // Dan menghasilkan nilai balikan yaitu berupa nilai pertama itu sediri let pets5 =[ "kucing", "anjing", "marmut" ] console.log(pets5[pets5.length - 1]); // Menghasilkan Marmut pets5.push(pets5.shift()); // Menghapus kucing dan memindahkannya ke elemen terakhir console.log(pets5[pets5.length - 1]); // Sekarang menghasilkan kucing // Method concat // dipakai untuk menggabungkan dua array // arraypertama.concat(arraykedua); let pets6 = [ "kucing", "anjing", "marmut" ] let flowers = [ "melati", "mawar", "anggrek" ] console.log(pets6.concat(flowers)); // Selain menggabungkan 2 array // concat() juga bisa menggabungkan 3 array // method join() // digunakan untuk menggabngkan seluruh elemen // menjadi sebuah string let flowers2 = [ "melati", "mawar", "anggrek" ]; console.log(flowers2.join()); // akan menghsilkan "melati, mawar, anggrek" // tanda koma akan menjadi tanda pemisah default // Kita bisa mengisi argumen di dalam method join untuk dijadikan tanda pemisah console.log(flowers2.join("-")); // akan menjadikan - sebagai tanda pemisah </script> </body> </html>
CREATE DATABASE futbol; USE futbol; CREATE TABLE equipos ( Id_equipo INT NOT NULL AUTO_INCREMENT, Nombre_equipo VARCHAR(45)NOT NULL, Numero_jugadores INT(5)NOT NULL, Fecha_fundacion DATE, Jugador_estrella VARCHAR(45)NOT NULL, PRIMARY KEY(Id_equipo) ); USE futbol; ALTER TABLE equipos ADD Color_camiseta VARCHAR(50) NOT NULL; CREATE TABLE jugadores ( Id_jugador INT NOT NULL AUTO_INCREMENT, Nombre_jugador VARCHAR(45)NOT NULL, Edad INT(5)NOT NULL, Fecha_nacimiento DATE, Equipo VARCHAR(45)NOT NULL, PRIMARY KEY(Id_jugador) ); CREATE TABLE estadios ( Id_estadios INT NOT NULL AUTO_INCREMENT, Nombre_estadio VARCHAR(45)NOT NULL, Numero_equipo INT(5)NOT NULL, Fecha_fundacion DATE, Fundador_estadio VARCHAR(45)NOT NULL, PRIMARY KEY(Id_estadios) ); CREATE TABLE entrenadores ( Id_entrenadores INT NOT NULL AUTO_INCREMENT, Nombre_entrenador VARCHAR(45)NOT NULL, Edad INT(5)NOT NULL, Numero_equipos INT(5)NOT NULL, Equipo_actual VARCHAR(45)NOT NULL, PRIMARY KEY(Id_entrenadores) ); CREATE TABLE ganadores_campeonato ( Id_ganador INT NOT NULL AUTO_INCREMENT, Nombre_equipo VARCHAR(45)NOT NULL, Año_gano INT(5)NOT NULL, Rival_final VARCHAR (45)NOT NULL, Goles_totales INT(5)NOT NULL, PRIMARY KEY(Id_ganador) ); -- codigo para insertar datos a las tablas -- USE futbol; INSERT INTO equipos (Nombre_equipo,Numero_jugadores,Fecha_fundacion,Jugador_estrella,Color_camiseta) VALUES ('Manchester', '24', '1987/06/07', 'Zlatan','Rojo'); INSERT INTO equipos (Nombre_equipo,Numero_jugadores,Fecha_fundacion,Jugador_estrella,Color_camiseta) VALUES ('Barcelona', '32', '1923/09/02', 'Messi','Rojo-Azul'); INSERT INTO equipos (Nombre_equipo,Numero_jugadores,Fecha_fundacion,Jugador_estrella,Color_camiseta) VALUES ('Barcelona', '32', '1923/09/02', 'Suares','Rojo-Azul'); INSERT INTO jugadores (Nombre_jugador,Edad,Fecha_nacimiento,Equipo) VALUES ('Zlatan', '33', '1987/06/07', 'Paris Saint German'); INSERT INTO jugadores (Nombre_jugador,Edad,Fecha_nacimiento,Equipo) VALUES ('Messi', '30', '1987/06/07', 'Barcelona'); INSERT INTO estadios (Nombre_estadio,Numero_equipo,Fecha_fundacion,Fundador_estadio) VALUES ('Old Trandford', '7', '1987/06/07', ' ALEXANDRE'); INSERT INTO estadios (Nombre_estadio,Numero_equipo,Fecha_fundacion,Fundador_estadio) VALUES ('Cap Now', '12', '1987/06/07', ' ARTHUR'); INSERT INTO entrenadores (Nombre_entrenador,Edad,Numero_equipos,Equipo_actual) VALUES ('Mourinho', '42', '12', ' Manchester United'); INSERT INTO entrenadores (Nombre_entrenador,Edad,Numero_equipos,Equipo_actual) VALUES ('Guardiola', '45', '15', ' Manchester City'); INSERT INTO ganadores_campeonato (Nombre_equipo,Año_gano,Rival_final,Goles_totales) VALUES ('Manchester United','1995', 'Chelsea', '3'); INSERT INTO ganadores_campeonato (Nombre_equipo,Año_gano,Rival_final,Goles_totales) VALUES ('Barcelona', '1989', 'Real Madrid', '5'); -- codigo para consultar datos repetidos de una columna de una tabla -- select Nombre_equipo, count(Nombre_equipo) as cantidad from equipos group by Nombre_equipo;
package jdk8.demo02; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * @author liuzhipeng * @description * @create 2019-12-24 11:00 */ public class D09_ParallelStreams { public static void main(String[] args) { int max = 1000000; List<String> values = new ArrayList<>(max); for (int i = 0; i < max; i++) { UUID uuid = UUID.randomUUID(); values.add(uuid.toString()); } sequentialSort(values); } private static void parallelSort(List<String> values) { //并行排序 long t0 = System.nanoTime(); long count = values.parallelStream().sorted().count(); System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format("parallel sort took: %d ms", millis)); } private static void sequentialSort(List<String> values) { //串行排序 long t0 = System.nanoTime(); long count = values.stream().sorted().count(); System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format("sequential sort took: %d ms", millis)); } }
import { Button, Grid, Typography } from "@mui/material"; import { useTournament } from "../contexts/tournamentContext"; import { Player } from "../types/tournamentTypes"; import { Icon } from "@iconify/react"; import { DataGrid, GridColDef, GridLocaleText, GRID_DEFAULT_LOCALE_TEXT, GridActionsCellItem, GridEventListener, GridRowId, GridRowModel, } from "@mui/x-data-grid"; import NewPlayerDialog from "../components/NewPlayerCard"; import { useMemo, useState } from "react"; import ConfirmationDialog from "@/components/ConfirmationDialog"; import { red } from "@mui/material/colors"; const gridLocaleText: GridLocaleText = { ...GRID_DEFAULT_LOCALE_TEXT, noRowsLabel: "Aucun joueur", }; const handleRowEdit: GridEventListener<"rowEditStart" | "rowEditStop"> = ( _params, event ) => { event.defaultMuiPrevented = true; }; export default function Players() { const { players, removePlayer, setPlayer, tournamentReset, playersSelected, setPlayersSelected, } = useTournament(); const [openNewPlayerDialog, setOpenNewPlayerDialog] = useState(false); const [openResetTournamentDialog, setOpenResetTournamentDialog] = useState(false); const handleDeleteClick = useMemo( () => (id: GridRowId) => () => { if (!removePlayer || typeof id !== "string") throw new Error("Unable to remove player"); removePlayer(id); }, [removePlayer] ); const processRowUpdate = useMemo( () => (newRow: GridRowModel, oldRow: GridRowModel) => { if (!setPlayer) throw new Error("Unable to set player"); const player = { id: newRow.id, name: newRow.name, level: newRow.level, score: newRow.score, } as Player; if (!player.name) { alert("Le nom du joueur est obligatoire !"); return oldRow; } if (!player.level || player.level < 1 || player.level > 6) { alert("Le niveau du joueur doit être compris entre 1 et 6 !"); return oldRow; } setPlayer(player); return newRow; }, [setPlayer] ); const columns: GridColDef[] = useMemo( () => [ { field: "name", headerName: "Nom du joueur", width: 250, editable: true, }, { field: "level", headerName: "Niveau", type: "number", width: 90, editable: true, align: "center", headerAlign: "center", }, { field: "matchesPlayed", headerName: "Matchs joués", type: "number", width: 110, align: "center", headerAlign: "center", }, { field: "actions", type: "actions", headerName: "Supprimer", width: 100, cellClassName: "actions", getActions: ({ id }) => { return [ <GridActionsCellItem icon={ <Icon icon="mdi:delete-outline" color={red[400]} width="20px" /> } label="Supprimer" onClick={handleDeleteClick(id)} color="inherit" key={`${id}-delete-button`} />, ]; }, }, ], [handleDeleteClick] ); return ( <> <Grid container rowSpacing={3} justifyContent="center" alignItems="center" > <Grid item container xs={12} justifyContent="center" alignItems="center" spacing={4} > <Grid item container justifyContent="center" sx={{ maxWidth: "250px" }} > <Button variant="contained" onClick={() => setOpenNewPlayerDialog(true)} > Ajouter un joueur </Button> </Grid> <Grid item container justifyContent="center" sx={{ maxWidth: "300px" }} > <Button variant="outlined" onClick={() => setOpenResetTournamentDialog(true)} color="error" > Supprimer tous les joueurs </Button> </Grid> </Grid> <Grid item container xs={12} justifyContent="center" alignItems="center" > <Typography variant="subtitle2"> Joueurs sélectionnés pour le tournoi :{" "} {playersSelected?.length ?? 0} sur un total de{" "} {Object.keys(players ?? []).length} </Typography> </Grid> <Grid item maxWidth="100%" sx={{ minWidth: "50px" }}> <DataGrid aria-label="Liste des joueurs" rows={players ? (Object.values(players) as Player[]) : []} columns={columns} disableColumnMenu hideFooter={true} autoHeight={true} localeText={gridLocaleText} onRowEditStart={handleRowEdit} onRowEditStop={handleRowEdit} processRowUpdate={processRowUpdate} checkboxSelection onRowSelectionModelChange={(newRowSelectionModel) => { setPlayersSelected?.(newRowSelectionModel as string[]); }} rowSelectionModel={playersSelected} /> </Grid> </Grid> <NewPlayerDialog open={openNewPlayerDialog} onClose={() => setOpenNewPlayerDialog(false)} /> <ConfirmationDialog title="Supprimer tous les joueurs ?" description="Voulez-vous vraiment supprimer tous les joueurs ? Cette action est irréversible." open={openResetTournamentDialog} onClose={() => setOpenResetTournamentDialog(false)} onConfirm={() => tournamentReset?.()} /> </> ); }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePurchaseOrdersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('purchase_orders', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('invoice_number')->nullable(); $table->string('invoice_date'); $table->double('total'); $table->double('discount')->nullable(); $table->double('taxable_amount'); $table->double('total_vat'); $table->double('total_amount_due'); $table->double('amount_paid')->nullable(); $table->double('amount_paid_bank')->nullable(); $table->double('amount_due'); $table->double('supplier_discount')->nullable(); $table->tinyInteger('supplier_discount_type')->comment('0=> currency, 1=> percentage')->nullable(); $table->double('supplier_discount_amount')->nullable(); $table->enum('status', ['close', 'open'])->default('close'); $table->bigInteger('user_id')->unsigned(); $table->bigInteger('branch_id')->unsigned(); $table->bigInteger('supplier_id')->unsigned(); $table->string('payment_method')->nullable(); $table->string('payment_method_bank')->nullable(); $table->string('payment_receipt_number')->nullable(); $table->string('notes')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('purchase_orders'); } }
import React, { useState } from "react"; const MemberForm = ({ addMember }) => { const [isOpen, setIsOpen] = useState(false); const [name, setName] = useState(""); const [age, setAge] = useState(""); const [place, setPlace] = useState(""); const [email, setEmail] = useState(""); const handleOpenForm = () => { setIsOpen(true); }; const handleCloseForm = () => { setIsOpen(false); }; const handleSubmit = (e) => { e.preventDefault(); const newMember = { name: name, age: age, place: place, email: email, access: "Admin" // Assuming all new members have "Admin" access initially }; addMember(newMember); // Reset the form fields setName(""); setAge(""); setPlace(""); setEmail(""); handleCloseForm(); }; if (!isOpen) { return ( <button className="btn btn-outline btn-warning" onClick={handleOpenForm}> Add member </button> ); } return ( <div className="flex items-center justify-center h-screen"> <form className="w-80 mt-4 bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" onSubmit={handleSubmit}> <div className="flex items-center justify-between mb-4"> <div className="flex items-center"> <div className="w-10 h-10 rounded-full overflow-hidden"> <img src="/logo.png" alt="Logo" className="w-full h-full object-cover" /> </div> <span className="text-gray-700 text-2xl ml-2">Add Member</span> </div> <button className="text-gray-500 hover:text-gray-700 focus:outline-none" type="button" onClick={handleCloseForm} > <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /> </svg> </button> </div> <div className="mb-4"> <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="name"> Name </label> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-white bg-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="text" id="name" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} required /> </div> <div className="mb-4"> <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="age"> Age </label> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-white bg-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="text" id="age" placeholder="Age" value={age} onChange={(e) => setAge(e.target.value)} required /> </div> <div className="mb-4"> <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="place"> Place </label> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-white bg-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="text" id="place" placeholder="Place" value={place} onChange={(e) => setPlace(e.target.value)} required /> </div> <div className="mb-4"> <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="email"> Email </label> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-white bg-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="email" id="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} required /> </div> <div className="flex items-center justify-end mt-6"> <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline mr-2" type="submit" > Save </button> <button className="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button" onClick={handleCloseForm} > Cancel </button> </div> </form> </div> ); }; export default MemberForm;
package ref import ( "context" "errors" "fmt" "strings" "gitlab.com/gitlab-org/gitaly/v16/internal/git" "gitlab.com/gitlab-org/gitaly/v16/internal/git/localrepo" "gitlab.com/gitlab-org/gitaly/v16/internal/git/updateref" "gitlab.com/gitlab-org/gitaly/v16/internal/gitaly/storage" "gitlab.com/gitlab-org/gitaly/v16/internal/gitaly/transaction" "gitlab.com/gitlab-org/gitaly/v16/internal/structerr" "gitlab.com/gitlab-org/gitaly/v16/internal/transaction/voting" "gitlab.com/gitlab-org/gitaly/v16/proto/go/gitalypb" ) func (s *server) DeleteRefs(ctx context.Context, in *gitalypb.DeleteRefsRequest) (_ *gitalypb.DeleteRefsResponse, returnedErr error) { if err := validateDeleteRefRequest(s.locator, in); err != nil { return nil, structerr.NewInvalidArgument("%w", err) } repo := s.localrepo(in.GetRepository()) refnames, err := s.refsToRemove(ctx, repo, in) if err != nil { return nil, structerr.NewInternal("%w", err) } updater, err := updateref.New(ctx, repo, updateref.WithNoDeref()) if err != nil { if errors.Is(err, git.ErrInvalidArg) { return nil, structerr.NewInvalidArgument("%w", err) } return nil, structerr.NewInternal("%w", err) } defer func() { if err := updater.Close(); err != nil && returnedErr == nil { returnedErr = fmt.Errorf("close updater: %w", err) } }() voteHash := voting.NewVoteHash() var invalidRefnames [][]byte for _, ref := range refnames { if err := git.ValidateRevision([]byte(ref)); err != nil { invalidRefnames = append(invalidRefnames, []byte(ref)) } } if len(invalidRefnames) > 0 { return nil, structerr.NewInvalidArgument("invalid references").WithDetail( &gitalypb.DeleteRefsError{ Error: &gitalypb.DeleteRefsError_InvalidFormat{ InvalidFormat: &gitalypb.InvalidRefFormatError{ Refs: invalidRefnames, }, }, }, ) } if err := updater.Start(); err != nil { return nil, structerr.NewInternal("start reference transaction: %w", err) } for _, ref := range refnames { if err := updater.Delete(ref); err != nil { return nil, structerr.NewInternal("unable to delete refs: %w", err) } if _, err := voteHash.Write([]byte(ref.String() + "\n")); err != nil { return nil, structerr.NewInternal("could not update vote hash: %w", err) } } if err := updater.Prepare(); err != nil { var alreadyLockedErr updateref.AlreadyLockedError if errors.As(err, &alreadyLockedErr) { return nil, structerr.NewAborted("cannot lock references").WithDetail( &gitalypb.DeleteRefsError{ Error: &gitalypb.DeleteRefsError_ReferencesLocked{ ReferencesLocked: &gitalypb.ReferencesLockedError{ Refs: [][]byte{[]byte(alreadyLockedErr.ReferenceName)}, }, }, }, ) } return nil, structerr.NewInternal("unable to prepare: %w", err) } vote, err := voteHash.Vote() if err != nil { return nil, structerr.NewInternal("could not compute vote: %w", err) } // All deletes we're doing in this RPC are force deletions. Because we're required to filter // out transactions which only consist of force deletions, we never do any voting via the // reference-transaction hook here. Instead, we need to resort to a manual vote which is // simply the concatenation of all reference we're about to delete. if err := transaction.VoteOnContext(ctx, s.txManager, vote, voting.Prepared); err != nil { return nil, structerr.NewInternal("preparatory vote: %w", err) } if err := updater.Commit(); err != nil { return nil, structerr.NewInternal("unable to commit: %w", err) } if err := transaction.VoteOnContext(ctx, s.txManager, vote, voting.Committed); err != nil { return nil, structerr.NewInternal("committing vote: %w", err) } return &gitalypb.DeleteRefsResponse{}, nil } func (s *server) refsToRemove(ctx context.Context, repo *localrepo.Repo, req *gitalypb.DeleteRefsRequest) ([]git.ReferenceName, error) { if len(req.Refs) > 0 { refs := make([]git.ReferenceName, len(req.Refs)) for i, ref := range req.Refs { refs[i] = git.ReferenceName(ref) } return refs, nil } prefixes := make([]string, len(req.ExceptWithPrefix)) for i, prefix := range req.ExceptWithPrefix { prefixes[i] = string(prefix) } existingRefs, err := repo.GetReferences(ctx) if err != nil { return nil, err } var refs []git.ReferenceName for _, existingRef := range existingRefs { if hasAnyPrefix(existingRef.Name.String(), prefixes) { continue } refs = append(refs, existingRef.Name) } return refs, nil } func hasAnyPrefix(s string, prefixes []string) bool { for _, prefix := range prefixes { if strings.HasPrefix(s, prefix) { return true } } return false } func validateDeleteRefRequest(locator storage.Locator, req *gitalypb.DeleteRefsRequest) error { if err := locator.ValidateRepository(req.GetRepository()); err != nil { return err } if len(req.ExceptWithPrefix) > 0 && len(req.Refs) > 0 { return errors.New("ExceptWithPrefix and Refs are mutually exclusive") } if len(req.ExceptWithPrefix) == 0 && len(req.Refs) == 0 { // You can't delete all refs return errors.New("empty ExceptWithPrefix and Refs") } for _, prefix := range req.ExceptWithPrefix { if len(prefix) == 0 { return errors.New("empty prefix for exclusion") } } for _, ref := range req.Refs { if len(ref) == 0 { return errors.New("empty ref") } } return nil }
<script setup> import InputError from '@/Components/InputError.vue'; import InputLabel from '@/Components/InputLabel.vue'; import PrimaryButton from '@/Components/PrimaryButton.vue'; import TextInput from '@/Components/TextInput.vue'; import { useForm } from '@inertiajs/vue3'; import {onMounted, ref} from 'vue'; const passwordInput = ref(null); const currentPasswordInput = ref(null); const emailInput = ref(null); const nameInput = ref(null); const props = defineProps({ user: { type: Object } }); const form = useForm({ id: props.user.id, name: props.user.name, email: props.user.email, password: undefined, password_confirmation: undefined, }); const updatePassword = () => { form.put(route('users.update'), { preserveScroll: true, // onSuccess: () => form.reset(), onError: () => { if (form.errors.password) { form.reset('password', 'password_confirmation'); passwordInput.value.focus(); } if (form.errors.email) { emailInput.value.focus(); } if (form.errors.name) { nameInput.value.focus(); } }, }); }; </script> <template> <section> <header> <h2 class="text-lg font-medium text-gray-900">Обновление ученика - {{ user.name }}</h2> </header> <form @submit.prevent="updatePassword" class="mt-6 space-y-6 flex flex-col"> <div> <InputLabel for="name" value="Имя" /> <TextInput id="name" ref="nameInput" v-model="form.name" :default="user.name" type="text" class="mt-1 block w-full" /> <InputError :message="form.errors.name" class="mt-2" /> </div> <div> <InputLabel for="email" value="E-mail" /> <TextInput id="email" ref="emailInput" v-model="form.email" type="text" class="mt-1 block w-full" /> <InputError :message="form.errors.email" class="mt-2" /> </div> <div> <InputLabel for="password" value="Пароль" /> <InputLabel for="password" value="Если пароль не нужно менять - не трогайте эти поля" /> <TextInput id="password" ref="passwordInput" v-model="form.password" type="password" class="mt-1 block w-full" autocomplete="new-password" /> <InputError :message="form.errors.password" class="mt-2" /> </div> <div> <InputLabel for="password_confirmation" value="Подтвердите пароль" /> <TextInput id="password_confirmation" v-model="form.password_confirmation" type="password" class="mt-1 block w-full" autocomplete="new-password" /> <InputError :message="form.errors.password_confirmation" class="mt-2" /> </div> <div class="flex items-center gap-4 self-center"> <PrimaryButton :disabled="form.processing">Обновить</PrimaryButton> </div> </form> </section> </template>
import {Description, Runtime, SpawnOptions, Worker} from "@spica-server/function/runtime"; import * as child_process from "child_process"; import * as path from "path"; import {Writable} from "stream"; class NodeWorker extends Worker { private _process: child_process.ChildProcess; private _quit = false; private get quit() { return this._process.killed || this._quit; } constructor(options: SpawnOptions) { super(); this._process = child_process.spawn( `node`, [ "--es-module-specifier-resolution=node", path.join(__dirname, "runtime", "entrypoint", "bootstrap") ], { stdio: ["ignore", "pipe", "pipe"], env: { PATH: process.env.PATH, HOME: process.env.HOME, FUNCTION_GRPC_ADDRESS: process.env.FUNCTION_GRPC_ADDRESS, ENTRYPOINT: "index", RUNTIME: "node", WORKER_ID: options.id, ...options.env } } ); this._process.once("exit", () => (this._quit = true)); Object.assign(this, this._process); } attach(stdout?: Writable, stderr?: Writable): void { this._process.stdout.unpipe(); this._process.stderr.unpipe(); this._process.stdout.pipe(stdout); this._process.stderr.pipe(stderr); } kill() { if (this.quit) { return Promise.resolve(); } return new Promise<void>(resolve => { this._process.once("exit", () => resolve()); this._process.kill("SIGTERM"); }); } } export class Node extends Runtime { description: Description = { name: "node", title: "Node.js 12", description: "Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine." }; spawn(options: SpawnOptions): Worker { return new NodeWorker(options); } }
# Sorted Tree ## Difficulty: ![Filled](../resources/star-filled.svg) ![Filled](../resources/star-filled.svg) ![Outlined](../resources/star-outlined.svg) So far, we have constructed trees by manually adding subtrees to nodes. This can be rather tedious. We would like to just add elements to a tree and have the tree decide where the new element must be placed. One method of deciding the location of new nodes is by using the alphabetical order. Items that come before the value of the current node must be added to the left side of the node; items that come after the value of the current node must be added to the right side of the node. ### TODO 1 * Implement the `add()` method of the `IADTree` class. Verify your implementation by adding some values and copy-paste the `toDot()` String in a graphviz viewer (e.g. https://dreampuf.github.io/GraphvizOnline) * _Hint_ use the `public int compareTo(String other)` of the `String` class to compare to Strings. #### example After adding nodes in the order C - A - B - D - F - E the tree should look like this: ![sorted_example.png](../resources/sorted_example.png) ### TODO 2 Add Strings in backwards alphabetical order. What is the effect on the tree structure? ### TODO 3 * One way to verify the correct implementation is by viewing an _in-order_ representation of the tree. Copy your solution from the previous exercise and verify that your sorted tree works as expected. For example: ``` IADTree tree =new IADTree(); tree.add("C"); tree.add("A"); tree.add("B"); tree.add("D"); tree.add("F"); tree.add("E"); System.out.println(tree.inOrder()); ``` should yield: `A, B, C, D, E, F, ` <br/> <br/>
import * as React from "react"; import Card from "@mui/material/Card"; import CardHeader from "@mui/material/CardHeader"; import CardContent from "@mui/material/CardContent"; import CardActions from "@mui/material/CardActions"; import IconButton from "@mui/material/IconButton"; import Typography from "@mui/material/Typography"; import FavoriteIcon from "@mui/icons-material/FavoriteBorderOutlined"; import ChatIcon from "@mui/icons-material/MapsUgcRounded"; import MoreVertIcon from "@mui/icons-material/MoreVert"; import { AvatarComponent, CardTitleComponent, MuteText } from "./styled"; import { IPost } from "../../interface/timeline.interface"; import { timeElapsed } from "../../utils"; interface PropsType { postData: IPost; onLikeAndUnlikePost: (post_id: string, index: number) => void; index: number; likedPost: Array<string>; } export default function CustomCard(props: PropsType) { const { postData, likedPost, index, onLikeAndUnlikePost } = props; // This Function will call when profile image is not available const onErrorImg = (e: any) => { const currentTarget = e.currentTarget; currentTarget.onerror = null; // prevents looping currentTarget.src = "https://st3.depositphotos.com/6672868/13701/v/600/depositphotos_137014128-stock-illustration-user-profile-icon.jpg"; }; const likeIconStyle = () => { if (likedPost.includes(postData.id)) { return "error"; } return "default"; }; return ( <Card sx={{ maxWidth: "100%" }} key={postData.id}> <CardHeader avatar={<AvatarComponent aria-label="recipe" alt="" onError={onErrorImg} src={postData.user.profile_image_url} />} action={ <IconButton aria-label="settings"> <MoreVertIcon /> </IconButton> } title={<CardTitleComponent>{`${postData.user.first_name} ${postData.user.last_name}`}</CardTitleComponent>} titleTypographyProps={{ variant: "h6" }} subheader={timeElapsed(postData.created_at)} /> <CardContent> <Typography sx={{ fontSize: "17px", paddingLeft: "20px", paddingRight: "20px" }} variant="body2"> {postData.text} </Typography> </CardContent> <CardActions disableSpacing> <IconButton color={likeIconStyle()} onClick={() => onLikeAndUnlikePost(postData.id, index)} aria-label="add to favorites"> <FavoriteIcon /> &nbsp; <MuteText>{postData.likes_count}</MuteText> </IconButton> <IconButton aria-label="share"> <ChatIcon /> &nbsp; <MuteText>{postData.replies_count}</MuteText> </IconButton> </CardActions> </Card> ); }
from typing import Optional class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random def display(self): current_node = self while current_node.next: print(current_node.val, end=" -> ") current_node = current_node.next print(current_node.val) class Solution: def pluck_even_nodes(self, head): even_head = Node(-1) # Creating a dummy head for the even nodes even_node = even_head current = head index = 0 while current: if index % 2 == 1: # If index is even (zero-based indexing) even_node.next = current even_node = even_node.next prev_next = current.next current.next = None current = prev_next else: current = current.next index += 1 return even_head.next # Return the head of even nodes def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': node = head while node: next = node.next node.next = Node(node.val+1, node.next) node = next node = head while node: if node.random: node.next.random = node.random.next node = node.next.next return self.pluck_even_nodes(head) n4 = Node(1) n3 = Node(10, n4) n2 = Node(11, n3) n1 = Node(13, n2) head = Node(7, n1) n1.random = head n2.random = n4 n3.random = n3 n4.random = head head.display() sol = Solution() new_head = sol.copyRandomList(head) new_head.display()
# ---- formula primitives ----------------------------------------------------- assert_formula <- function(formula) { assert_is(formula,"formula") } #' @keywords internal is_one_sided_formula <- function(formula) { is(formula,"formula") & (length(formula) == 2) } #' @keywords internal is_two_sided_formula <- function(formula) { is(formula,"formula") & (length(formula) == 3) } #' @keywords internal has_constant <- function(formula) { assert_formula(formula) attr(terms(formula,allowDotAsName = TRUE),"intercept") == 1 } #' @keywords internal has_dot_shortcut <- function(formula) { "." %in% extract_formula_terms(formula) } #' @keywords internal data_permits_formula <- function(formula,data) { assert_formula(formula) stopifnot(inherits(data, "data.frame")) data <- data[0, ,drop = FALSE] possible <- tryCatch( expr = {is(model.matrix(formula, data = data),"matrix")}, error = function(e) FALSE) if (possible) TRUE else FALSE } #' @keywords internal formula_expands_factors <- function(formula,data) { assert_formula(formula) stopifnot(is.data.frame(data)) data <- data[0, ,drop = FALSE] no_fct <- attr(model.matrix(formula, data = data), "contrasts") return(!is.null(no_fct)) } # ---- reshaping the formula -------------------------------------------------- #' @keywords internal compact_formula_internal <- function(formula, keep_const = TRUE) { assert_formula(formula) compact_rhs <- extract_formula_terms(formula) %||% "1" if (length(compact_rhs) == 0) return(formula) compact_lhs <- NULL if (is_two_sided_formula(formula)) compact_lhs <- extract_formula_terms(pull_lhs(formula)) compact_formula <- reformulate(compact_rhs, intercept = keep_const & has_constant(formula), response = compact_lhs) return(compact_formula) } #' @keywords internal compact_formula <- function(formula) { compact_formula_internal(formula,keep_const = TRUE) } #' @keywords internal remove_constant <- function(formula) { compact_formula_internal(formula,keep_const = FALSE) } #' @keywords internal combine_rhs_formulas <- function(...) { rhs_formulas <- flatlist(list(...)) rhs_formulas <- lapply(compact(rhs_formulas), "pull_rhs") use_constant <- all(sapply(rhs_formulas , "has_constant")) combined_formula <- unlist(lapply(rhs_formulas, extract_formula_terms)) combined_formula <- reformulate(unique(combined_formula), intercept = use_constant) return(combined_formula) } #' @keywords internal pull_rhs <- function(formula) { assert_formula(formula) return_rhs <- formula if (is_two_sided_formula(formula)) return_rhs <- return_rhs[c(1,3)] return(return_rhs) } #' @keywords internal pull_lhs <- function(formula) { assert(is_two_sided_formula(formula), "The input musst be a two sided formula!") return(formula[c(1,2)]) } # ---- accessing formula elements --------------------------------------------- #' @keywords internal extract_formula_terms <- function(formula, data = NULL) { assert_formula(formula) if (is.null(data)) return(labels(terms(formula, allowDotAsName = TRUE))) assert_is(data,"data.frame") return(labels(terms(formula, data = data))) } # ---- fine tuned expansions of the formula ----------------------------------- #' @keywords internal extract_transformed_varnames <- function(formula,data) { data <- data[0, ,drop = FALSE] assert(data_permits_formula(formula,data), "The formula cannot be applied to the data!") # add intercept to have predictable factor expansions terms_obj <- terms(formula, data = data) attr(terms_obj,"intercept") <- 1 dummy_matrix <- model.matrix(terms_obj,data) trans_vars <- colnames(dummy_matrix) # were there factors? used_factor <- names(attr(dummy_matrix,"contrasts")) expanded_factor <- NULL if (!is.null(used_factor)) { fact_index_pre <- which(attr(terms_obj,"term.labels") %in% used_factor) fact_index_trans <- which(attr(dummy_matrix,"assign") %in% fact_index_pre) expanded_factor <- trans_vars[fact_index_trans] } result <- compact(list( "names" = setdiff(trans_vars, "(Intercept)" %T% !has_constant(formula)), "factors" = expanded_factor)) return(result) } #' @keywords internal predict_tranfomed_vars <- function(formula,data) { setdiff(extract_transformed_varnames(formula,data)$names, "(Intercept)") } #' @keywords internal predict_expanded_factors <- function(formula,data) { extract_transformed_varnames(formula,data)$factors } #' @keywords internal extract_formula_specials <- function(formula,specials) { # split all terms into special or general terms_obj_formula <- terms.formula(formula, specials, allowDotAsName = TRUE) all_terms <- rownames(attr(terms_obj_formula, "factors")) special_terms <- lapply(attr(terms_obj_formula,"specials"), function(.s_index) {all_terms[.s_index]}) non_special_terms <- setdiff(all_terms,unlist(special_terms)) return(list("specials" = special_terms, "normals" = non_special_terms)) } # ---- split the formula by "special" functions ------------------------------- #' @keywords internal split_forumla_specials <- function( formula, specials) { assert_formula(formula) assert_is(specials,"character") split_terms <- extract_formula_specials(formula,specials) # first create the normal formula nt <- split_terms$normals normal_formula <- nt %|!|% reformulate(nt,intercept = has_constant(formula)) # then create the special formulas st <- split_terms$specials special_formulas <- st %|!|% Map("special_formula_as_rhs", special = names(st), string_formula = st) null_special <- unlist(lapply(special_formulas,is.null)) if (any(null_special)) { all_generals <- named_list(specials,normal_formula) special_formulas[null_special] <- all_generals[null_special] } return(special_formulas) } #' @keywords internal special_formula_as_rhs <- function(special,string_formula) { if (length(nchar(string_formula)) == 0) return(NULL) # make the special a function fun_env <- environment() assign(x = special, parse_fun_arguments_as_string, envir = fun_env) # evaluating the special -> returns its arguments a string special_rhs_formula <- eval_string_as_function(string_formula, e = fun_env) special_rhs_formula <- paste(special_rhs_formula, collapse = "") return(reformulate_string(special_rhs_formula)) } #' @keywords internal reformulate_string <- function(string_formula) { # catch empty string or only white spaces if ("" == gsub("\\s.*",replacement = "",x = string_formula)) string_formula <- "1" result <- reformulate(string_formula) result <- compact_formula(result) return(result) } #' @keywords internal parse_fun_arguments_as_string <- function(x){ deparse(substitute(x)) } #' @keywords internal eval_string_as_function <- function(x,e = environment()){ eval(parse(text = x),envir = e) }
// Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "arolla/decision_forest/pointwise_evaluation/oblivious.h" #include <limits> #include <memory> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" namespace arolla { namespace { using ::testing::ElementsAre; constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; constexpr float inf = std::numeric_limits<float>::infinity(); std::shared_ptr<SplitCondition> Cond(int input_id, float left, float right) { return std::make_shared<IntervalSplitCondition>(input_id, left, right); } TEST(ObliviousTest, Errors) { { // not power of 2 vertices DecisionTree tree; tree.split_nodes = {{A(0), S(1), Cond(0, -inf, 1.0)}, {A(1), A(2), Cond(0, -1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0}; EXPECT_EQ(ToObliviousTree(tree), std::nullopt); } { // not balanced tree DecisionTree tree; tree.split_nodes = {{A(0), S(1), Cond(0, -inf, 1.0)}, {S(2), A(2), Cond(0, -1.0, inf)}, {A(1), A(3), Cond(0, -1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; EXPECT_EQ(ToObliviousTree(tree), std::nullopt); } { // different splits on one layer DecisionTree tree; tree.split_nodes = {{S(2), S(1), Cond(0, -inf, 1.0)}, {A(1), A(2), Cond(0, -1.0, inf)}, {A(0), A(3), Cond(0, 1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; EXPECT_EQ(ToObliviousTree(tree), std::nullopt); } } TEST(ObliviousTest, Ok) { { // depth 0 with weight DecisionTree tree; tree.adjustments = {2.0}; tree.weight = 0.5; auto oblivious_tree = ToObliviousTree(tree); ASSERT_TRUE(oblivious_tree.has_value()); EXPECT_THAT(oblivious_tree->layer_splits, ElementsAre()); EXPECT_THAT(oblivious_tree->adjustments, ElementsAre(1.0)); } { // depth 1 with weight DecisionTree tree; tree.split_nodes = {{A(0), A(1), Cond(0, -inf, 1.0)}}; tree.adjustments = {7.0, 3.0}; tree.weight = 2.0; auto oblivious_tree = ToObliviousTree(tree); ASSERT_TRUE(oblivious_tree.has_value()); EXPECT_EQ(oblivious_tree->layer_splits.size(), 1); EXPECT_EQ(*oblivious_tree->layer_splits[0], *Cond(0, -inf, 1.0)); EXPECT_THAT(oblivious_tree->adjustments, ElementsAre(14.0, 6.0)); } { // depth 2 DecisionTree tree; tree.split_nodes = {{S(2), S(1), Cond(0, -inf, 1.0)}, {A(1), A(2), Cond(0, -1.0, inf)}, {A(0), A(3), Cond(0, -1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; auto oblivious_tree = ToObliviousTree(tree); ASSERT_TRUE(oblivious_tree.has_value()); EXPECT_EQ(oblivious_tree->layer_splits.size(), 2); EXPECT_EQ(*oblivious_tree->layer_splits[0], *Cond(0, -inf, 1.0)); EXPECT_EQ(*oblivious_tree->layer_splits[1], *Cond(0, -1.0, inf)); EXPECT_THAT(oblivious_tree->adjustments, ElementsAre(0.0, 3.0, 1.0, 2.0)); } } } // namespace } // namespace arolla
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue</title> </head> <body> <div id="app"> <cpn> <button slot="center">嘿嘿</button> </cpn> <cpn> <button slot="right">呵呵</button> </cpn> <cpn></cpn> </div> <template id="cpn"> <div> <slot name="left"><span>左边</span></slot> <slot name="center"><span>中间</span></slot> <slot name="right"><span>右边</span></slot> </div> </template> <script src="../js/vue.js"></script> <script> new Vue({ el: '#app', components: { cpn: { template: '#cpn' } }, data: { }, methods: { } }) </script> </body> </html>
/* * 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/>. */ /** * JSATRegression.java * Copyright (C) 2017 University of Waikato, Hamilton, NZ */ package weka.core; import weka.test.Regression; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; /** * Specicalized regression helper. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class JSATRegression extends Regression { /** Reference files have this extension. */ protected static final String FILE_EXTENSION = ".ref"; /** * The name of the system property that can be used to override the location * of the reference root. */ protected static final String ROOT_PROPERTY = "weka.test.Regression.root"; /** Default root location, relative to the users home direcory. */ protected static final String DEFAULT_ROOT = "src/test/resources"; /** Stores the root location under which reference files are stored. */ protected static File ROOT; /** Stores the output to be compared against the reference. */ protected final StringBuffer m_Output; /** The file where the reference output is (or will be) located */ protected final File m_RefFile; /** * Creates a new <code>JSATRegression</code> instance. */ public JSATRegression(Class cls, String suffix) { super(cls); String relative = cls.getName().replace('.', File.separatorChar) + (suffix == null ? "" : suffix) + FILE_EXTENSION; m_RefFile = new File(getRoot(), relative); m_Output = new StringBuffer(); } /** * Returns a <code>File</code> corresponding to the root of the reference * tree. * * @return a <code>File</code> giving the root of the reference tree. */ public static File getRoot() { if (ROOT == null) { String root = System.getProperty(ROOT_PROPERTY); if (root == null) { root = System.getProperty("user.dir"); ROOT = new File(root, DEFAULT_ROOT); } else { ROOT = new File(root); } } return ROOT; } /** * Adds some output to the current regression output. The accumulated output * will provide the material for the regression comparison. * * @param output a <code>String</code> that forms part of the regression test. */ public void println(String output) { m_Output.append(output).append('\n'); } /** * Returns the difference between the current output and the reference * version. * * @return a <code>String</code> value illustrating the differences. If this * string is empty, there are no differences. If null is returned, * there was no reference output found, and the current output has * been written as the reference. * @exception IOException if an error occurs during reading or writing of the * reference file. */ public String diff() throws IOException { try { String reference = readReference(); return diff(reference, m_Output.toString()); } catch (FileNotFoundException fnf) { // No, write out the current output writeAsReference(); return null; } } /** * Returns the difference between two strings, Will be the empty string if * there are no difference. * * @param reference a <code>String</code> value * @param current a <code>String</code> value * @return a <code>String</code> value describing the differences between the * two input strings. This will be the empty string if there are no * differences. */ protected String diff(String reference, String current) { if (reference.equals(current)) { return ""; } else { // Should do something more cunning here, like try to isolate the // actual differences. We could also try calling unix diff utility // if it exists. StringBuffer diff = new StringBuffer(); diff.append("+++ Reference: ").append(m_RefFile).append(" +++\n") .append(reference).append("+++ Current +++\n").append(current) .append("+++\n"); return diff.toString(); } } /** * Reads the reference output from a file and returns it as a String * * @return a <code>String</code> value containing the reference output * @exception IOException if an error occurs. */ protected String readReference() throws IOException { Reader r = new BufferedReader(new FileReader(m_RefFile)); StringBuffer ref = new StringBuffer(); char[] buf = new char[5]; for (int read = r.read(buf); read > 0; read = r.read(buf)) ref.append(new String(buf, 0, read)); r.close(); return ref.toString(); } /** * Writes the current output as the new reference. Normally this method is * called automatically if diff() is called with no existing reference * version. You may wish to call it explicitly if you know you want to create * the reference version. * * @exception IOException if an error occurs. */ public void writeAsReference() throws IOException { File parent = m_RefFile.getParentFile(); if (!parent.exists()) parent.mkdirs(); Writer w = new BufferedWriter(new FileWriter(m_RefFile)); w.write(m_Output.toString()); w.close(); } }
Thursday October 20th 2016 Today's objectives are: Question words Numbers Possessive adjectives there is / there are this, that, these, those adjectives vidaingles.com/app QUESTION WORDS Use question words to ask for different things. what, when, who, where, which, how, how old, why use: para preguntar por what ------------- cosas, objetos----- What are those? when ------------ hora/fecha -------- When is your birthday? who ------------- personas ---------- Who is Pedro? where ----------- lugares ----------- Where is Chichen Itza? which ----------- opciones ---------- Which is your favourite color, red or blue? how ------------- salud, cómo se hace algo -- How are you? How do you spell it? how old -------- edad How old is your brother? why ------------ motivos, razones Why do you use pants? Numbers 3,458,295 hundred thousand million Possessive adjectives I My You Your He His She Her It Its We Our You Your They Their there is / there are Se utiliza para describir lugares. clothes hammock In my bedroom there is/are ..... There isn't a ... There aren't any ... Are there any windows? Yes, there are. / No, there aren't. Is there a guitar? Yes, there is. / No, there isn't. SOME / ANY Usa "some" en frases positivas y en algunas preguntas. There are some chairs. Would you like some water? Usa "any" en frases negativas e interrogativas. There aren't any CDs. Are there any books? Adjectives Los adjetivos no se pluralizan. Van antes del sustantivo. This is an exercise book. These are recipie books. Homework> vidaingles.com/app presente simple del verbo "be" adjetivos posesivos numeros pronombres personales
/** * Sample React Native App * https://github.com/facebook/react-native * * @format */ import React from 'react'; import {PaperProvider} from 'react-native-paper'; import {NavigationContainer, DefaultTheme} from '@react-navigation/native'; import {ScoreProvider} from './context/ScoreContext'; import {RecoilRoot} from 'recoil'; import MainStack from './navigation/stacks/main-stack'; import {GPT_BACKGROUND} from './constants/colors'; const MyTheme = { ...DefaultTheme, colors: { ...DefaultTheme.colors, background: GPT_BACKGROUND, card: GPT_BACKGROUND, }, }; function App(): JSX.Element { return ( <RecoilRoot> <PaperProvider> <ScoreProvider> <NavigationContainer theme={MyTheme}> <MainStack /> </NavigationContainer> </ScoreProvider> </PaperProvider> </RecoilRoot> ); } export default App;
// Copyright 2021-2022, Offchain Labs, Inc. // For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE // SPDX-License-Identifier: BUSL-1.1 // solhint-disable-next-line compiler-version pragma solidity >=0.6.9 <0.9.0; import "./IOwnable.sol"; interface IBridge { /// @dev This is an instruction to offchain readers to inform them where to look /// for sequencer inbox batch data. This is not the type of data (eg. das, brotli encoded, or blob versioned hash) /// and this enum is not used in the state transition function, rather it informs an offchain /// reader where to find the data so that they can supply it to the replay binary enum BatchDataLocation { /// @notice The data can be found in the transaction call data TxInput, /// @notice The data can be found in an event emitted during the transaction SeparateBatchEvent, /// @notice This batch contains no data NoData, /// @notice The data can be found in the 4844 data blobs on this transaction Blob } struct TimeBounds { uint64 minTimestamp; uint64 maxTimestamp; uint64 minBlockNumber; uint64 maxBlockNumber; } event MessageDelivered( uint256 indexed messageIndex, bytes32 indexed beforeInboxAcc, address inbox, uint8 kind, address sender, bytes32 messageDataHash, uint256 baseFeeL1, uint64 timestamp ); event BridgeCallTriggered( address indexed outbox, address indexed to, uint256 value, bytes data ); event InboxToggle(address indexed inbox, bool enabled); event OutboxToggle(address indexed outbox, bool enabled); event SequencerInboxUpdated(address newSequencerInbox); event RollupUpdated(address rollup); function allowedDelayedInboxList(uint256) external returns (address); function allowedOutboxList(uint256) external returns (address); /// @dev Accumulator for delayed inbox messages; tail represents hash of the current state; each element represents the inclusion of a new message. function delayedInboxAccs(uint256) external view returns (bytes32); /// @dev Accumulator for sequencer inbox messages; tail represents hash of the current state; each element represents the inclusion of a new message. function sequencerInboxAccs(uint256) external view returns (bytes32); function rollup() external view returns (IOwnable); function sequencerInbox() external view returns (address); function activeOutbox() external view returns (address); function allowedDelayedInboxes(address inbox) external view returns (bool); function allowedOutboxes(address outbox) external view returns (bool); function sequencerReportedSubMessageCount() external view returns (uint256); function executeCall( address to, uint256 value, bytes calldata data ) external returns (bool success, bytes memory returnData); function delayedMessageCount() external view returns (uint256); function sequencerMessageCount() external view returns (uint256); // ---------- onlySequencerInbox functions ---------- function enqueueSequencerMessage( bytes32 dataHash, uint256 afterDelayedMessagesRead, uint256 prevMessageCount, uint256 newMessageCount ) external returns ( uint256 seqMessageIndex, bytes32 beforeAcc, bytes32 delayedAcc, bytes32 acc ); /** * @dev Allows the sequencer inbox to submit a delayed message of the batchPostingReport type * This is done through a separate function entrypoint instead of allowing the sequencer inbox * to call `enqueueDelayedMessage` to avoid the gas overhead of an extra SLOAD in either * every delayed inbox or every sequencer inbox call. */ function submitBatchSpendingReport(address batchPoster, bytes32 dataHash) external returns (uint256 msgNum); // ---------- onlyRollupOrOwner functions ---------- function setSequencerInbox(address _sequencerInbox) external; function setDelayedInbox(address inbox, bool enabled) external; function setOutbox(address inbox, bool enabled) external; function updateRollupAddress(IOwnable _rollup) external; }
import React, { FC } from 'react' import { Controller, SubmitHandler, useForm } from 'react-hook-form' import { connect } from 'react-redux' import useCSRF from '../../../hooks/useCSRF' import { register } from '../../../redux/reducers/authReducer/asyncActions' import { TDispatch } from '../../../redux/store' import { Props } from '../../../types/Props' import Form from '../../ui/form/Form' import SubmitButton from '../../ui/submitButton/SubmitButton' import TextInput from '../../ui/textInput/TextInput' import { datePattern } from '../../../global/regExPatterns' import { ErrorText } from '../../ui/errorText/ErrorText' interface RegisterFormProps extends Props { register: ( username: string, password: string, firstName: string, lastName: string, birthdate: string, csrf: string ) => void } interface IFormInput { login: string firstname: string lastName: string birthdate: string password: string rePassword: string } export const RegisterForm: FC<RegisterFormProps> = ({ register }) => { const { control, handleSubmit, formState: { errors }, getValues, } = useForm<IFormInput>() const csrf = useCSRF() const sendForm: SubmitHandler<IFormInput> = ({ login, password, firstname, lastName, birthdate, }) => { register(login, password, firstname, lastName, birthdate, csrf) } return ( <Form autoComplete='off' onSubmit={handleSubmit(sendForm)}> <h1>Регистрация</h1> <Controller name='login' control={control} rules={{ required: 'Поле должно быть заполнено', maxLength: { value: 150, message: 'Имя пользователя слишком большое', }, }} render={({ field }) => { return ( <TextInput placeholder='Логин' value={field.value} setValue={field.onChange} /> ) }} /> {errors.login && ( <ErrorText>{errors.login.message || 'Ошибка'}</ErrorText> )} <Controller name='firstname' control={control} rules={{ required: 'Поле должно быть заполнено', }} render={({ field }) => { return ( <TextInput placeholder='Имя' value={field.value} setValue={field.onChange} /> ) }} /> {errors.firstname && ( <ErrorText>{errors.firstname.message || 'Ошибка'}</ErrorText> )} <Controller name='lastName' control={control} rules={{ required: 'Поле должно быть заполнено', }} render={({ field }) => { return ( <TextInput placeholder='Фамилия' value={field.value} setValue={field.onChange} /> ) }} /> {errors.lastName && ( <ErrorText>{errors.lastName.message || 'Ошибка'}</ErrorText> )} <Controller name='birthdate' control={control} rules={{ required: 'Поле должно быть заполнено', pattern: { value: datePattern, message: 'Дата должна быть в формате DD.MM.YYYY', }, }} render={({ field }) => { return ( <TextInput placeholder='Дата рождения: DD.MM.YYYY' value={field.value} setValue={field.onChange} /> ) }} /> {errors.birthdate && ( <ErrorText>{errors.birthdate.message || 'Ошибка'}</ErrorText> )} <Controller name='password' control={control} rules={{ required: 'Поле должно быть заполнено', }} render={({ field }) => { return ( <TextInput placeholder='Пароль' password value={field.value} setValue={field.onChange} autoComplete='new-password' /> ) }} /> {errors.password && ( <ErrorText>{errors.password.message || 'Ошибка'}</ErrorText> )} <Controller name='rePassword' control={control} rules={{ required: 'Поле должно быть заполнено', validate: (v) => v === getValues('password') ? true : 'Пароли не совпадают', }} render={({ field }) => { return ( <TextInput placeholder='Повтор пароля' password value={field.value} setValue={field.onChange} autoComplete='new-password' /> ) }} /> {errors.rePassword && ( <ErrorText>{errors.rePassword.message || 'Ошибка'}</ErrorText> )} <SubmitButton value='Отправить' /> </Form> ) } const mapDispatchToProps = (dispatch: TDispatch) => { return { register: ( username: string, password: string, firstName: string, lastName: string, birthdate: string, csrf: string ) => dispatch( register( username, password, firstName, lastName, birthdate, csrf ) ), } } export default connect(null, mapDispatchToProps)(RegisterForm)
import type { PropsWithChildren } from 'react'; import { useCallback, useContext, useEffect, useMemo, useState } from 'react'; import type { IThemeContext } from './theme-context'; import { ThemeContext } from './theme-context'; export default function ThemeProvider({ children }: PropsWithChildren) { const [theme, setTheme] = useState<string>('light'); const toggleTheme = useCallback(() => { const updatedTheme = theme === 'light' ? 'dark' : 'light'; setTheme(updatedTheme); window.localStorage.setItem('theme', updatedTheme); }, [theme]); useEffect(() => { const localTheme = window.localStorage.getItem('theme'); if (localTheme) { setTheme(localTheme); } }, []); useEffect(() => { if (theme === 'dark') { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } }, [theme]); const providerValue = useMemo(() => ({ theme, toggleTheme }), [theme, toggleTheme]); return <ThemeContext.Provider value={providerValue}>{children}</ThemeContext.Provider>; } export const useTheme = () => useContext<IThemeContext>(ThemeContext);
import java.util.ArrayList; public class Flight { private ArrayList<Passenger> passengers; private Plane plane; private String flightNumber; private String destination; private String departureAirport; private String departureTime; public Flight(Plane plane, String flightNumber, String destination, String departureAirport, String departureTime){ this.passengers = new ArrayList<Passenger>(); this.plane = plane; this.flightNumber = flightNumber; this.destination = destination; this.departureAirport = departureAirport; this.departureTime = departureTime; } public int getNumberOfPassengers(){ return this.passengers.size(); } public Plane getPlaneModel(){ return this.plane; } public String getFlightNumber(){ return this.flightNumber; } public String getDestination(){ return this.destination; } public String getDepartureAirport(){ return this.departureAirport; } public String getDepartureTime(){ return this.departureTime; } public void addPassenger(Passenger passenger) { if (this.checkAvailableSeats() > 0) { this.passengers.add(passenger); passenger.setFlight(this); } } public int checkAvailableSeats(){ return this.plane.getCapacity() - this.passengers.size(); } }
import { createFastContext } from "./create-fast-context"; import styles from './context.module.css' const {Provider, useStore} = createFastContext({ first: "", last: "", }); const TextInput = ({value}: { value: "first" | "last" }) => { const [fieldValue, setStore] = useStore((store) => store[value]); return ( <div className={styles.field}> {value}:{" "} <input value={fieldValue} onChange={(e) => setStore({[value]: e.target.value})} /> </div> ); }; const Display = ({value}: { value: "first" | "last" }) => { const [fieldValue] = useStore((store) => store[value]); return ( <div className={styles.value}> {value}: {fieldValue} </div> ); }; const FormContainer = () => { return ( <div className={styles.container}> <h5>FormContainer</h5> <TextInput value="first"/> <TextInput value="last"/> </div> ); }; const DisplayContainer = () => { return ( <div className={styles.container}> <h5>DisplayContainer</h5> <Display value="first"/> <Display value="last"/> </div> ); }; const ContentContainer = () => { return ( <div className={styles.container}> <h5>ContentContainer</h5> <FormContainer/> <DisplayContainer/> </div> ); }; export function FastContextContent() { return ( <Provider> <div className={styles.container}> <h5>App</h5> <ContentContainer/> </div> </Provider> ); }
import React from 'react'; const TimestampConverter = ({ timestamp }) => { const months = [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', ]; const formatDate = (dateString) => { const date = new Date(dateString); const day = date.getDate(); const month = months[date.getMonth()]; const year = date.getFullYear(); return `${day} ${month} ${year}`; }; const formatTimeDifference = (timestamp) => { const currentDate = new Date(); const timestampDate = new Date(timestamp); const timeDifference = currentDate - timestampDate; const days = Math.floor(timeDifference / (24 * 60 * 60 * 1000)); if (days === 0) { const hours = Math.floor(timeDifference / (60 * 60 * 1000)); if (hours === 0) { const minutes = Math.floor(timeDifference / (60 * 1000)); if (minutes === 0) { return `in a few seconds`; } return `${minutes}m`; } return `${hours}h`; } else if (days <= 30) { return `${days}d`; } else { return formatDate(timestamp); } }; return <div>{formatTimeDifference(timestamp)}</div>; }; export default TimestampConverter;
/* This SQL script provides a comprehensive analysis of retail sales data, targeting the consumer electronics sector with a focus on monthly sales performance, customer behavior, and product pricing strategies. Through a series of meticulously crafted queries, it reveals insights into sales volume and revenue generation for key products like the iPhone, tracks customer transactions to understand buying patterns, and identifies the most economical product offerings. By analyzing sales data from January and February, including specific days with high sales volume and locations with significant customer engagement, the script offers valuable perspectives on market trends, customer preferences, and the effectiveness of sales strategies. The script not only demonstrates an adept handling of SQL for data analysis but also serves as a strategic tool for businesses in the consumer electronics market to optimize their sales approaches, enhance customer satisfaction, and drive revenue growth. */ -- Count the total number of orders placed in January. SELECT COUNT(orderid) FROM JanSales; -- Retrieve the location of orders placed on February 18, 2019, at 1:35 AM. SELECT location FROM FebSales WHERE orderdate = '02/18/19 01:35'; -- Count the total number of orders for iPhones sold in January. SELECT COUNT(orderid) FROM JanSales WHERE Product='iPhone'; -- List distinct account numbers of customers who made purchases in February, ensuring we're only considering those present in both customers and FebSales tables. SELECT DISTINCT acctnum FROM customers cust INNER JOIN FebSales Feb ON cust.order_id = Feb.orderid; -- Calculate the total quantity of all products sold on February 18, 2019. SELECT SUM(quantity) FROM FebSales WHERE orderdate LIKE '02/18/19%'; -- Retrieve the product with the lowest price sold in January. Limit to 1 to ensure we only get the single cheapest product. SELECT DISTINCT product, price FROM JanSales ORDER BY price ASC LIMIT 1; -- Calculate the total revenue (sum of quantity multiplied by price) per product for January sales. SELECT SUM(quantity) * price AS total_revenue, product FROM JanSales GROUP BY product; -- Count the number of products sold and the total revenue generated from sales at a specific location in February. SELECT COUNT(product), product, SUM(quantity) AS rev FROM FebSales AS f, customers AS c WHERE f.orderID = c.order_id AND f.location = '548 Lincoln St, Seattle, WA 98101' GROUP BY product; -- For customers who placed orders with more than 2 items in February, calculate the average revenue (quantity*price) and count the distinct account numbers. Filters out any erroneous order IDs. SELECT COUNT(DISTINCT cust.acctnum), AVG(quantity*price) FROM FebSales Feb, customers cust WHERE Feb.orderid = cust.order_id AND Feb.Quantity > 2 AND LENGTH(orderid) = 6 AND orderid <> 'Order ID'; -- Select the order dates for orders placed between February 13, 2019, and February 18, 2019. SELECT orderdate FROM FebSales WHERE orderdate BETWEEN '02/13/19 00:00' AND '02/18/19 00:00';
// Link : https://leetcode.com/problems/set-matrix-zeroes // Code: class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int n = matrix.size(); int m = matrix[0].size(); bool isRow = false; bool isCol = false; for(int i = 0;i < n;i++){ for(int j = 0;j < m;j++){ if(i == 0 && matrix[i][j] == 0){ isRow = true; } if(j == 0 && matrix[i][j] == 0){ isCol = true; } if(matrix[i][j] == 0){ matrix[i][0] = 0; matrix[0][j] = 0; } } } for(int i = 1;i < n;i++){ for(int j = 1;j < m;j++){ if(matrix[i][0] == 0 || matrix[0][j] == 0){ matrix[i][j] = 0; } } } if(isRow){ for(int j = 0;j < m;j++){ matrix[0][j] = 0; } } if(isCol){ for(int i = 0;i < n;i++){ matrix[i][0] = 0; } } } }; /* Time complexity: O(N * M) Space complexity: O(1) */ // Code by Shumbul Arifa - https://linktr.ee/shumbul
import { Component, OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; import { Reservation } from 'src/app/models/reservation.model'; import { DateService } from 'src/app/services/date.service'; import { ErrorService } from 'src/app/services/error.service'; import { ScheduleService } from 'src/app/services/schedule.service'; @Component({ selector: 'app-reservation-list', templateUrl: './reservation-list.component.html', styleUrls: ['./reservation-list.component.scss'], }) export class ReservationListComponent implements OnInit { public reservations: Reservation[] = []; public editModeArr: boolean[] = []; constructor( private scheduleService: ScheduleService, private dateService: DateService, private errorService: ErrorService ) {} ngOnInit(): void { this.scheduleService.getAllReservations().subscribe({ next: (loadedRes: Reservation[]) => { this.reservations = loadedRes; this.restartEditMode(); }, error: () => this.errorService.displayAlertMessage(), }); this.scheduleService.refreshReservationsRequired.subscribe(() => { this.scheduleService .getAllReservations() .subscribe((loadedRes: Reservation[]) => { this.reservations = loadedRes; this.restartEditMode(); }); }); } public getHowLong(reservation: Reservation): number { const time = new Date(reservation.end).getTime() - new Date(reservation.start).getTime(); return Math.floor(time / 1000 / 60); } public onDelete(deletedRes: Reservation): void { this.scheduleService.deleteReservation(deletedRes).subscribe(() => { this.reservations = this.reservations.filter((r) => r !== deletedRes); }); } public onEdit(index: number): void { this.editModeArr[index] = true; } public onCancel(): void { this.restartEditMode(); } public onSubmit(editedRes: Reservation, form: NgForm): void { editedRes.start = this.dateService.setDateStart(form); editedRes.end = this.dateService.setDateEnd(form); this.scheduleService.updateReservation(editedRes).subscribe(); this.restartEditMode(); form.resetForm(); } private restartEditMode(): void { this.editModeArr = this.editModeArr = new Array( this.reservations.length ).fill(false); } }
/* eslint-disable react/style-prop-object */ /* eslint-disable react-hooks/exhaustive-deps */ import React, { Fragment, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { getOneAction } from "redux/actions/actions"; import { getUserId } from "utils"; import * as actionType from "redux/actions/actionTypes"; import Pagination from "shared/components/Pagination/Pagination"; import LoadingSpinner from "shared/components/Spinner/LoadingSpinner"; import { usePagination } from "shared/hooks/usePagination"; import Container from "shared/components/Layout/Container/Container"; import Card from "shared/components/Card/Card"; import GridRow from "shared/components/Layout/Grid/GridRow"; import GridColumn from "shared/components/Layout/Grid/GridColumn"; import LayoutCenterChildren from "shared/components/Layout/Positioning/LayoutCenterChildren"; import Avatar from "shared/components/Image/Avatar"; import ButtonNavLink from "shared/components/Button/ButtonNavLink"; import LayoutSpacer from "shared/components/Layout/Positioning/LayoutSpacer"; import Table from "shared/components/Table/Table"; import { PLAIN_TEXT } from "shared/components/Button/buttonType"; function UserWord() { const dispatch = useDispatch(); const { user, learned } = useSelector((state) => state.users); useEffect(() => { dispatch(getOneAction(`/api/users/${getUserId()}`, actionType.GET_USER)); }, []); const { itemsPerPage, itemPaginated, paginate } = usePagination( 5, learned.words ); if (!itemPaginated) { return <LoadingSpinner />; } return ( <Fragment> <Container> <Card style="p-2"> <GridRow style="grid-cols-12"> <GridColumn style="lg:col-span-4 md:col-span-4 col-span-12"> <LayoutCenterChildren> <Avatar img={user?.avatar} customStyle={{ width: 200, height: 200 }} /> </LayoutCenterChildren> <LayoutCenterChildren> <p className="uppercase font-bold mb-5"> {user?.first_name + " " + user?.last_name || ""} </p> </LayoutCenterChildren> <LayoutCenterChildren> <ButtonNavLink text={`Learned ${learned.categoriesCount} categories`} style={PLAIN_TEXT} link="/user/learned/categories" /> </LayoutCenterChildren> </GridColumn> <GridColumn style="lg:col-span-8 md:col-span-8 col-span-12"> <Card> <LayoutSpacer spacer={1}> <h4>Learned Words</h4> </LayoutSpacer> <Table tableHeader={["Word", "Translation"]}> {itemPaginated && itemPaginated?.map((item) => ( <tr key={item.word_id}> <td className="px-6 py-4 text-sm text-gray-900"> {item.word} </td> <td className="px-6 py-4 text-sm text-gray-900"> {item.translation} </td> </tr> ))} </Table> <Pagination itemsPerPage={itemsPerPage} totalItems={learned.wordsCount} paginateTo={paginate} /> </Card> </GridColumn> </GridRow> </Card> </Container> </Fragment> ); } export default UserWord;
# WeBWorK problem written by Alex Jordan # Portland Community College # ENDDESCRIPTION ############################################## DOCUMENT(); loadMacros( "PGstandard.pl", "MathObjects.pl", "parserNumberWithUnits.pl", ); ############################################## TEXT(beginproblem()); Context("Numeric"); $windSpeed = random(10,30,0.1); $w = $windSpeed; $airSpeed = random(180,300,1); $distance[0] = random(600,1000,10); $d0 = $distance[0]; $distance[1] = ($airSpeed-$windSpeed)*$distance[0]/($airSpeed+$windSpeed); $distance[1] = round($distance[1]); $d1 = $distance[1]; $airSpeed = -$w*($d0+$d1)/($d1-$d0); $windSpeed = NumberWithUnits("$windSpeed","mi/hr"); $airSpeed = NumberWithUnits("$airSpeed","mi/hr"); $distance[0] = NumberWithUnits("$distance[0]","mi"); $distance[1] = NumberWithUnits("$distance[1]","mi"); ############################################## Context()->texStrings; BEGIN_TEXT When there is a \($windSpeed\) wind, an airplane can fly \($distance[0]\) with the wind in the same time that it can fly \($distance[1]\) against the wind. Find the speed of the plane when there is no wind. $PAR The plane's airspeed is \{ans_rule(15)\}. END_TEXT Context()->normalStrings; ############################################## $showPartialCorrectAnswers = 1; ANS( $airSpeed->cmp(tolerance=>0.01)); ENDDOCUMENT();
package com.github.practice.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.servlet.mvc.support.RedirectAttributes; import com.github.practice.domain.Article; import com.github.practice.dto.ArticleFormDTO; import com.github.practice.repository.ArticleRepository; import lombok.extern.slf4j.Slf4j; @Slf4j @Controller public class ArticleController { @Autowired ArticleRepository repository; @GetMapping("/") public String index() { return "index"; } @GetMapping("/articles/new") public String newArticleForm() { return "articles/new"; } @PostMapping("/articles/create") public String createArticle(ArticleFormDTO dto) { Article entity = dto.toEntity(); Article saved = repository.save(entity); log.info(saved.toString()); return "redirect:/articles/"+saved.getId(); } @GetMapping("/hi") public String hi(Model model) { model.addAttribute("username", "주아"); return "hi"; } @GetMapping("/articles/{id}") public String show(@PathVariable("id") Long id, Model model) { Article article = repository.findById(id).orElse(null); if (article == null) { return "articles/show"; } model.addAttribute("article", article); return "articles/show"; } @GetMapping("/articles") public String listArticles(Model model) { List<Article> articles = repository.findAll(); model.addAttribute("articleList", articles); return "articles/article-list"; } @GetMapping("/articles/{id}/edit") public String edit(@PathVariable("id") Long id, Model model) { Article article = repository.findById(id).orElse(null); model.addAttribute("article", article); return "/articles/edit"; } @PostMapping("/articles/update") public String update(ArticleFormDTO dto) { Article article = repository.findById(dto.getId()).orElse(null); if (article == null) { return "redirect:/articles"; } Article updatedArticle = dto.toEntity(); repository.save(updatedArticle); return "redirect:/articles/"+updatedArticle.getId(); } @GetMapping("/articles/{id}/delete") public String delete(@PathVariable Long id, RedirectAttributes redirectAttributes) { Article article = repository.findById(id).orElse(null); log.info("delete article {}", article); if (article == null) { return "redirect:/articles"; } repository.deleteById(id); redirectAttributes.addFlashAttribute("msg", "Deleted article " + article.getTitle()); return "redirect:/articles"; } }
# t3-a1-workbook ## Introduction As a developer (dev) you are sometimes required to prove your knowledge to prospective clients and employers. ## Brief In order to demonstrate your understanding of fundamental software concepts, you will provide answers to a series of short answer questions. ## Q1 Provide an overview and description of a standard source control process for a large project Source Control is a crucial process of software development because it helps teams effectively collaborate the management of code commits and version control. This is essential for large scale projects to ensure the code integrity and fluid cooperation. Below are the stages and practices utilised in large scale projects. ### Selecting a Version Control System Selecting and sticking to a version control system that suits the projects requirements is essential as it allows for fluid collaboration. A good example of Version Control Systems is Git. It has provided developers with the option to branch and merge code cheaply. "Git really changed the way developers think of merging and branching. From the classic CVS/Subversion world I came from, merging/branching has always been considered a bit scary (“beware of merge conflicts, they bite you!”) and something you only do every once in a while." (Driessen, n.d.) ### Branching Strategy Utilising a branching method is important as it facilitates concurrent development and allows developers to focus on tasks individually without interrupting the work and control flow of the entire team. Github for example provides branching within their repos that allow approved users to clone the source code into a separate branch its intended format with the version control of packages required to run it. ### Code Review Process Once developers have have completed their assigned tasks within their branch they submit a pull request. This request is then reviewed by generally a senior programmer to check for any issues/potential errors and suggest recommended changes. Depending on the decision, either pull request is accepted or rejected. If the pull request is accepted the proposed changes of the branch will be merged with the main branch and the source code is updated. ### Resolve conflicts This is a step that coincides with the Code review process as programmers working on the same source code can sometimes have conflicts on their proposed changes. The proposed changes from pull requests will need to be reviewed by the team to determine whether the proposed code can be combined or if redundant code is found and needs to be eliminated. ### Testing and Quality Assurance When the changes have been merged with the source code. Testing is required to ensure that the changes added to the source code works as intended without any side effects or errors. For example for applications written in Javascript can be tested utilising tools such as Jest, Mocha or Cypress. ### Release After all the changes have been examined and tested and approved. The team then releases the source code to production. In conclusion the source control process is important because it allows the team to collaborate and ensure proposed changes are correctly monitored and effectively managed. It ensures that the source code until all the review/testing processes have been completed. ## Q2 What are the most important aspects of quality software? Depending the requirements of the project, the most crucial elements of high quality software can change. However, some typical elements that are frequently seen as crucial for high quality software are as below: ### Reliability Software should reliably carry out its tasks as intended without interruptions or errors. It should be able to gracefully handle unforseen inputs or conditios that could trigger an error. ### Functionality Software should provide the required features/capabilities as outlined within the criteria. It should carry out the tasks it promised as intended for accurately and effectively. ### Usability Software should be designed to be simple and intuitive to use for the targeted userbase. This allows users to explore the options and capabilities with ease. It is important for effective and succinct documentation to be provided to the users so they can undertand the full scale of capabilites of the software. ### Performance Quality software should be able to efficiently respond quickly providing effective user interactions. The software should be able to effectively handle the expected workload gracefully without any errors. ### Security It is important that Software is designed to safeguard user information and prevent unauthorised access to sensitive data for nefarious purposes. ### Maintainability Quality software should be designed with maintenance frameworks and scalability depending on the requirements of the user. It is important that the code is clear and easy to read and accompanied with proper documentation such as version control. In conclusion Quality is important in software as this minimises the potential for unintended mishaps and errors "cost of a mistake might be just too high. History knows many examples of situations when software flaws have caused billions of dollars in waste or even lead to casualties: from Starbucks coffee shops being forced to give away free drinks because of a register malfunction, to the F-35 military aircraft being unable to detect the targets correctly because of a radar failure."(Quality Assurance, Quality Control and Testing — the Basics of Software Quality Management, 2020). ## Q3 Outline a standard high level structure for a MERN stack application and explain the components MERN stack application is web based application that utilises MERN which consists of (MongoDB, Express.js, React.js, Node.js). It is a well known technology stack and popular amonsgt developers for full stack Javascript applications."MERN Stack is a Javascript Stack that is used for easier and faster deployment of full-stack web applications."(Jasraj, 2021) The MERN stack consists of the following: #### MongoDB NoSQL document database that offers exceptional performance, scalability and flexibility while handling complicated data at the same time. It stores data in a flexible format similar to JSON known as BSON or Binary JSON. #### Express.js Is a quick and intuitive Node.js application framework. It provides a variety of features and tools to facilitate creation of APIs and web applications. Functions such as Routing, Request and Response handling are sorted by Express.js #### React.js React is a Javascript library that allows programmers to create reusable user interface elements and effectively handle application integrity. #### Node.js Node is a Javascript runtime thatallows programmers to write Javascript code to be executed on the server side. Node.js provides a framework that has scalability and event driven architecture for building effective network applications. It allows programmers to utilise Javascript for both Front end and Back end therefore enabling Full stack development in one language. ### Components of MERN Stack application #### Front-End With the front end of a MERN stack application React.js is used by developers to manage the structure of an application while generating reusable User Interface components. It typically consists of User interface elements, client side logic and views. "React is used for the development of single-page applications and mobile applications because of its ability to handle rapidly changing data"(MERN Stack - GeeksforGeeks, 2019). #### Back-end and Middle-ware In regards to the back-end, Node.js and Express.js are utilised to build the MERN stack application. Node.js is responsible for data processing, business logic and communications between databases. Express.js is utilised for the its capabilities in routing and tools in relation to developing APIs. "Rather than writing the code using Node.js and creating loads of Node modules, Express makes it simpler and easier to write the back-end code."(MERN Stack - GeeksforGeeks, 2019). #### Database Within the MERN stack application, the databse system used is MongoDB. It is a NoSQL document-database which provides strong capabilities in handling and processing complex data structures. Developers utilise this system to store and retrieve data in a JSON-like format. "MongoDB is flexible and allows its users to create schema, databases, tables, etc. Documents that are identifiable by a primary key make up the basic unit of MongoDB."(MERN Stack - GeeksforGeeks, 2019) #### Deployment In the final stage of the MERN stack application, it can be set up using a variety of different systems such as AWS and Azure cloud services or installed into a server utilising tools such as Docker. ## Q4 A team is about to engage in a project, developing a website for a small business. What knowledge and skills would they need in order to develop the project? There is quite a few elements that a team would need to consider when it comes to taking on a project. It would require a good balance of technical skills such as project management, technical expertise and communication skills. It is found that the general knowledge and skills required to take on a project such as developing a website for a small business would be the following: ### Front-end Web Development It is an important consideration whether the team has the required skills and knowledge of Front-end development to apply and develop the website that will meet the consumers requirements. The team should have a strong skill and knowledge base within development frameworks such as React.js or Angular and experience with languages such as HTML, CSS and Javascript. With these skills the team should be able to develop intuitive and responsive websites that would meet the clients requirements. "According to Krug’s first law of usability, the web-page should be obvious and self-explanatory."(Friedman , 2021) ### Back-end Development The team would need to ensure that they have the required proficiency within back-end development. This would require foundation and understanding of programming languages such as Node.js or Python and experience working with frameworks such as Express.js and Django. Developers would require these crucial skills as they have ### Database Management Team should also have a base of knowledge and familiarity of database systems such as Postgres, MySQL and MongoDB, it is crucial so developers can implement data structures, security and maintenance of data. ### Responsive User Interface Design Another matter to consider is that although a website that is developed to be efficient or function as intended if it is not visually appealing or responsive, users will not consider using it. Developers would do well to have an understanding and skill base using applications such as Adobe XD, Sketch and Figma because it allows them to consider the visual elements of websites and adaptability with responsive design to attract target users."Very simple principle: If a website isn’t able to meet users’ expectations, then designer failed to get his job done properly and the company loses money."(Friedman , 2021) ### Project Management and Collaboration While considering the teams capability and the clients requirements for the website, it is crucial for the team to establish the framework of project and how it's progress is managed. It is important to consider the compatibility of developers aswell ensuring that the team has a system in place such as Agile or Scrum to manage the workload and deadlines. Meetings and Huddles are important to encourage collaboration and communicate requirements or changes within the project. In conclusion it is important that teams consider not only technical ability but also other skills such as design and project management collaboration skills to ensure that when a project such as a website is considered, they will have the required skills to tackle the project with efficiency and effectiveness. ## Q5 With reference to one of your own projects, discuss what knowledge or skills were required to complete your project, and to overcome challenges For example when I was developing an API used for booking agents, tour guides and consumers to connect. There was some challenges and skills that were required for the completion of the project. Below were some of the skills and also some challenges that were faced to complete this project. ### Backend Development In this project I was required to have a good understanding of implementing the API functions and database. It was important as I needed to establish server side functionality, ability to handle requests, authentication and storing data within the database. I needed a base of knowledge with Python to effectively establish the API requests, functions and error handling with grace. ### Database Management Within this project I was required to have a good understanding and base in utilising a Database system with its capabilities. In this project I used Postgres to establish my database, design schemas, managing data storage and implementation of queries. There was definitely challenges in relation to linking different data and ensuring it was functioning as intended in tandem with the API requests. ### Version Control Within this project I needed to be experienced in managing the projects data and source code. I used Github as my repo system to establish consistency for my project and keeping track of my changes to the code and notes. It was also required so I could keep track of the packages I utilised for the Python project. ### Project Management For the project I utilised a project management software called Trello to allow me to organise and keep track of the projects tasks and notes. This allowed me to effectively keep track of the progress and any outstanding tasks that need attention. In conclusion I had to use alot of different skills and knowledge bases to effectively tackle this project. There was challenges across each element of the project but with the skills and problem solving nature required of a developer I was able to overcome them and accomplish the set task. ## Q6 With reference to one of your own projects, evaluate how effective your knowledge and skills were for this project, and suggest changes or improvements for future projects of a similar nature For the example with the API project I developed although I was able to accomplish the task and establish the API I did feel that there some short comings and challenges I could've been more effective at tackling through much deeper and effective research. ### Backend Development In this component I believe I could've done further research into example projects and tutorials to understand the full capabilities of Python and effectively utilising it. ### Database Management With Postgres I had some challenges with establishing the links between data and the API project. I think with further research and tutorials to effectively circumnavigate the errors and challenges. ### Project Management I had some challenges with the technical aspects of the project but I feel that with more effective task allocation and deadline management I could've done a much more efficient job at completing the API. ## Q7 Explain control flow, using an example from the JavaScript programming language in definition Control Flow is the sequence in which statements are carried out in order by a program. Developers are able to control the flow of the source code in specific conditions. For Example, a popular programming language such as Javascript provides a variety of methods to control flow like If-Else Statements, Loops, Ternary Operators and Switch Statements. Below are explanations of the various methods used. ### Switch Statements This state gives the developer the option to execute different blocks of code based on specific conditions that are satisfied, if it is not satisfied it will continue down the code block until a condition can be satisfied. The developer is able to handle various possible outcomes gracefully within a single expression. Please see below: ```javascript let pokemon = "Pikachu"; switch (pokemon) { case "pikachu": console.log("It's a Pikachu!"); // Since variable is Pikachu it will console.log the above message and then break break; case "charmander": console.log("It's a Charmander"); // If in a situation the variable was Charmander it will console.log the above and then break break; default: console.log("Its just another pokemon"); // If the variable was anything else that didn't meet the specific conditions it will default to the above message break; } ``` ### Loops This is used to execute specific blocks of code repeatedly until the condition is met. Javascripts provides several variations of Loops for specific situations such as For Loops and Do-While loops. Please below example of For loops ```javascript for (let i = 0; i < 5; i++) { console.log(i); // In this example // Variable (i) = 0 // Condition is if (i) less than 5 then execute console.log but also for each time (i) is used in the expression it will be incremented. Creating a Loop until the condition is not able to be satisfied. } ``` ### If-Else Statements This statement is used by developers for executing blocks of code based on specific conditions. If the condition is True then a specific code within that block will be executed. If not then the code within the Else block will be executed. Below is an example: ```javascript let num = 10; if (num > 0) { console.log("The number is positive."); } else { console.log("The number is negative or zero."); } // In this example the variable is 10 // If statement is if the variable is less than 0 then execute the If block or either run Else block. ``` ## Q8 Explain type coercion, using examples from the JavaScript programming language Type Coercion in Javascript is the process of automatic conversion of one data type into another. "This includes conversion from Number to String, String to Number, Boolean to Number etc. when different types of operators are applied to the values."(What Is Type Coercion in JavaScript, 2023) When a function or operator requests a data type that is different from existing data type, a conversion occurs. For example a popular programming language such as Javascript performs Type Coercion which gives developers flexbility but it sometimes can lead to side effects if the process is not fully understood. Below are examples of the types of Coercion by Javascript ### Explicit Coercion This type of conversion is intentional when converting a value from one data into another by using functions or methods. Please see below example ```javascript let num = 10; let str = String(num); // This explicitly converts the number into string data console.log(str); // Outputs "10" but as a string ``` ### Implicit Coercion In contrast Implicit coercion occurs when Javascript converts the data from one into another without a direct or explicit conversion. This commonly happens when operators or functions are established for different data types. Please see example below: ```javascript let num = "10"; let str = "5"; // As you can see there is number data type as 10 and a string data type as 5 console.log(num+str); // Output of Console.log would be 105 // In the Console.log with the + operator, what happens is that Javascript will apply implicit conversion which changes the number data type into str and concatenates the data. This can lead to unexpected results. ``` ## Q9 Explain data types, using examples from the JavaScript programming language Within Javascript, numerous data types can be assigned to variables such as Null, Boolean, Number, Undefined, String and Object. Please see below Examples of Data types with explanations. ### Boolean This data type represents a logical entity that is limited to only 2 outcomes being True or False. This Data type is commonly utilised by developers for situations where conditional operations are required. For example: ```javascript let isTrue = true; let isFalse = false; (isTrue == true) // Returns true (isFalse == true) // Returns false ``` ### Number This data type is for representing numerics such as integers and floating numbers. For Example ```javascript let myNumber = 10; let pi = 3.14159; console.log(myNumber); // Output is 10 console.log(pi); // Output is 3.14159 ``` ### Null Represents the lack of any value intentionally. It is a keyword in Javascript. For example ```javascript let nullVariable = null; console.log(nullVariable); // Output is null ``` ### Undefined This data type is used for an undefined value. Developers utilise it as a normal value and global property in Javascript. For example: ```javascript let randomVariable; console.log(randomVariable); // Output is undefined ``` ### Object This datatype is used to represent a collection of key value pairs. Developers use it Objects for its capability to hold a variety of data types making it vital in Javascript. For example: ```javascript let randomObject = { brand: "Toyota", type: "Hatch"}; console.log(randomObject); // Output would be { brand: "Toyota", type: "Hatch"} ``` ## Q10 Explain how arrays can be manipulated in JavaScript, using examples from the JavaScript programming language Javascript uses arrays to store a number of values within a variable. There is a variety of methods and processes that developers can employ to manipulate the data. Please see examples below of various methods that can be used: ### Accessing Array Elements Elements can be accessed through their Index numbers ranging from 0 and onwards. See below example: ```javascript let pokemon = ['pikachu', 'charmander', 'squirtle']; console.log(pokemon[0]); // Output will be Pikachu console.log(pokemon[1]); // Output will be Charmander console.log(pokemon[2]); // Output will be Squirtle ``` ### Adding Elements to an Array Developers can add elements into an array through methods such as push() and concat(). See below examples ```javascript let anime = ['Dragonball', 'Pokemon', 'Hunterxhunter']; anime.push('One Piece'); // Adds 'One Piece" to the end of the array console.log(anime); // Output: ['Dragonball', 'Pokemon', 'Hunterxhunter', 'One Piece'] let moreAnime = anime.concat(['Bleach', 'Naruto',]); //This concatenates two arrays together console.log(moreAnime) //Output :['Dragonball', 'Pokemon', 'Hunterxhunter', 'One Piece','Bleach', 'Naruto'] ``` ### Removing Elements from an Array We can remove elements within an array through methods such as pop(), shift() and splice(). See below examples ```javascript let pokemon = ['pikachu', 'charmander', 'bulbasaur']; pokemon.pop(); // Removes the last element from the array console.log(pokemon); // Output: ['pikachu', 'charmander'] pokemon.shift(); // Removes the first element from the array console.log(pokemon); // Output: ['charmander'] pokemon.splice(1, 1); // Removes one element at index 1 console.log(pokemon); // Output: ['charmander'] ``` ### Modifying Array Elements Elements within an Array can be modified through the method of assigning to a specific index. See below example ```javascript let pokemon = ['pikachu', 'charmander', 'bulbasaur']; pokemon[1] = 'eevee'; // Modifies the value at index 1 console.log(pokemon); // Output: ['pikachu', 'eevee', 'bulbasaur'] ``` ## Q11 Explain how objects can be manipulated in JavaScript, using examples from the JavaScript programming language. Javascript offers alot of flexibility to developers especially in relation to Ojects. Objects can be easily manipulated using various statements and techniques. "We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key. It’s easy to find a file by its name or add/remove a file."(Kantor, n.d.). ### Accessing an Object Javascript allows access to an Objects properties through Dot Notation or Bracket notation depending on the situation. For example developers would utilise Dot notation when the property name is known while for situations that involve accessing the property name is stored within a variable. See below code snippet as an example: ```javascript const pokemon = { name: "Pikachu", type: "Electric" }; console.log(pokemon.name); // Output: Pikachu - using dot notation console.log(pokemon["type"]); // Output: Electric - using bracket notation to access property name "type" which is within variable "pokemon" ``` ### Addition and Update of Object properties Within Javascript you can add and update properties of objects by assigning them values. See below examples ```javascript const pokemon = { name: "Pikachu", type: "Electric" }; person.move = "Thundershock"; // Adding a new property to variable person.type = "Normal"; // Updating an existing property type within the variable console.log(pokemon); // Output: { name: "Pikachu", type: "Normal", move: "Thundershock" } ``` ### Deleting Object Properties Javascript allows developers the option to delete properties through statement "delete". See below example ```javascript const pokemon = { name: "Pikachu", type: "Electric" }; delete person.type; console.log(pokemon); // Output: { name: "Pikachu" } - property "type" has been removed from log ``` ## Q12 Explain how JSON can be manipulated in JavaScript, using examples from the JavaScript programming language JSON or also known as JavaScript Object Notation is a lightweight data interchange format that is text based and is commonly utilised for data transmission and manipulation within web applications. JSON format was sourced from Javascript Object Syntax that is rendered in curly braces. "JSON was developed to be used any programming language" (Tagliaferri, 2021) Below are explanations of some of the methods that JSON data can be manipulated with Javascript: ### Stringify JSON This method involves the conversion of the Javascript object into a JSON string. To do this we use the JSON.stringify() statement. See below example ```javascript const pokemon = { name: "Pikachu", type: "Electric" }; const jsonString = JSON.stringify(pokemon); console.log(jsonString); // Output: {"name":"Pikachu","type":"Electric"} ``` ### Parsing JSON This method converts a JSON string into a JavaScript Object. To do this you would employ the JSON.parse() Statement. See below example: ```javascript const jsonString = '{"name": "Pikachu", "type": "Electric"}'; const jsonObject = JSON.parse(jsonString); console.log(jsonObject.name); // Output: Pikachu console.log(jsonObject.type); // Output: Electric ``` ### Manipulating JSON data Once the JSON string has been "parsed" and converted into a Javascript Object, it can also have its properties altered just like any other Object in Javascript. Please see below Examples ```javascript const jsonObject = { name: "Pikachu", type: "Electric" }; // Updates the property value jsonObject.type = "Normal"; // Adds a new property jsonObject.move = "Thunderbolt"; // Deletes the existing property value delete jsonObject.type; console.log(jsonObject); // Output: { name: "Pikachu", move: "Thunderbolt" } ``` ## Q13 For the code snippet provided below, write comments for each line of code to explain its functionality. In your comments you must demonstrates your ability to recognise and identify functions, ranges and classes ```javascript class Car { constructor(brand) { // Defines Constructor function within the "Car" class with the parameter "brand" this.carname = brand; // Assigns the value of 'brand' to the 'carname' property of the Car object } present() { // Defines the "present" method for class "Car" return 'I have a ' + this.carname; // Returns data in a string in addition with value of "carname" } } class Model extends Car { // Defines class "Model" which is an extension to class "Car" constructor(brand, mod) { // Defines Constructor function within the "Model" class with the parameters "brand" and 'mod' super(brand); // "super" function is called within the class "Model" and "Car" and then passes an argument with the parameter "brand" this.model = mod; //This assigns the value of "mod" to the "model" property within the Class "model" } show() { // Defining the "show" method for the class "Model" return this.present() + ', it was made in ' + this.model; // Returns string data that is Concatenated with method "present" and value of property "model" } } let makes = ["Ford", "Holden", "Toyota"]; // Declaration of an array with 3 elements let models = Array.from(new Array(40), (x,i) => i + 1980); // Generates an Array as "models" with parameters "x" and "i" and numbers ranging from 1980 to 2020 function randomIntFromInterval(min,max) { // Defines the function "randomIntFromInterval" with parameters "min" and "max" return Math.floor(Math.random()*(max-min+1)+min); // Statement returns a randomised integer that is between parameters "min" and "max" } for (model of models) { // For loop that iterates each element "model" over in array "models" make = makes[randomIntFromInterval(0,makes.length-1)]; // Assigns a random "make" from the array "makes" to the "make" variable model = models[randomIntFromInterval(0,makes.length-1)]; // Assigns a random "model" from the array "models" to the "model" variable mycar = new Model(make, model); // New Instance of Class "Model" is created with parameters "make" and "model" as arguments which is assigned to "mycar" object console.log(mycar.show()); // Statement that calls "show" method from Object "mycar" and then logs result to console terminal } ``` ## References ### Q1 Driessen, V. D. (n.d.). A successful Git branching model. https://nvie.com/. Retrieved September 13, 2023, from https://nvie.com/posts/a-successful-git-branching-model/ ### Q2 Quality Assurance, Quality Control and Testing — the Basics of Software Quality Management. (2020, January 6). AltexSoft. https://www.altexsoft.com/whitepapers/quality-assurance-quality-control-and-testing-the-basics-of-software-quality-management/ ### Q3 MERN Stack - GeeksforGeeks. (2019, October 11). GeeksforGeeks. https://www.geeksforgeeks.org/mern-stack/ Jasraj, J. (2021, October 7). MERN Stack. Geeksforgeeks. Retrieved September 13, 2023, from https://www.geeksforgeeks.org/mern-stack/ ### Q4 Friedman , V., F. (2021, October). 10 Principles Of Good Web Design. Smashing Magazine. Retrieved September 14, 2023, from https://www.smashingmagazine.com/2008/01/10-principles-of-effective-web-design/ ### Q7 What is Type Coercion in JavaScript. (2023, February 7). GeeksforGeeks. https://www.geeksforgeeks.org/what-is-type-coercion-in-javascript/ ### Q11 Kantor, I. (n.d.). Objects. https://javascript.info/object ### Q12 Tagliaferri, L. (2021, August 25). How To Work with JSON in JavaScript. DigitalOcean. https://www.digitalocean.com/community/tutorials/how-to-work-with-json-in-javascript
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'pages/HomePage.dart'; import 'pages/login_page.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( //home: HomePage(), themeMode: ThemeMode.light, theme: ThemeData(primarySwatch: Colors.deepPurple, fontFamily: GoogleFonts.lato().fontFamily), darkTheme: ThemeData( brightness: Brightness.dark, ), //initialRoute: "/home", routes: { "/": (context)=>LoginPage(), "/home": (context)=>HomePage(), } ); } }
import { useEffect } from "react"; import { Navigate, Route, Routes, useLocation } from "react-router-dom"; import AdminRoutes from "routes/AdminRoutes"; import HomePage from "pages/Home"; import LoginPage from "pages/Login"; import AdministracaoPage from "pages/Administracao"; import AdicionarProdutoPage from "pages/AdicionarProduto"; import VizualizarProdutoPage from "pages/VisualizarProduto"; import ResultadosPage from "pages/Resultados"; import VerCategoriaPage from "pages/VerCategoria"; import EditarProdutoPage from "pages/EditarProduto"; import SingupPage from "pages/Singup"; class AppRoutes { static home = "/home"; static login = "/login"; static singup = "/singup"; static administracao = "/administracao"; static adicionarProduto = `${this.administracao}/adicionar-produto`; static visualizarProduto = "/produto"; static resultados = "/search"; static verCategoria = "/categoria"; static editarProduto = `${this.administracao}/editar-produto`; } Object.freeze(AppRoutes); Object.bind(AppRoutes, AppRoutes); function RouteHandler() { const location = useLocation(); useEffect(() => window.scrollTo(0, 0), [location]); return ( <Routes> {/* normal routes */} <Route path="/" element={<Navigate to={AppRoutes.home} />} /> <Route path={AppRoutes.home} element={<HomePage />} /> <Route path={AppRoutes.login} element={<LoginPage />} /> <Route path={AppRoutes.singup} element={<SingupPage />} /> <Route path={AppRoutes.visualizarProduto + "/:id"} element={<VizualizarProdutoPage />} /> <Route path={AppRoutes.resultados + "/:query"} element={<ResultadosPage />} /> <Route path={AppRoutes.verCategoria + "/:categoria"} element={<VerCategoriaPage />} /> {/* admin routes */} <Route path={AppRoutes.administracao} element={<AdminRoutes />}> <Route index element={<AdministracaoPage />} /> <Route path={AppRoutes.adicionarProduto} element={<AdicionarProdutoPage />} /> <Route path={AppRoutes.editarProduto + "/:id"} element={<EditarProdutoPage />} /> </Route> {/* not found */} <Route path="*" element={<p>not found</p>}/> </Routes> ); } export default RouteHandler; export { AppRoutes };
import React, {useEffect, useLayoutEffect} from 'react'; import useFetch from "theme/hooks/useFetch.js"; import useStateHandler from "theme/hooks/useStateHandler.js"; import usePagination from "theme/hooks/usePagination.js"; import useQueryFilter from "theme/hooks/useQueryFilter.js"; /** * Выполняет fetch запрос. * * @param {Object} DEFAULT_STATE Объект DEFAULT_STATE. * @param {string} apiPath Адрес api. * @param {Object} options Объект с дополнительными параметрами. * @param {boolean|undefined} options.noQuery Если передать true, то фильтры не будут сохраняться в поисковой строке. * @param {boolean|undefined} options.noScroll Если передать true, то не будет скрола наверх при пагинации * @param {boolean|undefined} options.isBlock Условие, при котором блочится запрос * @param {number|undefined} options.allCount Общее количество элементов * @param {boolean | undefined} options.isInterval Использовать ли глобальный интервал обновления * @param {Array | undefined} options.deps Дополнительные зависимости * @return { data, state,stateUpd, isFetching, options} Объект stateObject */ const useStateFilter = (DEFAULT_STATE, apiPath, options={}) => { const {noQuery} = options // const location = useLocation() //console.log(location) const [data, doResponse, isFetching, isError, setData] = useFetch("GET", apiPath) const isBlock = !!options?.isBlock const hookDeps = options?.deps ?? [] DEFAULT_STATE = {...DEFAULT_STATE, ...options.fixedQuery, offset: 0} const [state, stateHandler, setState] = useStateHandler(DEFAULT_STATE); const [getQuery, pushQuery] = useQueryFilter() const paginationObject = usePagination(state, stateUpd, data, options.allCount) function beforeUpd (isReset=false, newFilters) { if (options.isBlock) return if (isReset) { doResponse({...DEFAULT_STATE}) } else { doResponse({...state, ...newFilters}) } } function stateUpd (newObject, needApply=false) { stateHandler(newObject) if (!needApply) applyHandler(newObject) } const applyHandler = (newFilters = null) => { let finalFilter = {...state, ...newFilters} if(newFilters?.offset === undefined) { finalFilter = {...finalFilter, offset: 0} stateHandler(finalFilter) } else { if (!options.noScroll) window.scrollTo(0, 0) if (JSON.stringify(state)!==JSON.stringify(finalFilter)) stateHandler(finalFilter) } if (!noQuery) pushQuery(finalFilter) beforeUpd(false, finalFilter) } function resetHandler() { setState(DEFAULT_STATE) if (!noQuery) pushQuery(null) beforeUpd("isReset") } useLayoutEffect(()=>{ let query = getQuery(DEFAULT_STATE) if (!options.noScroll) window.scrollTo(0, 0) if(isBlock) return if (noQuery) { beforeUpd("isReset") return; } if (query) { let newState = {...DEFAULT_STATE, ...query} //if (!noQuery) pushQuery(parseIfNotDefault(newState)) applyHandler(newState) } else { beforeUpd("isReset") } }, [isBlock, ...hookDeps]) //Need upd hooks function stateReload () { beforeUpd() } //End need upd hooks //Crud Logic function arrayEdit(callback) { setData(data.map(el=>callback(el))) } function arrayDelete(callback) { setData(data.filter(el=>callback(el))) } function arrayAdd(payload) { if (!options.noScroll) window.scrollTo(0, 0) if(state.offset === 0) { setData([payload, ...data]) } else { applyHandler() } } //End CRUD hooks let canReset = JSON.stringify(DEFAULT_STATE) !== JSON.stringify(state) return { data, state, stateUpd, isFetching: isFetching, options: { isFetching: isFetching, isError, canReset, resetHandler, applyHandler, DEFAULT_STATE, setData, ...paginationObject, arrayAdd, arrayEdit, arrayDelete, stateReload, } } }; export default useStateFilter;
import { ApplicationCommandData, ApplicationCommandType, ChatInputCommandInteraction } from "discord.js"; import { IArgData } from "../typings/interfaces/IArgData"; import { ICommandData } from "../typings/interfaces/ICommandData"; import getRealArgType from "../functions/getRealArgType"; import cast from "../functions/cast"; import { NekoClient } from "../core/NekoClient"; import { ArgType } from "../typings/enums/ArgType"; export class Command<Args extends [...IArgData[]] = IArgData[]> { constructor(public readonly data: ICommandData<Args>) {} async parseArgs(int: ChatInputCommandInteraction<'cached'>) { const client = int.client as NekoClient const arr = new Array() if (!this.data.args?.length) return arr for (let i = 0, len = this.data.args.length;i < len;i++) { const arg = this.data.args[i] let value: any; switch (arg.type) { case ArgType.Float: { value = int.options.getNumber(arg.name, arg.required) break } case ArgType.User: { value = int.options.getUser(arg.name, arg.required) break } case ArgType.Enum: { value = arg.enum![int.options.getString(arg.name, arg.required) as keyof typeof arg.enum] break } case ArgType.Member: { value = int.options.getMember(arg.name) break } case ArgType.Attachment: { value = int.options.getAttachment(arg.name, arg.required) break } case ArgType.String: { value = int.options.getString(arg.name, arg.required) break } case ArgType.Integer: { value = int.options.getInteger(arg.name, arg.required) break } default: { throw new Error(`Unresolved arg type ${ArgType[arg.type]}`) } } value ??= arg.default?.call(client, cast(int)) arr.push(value ?? null) } return arr } private async reject(i: ChatInputCommandInteraction<'cached'>, msg: string) { await i.reply({ ephemeral: true, content: msg }) return false } async hasPermissions(i: ChatInputCommandInteraction<'cached'>): Promise<boolean> { const client = i.client as NekoClient const reject = this.reject.bind(this, i) if (this.data.owner && !client.config.owners.includes(cast(i.user.id))) { return reject('You must be owner to run this command.') } return true } toJSON(): ApplicationCommandData { return { name: this.data.name, description: this.data.description, defaultMemberPermissions: this.data.permissions ?? null, dmPermission: this.data.allowDm ?? false, type: ApplicationCommandType.ChatInput, options: cast(this.data.args?.map( arg => ({ name: arg.name, description: arg.description, channelTypes: arg.channelTypes, choices: arg.enum ? Object.entries(arg.enum).map(d => ({ name: d[0], value: d[1] })) : null, min_length: arg.min, min_value: arg.min, max_length: arg.max, max_value: arg.max, required: arg.required, autocomplete: !!arg.autocomplete, type: getRealArgType(arg.type) })) ?? null ) } } }
package modelos; public class ContaCorrente extends Conta { private final Double TAXA = 2.0; @Override public void sacar(Double quantia) { Double total = quantia + calculaTaxa(quantia); if (quantia < getSaldo()) { this.setSaldo(total); System.out.println("Saldo após o saque R$: " + getSaldo()); } else { System.out.println("Não foi possível realizar o saque"); } } @Override public void depositar(Double quantia) { Double total = quantia + getSaldo() - calculaTaxa(quantia); this.setSaldo(total); System.out.println("Saldo após o depósito R$: " + getSaldo()); } public Double calculaTaxa(Double total) { return TAXA * 100 / total; } public ContaCorrente(String numero, Double saldo, Cliente cliente) { super(numero, saldo, cliente); } @Override public String toString() { return "\n**************Conta corrente**************" + "\nCliente: " + getCliente().getNome() + ", CPF: " + getCliente().getCpf() + "\nNúmero: " + getNumero() + "\nTaxa de operação: " + TAXA + "%" + "\nSaldo inicial: " + getSaldo(); } }
package com.collection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class ArrayListDemo { public static void main(String[] args) { // TODO Auto-generated method stub List<String> listObject=new ArrayList<String>(); listObject.add("Hello"); //Add the Object listObject.add("World"); //Add the Object listObject.add("!"); //Add the Object System.out.println("---------------"); System.out.println("For Loop:"); for(int i=0;i<listObject.size();i++) System.out.println(listObject.get(i)); System.out.println("---------------"); System.out.println("Foreach Loop:"); for (String string : listObject) { System.out.println(string); } // listObject.add(10); Compile Time Error // Integer i=(Integer)listObject.get(1); System.out.println("---------------"); System.out.println("Element at 0 index:"+listObject.get(0));//Index based read Operation System.out.println("---------------"); System.out.println("By Iterator:-"); Iterator<String> iteratorObject=listObject.iterator(); while(iteratorObject.hasNext()){ System.out.println(iteratorObject.next()); } System.out.println("---------------"); System.out.println("By ListIterator:"); ListIterator<String> listIteratorObject=listObject.listIterator(); while(listIteratorObject.hasNext()){ System.out.println(listIteratorObject.next()); } System.out.println("---------------"); System.out.println("By ListIterator in Reverse using Previous:"); //Retrieves the current index position while(listIteratorObject.hasPrevious()){ System.out.println(listIteratorObject.previous()); } } }
<!-- vision.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vision Accessibility Feature</title> <!-- Link your vision-specific styles if needed --> <link rel="stylesheet" href="accessibility.css"> <style> body { font-family: 'Arial', sans-serif; line-height: 1.6; margin: 0; padding: 0; background-color: #f8f8f8; color: #333; } header { background-color: #333333; /* Grey color */ color: #fff; padding: 10px; text-align: center; } section { max-width: 800px; margin: 20px auto; padding: 20px; background-color: #fff; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); transition: box-shadow 0.3s ease-in-out; } h1, h2, h3 { color: #ffcc00; /* Yellow color */ transition: font-size 0.3s ease-in-out; } ul { list-style-type: none; padding: 0; } li { margin-bottom: 10px; } .magnifier { font-size: 24px; cursor: pointer; transition: transform 0.3s ease-in-out; user-select: none; } .magnifier:hover { transform: scale(1.2); } footer { background-color: #333333; /* Grey color */ color: #fff; padding: 10px; text-align: center; } /* Add class for zoom effect */ .zoomed h1, .zoomed h2, .zoomed h3 { font-size: 1.5em; /* Adjust the font size for zoomed effect */ } /* Style for the plus sign */ .plus-sign { font-size: 20px; margin-left: 5px; } </style> <script> document.addEventListener("DOMContentLoaded", function () { const magnifier = document.querySelector('.magnifier'); if (magnifier) { magnifier.addEventListener('click', function () { // Toggle between zoom in and zoom out document.body.classList.toggle('zoomed'); }); } }); </script> </head> <body> <header> <h1>Vision Accessibility Feature</h1> </header> <section> <h2>Magnifiers and Visual Aids</h2> <p> Our vision accessibility feature includes magnifiers and visual aids to enhance your browsing experience. </p> <h3>Key Features:</h3> <ul> <li><strong>Magnification:</strong> Zoom in on text and images for better visibility.</li> <li><strong>Contrast Adjustment:</strong> Customize the color contrast to suit your preferences.</li> <li><strong>Highlighting:</strong> Highlight important elements on the page.</li> <!-- Add more features based on your implementation --> </ul> <h3>How to Use Magnifiers:</h3> <p> To use magnifiers, simply click on the "Vision" option in our accessibility widget, and the magnification tools will be activated. You can then adjust settings based on your needs. </p> <!-- Magnifier element --> <div class="magnifier">&#128269;<span class="plus-sign">+</span></div> </section> <footer> <p>&copy; 2023 Your Website. All rights reserved By Sam & Diala</p> </footer> </body> </html>
#Created by Yamin Deng, Tao He, and Yuehua Cui et al. #This R code is designed for the paper #"Genome-wide gene-based multi-trait analysis" ######Gene-based analysis for single trait analysis############# rm(list=ls()) ################### # load packages ### ################### library(ttutils) library(methods) library(psych) library(EQL) library(mvtnorm) library(Matrix) library(KRLS) library(kernlab) ##########function to generate kernel matrix###### #Note:for demonstration reasons, only certain commonly used kernels are defined in the function, #such as Gaussion/Quadratic/Linear/IBS. #The users can define the candidate kernel set of their interests. gen.ker <- function(covx,kernel.index) #covx:X; #kernel.index=c("Gau","Lin","Quad","IBS"): index of kernel function; { n <- nrow(covx) p <- ncol(covx) if (kernel.index=="Gau") { ker <- gausskernel(X=covx,sigma=p) # Gaussian kernel } if (kernel.index=="Lin") { f <- function(x,y) x%*%y # linear kernel ker <- outer( 1:n, 1:n, Vectorize( function(i,j) f(covx[i,], covx[j,]) ) ) } if (kernel.index=="Quad") { f <- function(x,y) (x%*%y+1)^2 # Quadratic kernel ker <- outer( 1:n, 1:n, Vectorize( function(i,j) f(covx[i,], covx[j,]) ) ) } if (kernel.index=="IBS") { f <- function(x,y) 1-sum(abs(x-y))/(2*p) #IBS kernel ker <- outer( 1:n, 1:n, Vectorize( function(i,j) f(covx[i,], covx[j,]) ) ) } ker <- as.matrix(forceSymmetric(ker)) ker0 <- ker diag(ker0) <- rep(0,n) J <- matrix(1,n,n) ker.cen <- ker-J%*%ker0/(n-1)-ker0%*%J/(n-1)+J%*%ker0%*%J/n/(n-1) v1.cen <- tr(ker.cen)/n return(list(ker.cen=ker.cen,v1.cen=v1.cen)) } Chisq.Ustat<-function(y,covx,z,ker) { n=length(y) p=ncol(covx) re.norm=re.lin=re.u=0 vec1=rep(1,n) h=diag(n)-z%*%solve(t(z)%*%z)%*%t(z) ker1=ker diag(ker1)=rep(0,n) ############################################################################ A=h%*%ker1%*%h hkhk=A%*%ker1 hkh.hkh=A*A hk=h%*%ker1 sigma.hat=t(y)%*%h%*%y/(n-ncol(z)) sd=as.numeric(sqrt(sigma.hat)) z0=h%*%y/sd m4=mean(z0^4) e1=tr(hk) e2=tr(hkhk) mu1=2*e1 mu2=e1*(1+2/(n-1)) delta=m4-3 var0=e1^2*(-2/(n-1))+e2*(2-12/(n-1)) #high order terms---simulation 1 var=var0+delta*(-e1^2/n+6*e2/n+tr(hkh.hkh)) #high order terms---simulation 1 #print(var) test=t(h%*%y)%*%ker1%*%(h%*%y)/(sigma.hat) v1=sum(diag(ker))/n theta=-sum(ker1)/n/(n-1) theta=0 #if using centralized kernel a=var/2/(n-1)^2/v1 g=v1/a if (test>qnorm(0.95,theta*(n-1),sqrt(var))) re.norm=1 if ((test/(n-1)+v1-theta)>a*qchisq(0.95,g)) re.u=1 sd.chi=test/(n-1)+v1-theta p.u=pchisq(sd.chi/a,g,lower.tail = F) test.sd=(test-theta*(n-1))/sqrt(var) #return(list(re.norm=re.norm, re.u=re.u,test.sd=test.sd,A.ma=h%*%ker1%*%h/sqrt(var),p.u=p.u)) return(p.u) } ker.G <- gen.ker(x,"Gau") ker.L <- gen.ker(x,"Lin") ker.I <- gen.ker(x,"IBS") ######centralized and normalized kernels kerM.G <- ker.G$ker.cen/ker.G$v1.cen kerM.L <- ker.L$ker.cen/ker.L$v1.cen kerM.I <- ker.I$ker.cen/ker.I$v1.cen H<-c(Chisq.Ustat(y,x,z,kerM.G),Chisq.Ustat(y,x,z,kerM.L),Chisq.Ustat(y,x,z,kerM.I)) cct=sum(tan(pi*(0.5-H))/n) #######Here, n denotes the number of kernel functions############ P-value<-1-pcauchy(cct) ####################For example################################### # Calulate the P-value for gene-based marginal phenotypes # Assume the sample=n, multiple traits=S(i=1,2,....,S), SNPs for one gene=p,Covariance =q # load data and test #n <- 100; p <- 100; q=2;S=5 x <- matrix(rnorm(n*p),n,p) z <- matrix(rnorm(n*q),n,q) yi <- rnorm(n) P-value ######Gene-based analysis for multi-trait analysis############################### #' For S traits , we combine the p-values with Fisher combination with dependent traits (FPC) #' This funciton intergrate the p-values from the marginal p-values and outcome matrix #' set.seed(1) #' pval <- matrix(runif(n*S),n,S) #########pval denotes a matrix of p-values, where n denotes the samples and S denotes the multiple traits ######## #' pheno <- data.frame(y1=rnorm(n), y2=rnorm(n), ...... yS=rnorm(n) ) #######pheno denotes a matrix of phenotypes############# #' FisherCombPval(P.values=pval, Pheno=pheno, kendall.only=FALSE, miss.pval=FALSE) #######################Fisher combination with dependent traits#################### FisherCombPval <- function(P.values, Pheno, kendall.only=FALSE,miss.pval=FALSE, verbose=FALSE){ if(!is.data.frame(Pheno)) Pheno <- as.data.frame(Pheno) if(is.data.frame(P.values)) P.values <- as.data.frame(P.values) if(ncol(Pheno) != ncol(P.values)) stop("The number of phenotypes does not match the number of p-values") log.P.values <- log(P.values) G <- nrow(P.values) res <- rep(NA, G) PAR <- cal.gamma.par(Pheno,kendall.only,verbose) SHAPE <- PAR$SHAPE SCALE <- PAR$SCALE T <- -2 * apply(log.P.values,1,sum) res <- pgamma(T, shape=SHAPE, scale=SCALE, lower.tail=FALSE) if(miss.pval && is.na(res)){ idx <- which(is.na(res)) for (i in idx){ ##cat("i = ",i,"\n") x <- log.P.values[i,] y <- x[!is.na(x)] if(length(y) == 1){ res[i] <- exp(y) } else { T <- -2*sum(y) PAR <- cal.gamma.par(Pheno[,!is.na(x)],kendall.only,verbose) SHAPE <- PAR$SHAPE SCALE <- PAR$SCALE res[i] <- pgamma(T, shape=SHAPE, scale=SCALE, lower.tail=FALSE) } } } return(res) } ## library(mvtnorm) #<- require ### utilities adj.cor <- function(r,n){ fac <- (1-r^2) / (2*(n-3)) res <- r * (1 + fac) return(res) } cal.cor.pearson <- function(x,y){ r <- cor(x,y) #,use="pairwise.complete.obs") return(r) } ### internal functions cal.cor.kendall <- function(x,y){ tau <- cor(x,y, method="kendall") ## use="pairwise.complete.obs") ## tau <- cor.fk(x) r <- sin(pi*tau/2) return(r) } cal.tetrachoric <- function(x,y){ obj <- table(x,y) if(nrow(obj) != 2 | ncol(obj) != 2){ res <- NA }else{ if(obj[1,1] ==0 && obj[2,2]==0){ res <- -1 }else if(obj[1,2]==0 & obj[2,1]==0){ res <- 1 }else{ idx <- obj == 0 if(any(idx)){ obj[idx] <- 0.5 } obj <- obj/sum(obj) p11 <- obj[1,1] p12 <- obj[1,2] p21 <- obj[2,1] p22 <- obj[2,2] pr <- p11 + p12 pc <- p11 + p21 h <- qnorm(1-pr) k <- qnorm(1-pc) make.score.eq <- function(h,k,p11){ function(r){ mvtnorm::pmvnorm(lower=c(h,k), cor=matrix(c(1,r,r,1),2,2)) - p11 } } score.eq <- make.score.eq(h,k,p11) res <- uniroot(score.eq,c(-1,1))$root } } return(res) } cal.r.BR <- function(x.bin, y.cont){ x.bin <- as.numeric(factor(x.bin)) - 1 if(length(unique(x.bin)) != 2){ warning("Neither x nor y is binary variable. Use Kendall tau to calculate correlation") res <- cal.cor.kendall(x.bin, y,cont) }else{ x.bar <- mean(x.bin) y.bar <- mean(y.cont) n <- length(x.bin) fac <- n * x.bar * y.bar nom <- sum(x.bin * y.cont) - fac den <- sum(sort(x.bin) * sort(y.cont)) - fac res <- nom/den } return(res) } cal.r.Lord <- function(x.bin, y.cont){ res <- cal.r.BR(x.bin, y.cont) if(res < 0) res <- - cal.r.BR(x.bin, -y.cont) return(res) } biserial <- function(x,y){ ## x: binary 0 and 1; ## y: continuous res <- cal.r.Lord(x.bin=x, y.cont=y) return(res) } polyserial <- function(x,y,ML=FALSE){ ## x: ordinal ## y: continuous x.tab <- table(x) N <- sum(x.tab) x.cut <- qnorm(cumsum(x.tab)/N) x.cut <- x.cut[-length(x.cut)] res <- sqrt((N - 1)/N)*sd(x)*cor(x, y)/sum(dnorm(x.cut)) if(res> 1) res <- 1 if(res< -1) res <- -1 return(res) } polychoric <- function(x,y,ML=FALSE){ ## x: oridinal ## y: oridinal obj <- table(x,y) if(nrow(obj) < 2 | ncol(obj) < 2){ res <- NA }else{ if(FALSE){## Add 0.5 to 0 cell idx <- obj == 0 if(any(idx)){ obj[idx] <- 0.5 } } R <- nrow(obj) C <- ncol(obj) tab <- obj/sum(obj) row.cut <- qnorm(cumsum(rowSums(obj))/sum(obj))[-R] col.cut <- qnorm(cumsum(colSums(obj))/sum(obj))[-C] make.like.fn <- function(obj,row.cut, col.cut){ R <- nrow(obj) C <- ncol(obj) lo <- - Inf up <- Inf row.cut1 <- c(lo,row.cut,up) col.cut1 <- c(lo,col.cut,up) function(rho){ COR <- matrix(c(1,rho,rho,1),2,2) PHI <- matrix(0,R,C) for (i in 1:R){ a1 <- row.cut1[i] a2 <- row.cut1[i+1] for (j in 1:C){ b1 <- col.cut1[j] b2 <- col.cut1[j+1] PHI[i,j] <- mvtnorm::pmvnorm(lower=c(a1,b1), upper=c(a2,b2), cor=COR) } } res <- - sum(obj* log(PHI)) return(res) } } like.fn <- make.like.fn(obj,row.cut,col.cut) res <- optimize(like.fn,c(-1, 1))$minimum } return(res) } detect.type <- function(x){ res <- "NULL" if(is.null(x)){ res <- "NULL" }else{ val <- unique(x)[!is.na(unique(x))] len <- length(val) if(len == 2){ res <- "dichotomous" }else if (len > 2 & len <= 5){ res <- "ordinal" }else{ res <- "continuous" } } return(res) } mixed.cor <- function(x, y,kendall.only=FALSE,verbose=FALSE){ idx <- complete.cases(x, y) x <- x[idx] y <- y[idx] num.x <- length(unique(x)) num.y <- length(unique(y)) if(kendall.only){ x.type <- "continuous" y.type <- "continuous" x <- as.numeric(x) y <- as.numeric(y) }else{ x.type <- detect.type(x) y.type <- detect.type(y) } if(x.type == "dichotomous" & y.type=="continuous"){ # biserial if(verbose) message("biserial:") x <- as.numeric(factor(x)) - 1 res <- biserial(x,y) }else if(y.type == "dichotomous" & x.type == "continuous"){ # biserial if(verbose) message("biserial:") y <- as.numeric(factor(y)) - 1 res <- biserial(y,x) }else if(x.type == "dichotomous" & y.type == "dichotomous"){ # tetrachoric if(verbose) message("tetrachoric:") x <- as.numeric(factor(x)) - 1 y <- as.numeric(factor(y)) - 1 res <- cal.tetrachoric(x,y) }else if(x.type == "ordinal" & y.type == "continuous"){ # polyserial if(verbose) message("polyserial:") x <- as.numeric(factor(x)) res <- polyserial(x,y) }else if(y.type == "ordinal" & x.type == "continuous"){ # polyserial if(verbose) message("polyserial:") y <- as.numeric(factor(y)) res <- polyserial(y,x) }else if((x.type == "ordinal" & y.type == "ordinal") | (x.type == "dichotomous" & y.type == "ordinal") | (x.type == "ordinal" & y.type == "dichotomous")){ # polychoric if(verbose) message("polychoric:") x <- as.numeric(factor(x)) y <- as.numeric(factor(y)) res <- polychoric(x,y) }else{ # if(x.type == "continuous" & y.type == "continuous"){ # kendall if(verbose) message("kendall correlation\n") res <- cal.cor.kendall(x,y) } return(res) } cal.cor.v <- function(obj,kendall.only=FALSE,verbose=FALSE){ m <- ncol(obj) res <- rep(NA, m*(m-1)/2) k <- 1 for (i in 1:(m-1)){ for (j in (i+1):m){ res[k] <- mixed.cor(obj[,i],obj[,j],kendall.only, verbose=verbose) k <- k + 1 } } return(res) } cal.gamma.par <- function(Pheno,kendall.only=FALSE,verbose=FALSE){ a1 <- 3.9081 a2 <- 0.0313 a3 <- 0.1022 a4 <- -0.1378 a5 <- 0.0941 n <- nrow(Pheno) K <- ncol(Pheno) rho.v <- cal.cor.v(Pheno,kendall.only,verbose) rho.adj <- adj.cor(rho.v, n) vT <- 4*K + 2* sum( a1 * (rho.adj^2) + a2 * (rho.adj^4) + a3 * (rho.adj^6) + a4 * (rho.adj^8) + a5 * (rho.adj^10) - a1/n*(1-rho.adj^2)^2 ) ET <- 2*K v <- 2*ET^2/vT r <- vT/(2*ET) return(list(SHAPE=v/2,SCALE=2*r)) }
<?php namespace App\Http\Requests; use Carbon\Carbon; use App\Models\Sms; use App\Traits\EnsuresRolloutCompliance; use Illuminate\Foundation\Http\FormRequest; class ProcessScheduledImmediateRequest extends FormRequest { use EnsuresRolloutCompliance; /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return $this->user()->hasRole('client'); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ // ]; } public function withValidator($validator) { $validator->after(function ($validator) { $request = request(); $sms = Sms::find($request->id); $sending_day = str_replace("-", ".",explode(" ", $sms->send_at)[0]); $sending_time = explode(" ", $sms->send_at)[1]; $completionTimeArray = array( 'recipient_list_id' => $sms->recipient_list_id, 'sending_time' => 'later', 'day' => Carbon::createFromFormat("Y.m.d", $sending_day)->format('d.m.Y'), 'time' => Carbon::createFromFormat("H:i:s", $sending_time)->format('H:i') ); if(!$this->isWithinTimeBounds()){ $validator->errors()->add('time','Sending time must be between 0700 and 2130 hrs.'); } if(!$this->rolloutWillCompleteInTime($completionTimeArray)){ $validator->errors()->add('completion-time', 'Unfortunately the rollout won\'t complete within the allowed time (7am to 9:30pm).'); } if($this->userHasTwoExecutingJobs()){ $validator->errors()->add('concurrency','Users are allowed two rollouts at most.'); } }); } public function passedValidation(){ if(!$this->isVacant()){ $vacancyTime = $this->estimatedTimeTillVacant(); if(Carbon::now()->diffInMinutes($vacancyTime) > 1){ $this->merge(['vacant-in' => Carbon::now()->longAbsoluteDiffForHumans($vacancyTime)]); } } } }
import Services from "./Services"; class KycService extends Services { constructor(init) { super(init); this._name = "KYC"; return this; } // CREATE -------------------------------------------------------------------------------- /** * @function find - Gets one or many users (**Admins only**) * @param {Object} data * @returns */ create = async (data) => { return await this.decorate( async () => await this.axios(`kyc`, { method: "POST", data, }) ); }; // FIND -------------------------------------------------------------------------------- /** * @function find - Gets one or many users (**Admins only**) * @param {Object} params * @returns */ find = async (params) => { return await this.decorate( async () => await this.axios(`kyc`, { method: "GET", params, }) ); }; /** * @function findByID * @param {String} id * @param {Object} params * @returns */ findByID = async (id, params) => { return await this.decorate( async () => await this.axios(`kyc/${id}`, { method: "GET", params, }) ); }; // UPDATE -------------------------------------------------------------------------------- /** * @function update * @param {Object} data * @param {String []} data.ids - Array of IDs * @returns */ update = async (data) => { return await this.decorate( async () => await this.axios(`kyc`, { method: "PUT", data, }) ); }; /** * @function updateByID * @param {String} id * @param {Object} data * @returns */ updateByID = async (id, data) => { return await this.decorate( async () => await this.axios(`kyc/${id}`, { method: "PUT", data, }) ); }; /** * @function updateByUserAndType * @param {String} id * @param {Object} data * @param {String} data.status * @returns */ updateByUserAndType = async (user_id, type, data) => { return await this.decorate( async () => await this.axios(`kyc/user/${user_id}/type/${type}`, { method: "PUT", data, }) ); }; // REMOVE -------------------------------------------------------------------------------- /** * @function removeByID - Bulk delete users (**Admins only**) * @param {String} id * @param {Object} data * @param {Boolean | false} data.force * @returns */ removeByID = async (id, data) => { return await this.decorate( async () => await this.axios(`kyc/${id}`, { method: "DELETE", data, }) ); }; /** * @function remove - Bulk delete users (**Admins only**) * @param {Object} data * @param {String []} data.ids - Array of IDs to delete from * @param {Boolean | false} data.force * @returns */ remove = async (data) => { return await this.decorate( async () => await this.axios(`kyc`, { method: "DELETE", data, }) ); }; } export default KycService;
// // Created by pc on 2023/8/18. // #pragma once #include "Core/Vulkan.h" #include "Core/Images/ImageView.h" #include "Core/Images/Image.h" struct Mipmap { /// Mipmap level uint32_t level = 0; /// Byte offset used for uploading uint32_t offset = 0; /// Width depth and height of the mipmap VkExtent3D extent = {0, 0, 0}; bool isInitialized() const { return extent.width != 0 && extent.height != 0 && extent.depth != 0; } }; class SgImage { public: /** * \brief load from hardware texture */ SgImage(Device& device, const std::string& path); /** * \brief load from memory */ SgImage(Device& device, const std::vector<uint8_t>& data, VkExtent3D extent, VkImageViewType viewType = VK_IMAGE_VIEW_TYPE_2D, VkFormat format = VK_FORMAT_R8G8B8A8_UNORM); /** * \brief create from image attribute */ SgImage(Device& device, const std::string& name, const VkExtent3D& extent, VkFormat format, VkImageUsageFlags image_usage, VmaMemoryUsage memory_usage, VkImageViewType viewType, VkSampleCountFlagBits sample_count = VK_SAMPLE_COUNT_1_BIT, uint32_t mip_levels = 1, uint32_t array_layers = 1, VkImageCreateFlags flags = 0); /** * \brief load from existing image.Mainly from swapChainImage */ SgImage(Device& device, VkImage handle, const VkExtent3D& extent, VkFormat format, VkImageUsageFlags image_usage, VkSampleCountFlagBits sample_count = VK_SAMPLE_COUNT_1_BIT, VkImageViewType viewType = VK_IMAGE_VIEW_TYPE_2D); ~SgImage(); SgImage(SgImage&& other); SgImage(SgImage& other) = delete; void freeImageCpuData(); void createVkImage(Device& device, uint32_t mipLevels = 0, VkImageViewType imageViewType = VK_IMAGE_VIEW_TYPE_2D, VkImageCreateFlags flags = 0); std::vector<uint8_t>& getData(); uint64_t getBufferSize() const; VkExtent3D getExtent() const; VkExtent2D getExtent2D() const; Image& getVkImage() const; // ImageView &getVkImageView() const; ImageView& getVkImageView(VkImageViewType view_type = VK_IMAGE_VIEW_TYPE_MAX_ENUM, VkFormat format = VK_FORMAT_UNDEFINED, uint32_t mip_level = 0, uint32_t base_array_layer = 0, uint32_t n_mip_levels = 0, uint32_t n_array_layers = 0) const; void createImageView(VkImageViewType view_type = VK_IMAGE_VIEW_TYPE_MAX_ENUM, VkFormat format = VK_FORMAT_UNDEFINED, uint32_t mip_level = 0, uint32_t base_array_layer = 0, uint32_t n_mip_levels = 0, uint32_t n_array_layers = 0); VkFormat getFormat() const; const std::vector<std::vector<VkDeviceSize>>& getOffsets() const; const std::vector<Mipmap>& getMipMaps() const; uint32_t getArrayLayerCount() const; uint32_t getMipLevelCount() const; void setArrayLevelCount(uint32_t layers); void generateMipMapOnCpu(); void generateMipMapOnGpu(); void setExtent(const VkExtent3D& extent3D); void loadResources(const std::string& path); bool isCubeMap() const; bool needGenerateMipMapOnGpu() const; private: protected: void setIsCubeMap(bool _isCube); friend class AstcImageHelper; std::unordered_map<size_t, std::unique_ptr<ImageView>> vkImageViews{}; std::unique_ptr<Image> vkImage{nullptr}; size_t firstImageViewHash{0}; //Attributes to init when load resources std::vector<uint8_t> mData{}; VkFormat format{}; VkExtent3D mExtent3D{0, 0, 1}; //Attention: size = layer * level //layer 0 mipmap 0, layer1 mipmap0 layer2 mipmap0 ... std::vector<Mipmap> mipMaps{{}}; std::vector<std::vector<VkDeviceSize>> offsets; bool mIsCubeMap{false}; bool needGenerateMipMap{true}; std::string name; Device& device; std::string filePath; protected: uint32_t layers{1}; };
import { Injectable } from '@nestjs/common'; import { CreateCatDto } from './dto/create-cat.dto'; import { UpdateCatDto } from './dto/update-cat.dto'; import { InjectRepository } from '@nestjs/typeorm'; import { Cat } from './entities/cat.entity'; import { Repository } from 'typeorm'; @Injectable() export class CatsService { constructor( @InjectRepository(Cat) private catRepository: Repository<Cat>, ) {} async create(createCatDto: CreateCatDto) { return await this.catRepository.save(createCatDto); } async findAll() { return await this.catRepository.find(); } async findOne(id: number) { return await this.catRepository.findOne({ where: { id } }); } async update(id: number, updateCatDto: UpdateCatDto) { const cat = await this.catRepository.findOne({ where: { id } }); if (!cat) throw new Error('CAT_NOT_FOUND'); Object.assign(cat, updateCatDto); return this.catRepository.save(cat); } async remove(id: number) { try { const cat = await this.catRepository.findOne({ where: { id } }); if (!cat) { throw new Error('CAT_NOT_FOUND'); } await this.catRepository.remove(cat); return `${cat.name} Cat_DELETED!`; } catch (err) { console.log(err); } } }
#include <stdio.h> #include "main.h" /** * _strncpy - Copies n bytes of src string. * @dest: destination. * @src: source string. * @n: number of characters. * Return: dest. */ char *_strncpy(char *dest, char *src, int n) { int i; i = 0; while (i < n && src[i] != '\0') { dest[i] = src[i]; i++; } while (i < n) { dest[i] = '\0'; i++; } return (dest); }
from openai import OpenAI import json from preprocess import remove_s, remove_newline from tqdm import tqdm import argparse # Modify the api key with yours client = OpenAI(api_key="OPENAI_API_KEY") parser = argparse.ArgumentParser(description='question answering script') parser.add_argument('--caption-file', type=str, help='Caption file path') parser.add_argument('--question-file', type=str, help='Question file path') args = parser.parse_args() caption_file = args.caption_file question_file = args.question_file def get_answer(messages): response = client.chat.completions.create( model="gpt-3.5-turbo", max_tokens=5, temperature=0.2, top_p=1, frequency_penalty=0, presence_penalty=0, messages=messages ) return response with open(caption_file) as file: descriptions = json.load(file) with open(question_file) as f: data = json.load(f) new_data = [] for key, datum in tqdm(data.items()): img_id = datum["imageId"] question = datum["question"] answer = datum["answer"] for i in range(len(descriptions)): desc_datum = descriptions[i] if img_id == desc_datum["img_id"]: text = desc_datum["description"] text = remove_s(text) text = remove_newline(text) prompt = (f"Answer the question in maximum two words based on the text." f"Consider the type of question in your answer. For example, if it is a yes/no question, answer should be yes or no." f"Text: {text} " f"Question: {question}") messages = [ { "role": "user", "content": prompt } ] response = get_answer(messages) new_datum = { 'question_id': key, 'img_id': img_id, 'question': question, 'answer': answer } prediction = response.choices[0].message.content new_datum["prediction"] = prediction new_datum["text"] = text new_data.append(new_datum) json.dump(new_data, open("predictions/predicted_answers.json", 'w'), indent=4, sort_keys=True)
require 'rails_helper' describe "Static Pages" do describe "Home page" do it "should have the content 'Sample App'" do visit '/static_pages/home' page.should have_content('Sample App') end end describe "contactUs page" do it "should have the content 'contactUs'" do visit '/static_pages/home' page.should have_content('contact Us') end end describe "About page" do it "should have the content 'About'" do visit '/static_pages/home' page.should have_content('About Us') end end describe "Location Page" do it "should have the content 'Location'" do visit '/static_pages/home' page.should have_content('Location') end end end
import {t} from 'sentry/locale'; import type {Sort} from 'sentry/utils/discover/fields'; import SortableHeader from 'sentry/views/replays/replayTable/sortableHeader'; import {ReplayColumns} from 'sentry/views/replays/replayTable/types'; type Props = { column: keyof typeof ReplayColumns; sort?: Sort; }; function HeaderCell({column, sort}: Props) { switch (column) { case ReplayColumns.session: return <SortableHeader label={t('Session')} />; case ReplayColumns.projectId: return <SortableHeader sort={sort} fieldName="project_id" label={t('Project')} />; case ReplayColumns.slowestTransaction: return ( <SortableHeader label={t('Slowest Transaction')} tooltip={t( 'Slowest single instance of this transaction captured by this session.' )} /> ); case ReplayColumns.startedAt: return ( <SortableHeader sort={sort} fieldName="started_at" label={t('Start Time')} /> ); case ReplayColumns.duration: return <SortableHeader sort={sort} fieldName="duration" label={t('Duration')} />; case ReplayColumns.countErrors: return <SortableHeader sort={sort} fieldName="count_errors" label={t('Errors')} />; case ReplayColumns.activity: return ( <SortableHeader sort={sort} fieldName="activity" label={t('Activity')} tooltip={t( 'Activity represents how much user activity happened in a replay. It is determined by the number of errors encountered, duration, and UI events.' )} /> ); default: return null; } } export default HeaderCell;
import sys import rclpy from rclpy.node import Node from rclpy.callback_groups import MutuallyExclusiveCallbackGroup from rclpy.executors import MultiThreadedExecutor from environment_interfaces.srv import Reset from f1tenth_control.SimulationServices import SimulationServices from ros_gz_interfaces.srv import SetEntityPose from ros_gz_interfaces.msg import Entity from geometry_msgs.msg import Pose, Point from ament_index_python import get_package_share_directory from .util import get_quaternion_from_euler class CarTrackReset(Node): def __init__(self): super().__init__('car_track_reset') srv_cb_group = MutuallyExclusiveCallbackGroup() self.srv = self.create_service(Reset, 'car_track_reset', callback=self.service_callback, callback_group=srv_cb_group) set_pose_cb_group = MutuallyExclusiveCallbackGroup() self.set_pose_client = self.create_client( SetEntityPose, f'world/empty/set_pose', callback_group=set_pose_cb_group ) while not self.set_pose_client.wait_for_service(timeout_sec=1.0): self.get_logger().info('set_pose service not available, waiting again...') def service_callback(self, request, response): goal_req = self.create_request('goal', x=request.gx, y=request.gy, z=1) car_req = self.create_request(request.car_name, x=request.cx, y=request.cy, z=0, yaw=request.cyaw) while not self.set_pose_client.wait_for_service(timeout_sec=1.0): self.get_logger().info('set_pose service not available, waiting again...') #TODO: Call async and wait for both to execute if (request.flag == "goal_only"): self.set_pose_client.call(goal_req) else: self.set_pose_client.call(goal_req) self.set_pose_client.call(car_req) response.success = True return response def create_request(self, name, x=0, y=0, z=0, roll=0, pitch=0, yaw=0): req = SetEntityPose.Request() req.entity = Entity() req.entity.name = name req.entity.type = 2 # M req.pose = Pose() req.pose.position = Point() req.pose.position.x = float(x) req.pose.position.y = float(y) req.pose.position.z = float(z) orientation = get_quaternion_from_euler(roll, pitch, yaw) req.pose.orientation.x = orientation[0] req.pose.orientation.y = orientation[1] req.pose.orientation.z = orientation[2] req.pose.orientation.w = orientation[3] return req def main(): rclpy.init() pkg_environments = get_package_share_directory('environments') reset_service = CarTrackReset() pkg_environments = get_package_share_directory('environments') services = SimulationServices('empty') services.spawn(sdf_filename=f"{pkg_environments}/sdf/goal.sdf", pose=[1, 1, 1], name='goal') reset_service.get_logger().info('Environment Spawning Complete') executor = MultiThreadedExecutor() executor.add_node(reset_service) executor.spin() # rclpy.spin(reset_service) reset_service.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
--- title: <frequency> slug: Web/CSS/frequency tags: - CSS - CSS Data Type - Data Type - Reference - Web browser-compat: css.types.frequency --- <div>{{CSSRef}}</div> <p> The <strong><code>&lt;frequency&gt;</code></strong> <a href="/en-US/docs/Web/CSS">CSS</a> <a href="/en-US/docs/Web/CSS/CSS_Types">data type</a> represents a frequency dimension, such as the pitch of a speaking voice. It is not currently used in any CSS properties. </p> <h2 id="Syntax">Syntax</h2> <p> The <code>&lt;frequency&gt;</code> data type consists of a {{cssxref("&lt;number&gt;")}} followed by one of the units listed below. As with all CSS dimensions, there is no space between the unit literal and the number. </p> <h3 id="Units">Units</h3> <dl> <dt> <code><a id="Hz">Hz</a></code> </dt> <dd> Represents a frequency in hertz. Examples: <code>0Hz</code>, <code>1500Hz</code>, <code>10000Hz</code>. </dd> <dt> <code><a id="kHz">kHz</a></code> </dt> <dd> Represents a frequency in kilohertz. Examples: <code>0kHz</code>, <code>1.5kHz</code>, <code>10kHz</code>. </dd> </dl> <div class="note"> <p> <strong>Note:</strong> Although the number <code>0</code> is always the same regardless of unit, the unit may not be omitted. In other words, <code>0</code> is invalid and does not represent <code>0Hz</code> or <code>0kHz</code>. Though the units are case-insensitive, it is good practice to use a capital "H" for <code>Hz</code> and <code>kHz</code>, as specified in the <a href="https://en.wikipedia.org/wiki/International_System_of_Units">SI</a >. </p> </div> <h2 id="Examples">Examples</h2> <h3 id="Valid_frequency_values">Valid frequency values</h3> <pre> 12Hz Positive integer 4.3Hz Non-integer 14KhZ The unit is case-insensitive, though non-SI capitalization is not recommended. +0Hz Zero, with a leading + and a unit -0kHz Zero, with a leading - and a unit</pre > <h3 id="Invalid_frequency_values">Invalid frequency values</h3> <pre class="example-bad"> 12.0 This is a &lt;number&gt;, not an &lt;frequency&gt;, because it is missing a unit. 7 Hz No space is allowed between the number and the unit. 0 Although unitless zero is an allowable &lt;length&gt;, it's an invalid &lt;frequency&gt;.</pre > <h2 id="Specifications">Specifications</h2> {{Specifications}} <div class="note"> <p> <strong>Note:</strong> This data type was initially introduced in <a href="https://www.w3.org/TR/CSS2/aural.html#q19.0">CSS Level 2</a> for the now-obsolete <a href="/en-US/docs/Web/CSS/@media/aural">aural</a> <a href="/en-US/docs/Web/CSS/@media#Media_types">media type</a>, where it was used to define the pitch of the voice. However, the <code>&lt;frequency&gt;</code> data type has been reintroduced in CSS3, though no CSS property is using it at the moment. </p> </div> <h2 id="Browser_compatibility">Browser compatibility</h2> <p>{{Compat}}</p> <h2 id="See_also">See also</h2> <ul> <li>{{cssxref("&lt;frequency-percentage&gt;")}}</li> <li> <a href="/en-US/docs/Web/CSS/CSS_Values_and_Units">CSS Values and Units</a> </li> </ul>
/* SimpleMQTTClient.ino The purpose of this exemple is to illustrate a simple handling of MQTT and Wifi connection. Once it connects successfully to a Wifi network and a MQTT broker, it subscribe to a topic and send a message to it. It will also send a message delayed 5 seconds later. */ #include "EspMQTTClient.h" #include "PubSubClient.h" EspMQTTClient client( "ssid", "password", "test.mosquitto.org", // MQTT Broker server ip (test.mosquitto.org) "MQTTUsername", // Can be omitted if not needed "MQTTPassword", // Can be omitted if not needed "TestClient", // Client name that uniquely identify your device 1883 // The MQTT port, default to 1883. this line can be omitted ); void setup() { Serial.begin(115200); // Optionnal functionnalities of EspMQTTClient : client.enableDebuggingMessages(); // Enable debugging messages sent to serial output client.enableHTTPWebUpdater(); // Enable the web updater. User and password default to values of MQTTUsername and MQTTPassword. These can be overrited with enableHTTPWebUpdater("user", "password"). client.enableLastWillMessage("TestClient/lastwill", "I am going offline"); // You can activate the retain flag by setting the third parameter to true } // This function is called once everything is connected (Wifi and MQTT) // WARNING : YOU MUST IMPLEMENT IT IF YOU USE EspMQTTClient void onConnectionEstablished() { // Subscribe to "mytopic/test" and display received message to Serial client.subscribe("nr_workshop/test", [](const String & payload) { Serial.println(payload); }); // Publish a message to "mytopic/test" client.publish("nr_workshop/hallSensor/Andre", "This is a message"); // You can activate the retain flag by setting the third parameter to true // Execute delayed instructions client.executeDelayed(5 * 1000, []() { client.publish("nr_workshop/test", "This is a message sent 5 seconds later"); }); } void loop() { client.loop(); // read hall effect sensor value and publish it to the topic: nr_workshop/hallSensor/<your_name> client.publish("nr_workshop/hallSensor/Andre", String(hallRead())); // You can activate the retain flag by setting the third parameter to true delay(2000); }
from Crypto.Cipher import AES from Crypto.Random import get_random_bytes def encrypt_aes(key, plaintext): cipher = AES.new(key, AES.MODE_ECB) padded_plaintext = _pad(plaintext) ciphertext = cipher.encrypt(padded_plaintext) return ciphertext def decrypt_aes(key, ciphertext): cipher = AES.new(key, AES.MODE_ECB) decrypted_text = cipher.decrypt(ciphertext) return _unpad(decrypted_text) def _pad(plaintext): padding_length = AES.block_size - (len(plaintext) % AES.block_size) return plaintext + bytes([padding_length] * padding_length) def _unpad(padded_text): padding_length = padded_text[-1] return padded_text[:-padding_length] def main(): key = get_random_bytes(16) # 128-bit key plaintext = b"Hello, World!" # Encryption ciphertext = encrypt_aes(key, plaintext) print("Encrypted:", ciphertext.hex()) # Decryption decrypted_text = decrypt_aes(key, ciphertext) print("Decrypted:", decrypted_text.decode()) if __name__ == "__main__": main()
import React, { useState, useEffect, useContext } from "react"; import { BsPersonCircle } from "react-icons/bs"; import { Link, useNavigate } from "react-router-dom"; import { toast } from "react-hot-toast"; import { register } from "../api/user.api"; import { AuthContext } from "../context/AccountProvider"; function Signup() { const { setAccount, setAuthenticated } = useContext(AuthContext); const [previewImage, setPreviewImage] = useState(""); const navigate = useNavigate(); const [signupCredentials, setSignupCredentials] = useState({ name: "", email: "", password: "", confirmPassword: "", avatar: "", }); const handleUserInput = (e) => { const { name, value } = e.target; setSignupCredentials({ ...signupCredentials, [name]: value, }); }; const getImage = (event) => { event.preventDefault(); // geeting image const uploadedImage = event.target.files[0]; if (uploadedImage) { setSignupCredentials({ ...signupCredentials, avatar: uploadedImage, }); const fileReader = new FileReader(); fileReader.readAsDataURL(uploadedImage); fileReader.addEventListener("load", function () { setPreviewImage(this.result); }); } }; const createNewAccount = async (e) => { e.preventDefault(); toast.dismiss(); if ( !signupCredentials.name || !signupCredentials.email || !signupCredentials.confirmPassword || !signupCredentials.password ) { toast.error("Please fill all details"); return; } // checking name field length if (signupCredentials.name.length < 4) { toast.error("Name should be atleast of 4 characters"); return; } // email validation if ( !signupCredentials.email .toLocaleLowerCase() .match( /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ) ) { toast.error("Invalid Email Adress"); return; } // validate a password if ( !signupCredentials.password.match( /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@.#$!%*?&^])[A-Za-z\d@.#$!%*?&]{8,}$/ ) ) { toast.error( "password must be atleast one lowerCase, one uppercase , special character, one numeric and minimum 8 characterś long" ); return; } // confirm password if (signupCredentials.password !== signupCredentials.confirmPassword) { toast.error("Password and confirm Password must be same"); return; } const formData = new FormData(); formData.append("avatar", signupCredentials.avatar); formData.append("name", signupCredentials.name); formData.append("email", signupCredentials.email); formData.append("password", signupCredentials.password); formData.append("confirmPassword", signupCredentials.confirmPassword); try { let toastloading = toast.loading("Creating new account"); // const response = await fetch('https://chat-api-zrff.onrender.com/api/auth/register', { // method: 'POST', // body: formData // }) const response = await register(formData); const json = await response.json(); console.log(json); if (!json.success) { toast.error(json.msg, { id: toastloading, }); return; } toast.success(json.msg, { id: toastloading, }); localStorage.setItem("auth_token", json.auth_token); localStorage.setItem("Login_user", JSON.stringify(json.user)); setAccount(json.user); setAuthenticated(true); navigate("/"); } catch (error) { toast.dismiss(); return toast.error("network error"); } }; useEffect(() => { if (localStorage.getItem("auth_token") !== null) { window.location.reload(); navigate("/"); } // eslint-disable-next-line }, []); return ( <div className="flex items-center justify-center bg-gray-800 h-[100vh]"> <form action="" className="flex flex-col justify-center gap-3 rounded-lg p-4 text-white w-96 shadow-[0_0_10px_black]" noValidate onSubmit={createNewAccount} encType="multipart/form-data" > <h1 className="text-center text-2xl font-bold">Registration Page</h1> <label htmlFor="image_uploads" className="cursor-pointer"> {previewImage ? ( <img className="w-24 h-24 rounded-full m-auto" src={previewImage} alt="upload img" /> ) : ( <BsPersonCircle className="w-24 h-24 rounded-full m-auto " /> )} </label> <input className="hidden" type="file" id="image_uploads" accept=".jpg , .jpeg,.png , .svg" onChange={getImage} /> <div className="flex flex-col gap-1"> <label htmlFor="name" className="font-semibold"> Name </label> <input type="text" required name="name" id="name" placeholder="Enter your name" className="bg-transparent px-2 py-1 border" onChange={handleUserInput} /> </div> <div className="flex flex-col gap-1"> <label htmlFor="email" className="font-semibold"> Email </label> <input type="email" required name="email" id="email" placeholder="Enter your email" className="bg-transparent px-2 py-1 border" onChange={handleUserInput} /> </div> <div className="flex flex-col gap-1"> <label htmlFor="password" className="font-semibold"> Password </label> <input type="password" required name="password" id="password" placeholder="Enter your password" className="bg-transparent px-2 py-1 border" onChange={handleUserInput} /> </div> <div className="flex flex-col gap-1"> <label htmlFor="confirmPassword" className="font-semibold"> Confirm Password </label> <input type="password" required name="confirmPassword" id="confirmPassword" placeholder="Re enter your password" className="bg-transparent px-2 py-1 border" onChange={handleUserInput} /> </div> <button className="mt-2 bg-yellow-600 py-2 hover:bg-yellow-500 hover:rounded-sm transition-all ease-in-out duration-300" type="submit" > Create account </button> <p> Already have an account ?{" "} <Link to="/login" className="underline text-green-600 cursor-pointer"> Login </Link> </p> </form> </div> ); } export default Signup;
import fs from "fs" import TOML from "@ltd/j-toml" import glob from "glob" import { getTemplate } from "./get_template.mjs" import { normalizeSiteProperties } from "./normalize_site_properties.mjs" import { mergeProperties } from "./merge_properties.mjs" import { showTomlSytaxError } from "./show_toml_syntax_error.mjs" const getSiteData = directory => { const cwd = process.cwd() const siteData = { pages: [], layouts: [], segments: [], wrappers: [], articles: [], components: [], properties: { main: { scheme: "http", host: "localhost", port: 3000, "root-url": "http://localhost:3000/" } } } process.chdir(directory) const site_toml_path = "src/site.toml" if (fs.existsSync(site_toml_path)) { const source = fs.readFileSync(site_toml_path) try { const properties = TOML.parse(source, {joiner: "\n", bigint: false}) siteData.properties = mergeProperties(siteData.properties, properties) } catch (error) { showTomlSytaxError(site_toml_path, source, error) } } normalizeSiteProperties(siteData.properties) if (fs.existsSync("src/components")) { siteData.components = glob.sync("src/components/**/*.html").map(path => getTemplate(path, "component")) } siteData.wrappers = glob.sync("src/@(pages|articles)/**/_wrapper.html").map(path => getTemplate(path, "wrapper")) if (fs.existsSync("src/articles")) { siteData.articles = glob.sync("src/articles/**/!(_wrapper).html").map(path => getTemplate(path, "article", siteData.properties) ) } if (fs.existsSync("src/segments")) { siteData.segments = glob.sync("src/segments/**/*.html").map(path => getTemplate(path, "segment") ) } if (fs.existsSync("src/layouts")) { siteData.layouts = glob.sync("src/layouts/**/*.html").map(path => getTemplate(path, "layout")) } if (fs.existsSync("src/pages")) { siteData.pages = glob.sync("src/pages/**/!(_wrapper).html").map(path => getTemplate(path, "page", siteData.properties) ) } process.chdir(cwd) return siteData } export { getSiteData }
/* * National Training and Education Resource (NTER) * Copyright (C) 2012 SRI International * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.nterlearning.course.search; import com.liferay.portal.kernel.dao.orm.DynamicQuery; import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil; import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil; import com.liferay.portal.kernel.dao.search.SearchContainer; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.search.Document; import com.liferay.portal.kernel.search.Field; import com.liferay.portal.kernel.search.Hits; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.service.GroupLocalServiceUtil; import org.nterlearning.course.util.NterKeys; import org.nterlearning.datamodel.catalog.model.Course; import org.nterlearning.datamodel.catalog.service.CourseLocalServiceUtil; import java.util.*; import org.apache.commons.beanutils.BeanComparator; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.collections.comparators.ReverseComparator; public class CourseSearchUtil { /** * Sorts a list of courses on the given property name. The property name * must correspond to a getter method. ie. the property * <code>"courseId"</code> corresponds to <code>getCourseId()</code>. * * @param results List of courses to be modified. * @param property Name of property to sort on. * @param asc True to sort ascending, false to sort descending. * @return a sorted list of courses. */ @SuppressWarnings("unchecked") public static List<Course> orderCoursesBy(List<Course> results, final String property, final boolean asc) { Comparator<?> comparator; if (asc) { comparator = new ComparableComparator(); } else { comparator = new ReverseComparator(new ComparableComparator()); } BeanComparator comp = new BeanComparator(property, comparator); Collections.sort(results, comp); return results; } public static List<Course> getCoursesBySearchResults( List<Document> search) throws PortalException, SystemException { List<Course> results = new ArrayList<Course>(); for (Document doc : search) { results.add(CourseLocalServiceUtil.getCourse(GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK)))); } return results; } public static SearchContainer<Course> search(SearchContainer<Course> searchContainer, boolean removed, long companyId, long groupId) throws PortalException, SystemException { List<Course> results = new ArrayList<Course>(); int total = 0; String searchTerms = searchContainer.getPortletRequest().getParameter(NterKeys.SEARCH_TERMS); if (Validator.isNotNull(searchTerms)) { // Lucene Search // Get all hits Hits hits = CourseLocalServiceUtil.search(companyId, groupId, searchTerms, false, searchContainer.getStart(), searchContainer.getEnd()); // Set total total = hits.getLength(); // Count total hits // Set results sublist of current page results = CourseSearchUtil.getCoursesBySearchResults(hits.toList()); // Save searchTerms for pagination searchContainer.getIteratorURL().setParameter(NterKeys.SEARCH_TERMS, searchTerms); } else { DynamicQuery query; DynamicQuery query2; // if the contextual group is 'global', we want to show all courses if (GroupLocalServiceUtil.getGroup(groupId).isCompany()) { // TODO why does getCoursesCount() return an int and // dynamicQueryCount() return a long? // Can't reuse the same query twice for some reason... query = DynamicQueryFactoryUtil.forClass(Course.class).add( PropertyFactoryUtil.forName("companyId").eq(companyId)).add( PropertyFactoryUtil.forName("removed").eq(removed)); query2 = DynamicQueryFactoryUtil.forClass(Course.class).add( PropertyFactoryUtil.forName("companyId").eq(companyId)).add( PropertyFactoryUtil.forName("removed").eq(removed)); } else { // TODO why does getCoursesCount() return an int and // dynamicQueryCount() return a long? // Can't reuse the same query twice for some reason... query = DynamicQueryFactoryUtil.forClass(Course.class).add( PropertyFactoryUtil.forName("groupId").eq(groupId)).add( PropertyFactoryUtil.forName("removed").eq(removed)); query2 = DynamicQueryFactoryUtil.forClass(Course.class).add( PropertyFactoryUtil.forName("groupId").eq(groupId)).add( PropertyFactoryUtil.forName("removed").eq(removed)); } total = (int) CourseLocalServiceUtil.dynamicQueryCount(query); results = (List<Course>) CourseLocalServiceUtil.dynamicQuery(query2, searchContainer.getStart(), searchContainer.getEnd()); } // Assign results to search container searchContainer.setResults(results); searchContainer.setTotal(total); return searchContainer; } private static final Log _log = LogFactoryUtil.getLog(CourseSearchUtil.class); }
"use client"; import { motion } from "framer-motion"; import { useState } from "react"; const lineVariants = { large: { width: 80, backgroundColor: "white" }, small: { width: 40, backgroundColor: "#94a3b8" }, }; const textVariants = { large: { color: "white" }, small: { color: "#94a3b8" }, }; export const RouteButton = ({ content, selected, scrollTo, handleClick }) => { const [isHovered, setIsHovered] = useState(false); const handleButtonClick = (option) => { scrollTo(option); handleClick(option); }; return ( <motion.button className={`text-md flex h-full items-center rounded-sm py-4 font-semibold text-slate-400 antialiased`} onClick={() => handleButtonClick(content.toLowerCase())} onHoverStart={() => setIsHovered((isHovered) => !isHovered)} onHoverEnd={() => setIsHovered((isHovered) => !isHovered)} > <motion.div animate={ isHovered || selected == content.toLowerCase() ? "large" : "small" } transition={{ duration: 0.1, ease: "easeInOut", }} className="mr-2 inline-flex h-px bg-white" variants={lineVariants} /> <motion.div animate={ isHovered || selected == content.toLowerCase() ? "large" : "small" } className={isHovered ? "large" : "small"} variants={textVariants} > {content} </motion.div> </motion.button> ); };
import { Button } from '../../../../components/global/Button/Button'; import { Form } from '../../../../components/global/Form/Form'; import { Modal } from '../../../../components/global/Modal/Modal'; import { TextInput } from '../../../../components/global/inputs/TextInput/TextInput'; import { UseModal } from '../../../../hooks/useModal'; import { useUpsertSurveyModal } from './useUpsertSurveyModal'; import { ColorInput } from '../../../../components/global/inputs/ColorInput/ColorInput'; import styles from './UpsertSurveyModal.module.css'; interface UpsertSurveyModalProps extends UseModal { editedSurvey?: Survey; } export const UpsertSurveyModal = ({ editedSurvey, ...modalData }: UpsertSurveyModalProps) => { const { errors, handleUpsert, isDirty, isValid, register, reset, setRandomColor, } = useUpsertSurveyModal({ editedSurvey, handleCloseModal: modalData.handleClose, }); return ( <Modal {...modalData}> <Form onReset={() => reset({})} onSubmit={handleUpsert}> <div> <TextInput {...register('title')} error={errors.title?.message} label={`Title: `} placeholder='My own title' /> <TextInput {...register('age')} error={errors.age?.message} label={`Age: `} type='number' placeholder='44' /> <TextInput {...register('hight')} error={errors.hight?.message} label={`Hight: `} type='number' placeholder='192' /> <div className={styles.colorInputWrapper}> <ColorInput {...register('favouriteColor')} error={errors.favouriteColor?.message} label={`Favourite color: `} /> <Button onClick={setRandomColor} type='button'> Random color </Button> </div> <TextInput {...register('sex')} error={errors.sex?.message} label={`Sex: `} placeholder='male or female' /> </div> <Form.ButtonsWrapper> <Button type={'reset'}>Reset</Button> <Button disabled={!isValid || !isDirty} type={'submit'}> {editedSurvey ? 'Edit' : 'Add'} survey </Button> </Form.ButtonsWrapper> </Form> </Modal> ); };
import { useSession } from "next-auth/react"; import { Button } from "./Button"; import { ProfileImage } from "./ProfileImage"; import { useCallback, useLayoutEffect, useRef, useState } from "react"; import type { FormEvent } from "react"; import { api } from "~/utils/api"; import { updateTextAreaSize } from "~/utils/helperFunctions"; export function NewTweetForm() { const session = useSession(); if (session.status !== "authenticated") return ( <div className="flex h-[75px] w-full items-center"> <h1 className="text-xl">Recent tweets:</h1> </div> ); return <Form />; } export function Form() { const session = useSession(); const [inputValue, setInputValue] = useState(""); const textAreaRef = useRef<HTMLTextAreaElement>(); const inputRef = useCallback((textArea: HTMLTextAreaElement) => { updateTextAreaSize(textArea); textAreaRef.current = textArea; }, []); const trpcUtils = api.useUtils(); useLayoutEffect(() => { updateTextAreaSize(textAreaRef.current); }, [inputValue]); const createTweet = api.tweet.create.useMutation({ onSuccess: (newTweet) => { setInputValue(""); if (session.status !== "authenticated") return null; trpcUtils.tweet.infiniteFeed.setInfiniteData({}, (oldData) => { if (!oldData?.pages[0]) return; const newCacheData = { ...newTweet, likeCount: 0, commentsCount: 0, likedByMe: false, user: { id: session.data.user.id, name: session.data.user.name ?? null, image: session.data.user.image ?? null, }, }; return { ...oldData, pages: [ { ...oldData.pages[0], tweets: [newCacheData, ...oldData.pages[0].tweets], }, ...oldData.pages.slice(1), ], }; }); trpcUtils.profile.getById.setData( { id: session.data?.user.id }, (oldData) => { if (oldData == null) return; return { ...oldData, tweetsCount: oldData.tweetsCount + 1, }; }, ); }, }); function handleSubmit(e: FormEvent) { e.preventDefault(); createTweet.mutate({ content: inputValue }); } if (session.status !== "authenticated") return null; return ( <> <form onSubmit={handleSubmit} className="mb-4 mt-6 flex flex-col gap-2 rounded-2xl bg-[#1b2730] px-4 py-4" > <div className="flex gap-4"> <ProfileImage src={session.data.user.image} /> <textarea ref={inputRef} style={{ height: 0 }} value={inputValue} onChange={(e) => setInputValue(e.target.value)} className="flex-grow resize-none overflow-hidden rounded-2xl bg-white/10 p-4 text-lg outline-none" placeholder="What is happening ?!" /> </div> <Button className="self-end" disabled={inputValue.length == 0}> Post </Button> </form> </> ); }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/sagemaker/model/UpdateHubRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::SageMaker::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateHubRequest::UpdateHubRequest() : m_hubNameHasBeenSet(false), m_hubDescriptionHasBeenSet(false), m_hubDisplayNameHasBeenSet(false), m_hubSearchKeywordsHasBeenSet(false) { } Aws::String UpdateHubRequest::SerializePayload() const { JsonValue payload; if(m_hubNameHasBeenSet) { payload.WithString("HubName", m_hubName); } if(m_hubDescriptionHasBeenSet) { payload.WithString("HubDescription", m_hubDescription); } if(m_hubDisplayNameHasBeenSet) { payload.WithString("HubDisplayName", m_hubDisplayName); } if(m_hubSearchKeywordsHasBeenSet) { Aws::Utils::Array<JsonValue> hubSearchKeywordsJsonList(m_hubSearchKeywords.size()); for(unsigned hubSearchKeywordsIndex = 0; hubSearchKeywordsIndex < hubSearchKeywordsJsonList.GetLength(); ++hubSearchKeywordsIndex) { hubSearchKeywordsJsonList[hubSearchKeywordsIndex].AsString(m_hubSearchKeywords[hubSearchKeywordsIndex]); } payload.WithArray("HubSearchKeywords", std::move(hubSearchKeywordsJsonList)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection UpdateHubRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "SageMaker.UpdateHub")); return headers; }
import { message, Modal, Typography } from 'antd' import songAPI from 'api/songAPI' import { changeValueCommon } from 'features/Common/commonSlice' import React from 'react' import { useMutation, useQueryClient } from 'react-query' import { useDispatch, useSelector } from 'react-redux' function SongModalUpdate() { const queryClient = useQueryClient() const dispatch = useDispatch() const setVisible = (value) => { dispatch( changeValueCommon({ name: 'songDeleteOpen', value: value, }) ) } const visible = useSelector((state) => state.common.songDeleteOpen) const data = useSelector((state) => state.common.songDeleteData) const { mutate, isLoading } = useMutation(() => songAPI.delete(data._id), { onSuccess: () => { message.success('Xóa bài hát thành công') }, onError: () => { message.error('Xóa bài hát thất bại') }, onSettled: () => { queryClient.invalidateQueries('my-song-list') setVisible(false) }, }) return ( <Modal title="Xóa bài hát" visible={visible} onCancel={() => setVisible(false)} onOk={mutate} okText="Đồng ý" cancelText="Hủy bỏ" confirmLoading={isLoading} > <Typography.Title level={5}> Bạn chắc chắc muốn xóa bài hát này?</Typography.Title> </Modal> ) } SongModalUpdate.propTypes = {} export default SongModalUpdate
import * as s from './ContactList.styled'; // import PropTypes from 'prop-types' import { useDispatch } from 'react-redux'; import { useSelector } from 'react-redux'; import { deleteContact } from '../../redux/contacts'; import { selectVisibleContacts } from '../../redux/selectors'; export const ContactList = () => { const dispatch = useDispatch(); const filteredContacts = useSelector(selectVisibleContacts) return ( <s.List> {filteredContacts.map(({id, name, number}) => ( <s.ListItems key={id}> <s.Name>{name}:</s.Name> <s.Number>{number}</s.Number> <s.Button type="button" onClick={() => dispatch(deleteContact(id))} > Delete </s.Button> </s.ListItems> ))} </s.List> ); };
def break_words(stuff): "This function will break up words for us!" words = stuff.split(' ') return words def sort_words(words): return sorted(words) def print_first_word(words): """print first word after popping it off """ word = words.pop(0) # pop = remove item from it position in the list, and return it to var. print(word) def print_last_word(words): word = words.pop() print(word) def sort_sentence(sentence): "Takes in a full sentence and return the sorted words" words = break_words(sentence) return sorted(words) def print_first_and_last(sentence): "Print first and last word" words = break_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): "Print sorted 1st and last word " words = sort_sentence(sentence) print_first_word(words) print_last_word(words)
package com.herald.currencyapp.presentation.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.herald.currencyapp.common.Resources import com.herald.currencyapp.domain.models.CurrencyExchange import com.herald.currencyapp.domain.usecases.GetExchangeRateUseCase import com.herald.currencyapp.domain.usecases.GetPopularCurrenciesUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import javax.inject.Inject @HiltViewModel class ConversionViewModel @Inject constructor( private val getPopularCurrenciesUseCase: GetPopularCurrenciesUseCase, private val getExchangeRateUseCase: GetExchangeRateUseCase ) : ViewModel() { private val _statePopularCurrencies = MutableLiveData<StateCurrency>() val statePopularCurrencies: LiveData<StateCurrency> = _statePopularCurrencies private val _stateExchange = MutableLiveData<StateCurrency>() val stateExchange: LiveData<StateCurrency> = _stateExchange fun getPopularCurrencies(currency: String) { getPopularCurrenciesUseCase(currency).onEach { when (it) { is Resources.Loading -> { _statePopularCurrencies.value = StateCurrency(isLoading = true) } is Resources.Success -> { _statePopularCurrencies.value = StateCurrency(topCurrenciesRates = mapTopCurrencies(it.data!!)) } is Resources.Error -> { _statePopularCurrencies.value = StateCurrency(error = it.message) } } }.launchIn(viewModelScope) } fun getExchangeRate(from: String, to: String) { getExchangeRateUseCase(from, to).onEach { when (it) { is Resources.Loading -> { _stateExchange.value = StateCurrency(isLoading = true) } is Resources.Success -> { _stateExchange.value = StateCurrency(exchangeRate = calculateExchangeRate(it.data!!)) } is Resources.Error -> { _stateExchange.value = StateCurrency(error = it.message) } } }.launchIn(viewModelScope) } private fun mapTopCurrencies(exchange: CurrencyExchange):Map<String,Double>{ val topCurrenciesRates: Map<String, Double> = exchange.rates.entries.toList().associate { entry-> entry.key to entry.value / exchange.rates.values.toList()[0] } return topCurrenciesRates } private fun calculateExchangeRate(exchange: CurrencyExchange): Double{ val ratesList = exchange.rates.values.toList() return if (ratesList.count() == 1) 1.0 else ratesList[1] / ratesList[0] } data class StateCurrency( val isLoading: Boolean = false, val topCurrenciesRates: Map<String, Double>? = null, val exchangeRate: Double? = null, val error: String? = null ) }
<!DOCTYPE html> <html lang="es"> <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>Pet Paradise - Home page.</title> <link rel="stylesheet" href="/css/styles.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Neucha&family=Nunito+Sans:wght@200;300;400;700&display=swap" rel="stylesheet"> <script src="https://kit.fontawesome.com/be2f25d2d7.js" crossorigin="anonymous"></script> </head> <body> <!-- Header con 4 divs: 1. superior: solo para efectos estéticos de color. visible en todos los viewports 2. main: logo, barra búsqueda e ícono carrito compras. visible en todos los viewports. se adapta el main a su vez tendrá una sección oculta (precio) que solo se ve en el viewport full 3. nav: links de navegación. solo visible en viewport tablet y full 4. inferior: para promos. visible en todos los viewports --> <!-- aqui va el header desde el partial --> <%- include("../partials/header") %> <main> <div class="main__posicionMenuTitulo"> <div class="header_nav-versionesMobile"> <i class="fa-solid fa-bars header_nav-hamgurgerMenu"></i> </div> <div> <h1 class="main__tituloPagina">Pet Paradise</h1> <p class="main__texto-subtitulo"><em> Comprá desde la comodidad tu casa. Ahorrá tiempo y dinero. Descubrí el más amplio stock de productos, las mejores ofertas y servicios para tu mascota.</em> <p> </div> </div> <hr class="main__bordeInferiorTextSubtitulo"> <!-- Navegacion lateral y cuerpo con imágenes principales total 4 --> <div class="main-principal"> <nav class="main-principal__nav"> <h3>Perros</h3> <ul> <li> <a href="">Alimentos secos </a> </li> <li> <a href="">Alimentos humedos</a> </li> <li> <a href="">Alimentos especiales</a></li> </ul> <h3>Gatos</h3> <ul> <li> <a href="">Alimentos secos</a> </li> <li> <a href="">Alimentos humedos</a> </li> <li> <a href="">Alimentos especiales</a> </li> </ul> <h3>Accesorios</h3> <ul> <li> <a href="">Camas y mantas</a> </li> <li> <a href="">Comederos y bebederos</a> </li> <li> <a href="">Elementos de paseo</a> </li> <li> <a href="">Juguetes</a> </li> </ul> <h3>Servicios</h3> <ul> <li> <a href="">Paseadores de perros</a> </li> <li> <a href="">Veterinarias asociadas</a> </li> <li> <a href="">Higiene de mascotas</a> </li> </ul> </nav> <section class="main-section-articles"> <% products.forEach(product => { %> <a href="/products/detail/<%= product.id %> "> <article class="main-article"> <img src="/img/productos/<%= product.image %> " alt=""> <div class="main-article__textos"> <div class="main-article__nombre-precio" > <h3><%= product.brand %> </h3> <p>$<%= product.price %> </p> </div> <a href="/products/detail/<%= product.id %> "><p> <%= product.name %> </p> </a> <p class="main-article__texto-detalle" main-article__texto-detalle><%= product.codigo %> </p> </div> </article> </a> <% }); %> <!-- <article class="main-article"> <img src="/img/productos/criadores-150002.png" alt=""> <div class="main-article__textos"> <div class="main-article__nombre-precio" > <h3>Criadores</h3> <p>$4555</p> </div> <a href="/products/detail"><p> Carne y pollo para perros adultos </p> </a> <p class="main-article__texto-detalle" main-article__texto-detalle>Bolsa 15 kilos. Código de producto: 148048</p> </div> </article> <article class="main-article"> <img src="/img/productos/oldPrince-148048.png" alt=""> <div class="main-article__textos"> <div class="main-article__nombre-precio" > <h3>Old Prince</h3><p>$7250</p> </div> <p> <a href="">Alimento secos perros medianos</a> </p> <p class="main-article__texto-detalle">Bolsa 10 kilos. Código de producto: 135845</p> </div> </article> <article class="main-article"> <img src="/img/productos/royalCanin-156157.jpg" alt=""> <div class="main-article__textos"> <div class="main-article__nombre-precio" > <h3>Royal Canin</h3><p>$9250</p> </div> <p> <a href="">Adult mix tamaño perros medianos</a> </p> <p class="main-article__texto-detalle">Bolsa 20 kilos. Código de producto: 167865</p> </div> </article> <article class="main-article"> <img src="/img/productos/vitalCanBalaced_121070.png" alt=""> <div class="main-article__textos"> <div class="main-article__nombre-precio" > <h3>Vital Balance</h3><p>$4300</p> </div> <p> <a href="">Alimento mix balanceado</a> </p> <p class="main-article__texto-detalle">Bolsa 10 kilos. Código de producto: 115597</p> </div> </article> <article class="main-article"> <img src="/img/productos/excellent-alimento-para-gato.png" alt=""> <div class="main-article__textos"> <div class="main-article__nombre-precio" > <h3>Purina Chow</h3><p>$2150</p> </div> <p> <a href="">Alimento seco para gatos mayores</a> </p> <p class="main-article__texto-detalle">Bolsa 12 kilos. Código de producto: 198753</p> </div> </article> <article class="main-article"> <img src="/img/productos/mvholiday-alimento-para-gatos.png" alt=""> <div class="main-article__textos"> <div class="main-article__nombre-precio" > <h3>MV Alimento</h3><p>$3870</p> </div> <p> <a href="">Defense plus multiproteína</a> </p> <p class="main-article__texto-detalle">Bolsa 5 kilos. Código de producto: 1567893</p> </div> </article> <article class="main-article"> <img src="/img/productos/proplan-alimento-para-gatos.png" alt=""> <div class="main-article__textos"> <div class="main-article__nombre-precio" > <h3>Purina Cat</h3><p>$9800</p> </div> <p> <a href="">Alimento rico en aminoácicos</a> </p> <p class="main-article__texto-detalle">Bolsa 7.5 kilos. Código de producto: 198756</p> </div> </article> <article class="main-article"> <img src="/img/productos/royalcanin-alimento-para-gatos.png" alt=""> <div class="main-article__textos"> <div class="main-article__nombre-precio" > <h3>Royal Canin</h3><p>$7350</p> </div> <p> <a href="">Para gatos castrados young male</a> </p> <p class="main-article__texto-detalle">Bolsa 12 kilos. Código de producto: 159876</p> </div> </article> --> </section> </div> </main> <!-- insertar el footer con partials ejs --> <%- include("../partials/footer") %> </body> </html>
#include <iostream> #include <fstream> #include <string> #include <unordered_map> int main(int argc, char * argv[]) { std::ifstream infile(argv[1]); // Input file named "strings.txt" if (!infile) { std::cerr << "Failed to open the input file." << std::endl; return 1; } // Using an unordered_map to store file streams for different lengths. std::unordered_map<size_t, std::ofstream> outfiles; std::string line; while (std::getline(infile, line)) { size_t length = line.size(); // If an ofstream for this length doesn't already exist, create it. if (outfiles.find(length) == outfiles.end()) { std::string filename = "length_" + std::to_string(length) + ".txt"; outfiles[length].open(filename, std::ios::out); if (!outfiles[length]) { std::cerr << "Failed to open the output file: " << filename << std::endl; return 1; } } outfiles[length] << line << '\n'; } // Close all the opened ofstream objects. for (auto& pair : outfiles) { pair.second.close(); } return 0; }
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppRoutingModule} from './app-routing.module'; import {AppComponent} from './app.component'; import {environment} from '../environments/environment'; import {AngularFireModule} from '@angular/fire'; import {AngularFirestoreModule} from '@angular/fire/firestore'; import {AngularFireAuthModule} from '@angular/fire/auth'; import {StoreModule} from '@ngrx/store'; import {AppReducers} from './app.reducer'; import {StoreDevtoolsModule} from '@ngrx/store-devtools'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, AngularFireModule.initializeApp(environment.firebase), AngularFirestoreModule, AngularFireAuthModule, StoreModule.forRoot(AppReducers), StoreDevtoolsModule.instrument({ maxAge: 25 }), ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
/* Copyright (C) 2014-2017 de4dot@gmail.com This file is part of dnSpy dnSpy 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. dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>. */ using System; namespace dnSpy.Contracts.Hex { /// <summary> /// Hex version changed event args /// </summary> public abstract class HexVersionChangedEventArgs : EventArgs { /// <summary> /// Version before the change /// </summary> public HexVersion BeforeVersion { get; } /// <summary> /// Version after the change /// </summary> public HexVersion AfterVersion { get; } /// <summary> /// Edit tag passed to <see cref="HexBuffer.CreateEdit(int?, object)"/> /// </summary> public object EditTag { get; } /// <summary> /// Constructor /// </summary> /// <param name="beforeVersion">Version before the change</param> /// <param name="afterVersion">Version after the change</param> /// <param name="editTag">Edit tag</param> protected HexVersionChangedEventArgs(HexVersion beforeVersion, HexVersion afterVersion, object editTag) { BeforeVersion = beforeVersion ?? throw new ArgumentNullException(nameof(beforeVersion)); AfterVersion = afterVersion ?? throw new ArgumentNullException(nameof(afterVersion)); EditTag = editTag; } } }
import numpy as np import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, LSTM, Dense # Загрузка данных из файла with open('training_data.txt', 'r', encoding='utf-8') as file: lines = file.readlines() # Разделение на вопросы и ответы questions = [line.strip() for i, line in enumerate(lines) if i % 2 == 0] answers = [line.strip() for i, line in enumerate(lines) if i % 2 != 0] # Инициализация токенизатора tokenizer = Tokenizer() tokenizer.fit_on_texts(questions + answers) # Преобразование текстов в последовательности чисел questions_sequences = tokenizer.texts_to_sequences(questions) answers_sequences = tokenizer.texts_to_sequences(answers) # Определение максимальной длины последовательности max_len = max(len(seq) for seq in questions_sequences + answers_sequences) # Приведение всех последовательностей к одной длине questions_padded_sequences = pad_sequences(questions_sequences, maxlen=max_len, padding='post') answers_padded_sequences = pad_sequences(answers_sequences, maxlen=max_len, padding='post') # Создание модели model = Sequential([ Embedding(input_dim=len(tokenizer.word_index) + 1, output_dim=8, input_length=max_len), LSTM(16), Dense(len(tokenizer.word_index) + 1, activation='softmax') ]) # Компиляция модели model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Обучение модели model.fit(questions_padded_sequences, np.argmax(answers_padded_sequences, axis=1), epochs=100) # Сохранение модели model.save('chatbot_model.h5') # modal
import { TestBed, getTestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import * as moment from 'moment'; import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; import { CaseStatusDetailsService } from 'app/entities/case-status-details/case-status-details.service'; import { ICaseStatusDetails, CaseStatusDetails } from 'app/shared/model/case-status-details.model'; describe('Service Tests', () => { describe('CaseStatusDetails Service', () => { let injector: TestBed; let service: CaseStatusDetailsService; let httpMock: HttpTestingController; let elemDefault: ICaseStatusDetails; let expectedResult: ICaseStatusDetails | ICaseStatusDetails[] | boolean | null; let currentDate: moment.Moment; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], }); expectedResult = null; injector = getTestBed(); service = injector.get(CaseStatusDetailsService); httpMock = injector.get(HttpTestingController); currentDate = moment(); elemDefault = new CaseStatusDetails(0, 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', currentDate, 'AAAAAAA'); }); describe('Service methods', () => { it('should find an element', () => { const returnedFromService = Object.assign( { createdAt: currentDate.format(DATE_TIME_FORMAT), }, elemDefault ); service.find(123).subscribe(resp => (expectedResult = resp.body)); const req = httpMock.expectOne({ method: 'GET' }); req.flush(returnedFromService); expect(expectedResult).toMatchObject(elemDefault); }); it('should create a CaseStatusDetails', () => { const returnedFromService = Object.assign( { id: 0, createdAt: currentDate.format(DATE_TIME_FORMAT), }, elemDefault ); const expected = Object.assign( { createdAt: currentDate, }, returnedFromService ); service.create(new CaseStatusDetails()).subscribe(resp => (expectedResult = resp.body)); const req = httpMock.expectOne({ method: 'POST' }); req.flush(returnedFromService); expect(expectedResult).toMatchObject(expected); }); it('should update a CaseStatusDetails', () => { const returnedFromService = Object.assign( { status: 'BBBBBB', assignee: 'BBBBBB', comments: 'BBBBBB', timeElapasedInCurrentStatus: 'BBBBBB', createdAt: currentDate.format(DATE_TIME_FORMAT), createdBy: 'BBBBBB', }, elemDefault ); const expected = Object.assign( { createdAt: currentDate, }, returnedFromService ); service.update(expected).subscribe(resp => (expectedResult = resp.body)); const req = httpMock.expectOne({ method: 'PUT' }); req.flush(returnedFromService); expect(expectedResult).toMatchObject(expected); }); it('should return a list of CaseStatusDetails', () => { const returnedFromService = Object.assign( { status: 'BBBBBB', assignee: 'BBBBBB', comments: 'BBBBBB', timeElapasedInCurrentStatus: 'BBBBBB', createdAt: currentDate.format(DATE_TIME_FORMAT), createdBy: 'BBBBBB', }, elemDefault ); const expected = Object.assign( { createdAt: currentDate, }, returnedFromService ); service.query().subscribe(resp => (expectedResult = resp.body)); const req = httpMock.expectOne({ method: 'GET' }); req.flush([returnedFromService]); httpMock.verify(); expect(expectedResult).toContainEqual(expected); }); it('should delete a CaseStatusDetails', () => { service.delete(123).subscribe(resp => (expectedResult = resp.ok)); const req = httpMock.expectOne({ method: 'DELETE' }); req.flush({ status: 200 }); expect(expectedResult); }); }); afterEach(() => { httpMock.verify(); }); }); });
#include <WiFi.h> #include <ESPAsyncWebServer.h> const char * apSsid = "Smart Config NBY"; const char * apPassword = "12345678"; AsyncWebServer server(80); const String html = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><script src=\"https:\/\/cdn.tailwindcss.com\"><\/script><title>Smart Config<\/title><\/head><body><div class=\"w-full h-screen py-20 md:py-40 p-2\" style=\"background-image:url(https:\/\/www.linkpicture.com\/q\/sc_1.webp);background-size:cover\"><div class=\"container max-w-lg mx-auto p-4 bg-sky-100 bg-opacity-30 rounded-lg shadow-lg\"><h1 class=\"text text-2xl text-center text-sky-500 font-bold tracking-widest\">SMART CONFIG<\/h1><div class=\"my-8\"><\/div><form method=\"post\" action=\"\/smart-config\"><div class=\"flex flex-col\"><label for=\"ssid-input\" class=\"text text-lg text-sky-500\">SSID<\/label><input type=\"text\" name=\"ssid\" id=\"ssid-input\" class=\"shadow-lg outline-none rounded-lg p-2 focus:ring-1 ring-sky-500 placeholder:text-sky-300\" placeholder=\"Enter SSID\"><\/div><div class=\"my-2\"><\/div><div class=\"flex flex-col\"><label for=\"password-input\" class=\"text text-lg text-sky-500\">Password<\/label><input type=\"password\" name=\"password\" id=\"password-input\" class=\"shadow-lg outline-none rounded-lg p-2 focus:ring-1 ring-sky-500 placeholder:text-sky-300\" placeholder=\"Enter Password\"><\/div><div class=\"my-6\"><\/div><div class=\"flex justify-center w-full\"><button type=\"submit\" class=\"shadow-lg bg-sky-500 text-white rounded-lg p-2 hover:bg-sky-600 duration-100 focus:scale-110\">SUBMIT<\/button><\/div><\/form><\/div><\/div><\/body><\/html>"; void setup() { Serial.begin(115200); WiFi.softAP(apSsid, apPassword); Serial.print("AP started with IP: "); Serial.println(WiFi.softAPIP()); server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) { request -> send(200, "text/plain", "Hello, world"); }); server.on("/smart-config", HTTP_GET, [](AsyncWebServerRequest * request) { request -> send(200, "text/html", html); }); server.on("/smart-config", HTTP_POST, [](AsyncWebServerRequest * request) { Serial.println("POST"); Serial.println(request -> arg("ssid")); Serial.println(request -> arg("password")); WiFi.begin(request -> arg("ssid").c_str(), request -> arg("password").c_str()); Serial.print("\nConnecting to WiFi.."); unsigned long start = millis(); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); if (millis() - start > 10000) { Serial.println("Can not connect to the WiFi network"); request -> send(200, "text/html", "Can not connect to the WiFi network"); break; } } Serial.print("\n\nConnected to the WiFi network with local IP: "); Serial.println(WiFi.localIP()); request -> send(200, "text/html", "Connected to the WiFi network with local IP: " + WiFi.localIP().toString()); }); // Start server server.begin(); Serial.println("Server started"); } void loop() {}
package com.emirtemindarov.tablesapp.games import androidx.room.* import kotlinx.coroutines.flow.Flow @Dao interface GamesDao { @Upsert suspend fun upsertGame(game: Game) @Delete suspend fun deleteGame(game: Game) @Query("SELECT * FROM game") fun getGamesOrderedByDefault(): Flow<List<Game>> @Query("SELECT * FROM game ORDER BY difficulty Asc") fun getGamesOrderedByDifficulty(): Flow<List<Game>> @Query("SELECT * FROM game ORDER BY bestScore Desc") fun getGamesOrderedByBestScore(): Flow<List<Game>> }
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.css"> <style> .item { float: left; margin-right: 16px; } .toolbar { margin: auto; padding: auto; width: 60%; display: block; } /* 默认编辑器样式 */ #editor { position: relative; top: 8px; width: 60%; height: 600px; border: 1px solid #a2a2a2; border-radius: 8px; padding: 8px; margin: auto; font-family: STKaiti; font-size: 18px; clear: both; } </style> </head> <body> <div class="toolbar"> <div class="item"> <!-- 字体样式选择 --> <label for="font-family"><i class="fa-solid fa-font"></i></label> <select id="font-family" onchange="setFontFamily()"> <option value="SimHei">黑体</option> <option value="Microsoft YaHei">微软雅黑</option> <option value="STXihei">华文细黑</option> <option value="STKaiti" selected>楷体</option> <option value="kaiTi_GB2312">楷体_GB2312</option> <option value="SimSun">宋体</option> <option value="FangSong">仿宋</option> <option value="NSimSun">新宋体</option> <option value="LiSu">隶书</option> <option value="STXinwei">华文新魏</option> <option value="STCaiYun">华文彩云</option> <option value="FZShuTi">方正舒体</option> <option value="FZYaoTi">方正姚体</option> </select> </div> <div class="item"> <!-- 文字大小选择 --> <label for="font-size">Size:</label> <input type="number" id="font-size" min="1" max="100" value="18" onchange="setFontSize()"> </div> <div class="item"> <!-- 字体粗细选择 --> <label for="font-weight"><i class="fa-solid fa-bold"></i></label> <select id="font-weight" onchange="setFontWeight()"> <option value="normal">正常</option> <option value="bold">粗体</option> </select> </div> <div class="item"> <!-- 文字颜色选择 --> <label for="font-color"><i class="fa-solid fa-palette"></i></label> <input type="color" id="font-color" onchange="setColor()"> </div> <div class="item"> <!-- 保存文件格式选择 --> <label for="file-format"><i class="fa-solid fa-file"></i></label> <select id="file-format"> <option value=".java">Java</option> <option value=".c">C</option> <option value=".cpp">C++</option> <option value=".html">HTML</option> <option value=".py">Python</option> <option value=".css">CSS</option> <option value=".js">JavaScript</option> </select> </div> <div> <!-- 保存 --> <i class="fa-solid fa-download" onclick="saveToFile()"></i> </div> </div> <div> <!-- 编辑器内容区域 --> <div id="editor" contenteditable="true"> </div> </div> </body> <script> function setFontFamily() { var editor = document.getElementById('editor'); var fontFamily = document.getElementById('font-family').value; editor.style.fontFamily = fontFamily; } function setFontSize() { var editor = document.getElementById('editor'); var fontSize = document.getElementById('font-size').value + "px"; editor.style.fontSize = fontSize; } function setColor() { var editor = document.getElementById('editor'); var fontColor = document.getElementById('font-color').value; editor.style.color = fontColor; } function setFontWeight() { var editor = document.getElementById('editor'); var fontWeight = document.getElementById('font-weight').value; editor.style.fontWeight = fontWeight; } function saveToFile() { // 获取编辑器 var editor = document.getElementById('editor'); var editorContent = editor.innerHTML; // 获取用户选择的保存文件格式 var fileFormat = document.getElementById('file-format').value; // 创建一个下载链接 var downloadLink = document.createElement('a'); downloadLink.href = 'data:text/plain,' + encodeURIComponent(editorContent); downloadLink.download = 'file' + fileFormat; // 添加下载链接到页面并点击触发下载 document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } </script> </html>
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. import assert from "assert"; import { RankedStorageAccountSet } from "../src/rankedStorageAccountSet"; describe("RankedStorageAccountSet", () => { describe("Input validation.", () => { it("Validate registerStorageAccount().", () => { const accounts = new RankedStorageAccountSet(); // Register accounts for (let i = 0; i < 10; i++) { accounts.registerStorageAccount("account_" + i.toString()); } // Validate accounts for (let i = 0; i < 10; i++) { assert.equal(accounts.getStorageAccount("account_" + i.toString()).getAccountName(), "account_" + i.toString()); } }); it("Validate logResultToAccount().", () => { const accounts = new RankedStorageAccountSet(); // Register accounts accounts.registerStorageAccount("account_1"); // Should work accounts.logResultToAccount("account_1", true); // Should throw assert.throws(() => accounts.logResultToAccount("account_2", true), Error); }); it("Validate getStorageAccount().", () => { const accounts = new RankedStorageAccountSet(); // Register accounts accounts.registerStorageAccount("account_1"); // Should work assert.equal(accounts.getStorageAccount("account_1").getAccountName(), "account_1"); // Should throw assert.throws(() => accounts.getStorageAccount("account_2"), Error); }); }); describe("Check rank using getRankedShuffledAccounts.", () => { it("Validate rank when no data.", () => { const accounts = new RankedStorageAccountSet(); // Register accounts for (let i = 0; i < 10; i++) { accounts.registerStorageAccount("account_" + i.toString()); } // get shuffeled accounts const rankedAccounts = accounts.getRankedShuffledAccounts(); // validate rank for (const account of rankedAccounts) { // All accounts should have rank 1 (highest rank) assert.equal(account.getRank(), 1); } }); it("Verify that getRankedShuffledAccounts returns shuffled accounts in each call.", () => { const accounts = new RankedStorageAccountSet(); // Register accounts for (let i = 0; i < 100; i++) { accounts.registerStorageAccount("account_" + i.toString()); } // get shuffeled accounts const shuffledAccounts1 = accounts.getRankedShuffledAccounts(); const shuffledAccounts2 = accounts.getRankedShuffledAccounts(); // make sure buth list has the same accounts const set1 = new Set(shuffledAccounts1); const set2 = new Set(shuffledAccounts2); // check intersection const intersection = new Set([...set1].filter((x) => !set2.has(x))); assert.equal(intersection.size, 0); // Check that the order is different assert.notDeepEqual(shuffledAccounts1, shuffledAccounts2); }); it("Validate rank when success rate is different.", () => { let time = 0; const accounts = new RankedStorageAccountSet(undefined, undefined, undefined, () => { return time; }); // Register accounts for (let i = 1; i <= 5; i++) { accounts.registerStorageAccount("account_" + i.toString()); } // log results for 60 seconds for (time = 0; time < 60; time++) { accounts.logResultToAccount("account_1", true); // 100% success accounts.logResultToAccount("account_2", time % 10 !== 0); // ~90% success accounts.logResultToAccount("account_3", time % 2 === 0); // 50% success accounts.logResultToAccount("account_4", time % 3 === 0); // ~33% success accounts.logResultToAccount("account_5", false); // 0% success } // get shuffeled accounts and validate order const rankedAccounts = accounts.getRankedShuffledAccounts(); assert.equal(rankedAccounts[0].getAccountName(), "account_1"); assert.equal(rankedAccounts[1].getAccountName(), "account_2"); expect(["account_3", "account_4"]).toContain(rankedAccounts[2].getAccountName()); expect(["account_3", "account_4"]).toContain(rankedAccounts[3].getAccountName()); assert.equal(rankedAccounts[4].getAccountName(), "account_5"); // validate rank assert.equal(accounts.getStorageAccount("account_1").getRank(), 1); expect(accounts.getStorageAccount("account_2").getRank()).toBeCloseTo(0.9); assert.equal(accounts.getStorageAccount("account_3").getRank(), 0.5); expect(accounts.getStorageAccount("account_4").getRank()).toBeCloseTo(0.32); assert.equal(accounts.getStorageAccount("account_5").getRank(), 0); }); it("Validate that newer results have more weight.", () => { let time = 0; const accounts = new RankedStorageAccountSet(undefined, 1, undefined, () => { return time; }); // Register accounts accounts.registerStorageAccount("account_1"); // log results accounts.logResultToAccount("account_1", true); time++; accounts.logResultToAccount("account_1", true); time++; accounts.logResultToAccount("account_1", true); time++; accounts.logResultToAccount("account_1", false); time++; accounts.logResultToAccount("account_1", false); time++; accounts.logResultToAccount("account_1", false); expect(accounts.getStorageAccount("account_1").getRank()).toBeLessThan(0.5); }); }); });