text
stringlengths
184
4.48M
import 'package:e_commerce_app/utilities/constants.dart'; import 'package:flutter/material.dart'; import 'big_text.dart'; class GeneralButton extends StatelessWidget { const GeneralButton({ Key? key, required this.onPressed, required this.text, this.width=170, this.borderRadius=5, }) : super(key: key); final Function onPressed; final String text; final double width; final double borderRadius; @override Widget build(BuildContext context) { return GestureDetector( onTap: () => onPressed(), child: Center( child: Container( width: width, height: 35, padding: EdgeInsets.all(5), child: Center( child: BigText( text: text, color: Colors.white, fontWeight: FontWeight.w500, size: 14, ) ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(borderRadius), color: kPrimaryColor ), ), ), ); } }
import 'dart:io'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:open_filex/open_filex.dart'; import 'package:path_provider/path_provider.dart'; import '../../../data_layer/network.dart'; import '../../../domain_layer/models.dart'; import '../../../domain_layer/use_cases.dart'; import '../../extensions.dart'; import 'mandate_create_state.dart'; /// Cubit for handling the creation of Debit Mandates class MandateCreateCubit extends Cubit<MandateCreateState> { final LoadInfoRenderedFileUseCase _mandateFileUseCase; /// Creates a new instance of [MandateCreateCubit] MandateCreateCubit({ required LoadInfoRenderedFileUseCase renderedFileUseCase, }) : _mandateFileUseCase = renderedFileUseCase, super(MandateCreateState()); /// TODO: cubit_issue | This seems to be UI only logic. Should not be placed /// on the cubit state. /// /// Set the account that can be charged void setAccount(Account account) { emit( state.copyWith( account: account, ), ); } /// TODO: cubit_issue | This seems to be UI only logic. Should not be placed /// on the cubit state. /// /// set if the user marked the checkbox void setHasAccepted({ required bool accepted, }) { emit( state.copyWith(hasAccepted: accepted), ); } /// Fetches the Mandate pdf file Future<void> loadMandateImage({ required List<MoreInfoField> infoFields, }) async { emit( state.copyWith( busy: true, errorStatus: MandateCreateErrorStatus.none, ), ); try { final mandateFile = await _mandateFileUseCase(infoFields: infoFields); emit( state.copyWith( busy: false, mandatePDFFile: mandateFile, ), ); } on Exception catch (e, st) { logException(e, st); emit( state.copyWith( busy: false, errorMessage: e is NetException ? e.message : null, errorStatus: e is NetException ? MandateCreateErrorStatus.network : MandateCreateErrorStatus.generic, ), ); rethrow; } } /// TODO: cubit_issue | This does not seem to be something that the cubit /// should handle. Looks more like a method that could be converted into a /// mixin for opening files and being used directly by the UI. /// /// Opens the more info pdf Future<void> getMoreInfoPdf( List<int> bytes, String? id, { bool isImage = false, }) async { final appDocDir = await getApplicationDocumentsDirectory(); final appPath = appDocDir.path; final fileFormat = isImage ? "png" : "pdf"; final path = '$appPath/direct_debit_more_info${id != null ? "_$id" : ""}.$fileFormat'; final file = File(path); await file.writeAsBytes(bytes); OpenFilex.open( file.path, uti: isImage ? 'public.jpeg' : 'com.adobe.pdf', type: isImage ? 'image/jpeg' : 'application/pdf', ); } }
import { createContext, ReactNode, useContext, useEffect, useState } from 'react'; import { api } from '../services/api'; interface Medicine { nome: string, efeito: string, id: number, descricao:string } interface MedicinesProviderProps { children: ReactNode; } interface Params { medicineId : number; pacienteId: number; } type MedicineInput = Omit<Medicine, 'id'>; interface MedicinesContextData { medicines: Medicine[], createMedicine: (medicine: MedicineInput) =>Promise<void>; assignMedicine:({medicineId, pacienteId}: Params)=> Promise<void> } const MedicinesContext = createContext<MedicinesContextData>({} as MedicinesContextData); export function MedicinesProvider({ children }: MedicinesProviderProps) { const [medicines, setMedicines] = useState<Medicine[]>([]); useEffect(() => { api.get('/medicines').then((response) => { setMedicines(response.data) }) }, []); async function createMedicine(medicineInput: MedicineInput) { const response = await api.post('medicines', { ...medicineInput }); const {medicine} = response.data; setMedicines([ ...medicines, medicine ]) } async function assignMedicine({medicineId ,pacienteId}:Params){ await api.post('assignMedicine',{ medicine_id: medicineId, pacient_id : pacienteId }).then((response)=>{ console.log(response.data); }); } return ( <MedicinesContext.Provider value={{ medicines, createMedicine,assignMedicine}}> {children} </MedicinesContext.Provider> ) } export function useMedicines(){ const context = useContext(MedicinesContext); return context; }
import { LitElement, css, html } from 'lit'; import { property, customElement } from 'lit/decorators.js'; @customElement('app-menu') export class AppMenu extends LitElement { @property({ type: String }) title = 'Spacefight'; @property() enableBack: boolean = false; static get styles() { return css` #menuToggle { display: block; position: fixed; bottom: 10px; right: 10px; z-index: 1; -webkit-user-select: none; user-select: none; } #menuToggle a { // text-align: right; text-decoration: none; color: #232323; transition: color 0.3s ease; } #menuToggle a:hover { color: tomato; } #menuToggle input { display: block; width: 40px; height: 32px; position: absolute; top: -7px; left: -5px; cursor: pointer; opacity: 0; /* hide this */ z-index: 2; /* and place it over the hamburger */ -webkit-touch-callout: none; } /* * Just a quick hamburger */ #menuToggle span { display: block; width: 33px; height: 4px; margin-bottom: 5px; position: relative; background: #cdcdcd; border-radius: 3px; z-index: 1; transform-origin: 4px 0px; transition: transform 0.5s cubic-bezier(0.77,0.2,0.05,1.0), background 0.5s cubic-bezier(0.77,0.2,0.05,1.0), opacity 0.55s ease; } #menuToggle span:first-child { transform-origin: 0% 0%; } #menuToggle span:nth-last-child(2) { transform-origin: 0% 100%; } /* * Transform all the slices of hamburger * into a crossmark. */ #menuToggle input:checked ~ span { opacity: 1; transform: rotate(45deg) translate(-2px, -1px); background: #232323; } /* * But let's hide the middle one. */ #menuToggle input:checked ~ span:nth-last-child(3) { opacity: 0; transform: rotate(0deg) scale(0.2, 0.2); } /* * Ohyeah and the last one should go the other direction */ #menuToggle input:checked ~ span:nth-last-child(2) { transform: rotate(-45deg) translate(0, -1px); } /* * Make this absolute positioned * at the top left of the screen */ #menu { position: fixed; width: 130px; margin: -100px 0 0 -50px; padding: 10px 20px; background: #ededed; list-style-type: none; -webkit-font-smoothing: antialiased; transform-origin: 0% 0%; transform: translate(100%, 0); transition: transform 0.5s cubic-bezier(0.77,0.2,0.05,1.0); bottom: 0; right: 0; } #menu li { padding: 10px 0; font-size: 22px; } /* * And let's slide it in from the left */ #menuToggle input:checked ~ ul { transform: none; } `; } constructor() { super(); } updated(changedProperties: any) { if (changedProperties.has('enableBack')) { console.log('enableBack', this.enableBack); } } render() { // menu from https://codepen.io/erikterwan/pen/EVzeRP return html` <nav role="navigation"> <div id="menuToggle"> <!-- A fake / hidden checkbox is used as click reciever, so you can use the :checked selector on it. --> <input type="checkbox" /> <!-- Some spans to act as a hamburger. They are acting like a real hamburger, not that McDonalds stuff. --> <span></span> <span></span> <span></span> <ul id="menu"> <a href="/"><li>Home</li></a> <a href="/about"><li>About</li></a> <a href="/game"><li>Play</li></a> </ul> </div> </nav> `; } }
import { AxiosRequestConfig } from 'axios' import Card from 'components/Card' import ReviewForm from 'components/ReviewForm' import ReviewListing from 'components/ReviewListing' import ReviewSynopsis from 'components/ReviewSynopsis' import { useEffect, useState } from 'react' import { useParams } from 'react-router-dom' import { Movie } from 'types/movie' import { Review } from 'types/review' import { hasAnyRoles } from 'util/auth' import { BASE_URL, requestBackend } from 'util/requests' import MovieDetailsLoader from './MovieDetailsLoader' import './styles.css' type urlParams = { movieId: string } const MovieDetails = () => { const { movieId } = useParams<urlParams>() const [movie, setMovie] = useState<Movie>() useEffect(() => { const params: AxiosRequestConfig = { method: 'GET', url: `${BASE_URL}/movies/${movieId}`, withCredentials: true, } requestBackend(params).then((response) => { setMovie(response.data) }) }, []) const [reviews, setReviews] = useState<Review[]>([]) const [isLoading, setIsLoading] = useState(false) useEffect(() => { const config: AxiosRequestConfig = { method: 'GET', url: `/movies/${movieId}/reviews`, withCredentials: true, } setIsLoading(true) requestBackend(config) .then((response) => { setReviews(response.data) }) .finally(() => { setIsLoading(false) }) }, [movieId]) const handleInsertReview = (review: Review) => { const clone = [...reviews] clone.push(review) setReviews(clone) } return ( <div className="container "> {isLoading ? ( <MovieDetailsLoader /> ) : ( <div className="container-details"> <div className="container-rota-details"> <img src={movie?.imgUrl} alt={movie?.title} /> </div> <div className="card-top-container"> <h3>{movie?.title}</h3> <h4>{movie?.year}</h4> <p>{movie?.subTitle}</p> <div className="card-details-container"> <p>{movie?.synopsis}</p> </div> </div> </div> )} <div className="review-form"> {hasAnyRoles(['ROLE_MEMBER']) && ( <ReviewForm movieId={movieId} onInsertReview={handleInsertReview} /> )} </div> {isLoading ? ( <MovieDetailsLoader /> ) : ( <div className="review-listing"> <ReviewListing reviews={reviews} /> </div> )} </div> ) } export default MovieDetails
!> \\file init.f03 module init use HDF5 use fft implicit none contains ! generate the initial form of the wavefunction function init_wav(x,y,z,init_type,gauss_sig) double precision, intent(in) :: x(:), y(:), z(:) integer, intent(in) :: init_type double precision, intent(in) :: gauss_sig complex(C_DOUBLE_COMPLEX), allocatable :: init_wav(:,:,:) ! Local variables integer :: Nx, Ny, Nz integer :: i, j, k Nx = size(x) Ny = size(y) Nz = size(z) allocate(init_wav(Nx,Ny,Nz)) ! define initial wavefunction profile as a Gaussian if (init_type == 1) then write(*,*) "initial input to imaginary time: Gaussian" do k = 1, Nz do j = 1, Ny do i = 1, Nx init_wav(i,j,k) = exp(-(x(i)**2.0/(2.0*gauss_sig**2.0) & + y(j)**2.0/(2.0*gauss_sig**2.0) & + z(k)**2.0/(2.0*gauss_sig**2.0)))**0.5 end do end do end do ! define initial wavefunction profile as a Super-Gaussian elseif (init_type == 2) then write(*,*) "initial input to imaginary time: Super-Gaussian" do k = 1, Nz do j = 1, Ny do i = 1, Nx init_wav(i,j,k) = exp(-(x(i)**2.0/(2.0*gauss_sig**2.0) & + y(j)**2.0/(2.0*gauss_sig**2.0) & + z(k)**2.0/(2.0*gauss_sig**2.0))**3.0)**0.5 end do end do end do end if end function init_wav function readin_wav(x,y,z) double precision, intent(in) :: x(:), y(:), z(:) complex(C_DOUBLE_COMPLEX), allocatable :: readin_wav(:,:,:) ! Local variables type(C_PTR) :: f_ptr double precision, allocatable, target :: psi_imag(:,:,:), psi_real(:,:,:) integer :: Nx, Ny, Nz integer :: errors integer(HID_T) :: file_id, dset_id integer(HSIZE_T), dimension(3) :: dims dims(1) = size(x) dims(2) = size(y) dims(3) = size(z) allocate(psi_imag(dims(1),dims(2),dims(3))) allocate(psi_real(dims(1),dims(2),dims(3))) allocate(readin_wav(dims(1),dims(2),dims(3))) write(*,*) "initial wavefunction read from file" ! open hdf5 API call h5open_f(errors) ! open wavefunction file call h5fopen_f('psi_init.h5', H5F_ACC_RDONLY_F, file_id, errors) ! open imaginary component dataset call h5dopen_f(file_id, 'psi_imag', dset_id, errors) f_ptr = C_LOC(psi_imag(1,1,1)) ! read in imaginary component call h5dread_f(dset_id, H5T_NATIVE_DOUBLE, f_ptr, errors) call h5dclose_f(dset_id, errors) ! open real component dataset call h5dopen_f(file_id, 'psi_real', dset_id, errors) f_ptr = C_LOC(psi_real(1,1,1)) ! read in real component call h5dread_f(dset_id, H5T_NATIVE_DOUBLE, f_ptr, errors) call h5dclose_f(dset_id, errors) call h5fclose_f(file_id, errors) ! close hdf5 API call h5close_f(errors) ! construct wavefunction from real and imaginary components readin_wav = psi_real + cmplx(0.0,1.0)*psi_imag deallocate(psi_imag) deallocate(psi_real) end function readin_wav function readin_chempot() double precision :: readin_chempot ! Local variables integer :: errors integer(HID_T) :: file_id, dset_id integer(HSIZE_T), dimension(1) :: scal_dim=1 write(*,*) "initial chemical potential read from file" ! open hdf5 API call h5open_f(errors) ! open wavefunction file call h5fopen_f('psi_init.h5', H5F_ACC_RDONLY_F, file_id, errors) ! open chemical potential dataset call h5dopen_f(file_id, 'mu', dset_id, errors) ! read in imaginary component call h5dread_f(dset_id, H5T_NATIVE_DOUBLE, readin_chempot, scal_dim, errors) call h5dclose_f(dset_id, errors) call h5fclose_f(file_id, errors) ! close hdf5 API call h5close_f(errors) write(*,*) "using mu:" write(*,*) readin_chempot end function readin_chempot end module init
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Prime Calculator</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <link rel="stylesheet" href="bootstrap.min.css" media="screen"> </head> <body> <div class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <a href="" class="navbar-brand">PrimeLand</a> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse" id="navbar-main"> <ul class="nav navbar-nav"> <li> <a href="#checker">Prime Checker</a> </li> <li> <a href="#lister">Primes Lister</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="#">by HG</a></li> </ul> </div> </div> </div> <div class="container"> <div class="page-header" id="banner"> <div class="row"> <div class="col-lg-8 col-md-7 col-sm-6"> <h1>Primes</h1> <p class="lead">A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.</p> </div> </div> <div class="row"> <p>This generator uses multiple methods to highlight pros/cons of different approaches.</p> <ul> <li><b>Direct</b> - uses brute force method of checking if number is a prime, by going through all of its possible divisors. It's optimised to go through minimal set of iterations and thus is very efficient.</li> <li><b>Set Sieve</b> - sieve which uses bitset. It's fast, but limited to available memory</li> <li><b>Dictionary</b> - version using dictionary for caching. It uses efficient primitive AVLTreeMap from <a href="http://fastutil.di.unimi.it/">FastUtil</a> library. This library adds 17mb to the project, and is not justified here. It's purely to demonstrate an alternative approach.</li> <li><b>Direct Cached</b> - uses optimised version with small cache of first 200 prime numbers.</li> <!--<li></li>--> </ul> </div> </div> <div class="bs-docs-section"> <div class="page-header"> <div class="row"> <div class="col-lg-12"> <h1><a name="checker">Prime Checker</a></h1> </div> </div> </div> <div class="row"> <legend>Check if a number is a prime by one of the methods?</legend> <br><br> <div class="well bs-component"> <form name="primetest" class="form-inline" onsubmit="return false"> Is <input id="checkNumber" type="text" size="19" name="input" maxlength="20" class="form-control" placeholder="Input number"> prime via <select id="checkMethod" class="form-control"> <option>Direct</option> <option>Direct Cached</option> <option>Dictionary</option> <option>Set Sieve</option> </select> method? <button id="btnCheck" class="btn btn-primary">Check!</button> <br><br> <div id="checkOutArea" class="alert alert-dismissible"> <button type="button" class="close" data-dismiss="alert">&times;</button> <strong id="checkOut"></strong> </div> </form> </div> </div> </div> <div class="bs-docs-section"> <div class="page-header"> <div class="row"> <div class="col-lg-12"> <h1><a name="lister">Prime Lister</a></h1> </div> </div> </div> <div class="row"> <legend>Uses one of the given methods to calculate list of primes.</legend> <div class="well bs-component"> <form name="primelist" onsubmit="return false" class="form-inline"> <fieldset> Show first <input type="text" size="5" name="input" maxlength="7" class="form-control" placeholder="Number input" value="100" id="listNumber"> primes via <select id="listMethod" class="form-control"> <option>Direct</option> <option>Direct Cached</option> <option>Dictionary</option> <option>Set Sieve</option> </select> method? <button id="btnList" class="btn btn-primary">Go!</button> <br><br> <div id="listOutArea" class="alert alert-dismissible"> <button type="button" class="close" data-dismiss="alert">&times;</button> <strong id="listOut"></strong> </div> </fieldset> </form> </div> </div> </div> <div class="bs-docs-section"> <div class="page-header"> <div class="row"> <div class="col-lg-12"> <h1><a name="lister">Some speed observations</a></h1> </div> </div> </div> <div class="row"> <legend>Speed benchmarks in ms.</legend> <table class="table table-bordered"> <tr><td>Method / Primes count</td><td>10,000</td><td>100,000</td><td>1,000,000</td></tr> <tr><td>Direct</td><td>70</td><td>423</td><td>10920</td></tr> <tr><td>Set Sieve*</td><td>1</td><td>10</td><td>238</td></tr> <tr><td>Dictionary</td><td>9642</td><td>-</td><td>-</td></tr> <tr><td>Direct Cached</td><td>84</td><td>362</td><td>8219</td></tr> <!--<tr><td></td><td></td><td></td><td></td></tr>--> </table> <p>* Set Sieve method takes around 4s to initialise and afterwards it is just using precalculated sieve.</p> </div> </div> <br> <br> <footer> <div class="row"> <div class="col-lg-12"> <p>Made by HG</p> <p>See Code at <a href="https://github.com/husayt/hgprimes">GitHub</a>.</p> </div> </div> </footer> </div> </body> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script src="bootstrap.min.js"></script> <script> $("#checkNumber").keyup(function (event) { $("#checkOutArea").hide(); }); $("#btnCheck").on("click", function (event) { $("#btnCheck").text("Checking..."); $("#checkOutArea").hide(); var number = $("#checkNumber").val(), method = getMethodName($("#checkMethod").val()), url = "/rst/isprime?number=" + number + "&method=" + method; $.ajax({ url: url, success: function (result) { $("#checkOutArea").show(); $("#checkOutArea").removeClass("alert-danger"); $("#checkOutArea").addClass("alert-success"); $("#checkOut").text(result ? "Yes" : "No"); $("#btnCheck").text("Check!"); }, error: function (result) { $("#checkOutArea").show(); $("#checkOutArea").removeClass("alert-success"); $("#checkOutArea").addClass("alert-danger"); $("#checkOut").text("Error. "); $("#btnCheck").text("Check!"); } }); }); //list primes $("#listNumber").keyup(function (event) { $("#listOutArea").hide(); }); $("#btnList").on("click", function (event) { $("#btnList").text("Listing..."); $("#listOutArea").hide(); var number = $("#listNumber").val(), method = getMethodName($("#listMethod").val()), url = "/rst/listprimes?count=" + number + "&method=" + method; $.ajax({ url: url, success: function (result) { $("#listOutArea").show(); if (!result.error) { $("#listOutArea").removeClass("alert-danger"); $("#listOutArea").addClass("alert-success"); $("#listOut").html(result.numbers.join(", ") + ".<br><br> Finished in " + result.ms + "ms"); } else { $("#listOutArea").addClass("alert-danger"); $("#listOutArea").removeClass("alert-success"); $("#listOut").text("Error: " + result.error); } $("#btnList").text("List!"); }, error: function (result) { $("#listOutArea").show(); $("#listOutArea").addClass("alert-danger"); $("#listOut").text("Error. "); $("#btnList").text("List!"); } }); }); //helper var getMethodName = function (name) { switch (name) { case "Dictionary": return "dict"; break; case "Set Sieve": return "set"; break; case "Direct Cached": return "directCached"; break; case "Direct": default: return "direct"; } } </script> </html>
import * as React from 'react' import { PropsWithChildren, useEffect, useState } from 'react' import classNames from 'classnames/bind' const cx = classNames.bind(styles) import styles from './Switch.module.scss' export interface SwitchProps { checked?: boolean onChange(e: React.ChangeEvent<HTMLInputElement>): void id?: string } export const Switch = ({ checked = true, id, onChange }: PropsWithChildren<SwitchProps>) => { const [isChecked, setIsChecked] = useState(checked) useEffect(() => { setIsChecked(checked) }, [checked]) const getSliderClasses = cx({ [styles.slider]: true, [styles.sliderChecked]: !isChecked }) return ( <label className={styles.label}> <input type="checkbox" checked={isChecked} onChange={(e) => { setIsChecked(!isChecked) onChange(e) }} id={id} /> <span className={getSliderClasses} /> </label> ) }
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Copyright (C) 2007-2011 Catalyst IT (http://www.catalyst.net.nz) * Copyright (C) 2011-2013 Totara LMS (http://www.totaralms.com) * Copyright (C) 2014 onwards Catalyst IT (http://www.catalyst-eu.net) * * @package mod * @subpackage ilt * @copyright 2014 onwards Catalyst IT <http://www.catalyst-eu.net> * @author Stacey Walker <stacey@catalyst-eu.net> * @author Alastair Munro <alastair.munro@totaralms.com> * @author Aaron Barnes <aaron.barnes@totaralms.com> * @author Francois Marier <francois@catalyst.net.nz> */ defined('MOODLE_INTERNAL') || die(); require_once($CFG->dirroot.'/course/moodleform_mod.php'); require_once($CFG->dirroot.'/mod/ilt/lib.php'); class mod_ilt_mod_form extends moodleform_mod { public function definition() { global $CFG; $mform =& $this->_form; // General. $mform->addElement('header', 'general', get_string('general', 'form')); $mform->addElement('text', 'name', get_string('name'), array('size' => '64')); if (!empty($CFG->formatstringstriptags)) { $mform->setType('name', PARAM_TEXT); } else { $mform->setType('name', PARAM_CLEANHTML); } $mform->addRule('name', null, 'required', null, 'client'); $this->standard_intro_elements(); $mform->addElement('text', 'thirdparty', get_string('thirdpartyemailaddress', 'ilt'), array('size' => '64')); $mform->setType('thirdparty', PARAM_NOTAGS); $mform->addHelpButton('thirdparty', 'thirdpartyemailaddress', 'ilt'); $mform->addElement('checkbox', 'thirdpartywaitlist', get_string('thirdpartywaitlist', 'ilt')); $mform->addHelpButton('thirdpartywaitlist', 'thirdpartywaitlist', 'ilt'); $display = array(); for ($i = 0; $i <= 18; $i += 2) { $display[$i] = $i; } $mform->addElement('select', 'display', get_string('sessionsoncoursepage', 'ilt'), $display); $mform->setDefault('display', 6); $mform->addHelpButton('display', 'sessionsoncoursepage', 'ilt'); $mform->addElement('checkbox', 'approvalreqd', get_string('approvalreqd', 'ilt')); $mform->addHelpButton('approvalreqd', 'approvalreqd', 'ilt'); if (has_capability('mod/ilt:configurecancellation', $this->context)) { $mform->addElement('advcheckbox', 'allowcancellationsdefault', get_string('allowcancellationsdefault', 'ilt')); $mform->setDefault('allowcancellationsdefault', 1); $mform->addHelpButton('allowcancellationsdefault', 'allowcancellationsdefault', 'ilt'); } $mform->addElement('header', 'calendaroptions', get_string('calendaroptions', 'ilt')); $calendaroptions = array( ILT_CAL_NONE => get_string('none'), ILT_CAL_COURSE => get_string('course'), ILT_CAL_SITE => get_string('site') ); $mform->addElement('select', 'showoncalendar', get_string('showoncalendar', 'ilt'), $calendaroptions); $mform->setDefault('showoncalendar', ILT_CAL_COURSE); $mform->addHelpButton('showoncalendar', 'showoncalendar', 'ilt'); $mform->addElement('advcheckbox', 'usercalentry', get_string('usercalentry', 'ilt')); $mform->setDefault('usercalentry', true); $mform->addHelpButton('usercalentry', 'usercalentry', 'ilt'); $mform->addElement('text', 'shortname', get_string('shortname'), array('size' => 32, 'maxlength' => 32)); $mform->setType('shortname', PARAM_TEXT); $mform->addHelpButton('shortname', 'shortname', 'ilt'); $mform->addRule('shortname', null, 'maxlength', 32); // Request message. $mform->addElement('header', 'request', get_string('requestmessage', 'ilt')); $mform->addHelpButton('request', 'requestmessage', 'ilt'); $mform->addElement('text', 'requestsubject', get_string('email:subject', 'ilt'), array('size' => '55')); $mform->setType('requestsubject', PARAM_TEXT); $mform->setDefault('requestsubject', get_string('setting:defaultrequestsubjectdefault', 'ilt')); $mform->disabledIf('requestsubject', 'approvalreqd'); $mform->addElement('textarea', 'requestmessage', get_string('email:message', 'ilt'), 'wrap="virtual" rows="15" cols="70"'); $mform->setDefault('requestmessage', get_string('setting:defaultrequestmessagedefault', 'ilt')); $mform->disabledIf('requestmessage', 'approvalreqd'); $mform->addElement('textarea', 'requestinstrmngr', get_string('email:instrmngr', 'ilt'), 'wrap="virtual" rows="10" cols="70"'); $mform->setDefault('requestinstrmngr', get_string('setting:defaultrequestinstrmngrdefault', 'ilt')); $mform->disabledIf('requestinstrmngr', 'approvalreqd'); // Confirmation message. $mform->addElement('header', 'confirmation', get_string('confirmationmessage', 'ilt')); $mform->addHelpButton('confirmation', 'confirmationmessage', 'ilt'); $mform->addElement('text', 'confirmationsubject', get_string('email:subject', 'ilt'), array('size' => '55')); $mform->setType('confirmationsubject', PARAM_TEXT); $mform->setDefault('confirmationsubject', get_string('setting:defaultconfirmationsubjectdefault', 'ilt')); $mform->addElement('textarea', 'confirmationmessage', get_string('email:message', 'ilt'), 'wrap="virtual" rows="15" cols="70"'); $mform->setDefault('confirmationmessage', get_string('setting:defaultconfirmationmessagedefault', 'ilt')); $mform->addElement('checkbox', 'emailmanagerconfirmation', get_string('emailmanager', 'ilt')); $mform->addHelpButton('emailmanagerconfirmation', 'emailmanagerconfirmation', 'ilt'); $mform->addElement('textarea', 'confirmationinstrmngr', get_string('email:instrmngr', 'ilt'), 'wrap="virtual" rows="4" cols="70"'); $mform->addHelpButton('confirmationinstrmngr', 'confirmationinstrmngr', 'ilt'); $mform->disabledIf('confirmationinstrmngr', 'emailmanagerconfirmation'); $mform->setDefault('confirmationinstrmngr', get_string('setting:defaultconfirmationinstrmngrdefault', 'ilt')); // Reminder message. $mform->addElement('header', 'reminder', get_string('remindermessage', 'ilt')); $mform->addHelpButton('reminder', 'remindermessage', 'ilt'); $mform->addElement('text', 'remindersubject', get_string('email:subject', 'ilt'), array('size' => '55')); $mform->setType('remindersubject', PARAM_TEXT); $mform->setDefault('remindersubject', get_string('setting:defaultremindersubjectdefault', 'ilt')); $mform->addElement('textarea', 'remindermessage', get_string('email:message', 'ilt'), 'wrap="virtual" rows="15" cols="70"'); $mform->setDefault('remindermessage', get_string('setting:defaultremindermessagedefault', 'ilt')); $mform->addElement('checkbox', 'emailmanagerreminder', get_string('emailmanager', 'ilt')); $mform->addHelpButton('emailmanagerreminder', 'emailmanagerreminder', 'ilt'); $mform->addElement('textarea', 'reminderinstrmngr', get_string('email:instrmngr', 'ilt'), 'wrap="virtual" rows="4" cols="70"'); $mform->addHelpButton('reminderinstrmngr', 'reminderinstrmngr', 'ilt'); $mform->disabledIf('reminderinstrmngr', 'emailmanagerreminder'); $mform->setDefault('reminderinstrmngr', get_string('setting:defaultreminderinstrmngrdefault', 'ilt')); $reminderperiod = array(); for ($i = 1; $i <= 20; $i += 1) { $reminderperiod[$i] = $i; } $mform->addElement('select', 'reminderperiod', get_string('reminderperiod', 'ilt'), $reminderperiod); $mform->setDefault('reminderperiod', 2); $mform->addHelpButton('reminderperiod', 'reminderperiod', 'ilt'); // Waitlisted message. $mform->addElement('header', 'waitlisted', get_string('waitlistedmessage', 'ilt')); $mform->addHelpButton('waitlisted', 'waitlistedmessage', 'ilt'); $mform->addElement('text', 'waitlistedsubject', get_string('email:subject', 'ilt'), array('size' => '55')); $mform->setType('waitlistedsubject', PARAM_TEXT); $mform->setDefault('waitlistedsubject', get_string('setting:defaultwaitlistedsubjectdefault', 'ilt')); $mform->addElement('textarea', 'waitlistedmessage', get_string('email:message', 'ilt'), 'wrap="virtual" rows="15" cols="70"'); $mform->setDefault('waitlistedmessage', get_string('setting:defaultwaitlistedmessagedefault', 'ilt')); // Cancellation message. $mform->addElement('header', 'cancellation', get_string('cancellationmessage', 'ilt')); $mform->addHelpButton('cancellation', 'cancellationmessage', 'ilt'); $mform->addElement('text', 'cancellationsubject', get_string('email:subject', 'ilt'), array('size' => '55')); $mform->setType('cancellationsubject', PARAM_TEXT); $mform->setDefault('cancellationsubject', get_string('setting:defaultcancellationsubjectdefault', 'ilt')); $mform->addElement('textarea', 'cancellationmessage', get_string('email:message', 'ilt'), 'wrap="virtual" rows="15" cols="70"'); $mform->setDefault('cancellationmessage', get_string('setting:defaultcancellationmessagedefault', 'ilt')); $mform->addElement('checkbox', 'emailmanagercancellation', get_string('emailmanager', 'ilt')); $mform->addHelpButton('emailmanagercancellation', 'emailmanagercancellation', 'ilt'); $mform->addElement('textarea', 'cancellationinstrmngr', get_string('email:instrmngr', 'ilt'), 'wrap="virtual" rows="4" cols="70"'); $mform->addHelpButton('cancellationinstrmngr', 'cancellationinstrmngr', 'ilt'); $mform->disabledIf('cancellationinstrmngr', 'emailmanagercancellation'); $mform->setDefault('cancellationinstrmngr', get_string('setting:defaultcancellationinstrmngrdefault', 'ilt')); $features = new stdClass; $features->groups = false; $features->groupings = false; $features->groupmembersonly = false; $features->outcomes = false; $features->gradecat = false; $features->idnumber = true; $this->standard_coursemodule_elements($features); $this->add_action_buttons(); } public function data_preprocessing(&$defaultvalues) { // Fix manager emails. if (empty($defaultvalues['confirmationinstrmngr'])) { $defaultvalues['confirmationinstrmngr'] = null; } else { $defaultvalues['emailmanagerconfirmation'] = 1; } if (empty($defaultvalues['reminderinstrmngr'])) { $defaultvalues['reminderinstrmngr'] = null; } else { $defaultvalues['emailmanagerreminder'] = 1; } if (empty($defaultvalues['cancellationinstrmngr'])) { $defaultvalues['cancellationinstrmngr'] = null; } else { $defaultvalues['emailmanagercancellation'] = 1; } } }
package my.gov.kpn.quiz.core.model.impl; import my.gov.kpn.quiz.core.model.*; import javax.persistence.*; import java.util.Date; /** * @author rafizan.baharum * @since 7/10/13 */ @Table(name = "QA_STDN") @Entity(name = "QaStudent") public class QaStudentImpl extends QaActorImpl implements QaStudent { @ManyToOne(targetEntity = QaInstructorImpl.class) @JoinColumn(name = "INSTRUCTOR_ID") private QaInstructor instructor; @Column(name = "DOB") private Date dob; @Column(name = "SCHOOL_NAME") private String schoolName; @Column(name = "SCHOOL_TYPE") private QaSchoolType schoolType; @Column(name = "GENDER_TYPE") private QaGenderType genderType; @Column(name = "RACE_TYPE") private QaRaceType raceType; @OneToOne(targetEntity = QaStateImpl.class) @JoinColumn(name = "STATE_ID") private QaState state; @Column(name = "DISTRICT_NAME") private String districtName; public QaStudentImpl() { setActorType(QaActorType.STUDENT); } public QaInstructor getInstructor() { return instructor; } public void setInstructor(QaInstructor instructor) { this.instructor = instructor; } @Override public Date getDob() { return dob; } @Override public void setDob(Date dob) { this.dob = dob; } public String getDistrictName() { return districtName; } public void setDistrictName(String districtName) { this.districtName = districtName; } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } public QaGenderType getGenderType() { return genderType; } public void setGenderType(QaGenderType genderType) { this.genderType = genderType; } public QaRaceType getRaceType() { return raceType; } public void setRaceType(QaRaceType raceType) { this.raceType = raceType; } public QaSchoolType getSchoolType() { return schoolType; } public void setSchoolType(QaSchoolType schoolType) { this.schoolType = schoolType; } public QaState getState() { return state; } public void setState(QaState state) { this.state = state; } }
-- Bongo x Bongo, by Mr Speaker. -- https://www.mrspeaker.net --[[ Welcome to Bongo x Bongo. This script makes modifications to the game Bongo, written by John Hutchinson for JetSoft in 1983. * General cheatin' and tweaks for practising * OGNOB mode: new challenge - try to complete the game in reverse! * New main character and colour themes * Random stuff I found unused in the game code * ... and much more! SETTINGS Changing the variables below to enable features. Most settings are true/false options for enabling or disabling. For example, to turn off the "infinite lives" feature: infinite_lives = false There are tonnes of things to set - some are really useful if you're trying to improve your Bongo runs, some are just for fun, and a bunch are things I was testing when I found it buried in unused code in the Bongo ROM dump. RUNNING As a prerequisite, you should already be able to load and play Bongo on MAME. To run this script, you need to supply it as an extra argument when running MAME from the command line: `mame bongo -autoboot_script ./bongo.lua` Where the path `./bongo.lua` points to the file you are currently reading. (If you don't know how to run MAME from command line, you'll have to do a bit of googlin'. Instead of clicking on mame.exe you need to run that from a command prompt as described here: https://easyemu.mameworld.info/mameguide/getting_started/running_mame.html) --]] start_screen = 1 -- [1 - 27]. Screen to start the game. 27 is the dino screen. loop_screens = {}--{13,14,18,21,25,27} -- Loop if you want to practise levels, eg: -- {}: no looping, normal Bongo sequence -- {14}: repeat screen 14 over and over -- {14, 18, 26}: repeat a sequence of screens round = 2 -- starting round (1: initial speed, 2+: faster) -- 1: default Bongo speed for dinosaur and enemies -- 2: faster movement for player and enemies, and dinosaur starts earlier -- 3+: each round after 2, the player and enemeies are the same speed, -- but the dinosaur starts earlier and earlier and earlier... infinite_lives = true fast_death = true -- restart fast after death fast_wipe = true -- fast transition to next screen disable_dino = false -- no pesky dino (oh, but also now you can't catch 'im) disable_round_speed_up = true -- don't get faster after catching dino disable_bonus_skip = false -- don't skip screen on 6xbonus disable_cutscene = true -- don't show the awesome cutscene reset_score = false -- reset score to 0 on death and new screen collision_indicator = false -- show where ground and pickup collisions occur -- Bongo is bad at picking things up because of his bongoitis and bad knees. -- This setting shows you exactly where collisions will occur. As you walk -- the ground will "cycle" so you can see which tile the game thinks you are on. -- *Middle line* shows exactly where the tile collision happenss. -- *Back line* shows you where pickup collision will happen. -- So you need to get the back line over a pickup before you actally pick anything up. allow_skip = true -- use player1/player to navigate screens while playing -- P1: skip forward one screen -- P2: skip back one screen -- P1 + P2: reset back to attract screen theme = 0 -- color theme (0-7). 0 = default, 7 = best one technicolor = false -- randomize theme every death head_style = 0 -- 0 = normal, 1 = dance, 2 = dino, 3 = bongo, 4 = shy guy ognob_mode = true -- open-world Bongo. Can go out left or right. --[[ ======= Official OGNOB MODE Rules ======= You've caught the dinosaur and danced with Bongo & friends, but your knees can handle more? Then exit stage left... and try your luck in the wild world of Ognob. Ognob competitive settings: * ognob_mode = true * start_screen = 1 * loop_screens = {} * round = 2 * infinite_lives = false (hardcore), true (easy) * disable_dino = true (good luck otherwise...) * disable_bonus_skip = true * allow_skip = false Start on screen 1, and make your way left. Your not being chased by a dinosaur, yet many challenges lay ahead of you. Make it all the way back to screen 1 to lay claim to the title, The Honourable Earl of Ognob. --]] -- Removed features I found in the code, and tweaks/tests show_timers = false -- speed run timers! Don't know why they removed them prevent_cloud_jump = false -- makes jumping from underneath really crap! alt_bongo_place = false -- maybe supposed to put lil guy on the ground for highwire levels? one_px_moves = false -- test how it feels moving 1px per frame, not 3px per 3 frames. -- I think this is the reason Bongo is so hard. This is responsible for Bongo 50/50s. -- Every three frames the player will move three pixels. The ground collision detection has -- *four* frames of leeway: so making a jump from the edge of a S_S level has a very -- small margin to be out - and the chunky three-pixel movement makes it even harder to -- get right. This setting shows kind of what a smooth movement would be like fix_jump_bug = false -- don't die when holding jump on new screen -- Theres a nasty bug that sometimes comes up in game play: if you jump off a platform -- into the next screen, then if you hold jump while the next screen starts - sometimes -- the player does a weird stunted tripple-jump and just... dies. This fixes it. fix_all_the_lil_bugs = true -- * fix call to draw inner border on YOUR BEING CHASED screen -- * add other missing inner border in empty attract screen -- * fixed the pointy stair-down platform -- * don't jump to wrong byte in hiscore timer code (0x3108). -- (no visual changes, but hey.) -- * in BONGO attract screen, jumping up and down stairs the player's head -- and legs are switched for one frame of animation (really!). Fix it! -- * subjective typography fix: align 1000 bonus better -- * add the cool spiral transition to attract mode. Code was just sitting there. -- NOTE: to get some bytes for features, I broke P2 handling I think. -- Probably One-player only now. -- Bongo world map -- 01: n_n n_n nTn n_n / W -- 07: \ n_n nTn / W -- 12: \ n_n nTn n_n S -- 17: \ n_n S \ S_S -- 22: W \ S_S -- 25: W \ S -- Warning traveller ... -- ... You can look at the code, -- ... but you can not unlook at the code -- Mr Speaker --------------- General helpers ---------------- function dump(o) if type(o) == 'table' then local s = '{ ' for k,v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '['..k..'] = ' .. dump(v) .. ',' end return s .. '} ' else return tostring(o) end end function flatten(list) if type(list) ~= "table" then return { list } end local flat = {} for _, el in ipairs(list) do for _, val in ipairs(flatten(el)) do flat[#flat + 1] = val end end return flat end function print_pairs(o) for tag, device in pairs(o) do print(tag) end end function yn(v) if v == true then return "Y" end return "N" end local evs = { game_start = {}, game_over = {}, screen_change = {}, died = {} } function add_ev(name, func) local ev = evs[name] ev[#ev+1]=func end function fire_ev(name, ...) for _, f in ipairs(evs[name]) do f(...) end end ------------------- MAME machine ----------------------- local debug_mame = true cpu = manager.machine.devices[":maincpu"] cpudebug = cpu.debug mem = cpu.spaces["program"] io = cpu.spaces["io"] gfx1 = manager.machine.memory.regions[":gfx1"] if debug_mame == true then print("=== bongo trainer dbg ===") print_pairs(manager.machine.devices) print("gfx size: "..dump(gfx1.size)) print("io:"..dump(io.map.entries)) --print_pairs(cpu.state) -- prints all cpu flags, regs -- cpudebug:wpset(mem, "rw", 0xc080, 1, "1","{ printf \"Read @ %08X\n\",wpaddr ; g }") -- cpudebug:wpset(mem, "rw", 0x10d4bc, 1, 'printf "Read @ %08X\n",wpaddr ; g') print("=== end dbg ===") end ------------------- MAME Helpers --------------------- function poke(addr, bytes) if type(bytes)=="number" then bytes = {bytes} end bytes = flatten(bytes) -- you should be scared by now... for i = 1, #bytes do mem:write_u8(addr + (i - 1), bytes[i]) end end function poke_rom(addr, bytes) if type(bytes) == "number" then bytes = {bytes} end bytes = flatten(bytes) for i = 1, #bytes do mem:write_direct_u8(addr + (i - 1), bytes[i]) end end function peek(addr) return mem:read_u8(addr) end function peek_rom(addr) return mem:read_direct_u8(addr) end function poke_gfx(color, addr, byte) if color & 1 == 1 then gfx1:write_u8(addr, byte) end if color & 2 == 2 then gfx1:write_u8(addr + 0x1000, byte) end end function get_pc() return cpu.state["PC"].value end function set_pc(addr) cpu.state["PC"].value = addr end function set_sp(addr) cpu.state["SP"].value = addr end -- return an array with hi/lo bytes of a 16bit value function x(v) return { v & 0xff, v >> 8 } end function is_on_game_screen() return peek(0x93a9) == 0xFE -- platform tile in top left end ----------------- Scratch pad ------------------- -- poke_rom(0x069D, 0x20); -- autojump -- try colorizing player --poke_rom(0x8a2,8) --poke_rom(0x1811,8) --nope. poke_rom(0x149b,{0x3d,col,0x32,0x42,0x81,0x32,0x46,0x81,0xc9} -- length, velocity, volume, transpose poke_rom(0x1c42, 0xf); --poke_rom(0x4c46, 1); --poke_rom(0x4c3a, 0x3); --poke_rom(0x50b0, {0x2,0x2,0xf,0x0,0x1,0x2,0x1,0x2}); --poke_rom(0x4b0c, {0x15,0x01,0x17,0x01,0x19,0x01,0x1A,0x02,0x1A,0x02,0x18,0x02,0x18,0x02,0x17,0x02}) --poke_rom(0x4b40,{0x3}) ------------------ z/80 opcodes ----------------- NOP = 0x00 JR = 0x18 JR_NZ = 0x20 LD_HL = 0x21 INC_HL = 0x23 JR_Z = 0x28 LD_MEM_A = 0x32 LD_HLP = 0x36 SCF = 0x37 JR_C = 0x38 LD_A_MEM = 0x3a INC_A = 0x3c DEC_A = 0x3d LD_A = 0x3e CCF = 0x3f LD_B_A = 0x47 LD_HL_A = 0x77 LD_A_B = 0x78 LD_A_L = 0x7d LD_A_HL = 0x7e AND_A = 0xA7 RET_NZ = 0xC0 JP = 0xC3 ADD_A = 0xC6 RET_Z = 0xC8 RET = 0xC9 CALL = 0xCD SUB = 0xD6 RET_C = 0xD8 XOR_A = 0xAF AND = 0xE6 OR = 0xF6 CP = 0xFE --- RAM locations --- SCREEN_NUM = 0x8029 PLAYER_LEFT_Y = 0x8077 OGNOB_TRIGGER = 0x8078 --- Constants ----- TILE_BLANK = 0x10 --------------------------------------------------------- -- change color palette -- (seems to also mess up a couple of tiles under P2 on load?) function set_theme(col) -- patches RESET_XOFF_AND_COLS_AND_SPRITES -- change screen colors (resets xoffs and cols seperately) -- by adding an extra: `ld (hl), $col, inc hl` for the color poke_rom(0x1496, { LD_HLP, col, INC_HL, LD_A_L, CP, 0x80, JR_NZ, 0xF5, RET }) -- the routine above was duplicated, so just call instead. poke_rom(0x19d8, { CALL, x(0x1490), -- RESET_XOFF_AND_COLS_AND_SPRITES 0,0,0,0,0,0,0,0 }) -- bottom row color poke_rom(0x1047, col) poke_rom(0x179B, col) poke_rom(0x179B, col) end function do_reset_score() poke(0x8014, {0, 0, 0}) end function do_reset_time() poke(0x8007, {0, 0}) end function do_disable_bonus_skip() local GOT_A_BONUS = 0x29c0 poke_rom(GOT_A_BONUS, { JP, x(0x29f5) }) -- jump to end of sub poke_rom(0x29FC, { NOP, NOP, NOP }) -- but don't skip screen end ----------- bug fixes ------------- if fix_all_the_lil_bugs == true then -- bugfix: fix call to draw inner border on YOUR BEING CHASED screen poke_rom(0x56da, 0x5c) -- (was typo'd as 0x4c) -- bugfix: the pointy stair-down platform poke_rom(0x1f01, 0xfc) -- subjective typography fix: align 1000 bonus better poke_rom(0x162d, 0x0f) -- bugfix: don't jump to wrong byte in hiscore something. -- no visual changes, but hey. poke_rom(0x3120, 0x17) -- bugfix: in BONGO attract screen, jumping up stairs the player's -- head and legs are switched for one frame of animation. Fix it! poke_rom(0x5390, { 0x93, 0x94 }) -- on the way up poke_rom(0x5418, { 0x13, 0x14 }) -- on the way down -- subjective bugfix: add inner border to empty attract screen poke_rom(0x48C7, { CALL, x(0x56D0), -- call DRAW_BUGGY_BORDER CALL, x(0x5aA8), -- call original FLASH_BORDER RET }) -- add the cool spiral transition to attract mode -- (if not ognob, because I need the bytes for that) if ognob_mode == false then poke_rom(0x038b, { CALL, x(0x2550) }) -- cool transition! end end -- what to do about Bongo Tree. -- feels wrong to "fix" it. -- poke_rom(0x19b7, {0,0,0, 0,0,0}) ------------- settings ------------- if infinite_lives == true then poke_rom(0x26c, { NOP, NOP }) -- act like DIP switch on end if fast_death == true then -- return early from DO_DEATH_SEQUENCE poke_rom(0x0CCB, { CALL, x(0x0ca0), -- delay 8 vblanks to delay a little CALL, x(0x0ca0), -- delay 8 vblanks (still pretty short) RET, NOP, NOP -- return after dino reset }); end if fast_wipe == true then -- skip parts of $DURING_TRANSITION_NEXT poke_rom(0x1358, { JR, 0x1e, NOP }) -- jumps to $_RESET_FOR_NEXT_LEVEL -- speeds up transition even more: skips $CLEAR_SCR_TO_BLANKS ... poke_rom(0x1378, { CALL, x(0x1490) }) -- ...and just does RESET_XOFF_AND_COLS_AND_SPRITES -- don't do bottom "level indicator" animation. poke_rom(0x3F42, { NOP, NOP, NOP }) -- saves 2 vblanks-per-screen-number end if disable_dino == true then poke_rom(0x22FE, RET); -- ret from timer start check end if disable_round_speed_up == true then poke_rom(0x4EE3, RET); -- return early end if disable_cutscene == true then poke_rom(0x3d48, { XOR_A, LD_MEM_A, x(0x802d), -- reset DINO_COUNTER JP, x(0x3D88) -- _CUTSCENE_DONE }); end if disable_bonus_skip == true then do_disable_bonus_skip() end -- not doing by default because it changes how the game plays if fix_jump_bug == true then poke_rom(0x14dd, { XOR_A, -- reset falling_timer on screen reset LD_MEM_A, x(0x8011), -- FALLING_TIMER RET, LD_A_MEM, x(0x0815), -- Existing: used to start at $14e0, AND, 0x03, -- now starts $14e2 RET_NZ, CALL, x(0x3a50), -- ENEMY_1_RESET CALL, x(0x3a88), -- ENEMY_2_RESET CALL, x(0x3ac0), -- ENEMY_3_RESET RET }) poke_rom(0x3b6c, 0xe2) -- bump call addr to $14e2 end if alt_bongo_place == true then --Bongo on ground for high-wire levels (I think) poke_rom(0x0d40, NOP); -- nop out ret end if show_timers == true then --enable's hidden speed-run timers! poke_rom(0x1410, NOP); -- nop out ret end if prevent_cloud_jump == true then -- PREVENT_CLOUD_JUMP_REDACTED poke_rom(0x1290, NOP); -- nop out ret end if theme ~= 0 then set_theme(theme) end if one_px_moves == true then poke_rom(0x068D, NOP) -- run every frame, not every 3 poke_rom(0x0632, { NOP,NOP }) -- nop 2x inc poke_rom(0x0672, { NOP,NOP }) -- nop 2x dec end if head_style > 0 then local flip_x = function(v) return v + 0x80 end local fr = ({0x3e, 0x2c, 0x05, 0x17})[head_style] local fl = ({flip_x(0x3e), flip_x(0x2c), 0x07, flip_x(0x17)})[head_style] local jump_fr = ({0x3a, 0x2c + 2, 0x05, 0x19})[head_style] poke_rom(0x063A, { LD_A, fr, LD_MEM_A, x(0x8141), RET }) -- player_move_right poke_rom(0x067a, { LD_A, fl, LD_MEM_A, x(0x8141), RET }) -- player_move_left poke_rom(0x1819, { LD_A, fr, LD_MEM_A, x(0x8141), RET }) -- reset_player poke_rom(0x07d5, fr) -- trigger_jump_left poke_rom(0x07b5, fl) -- trigger_jump_right poke_rom(0x08d5, jump_fr) -- trigger_jump_straight_up poke_rom(0x09de, { NOP, NOP, NOP }) -- check_if_landed reset poke_rom(0x06FA, { NOP, NOP, NOP }) -- player_physics frame set end if collision_indicator == true then -- draw in empty "solid" tile graphics (otherwise it draws holes) for i = 0, 7 do poke_gfx(2, 0xf9 * 0x8 + i, 0x7f) poke_gfx(1, 0xfb * 0x8 + i, 0x7f) poke_gfx(2, 0xff * 0x8 + i, 0x7f) end -- draw a "collision pole" in player graphics local feet_frames = {0x135, 0x13d, 0x145, 0x14d, 0x155, 0x161} for i, v in pairs(feet_frames) do -- middle pole poke_gfx(1, v * 0x8 + 7, 0x55) poke_gfx(2, v * 0x8 + 7, 0xAA) -- blank out columns next poke_gfx(3, v * 0x8 + 5, 0x00) poke_gfx(3, v * 0x8 + 6, 0x00) poke_gfx(3, v * 0x8 + 8 + 8, 0x00) poke_gfx(3, v * 0x8 + 8 + 8 + 1, 0x00) -- fwd/back markers --poke_gfx(2, v * 0x8, 0x3f) poke_gfx(1, v * 0x8 + 8 + 8 + 3, 0x55) poke_gfx(2, v * 0x8 + 8 + 8 + 3, 0xAA) poke_gfx(3, v * 0x8 + 8 + 8 + 2, 0x00) poke_gfx(3, v * 0x8 + 8 + 8 + 4, 0x00) end --- rotate through tiles as player walks poke_rom(0x09AD, { JR_Z, 0x7, -- jump to SOLID -- WALKABLE LD_A_HL, INC_A, AND, 0xef, NOP, --LD_HL_A, -- don't print empties! XOR_A, -- 0 = walkable tile RET, -- SOLID: LD_A_HL, INC_A, OR, 0xFC, LD_HL_A, LD_A, 0x1, -- 1 = solid tile RET }) end ------------- RAM hacks ------------- run_started = false loop_len = #loop_screens loop_idx = 0 LIVES = 0x8032 cur_lives = -1 -- Game doesn't update LIVES on final death, so can't be hooked. -- This patch sets LIVES to 0xff so it fires, then in the tap -- can check this (and return 0 to set it back to 0) poke_rom(0x0410, { CALL, x(0x0426) }) -- jump down to some free bytes poke_rom(0x0426, { LD_A, 0xff, -- set lives to 0xff marker LD_MEM_A, x(LIVES), LD_HL, x(0x16e8), -- replace original code form 0x410 RET }) tap1 = mem:install_write_tap(LIVES, LIVES, "writes", function(offset, lives) -- clear score on death if reset_score == true then do_reset_score() end if technicolor == true then set_theme(math.random(16)) end -- Player deaths if run_started then -- deal with init or bonus lives (plus init-write weirdness) if cur_lives == -1 or lives > cur_lives then cur_lives = lives end local game_over = false if lives == 0xff then -- my game-over marker lives = -1 game_over = true end if game_over or lives < cur_lives then fire_ev("died", lives + 1) cur_lives = lives end if game_over then fire_ev("game_over") run_started = false return 0 end end end) local last_screen = 1 add_ev("game_start", function() last_screen = 1 end) tap2 = mem:install_write_tap(SCREEN_NUM, SCREEN_NUM, "writes", function(offset, data) if data == 0 then return end -- loop screens if data == 1 and not run_started then -- player has started run_started = true fire_ev("game_start") -- go to round 2 if requested local SPEED_DELAY_P1 = 0x805b if round > 1 and peek(SPEED_DELAY_P1) == 0x1f then local speeds = { 0x1f, 0x10, 0x0d, 0x0b, 9, 7, 5, 3 } poke(SPEED_DELAY_P1, speeds[round]) end if loop_len == 0 then return start_screen end end if not run_started then return end -- reset score on screen change if reset_score == true then do_reset_score() end if data ~= last_screen then fire_ev("screen_change", data, last_screen) last_screen = data end if loop_len > 0 then local next = loop_screens[loop_idx + 1] loop_idx = (loop_idx + 1) % loop_len -- um, why does this work? "next" should mod? return next end end) local START_OF_TILES = 0x9040 -- top right tile local TW = 27 local TH = 31 -- END_OF_TILES $93BF ; bottom left tile function draw_tile(x, y, tile) poke(START_OF_TILES + (TW - x) * 32 + y, tile) end -- What? if false then ground = 0x90fe -- rando ground tile on screen w = {0x0e, 0x0a, 0x22, 0x1c, 0x0e, 0x3b, 0x3e, 0x22, 0x25, 0x1c, 0x0e, 0x23} tap3 = mem:install_write_tap(ground, ground, "writes", function(offset, data) if data == 0x3e then local pos = 0x929e for i, v in pairs(w) do poke(pos - (i - 1) * 0x20, v); end end end) end -- p1/p2 button to skip forward/go back screens if allow_skip == true then buttons = false BUTTONS = 0x800c tap_buttons = mem:install_write_tap(BUTTONS, BUTTONS, "writes", function(offset, data) local val = data & 3 -- 1: p1, 2: p2 if buttons == true and val == 0 then -- button released (stops repeats) buttons = false end if not buttons and (val > 0) then buttons = true -- Don't transition unless playing if not is_on_game_screen() then return end if val == 3 then -- both p1 & p2: reset set_pc(0x0410) -- game over return end local cur = peek(SCREEN_NUM) -- TODO: this doesn't work properly when you have loop selections. if val == 1 then -- p1 button. wrap on cage screen. if cur == 27 then poke(SCREEN_NUM, 0) -- 0 as it get incremented... somewhere else end end if val == 2 then -- p2 button, go back screen if cur <= 1 then poke(SCREEN_NUM, 26) else poke(SCREEN_NUM, cur - 2) end end -- Triggers next level. Checks that $SCREEN_XOFF_COL+6 is 0 -- (this is what is scrolled while transitioning: to prevent double-triggering) if peek(0x8106) == 0 then set_pc(0x1778) end end end) end -------------------- OGNOB mode ------------------- -- Open-world mode: freely wander left or right if ognob_mode == true then local OGNOB_MODE_ADDR = 0x2538 -- on EXIT_STAGE_LEFT, call $OGNOB_MODE poke_rom(0x1a0c, { CALL, x(OGNOB_MODE_ADDR) }) --[[ The main OGNOB_MODE routine. Does what would happen during a normal screen switch, but also sets PLAYER_LEFT_Y (0x8077: my variable) that indicates the player is left-transitioning. It gets cleared if you go through a normal right-transitioning. -- ]] poke_rom(OGNOB_MODE_ADDR, { LD_A_MEM, x(0x8143), -- PLAYER_Y LD_MEM_A, x(PLAYER_LEFT_Y), -- (was using 8099 - but seemed to affect 8029?! How?!) -- TRANSITION_TO_NEXT_SCREEN CALL, x(0x17C0), -- RESET_DINO -- get the previous screen LD_A_MEM, x(SCREEN_NUM), CP, 0x1, -- screen 1? JR_NZ, 0x2, -- don't reset LD_A, 0x1C, -- screen 28 (1 extra, that gets dec-d) DEC_A, LD_MEM_A, x(SCREEN_NUM), -- DURING_TRANSITION_NEXT CALL, x(0x14B0), -- SCREEN_RESET CALL, x(0x1490), -- RESET_XOFF_AND_COLS_AND_SPRITES CALL, x(0x12B8), -- DRAW_BACKGROUND CALL, x(0x1820), -- INIT_PLAYER_POS_FOR_SCREEN CALL, x(0x0db8), -- DRAW_BONGO -- SET_PLAYER_LEFT: PC must be OGNOB_MODE_ADDR+0x25 LD_A, 0xE0 - 1, -- very right edge of screen LD_MEM_A, x(0x8140), -- PLAYER_X LD_MEM_A, x(0x8144), -- PLAYER_X_LEGS LD_A_MEM, x(PLAYER_LEFT_Y), -- (mine) -- Set player to top or bottom depending where they entered the screen -- dodgy (should do like INIT_PLAYER_POS_FOR_SCREEN, but eh. SCF, CCF, -- clear carry SUB, 0x70, -- ~ middle of screen height JR_C, 4, LD_A, 0xD0, -- set to bottom of screen JR, 2, LD_A, 0x26, -- set to top of screen LD_MEM_A, x(0x8143), -- PLAYER_Y ADD_A, 0x10, LD_MEM_A, x(0x8147), -- PLAYER_Y_LEGS LD_A_MEM, x(0x8141), -- PLAYER_FRAME ADD_A, 0x80, -- flip x LD_MEM_A, x(0x8141), -- PLAYER_FRAME LD_A_MEM, x(0x8145), -- PLAYER_FRAME_LEGS ADD_A, 0x80, -- flip x LD_MEM_A, x(0x8145), -- PLAYER_FRAME_LEGS -- after DURING_TRANSTION_NEXT CALL, x(0x0AD0), -- SET_LEVEL_PLATFORM_XOFFS LD_A, 0x02, CALL, x(0x17B4), -- RESET_JUMP_AND_REDIFY_BOTTOM_ROW -- trigger 0x8078 so I can catch it in hook LD_A, 0x1, LD_MEM_A, x(OGNOB_TRIGGER), RET, }) local SET_PLAYER_LEFT = OGNOB_MODE_ADDR + 0x25 -- careful! Address will change if above modified. -- Patch end of INIT_PLAYER_SPRITE after death: -- reset to right side of screen if ognob-ing poke_rom(0x08b5, { LD_A_MEM, x(PLAYER_LEFT_Y), CP, 0x0, RET_Z, CALL, x(SET_PLAYER_LEFT), RET }) local SET_PLAYER_LEFT_LOC = 0x1886 -- some free bytes here -- Patch TRANSITION_TO_NEXT_SCREEN to account for -- being able to go right out of cage screen. poke_rom(0x177B, { CALL, x(SET_PLAYER_LEFT_LOC), -- (breaks P2 handling!) NOP, NOP, NOP }) -- Reset PLAYER_LEFT_Y on right-transition, -- and wrap level if right-transition on cage screen (possible now!) -- Used some free (looking) bytes at 0x1886... poke_rom(SET_PLAYER_LEFT_LOC, { XOR_A, LD_MEM_A, x(PLAYER_LEFT_Y), LD_A_MEM, x(SCREEN_NUM), CP, 0x1b, -- is it 27? RET_C, -- nah, carry on XOR_A, LD_MEM_A, x(SCREEN_NUM), -- yep - reset to 0 RET }) -- Patch SET_SPEAR_LEFT_BOTTOM to fix insta-death spears -- Not enough bytes, so overwriting color set, but then -- doing this in SET_SPEAR_LEFT_MIDDLE. lol. poke_rom(0x3947, { -- original code, moved up 3 bytes... LD_A, 0xC8, -- original y value LD_MEM_A, x(0x8157), -- ENEMY_1_Y LD_A, 0x01, -- original active value LD_MEM_A, x(0x8037), -- ENEMY_1_ACTIVE -- fix screen 26 spears insta-death LD_A_MEM, x(PLAYER_LEFT_Y), -- is left side? AND_A, RET_Z, LD_A, 0xC6, -- New Y value (2 higher - misses head!) LD_MEM_A, x(0x8157), -- ENEMY_1_Y RET }) -- Patch SET_SPEAR_LEFT_MIDDLE to set the bottom spear color. -- Had to be done here because of the bytes we stole above! poke_rom(0x397E, { LD_A, 0x17, -- set spear color LD_MEM_A, x(0x8156), -- ENEMY_1_COL RET }) -- extra platforms to make Bongo backwards-compatible (tee hee) poke_rom(0x1e02, 0xfe) -- S, entry point bottom-right poke_rom(0x21ea, 0xfc) -- nTn helper step -- Prevent score-accumulation from moving ognob. (too hard to do properly) -- Patch UPDATE_EVERYTHING_MORE to conditionally call -- ADD_MOVE_SCORE only when not Ognobbing. poke_rom(0x4020, { CALL, x(0x4030) }) -- jump to some free bytes poke_rom(0x4030, { LD_A_MEM, x(PLAYER_LEFT_Y), AND_A, RET_NZ, JP, x(0x4050), -- ADD_MOVE_SCORE }) -- track an Ognob run local ognobbing = false is_ognob_win = false local ognob_done = add_ev("screen_change", function(cur, last) if cur == 1 and last == 27 then ognobbing = false ognob_stop() end if cur == 27 and last == 1 then ognobbing = true ognob_start() end -- You did it! if ognobbing == true and last == 2 and cur == 1 then ognob_win() end end) add_ev("game_over", function() ognobbing = false end) function ognob_stop() -- clear OGNOB text for i = 1, 5 do draw_tile(i-1, TH-2, TILE_BLANK) end is_ognob_win = false end -- begin your ognob run function ognob_start() do_reset_time() do_reset_score() poke(0x801D, 10) -- 100 starting points to force re-draw -- draw OGNOB text local ogtxt = {31,23,30,31,18} for i = 1, 5 do draw_tile(i-1,TH-2,ogtxt[i]) end is_ognob_win = false end function ognob_win() local ogtxt = {31,23,30,31,18,0x10} for j = 3, TH do for i = 0, 5 do draw_tile(i,j,ogtxt[(j+i) % #ogtxt + 1]) end end is_ognob_win = true end -- tap (and OGNOB_TRIGGER) is because the screen write that fires -- ognob_win happens BEFORE screen drawing etc, so any changes we make -- will get overwritten by the original code. This tap happens -- AFTER the original reseting and drawing. tap_ognob = mem:install_write_tap(OGNOB_TRIGGER, OGNOB_TRIGGER, "writes", function(offset, data) if is_ognob_win then -- Play win song poke(0x8042, 0x6) -- ch1 sfx poke(0x8065, 0x6) -- prev sfx (or something) -- remove pickup from last screen, so can't trigger bonus skip! poke(0x915a, TILE_BLANK) end end) end ---- Bongo always -----
// Copyright 2021 Matrix Origin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package txnbase import ( "bytes" "github.com/matrixorigin/matrixone/pkg/container/types" "github.com/matrixorigin/matrixone/pkg/vm/engine/tae/iface/txnif" "github.com/matrixorigin/matrixone/pkg/vm/engine/tae/wal" ) type MVCCSlice struct { MVCC []txnif.MVCCNode comparefn func(txnif.MVCCNode, txnif.MVCCNode) int } func NewMVCCSlice(newnodefn func() txnif.MVCCNode, comparefn func(txnif.MVCCNode, txnif.MVCCNode) int) *MVCCSlice { return &MVCCSlice{ MVCC: make([]txnif.MVCCNode, 0), comparefn: comparefn, } } func (be *MVCCSlice) StringLocked() string { var w bytes.Buffer length := len(be.MVCC) for i := length - 1; i >= 0; i-- { version := be.MVCC[i] _, _ = w.WriteString(" -> ") _, _ = w.WriteString(version.String()) } return w.String() } // for replay func (be *MVCCSlice) GetTs() types.TS { return be.GetUpdateNodeLocked().GetEnd() } // func (be *MVCCSlice) GetTxn() txnif.TxnReader { return be.GetUpdateNodeLocked().GetTxn() } func (be *MVCCSlice) InsertNode(un txnif.MVCCNode) { be.MVCC = append(be.MVCC, un) } // GetUpdateNode gets the latest UpdateNode. // It is useful in making command, apply state(e.g. ApplyCommit), // check confilct. func (be *MVCCSlice) GetUpdateNodeLocked() txnif.MVCCNode { length := len(be.MVCC) if length == 0 { return nil } return be.MVCC[length-1] } // GetCommittedNode gets the latest committed UpdateNode. // It's useful when check whether the catalog/metadata entry is deleted. func (be *MVCCSlice) GetCommittedNode() (node txnif.MVCCNode) { length := len(be.MVCC) for i := length - 1; i >= 0; i-- { un := be.MVCC[i] if !un.IsActive() && !un.IsCommitting() { node = un break } } return } func (be *MVCCSlice) DeleteNode(node txnif.MVCCNode) { length := len(be.MVCC) for i := length - 1; i >= 0; i-- { un := be.MVCC[i] compare := be.comparefn(un, node) if compare == 0 { be.MVCC = append(be.MVCC[:i], be.MVCC[i+1:]...) break } else if compare < 0 { break } } } func (be *MVCCSlice) SearchNode(o txnif.MVCCNode) (node txnif.MVCCNode) { for _, n := range be.MVCC { if be.comparefn(n, o) == 0 { node = n break } } return } func (be *MVCCSlice) GetVisibleNode(ts types.TS) (node txnif.MVCCNode) { length := len(be.MVCC) for i := length - 1; i >= 0; i-- { un := be.MVCC[i] var visible bool if visible = un.IsVisible(ts); visible { node = un break } } return } func (be *MVCCSlice) GetLastNonAbortedNode() (node txnif.MVCCNode) { length := len(be.MVCC) for i := length - 1; i >= 0; i-- { un := be.MVCC[i] if !un.IsAborted() { node = un break } } return } func (be *MVCCSlice) SearchNodeByTS(ts types.TS) (node txnif.MVCCNode) { for _, n := range be.MVCC { if n.GetStart().Equal(ts) { node = n break } } return } func (be *MVCCSlice) ForEach(fn func(un txnif.MVCCNode) bool, reverse bool) { if reverse { be.forEachReverse(fn) } else { be.forEach(fn) } } func (be *MVCCSlice) forEach(fn func(un txnif.MVCCNode) bool) { for i := len(be.MVCC) - 1; i >= 0; i-- { n := be.MVCC[i] gonext := fn(n) if !gonext { break } } } func (be *MVCCSlice) forEachReverse(fn func(un txnif.MVCCNode) bool) { for _, n := range be.MVCC { gonext := fn(n) if !gonext { break } } } // GetNodeToRead gets UpdateNode according to the timestamp. // It returns the UpdateNode in the same txn as the read txn // or returns the latest UpdateNode with commitTS less than the timestamp. // todo getend or getcommitts func (be *MVCCSlice) GetNodeToReadByPrepareTS(ts types.TS) (offset int, node txnif.MVCCNode) { if len(be.MVCC) == 0 { return 0, nil } lastAppend := be.MVCC[len(be.MVCC)-1] // 1. Last append node is in the window and it was already committed if ts.Greater(lastAppend.GetPrepare()) { return len(be.MVCC) - 1, lastAppend } start, end := 0, len(be.MVCC)-1 var mid int for start <= end { mid = (start + end) / 2 if be.MVCC[mid].GetPrepare().Less(ts) { start = mid + 1 } else if be.MVCC[mid].GetPrepare().Greater(ts) { end = mid - 1 } else { break } } if mid == 0 && be.MVCC[mid].GetPrepare().Greater(ts) { // 2. The first node is found and it was committed after ts return 0, nil } else if mid != 0 && be.MVCC[mid].GetPrepare().Greater(ts) { // 3. A node (not first) is found and it was committed after ts. Use the prev node mid = mid - 1 } return mid, be.MVCC[mid] } func (be *MVCCSlice) SearchNodeByCompareFn(fn func(a txnif.MVCCNode) int) (offset int, node txnif.MVCCNode) { if len(be.MVCC) == 0 { return 0, nil } lastAppend := be.MVCC[len(be.MVCC)-1] // 1. Last append node is in the window and it was already committed if fn(lastAppend) < 0 { return 0, nil } start, end := 0, len(be.MVCC)-1 var mid int for start <= end { mid = (start + end) / 2 if fn(be.MVCC[mid]) < 0 { start = mid + 1 } else if fn(be.MVCC[mid]) > 0 { end = mid - 1 } else { break } } if fn(be.MVCC[mid]) != 0 { return 0, nil } return mid, be.MVCC[mid] } func (be *MVCCSlice) IsEmpty() bool { return len(be.MVCC) == 0 } func (be *MVCCSlice) IsCommitting() bool { node := be.GetUpdateNodeLocked() if node == nil { return false } return node.IsCommitting() } func (be *MVCCSlice) IsCommitted() bool { un := be.GetUpdateNodeLocked() if un == nil { return false } return un.IsCommitted() } func (be *MVCCSlice) LoopInRange(start, end types.TS, fn func(txnif.MVCCNode) bool) (indexes []*wal.Index) { startOffset, node := be.GetNodeToReadByPrepareTS(start) if node != nil && node.GetPrepare().Less(start) { startOffset++ } endOffset, node := be.GetNodeToReadByPrepareTS(end) if node == nil { return nil } for i := endOffset; i >= startOffset; i-- { if !fn(be.MVCC[i]) { break } } return } func (be *MVCCSlice) LoopOffsetRange(start, end int, fn func(txnif.MVCCNode) bool) { for i := start; i <= end; i++ { if !fn(be.MVCC[i]) { break } } } func (be *MVCCSlice) GetNodeByOffset(offset int) txnif.MVCCNode { return be.MVCC[offset] }
# 一、Shell的基本功能 一般用于脚本自动化、系统管理及配置。 shell命令通过空格分隔,如果在命令中需要使用到空格,则需要进行转义操作“\ ”;如果希望执行多条语句,则需要用“;”进行分隔。 对于一个程序来讲,一般来讲为: ```text 执行路径或相对路径下程序 > 别名 > Bash内部命令 > 环境变量定义下第一个对应命令 ``` 在开发过程中,我们往往会使用到一些快捷键以帮助开发,例如:(^表示ctrl,例如`^a`表示`ctrl+a`) - ^a,将光标移动至行首 - ^e,将光标移动至行尾 - ^c,强制终止当前命令 - ^l,清屏(与直接使用clear命令不同) - ^u,删除光标之前命令 - ^k,删除光标之后命令 - ^y,粘贴上述两个命令内容 - ^r,搜索历史命令 - ^d,退出当前终端 - ^z,暂停(如程序) - ^s,暂停屏幕输出 - ^q,恢复屏幕输出 > 补充: > > bash采用emacs操作逻辑,所以会发现许多快捷键:),如果想要使用vi操作逻辑,可以在~/.bashrc下插入`set -o vi`,如果使用的是`fish shell`则插入`set fish_plugins autojump vi-mode`。 --- 在正式学习之前,先了解以下基础shell知识点: - 标准输入/输出 - 标准输入 - 一般通过键盘实现,其设备文件名为:/dev/stdin - 文件描述符为0 - 标准输出 - 一般显示在显示器上,设备文件名为:/dev/stdout - 文件描述符为1 - 标准错误输出 - 一般显示在显示器上,文件设备名为:/dev/stderr - 文件描述符为2 在后续开发中,我们会经常使用到这三者。 不妨做个小练习: ```bash ~/Downloads> echo 'a' 1> a.txt ~/Downloads> echo 'b' 2> b.txt b ~/Downloads> cat 0< a.txt a ~/Downloads> cat 0< b.txt ``` > 补充: > > `~>Downloads`为笔者的终端提示符,您无需关心。请注意`>`后的命令。 在上面的练习中,笔者使用了两个程序:`echo`和`cat`。二者均是linux操作系统默认提供的,无需自行下载。 简单介绍二者功能: - echo,打印数据或将数据写入某文件 - cat,打印某文件数据于终端 当然,二者还有许多功能和参数实现,详细可以通过使用`man`程序查看,例如:man echo 回到练习,这里我们使用到了`>`重定向符号,您无需担心,只需要记住该符号即可。 首先,我们`echo 'a' 1> a.txt`,意图将字符a输入至`a.txt`文件中,同理可得,`echo 'b' 2> b.txt`,也是意图将字符b输入至`b.txt`文件中。但是仔细观察发现,第二个命令直接将b打印在终端上了,这是为什么呢❓ 还记得之前说的吗?标准输出的文件描述符为1,标准错误输出文件描述符为2。`echo 'b' 2> b.txt`命令中`echo`程序正确执行了,但是却让我们将标准错误输出到`b.txt`文件中,这显然是不正确的。所以程序仅执行`2>`的前半段,而并没有执行后半段。 事实上,当我们能输入`cat 0< a.txt`和`cat 0< b.txt`时,发现:`a.txt`文件中存在字符a,而`b.txt`文件并没有字符b。这里就可以证明第二条命令的后半段并没有被执行。 --- 相信您对上述的第一知识点:`标准输入/输出`有一定了解了。那么我们接着来学习第二个关键点:逻辑符 如果您之前对编程有一定了解,相信一定了解`&&`和`||`逻辑符。 `&&`逻辑符表示“与”,例如:`a && b`,意思是当a正确时b才会被执行,a如果错误则b不会被执行。 `||`逻辑符表示“或”,同样例如:`a || b`,意思为当a正确时b不会被执行,a如果错误则b将会被执行 实例: ```bash ~/Downloads> lss && echo 'true' && echo 'false' bash: lss:未找到命令 ~/Downloads> lss && echo 'true' || echo 'false' bash: lss:未找到命令 false ~/Downloads> lss || echo 'true' || echo 'false' bash: lss:未找到命令 true ~/Downloads> lss || echo 'true' && echo 'false' bash: lss:未找到命令 true false ``` 在上面的例子中,我们用到了两个逻辑符,分别组合就可以发现例子: 1. `lss`程序并不存在,所以无法输出true,同样由于前者是错误的,同样无法输出false 2. 与例子1的差别在于,第二个`&&`变为`||`,由于前者是错误的,根据`||`的特性,false语句能够被执行 3. 同样根据`||`特性,true能够被执行,但是由于`echo 'true'`的正确执行,最后一条语句则不能被执行,因为`||`逻辑符要求如果`a`正确,则`b`不能执行 4. `lss`程序不存在,所以第一条语句错误,那么第二条语句正确,true被输出;第二条语句的正确,让第三条语句能够被执行,false也被输出 --- 在上面我们使用到了`||`和`&&`两个逻辑符,这两个符号在shell中属于特殊符号(因为其具有特定的功能),除此之外还有以下特殊符号[^2]: - `''`,单引号。用于将单引号内的文本设置为字符串形式,其中的特殊符号转换为普通字符 - `""`,双引号。与单引号类似,但是对于`$`、` `` `、`\ `例外,三者仍然具有特殊意义(调用变量的值、引用命令、转移符) - `$`,美元符号。用于调用变量值 - ` `` `,反引号。其中内容为系统命令,在Bash中会优先执行。与`$()`类似,但是推荐使用后者 - `$()`,与反引号类似。用于引用系统命令 - `#`,井号。在Bash中用于注释 - `\ `,反斜杠号。用于转义,将特殊字符转义为普通字符 - `()`,小括号。用于命令执行,括号内命令会在子Shell(重新开启一个子Shell)中执行 - `{}`,大括号。用于命令执行,括号内命令会在当前Shell中执行 - `[]`,中括号。用于变量测试 了解玩基本的特殊字符,我们测试一下: ```bash $ a=data $ echo '$a' # test ' ' $a $ echo "a" # test " " a $ echo "$a" # test $ data $ a=`date` # test ` ` $ echo $a 2024年 01月 04日 星期四 17:23:20 CST data $ echo $a # test $ 2024年 01月 04日 星期四 17:14:55 CST $ a=$(date) # test $() $ echo $a 2024年 01月 04日 星期四 17:15:09 CST $ (date) # test () 2024年 01月 04日 星期四 17:15:14 CST $ a=`#date` # test # $ echo $a $ a=aa $ b="$a" $ echo $b aa $ b="\$a" # test \ $ echo $b $a ``` > 补充 > > `()`和`{}`二者具有一定区别: > > - `()`和`{}`都将一串命令放在括号内,并且命令之间用;号隔开。 > - `()`最后一个命令可以不用分号结尾 >> `$ ( name=lm; echo $name )` > - `{}`中最后一个命令要用分号结尾 >> `$ { 空格 name=lm; echo $name; }` > - `{}`中的第一个命令和左括号之间必须要有一个空格; >> `$ { 空格 name=lm; echo $name; }` > - `()`里的各命令不必和括号有空格; > - `()`和`{}`中,括号里面的某个命令的重定向只影响该命令,但括号外的重定向则影响到括号里的所有命令。 --- 其实`()`和`{}`深究下来还有一些差别,这就需要知道**父子Shell**的概念 简单来说,当我们启动终端后,当前Shell我们成为“父Shell”,而当我们运行一个shell脚本时,当前Shell就会创建一个“子Shell”,当脚本介绍,其子Shell也就被销毁了。子Shell由父Shell派生而来,例如,当前Shell为Bash,那么其子Shell也为Bash。 示例: ```bash [I] aaron@aaron-PC ~> ps -f # 查看当前进程 UID PID PPID C STIME TTY TIME CMD aaron 28901 10411 1 17:46 pts/3 00:00:00 /usr/bin/fish aaron 28937 28901 99 17:46 pts/3 00:00:00 ps -f [I] aaron@aaron-PC ~> bash # 创建一个bash子Shell (base) aaron@aaron-PC:~$ ps -f # 查看当前进程 UID PID PPID C STIME TTY TIME CMD aaron 28901 10411 0 17:46 pts/3 00:00:00 /usr/bin/fish aaron 28947 28901 0 17:46 pts/3 00:00:00 bash aaron 28965 28947 99 17:46 pts/3 00:00:00 ps -f (base) aaron@aaron-PC:~$ bash # 再创建一个bash子Shell (base) aaron@aaron-PC:~$ ps --forest # 查看Shell关系图 PID TTY TIME CMD 28901 pts/3 00:00:00 fish # 父shell 28947 pts/3 00:00:00 \_ bash # 子shell 28970 pts/3 00:00:00 \_ bash # 子shell(孙shell) 28991 pts/3 00:00:00 \_ ps # 当前ps进程 (base) aaron@aaron-PC:~$ exit # 退出 (base) aaron@aaron-PC:~$ exit # 退出 [I] aaron@aaron-PC ~> ps -f # 查看当前进程 UID PID PPID C STIME TTY TIME CMD aaron 28901 10411 0 17:46 pts/3 00:00:00 /usr/bin/fish aaron 29009 28901 99 17:46 pts/3 00:00:00 ps -f ``` 从上面示例就可以看出父子shell之间的关系。 回到`()`和`{}`之间的差别,在介绍特殊符号时简单说明了二者都会包含命令。深究以下:`()`执行括号内命令时,会创建一个子shell执行,而`{}`则是直接在当前shell中执行。 示例: ```bash (base) aaron@aaron-PC:~$ a=aa (base) aaron@aaron-PC:~$ ( a=bb; echo $a;) bb (base) aaron@aaron-PC:~$ echo $a aa (base) aaron@aaron-PC:~$ { a=bb; echo $a;} bb (base) aaron@aaron-PC:~$ echo $a bb ``` 从上面的示例我们就可以看出,`()`会单独创建一个子shell,所以`a=bb`命令并在当前shell生效,而当在`{}`写上`a=bb`时,当前shell生效了。说明`{}`括号中命令运行在当前shell中。 > 注意: > > 生成子shell的成本并不低且生成速度慢,创建嵌套子shell去处理命令进程性能低效。所以在开发中应该尽量少的使用`()`方式存放命令。 --- 在前面我们了解父子进程时,不知道您是否注意到执行`ps -f`和`ps --forest`命令时,总是会产生一个有关`ps`的进程。为什么会产生呢? 原因是`ps`命令为**外部命令**。 何谓外部命令?外部命令也叫做**文件系统命**,简单来说就是存在于Bash shell之外的程序,并不是Bash shell内嵌的程序。 通过这些命令存放在:`/usr/bin`、`/bin`、`sbin`或者`/usr/sbin`目录中,当然也有可能存在于`~/.local/bin`目录中。 当选择执行外部命令时,Bash shell就会创建一个子进程(也叫做衍生)来执行该程序。所以,当我们执行`ps`程序时才会在进程中看到该程序名。在前面介绍,子进程的创建和使用对资源消耗是比较大的。所以执行外部命令通常开销较大。与之相对的,便是那些存在于Bash shell中的命令,也成为 **内建命令**。 那么有那些内置命令呢?您可以查看[Linux Bash内置命令大全详细介绍](https://www.cnblogs.com/11hwu2/p/3724986.html) > 如果想立即查看自己正在使用的命令是否属于内置命令,可以通过`type`程序查看: > > ```bash > $ type pwd > pwd 是 shell 内建 > $ type ps > ps 是 /usr/bin/ps > ``` > > 有些命令既有内建命令,也有外部命令。那么便可以加上`-a`参数查看该命令的所有命令位置: > > ```bash > $ type pwd -a > pwd is a builtin > pwd is /usr/bin/pwd > pwd is /bin/pwd > ``` > > 与之类似的命令还有: > - `which`,但是该程序仅能查询外部命令: > - `whereis`,也是仅能查询外部命令,但是可以查找该命令的man手册 --- 最后,我们以**别名**作为结尾吧。 别名可以说在shell的使用中属于相当频繁的了。因为这有效地解决了程序参数设置过长、程序较为复杂的情况。 例如:我希望能够通过笔记本的摄像头拍一张照片并保存为“jpg”格式,那么我可以输入下面的命令: `ffmpeg -i /dev/video0 -frames 1 -r 1 -f image2 image.jpg` 但是这个命令似乎太长了,这个时候就可以使用别名方式: ```bash $ alias Cheese='ffmpeg -i /dev/video0 -frames 1 -r 1 -f image2 image.jpg' ``` 这样,当想要拍照时,输入`Cheese`命令即可。是不是很方便! > 补充 > > 由于`alias`本身就是内建命令,其产生的别名也是内建命令,即仅在当前shell中有效。当换一个shell时,该别名便失效了。 > > 对此的解决思路是,将别名存放在shell的配置文件中,比如存放在Bash shell的配置文件`~/.bashrc`。 ---- 参考文献: [基于deepin的shell编程-上](https://bbs.deepin.org/post/266587) [Bash脚本进阶指南](https://linuxstory.gitbook.io/advanced-bash-scripting-guide-in-chinese/zheng-wen/part1) --- 索引: [^1]:[在 Linux 上自定义 bash 命令提示符](https://zhuanlan.zhihu.com/p/50993989) [^2]:[Shell基础——Bash的特殊字符](https://zhuanlan.zhihu.com/p/558775217)
<template> <v-toolbar tabs dense :absolute="absolute" class="custom-toolbar elevation-0"> <slot name="left"></slot> <template v-for="(item, i) in items"> <v-checkbox v-if="item.select" :key="i" v-model="item.selected" class="shrink" :color="getColor(item)" :indeterminate="getIndeterminate(item)" hide-details @change="onEmit('onChange', $event, item, i)" ></v-checkbox> <v-compoment v-else-if="!item.menu && item.component" :key="i" :is="item.component()" v-bind="item.componentProps ? item.componentProps() : {}" ></v-compoment> <v-menu v-else-if="item.menu" :key="i" :open-on-hover="item.hover" :min-width="item.minwidth || 200" offset-y :disabled="getDisabledAttribute(item)" > <template v-slot:activator="{ on }"> <v-tooltip v-if="item.icon && item.text" :key="`tooltip-menu-${i}`" v-bind="item.tooltipAttr ? item.tooltipAttr : { top: true }" > <template v-slot:activator="{ on: tooltip }"> <v-btn v-on="{ ...on, ...tooltip }" icon small :disabled="getDisabledAttribute(item)"> <v-icon>{{ item.icon }}</v-icon> </v-btn> </template> <span>{{ item.text }}</span> </v-tooltip> <v-icon color="grey darken-4" v-else-if="hasIcon(item)" v-text="item.icon" :class="getClasses(item)" v-on="on" ></v-icon> <v-btn v-else-if="item.html || item.component" flat :class="getClasses(item)" v-on="on" @click.prevent.stop="item.onClick ? item.onClick($event, item, i) : () => {}" > <div v-if="item.html" class="caption text-lowercase" v-html="item.html()"></div> <v-compoment v-else-if="item.component" :is="item.component()" v-bind="item.componentProps ? item.componentProps() : {}" ></v-compoment> </v-btn> <div v-else v-html="item.text" :class="getClasses(item)" v-on="on"></div> </template> <v-list v-if="item.menuItems" dense> <v-list-tile v-for="(menuItem, menuIndex) in item.menuItems" :key="`menuItem-${i}--${menuIndex}`" :disabled="getDisabledAttribute(menuItem)" :class="getMenuItemClassAttribute(menuItem)" @click="onEmit('onClick', $event, menuItem, i, menuIndex)" > <v-subheader v-if="menuItem.subheading" class="body-2 pl-4" v-text="item.text" disabled></v-subheader> <v-divider v-else-if="menuItem.divider" /> <v-compoment v-else-if="menuItem.component" :is="menuItem.component()" v-bind="menuItem.componentProps ? menuItem.componentProps() : {}" ></v-compoment> <v-list-tile-title v-else class="pl-4">{{ menuItem.text }}</v-list-tile-title> </v-list-tile> </v-list> </v-menu> <v-spacer v-else-if="item.spacer" :key="i" /> <v-divider v-else-if="item.divider" vertical class="custom-toolbar__divider" :key="i" /> <v-tooltip v-else-if="item.icon && item.text" :key="`tooltip-menu-${i}`" v-bind="item.tooltipAttr ? item.tooltipAttr : { top: true }" > <template v-slot:activator="{ on }"> <v-btn v-on="on" icon small :disabled="getDisabledAttribute(item)" @click="onEmit('onClick', $event, item, i)" > <v-icon>{{ item.icon }}</v-icon> </v-btn> </template> <span>{{ item.text }}</span> </v-tooltip> <v-btn v-else-if="item.icon" :key="i" icon small :class="getClasses(item)" :disabled="getDisabledAttribute(item)" @click="onEmit('onClick', $event, item, i)" > <v-icon>{{ item.icon }}</v-icon> </v-btn> <span v-else :key="i" v-text="item.text" :class="getClasses(item)"></span> </template> <template v-slot:extension> <slot name="extension"></slot> </template> </v-toolbar> </template> <script> import { onEmit } from "../helpers"; export default { props: { items: { type: Array, default: () => [] }, absolute: { type: Boolean, default: () => false } }, methods: { onEmit, hasIcon({ icon = "" } = {}) { return icon.length !== 0; }, getIndeterminate(item) { return item.indeterminate ? item.indeterminate(item) : false; }, getColor({ color = "accent" }) { return color; }, getClasses({ classes = {} } = {}) { return classes; }, getDisabledAttribute(item) { return item.disabled ? item.disabled() : false; }, getMenuItemClassAttribute(item) { return { "is-divider": item.divider }; } } }; </script> <style lang="scss"> .custom-toolbar { background: white !important; padding-bottom: 8px; z-index: 1; &__divider { min-height: 45%; max-height: 45%; align-self: center; } } .v-list { .is-divider { .v-list { &__tile { padding: 0; height: 1px; } } } } </style>
import React, { useEffect, useRef, useState } from 'react'; import { AlertStatus } from '../types'; type AlertContextValue = { alert: AlertStatus; alertText: string | undefined; success: (text: string) => void; error: (text: string) => void; }; export const AlertContext = React.createContext<AlertContextValue>({ alert: AlertStatus.None, alertText: undefined, success: () => {}, error: () => {} }); const AlertProvider = ({ children }: any) => { const [alert, setAlert] = useState(AlertStatus.None); const [alertText, setAlertText] = useState<string | undefined>(undefined); const timerRef = useRef<undefined | number>(undefined); useEffect(() => { // Clear the interval when the component unmounts return () => { if (timerRef.current) { window.clearTimeout(timerRef.current); } }; }, []); const runAlert = () => { if (timerRef.current) { clearTimeout(timerRef.current); } timerRef.current = window.setTimeout(() => { setAlertText(undefined); setAlert(AlertStatus.None); }, 1000); }; return ( <AlertContext.Provider value={{ alert, alertText, success: (text: string) => { setAlertText(text); setAlert(AlertStatus.Success); runAlert(); }, error: (text: string) => { setAlertText(text); setAlert(AlertStatus.Error); runAlert(); } }} > {children} </AlertContext.Provider> ); }; export default AlertProvider;
import { Component, inject } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { CustomCarouselComponent } from '../custom-carousel/custom-carousel.component'; import { CommonModule } from '@angular/common'; import { registrationForm } from '../../../models/user-formType.models'; import { CommonFunctionService } from '../../../services/Common-function.service'; import { Console } from 'console'; import { UserService } from '../../../services/user.service'; import { Router, RouterLink } from '@angular/router'; import { Subject, takeUntil } from 'rxjs'; import { StatusCodes } from '../../../Common/constant'; import { RegisterDTO } from '../../../models/user-models'; import { MatIcon } from '@angular/material/icon'; @Component({ selector: 'app-registration', standalone: true, imports: [RouterLink, CommonModule, FormsModule, ReactiveFormsModule, MatFormFieldModule, MatInputModule, MatButtonModule, MatSnackBarModule, CustomCarouselComponent,MatIcon], templateUrl: './registration.component.html', styleUrl: './registration.component.css' }) export class RegistrationComponent { private ngUnsubscribe = new Subject<void>(); passwordHide = true; confirmPasswordHide = true; registerForm: FormGroup<registrationForm> = new FormGroup<registrationForm>({ firstName: new FormControl("", [Validators.required]), lastName: new FormControl("", [Validators.required]), phoneNumber: new FormControl("", [Validators.required, Validators.pattern("[0-9 ]{10}")]), email: new FormControl("", [Validators.required, Validators.email]), password: new FormControl("", [Validators.required, Validators.minLength(8), Validators.pattern(/^(?=.*[A-Z])(?=.*\d).+$/)]), confirmPassword: new FormControl("", [Validators.required, Validators.minLength(8), Validators.pattern(/^(?=.*[A-Z])(?=.*\d).+$/)]) }); constructor(private fb: FormBuilder, private snackBar: MatSnackBar, public commonFunctionService: CommonFunctionService, private router: Router, private userservice: UserService ) { } get ctrl(): registrationForm { return this.registerForm.controls; } checkpassword() { if (this.ctrl.password.value != this.ctrl.confirmPassword.value) { this.ctrl.confirmPassword.setErrors({ invalid: true }); } } submit = (): void => { this.userservice.IsUserExist(this.ctrl.email.value).subscribe((result) => { if (result.code === StatusCodes.Ok) { this.registerForm.controls.email.setErrors({ incorrect: true }); } }); if (this.registerForm.valid) { const data: RegisterDTO = { ...this.registerForm.value } as RegisterDTO; this.userservice.CreateUser(data).pipe(takeUntil(this.ngUnsubscribe)).subscribe((result) => { if (result.code === StatusCodes.Ok) { this.snackBar.open('Registration Successfull', 'OK', { duration: 3000, horizontalPosition: 'right', verticalPosition: 'top' }); this.redirectToUrl("/"); } else { this.snackBar.open('Registration UnSuccessfull', 'OK', { duration: 3000, horizontalPosition: 'right', verticalPosition: 'top' }); } }); } } redirectToUrl(url: string) { this.router.navigate([url]); } ngOnDestroy(): void { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); } }
import {ClientType} from "../../types"; import {ValidationError} from "../../utils/errors"; import {pool} from "../../utils/db"; import {FieldPacket} from "mysql2/promise"; type AdRecordResults = [ClientType[], FieldPacket[]]; export class Client implements ClientType { address: string; birth: string; city: string; code: string; gender: string; id: string; email: string; name: string; phone: number; surname: string; ban: number; constructor(obj: ClientType) { // if (!obj.name || obj.name.length > 36 || obj.name.length < 3) { // throw new ValidationError('Imię musi składać się min z 3 i maks 36 znaków') // } // // if (!obj.surname || obj.surname.length > 96 || obj.surname.length < 3) { // throw new ValidationError('Nazwisko musi skłądać się z min 3 oraz maks 96 znaków') // } // // if (!obj.address || obj.address.length < 5 || obj.address.length > 150) { // throw new ValidationError('Podaj prawidłowy adres wysyłkowy') // } // // if (!(obj.code.length === 6)) { // throw new ValidationError('Kod pocztowy składa się łącznie z 6 znaków!') // } // // if (!obj.city || obj.city.length < 3 || obj.city.length > 70) { // throw new ValidationError('Nazwa miasta w Polsce składa się z minimu 3 znaków oraz nie więcej niz 70 znaków') // } // if (!obj.phone || !(obj.phone.toString().length === 9)) { // throw new ValidationError('Numer telefonu składa się z 9 cyfr !') // } // if (obj.gender === '-') { // throw new ValidationError('Nie chcesz nam powiedzieć chyba, ze nie posiadasz płci ? :)') // } // if (obj.mail.indexOf('@') === -1) { // throw new ValidationError('Email musi zawierać znak @') // } this.id = obj.id; this.name = obj.name; this.surname = obj.surname; this.address = obj.address; this.code = obj.code; this.city = obj.city; this.phone = obj.phone; this.gender = obj.gender; this.birth = obj.birth; this.email = obj.email; this.ban = obj.ban; } static async getAll(): Promise<ClientType[] | null> { const [result] = await pool.execute("SELECT * FROM `clients`") as AdRecordResults; return result.map((obj: ClientType) => new Client(obj)) } async add(): Promise<void> { await pool.execute("INSERT INTO `clients`(`id`, `name`, `surname`, `address`, `code`, `city`, `phone`, `gender`, `birth`, `email`) VALUES(:id, :name, :surname, :address, :code, :city, :phone, :gender, :birth, :email)", this); } }
<template> <div> <div class="page-heading"> <div class="row"> <div class="col-12 col-md-6 order-md-1 order-last"> <h3>Manage Sellers</h3> </div> <div class="col-12 col-md-6 order-md-2 order-first"> <nav aria-label="breadcrumb" class="breadcrumb-header float-start float-lg-end"> <ol class="breadcrumb"> <li class="breadcrumb-item"><router-link to="/dashboard">{{ __('dashboard') }}</router-link></li> <li class="breadcrumb-item active" aria-current="page">Manage Sellers</li> </ol> </nav> </div> </div> <div class="row"> <div class="col-12 col-md-12 order-md-1 order-last"> <div class="card"> <div class="card-header"> <h4>Sellers</h4> <span class="pull-right"> <a href="javascript:void(0)" @click="updateSellerCommission()" class="btn btn-primary" v-b-tooltip.hover title="If you found seller commission not crediting using cron job you can update seller commission from here!">Update seller commission</a> <router-link to="/sellers/create" class="btn btn-primary" v-b-tooltip.hover title="Add New Seller" v-if="$can('seller_create')">Add Seller</router-link> </span> </div> <div class="card-body"> <b-row> <b-col md="3"> <div class="form-group"> <h6 for="filterStatus">Filter Seller by Status </h6> <select id="filterStatus" name="filterStatus" v-model="filterStatus" @change="getRecords()" class="form-control form-select"> <option value="">All</option> <option value="0">Registered</option> <option value="1">Approved</option> <option value="2">Not-Approved</option> <option value="3">Deactivate</option> <option value="7">Removed</option> </select> </div> </b-col> <b-col md="3" offset-md="5"> <h6 class="box-title">Search</h6> <b-form-input id="filter-input" v-model="filter" type="search" placeholder="Search" ></b-form-input> </b-col> <b-col md="1" class="text-center"> <button class="btn btn-primary btn_refresh" v-b-tooltip.hover :title="__('refresh')" @click="getRecords()"> <i class="fa fa-refresh" aria-hidden="true"></i> </button> </b-col> </b-row> <b-row class="table-responsive"> <b-table :items="records" :fields="fields" :current-page="currentPage" :per-page="perPage" :filter="filter" :filter-included-fields="filterOn" :sort-by.sync="sortBy" :sort-desc.sync="sortDesc" :sort-direction="sortDirection" :bordered="true" :busy="isLoading" stacked="md" show-empty small> <template #table-busy> <div class="text-center text-black my-2"> <b-spinner class="align-middle"></b-spinner> <strong>{{ __('loading') }}...</strong> </div> </template> <template #cell(logo)="row"> <span v-if="!row.item.logo">No Image</span> <img v-else :src="$storageUrl + row.item.logo" height="50" /> </template> <template #cell(catWiseEditCommission)="row"> <button class="btn btn-sm btn-primary" @click="edit_record = row.item" v-if="$can('seller_update')"><i class="fa fa-edit"></i></button> </template> <template #cell(status)="row"> <label v-if="row.item.status === 0" class='badge bg-primary'>Registered</label> <label v-else-if="row.item.status === 1" class='badge bg-success'>Approved</label> <label v-else-if="row.item.status === 2" class='badge bg-warning'>Not-Approved</label> <label v-else-if="row.item.status === 3" class='badge bg-danger'>Deactive</label> <label v-else-if="row.item.status === 7" class='badge bg-danger'>Removed</label> </template> <template #cell(require_products_approval)="row"> <label v-if="row.item.require_products_approval === 1" class='badge bg-success'>Yes</label> <label v-else-if="row.item.require_products_approval === 0" class='badge bg-danger'>No</label> </template> <template #cell(actions)="row"> <router-link :to="{ name: 'EditSeller',params: { id: row.item.id, record : row.item }}" v-b-tooltip.hover title="Edit" class="btn btn-primary btn-sm" v-if="$can('seller_update')" v-b-tooltip.hover :title="__('edit')"> <i class="fa fa-pencil"></i> </router-link> <button class="btn btn-sm btn-danger" @click="deleteSeller(row.index,row.item.id)" v-if="$can('seller_delete')" v-b-tooltip.hover :title="__('delete')"> <i class="fa fa-trash"></i> </button> </template> </b-table> </b-row> <b-row> <b-col md="2" class="my-1"> <b-form-group :label="__('per_page')" label-for="per-page-select" label-align-sm="right" label-size="sm" class="mb-0"> <b-form-select id="per-page-select" v-model="perPage" :options="pageOptions" size="sm" class="form-control form-select" ></b-form-select> </b-form-group> </b-col> <b-col md="4" class="my-1" offset-md="6"> <b-pagination v-model="currentPage" :total-rows="totalRows" :per-page="perPage" align="fill" size="sm" class="my-0" ></b-pagination> </b-col> </b-row> </div> </div> </div> </div> </div> <!-- Add / Edit --> <app-edit-record v-if="edit_record" :record="edit_record" @modalClose="hideModal()" ></app-edit-record> </div> </template> <script> import EditRecord from './Commissions/Edit.vue'; export default { components: { 'app-edit-record' : EditRecord, }, data: function() { return { fields: [ { key: 'id', label: 'ID', sortable: true, sortDirection: 'desc' }, { key: 'name', label: 'Name', class: 'text-center', sortable: true, sortDirection: 'desc' }, { key: 'store_name', label: 'Store Name', class: 'text-center', sortable: true, sortDirection: 'desc' }, { key: 'email', label: 'Email', class: 'text-center', sortable: true, sortDirection: 'desc' }, { key: 'mobile', label: 'Mobile No.', class: 'text-center', sortable: true, sortDirection: 'desc' }, { key: 'balance', label: 'Balance', class: 'text-center', sortable: true, sortDirection: 'desc' }, { key: 'logo', label: 'Logo', class: 'text-center', sortable: true, sortDirection: 'desc' }, { key: 'commission', label: 'Commi.(%)', class: 'text-center', sortable: true, sortDirection: 'desc' }, { key: 'categories', label: 'Categories', class: 'text-center', sortable: true, sortDirection: 'desc' }, { key: 'catWiseEditCommission', label: 'Cat. Wise Comm.', class: 'text-center'}, { key: 'status', label: 'Status', class: 'text-center', sortable: true, sortDirection: 'desc' }, { key: 'require_products_approval', label: 'Pr. Approved?', class: 'text-center', sortable: true, sortDirection: 'desc' }, { key: 'actions', label: 'Action' } ], totalRows: 1, currentPage: 1, perPage: this.$perPage, pageOptions: this.$pageOptions, sortBy: '', sortDesc: false, sortDirection: 'asc', filter: null, filterOn: [], page: 1, isLoading: false, sectionStyle : 'style_1', max_visible_units : 12, max_col_in_single_row : 3, records: [], edit_record : null, filterStatus : "" } }, created: function() { this.category_id = this.$route.params.id; this.$eventBus.$on('recordSaved', (message) => { this.showMessage('success', message); this.getRecords(); }); this.$eventBus.$on('commissionsSaved', (message) => { this.showMessage('success', message); this.getRecords(); }); this.getRecords(); }, methods: { getRecords(){ this.isLoading = true; //axios.get(this.$apiUrl + '/sellers/'+this.filterStatus) axios.get(this.$apiUrl + '/sellers', { params: { filterStatus: this.filterStatus } }).then((response) => { this.isLoading = false let data = response.data; this.records = data.data }); }, deleteSeller(index, id){ this.$swal.fire({ title: "Are you Sure?", text: "You want be able to revert this", confirmButtonText: "Yes, Sure", cancelButtonText: "Cancel", icon: 'warning', showCancelButton: true, confirmButtonColor: '#37a279', cancelButtonColor: '#d33', }).then(result => { if (result.value) { this.isLoading = true let postData = { id : id } axios.post(this.$apiUrl + '/sellers/delete',postData) .then((response) => { this.isLoading = false let data = response.data; this.records.splice(index, 1) //this.showSuccess(data.message) this.showMessage('success', data.message); }); } }); }, updateSellerCommission(){ this.$swal.fire({ title: "Are you sure you want to credit seller commission?", text: "You want be able to revert this", confirmButtonText: "Yes, Sure", cancelButtonText: "Cancel", icon: 'warning', showCancelButton: true, confirmButtonColor: '#37a279', cancelButtonColor: '#d33', }).then(result => { if (result.value) { this.isLoading = true axios.get(this.$apiUrl + '/sellers/updateCommission') .then((response) => { let data = response.data; if (data.status === 1) { //this.showSuccess(data.message) this.showMessage('success', data.message); }else{ this.showError(data.message); } this.isLoading = false }); } }); }, hideModal() { this.edit_record = false }, } }; </script>
# Example: Abstract Factory from abc import ABC, abstractmethod class Button(ABC): # Abstract interface for buttons @abstractmethod def paint(self): raise NotImplementedError class WinButton(Button): # Concrete product for Windows buttons def paint(self): print("WinButton") class LinuxButton(Button): def paint(self): print("LinuxButton") class Menu(ABC): # Abstract interface for menus @abstractmethod def paint(self): raise NotImplementedError class WinMenu(Menu): # Concrete product for Windows menus def paint(self): print("WindowsMenu") class LinuxMenu(Menu): # Concrete product for Linux menus def paint(self): print("LinuxMenu") class GUIFactory(ABC): # Abstract factory that declares a set of methods for creating each of the # products. These methods must return abstract product types represented by # the abstract interfaces Button and Menu. @abstractmethod def create_button(self) -> Button: raise NotImplementedError @abstractmethod def create_menu(self) -> Menu: raise NotImplementedError class WinFactory(GUIFactory): # The concrete factory for Windows product variants. def create_button(self): return WinButton() def create_menu(self): return WinMenu() class LinuxFactory(GUIFactory): # The concrete factory for Linux product variants. def create_button(self): return LinuxButton() def create_menu(self): return LinuxMenu() if __name__ == "__main__": os = input("Select OS: ") if os == "win": factory = WinFactory() elif os == "linux": factory = LinuxFactory() else: raise ValueError("Invalid GUI") # Create the GUI button = factory.create_button() menu = factory.create_menu() gui = [button, menu] # Paint the GUI for item in gui: item.paint()
/*** * @project: Firestorm Freelance * @author: Meltie2013 * @copyright: 2017 - 2018 */ #ifndef ADVANCEDANTICHEATHMGR_H #define ADVANCEDANTICHEATHMGR_H #include "AdvancedAnticheatData.h" #include "Common.h" #include "SharedDefines.h" #include "ScriptMgr.h" #include "Player.h" class ChatHandler; class AnticheatCheck; enum DetectionTypes { SPEED_HACK_DETECTION = 0x01, FLY_HACK_DETECTION = 0x02, WALK_WATER_HACK_DETECTION = 0x04, JUMP_HACK_DETECTION = 0x08, TELEPORT_PLANE_HACK_DETECTION = 0x10, CLIMB_HACK_DETECTION = 0x20 }; typedef std::unordered_map<ObjectGuid, AdvancedAnticheatData> AnticheatPlayerDataMap; class AdvancedAnticheatMgr { friend class AnticheatCheck; AdvancedAnticheatMgr(); ~AdvancedAnticheatMgr(); public: static AdvancedAnticheatMgr* Instance(); void StartHackDetection(Player* player, MovementInfo const& movementInfo, uint16 opcode); void PlayerLogin(Player* player, PreparedQueryResult result); void PlayerLogout(ObjectGuid const& guid); void SavePlayerData(ObjectGuid const& guid, SQLTransaction& trans); inline uint32 GetTotalReports(ObjectGuid const& guid) { return _playerMap[guid].GetTotalReports(); } inline float GetAverage(ObjectGuid const& guid) { return _playerMap[guid].GetAverage(); } inline uint32 GetTypeReports(ObjectGuid const& guid, ReportTypes type) { return _playerMap[guid].GetTypeReports(type); } bool AnticheatGlobalCommand(ChatHandler* handler); void ResetDailyReportStates(); void LoadSettings(); private: AnticheatPlayerDataMap _playerMap; std::vector<AnticheatCheck*> _checks; bool _enabled; }; class AnticheatCheck { public: virtual ~AnticheatCheck() { } virtual bool OnCheck(Player* player, AdvancedAnticheatData* playerData, MovementInfo const& movementInfo, uint16 opcode = 0) const = 0; virtual void HackReport(Player* player, AdvancedAnticheatData* playerData) const = 0; }; template <ReportTypes type> class AnticheatCheckBase : public AnticheatCheck { public: bool OnCheck(Player* /*player*/, AdvancedAnticheatData* /*playerData*/, MovementInfo const& /*movementInfo*/, uint16 /*opcode = 0*/) const override { ASSERT(false && "AnticheatCheckBase::OnCheck called directly"); return false; } void HackReport(Player* player, AdvancedAnticheatData* playerData) const final override; }; #define sAdvancedAnticheatMgr AdvancedAnticheatMgr::Instance() #endif
const { useState, useEffect } = require("react"); const useTextToSpeech = () => { const [inputText, setInputText] = useState(""); const [spokenText, setSpokenText] = useState(""); const [utterance, setUtterance] = useState(null); const [voice, setVoice] = useState(null); console.log("voice", voice); // useEffect(() => { // // const voices = speechSynthesis.getVoices(); // // console.log("voices", voices); // // const femaleVoice = voices.find( // // (v) => v.lang === "en-US" && v.gender === "female" // // ); // // if (femaleVoice) { // // setVoice(femaleVoice); // // } // if(window.speechSynthesis){ // handleVoiceChange() // } // }, []); // const handleVoiceChange = () => { // const voices = speechSynthesis.getVoices(); // const femaleVoice = voices.find( // (v) => v.lang === "en-US" && v.gender === "female" // ); // console.log('voices',voices) // if (femaleVoice) { // setVoice(femaleVoice); // } // }; const speakText = (text) => { const newUtterance = new SpeechSynthesisUtterance(text); speechSynthesis.speak(newUtterance); const femaleVoice = null; setUtterance(newUtterance); setSpokenText(text); return newUtterance; }; const handleInputChange = (event) => { setInputText(event.target.value); }; const stopSpeaking = () => { if (utterance) { speechSynthesis.cancel(utterance); setUtterance(null); setSpokenText(""); } }; const handleSpeakButtonClick = () => { stopSpeaking(); // Stop any currently playing speech before starting new speech speakText(inputText); }; return { inputText, spokenText, handleInputChange, handleSpeakButtonClick, setInputText, stopSpeaking, }; }; export default useTextToSpeech;
package nasa.apod.single.vm import androidx.lifecycle.SavedStateHandle import app.cash.turbine.test import io.mockk.coEvery import io.mockk.mockk import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import kotlinx.datetime.LocalDate import kotlinx.datetime.Month import nasa.apod.data.repo.FailureResult import nasa.apod.data.repo.SingleApodRepository import nasa.apod.data.repo.SingleLoadResult import nasa.apod.model.ApodNavButtonsState import nasa.apod.model.EARLIEST_APOD_DATE import nasa.apod.nav.ApodScreenConfig import nasa.core.model.ApiKey import nasa.core.model.Calendar import nasa.core.url.UrlOpener import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertTrue @RunWith(RobolectricTestRunner::class) class ApodSingleViewModelTest { // real private lateinit var viewModel: ApodSingleViewModel private lateinit var apiKeyProvider: ApiKey.Provider private lateinit var calendar: Calendar private lateinit var savedStateHandle: SavedStateHandle // mock private lateinit var repository: SingleApodRepository private lateinit var urlOpener: UrlOpener @Before fun before() { apiKeyProvider = ApiKey.Provider { flowOf(API_KEY) } calendar = Calendar { TODAY } savedStateHandle = SavedStateHandle() repository = mockk() urlOpener = mockk(relaxed = true) buildViewModel() } @Test fun `Loading random day`() = runTest { viewModel.state.test { // Given the repo is set to return an item successfully coEvery { repository.loadRandom(API_KEY) } returns SingleLoadResult.Success(EXAMPLE_ITEM_1) assertEquals(ScreenState.Inactive, awaitItem()) // When we load with random config viewModel.load(API_KEY, ApodScreenConfig.Random()) assertEquals(ScreenState.Loading(date = null, API_KEY), awaitItem()) testScheduler.advanceUntilIdle() // Then we get a success state assertEquals( expected = ScreenState.Success(EXAMPLE_ITEM_1, API_KEY), actual = awaitItem(), ) // and the saved state is updated with the loaded date assertEquals( expected = EXAMPLE_ITEM_1.date.toString(), actual = savedStateHandle.get<String>("mostRecentDate"), ) expectNoEvents() cancelAndIgnoreRemainingEvents() } } @Test fun `Loading today`() = runTest { viewModel.state.test { // Given the repo is set to return the data successfully coEvery { repository.loadToday(API_KEY) } returns SingleLoadResult.Success(EXAMPLE_ITEM_1) assertEquals(ScreenState.Inactive, awaitItem()) // When we load with today config viewModel.load(API_KEY, ApodScreenConfig.Today) assertEquals(ScreenState.Loading(date = null, API_KEY), awaitItem()) testScheduler.advanceUntilIdle() // Then we get a success state assertEquals( expected = ScreenState.Success(EXAMPLE_ITEM_1, API_KEY), actual = awaitItem(), ) // and the saved state is updated with the loaded date assertEquals( expected = EXAMPLE_ITEM_1.date.toString(), actual = savedStateHandle.get<String>("mostRecentDate"), ) expectNoEvents() cancelAndIgnoreRemainingEvents() } } @Test fun `Handle load failure`() = runTest { viewModel.state.test { // Given the repo is set to return the data successfully val errorMessage = "foobar" coEvery { repository.loadToday(API_KEY) } returns FailureResult.OutOfRange(errorMessage) assertEquals(ScreenState.Inactive, awaitItem()) // When we load the data viewModel.load(API_KEY, ApodScreenConfig.Today) assertEquals(ScreenState.Loading(date = null, API_KEY), awaitItem()) testScheduler.advanceUntilIdle() // Then we get a failure state val item = awaitItem() assertIs<ScreenState.Failed>(item) assertTrue(item.message.contains(errorMessage)) // and the saved state is NOT updated with anything, because the request failed and we didn't supply a specific // date assertFalse(savedStateHandle.contains("mostRecentDate")) expectNoEvents() cancelAndIgnoreRemainingEvents() } } @Test fun `Reload previous date, even if in random config`() = runTest { // Given the repo is set to return the data successfully val twelfthOfApril = LocalDate(year = 2024, month = Month.APRIL, dayOfMonth = 12) coEvery { repository.loadSpecific(API_KEY, twelfthOfApril) } returns SingleLoadResult.Success(EXAMPLE_ITEM_1) // and the saved state has a previously-loaded date saved. This happens if we selected random, so if we go back // to this screen from the nav stack, it'll reload the same random item savedStateHandle["mostRecentDate"] = twelfthOfApril.toString() buildViewModel() viewModel.state.test { assertEquals(ScreenState.Inactive, awaitItem()) // When we load with a random config viewModel.load(API_KEY, ApodScreenConfig.Random()) // then we start loading the previously-loaded date, not a new random one assertEquals(ScreenState.Loading(twelfthOfApril, API_KEY), awaitItem()) testScheduler.advanceUntilIdle() // and we get a success state assertEquals( expected = ScreenState.Success(EXAMPLE_ITEM_1, API_KEY), actual = awaitItem(), ) expectNoEvents() cancelAndIgnoreRemainingEvents() } } @Test fun `Handle null API key`() = runTest { // Given we have no API key saved apiKeyProvider = ApiKey.Provider { flowOf(null) } buildViewModel() testScheduler.advanceUntilIdle() viewModel.state.test { // Then the UI is updated to tell the user assertEquals(ScreenState.NoApiKey(null), awaitItem()) expectNoEvents() cancelAndIgnoreRemainingEvents() } } @Test fun `Loading the current date disables the next button`() = runTest { // Given the current date is in May val firstOfMay = LocalDate(year = 2024, month = Month.MAY, dayOfMonth = 1) calendar = Calendar { firstOfMay } buildViewModel() // and we can load data from May val item = EXAMPLE_ITEM_1.copy(date = firstOfMay) coEvery { repository.loadSpecific(API_KEY, firstOfMay) } returns SingleLoadResult.Success(item) viewModel.navButtonsState.test { // no data loaded yet, so both disabled assertEquals(ApodNavButtonsState.BothDisabled, awaitItem()) // When we load data viewModel.load(API_KEY, ApodScreenConfig.Specific(firstOfMay)) testScheduler.advanceUntilIdle() // Then the next button is disabled, since there isn't an available date after this one assertEquals( actual = awaitItem(), expected = ApodNavButtonsState(enablePrevious = true, enableNext = false), ) } } @Test fun `Loading the earliest day disables the previous button`() = runTest { // Given we can load data from the earliest day val item = EXAMPLE_ITEM_1.copy(date = EARLIEST_APOD_DATE) coEvery { repository.loadSpecific(API_KEY, EARLIEST_APOD_DATE) } returns SingleLoadResult.Success(item) viewModel.navButtonsState.test { // no data loaded yet, so both disabled assertEquals(ApodNavButtonsState.BothDisabled, awaitItem()) // When we load data viewModel.load(API_KEY, ApodScreenConfig.Specific(EARLIEST_APOD_DATE)) testScheduler.advanceUntilIdle() // Then the previous button is disabled, since there isn't an available date before this one assertEquals( actual = awaitItem(), expected = ApodNavButtonsState(enablePrevious = false, enableNext = true), ) } } private fun buildViewModel() { viewModel = ApodSingleViewModel( repository = repository, urlOpener = urlOpener, apiKeyProvider = apiKeyProvider, calendar = calendar, savedState = savedStateHandle, ) } private companion object { val API_KEY = ApiKey(value = "my-api-key") val TODAY = LocalDate.parse("2024-05-03") } }
import logging from atm.application.dto import BankAccountRead from atm.application.dto import BankAccountUpdate from atm.application.dto import BankCustomerCreate from atm.application.dto import BankOperationCreate from atm.application.dto import BankOperationRead from atm.application.dto import DepositRequest from atm.application.dto import OperationShortResponse from atm.application.exceptions import CustomerNotExist from .base import BaseHandler _logger = logging.getLogger(__name__) class Deposit(BaseHandler): async def execute( self, input_data: DepositRequest ) -> OperationShortResponse: async with self._uow: try: customer = await self._customer_service.get_by_fullname( customer_first_name=input_data.first_name, customer_last_name=input_data.last_name ) _logger.info( f"The customer '{customer.id}' requested " f"a deposit operation in the amount " f"of '{input_data.amount}'" ) except CustomerNotExist: _logger.info( f"A customer '{input_data.first_name} " f"{input_data.last_name}' does not exist" ) new_customer_data = BankCustomerCreate( first_name=input_data.first_name, last_name=input_data.last_name ) customer = await self._customer_service.create( create_data=new_customer_data ) _logger.info( f"Customer '{customer.first_name} {customer.last_name}' " f"has been registered with ID '{customer.id}'" ) account_update_data = BankAccountUpdate( id=customer.bank_account_id, balance=(customer.bank_account.balance + input_data.amount) ) updated_account = await self._update_bank_account( update_data=account_update_data, ) _logger.info( f"Deposit operation for customer '{customer.id}' " "was successful" ) operation_register_data = BankOperationCreate( amount=input_data.amount, bank_account_id=updated_account.id, bank_customer_id=customer.id, bank_operation_type=input_data.operation_type ) operation = await self._register_bank_operation( operation_register_data=operation_register_data ) _logger.info( f"Deposit operation for customer '{customer.id}' " f"was registered" ) return OperationShortResponse( created_at=operation.created_at, bank_operation_type=operation.bank_operation_type, amount=operation.amount, current_balance=updated_account.balance ) async def _update_bank_account( self, update_data: BankAccountUpdate ) -> BankAccountRead: updated_account = await self._account_service.update( update_data=update_data ) return updated_account async def _register_bank_operation( self, operation_register_data: BankOperationCreate ) -> BankOperationRead: operation = await self._operation_service.create( create_data=operation_register_data ) return operation
from fastapi import APIRouter, Depends, Body from fastapi.responses import JSONResponse from app.models import Product, Inventory from sqlalchemy.orm import Session from datetime import datetime from app.db import get_db from typing import Optional router = APIRouter() LOW_STOCK_THRESHOLD = 10 @router.get("/inventory/") async def get_inventory_status(low_stock_alert: bool = False, db: Session = Depends(get_db)): inventories = db.query(Inventory, Product.name).join(Product).all() if not inventories: return JSONResponse(content={"error": "No inventory records found."}, status_code=404) results = [{"product_name": item[1], "quantity": item[0].quantity} for item in inventories] if low_stock_alert: results = [item for item in results if item["quantity"] <= LOW_STOCK_THRESHOLD] return results @router.put("/inventory/{product_id}") async def update_inventory( product_id: int = None, quantity: Optional[int] = Body(None, embed=True), db: Session = Depends(get_db) ): product = db.query(Product).filter(Product.id == product_id).first() if not product: return JSONResponse(content={"error": f'Product with id {product_id} not found'}) if not quantity: return JSONResponse(content={"error": "Quantity is not passed"}) new_inventory = Inventory(product_id=product_id, quantity=quantity, created_at=datetime.now()) db.add(new_inventory) db.commit() return {"message": f"Inventory for product {product.name} updated to {quantity}."} @router.get("/inventory/track/{product_id}") async def track_inventory_changes(product_id: int, db: Session = Depends(get_db)): product = db.query(Product).filter(Product.id == product_id).first() if not product: return JSONResponse(content={"error": f'Product with id {product_id} not found'}) inventory_changes = db.query(Inventory).filter(Inventory.product_id == product_id).order_by( Inventory.created_at.desc()).all() results = [{"date": item.created_at, "quantity": item.quantity} for item in inventory_changes] return results
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover"/> <meta name="description" content="A PERT chart: a diagram for visualizing and analyzing task dependencies and bottlenecks."/> <link rel="stylesheet" href="../assets/css/style.css"/> <!-- Copyright 1998-2023 by Northwoods Software Corporation. --> <title>PERT chart</title> </head> <body> <!-- This top nav is not part of the sample code --> <nav id="navTop" class="w-full z-30 top-0 text-white bg-nwoods-primary"> <div class="w-full container max-w-screen-lg mx-auto flex flex-wrap sm:flex-nowrap items-center justify-between mt-0 py-2"> <div class="md:pl-4"> <a class="text-white hover:text-white no-underline hover:no-underline font-bold text-2xl lg:text-4xl rounded-lg hover:bg-nwoods-secondary " href="../"> <h1 class="my-0 p-1 ">GoJS</h1> </a> </div> <button id="topnavButton" class="rounded-lg sm:hidden focus:outline-none focus:ring" aria-label="Navigation"> <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6"> <path id="topnavOpen" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path> <path id="topnavClosed" class="hidden" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path> </svg> </button> <div id="topnavList" class="hidden sm:block items-center w-auto mt-0 text-white p-0 z-20"> <ul class="list-reset list-none font-semibold flex justify-end flex-wrap sm:flex-nowrap items-center px-0 pb-0"> <li class="p-1 sm:p-0"><a class="topnav-link" href="../learn/">Learn</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="../samples/">Samples</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="../intro/">Intro</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="../api/">API</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="https://www.nwoods.com/products/register.html">Register</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="../download.html">Download</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="https://forum.nwoods.com/c/gojs/11">Forum</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="https://www.nwoods.com/contact.html" target="_blank" rel="noopener" onclick="getOutboundLink('https://www.nwoods.com/contact.html', 'contact');">Contact</a></li> <li class="p-1 sm:p-0"><a class="topnav-link" href="https://www.nwoods.com/sales/index.html" target="_blank" rel="noopener" onclick="getOutboundLink('https://www.nwoods.com/sales/index.html', 'buy');">Buy</a></li> </ul> </div> </div> <hr class="border-b border-gray-600 opacity-50 my-0 py-0" /> </nav> <div class="md:flex flex-col md:flex-row md:min-h-screen w-full max-w-screen-xl mx-auto"> <div id="navSide" class="flex flex-col w-full md:w-48 text-gray-700 bg-white flex-shrink-0"></div> <!-- * * * * * * * * * * * * * --> <!-- Start of GoJS sample code --> <script src="../release/go.js"></script> <div id="allSampleContent" class="p-4 w-full"> <script id="code"> function init() { // Since 2.2 you can also author concise templates with method chaining instead of GraphObject.make // For details, see https://gojs.net/latest/intro/buildingObjects.html const $ = go.GraphObject.make; // for more concise visual tree definitions // colors used, named for easier identification var blue = "#0288D1"; var pink = "#B71C1C"; var pinkfill = "#F8BBD0"; var bluefill = "#B3E5FC"; myDiagram = new go.Diagram("myDiagramDiv", { initialAutoScale: go.Diagram.Uniform, layout: $(go.LayeredDigraphLayout, { alignOption: go.LayeredDigraphLayout.AlignAll }) }); // The node template shows the activity name in the middle as well as // various statistics about the activity, all surrounded by a border. // The border's color is determined by the node data's ".critical" property. // Some information is not available as properties on the node data, // but must be computed -- we use converter functions for that. myDiagram.nodeTemplate = $(go.Node, "Auto", $(go.Shape, "Rectangle", // the border { fill: "white", strokeWidth: 2 }, new go.Binding("fill", "critical", b => b ? pinkfill : bluefill), new go.Binding("stroke", "critical", b => b ? pink : blue)), $(go.Panel, "Table", { padding: 0.5 }, $(go.RowColumnDefinition, { column: 1, separatorStroke: "black" }), $(go.RowColumnDefinition, { column: 2, separatorStroke: "black" }), $(go.RowColumnDefinition, { row: 1, separatorStroke: "black", background: "white", coversSeparators: true }), $(go.RowColumnDefinition, { row: 2, separatorStroke: "black" }), $(go.TextBlock, // earlyStart new go.Binding("text", "earlyStart"), { row: 0, column: 0, margin: 5, textAlign: "center" }), $(go.TextBlock, new go.Binding("text", "length"), { row: 0, column: 1, margin: 5, textAlign: "center" }), $(go.TextBlock, // earlyFinish new go.Binding("text", "", d => (d.earlyStart + d.length).toFixed(2)), { row: 0, column: 2, margin: 5, textAlign: "center" }), $(go.TextBlock, new go.Binding("text", "text"), { row: 1, column: 0, columnSpan: 3, margin: 5, textAlign: "center", font: "bold 14px sans-serif" }), $(go.TextBlock, // lateStart new go.Binding("text", "", d => (d.lateFinish - d.length).toFixed(2)), { row: 2, column: 0, margin: 5, textAlign: "center" }), $(go.TextBlock, // slack new go.Binding("text", "", d => (d.lateFinish - (d.earlyStart + d.length)).toFixed(2)), { row: 2, column: 1, margin: 5, textAlign: "center" }), $(go.TextBlock, // lateFinish new go.Binding("text", "lateFinish"), { row: 2, column: 2, margin: 5, textAlign: "center" }) ) // end Table Panel ); // end Node // The link data object does not have direct access to both nodes // (although it does have references to their keys: .from and .to). // This conversion function gets the GraphObject that was data-bound as the second argument. // From that we can get the containing Link, and then the Link.fromNode or .toNode, // and then its node data, which has the ".critical" property we need. // // But note that if we were to dynamically change the ".critical" property on a node data, // calling myDiagram.model.updateTargetBindings(nodedata) would only update the color // of the nodes. It would be insufficient to change the appearance of any Links. function linkColorConverter(linkdata, elt) { var link = elt.part; if (!link) return blue; var f = link.fromNode; if (!f || !f.data || !f.data.critical) return blue; var t = link.toNode; if (!t || !t.data || !t.data.critical) return blue; return pink; // when both Link.fromNode.data.critical and Link.toNode.data.critical } // The color of a link (including its arrowhead) is red only when both // connected nodes have data that is ".critical"; otherwise it is blue. // This is computed by the binding converter function. myDiagram.linkTemplate = $(go.Link, { toShortLength: 6, toEndSegmentLength: 20 }, $(go.Shape, { strokeWidth: 4 }, new go.Binding("stroke", "", linkColorConverter)), $(go.Shape, // arrowhead { toArrow: "Triangle", stroke: null, scale: 1.5 }, new go.Binding("fill", "", linkColorConverter)) ); // here's the data defining the graph var nodeDataArray = [ { key: 1, text: "Start", length: 0, earlyStart: 0, lateFinish: 0, critical: true }, { key: 2, text: "a", length: 4, earlyStart: 0, lateFinish: 4, critical: true }, { key: 3, text: "b", length: 5.33, earlyStart: 0, lateFinish: 9.17, critical: false }, { key: 4, text: "c", length: 5.17, earlyStart: 4, lateFinish: 9.17, critical: true }, { key: 5, text: "d", length: 6.33, earlyStart: 4, lateFinish: 15.01, critical: false }, { key: 6, text: "e", length: 5.17, earlyStart: 9.17, lateFinish: 14.34, critical: true }, { key: 7, text: "f", length: 4.5, earlyStart: 10.33, lateFinish: 19.51, critical: false }, { key: 8, text: "g", length: 5.17, earlyStart: 14.34, lateFinish: 19.51, critical: true }, { key: 9, text: "Finish", length: 0, earlyStart: 19.51, lateFinish: 19.51, critical: true } ]; var linkDataArray = [ { from: 1, to: 2 }, { from: 1, to: 3 }, { from: 2, to: 4 }, { from: 2, to: 5 }, { from: 3, to: 6 }, { from: 4, to: 6 }, { from: 5, to: 7 }, { from: 6, to: 8 }, { from: 7, to: 9 }, { from: 8, to: 9 } ]; myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray); // create an unbound Part that acts as a "legend" for the diagram myDiagram.add( $(go.Node, "Auto", $(go.Shape, "Rectangle", // the border { fill: "#EEEEEE" }), $(go.Panel, "Table", $(go.RowColumnDefinition, { column: 1, separatorStroke: "black" }), $(go.RowColumnDefinition, { column: 2, separatorStroke: "black" }), $(go.RowColumnDefinition, { row: 1, separatorStroke: "black", background: "#EEEEEE", coversSeparators: true }), $(go.RowColumnDefinition, { row: 2, separatorStroke: "black" }), $(go.TextBlock, "Early Start", { row: 0, column: 0, margin: 5, textAlign: "center" }), $(go.TextBlock, "Length", { row: 0, column: 1, margin: 5, textAlign: "center" }), $(go.TextBlock, "Early Finish", { row: 0, column: 2, margin: 5, textAlign: "center" }), $(go.TextBlock, "Activity Name", { row: 1, column: 0, columnSpan: 3, margin: 5, textAlign: "center", font: "bold 14px sans-serif" }), $(go.TextBlock, "Late Start", { row: 2, column: 0, margin: 5, textAlign: "center" }), $(go.TextBlock, "Slack", { row: 2, column: 1, margin: 5, textAlign: "center" }), $(go.TextBlock, "Late Finish", { row: 2, column: 2, margin: 5, textAlign: "center" }) ) // end Table Panel )); } window.addEventListener('DOMContentLoaded', init); </script> <div id="sample"> <div id="myDiagramDiv" style="border: solid 1px black; width:100%; height:400px"></div> <p> This sample demonstrates how to create a simple PERT chart. A PERT chart is a project management tool used to schedule and coordinate tasks within a project. </p> <p> Each node represents an activity and displays several pieces of information about each one. The node template is basically a <a>Panel</a> of type <a>Panel,Table</a> holding several <a>TextBlock</a>s that are data-bound to properties of the Activity, all surrounded by a rectangular border. The lines separating the text are implemented by setting the <a>RowColumnDefinition.separatorStroke</a> for two columns and two rows. The separators are not seen in the middle because the middle row of each node has its <a>RowColumnDefinition.background</a> set to white, and <a>RowColumnDefinition.coversSeparators</a> set to true. </p> <p> The "critical" property on the activity data object controls whether the node is drawn with a red brush or a blue one. There is a special converter that is used to determine the brush used by the links. </p> <p> The light blue legend is implemented by a separate Part implemented in a manner similar to the Node template. However it is not bound to data -- there is no JavaScript object in the model representing the legend. </p> </div> </div> <!-- * * * * * * * * * * * * * --> <!-- End of GoJS sample code --> </div> </body> <!-- This script is part of the gojs.net website, and is not needed to run the sample --> <script src="../assets/js/goSamples.js"></script> </html>
package com.github.angel.raa.modules.prototype.models; import com.github.angel.raa.modules.prototype.Prototype; import java.util.Arrays; public class Products implements Prototype { private String name; private String description; private int price; private String[] items; public Products(String name, String description, int price, String[] items) { this.name = name; this.description = description; this.price = price; this.items = items; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String[] getItems() { return items; } public void setItems(String[] items) { this.items = items; } @Override public Prototype clone() { Products products = new Products(this.name, this.description, this.price, this.items.clone()); return products; } @Override public Prototype deepClone() { return clone(); } @Override public Prototype reset() { return clone(); } @Override public String toString() { return Integer.toHexString( System.identityHashCode(this)) + "Products{" + "name='" + name + '\'' + ", description='" + description + '\'' + ", price='" + price + '\'' + ", items=" + Arrays.toString(items) + '}'; } }
@c @c COPYRIGHT (c) 1988-2008. @c On-Line Applications Research Corporation (OAR). @c All rights reserved. @c @c $Id$ @c @chapter Network Commands @section Introduction The RTEMS shell has the following network commands: @itemize @bullet @item @code{netstats} - obtain network statistics @item @code{ifconfig} - configure a network interface @item @code{route} - show or manipulate the IP routing table @end itemize @section Commands This section details the Network Commands available. A subsection is dedicated to each of the commands and describes the behavior and configuration of that command as well as providing an example usage. @c @c @c @page @subsection netstats - obtain network statistics @pgindex netstats @subheading SYNOPSYS: @example netstats [-Aimfpcut] @end example @subheading DESCRIPTION: This command is used to display various types of network statistics. The information displayed can be specified using command line arguments in various combinations. The arguments are interpreted as follows: @table @b @item -A print All statistics @item -i print Inet Routes @item -m print MBUF Statistics @item -f print IF Statistics @item -p print IP Statistics @item -c print ICMP Statistics @item -u print UDP Statistics @item -t print TCP Statistics @end table @subheading EXIT STATUS: This command returns 0 on success and non-zero if an error is encountered. @subheading NOTES: NONE @subheading EXAMPLES: The following is an example of how to use @code{netstats}: The following is an example of using the @code{netstats} command to print the IP routing table: @smallexample [/] $ netstats -i Destination Gateway/Mask/Hw Flags Refs Use Expire Interface default 192.168.1.14 UGS 0 0 0 eth1 192.168.1.0 255.255.255.0 U 0 0 1 eth1 192.168.1.14 00:A0:C8:1C:EE:28 UHL 1 0 1219 eth1 192.168.1.51 00:1D:7E:0C:D0:7C UHL 0 840 1202 eth1 192.168.1.151 00:1C:23:B2:0F:BB UHL 1 23 1219 eth1 @end smallexample The following is an example of using the @code{netstats} command to print the MBUF statistics: @smallexample [/] $ netstats -m ************ MBUF STATISTICS ************ mbufs:2048 clusters: 128 free: 63 drops: 0 waits: 0 drains: 0 free:1967 data:79 header:2 socket:0 pcb:0 rtable:0 htable:0 atable:0 soname:0 soopts:0 ftable:0 rights:0 ifaddr:0 control:0 oobdata:0 @end smallexample The following is an example of using the @code{netstats} command to print the print the interface statistics: @smallexample [/] $ netstats -f ************ INTERFACE STATISTICS ************ ***** eth1 ***** Ethernet Address: 00:04:9F:00:5B:21 Address:192.168.1.244 Broadcast Address:192.168.1.255 Net mask:255.255.255.0 Flags: Up Broadcast Running Active Multicast Send queue limit:50 length:1 Dropped:0 Rx Interrupts:889 Not First:0 Not Last:0 Giant:0 Non-octet:0 Bad CRC:0 Overrun:0 Collision:0 Tx Interrupts:867 Deferred:0 Late Collision:0 Retransmit Limit:0 Underrun:0 Misaligned:0 @end smallexample The following is an example of using the @code{netstats} command to print the print IP statistics: @smallexample [/] $ netstats -p ************ IP Statistics ************ total packets received 894 packets rcvd for unreachable dest 13 datagrams delivered to upper level 881 total ip packets generated here 871 @end smallexample The following is an example of using the @code{netstats} command to print the ICMP statistics: @smallexample [/] $ netstats -c ************ ICMP Statistics ************ Type 0 sent 843 number of responses 843 Type 8 received 843 @end smallexample The following is an example of using the @code{netstats} command to print the UDP statistics: @smallexample [/] $ netstats -u ************ UDP Statistics ************ @end smallexample The following is an example of using the @code{netstats} command to print the TCP statistics: @smallexample [/] $ netstats -t ************ TCP Statistics ************ connections accepted 1 connections established 1 segs where we tried to get rtt 34 times we succeeded 35 delayed acks sent 2 total packets sent 37 data packets sent 35 data bytes sent 2618 ack-only packets sent 2 total packets received 47 packets received in sequence 12 bytes received in sequence 307 rcvd ack packets 35 bytes acked by rcvd acks 2590 times hdr predict ok for acks 27 times hdr predict ok for data pkts 10 @end smallexample @subheading CONFIGURATION: @findex CONFIGURE_SHELL_NO_COMMAND_NETSTATS @findex CONFIGURE_SHELL_COMMAND_NETSTATS This command is included in the default shell command set. When building a custom command set, define @code{CONFIGURE_SHELL_COMMAND_NETSTATS} to have this command included. This command can be excluded from the shell command set by defining @code{CONFIGURE_SHELL_NO_COMMAND_NETSTATS} when all shell commands have been configured. @subheading PROGRAMMING INFORMATION: @findex rtems_shell_rtems_main_netstats The @code{netstats} is implemented by a C language function which has the following prototype: @example int rtems_shell_rtems_main_netstats( int argc, char **argv ); @end example The configuration structure for the @code{netstats} has the following prototype: @example extern rtems_shell_cmd_t rtems_shell_NETSTATS_Command; @end example @c @c @c @page @subsection ifconfig - configure a network interface @pgindex ifconfig @subheading SYNOPSYS: @example ifconfig ifconfig interface ifconfig interface [up|down] ifconfig interface [netmask|pointtopoint|broadcast] IP @end example @subheading DESCRIPTION: This command may be used to display information about the network interfaces in the system or configure them. @subheading EXIT STATUS: This command returns 0 on success and non-zero if an error is encountered. @subheading NOTES: Just like its counterpart on GNU/Linux and BSD systems, this command is complicated. More example usages would be a welcome submission. @subheading EXAMPLES: The following is an example of how to use @code{ifconfig}: @smallexample ************ INTERFACE STATISTICS ************ ***** eth1 ***** Ethernet Address: 00:04:9F:00:5B:21 Address:192.168.1.244 Broadcast Address:192.168.1.255 Net mask:255.255.255.0 Flags: Up Broadcast Running Active Multicast Send queue limit:50 length:1 Dropped:0 Rx Interrupts:5391 Not First:0 Not Last:0 Giant:0 Non-octet:0 Bad CRC:0 Overrun:0 Collision:0 Tx Interrupts:5256 Deferred:0 Late Collision:0 Retransmit Limit:0 Underrun:0 Misaligned:0 @end smallexample @subheading CONFIGURATION: @findex CONFIGURE_SHELL_NO_COMMAND_IFCONFIG @findex CONFIGURE_SHELL_COMMAND_IFCONFIG This command is included in the default shell command set. When building a custom command set, define @code{CONFIGURE_SHELL_COMMAND_IFCONFIG} to have this command included. This command can be excluded from the shell command set by defining @code{CONFIGURE_SHELL_NO_COMMAND_IFCONFIG} when all shell commands have been configured. @subheading PROGRAMMING INFORMATION: @findex rtems_shell_rtems_main_ifconfig The @code{ifconfig} is implemented by a C language function which has the following prototype: @example int rtems_shell_rtems_main_ifconfig( int argc, char **argv ); @end example The configuration structure for the @code{ifconfig} has the following prototype: @example extern rtems_shell_cmd_t rtems_shell_IFCONFIG_Command; @end example @c @c @c @page @subsection route - show or manipulate the ip routing table @pgindex route @subheading SYNOPSYS: @example route [subcommand] [args] @end example @subheading DESCRIPTION: This command is used to display and manipulate the routing table. When invoked with no arguments, the current routing information is displayed. When invoked with the subcommands @code{add} or @code{del}, then additional arguments must be provided to describe the route. Command templates include the following: @smallexample route [add|del] -net IP_ADDRESS gw GATEWAY_ADDRESS [netmask MASK] route [add|del] -host IP_ADDRESS gw GATEWAY_ADDRES [netmask MASK] @end smallexample When not provided the netmask defaults to @code{255.255.255.0} @subheading EXIT STATUS: This command returns 0 on success and non-zero if an error is encountered. @subheading NOTES: Just like its counterpart on GNU/Linux and BSD systems, this command is complicated. More example usages would be a welcome submission. @subheading EXAMPLES: The following is an example of how to use @code{route} to display, add, and delete a new route: @smallexample [/] $ route Destination Gateway/Mask/Hw Flags Refs Use Expire Interface default 192.168.1.14 UGS 0 0 0 eth1 192.168.1.0 255.255.255.0 U 0 0 1 eth1 192.168.1.14 00:A0:C8:1C:EE:28 UHL 1 0 1444 eth1 192.168.1.51 00:1D:7E:0C:D0:7C UHL 0 10844 1202 eth1 192.168.1.151 00:1C:23:B2:0F:BB UHL 2 37 1399 eth1 [/] $ route add -net 192.168.3.0 gw 192.168.1.14 [/] $ route Destination Gateway/Mask/Hw Flags Refs Use Expire Interface default 192.168.1.14 UGS 0 0 0 eth1 192.168.1.0 255.255.255.0 U 0 0 1 eth1 192.168.1.14 00:A0:C8:1C:EE:28 UHL 2 0 1498 eth1 192.168.1.51 00:1D:7E:0C:D0:7C UHL 0 14937 1202 eth1 192.168.1.151 00:1C:23:B2:0F:BB UHL 2 96 1399 eth1 192.168.3.0 192.168.1.14 UGS 0 0 0 eth1 [/] $ route del -net 192.168.3.0 gw 192.168.1.14 [/] $ route Destination Gateway/Mask/Hw Flags Refs Use Expire Interface default 192.168.1.14 UGS 0 0 0 eth1 192.168.1.0 255.255.255.0 U 0 0 1 eth1 192.168.1.14 00:A0:C8:1C:EE:28 UHL 1 0 1498 eth1 192.168.1.51 00:1D:7E:0C:D0:7C UHL 0 15945 1202 eth1 192.168.1.151 00:1C:23:B2:0F:BB UHL 2 117 1399 eth1 @end smallexample @subheading CONFIGURATION: @findex CONFIGURE_SHELL_NO_COMMAND_ROUTE @findex CONFIGURE_SHELL_COMMAND_ROUTE This command is included in the default shell command set. When building a custom command set, define @code{CONFIGURE_SHELL_COMMAND_ROUTE} to have this command included. This command can be excluded from the shell command set by defining @code{CONFIGURE_SHELL_NO_COMMAND_ROUTE} when all shell commands have been configured. @subheading PROGRAMMING INFORMATION: @findex rtems_shell_rtems_main_route The @code{route} is implemented by a C language function which has the following prototype: @example int rtems_shell_rtems_main_route( int argc, char **argv ); @end example The configuration structure for the @code{route} has the following prototype: @example extern rtems_shell_cmd_t rtems_shell_ROUTE_Command; @end example
/* 백준 1992번 쿼드 트리 풀이: 문제를 읽다가 방금 풀었던 2630 색종이 만들기와 동일한 문제임을 알았다. 역시 재귀로 풀면 된다. 입력 방식과 출력 방식만 다르게 하고 1->2->4->3 사분면 순서대로 잘 분할 정복해서 출력하면 풀 수 있는 문제이다. */ #include <iostream> using namespace std; int n; string board[64]; bool divisionCheck(int startX, int startY, int N) { //분할 해야 할지 아닐지 판단 for (int i = startY; i < startY + N; i++) { for (int j = startX; j < startX + N; j++) { if (board[startY][startX] != board[i][j]) { return true; } } } return false; } void division(int startX, int startY, int N) { //하지 않아도 되면 파랑 종이인지 하얀 종이인지 판단 후 재귀 탈출 if (!divisionCheck(startX, startY, N)) { if (board[startY][startX] == '0') cout << '0'; else if (board[startY][startX] == '1') cout << '1'; return; } //해야 하면 재귀 호출 cout << '('; division(startX, startY, N / 2); //1사분면 division(startX + N / 2, startY, N / 2); //2사분면 division(startX, startY + N / 2, N / 2); //4사분면 division(startX + N / 2, startY + N / 2, N / 2);//3사분면 cout << ')'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; //입력 값 세팅 for (int i = 0; i < n; i++) { cin >> board[i]; } division(0, 0, n); }
import os from Prompt_templates.constant import openai_key from langchain.llms import OpenAI import streamlit as st from langchain.prompts import PromptTemplate from langchain.chains import LLMChain ## streamlit framemwork os.environ['OPENAI_API_KEY']=openai_key st.title("Celebrity Search Result") input_text=st.text_input("Search The Topic You Want") ## OPENAI LLM MODEL llms=OpenAI(temperature=0.8) first_input_prompt=PromptTemplate( input_variables=['name'], template="Tell About You {name}" ) second_input_prompt=PromptTemplate( input_variables=['person'], template="When was {person} born" ) third_input_prompt=PromptTemplate( input_variables=['dob'], template="Mention five major event happend arround {dob} in india" ) chain=LLMChain(llm=llms,prompt=first_input_prompt,verbose=True,output_key='person') chain2=LLMChain(llm=llms,prompt=second_input_prompt,verbose=True,output_key='dob') chain3=LLMChain(llm=llms,prompt=third_input_prompt,verbose=True,output_key='decrption') from langchain.chains import SimpleSequentialChain from langchain.chains import SequentialChain # parent_chain=SimpleSequentialChain(chains=[chain,chain2],verbose=True) parent_chain_1=SequentialChain(chains=[chain,chain2,chain3],input_variables=['name'],output_variables=['person','dob','decrption'],verbose=True) if input_text: st.write(parent_chain_1({'name':input_text}))
// mat_a: row major matrix ( real components followed by imaginary components) // mat_b: row major matrix ( real components followed by imaginary components) // mat_num_row: number of rows in matrix, Assumption: mat_a and mat_b are square matrices-> number of rows=number of columns // mat_out: output matrix also row major order (real components followed by imaginary components) // how to use the module: // set the input values->raise valid signal for one clock period->raise start signal for the next clock period // ->wait for the done signal to be raised to read the output module mat_mult_uneven #(parameter out_row=2, parameter out_col=3, parameter common_factor=2)( input clk, input rst, input start, input valid, input [2*64*out_row*common_factor-1:0] mat_a, input [2*64*common_factor*out_col-1:0] mat_b, output reg [2*64*out_row*out_col-1:0] mat_out, output reg done); reg[2:0] state; // reg[63:0] a_real_local[mat_num_row*mat_num_row-1:0]; // a has to be rearranged in row major order // reg[63:0] a_imag_local[mat_num_row*mat_num_row-1:0]; // reg[63:0] b_real_local[mat_num_row*mat_num_row-1:0]; // b has to be rearranged in column major order // reg[63:0] b_imag_local[mat_num_row*mat_num_row-1:0]; // reg[63:0] out_real_local[mat_num_row*mat_num_row-1:0]; // reg[63:0] out_imag_local[mat_num_row*mat_num_row-1:0]; reg[64*out_row*common_factor-1:0] a_real_local; // a has to be rearranged in row major order reg[64*out_row*common_factor-1:0] a_imag_local; reg[64*common_factor*out_col-1:0] b_real_local; // b has to be rearranged in column major order reg[64*common_factor*out_col-1:0] b_imag_local; reg[64*out_row*out_col-1:0] out_real_local; reg[64*out_row*out_col-1:0] out_imag_local; reg[out_row*out_col-1:0] done_vecMult; reg[out_row*out_col-1:0] start_vecMult; reg[out_row*out_col-1:0] valid_vecMult; reg[out_row*out_col-1:0] out_read_ack_vecMult; genvar i,j; generate for(i=0;i<out_row;i=i+1) begin : name_block_1 for(j=0;j<out_col;j=j+1) begin : name_block_2 vec_mult_acc#(.mat_add_gen(common_factor)) m0(clk,rst, start_vecMult[i*out_col+j], valid_vecMult[i*out_col+j], a_real_local[(64*i*common_factor)+:64*common_factor], a_imag_local[(64*i*common_factor)+:64*common_factor], b_real_local[(64*j*common_factor)+:64*common_factor], b_imag_local[(64*j*common_factor)+:64*common_factor], out_read_ack_vecMult[i*out_col+j], out_real_local[64*(i*out_col+j)+:64], out_imag_local[64*(i*out_col+j)+:64], done_vecMult[i*out_col+j]); // assign b_real_local[64*(j*common_factor+i)+:64]=mat_b[64*(i*common_factor+j) +:64]; // rearrange the input into separate real and imaginary vectors // assign b_imag_local[64*(j*common_factor+i)+:64]=mat_b[64*(i*mat_num_row+j)+(64*out_col*common_factor)+:64]; end end for(i=0;i<common_factor;i++) begin : assign_b_1 for(j=0;j<out_col;j++) begin: assign_b_2 assign b_real_local[64*(j*common_factor+i)+:64]=mat_b[64*(i*out_col+j) +:64]; assign b_imag_local[64*(j*common_factor+i)+:64]=mat_b[64*(i*out_col+j)+(64*out_col*common_factor)+:64]; end end endgenerate assign a_real_local = mat_a[out_row*64*common_factor-1:0];// rearrange the input into separate real and imaginary vectors assign a_imag_local = mat_a[2*64*out_row*common_factor-1:out_row*64*common_factor]; always@(posedge clk) begin if(rst==1) begin // a_real_local<=0; // a_imag_local<=0; // b_real_local<=0; // b_imag_local<=0; // count<=0; state<=0; valid_vecMult<={(out_row*out_col){1'b0}}; start_vecMult<={(out_row*out_col){1'b0}}; done<=0; out_read_ack_vecMult<={(out_row*out_col){1'b0}}; end else begin case(state) 0: // if the inputs are valid, feed them to the vec_mult_acc modules begin done<=0; if(valid==1) begin valid_vecMult<={(out_row*out_col){1'b1}}; if(start==1) begin state<=1; end else begin state<=0; end end else begin valid_vecMult<={(out_row*out_col){1'b0}}; out_read_ack_vecMult<={(out_row*out_col){1'b0}}; state<=0; end end 1: // if the start command is given, start the vec_mult_acc modules' computation begin if(start==1) begin start_vecMult<={(out_row*out_col){1'b1}}; state<=2; end else begin start_vecMult<={(out_row*out_col){1'b0}}; state<=1; // if start command is not given wait in this state; end end 2: // wait for the vec_mult_acc modules' computation to be done begin if(done_vecMult=={(out_row*out_col){1'b1}}) begin mat_out[out_row*out_col*64-1:0]<=out_real_local; mat_out[2*64*out_row*out_col-1:out_row*out_col*64]<=out_imag_local; out_read_ack_vecMult<={(out_row*out_col){1'b1}}; start_vecMult<={(out_row*out_col){1'b0}}; valid_vecMult<={(out_row*out_col){1'b0}}; done<=1; state<=0; end else begin state<=2; end end endcase end end endmodule
import React, {useState} from 'react' import {useTranslation} from 'react-i18next' import {StyleSheet} from 'react-native' import {analytics} from '../../Analytics' import {UserModel} from '../../models' import {makeTextStyle} from '../../theme/appTheme' import {ms} from '../../utils/layout.utils' import {profileShortenSurname} from '../../utils/userHelper' import AppText from './AppText' import FloatingPopupView from './FloatingPopupView' import PrimaryButton from './PrimaryButton' interface PrivateMeetingProps { readonly meetingUser: UserModel readonly onArrangeMeetingPress: (user: UserModel) => void } const PrivateMeetingPopup: React.FC<PrivateMeetingProps> = (props) => { const {t} = useTranslation() const [isVisible, setModalVisible] = useState(true) const onArrangePress = () => { analytics.sendEvent('click_arrange_private_meeting_popup') props.onArrangeMeetingPress(props.meetingUser) } const onClose = () => { analytics.sendEvent('close_private_meeting_popup') setModalVisible(false) } return ( <FloatingPopupView handleOnClose={onClose} isVisible={isVisible}> <AppText style={styles.header}>{t('arrangeMeetingHeader')}</AppText> <AppText style={styles.message}> {t('arrangeMeetingMessage', { name: profileShortenSurname(props.meetingUser), })} </AppText> <PrimaryButton title={t('arrangeMeetingButton')} onPress={onArrangePress} /> </FloatingPopupView> ) } export default PrivateMeetingPopup const styles = StyleSheet.create({ header: { textAlign: 'center', ...makeTextStyle(ms(32), ms(38), 'bold'), }, message: { paddingTop: ms(16), paddingBottom: ms(24), textAlign: 'center', ...makeTextStyle(ms(15), ms(22), 'normal'), }, })
import { useState } from 'react' import { Theme, Size, Tokens, Profile } from './types' import { getContainerStyle, getTextStyle } from './utils' import { Web3Provider } from '@ethersproject/providers' import { ethers } from 'ethers' import { client } from './graphql/client' import { challenge, authenticate, profileByAddress, profiles as profilesQuery } from './graphql' import LensIcon from './LensIcon' declare global { interface Window{ ethereum?: any } } export function SignInWithLens({ provider, theme = Theme.default, size = Size.medium, title = 'Sign in With Lens', onSignIn, onError, containerStyle, textStyle, icon, iconBackgroundColor, iconForegroundColor } : { provider?: Web3Provider, theme?: Theme, size?: Size, title?: string, onSignIn: (tokens: Tokens, profile: Profile) => void, onError?: (error) => void, containerStyle?: any, textStyle?: any, icon?: any, iconBackgroundColor?: string, iconForegroundColor?: string }) { const [authTokens, setAuthTokens] = useState<Tokens | null>(null) const [authenticating, setAuthenticating] = useState<boolean>(false) const [profile, setProfile] = useState<Profile | undefined>() async function authenticateWithLens() { try { if (authenticating) return if (authTokens && profile) { onSignIn(authTokens, profile) return } setAuthenticating(true) if (!provider && window.ethereum) { provider = await getProvider() } if (!provider) { console.log('no provider configured...') setAuthenticating(false) return } const address = await getAddress() const { data: { challenge: { text }} } = await client .query(challenge, { address }) .toPromise() const signer = provider.getSigner() const signature = await signer.signMessage(text) const { data: { authenticate: tokens } } = await client .mutation(authenticate, { address, signature }) .toPromise() const { data: { defaultProfile } } = await client .query(profileByAddress, { address }) .toPromise() if (!defaultProfile) { const { data: { profiles: { items } } } = await client .query(profilesQuery, { address }) .toPromise() onSignIn(tokens, items[0]) setProfile(items[0]) } else { onSignIn(tokens, defaultProfile) setProfile(defaultProfile) } setAuthTokens(tokens) setAuthenticating(false) } catch (err) { setAuthenticating(false) console.log('error signing in with Lens...', err) if (onError) { onError(err) } } } async function getAddress() { const response = await window.ethereum.request({ method: 'eth_requestAccounts' }) return response[0] } async function getProvider() { try { await window.ethereum.request({ method: 'eth_requestAccounts' }) return new ethers.providers.Web3Provider(window.ethereum) } catch (err) { console.log('error connecting wallet and signing in...', err) } } return ( <button onClick={authenticateWithLens} style={containerStyle || getContainerStyle(theme, size)}> { icon || ( <LensIcon theme={theme} size={size} iconBackgroundColor={iconBackgroundColor} iconForegroundColor={iconForegroundColor} /> ) } <p style={textStyle || getTextStyle(theme, size)}>{title}</p> </button> ) }
import numpy as np from collections import defaultdict as D from collections import namedtuple as T from simplify.plotting import plot from simplify.MinHeap import MinHeap from typing import Dict, Tuple import random from simplify.utils.types import HeapStruct Solution = T("Solution", "error currentIdx currentOrder prevIdx prevOrder last_seg") Function = T("Function", "m b") def sol(error, currentIdx, currentOrder, prevIdx, prevOrder, last_seg): return Solution(error, currentIdx, currentOrder, prevIdx, prevOrder, last_seg) # please never round def heap(error: float, lineSegError: float, j: int, i: int, order: int, last_seg: bool): """ :param error: Total error :param lineSegError: Error from line segment from j to i :param j: Start of line :param i: End of line :param order: Currently evaluating k-best option from [0,j]. :param last_seg: Extrapolate the line to 0. :return: """ return HeapStruct(error, lineSegError, j, i, order, last_seg) sol0 = sol(0, 0, 0, 0, 0, True) VINF = sol(float("inf"), 0, 0, 0, 0, True) def _line_error(f: Function, X, Y): error = 0 for x, y in zip(X, Y): error += abs(f.m * x + f.b - y) ** 2 return error def _gen_line(x1, y1, x2, y2) -> Function: m = (y2 - y1) / (x2 - x1) b = y1 - m * x1 return Function(m, b) def segmented_least_squares_DP(X, Y, c, K) -> Dict[Tuple[int, int], Solution]: """ Least squares solution using segmented least squares DP algo. Parameters @ X:param, List of X values @ Y:param, List of Y values @ c:param, Punishment for more segments """ OPT = D(lambda: VINF) # Base case for only one point OPT[0, 0] = sol0 # Solve DP for i in range(1, len(X)): min_heap_top_k_solutions = MinHeap() # Size: O(2*i) for j in range(0, i): f = _gen_line(X[j], Y[j], X[i], Y[i]) # Keep other segments f_line_error = _line_error(f, X[j:i + 1], Y[j:i + 1]) f_segment_keep_error = OPT[j, 0].error + c + f_line_error heap_best_opt_j = heap(f_segment_keep_error, f_line_error, j, i, 0, last_seg=False) min_heap_top_k_solutions.insert(heap_best_opt_j) if j != 0: # Draw a line to the start f_total_line_error = _line_error(f, X[0:i + 1], Y[0:i + 1]) f_total_error = f_total_line_error + c heap_final_best_opt_j = heap(f_total_error, None, j, i, 0, last_seg=True) min_heap_top_k_solutions.insert(heap_final_best_opt_j) # For each possible j we have now found the best solution, let's search for the overall k best. if i == len(X) - 1: print("Stop!") idx_k = 0 while idx_k < K and min_heap_top_k_solutions.getMin() is not None: heapObj = min_heap_top_k_solutions.removeMin() if heapObj.last_seg: k_best = sol(error=heapObj.error, currentIdx=i, currentOrder=idx_k, prevIdx=heapObj.j, prevOrder=heapObj.order, last_seg=True) OPT[i, idx_k] = k_best else: k_best = sol(error=heapObj.error, currentIdx=i, currentOrder=idx_k, prevIdx=heapObj.j, prevOrder=heapObj.order, last_seg=False) OPT[i, idx_k] = k_best # Add the next best option from j to the heap if OPT[heapObj.j, heapObj.order + 1].error < float("inf"): new_total_error = OPT[heapObj.j, heapObj.order + 1].error + c + heapObj.lineSegError newHeapObj = heap(error=new_total_error, lineSegError=heapObj.lineSegError, j=heapObj.j, i=i, order=heapObj.order + 1, last_seg=False) min_heap_top_k_solutions.insert(newHeapObj) idx_k += 1 # Currently OPT[n-1] holds the best solution, if we require the algorithm to pick n, lets fix this. # Let's manually check all possible last segments, going through two points in the TS. # We will leave the DP for the area before last segment. min_heap_last_point = MinHeap() # Size: O(2*i) for i in range(1, len(X)): for j in range(0, i): # Line between i and j f = _gen_line(X[j], Y[j], X[i], Y[i]) # Find error j to end. f_line_out_error = _line_error(f, X[j:], Y[j:]) f_out_error = OPT[j, 0].error + c + f_line_out_error # OPTIMAL 0..j + c + rest heap_best_opt_j = heap(f_out_error, f_line_out_error, j, i, 0, last_seg=False) min_heap_last_point.insert(heap_best_opt_j) if j != 0: # Don't want duplicate # Find error 0 to end f_line_full_error = _line_error(f, X, Y) f_out_full_error = c + f_line_full_error # c + ALL heap_best_all_opt_j = heap(f_out_full_error, None, j, i, 0, last_seg=True) min_heap_last_point.insert(heap_best_all_opt_j) idx_k = 0 while idx_k < K and min_heap_last_point.getMin() is not None: last_heapObj = min_heap_last_point.removeMin() if last_heapObj.last_seg: k_best = sol(error=last_heapObj.error, currentIdx=last_heapObj.i, currentOrder=idx_k, prevIdx=last_heapObj.j, prevOrder=last_heapObj.order, last_seg=True) OPT[len(X) - 1, idx_k] = k_best if idx_k == 0: print("Error check", k_best.error, k_best.currentIdx, k_best.prevIdx) else: k_best = sol(error=last_heapObj.error, currentIdx=last_heapObj.i, currentOrder=idx_k, prevIdx=last_heapObj.j, prevOrder=last_heapObj.order, last_seg=False) OPT[len(X) - 1, idx_k] = k_best if idx_k == 0: print("Error check", k_best.error, k_best.currentIdx, k_best.prevIdx) # Add the next best option from j to the heap if OPT[last_heapObj.j, last_heapObj.order + 1].error < float("inf"): new_total_error = OPT[last_heapObj.j, last_heapObj.order + 1].error + c + last_heapObj.lineSegError newHeapObj = heap(error=new_total_error, lineSegError=last_heapObj.lineSegError, j=last_heapObj.j, i=last_heapObj.i, order=last_heapObj.order + 1, last_seg=False) min_heap_last_point.insert(newHeapObj) idx_k += 1 return OPT def solve(X, Y, c, K) -> Dict[Tuple[int, int], Solution]: OPT = segmented_least_squares_DP(X, Y, c, K) return OPT def extract_points(OPT: Dict[Tuple[int, int], Solution], k: int, X): """ :param OPT: The OPT dict :param k: k-th best solution :param X: timeseries :return: k-best approximation """ solution = OPT[len(X) - 1, k] list_of_points_last_first = [solution.currentIdx] while (not solution.last_seg) and (solution.currentIdx != solution.prevIdx): solution = OPT[solution.prevIdx, solution.prevOrder] list_of_points_last_first.append(solution.currentIdx) if solution.last_seg and solution.currentIdx != solution.prevIdx: list_of_points_last_first.append(solution.prevIdx) return list(reversed(list_of_points_last_first)) def solve_and_find_points(X, Y, c, K, saveImg=False): """ :param X: X_values in timeseries :param Y: Y_values in timeseries :param c: Punishment for more segments :param K: Top k best solution :param saveImg: :return: all_selected_points, all_ys """ print("Solve done") OPT = solve(X, Y, c, K) if saveImg: print("Making images...") print("Min error:", OPT[len(X) - 1, 0].error) all_selected_points = [] all_ys = [] for k in range(K): selected_points = extract_points(OPT, k, X) ys = [Y[i] for i in selected_points] if saveImg: print(f"{k}/{K}") plot(X, Y, selected_points, ys, fname=f"simplify/img/{k}") all_selected_points.append(selected_points) all_ys.append(ys) return all_selected_points, all_ys if __name__ == "__main__": random.seed(6) ts_x = list(range(20)) ts_y = [random.randint(-10, 10) for _ in range(len(ts_x))] my_c = 1 my_k = 10000 solve_and_find_points(ts_x, ts_y, my_c, my_k)
const express = require("express") const bodyParser = require("body-parser") const PORT = 3000 const date = require("./date") const app = express() app.use(bodyParser.urlencoded({ extended: true })) app.use(express.static("public")) app.set("view engine", "ejs") let newItems = ["Buy Food", "Cook Food", "Eat food"] let workItems = [] app.get("/", (req, res) => { const date2 = date.getDate() const day = date.getDay() const fullDate = day + "," + date2 res.render("list", { listTitle: fullDate, newListItems: newItems }) }) app.post("/", (req, res) => { if (req.body.list === "Work") { let item = req.body.newItem workItems.push(item) res.redirect("/work") } else { newItems.push(req.body.newItem) res.redirect("/") } }) app.get("/work", (req, res) => { res.render("list", { listTitle: "Work List", newListItems: workItems }) }) app.get("/about", (req, res) => { res.render("about") }) app.listen(PORT, () => { console.log(`Server running on port ${PORT}`) })
package com.tanhua.config.template; import cn.hutool.core.collection.CollUtil; import com.easemob.im.server.EMProperties; import com.easemob.im.server.EMService; import com.easemob.im.server.model.EMTextMessage; import com.tanhua.config.properties.HuanXinProperties; import lombok.extern.slf4j.Slf4j; import java.util.Set; @Slf4j public class HuanXinTemplate { private EMService emService; public HuanXinTemplate(HuanXinProperties properties) { EMProperties emProperties = EMProperties.builder() .setAppkey(properties.getAppkey()) .setClientId(properties.getClientId()) .setClientSecret(properties.getClientSecret()) .build(); emService = new EMService(emProperties); } //创建环信用户 public Boolean createUser(String username, String password) { try { //创建环信用户 emService.user().create(username.toLowerCase(), password) .block(); return true; } catch (Exception e) { e.printStackTrace(); log.error("创建环信用户失败~"); } return false; } //添加联系人 public Boolean addContact(String user, String contact) { try { //创建环信用户 emService.contact().add(user, contact) .block(); return true; } catch (Exception e) { log.error("添加联系人失败~"); } return false; } //删除联系人 public Boolean deleteContact(String username1, String username2) { try { //创建环信用户 emService.contact().remove(username1, username2) .block(); return true; } catch (Exception e) { log.error("删除联系人失败~"); } return false; } //发送消息 public Boolean sendMsg(String username, String content) { try { //接收人用户列表 Set<String> set = CollUtil.newHashSet(username); //文本消息 EMTextMessage message = new EMTextMessage().text(content); //发送消息 from:admin是管理员发送 emService.message().send( "admin", "users", set, message, null ).block(); return true; } catch (Exception e) { log.error("删除联系人失败~"); } return false; } }
<!doctype html> <head> <meta charset="UTF-8"> <meta name="Author" content="ninachow"> <meta name="Keywords" content="ninachow,blog"> <meta name="Description" content="ninachow 的博客首页,对前端开发都一些总结文章和作品"> <link rel='stylesheet' type='text/css' href='https://fonts.googleapis.com/css?family=Freckle+Face'> <link rel="stylesheet" type="text/css" href="../font/iconfont.css"> <link type="text/css" rel="stylesheet" href="../css/base.css"> <link type="text/css" rel="stylesheet" href="../css/main.css"> <link type="text/css" rel="stylesheet" href="../css/blogs.css"> <link rel="stylesheet" href="../highlight-stype/monokai-sublime.css"> <script src="../highlight-stype/highlight.pack.js"></script> <script>hljs.initHighlightingOnLoad();</script> <title>Ninachow blog</title> <style> h3{ font-size: 30px; } h3,strong{ font-weight: bolder; } </style> </head> <body> <header> <div class="h-title"> <img src="../images/myhead.jpg" alt="myhead" /> <hgroup> <h1>Ninachow的博客园</h1> <p>伊人是个攻城狮 / web前端开发 / HTML5 / CSS3 / Javascript</p> </hgroup> </div> </header> <nav> <ul> <li> <a href="../index.html">首页</a> </li> <li> <a href="workshow-HC.html">作品欣赏</a> <dd> <dl> <a href="workshow-HC.html">HTML/CSS</a> </dl> <dl> <a href="workshow-CJ.html">CSS3/JS</a> </dl> <dl> <a href="workshow-JS.html">Javascript</a> </dl> <dl> <a href="workshow-CP.html">Codepen</a> </dl> <dl> <a href="workshow-Other.html">Others</a> </dl> </dd> </li> <li> <a href="#">前端开发</a> </li> <li> <a href="#">时光机</a> </li> <li> <a href="#">关于我</a> </li> </ul> </nav> <section class="clearfix"> <aside> <div class="a-aboutme"> <h2>博客简介</h2> <img src="../images/aboutme.jpg" alt="aboutme"> <p>Ninachow 准前端开发工程师,目前就读于潭州教育,系统学习全栈开发。80后女青年,期待在前端领域占领一席之地。</p> <div class="otherlink"> <a href="https://github.com/ninachowcn" target="_blank"> <img src="../images/github-icon.png" alt="git"> </a> <a href="https://codepen.io/ninachow/" target="_blank"> <img src="../images/codepen-icon.png" alt="codepen"> </a> <a class="i-codecamp" href="https://codepen.io/ninachow/" target="_blank"> <img src="../images/freecodecamp.png" alt="codecamp"> </a> </div> </div> <div class="a-likelist a-listbox"> <p> <i class="iconfont icon-liebiao"></i>大家喜欢 </p> <ul> <li> <i class="iconfont icon-huore"></i> <a href="#">HTML5 常用标签</a> </li> <li> <i class="iconfont icon-huore"></i> <a href="#">CSS3 动画实现</a> </li> <li> <i class="iconfont icon-huore"></i> <a href="#">弹性盒子使用</a> </li> <li> <i class="iconfont icon-huore"></i> <a href="#">HTML5 新增标签及兼容性</a> </li> <li> <i class="iconfont icon-huore"></i> <a href="#">HTML5 常用标签HTML5 常用标签HTML5 常用标签HTML5 常用标签</a> </li> <li> <a href="#">HTML5 常用标签</a> </li> <li> <a href="#">CSS3 动画实现</a> </li> <li> <a href="#">弹性盒子使用</a> </li> <li> <a href="#">HTML5 新增标签及兼容性</a> </li> <li> <a href="#">HTML5 常用标签HTML5 常用标签HTML5 常用标签HTML5 常用标签</a> </li> </ul> </div> <div class="a-articlist a-listbox"> <p> <i class="iconfont icon-liebiao"></i>文章分类 </p> <ul class="clearfix"> <li> <a href="#">HTML/CSS <span>(5)</span> </a> </li> <li> <a href="#">HTML5 <span>(0)</span> </a> </li> <li> <a href="#">CSS3详解 <span>(0)</span> </a> </li> <li> <a href="#">Javascript <span>(0)</span> </a> </li> <li> <a href="#">jQuery <span>(0)</span> </a> </li> <li> <a href="#">Vus.js <span>(0)</span> </a> </li> <li> <a href="#">Angular.js <span>(0)</span> </a> </li> <li> <a href="#">Node.js <span>(0)</span> </a> </li> <li> <a href="#">wordpress <span>(0)</span> </a> </li> <li> <a href="#">Webpack <span>(0)</span> </a> </li> <li> <a href="#">W3C标准 <span>(0)</span> </a> </li> <li> <a href="#">作品欣赏 <span>(0)</span> </a> </li> <li> <a href="#">Github开源 <span>(0)</span> </a> </li> <li> <a href="#">WEB兼容性 <span>(0)</span> </a> </li> <li> <a href="#">网页设计 <span>(0)</span> </a> </li> </ul> </div> <div class="a-listbox a-webcount"> <p> <i class="iconfont icon-liebiao"></i>站点统计 </p> <ul> <li>更新: 2017年11月29日</li> <li>总访问量:12345次</li> <li>文章: 23篇</li> <li>分类: 14个</li> <li>标签: 77个</li> <li>运行: 26天</li> </ul> </div> </aside> <div class="maincontent"> <header class="m-box"> <a href="../index.html">首页</a> > <a href="../index.html">HTML/CSS</a> >CSS3 2D转换 </header> <div class="m-box"> <article> <div class="m-header"> <h2>CSS3 2D转换</h2> <div class="m-h-tags"> <span> <i class="iconfont icon-tixing"></i>2017年11月10日</span> <span> <i class="iconfont icon-shuru"></i>0 条评论</span> <span> <i class="iconfont icon-xiai"></i>0 喜欢</span> <span>作者:Nina</i> </span> </div> </div> <div class="m-content"> <!-- 文本内容 --> <h3>transform</h3> <p>CSS3 2d转换,可以移动,比例化,反过来,旋转,和拉伸元素。</p> <p>transform /* 一般写法 */</p> <p>-ms-transform /* IE 9 */, </p> <p>-webkit-transform /* Safari and Chrome */</p> <p> <ul> <li> <strong>transform : translate(xpx,ypx)</strong> 根据左(X轴)和顶部(Y轴)位置给定的参数,从当前元素位置移动。 </li> <li> <strong>transform : rotate(xdeg)</strong> 在一个给定度数顺时针旋转的元素(-360deg ~ +360deg)。负值是允许的,这样是元素逆时针旋转。 </li> <li> <strong>transform : scale(x,y)</strong> 该元素增加或减少的大小,取决于宽度(X轴)和高度(Y轴)的参数,通常取倍数值1,1.5,0.5等。 </li> <li> <strong>transform : skew(xdeg,ydeg)</strong> 包含两个参数值,分别表示X轴和Y轴倾斜的角度,如果第二个参数为空,则默认为0,参数为负表示向相反方向倾斜。skewX(xdeg);表示只在X轴(水平方向)倾斜。skewY(ydeg);表示只在Y轴(垂直方向)倾斜。 </li> <li> <strong>transform : matrix()</strong> matrix()方法和2D变换方法合并成一个。 matrix 方法有六个参数,包含旋转,缩放,移动(平移)和倾斜功能。 </li> </ul> </p> <em>当transform多个变化组合时,顺序不同,产生的结果也不同</em> <pre> <code class="css"> <!-- 放大和移动效果在运动的过程中相互影响,最后产生的结果也是不同的--> {transform: scale(2) translate(300px,100px);} {transform: translate(300px,100px) scale(2);} </code> </pre> <h3>transform-origin</h3> <p>改变转换的中心点,适用与2D,3D转换。</p> <p>transform-origin: (x-axis y-axis z-axis);【默认50% 50%】,效果等同于center center </p> <!-- 高亮区 --> <pre> <code class="css"> {transform-origin:20% 40%;} {transform-origin:20px 40px 10px;} </code> </pre> </div> <div class="m-footer"> <p>如果觉得这篇文章对您有帮助,请帮助本站成长</p> <img src="../images/zan.png" alt="👍" /> </div> </article> </div> </div> </section> <footer> <p>©2017 Ninachow 版权所有</p> <p>站长统计 | 今日IP[0] | 今日PV[1] | 昨日IP[1] | 昨日PV[1] | | 当前在线[1]</p> </footer> <script> // 对HTMLcode中的<>括号进行转换,才能显示 document.querySelectorAll("code").forEach(function (element) { element.innerHTML = element.innerHTML.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;"); }); </script> </body>
#include <string.h> #include <ctype.h> #include <cda.h> #include <stack_calc.h> typedef const char *CSTR_p_t; #define ADD (0) #define SUB (1) #define MUL (2) #define DIV (3) #define XOR (4) #define LOR (5) #define AND (6) #define LSH (7) #define RSH (8) #define SUM (9) static long stack[512]; static long *sptr = stack; static void push( int item ); static long pop( void ); static long getOperator( CSTR_p_t *str ); static CDA_BOOL_t getOperand( long *operand, CSTR_p_t *str ); static const char *skipWhite( const char *str ); static long xadd( int count ); static long xsum( int count ); static long xxor( int count ); static long xlor( int count ); static long xand( int count ); static long xlsh( int count ); static long xrsh( int count ); static long xsub( int count ); static long xmul( int count ); static long xdiv( int count ); static void push( int item ) { *sptr++ = item ; } static long pop( void ) { return *--sptr; } static long getOperator( CSTR_p_t *str ) { long rcode = 0; CSTR_p_t temp = *str; if ( strncmp( "add", temp, 3 ) == 0 ) rcode = ADD; else if ( strncmp( "sum", temp, 3 ) == 0 ) rcode = SUM; else if ( strncmp( "xor", temp, 3 ) == 0 ) rcode = XOR; else if ( strncmp( "lor", temp, 3 ) == 0 ) rcode = LOR; else if ( strncmp( "lsh", temp, 3 ) == 0 ) rcode = LSH; else if ( strncmp( "rsh", temp, 3 ) == 0 ) rcode = RSH; else if ( strncmp( "and", temp, 3 ) == 0 ) rcode = AND; else if ( strncmp( "sub", temp, 3 ) == 0 ) rcode = SUB; else if ( strncmp( "mul", temp, 3 ) == 0 ) rcode = MUL; else if ( strncmp( "div", temp, 3 ) == 0 ) rcode = DIV; else abort(); temp += 3; temp = skipWhite( temp ); if ( *temp++ != '(' ) abort(); temp = skipWhite( temp ); *str = temp; return rcode; } static CDA_BOOL_t getOperand( long *operand, CSTR_p_t *str ) { CDA_BOOL_t rcode = CDA_TRUE; CSTR_p_t temp = *str; if ( *temp == ')' ) { temp = skipWhite( ++temp ); rcode = CDA_FALSE; } else if ( isalpha( *temp ) ) *operand = StackCalc( *str, &temp ); else if ( isdigit( *temp ) || (*temp == '-') || (*temp == '+') ) { *operand = strtol( *str, (char **)&temp, 0 ); temp = skipWhite( temp ); } else abort(); if ( *temp == ',' ) { temp = skipWhite( ++temp ); if ( *temp == ')' ) abort(); } else skipWhite( temp ); *str = temp; return rcode; } static const char *skipWhite( const char *str ) { const char *temp = str; while ( isspace( *temp ) && (*temp != '\000') ) ++temp; return temp; } long StackCalc( const char *expr, const char **end ) { long rval = 0; long operator = 0; long operand = 0; int count = 0; CDA_BOOL_t working = CDA_TRUE; const char *temp = skipWhite( expr ); operator = getOperator( &temp ); while ( working ) { if ( getOperand( &operand, &temp ) ) { ++count; push( operand ); } else working = CDA_FALSE; } switch ( operator ) { case ADD: rval = xadd( count ); break; case SUB: rval = xsub( count ); break; case MUL: rval = xmul( count ); break; case DIV: rval = xdiv( count ); break; case XOR: rval = xxor( count ); break; case LOR: rval = xlor( count ); break; case AND: rval = xand( count ); break; case LSH: rval = xlsh( count ); break; case RSH: rval = xrsh( count ); break; case SUM: rval = xsum( count ); break; default: abort(); } if ( end != NULL ) *end = skipWhite( temp ); return rval; } static long xadd( int count ) { long rcode = 0; if ( count != 2 ) abort(); rcode = pop(); rcode += pop(); return rcode; } static long xsum( int count ) { long rcode = 0; int inx = 0; for ( inx = 0 ; inx < count ; ++inx ) rcode += pop(); return rcode; } static long xxor( int count ) { long rcode = 0; int inx = 0; for ( inx = 0 ; inx < count ; ++inx ) rcode ^= pop(); return rcode; } static long xlor( int count ) { long rcode = 0; int inx = 0; for ( inx = 0 ; inx < count ; ++inx ) rcode |= pop(); return rcode; } static long xand( int count ) { long rcode = 0; int inx = 0; if ( count > 0 ) rcode = pop(); for ( inx = 1 ; inx < count ; ++inx ) rcode &= pop(); return rcode; } static long xlsh( int count ) { long rcode = 0; unsigned long val = 0; unsigned long shift = 0; if ( count != 2 ) abort(); shift = (unsigned long)pop(); val = (unsigned long)pop(); rcode = (long)(val << shift ); return rcode; } static long xrsh( int count ) { long rcode = 0; unsigned long val = 0; unsigned long shift = 0; if ( count != 2 ) abort(); shift = (unsigned long)pop(); val = (unsigned long)pop(); rcode = (long)(val >> shift ); return rcode; } static long xsub( int count ) { long rcode = 0; if ( count != 2 ) abort(); rcode = pop(); rcode = pop() - rcode; return rcode; } static long xmul( int count ) { long rcode = 0; if ( count != 2 ) abort(); rcode = pop(); rcode *= pop(); return rcode; } static long xdiv( int count ) { long rcode = 0; if ( count != 2 ) abort(); rcode = pop(); rcode = pop() / rcode; return rcode; }
import asyncHandler from "express-async-handler"; import bcrypt from "bcryptjs"; import { User } from "./../../models/User/User.js"; import { generateToken } from "../../utils/generateToken.js"; import { getTokenFromHeader } from "../../utils/getTokenFromHeader.js"; import { verifyToken } from "../../utils/verifyToken.js"; // @desk Register user // @route POST api/v1/users/register // @access Private/Admin export const registerUserCtrl = asyncHandler(async (req, res, next) => { const { fullname, email, password } = req.body; // Check user already exist const userExist = await User.findOne({ email }); if (userExist) { throw new Error("User Already Existed.."); } // Hash Passwprd const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(password, salt); // Create user const user = await User.create({ fullname, email, password: hashedPassword, }); res .status(200) .json({ status: "success", message: "User registered...", data: user }); }); // @desk Login user // @route POST api/v1/users/login // @access Public export const loginUserCtrl = asyncHandler(async (req, res) => { const { email, password } = req.body; // Find the user in DB is exist or not const userFound = await User.findOne({ email }); if (userFound && (await bcrypt.compare(password, userFound?.password))) { const { password, ...other } = userFound._doc; return res.json({ status: "Success", message: "Logged in successfully.", data: { ...other, token: generateToken(userFound?._id) }, }); } else { throw new Error("Invalid Credentials."); } }); // @desk Get user profile // @route GET api/v1/users/profile // @access Private export const getUserProfile = asyncHandler(async (req, res) => { // Find the User const user = await User.findById(req.userAuthId).populate('orders') // console.log(req); res.json({ message: "Welcome to profile page.", user }); }); // @desk Update Shipping Address // @route GET api/v1/users/update/shipping // @access Private export const updateShippingAddress = asyncHandler(async (req, res) => { const { firstname, lastname, address, city, postalCode, province, country, phone, } = req.body; const user = await User.findByIdAndUpdate( req.userAuthId, { shippingAddress: { firstname, lastname, address, city, postalCode, province, country, phone, }, hasShippingAddress: true, }, { new: true } ); // Send the shipping address response res.json({ status:true, message: "User shipping address has been updated.", user }); });
import { useState, useEffect } from "react"; import { Link } from "react-router-dom"; import "../style/Mod.css"; import blogFetch from "../axios/config"; import axios from "axios"; import Modal from "react-modal"; import MeuModal from "../components/modal"; // ... Modal.setAppElement("#root"); const Mod = () => { const [posts, setPosts] = useState([]); const [showModal, setShowModal] = useState(false); const [selectedPost, setSelectedPost] = useState(null); const getTodos = async () => {// atualização da pagina try { const response = await blogFetch.get("postcontroller/todos"); const data = response.data; setPosts(data); } catch (error) { console.log(error); } }; useEffect(() => { // recarrega pagina getTodos(); }, []); function deletePost(id) { // deleta os poster blogFetch .delete(`postcontroller/${id}`) .then((response) => { console.log(response.data); }) .catch((error) => { console.error(error); }); setPosts(posts.filter((post) => post.id !== id)); } function editaPoster(event) { // altera os poster event.preventDefault(); const form = event.target; const updatedPost = { id: selectedPost.id, titulo: form.titulo.value, conteudo: form.conteudo.value, }; blogFetch .put(`postcontroller/alt`, updatedPost) .then((response) => { getTodos(); console.log(response.data); }) .catch((error) => { console.error(error); }); setShowModal(false); } return ( <div className="mod"> <h1> Ultimos Posters </h1> {posts.length === 0 ? ( <p> Não a poster no momento </p> ) : ( posts.map((post) => ( <div className="mod" key={post.id}> <h2> {post.titulo} <button className="btnAlt" onClick={() => { setSelectedPost(post); setShowModal(true); }} > Alterar </button> <button className="btnDel" onClick={() => deletePost(post.id)}> Deletar </button> </h2> <p>{post.conteudo} </p> </div> )) )} {showModal && selectedPost && ( <MeuModal showModal={showModal} setShowModal={() => setShowModal(false)} editaPoster={editaPoster} selectedPost={selectedPost}/> )} </div> ); }; export default Mod
require "application_system_test_case" class TasksTest < ApplicationSystemTestCase setup do @task = tasks(:one) end test "visiting the index" do visit tasks_url assert_selector "h1", text: "Tasks" end test "should create task" do visit tasks_url click_on "New task" fill_in "Email", with: @task.email fill_in "First name", with: @task.first_name fill_in "Github", with: @task.github fill_in "Last name", with: @task.last_name fill_in "Linkedin", with: @task.linkedIn fill_in "Phone", with: @task.phone click_on "Create Task" assert_text "Task was successfully created" click_on "Back" end test "should update Task" do visit task_url(@task) click_on "Edit this task", match: :first fill_in "Email", with: @task.email fill_in "First name", with: @task.first_name fill_in "Github", with: @task.github fill_in "Last name", with: @task.last_name fill_in "Linkedin", with: @task.linkedIn fill_in "Phone", with: @task.phone click_on "Update Task" assert_text "Task was successfully updated" click_on "Back" end test "should destroy Task" do visit task_url(@task) click_on "Destroy this task", match: :first assert_text "Task was successfully destroyed" end end
// // CheckoutView.swift // SwfitUI-CupcakeCorner // // Created by JimmyChao on 2024/4/21. // import SwiftUI struct CheckoutView: View { let code = Locale.current.currency?.identifier ?? "USD" @Bindable var viewModel: ViewModel var body: some View { ScrollView { VStack { // Image AsyncImage( url: URL(string: "https://hws.dev/img/cupcakes@3x.jpg"), scale: 3) { image in image.resizable().scaledToFit() } placeholder: { ProgressView() } .frame(height: 233) .frame(maxWidth: .infinity).padding() // Cost Text("The total cost is \(viewModel.order.cost.formatted(.currency(code: "\(code)")))") // Button Button("Checkout") { Task { await viewModel.placeOrder() } }.buttonStyle(BorderedButtonStyle()) } } .navigationTitle("Checkout view") .navigationBarTitleDisplayMode(.inline) .scrollBounceBehavior(.basedOnSize) .alert(viewModel.alertTitle, isPresented: $viewModel.showingAlert) { Button("Okay") { } } message: { Text(viewModel.alertMessage) } } }
import 'package:hyper_ui/core.dart'; import 'package:flutter/material.dart'; class QAutoComplete extends StatefulWidget { final String label; final String? hint; final List<Map<String, dynamic>> items; final String? Function(String? item)? validator; final Function(dynamic value, String? label) onChanged; const QAutoComplete({ Key? key, required this.label, required this.items, this.validator, this.hint, required this.onChanged, }) : super(key: key); @override State<QAutoComplete> createState() => _QAutoCompleteState(); } class _QAutoCompleteState extends State<QAutoComplete> { List<Map<String, dynamic>> items = []; @override void initState() { super.initState(); for (var item in widget.items) { items.add(Map.from(item)); } } @override Widget build(BuildContext context) { return LayoutBuilder(builder: (context, constraints) { return FormField( initialValue: false, // validator: (value) => widget.validator!(items), enabled: true, builder: (field) { return Autocomplete<Map>( fieldViewBuilder: (context, textEditingController, focusNode, onFieldSubmitted) { return TextFormField( controller: textEditingController, focusNode: focusNode, onFieldSubmitted: (text) => onFieldSubmitted(), validator: widget.validator, decoration: InputDecoration( labelText: widget.label, errorText: field.errorText, // border: InputBorder.none, suffixIcon: const Icon(Icons.search), helperText: widget.hint, ), ); }, initialValue: TextEditingValue( text: items.first["label"], ), onSelected: (Map map) { //selected value String? label = map["label"]; dynamic value = map["value"]; widget.onChanged(value, label); }, optionsBuilder: (TextEditingValue textEditingValue) { if (textEditingValue.text == '') { return const Iterable<Map>.empty(); } return items.where((Map option) { return option["label"] .toString() .toLowerCase() .contains(textEditingValue.text.toLowerCase()); }); }, displayStringForOption: (option) { return option["label"]; }, optionsViewBuilder: (context, onSelected, options) => Align( alignment: Alignment.topLeft, child: Material( color: Colors.transparent, child: ClipRRect( borderRadius: const BorderRadius.vertical( bottom: Radius.circular(4.0), ), child: Container( width: constraints.biggest.width, // width: MediaQuery.of(context).size.width, margin: const EdgeInsets.only(top: 10.0), child: Wrap( children: [ Container( decoration: BoxDecoration( // color: Colors.grey[100], color: Theme.of(globalContext) .scaffoldBackgroundColor, borderRadius: const BorderRadius.all( Radius.circular(12.0), ), border: Border.all( width: 1.0, color: Theme.of(context) .scaffoldBackgroundColor .withOpacity(0.4), ), ), child: ListView.builder( padding: EdgeInsets.zero, itemCount: options.length, shrinkWrap: true, itemBuilder: (BuildContext context, int index) { bool selected = AutocompleteHighlightedOption.of(context) == index; Map option = options.elementAt(index); return InkWell( onTap: () => onSelected(option), child: Container( decoration: BoxDecoration( color: selected ? Theme.of(context).focusColor : null, borderRadius: BorderRadius.only( topLeft: Radius.circular( index == 0 ? 12 : 0, ), topRight: Radius.circular( index == 0 ? 12 : 0, ), bottomLeft: Radius.circular( index == options.length - 1 ? 12 : 0.0, ), bottomRight: Radius.circular( index == options.length - 1 ? 12 : 0.0, ), ), ), child: ListTile( leading: option["photo"] == null ? null : CircleAvatar( backgroundImage: NetworkImage( option["photo"], ), ), title: Text("${option["label"]}"), subtitle: Text("${option["info"]}"), ), ), ); }, ), ), ], ), ), ), ), ), ); }); }); } }
@file:OptIn( ExperimentalMaterialApi::class, ExperimentalMaterial3Api::class, ExperimentalTime::class, ) package ca.amandeep.path.ui.main import android.Manifest.permission.ACCESS_COARSE_LOCATION import android.Manifest.permission.ACCESS_FINE_LOCATION import android.content.Intent import android.net.Uri import android.provider.Settings import androidx.annotation.VisibleForTesting import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.Crossfade import androidx.compose.animation.expandVertically import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridItemSpan import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.pullrefresh.PullRefreshIndicator import androidx.compose.material.pullrefresh.pullRefresh import androidx.compose.material.pullrefresh.rememberPullRefreshState import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.Checkbox import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarResult import androidx.compose.material3.Text import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat.startActivity import androidx.lifecycle.compose.collectAsStateWithLifecycle import ca.amandeep.path.R import ca.amandeep.path.data.model.AlertData import ca.amandeep.path.ui.ErrorBar import ca.amandeep.path.ui.ErrorScreen import ca.amandeep.path.ui.KeepUpdatedEffect import ca.amandeep.path.ui.LastUpdatedInfoRow import ca.amandeep.path.ui.LastUpdatedUiModel import ca.amandeep.path.ui.alerts.ExpandableAlerts import ca.amandeep.path.ui.rememberLastUpdatedState import ca.amandeep.path.ui.requireOptionalLocationItem import ca.amandeep.path.ui.stations.DirectionWarning import ca.amandeep.path.ui.stations.Station import ca.amandeep.path.util.ConnectionState import ca.amandeep.path.util.checkPermission import ca.amandeep.path.util.observeConnectivity import dev.burnoo.compose.rememberpreference.rememberBooleanPreference import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import kotlin.system.measureTimeMillis import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime @Composable fun MainScreen( mainViewModel: MainViewModel, windowSizeClass: WindowSizeClass, modifier: Modifier = Modifier, ) { val context = LocalContext.current val snackbarState = remember { SnackbarHostState() } val coroutineScope = rememberCoroutineScope() var refreshing by remember { mutableStateOf(false) } LaunchedEffect(refreshing) { if (refreshing) { val elapsedMillis = measureTimeMillis { mainViewModel.refreshTrainsFromNetwork() } delay((500 - elapsedMillis).milliseconds) refreshing = false } } val forceRefresh = { refreshing = true } var anyLocationPermissionsGranted by remember { mutableStateOf( context.checkPermission(ACCESS_COARSE_LOCATION) || context.checkPermission( ACCESS_FINE_LOCATION, ), ) } val (shortenNamesPref, setShortenNamesPref) = rememberBooleanPreference( keyName = "shortenNames", initialValue = false, defaultValue = false, ) val (showOppositeDirectionPref, setShowOppositeDirectionPref) = rememberBooleanPreference( keyName = "showOppositeDirection", initialValue = true, defaultValue = true, ) val showOppositeDirection by remember( showOppositeDirectionPref, anyLocationPermissionsGranted, ) { derivedStateOf { showOppositeDirectionPref || !anyLocationPermissionsGranted } } val (showElevatorAlertsPref, setShowElevatorAlertsPref) = rememberBooleanPreference( keyName = "showElevatorAlerts", initialValue = true, defaultValue = true, ) val setShowElevatorAlertsWithUndo = run { val snackbarMessage = stringResource(R.string.change_dir_in_options) val snackbarActionLabel = stringResource(R.string.undo) return@run { newValue: Boolean -> setShowElevatorAlertsPref(newValue) if (!newValue) { coroutineScope.launch { val snackbarResult = snackbarState.showSnackbar( message = snackbarMessage, actionLabel = snackbarActionLabel, ) if (snackbarResult == SnackbarResult.ActionPerformed) { setShowElevatorAlertsPref(true) } } } } } val (showHelpGuidePref, setShowHelpGuidePref) = rememberBooleanPreference( keyName = "showHelpGuide", initialValue = true, defaultValue = true, ) val setShowHelpGuideWithUndo = run { val snackbarMessage = stringResource(R.string.change_dir_in_options) val snackbarActionLabel = stringResource(R.string.undo) return@run { newValue: Boolean -> setShowHelpGuidePref(newValue) if (!newValue) { coroutineScope.launch { val snackbarResult = snackbarState.showSnackbar( message = snackbarMessage, actionLabel = snackbarActionLabel, ) if (snackbarResult == SnackbarResult.ActionPerformed) { setShowHelpGuidePref(true) } } } } } val overflowItems: @Composable RowScope.() -> Unit = { OverflowItems( forceRefresh = forceRefresh, shortenNamesPref = shortenNamesPref, setShortenNamesPref = setShortenNamesPref, showOppositeDirectionPref = showOppositeDirectionPref, setShowOppositeDirectionPref = setShowOppositeDirectionPref, showElevatorAlertsPref = showElevatorAlertsPref, showHelpGuidePref = showHelpGuidePref, setShowElevatorAlertsPref = setShowElevatorAlertsPref, setShowHelpGuidePref = setShowHelpGuidePref, anyLocationPermissionsGranted = anyLocationPermissionsGranted, ) } Scaffold( modifier = modifier, snackbarHost = { SnackbarHost(snackbarState) }, topBar = { TopBar(overflowItems) }, ) { innerPadding -> val ptrState = rememberPullRefreshState( refreshing = refreshing, onRefresh = forceRefresh, ) val isInNJ by mainViewModel.isInNJ.collectAsStateWithLifecycle(initialValue = false) // If there's an error, show the last valid state, but with an error flag val uiState = setAndComputeLastGoodState( uiStateFlow = mainViewModel.uiState, forceUpdate = forceRefresh, ) var now by remember { mutableStateOf(System.currentTimeMillis()) } LaunchedEffect(Unit) { while (true) { now = System.currentTimeMillis() delay(5.seconds) } } Box( Modifier .padding(innerPadding) .pullRefresh(ptrState), ) { MainScreenContent( uiModel = uiState, now = now, userState = UserState( shortenNames = shortenNamesPref, showOppositeDirection = showOppositeDirection, showElevatorAlerts = showElevatorAlertsPref, showHelpGuide = showHelpGuidePref, isInNJ = isInNJ, ), forceUpdate = forceRefresh, locationPermissionsUpdated = { anyLocationPermissionsGranted = it.isNotEmpty() mainViewModel.locationPermissionsUpdated(it) }, snackbarState = snackbarState, setShowingOppositeDirection = setShowOppositeDirectionPref, setShowElevatorAlerts = setShowElevatorAlertsWithUndo, setShowHelpGuide = setShowHelpGuideWithUndo, anyLocationPermissionsGranted = anyLocationPermissionsGranted, windowSizeClass = windowSizeClass, ) PullRefreshIndicator( refreshing = refreshing, state = ptrState, modifier = Modifier.align(Alignment.TopCenter), ) } } } @Composable @VisibleForTesting fun TopBar(overflowItems: @Composable (RowScope.() -> Unit)) { CenterAlignedTopAppBar( title = { Text(stringResource(id = R.string.app_name)) }, actions = { overflowItems() }, ) } @Composable private fun setAndComputeLastGoodState( uiStateFlow: Flow<MainUiModel>, forceUpdate: () -> Unit, ): MainUiModel { val uiModel by uiStateFlow.collectAsStateWithLifecycle(initialValue = MainUiModel()) val (lastGoodState, setLastGoodState) = remember { mutableStateOf(MainUiModel()) } setLastGoodState( MainUiModel( arrivals = foldWithLastGoodState(uiModel, lastGoodState) { it.arrivals }, alerts = foldWithLastGoodState(uiModel, lastGoodState) { it.alerts }, ), ) // If all trains are empty, force a refresh, and show a loading screen val allTrainsEmpty = lastGoodState.arrivals is Result.Valid && lastGoodState.arrivals.data.all { it.second.all { it.isDepartedTrain } } LaunchedEffect(allTrainsEmpty) { if (allTrainsEmpty) { forceUpdate() setLastGoodState( MainUiModel(alerts = lastGoodState.alerts), ) } } return lastGoodState } private fun <T : Any> foldWithLastGoodState( currentState: MainUiModel, lastGoodState: MainUiModel, attribute: (MainUiModel) -> Result<T>, ): Result<T> { val lastGoodStateAttribute = attribute(lastGoodState) val currentStateAttribute = attribute(currentState) return if (currentStateAttribute is Result.Error<T> && lastGoodStateAttribute is Result.Valid<T>) { lastGoodStateAttribute.copy(hasError = true) } else if (currentStateAttribute is Result.Loading<T> && lastGoodStateAttribute is Result.Valid<T>) { lastGoodStateAttribute } else { currentStateAttribute } } @Suppress("UnusedReceiverParameter") @Composable @VisibleForTesting fun RowScope.OverflowItems( forceRefresh: () -> Unit, shortenNamesPref: Boolean, setShortenNamesPref: (Boolean) -> Unit, showOppositeDirectionPref: Boolean, setShowOppositeDirectionPref: (Boolean) -> Unit, showElevatorAlertsPref: Boolean, showHelpGuidePref: Boolean, setShowElevatorAlertsPref: (Boolean) -> Unit, setShowHelpGuidePref: (Boolean) -> Unit, anyLocationPermissionsGranted: Boolean, ) { IconButton(onClick = forceRefresh) { Icon( imageVector = Icons.Filled.Refresh, contentDescription = stringResource(R.string.refresh_action), ) } var expanded by remember { mutableStateOf(false) } IconButton(onClick = { expanded = true }) { Icon( imageVector = Icons.Default.MoreVert, contentDescription = stringResource(R.string.more_item_actions), ) } DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .clickable { setShortenNamesPref(!shortenNamesPref) }, ) { Checkbox( checked = shortenNamesPref, onCheckedChange = setShortenNamesPref, ) Text( text = stringResource(R.string.shorten_names_action_text), modifier = Modifier.padding(end = 10.dp), ) } if (anyLocationPermissionsGranted) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .clickable { setShowOppositeDirectionPref(!showOppositeDirectionPref) }, ) { Checkbox( checked = showOppositeDirectionPref, onCheckedChange = setShowOppositeDirectionPref, ) Text( text = stringResource(R.string.show_opposite_direction_action_text), modifier = Modifier.padding(end = 10.dp), ) } } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .clickable { setShowElevatorAlertsPref(!showElevatorAlertsPref) }, ) { Checkbox( checked = showElevatorAlertsPref, onCheckedChange = setShowElevatorAlertsPref, ) Text( text = stringResource(R.string.show_elevator_alerts), modifier = Modifier.padding(end = 10.dp), ) } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .clickable { setShowHelpGuidePref(!showHelpGuidePref) }, ) { Checkbox( checked = showHelpGuidePref, onCheckedChange = setShowHelpGuidePref, ) Text( text = stringResource(R.string.show_help_guide), modifier = Modifier.padding(end = 10.dp), ) } } } @OptIn(ExperimentalCoroutinesApi::class) @Composable private fun MainScreenContent( uiModel: MainUiModel, now: Long, userState: UserState, forceUpdate: () -> Unit, locationPermissionsUpdated: suspend (ImmutableList<String>) -> Unit, snackbarState: SnackbarHostState, anyLocationPermissionsGranted: Boolean, setShowingOppositeDirection: (Boolean) -> Unit, setShowElevatorAlerts: (Boolean) -> Unit, setShowHelpGuide: (Boolean) -> Unit, windowSizeClass: WindowSizeClass, ) { val connectivityState by LocalContext.current.observeConnectivity() .collectAsStateWithLifecycle(initialValue = ConnectionState.Available) if (uiModel.arrivals is Result.Error) { ErrorScreen( connectivityState = connectivityState, forceUpdate = forceUpdate, ) } else { Crossfade( targetState = uiModel.arrivals is Result.Loading, label = "loading crossfade", ) { isLoading -> when (isLoading || uiModel.arrivals !is Result.Valid) { true -> LoadingScreen() false -> { val lastUpdatedState = rememberLastUpdatedState(uiModel.arrivals.lastUpdated) lastUpdatedState.KeepUpdatedEffect(uiModel.arrivals.lastUpdated, 1.seconds) val requireOptionalLocationItem = requireOptionalLocationItem( permissionsUpdated = locationPermissionsUpdated, navigateToSettingsScreen = { startActivity( it, Intent( Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", it.packageName, null), ), null, ) }, ) val (showDirectionWarning, setShowDirectionWarning) = rememberBooleanPreference( keyName = "showDirectionWarning", initialValue = true, defaultValue = true, ) val (alertsExpanded, setAlertsExpanded) = remember { mutableStateOf(false) } LoadedScreen( connectivityState = connectivityState, requireOptionalLocationItem = requireOptionalLocationItem, uiModel = uiModel, userState = userState, setShowElevatorAlerts = setShowElevatorAlerts, anyLocationPermissionsGranted = anyLocationPermissionsGranted, setShowingOppositeDirection = setShowingOppositeDirection, snackbarState = snackbarState, lastUpdatedState = lastUpdatedState.value, now = now, setShowHelpGuide = setShowHelpGuide, alertsExpanded = alertsExpanded, showDirectionWarning = showDirectionWarning, setAlertsExpanded = setAlertsExpanded, setShowDirectionWarning = setShowDirectionWarning, windowSizeClass = windowSizeClass, ) } } } } } @Composable @VisibleForTesting fun LoadedScreen( modifier: Modifier = Modifier, requireOptionalLocationItem: @Composable (Modifier) -> Unit, uiModel: MainUiModel, connectivityState: ConnectionState, anyLocationPermissionsGranted: Boolean, userState: UserState, setShowingOppositeDirection: (Boolean) -> Unit, setShowElevatorAlerts: (Boolean) -> Unit, snackbarState: SnackbarHostState, lastUpdatedState: LastUpdatedUiModel, now: Long, setShowHelpGuide: (Boolean) -> Unit, alertsExpanded: Boolean, showDirectionWarning: Boolean, setAlertsExpanded: (Boolean) -> Unit, setShowDirectionWarning: (Boolean) -> Unit, windowSizeClass: WindowSizeClass, ) { val arrivals = uiModel.arrivals as Result.Valid<ArrivalsUiModel> val autoRefreshingNow = connectivityState != ConnectionState.Unavailable val spacingModifier = when(windowSizeClass.widthSizeClass) { WindowWidthSizeClass.Compact -> Modifier.padding(vertical = 4.dp) WindowWidthSizeClass.Medium -> Modifier.padding(vertical = 4.dp) WindowWidthSizeClass.Expanded -> Modifier.padding(bottom = 8.dp) else -> Modifier.padding(vertical = 4.dp) } val columns = when(windowSizeClass.widthSizeClass) { WindowWidthSizeClass.Compact -> 1 WindowWidthSizeClass.Medium -> 2 WindowWidthSizeClass.Expanded -> 2 else -> 1 } val horizontalArrangement = when(windowSizeClass.widthSizeClass) { WindowWidthSizeClass.Compact -> 0.dp WindowWidthSizeClass.Medium -> 10.dp WindowWidthSizeClass.Expanded -> 10.dp else -> 0.dp } LazyVerticalStaggeredGrid( columns = StaggeredGridCells.Fixed(columns), horizontalArrangement = Arrangement.spacedBy(horizontalArrangement), modifier = modifier.padding(horizontal = 10.dp), ) { item( contentType = "top", ) { Column { requireOptionalLocationItem(spacingModifier) val alertsModel = when (uiModel.alerts) { is Result.Valid -> uiModel.alerts.copy( data = uiModel.alerts.data.copy( alerts = uiModel.alerts.data.alerts.filter { when { userState.showElevatorAlerts -> true it is AlertData.Single -> !it.isElevator else -> true } }.toImmutableList(), ), ) else -> uiModel.alerts } ExpandableAlerts( modifier = spacingModifier, connectivityState = connectivityState, alertsResult = alertsModel, expanded = alertsExpanded, setExpanded = setAlertsExpanded, setShowElevatorAlerts = setShowElevatorAlerts, ) if (anyLocationPermissionsGranted && showDirectionWarning) { DirectionWarning( modifier = spacingModifier, isInNJ = userState.isInNJ, showOppositeDirection = userState.showOppositeDirection, setShowingOppositeDirection = setShowingOppositeDirection, snackbarState = snackbarState, setShowDirectionWarning = setShowDirectionWarning, ) } AnimatedVisibility( visible = arrivals.hasError, enter = expandVertically(), exit = shrinkVertically(), ) { ErrorBar( modifier = spacingModifier, connectivityState = connectivityState, ) } when(windowSizeClass.widthSizeClass) { WindowWidthSizeClass.Compact -> Unit WindowWidthSizeClass.Medium -> Spacer(modifier = spacingModifier) WindowWidthSizeClass.Expanded -> Spacer(modifier = spacingModifier) else -> Unit } AnimatedVisibility( visible = !autoRefreshingNow && lastUpdatedState.secondsAgo > TOP_LAST_UPDATED_THRESHOLD_SECS, enter = expandVertically(), exit = shrinkVertically(), ) { LastUpdatedInfoRow( modifier = spacingModifier, lastUpdatedState = lastUpdatedState, ) } } } items( count = arrivals.data.size, contentType = { "station" }, ) { Station( modifier = spacingModifier, station = arrivals.data[it], now = now, userState = userState, autoRefreshingNow = autoRefreshingNow, setShowHelpGuide = setShowHelpGuide, ) } item( span = StaggeredGridItemSpan.FullLine, contentType = "lastUpdated", ) { LastUpdatedInfoRow( modifier = spacingModifier, lastUpdatedState = lastUpdatedState, ) } } } @Composable private fun LoadingScreen() { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { CircularProgressIndicator() Spacer(Modifier.height(10.dp)) Text(text = stringResource(R.string.loading), color = MaterialTheme.colorScheme.secondary) } } data class UserState( val shortenNames: Boolean, val showOppositeDirection: Boolean, val showElevatorAlerts: Boolean, val showHelpGuide: Boolean, val isInNJ: Boolean, ) const val TOP_LAST_UPDATED_THRESHOLD_SECS: Long = 60 * 2
import { useCallback, useState } from "react"; import { Merge } from "@/utils"; import { Column } from "@/components"; import styles from "./styles"; type BaseProps = {}; type Value = never; type OwnProps = { value?: Value; defaultValue?: Value; onChange?: (value: Value) => void; disabled?: boolean; error?: boolean; }; type {{pascalCase name}}Props = Merge<BaseProps, OwnProps>; const {{pascalCase name}}: React.FC<{{pascalCase name}}Props> = (props) => { const { value: propsValue, defaultValue, onChange, ...rest } = props; const [innerValue, setInnerValue] = useState<Value | null>(defaultValue ?? null); const value = propsValue !== undefined ? propsValue : innerValue; const handleChange = useCallback( (e: any) => { const newValue = e.target.value as Value; onChange?.(newValue); setInnerValue(newValue); }, [setInnerValue, onChange] ); return ( <Column sx={styles.root} {...rest}> {{pascalCase name}} Component </Column> ); }; export type { {{pascalCase name}}Props }; export default {{pascalCase name}};
package heap; import java.util.*; public class DesignTwitter355 { class Tweet{ int tweetId; int time; public Tweet(int tweetId, int time){ this.tweetId = tweetId; this.time=time; } } Map<Integer, List<Tweet>> userTweetMap; Map<Integer, Set<Integer>> followersMap; int time,k; public DesignTwitter355() { userTweetMap = new HashMap<>(); followersMap = new HashMap<>(); time=0; k=10; } public void postTweet(int userId, int tweetId) { time++; userTweetMap.computeIfAbsent(userId, t->new ArrayList<>()).add(new Tweet(tweetId, -time)); } public List<Integer> getNewsFeed(int userId) { List<Integer> tweets = new ArrayList<>(); PriorityQueue<int[]> latestTweet = new PriorityQueue<>(Comparator.comparing(a->a[0])); Set<Integer> followers = followersMap.getOrDefault(userId, new HashSet<>()); followers.add(userId); for(int user: followers){ if (!userTweetMap.containsKey(user) || userTweetMap.get(user).isEmpty()) continue; Tweet lastTweet =userTweetMap.get(user).get(userTweetMap.get(user).size() -1); latestTweet.offer(new int[]{lastTweet.time, lastTweet.tweetId, user, userTweetMap.get(user).size()-1}); } while (!latestTweet.isEmpty() && tweets.size() < k){ int[] mostRecent = latestTweet.poll(); tweets.add(mostRecent[1]); if (mostRecent[3] > 0 ){ Tweet t = userTweetMap.get(mostRecent[2]).get(--mostRecent[3]); latestTweet.offer(new int[]{t.time, t.tweetId, mostRecent[2], mostRecent[3]}); } } return tweets; } public void follow(int followerId, int followeeId) { followersMap.computeIfAbsent(followerId, e-> new HashSet<>()).add(followeeId); } public void unfollow(int followerId, int followeeId) { followersMap.computeIfAbsent(followerId, e -> new HashSet<>()).remove(followeeId); } public static void main(String[] args) { DesignTwitter355 prog = new DesignTwitter355(); prog.postTweet(1,5); prog.follow(1,2); prog.follow(2,1); System.out.println(prog.getNewsFeed(2)); prog.postTweet(2,6); System.out.println(prog.getNewsFeed(1)); System.out.println(prog.getNewsFeed(2)); prog.unfollow(2,1); System.out.println(prog.getNewsFeed(1)); System.out.println(prog.getNewsFeed(2)); prog.unfollow(1,2); System.out.println(prog.getNewsFeed(1)); System.out.println(prog.getNewsFeed(2)); //[5] //[6, 5] //[6, 5] //[6, 5] //[6] //[5] //[6] } }
import { ADD_EXPENSE, REMOVE_EXPENSE, EDIT_EXPENSE, SET_EXPENSES, START_SET_EXPENSES, } from './types'; import database from '../firebase/firebase'; // ACTIONS NEEDED // // ADD_EXPENSE export const addExpense = (expense) => (dispatch) => { dispatch({ type: ADD_EXPENSE, expense, }); }; // FIREBASE_EXPENSE PUSH -> ADD_EXPENSE export const startAddExpense = (expenseData = {}) => (dispatch, getState) => { const uid = getState().auth.uid; const { description = '', note = '', amount = 0, createdAt = '', } = expenseData; const expense = { createdAt, description, note, amount, }; database .ref(`users/${uid}/expenses`) .push(expense) .then((ref) => { dispatch( addExpense({ id: ref.key, ...expense, }) ); }); }; // REMOVE_EXPENSE export const removeExpense = ({ id } = {}) => ({ type: REMOVE_EXPENSE, id, }); // START REMOVE EXPENSE TO REMOVE EXPENSE FROM DB export const startRemoveExpense = ({ id }) => (dispatch, getState) => { const uid = getState().auth.uid; return database .ref(`users/${uid}/expenses/${id}`) .remove() .then(() => { dispatch(removeExpense({ id })); }); }; // EDIT_EXPENSE export const editExpense = (id, updates) => ({ type: EDIT_EXPENSE, id, updates, }); // START EDIT EXPENSE TO EDIT EXPENSE IN THE DB export const startEditExpense = (id, updates) => (dispatch, getState) => { const uid = getState().auth.uid; return database .ref(`users/${uid}/expenses/${id}`) .update(updates) .then(() => { dispatch(editExpense(id, updates)); }); }; // SET EXPENSES export const setExpenses = (expenses) => ({ type: SET_EXPENSES, expenses, }); // START SET EXPENSES FROM FIREBASE export const startSetExpenses = () => (dispatch, getState) => { const uid = getState().auth.uid; return database .ref(`users/${uid}/expenses`) .once('value') .then((snapshot) => { const expenses = []; snapshot.forEach((childSnapshot) => { expenses.push({ id: childSnapshot.key, ...childSnapshot.val(), }); }); dispatch(setExpenses(expenses)); }); };
const nodemailer = require("nodemailer"); export const SendReminderEmail = async ( name: string, email: string, taskTitle: string, taskDesc: string, taskId: string, url: string | null, status: string ) => { try { const transporter = nodemailer.createTransport({ host: "smtp.gmail.com", service: "gmail", port: 587, secure: true, auth: { user: process.env.EMAIL, pass: process.env.EMAIL_PASS, }, }); const urlValue = url === null || url === "" ? "N/A" : url; const emailSent = await transporter.sendMail({ from: `"Task Notify" <${process.env.EMAIL}>`, to: email, subject: "Task Reminder", html: `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div style="font-family: sans-serif"> <div style="font-weight: bold; font-weight: 500; font-size: 1.25rem"> <p>task<span style="color: #19fa9a">notify</span></p> </div> <p style=" margin-top: 5px; margin-bottom: 2rem; font-weight: 500; font-size: 1.1rem; " > Hi ${name}, hope you are doing great. You are recieving this email as a reminder for your task that you added in your tasks list. Details of the task are as below </p> <p style=" width: fit-content; margin: 5px auto 5px auto; font-size: 2rem; font-weight: bold; " > ${taskTitle} </p> <p style="margin-top: 2rem; font-weight: bold; font-size: 1.1rem"> Task description : <span style="font-weight: 500">${taskDesc}</span> </p> <p style="margin-top: 2rem; font-weight: bold; font-size: 1.1rem"> Current Status : <span style="font-weight: 500">${status}</span> </p> <p style="margin-top: 5px; font-weight: bold; font-size: 1.1rem"> Attached link: <span style="font-weight: 500"> <a href="${ urlValue === "N/A" ? "" : url }">${urlValue}</a> </span> </p> <a href="${process.env.HOST}/dashboard/tasks/taskdetail/${taskId}" > <button style=" padding: .75rem 1.5rem; font-size: 1rem; border: none; border-radius: 0.5rem; background-color: #19fa9a; margin: 1rem 0 1rem 0; box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px; color : black " > See task details </button> </a> <p style="margin-top: 10px; font-weight: bold; font-size: 0.8rem"> Note: <span style="font-weight: 500; font-size: 0.7rem " >If you did not schedule this task, kindly change your password ASAP. If you face any issue feel free to reply us on this email</span > </p> <p>Regards,</p> <p>taskNotify</p> </div> </body> </html> `, }); console.log(emailSent); return emailSent; } catch (error: any) { console.log(error.message); return error; } };
import { DropdownValue } from '../../components/styles/Dropdown' import { Item } from '../stores/items/item.model' import { inventoryValues } from './filterValues' export interface SearchFilterValues { item?: Item itemCharacter: DropdownValue itemSlot: DropdownValue itemEvent: DropdownValue itemRarity: DropdownValue inventory: DropdownValue wishlistOnly: boolean } export function createDefaultSearchFilter(): SearchFilterValues { return { itemCharacter: itemCharacterValues[0], itemSlot: itemSlotValues[0], itemEvent: itemEventValues[0], itemRarity: tradeableItemRarityValues[0], inventory: inventoryValues[0], wishlistOnly: false, } } export const itemCharacterValues: DropdownValue[] = [ { key: 'any', displayName: 'Any' }, { key: 'none', displayName: 'No Character' }, { key: 'hunter', displayName: 'Hunter' }, { key: 'witch', displayName: 'Witch' }, ] export const itemSlotValues: DropdownValue[] = [ { key: 'any', displayName: 'Any' }, { key: 'ingredient', displayName: 'Ingredient', imagePath: '/assets/images/slotIcons/ingredient.png', }, { key: 'recipe', displayName: 'Recipe', imagePath: '/assets/images/slotIcons/recipe.png', }, { key: 'body', displayName: 'Body', imagePath: '/assets/images/slotIcons/body.png', }, { key: 'broom', displayName: 'Broom', imagePath: '/assets/images/slotIcons/broom.png', }, { key: 'hat', displayName: 'Hat', imagePath: '/assets/images/slotIcons/hat.png', }, { key: 'head', displayName: 'Head', imagePath: '/assets/images/slotIcons/head.png', }, { key: 'lower body', displayName: 'Lower Body', imagePath: '/assets/images/slotIcons/lowerbody.png', }, { key: 'melee weapon', displayName: 'Melee Weapon', imagePath: '/assets/images/slotIcons/melee.png', }, { key: 'player icon', displayName: 'Player Icon', imagePath: '/assets/images/slotIcons/playericon.png', }, { key: 'projectile', displayName: 'Projectile', imagePath: '/assets/images/slotIcons/projectile.png', }, { key: 'skin color', displayName: 'Skin Color', imagePath: '/assets/images/slotIcons/skincolor.png', }, { key: 'upper body', displayName: 'Upper Body', imagePath: '/assets/images/slotIcons/upperbody.png', }, ] export const itemEventValues: DropdownValue[] = [ { key: 'any', displayName: 'Any' }, { key: 'none', displayName: 'No Event' }, { key: 'chinese newyear', displayName: 'Chinese New Year', imagePath: '/assets/images/eventIcons/chineseNewYear.png', }, { key: 'halloween', displayName: 'Halloween 2017', imagePath: '/assets/images/eventIcons/halloween.png', }, { key: 'halloween2018', displayName: 'Halloween 2018', imagePath: '/assets/images/eventIcons/halloween2018.png', }, { key: 'halloween2019', displayName: 'Halloween 2019', imagePath: '/assets/images/eventIcons/halloween2019.png', }, { key: 'halloween2020', displayName: 'Halloween 2020', imagePath: '/assets/images/eventIcons/halloween2020.png', }, { key: 'halloween2022', displayName: 'Halloween 2022', imagePath: '/assets/images/eventIcons/halloween2022.png', }, { key: 'mystic sands', displayName: 'Mystic Sands', imagePath: '/assets/images/eventIcons/mysticSands.png', }, { key: 'plunderparty', displayName: 'Plunder Party', imagePath: '/assets/images/eventIcons/plunderparty.png', }, { key: 'springfever', displayName: 'Spring Fever', imagePath: '/assets/images/eventIcons/springfever.png', }, { key: 'summerevent', displayName: 'Summer', imagePath: '/assets/images/eventIcons/summer.png', }, { key: 'theater', displayName: 'Theater', imagePath: '/assets/images/eventIcons/theater.png', }, { key: 'winterdream', displayName: 'Winterdream 2017', imagePath: '/assets/images/eventIcons/winterdream.png', }, { key: 'winterdream2018', displayName: 'Winterdream 2018', imagePath: '/assets/images/eventIcons/winterdream2018.png', }, { key: 'winterdream2019', displayName: 'Winterdream 2019', imagePath: '/assets/images/eventIcons/winterdream2019.png', }, { key: 'winterdream2020', displayName: 'Winterdream 2020', imagePath: '/assets/images/eventIcons/winterdream2020.png', }, { key: 'winterdream2021', displayName: 'Winterdream 2021', imagePath: '/assets/images/eventIcons/winterdream2021.png', }, { key: 'winterdream2022', displayName: 'Winterdream 2022', imagePath: '/assets/images/eventIcons/winterdream2022.png', }, { key: 'winterdream witch', displayName: 'Winterdream Witch', imagePath: '/assets/images/eventIcons/winterdreamwitch.png', }, { key: 'witchforest', displayName: 'Witch Forest', imagePath: '/assets/images/eventIcons/witchforest.png', }, ] export const itemRarityValues: DropdownValue[] = [ { key: 'any', displayName: 'Any' }, { key: 'common', displayName: 'Common', imagePath: '/assets/svgs/rarity_circles/common.svg', }, { key: 'uncommon', displayName: 'Uncommon', imagePath: '/assets/svgs/rarity_circles/uncommon.svg', }, { key: 'unlock', displayName: 'Unlock', imagePath: '/assets/svgs/rarity_circles/unlock.svg', }, { key: 'eventrarity', displayName: 'Eventrarity', imagePath: '/assets/svgs/rarity_circles/eventrarity.svg', }, { key: 'rare', displayName: 'Rare', imagePath: '/assets/svgs/rarity_circles/rare.svg', }, { key: 'veryrare', displayName: 'Veryrare', imagePath: '/assets/svgs/rarity_circles/veryrare.svg', }, { key: 'whimsical', displayName: 'Whimsical', imagePath: '/assets/svgs/rarity_circles/whimsical.svg', }, { key: 'promo', displayName: 'Promo', imagePath: '/assets/svgs/rarity_circles/promo.svg', }, ] export const tradeableItemRarityValues: DropdownValue[] = [ { key: 'any', displayName: 'Any' }, { key: 'common', displayName: 'Common', imagePath: '/assets/svgs/rarity_circles/common.svg', }, { key: 'uncommon', displayName: 'Uncommon', imagePath: '/assets/svgs/rarity_circles/uncommon.svg', }, { key: 'rare', displayName: 'Rare', imagePath: '/assets/svgs/rarity_circles/rare.svg', }, { key: 'veryrare', displayName: 'Veryrare', imagePath: '/assets/svgs/rarity_circles/veryrare.svg', }, { key: 'whimsical', displayName: 'Whimsical', imagePath: '/assets/svgs/rarity_circles/whimsical.svg', }, ]
% Path integral Eigenfunctions %% eigenfunctions for duffing system clc; clear; close all; %% system description % nonlinear ode x_dot = f(x) % linearization at (0,0) saddle Dom = [-2 2]; x = sym('x',[2;1]); delta = 0.5; f = -[x(2); + x(1) - delta*x(2) - x(1)^3]; % get quiver grid = Dom(1):0.5:Dom(2); [X,Y] = meshgrid(grid); u = Y; v = X - delta.*Y - X.^3; % % figure(1) % subplot(2,4,1) % ff = @(t,x)[x(2); + x(1) - delta*x(2) - x(1)^3]; % tspan = [0,20]; ic_pts = 2; % xl = Dom(1); xh = Dom(2); % yl = Dom(1); yh = Dom(2); % Xs = []; % start_idx = 1; % for x0 = linspace(Dom(1), Dom(2), ic_pts) % for y0 = linspace(Dom(1), Dom(2), ic_pts) % [ts,xs] = ode45(@(t,x)ff(t,x),tspan,[x0 y0]); % plot(xs(start_idx:end,1),xs(start_idx:end,2),'k','LineWidth',1); hold on; % Xs = [Xs;xs(start_idx:end,:)]; % end % end % % xlim([-3,3]) % % ylim([-3,3]) % axes = gca; % axis square % set(axes,'FontSize',15); % xlabel('$x_1$','FontSize',20, 'Interpreter','latex') % ylabel('$x_2$','FontSize',20, 'Interpreter','latex') % zlabel('$x_3$','FontSize',20, 'Interpreter','latex') % box on % axes.LineWidth=2; %% Linearize system eqb_point_saddle = [0 0]; A = eval(subs(jacobian(f),[x(1) x(2)],eqb_point_saddle)); [V,D,W] = eig(A); D = diag(D); % for real eig functionsTh eig_val1 = real(D(1)); w1 = W(:,1); eig_val2 = real(D(2)); w2 = (W(:,2)); % define nonlinear part x_dot = Ax + fn(x) fn = f - A*[x(1);x(2)]; % define matlab functions g1 = matlabFunction(w1'*fn,'vars',{x(1),x(2)}); g2 = matlabFunction(w2'*fn,'vars',{x(1),x(2)}); f = matlabFunction(f); %% Set up path Integral grid = Dom(1):0.1:Dom(2); %define grid where eigenfunction is well defined [q1,q2] = meshgrid(grid); dim = 1; x_0 = [q1(:),q2(:)]; phi1_est=[];phi2_est=[]; phi1=[]; phi1_est_time_ode45 = []; phi2=[]; phi2_est_time_ode45 = []; options = odeset('RelTol',1e-9,'AbsTol',1e-300,'events',@(t, x)offFrame(t, x, Dom(2))); t_ode45 = linspace(0.001,20,5); figure(2) for t_span = t_ode45 phi1 = []; phi2 = []; w_bar = waitbar(0,'1','Name','Path integral for t ='+string(t_span)+'s ...',... 'CreateCancelBtn','setappdata(gcbf,''canceling'',1)'); for i = 1:length(x_0) waitbar(i/length(x_0),w_bar,sprintf(string(i)+'/'+string(length(x_0)))) [t,x] = ode45(@(t,x)f(x(1),x(2)),[0 t_span],x_0(i,:), options); % terminate t and x when they enter linear region idx = find(norm(x(end,:)-eqb_point_saddle)<1e-6); if(~isempty(idx)) idx = idx(1); t = t(1:idx); x = x(1:idx,:); end %collect row vector of eig fun % stable eigenfunctions at saddle point (0,0) phi1 = [phi1, w1'*x_0(i,:)' + trapz(t,exp(-eig_val1*t).*g1(x(:,1),x(:,2)),dim)]; % unstable eigenfunctions at saddle point (0,0) phi2 = [phi2, w2'*x_0(i,:)' + trapz(t,exp(-eig_val2*t).*g2(x(:,1),x(:,2)),dim)]; end % reshape for plot phi1 = reshape((phi1),size(q2)); phi2 = reshape((phi2),size(q2)); % plot eignfuns as a gif for each time ic_pts = 1; subplot(2,2,1) p1 = pcolor(q1,q2,phi1); hold on; set(p1,'Edgecolor','none') colormap jet l = streamslice(X,Y,u,v); hold on; set(l,'LineWidth',1) set(l,'Color','k'); axes1 = gca; axis square axis([Dom(1) Dom(2) Dom(1) Dom(2)]) set(axes1,'FontSize',15); xlabel('$x_1$','FontSize',20, 'Interpreter','latex') ylabel('$x_2$','FontSize',20, 'Interpreter','latex') colorbar phi1_min = min(phi1,[],'all'); phi1_max = max(phi1,[],'all'); clim([phi1_min,phi1_max]) box on axes.LineWidth=2; subplot(2,2,2) p2 = pcolor(q1,q2,phi2); hold on; set(p2,'Edgecolor','none') colormap jet l = streamslice(X,Y,u,v); hold on; set(l,'LineWidth',1) set(l,'Color','k'); axes2 = gca; axis square axis([Dom(1) Dom(2) Dom(1) Dom(2)]) set(axes2,'FontSize',15); xlabel('$x_1$','FontSize',20, 'Interpreter','latex') ylabel('$x_2$','FontSize',20, 'Interpreter','latex') colorbar phi2_min = min(phi2,[],'all'); phi2_max = max(phi2,[],'all'); clim([phi2_min,phi2_max]) box on axes.LineWidth=2; % collect columns of phi1_time for each time phi1_est_time_ode45 = [phi1_est_time_ode45;phi1]; phi2_est_time_ode45 = [phi2_est_time_ode45;phi2]; F = findall(0,'type','figure','tag','TMWWaitbar'); delete(F); end %% Convergence plot figure(2) subplot(2,2,3) t_plot = t_ode45; phi1_convergence = reshape(phi1_est_time_ode45,5,[]); for i = 1:1:length(x_0) plot(t_plot,phi1_convergence(:,i)); hold on end axes = gca; set(axes,'FontSize',15); xlabel('integration time $(s)$','FontSize',20, 'Interpreter','latex') ylabel('$\psi_s(x)$','FontSize',20, 'Interpreter','latex') box on axes.LineWidth=2; subplot(2,2,4) phi2_convergence = reshape(phi2_est_time_ode45,5,[]); t_plot = t_ode45; for i = 1:1:length(x_0) plot(t_plot,phi2_convergence(:,i)); hold on end axes = gca; set(axes,'FontSize',15); xlabel('integration time $(s)$','FontSize',20, 'Interpreter','latex') ylabel('$\psi_u(x)$','FontSize',20, 'Interpreter','latex') box on axes.LineWidth=2; %% helper functions function [value,isterminal,direction]=offFrame(~, Y, Dom) value = (max(abs(Y))>4.*Dom) | (min(sum(abs(Y)))<1e-2); isterminal=1; direction=0; end
import unittest import sys from pathlib import Path import json sys.path.append(str(Path(__file__).resolve().parent.parent)) from src import messages from src import database def big_msg_open(): with open("tests\msg_with_above_225_char.txt", "r") as f: text = f.read() return text class MessagesTests(unittest.TestCase): def setUp(self): self.db = database.DatabasePsql("tests\database_test.ini") def test_message_new_with_incorrect_command(self): test_msg = "message new FirstUser admin > This is the message" self.assertEqual(messages.message_new(test_msg, self.db, "admin"), "The wrong amount of data was entered or the format was incorrect" ) def test_message_new_if_the_receiver_is_not_in_user_database(self): test_msg = "message new UserNotExist > This is the message" self.assertEqual(messages.message_new(test_msg, self.db, "admin"), "User does not exist!") def test_message_new_if_the_inbox_is_full_with_more_than_5_messages(self): test_msg = "message new user > This is the message" self.assertEqual(messages.message_new(test_msg, self.db, "admin"), "This user's inbox is full" ) def test_message_new_when_the_message_exceeds_255_characters(self): test_msg = f"message new admin > {big_msg_open()}" self.assertEqual(messages.message_new(test_msg, self.db, "user") , "Message exceeds 255 characters!") def test_message_new_when_have_been_sent_and_have_been_deleted(self): test_msg = "message new admin > This is a message which will be deleted" self.assertEqual(messages.message_new(test_msg, self.db, "user"), "The message has been sent") query_to_find_id_msg = "select msg_id from messages where msg_from = 'user' and msg_for = 'admin' and msg = 'This is a message which will be deleted';" msg_id = self.db.load_data_from_database(query_to_find_id_msg)[0][0] test_msg = f"message delete {msg_id}" self.assertEqual(messages.message_delete(test_msg, self.db, 'admin'), "The message has been deleted") def test_messages_delete_when_the_number_of_messages_is_incorrect(self): test_msg = f"messages delete 99" self.assertEqual(messages.message_delete(test_msg, self.db, 'admin'), "The message does not exist") def test_message_delete_with_incorrect_command(self): test_msg = "message delete 1 delete" self.assertEqual(messages.message_delete(test_msg, self.db, ""), "The wrong amount of data was entered or the format was incorrect") def test_messages_read_all_for_user(self): with open(r'tests\test_msg_list.json', 'r') as file: users_json = json.load(file) users_list_json = json.dumps(users_json, indent=2) self.assertEqual(messages.message_read("admin", self.db), users_list_json) def test_messages_read_from_one_messages(self): testMsg = "messages read from 12" with open(r'tests\test_msg_one.json', 'r') as file: users_json = json.load(file) users_list_json = json.dumps([users_json[0]], indent=1) self.assertEqual(messages.message_read_from(testMsg, self.db, "admin"), (users_list_json, 12)) query_rollback = f"UPDATE messages SET unread = false WHERE msg_for = 'admin' and msg_id = 12;" self.db.write_data_to_database(query_rollback) if __name__ == "__main__": unittest.main()
package br.com.vpereira; import java.math.BigDecimal; import br.com.vpereira.dao.ProdutoDaoMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import main.java.br.com.vpereira.dao.IProdutoDAO; import main.java.br.com.vpereira.domain.Produto; import main.java.br.com.vpereira.exceptions.TipoChaveNaoEncontradaException; import main.java.br.com.vpereira.services.IProdutoService; import main.java.br.com.vpereira.services.ProdutoService; public class ProdutoServiceTest { private IProdutoService produtoService; private Produto produto; public ProdutoServiceTest() { IProdutoDAO dao = new ProdutoDaoMock(); produtoService = new ProdutoService(dao); } @Before public void init() { produto = new Produto(); produto.setCodigo("A1"); produto.setDescricao("Produto 1"); produto.setNome("Produto 1"); produto.setValor(BigDecimal.TEN); } @Test public void pesquisar() { Produto produtor = this.produtoService.consultar(produto.getCodigo()); Assert.assertNotNull(produtor); } @Test public void salvar() throws TipoChaveNaoEncontradaException { Boolean retorno = produtoService.cadastrar(produto); Assert.assertTrue(retorno); } @Test public void excluir() { produtoService.excluir(produto.getCodigo()); } @Test public void alterarCliente() throws TipoChaveNaoEncontradaException { produto.setNome("Rodrigo Pires"); produtoService.alterar(produto); Assert.assertEquals("Rodrigo Pires", produto.getNome()); } }
import firebase_admin from firebase_admin import credentials, db from flask import Flask, request, jsonify from flask_cors import CORS from datetime import datetime app = Flask(__name__) CORS(app) cred = credentials.Certificate( "C:\\Users\\vitht\\PycharmProjects\\pythonProject4\\firebase_db_connection\\test-71f04-firebase-adminsdk-70vbu-7a05af999c.json") firebase_admin.initialize_app(cred, { 'databaseURL': 'https://test-71f04-default-rtdb.firebaseio.com//' }) switch_state = 'On' previous_mode = None previous_switch = None @app.route('/fan', methods=['POST']) def fan_information(): global switch_state, previous_mode, previous_switch try: data = request.get_json() print("data: ", data) required_fields = ['switch', 'mode'] for field in required_fields: if field not in data: return jsonify({"error": f"Missing {field}"}), 400 switch = data['switch'] mode = data['mode'] # Validating switch value if switch not in ['On', 'Off']: return jsonify({"error": "Invalid switch value. Valid values are 'On' or 'Off'"}), 400 # Validating mode value if mode not in ['Low Power', 'Mid Power', 'High Power']: return jsonify({"error": "Invalid mode value. Valid values are 'Low Power' or 'High Power'"}), 400 timestamp = datetime.now() ref = db.reference('fan_data') fan = ref.get() if fan: if previous_switch == switch and previous_mode == mode: print(f"Fan with switch {switch}, {mode} already exists") return jsonify({"error": f"Fan with switch {switch}, {mode} already exists"}), 400 if previous_switch == "Off" and switch == "Off": print("Cannot proceed. Fan is currently switched Off.") return jsonify({"error": "Cannot proceed. Fan is currently switched Off."}), 400 previous_mode = mode previous_switch = switch new_client_ref = ref.push() new_client_ref.set({ 'Switch': switch, 'Mode': mode, 'On Time': timestamp.strftime("%Y-%m-%d %H:%M:%S") }) print(f"Fan information added successfully, 'timestamp': {timestamp.strftime('%Y-%m-%d %H:%M:%S')}") return jsonify({"message": "Fan information added successfully", "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S")}) except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == '__main__': app.run("localhost", 11000)
import { useState } from "react"; import { postVoluntario } from "../../services/VoluntarioService"; import "./Voluntario"; const Voluntario = () => { const [nome, setNome] = useState(""); const [cpf, setCpf] = useState(); const [email, setEmail] = useState(""); const [dataNasc, setDataNasc] = useState(""); const [endereco, setEndereco] = useState(""); const [uf, setUf] = useState(""); const [formacao, setFormacao] = useState(""); const submitHandler = (event) => { event.preventDefault(); const voluntario = { nome: nome, cpf: cpf, email: email, dataNasc: dataNasc, endereco: endereco, uf: uf, formacao: formacao }; postVoluntario(voluntario); setNome(""); setCpf(""); setEmail(""); setDataNasc(""); setEndereco(""); setUf(""); setFormacao(""); }; const nomeChangeHandler = (event) => { setNome(event.target.value) } const cpfChangeHandler = (event) => { setCpf(event.target.value) } const emailChangeHandler = (event) => { setEmail(event.target.value) } const dataNascChangeHandler = (event) => { setDataNasc(event.target.value) } const enderecoChangeHandler = (event) => { setEndereco(event.target.value) } const ufChangeHandler = (event) => { setUf(event.target.value) } const formacaoChangeHandler = (event) => { setFormacao(event.target.value) } return ( <main> <section id="cadastro-layout"> <section className="cadastro-title"> <h1>Faça parte, seja um voluntário!</h1> </section> <section className="cadastro-infos"> <h2> O voluntário é peça-chave na viabilização do projeto Hubfarma. É por meio dele que podemos levar a alfabetização às pessoas que precisam dela. Portanto, fique por dentro do papel do <span className="color-blue"> voluntário</span>: </h2> <img src={require("../../assets/voluntario.png")} /> <ol id="lista-cadastro-infos" type="A"> <li className="item-lista-cadastro"> <h3>Requisitos para se voluntariar:</h3> <ul> <li>Ter 18 (dezoito) anos ou mais.</li> <li>Ser graduado em Letras, na modalidade licenciatura, ou em Pedagogia.</li> </ul> </li> <li className="item-lista-cadastro"> <h3>Como a Hubfarma dará suporte ao voluntário:</h3> <ul> <li>Os custos de ida e volta para a localidade onde as aulas serão ministradas serão arcados pelo projeto.</li> <li>Haverá um canal de comunicação exclusivo à disposição do voluntário durante todo o período de atuação no projeto.</li> </ul> </li> </ol> </section> <section className="cadastro-form"> <div className="cadastro-form-header"> <h3>Entre para se voluntariar:</h3> <button type="button" className="btn-default btn3" data-bs-toggle="modal" data-bs-target="#modalLogin"> Entrar </button> <div className="modal fade" id="modalLogin" tabIndex="-1" aria-labelledby="modalLoginLabel" aria-hidden="true"> <div className="modal-dialog"> <div className="modal-content login-form"> <div className="modal-header"> <h5 className="modal-title" id="modalLoginLabel"> Entre em sua conta: </h5> <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div className="modal-body"> <form> <div className="campos-form"> <label htmlFor="email-login">E-mail:</label> <input type="email" name="email-login" id="email-login" /> </div> <div className="campos-form"> <label htmlFor="senha-login">Senha:</label> <input type="password" name="senha-login" id="senha-login" /> </div> </form> </div> <div className="modal-footer"> <button type="button" className="btn-default btn1"> Salvar </button> </div> </div> </div> </div> </div> <p> Se é a sua <b className="color-blue">primeira vez</b> aqui, realize seu cadastro para entrarmos em contato: </p> <form onSubmit={submitHandler} id="formulario"> <div className="campos-form"> <label htmlFor="nome-user">Nome completo:</label> <input onChange={nomeChangeHandler} value={nome} type="text" name="nome-user" id="nome-user" /> </div> <div className="campos-form"> <label htmlFor="cpf-user">CPF:</label> <input onChange={cpfChangeHandler} value={cpf} type="number" name="cpf-user" id="cpf-user" /> </div> <div className="campos-form"> <label htmlFor="email-user">E-mail:</label> <input onChange={emailChangeHandler} value={email} type="email" name="email-user" id="email-user" /> </div> <div className="campos-form"> <label htmlFor="data-nsc-user">Data de nascimento:</label> <input onChange={dataNascChangeHandler} value={dataNasc} type="date" name="data-nsc-user" id="data-nsc-user" /> </div> <div className="campos-form"> <label htmlFor="endereco-user">Endereço completo:</label> <textarea onChange={enderecoChangeHandler} value={endereco} name="endereco-user" id="endereco-user" cols="40" rows="2" placeholder="Ex.: Rua José da Silva, 314, apartamento 102. Bairro Novo Brasil."></textarea> </div> <div className="campos-form"> <label htmlFor="uf-user">UF:</label> <select onChange={ufChangeHandler} value={uf} name="uf-user" id="uf-user"> <option value=""></option> <option value="AC">Acre</option> <option value="AL">Alagoas</option> <option value="AP">Amapá</option> <option value="AM">Amazonas</option> <option value="BA">Bahia</option> <option value="CE">Ceará</option> <option value="DF">Distrito Federal</option> <option value="ES">Espírito Santo</option> <option value="GO">Goiás</option> <option value="MA">Maranhão</option> <option value="MT">Mato Grosso</option> <option value="MS">Mato Grosso do Sul</option> <option value="MG">Minas Gerais</option> <option value="PA">Pará</option> <option value="PB">Paraíba</option> <option value="PR">Paraná</option> <option value="PE">Pernambuco</option> <option value="PI">Piauí</option> <option value="RJ">Rio de Janeiro</option> <option value="RN">Rio Grande do Norte</option> <option value="RS">Rio Grande do Sul</option> <option value="RO">Rondônia</option> <option value="RR">Roraima</option> <option value="SC">Santa Catarina</option> <option value="SP">São Paulo</option> <option value="SE">Sergipe</option> <option value="TO">Tocantins</option> <option value="EX">Estrangeiro</option> </select> </div> <div className="campos-form"> <label htmlFor="formacao-user">Formação acadêmica:</label> <select onChange={formacaoChangeHandler} value={formacao} name="formacao-user" id="formacao-user"> <option value=""></option> <option value="sc">Superior completo</option> <option value="si">Superior incompleto</option> </select> </div> <div id="btn-cadastrar"> <input className="btn-default btn1" type="submit" value="Cadastrar-se" /> </div> </form> </section> </section> </main> ); }; export default Voluntario;
<!-- - @copyright 2022 Christoph Wurst <christoph@winzerhof-wurst.at> - - @author Michael Blumenstein <M.Flower@gmx.de> - @author 2022 Christoph Wurst <christoph@winzerhof-wurst.at> - @author 2023 Richard Steinmetz <richard@steinmetz.cloud> - - @license GNU AGPL version 3 or any later version - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. --> <template> <div v-if="step === RegistrationSteps.READY"> <NcButton class="new-webauthn-device__button" @click="start"> {{ t('twofactor_webauthn', 'Add security key') }} </NcButton> <p v-if="errorMessage" class="error-message"> <span class="icon icon-error" /> {{ errorMessage }} </p> </div> <div v-else-if="step === RegistrationSteps.REGISTRATION" class="new-webauthn-device"> <span class="icon-loading-small webauthn-loading" /> {{ t('twofactor_webauthn', 'Please use your security key to authorize.') }} </div> <div v-else-if="step === RegistrationSteps.NAMING" class="new-webauthn-device"> <span class="icon-loading-small webauthn-loading" /> <form @submit.prevent="submit" class="new-webauthn-device__form"> <input v-model="name" required type="text" :placeholder="t('twofactor_webauthn', 'Name your security key')"> <NcButton class="new-webauthn-device__button" native-type="submit" :disabled="!name.length"> {{ t('twofactor_webauthn', 'Add') }} </NcButton> </form> </div> <div v-else-if="step === RegistrationSteps.PERSIST" class="new-webauthn-device"> <span class="icon-loading-small webauthn-loading" /> {{ t('twofactor_webauthn', 'Adding your security key …') }} </div> <div v-else> Invalid registration step. This should not have happened. </div> </template> <script> import { confirmPassword } from '@nextcloud/password-confirmation' import { NcButton } from '@nextcloud/vue' import { startRegistration, finishRegistration, } from '../services/RegistrationService.js' import logger from '../logger.js' const debug = (text) => (data) => { logger.debug(text, { data }) return data } const RegistrationSteps = Object.freeze({ READY: 1, REGISTRATION: 2, NAMING: 3, PERSIST: 4, }) export default { name: 'AddDeviceDialog', components: { NcButton, }, props: { httpWarning: Boolean, }, data() { return { name: '', credential: {}, RegistrationSteps, step: RegistrationSteps.READY, errorMessage: null, } }, methods: { arrayToBase64String(a) { return btoa(String.fromCharCode(...a)) }, base64url2base64(input) { input = input .replace(/=/g, '') .replace(/-/g, '+') .replace(/_/g, '/') const pad = input.length % 4 if (pad) { if (pad === 1) { throw new Error('InvalidLengthError: Input base64url string is the wrong length to determine padding') } input += new Array(5 - pad).join('=') } return input }, start() { this.errorMessage = null logger.info('Starting to add a new twofactor webauthn device') this.step = RegistrationSteps.REGISTRATION return confirmPassword() .then(this.getRegistrationData) .then(this.register.bind(this)) .then(() => (this.step = RegistrationSteps.NAMING)) .catch(error => { if (error && error.name && error.message) { logger.error(error.name + ': ' + error.message, { error, }) // Do not show an error when the user aborts registration if (error.name !== 'AbortError') { this.errorMessage = error.message } } this.step = RegistrationSteps.READY }) }, getRegistrationData() { return startRegistration() .then(publicKey => { publicKey.challenge = Uint8Array.from(window.atob(this.base64url2base64(publicKey.challenge)), c => c.charCodeAt(0)) publicKey.user.id = Uint8Array.from(window.atob(publicKey.user.id), c => c.charCodeAt(0)) if (publicKey.excludeCredentials) { publicKey.excludeCredentials = publicKey.excludeCredentials.map(data => { data.id = Uint8Array.from(window.atob(this.base64url2base64(data.id)), c => c.charCodeAt(0)) return data }) } return publicKey }) .catch(error => { logger.error('getRegistrationData: Error getting webauthn registration data from server', { error }) throw new Error(t('twofactor_webauthn', 'Server error while trying to add WebAuthn device')) }) }, register(publicKey) { logger.debug('starting webauthn registration') return navigator.credentials.create({ publicKey }) .then(debug('navigator.credentials.create called')) .then(data => { this.credential = { id: data.id, type: data.type, rawId: this.arrayToBase64String(new Uint8Array(data.rawId)), response: { clientDataJSON: this.arrayToBase64String(new Uint8Array(data.response.clientDataJSON)), attestationObject: this.arrayToBase64String(new Uint8Array(data.response.attestationObject)), }, } }) .then(debug('mapped credentials data')) .catch(error => { logger.error('register: Error creating credentials', { error }) throw error }) }, submit() { this.step = RegistrationSteps.PERSIST return confirmPassword() .then(this.saveRegistrationData) .then(debug('registration data saved')) .then(() => this.reset()) .then(debug('app reset')) .then(() => this.$emit('add')) .catch(error => { logger.error(error, error.name) this.errorMessage = error.message this.step = RegistrationSteps.READY }) }, saveRegistrationData() { return finishRegistration(this.name, JSON.stringify(this.credential)) .then(device => this.$store.commit('addDevice', device)) .then(debug('new device added to store')) .catch(error => { logger.error('Error persisting webauthn registration', { error }) throw new Error(t('twofactor_webauthn', 'Server error while trying to complete security key registration')) }) }, reset() { this.name = '' this.registrationData = {} this.step = RegistrationSteps.READY }, }, } </script> <style scoped lang="scss"> .webauthn-loading { display: inline-block; vertical-align: sub; margin-left: 2px; margin-right: 5px; } .new-webauthn-device { display: flex; line-height: 300%; align-items: center; &__form { display: flex; align-items: center; } } .new-webauthn-device__button { margin: 10px 6px; } .error-message { color: var(--color-error); } input { /* Fix appearance on login setup page */ padding: 0; font-size: 15px; } </style>
# Проект Explore-with-me ## EDT схема ![Cхема](https://github.com/SergeiBrin/java-explore-with-me/blob/main/EDT%20ewm.png) ## Описание проекта Приложение explore-with-me - это сервис, который позволяет пользователям делиться информацией об интересных событиях и находить компанию для участия в них, а также подписываться на интересных людей, чтобы не пропустить ничего важного. Приложение состоит из 2 основных модулей, которые связаны между собой. ### 1. Основной сервис: Реализуют всю основную функциональность и хранит ключевые данные приложения. Отвечает за управление взаимодействием между моделью и представлением и обеспечивает корректное отображение данных пользователю. В основном сервисе находится точка входа в приложение. API основного сервиса состоит из трех частей: • **публичная** - доступна без регистрации любому пользователю сети; • **закрытая** - доступна только авторизованным пользователям; • **административная** — для администраторов сервиса. Для каждого слоя работает свой контроллер. ### 2. Сервис статистики (состоит из трех подмодулей): 1. **Подмодуль - Клиент:**<br> Связывает основной сервис с сервисом статистики через HTTP запросы. 2. **Подмодуль - Dto:**<br> Хранит модели DTO, используемые как клиентом, так и статистикой. 3. **Подмодуль - Статистика.**<br> Основной подмодуль сервиса статистики. Реализуют его основную функциональность - сохраняет статистику публичных запросов к событиям, поступающих в PublicEventController основного сервиса. В дальнейшем позволяет делать выборки по количеству обращений - как по общему количеству просмотров для события, так и по количеству уникальных пользователей, смотревших его. ## Инструкция по развёртыванию и системные требования JDK 11 и выше, Maven, Spring Boot 2.7.6, зависимости из pom файла, настройки из application properties, файлы schema.sql с данными - в основном сервисе и в сервисе статистики. Чтобы запустить приложение в IntelijIdea, зайдите в «Edit Congigurations -> Add new configuration -> Application -> создайте две конфигурации для основного сервиса и для сервиса статистики. Пропишите в конфигурациях данные переменных окружения. Теперь создайте в конфигурациях Compound» и добавьте в него эти две Application. Запустите Compound. Чтобы запустить приложение в Docker сделайте следующие шаги: 1. Соберите jar c помощью команды mvn clean package - для всего проекта. 2. Запустите Docker. 3. Откройте командную строку 4. Перейдите в корневую папку проекта Explore-with-me. 5. Введите команду docker-compose up.
// // Models.swift // RickAndMorty // // Created by Daniel Agbemava on 02/01/2023. // import Foundation struct Episode : Codable, Hashable { var id: Int var name: String var airDate: String var episode: String var characters: [String] var url: String enum CodingKeys : String, CodingKey { case id case name case airDate = "air_date" case episode case characters case url } } let dummyEpisode = Episode( id: 1, name: "Pilot", airDate: "December 2, 2013", episode: "S01E01", characters: [ "https://rickandmortyapi.com/api/character/1", "https://rickandmortyapi.com/api/character/2", ], url: "https://rickandmortyapi.com/api/episode/1" )
###################################################### # Bar plots Similar to Jagsi Paper and Correlations # # Between Dim 2 and Other Continuous Variables # ###################################################### library( tidyverse ) library( ggpubr ) # for arranging subplots library( Hmisc ) # for correlation matrix with p-values d <- readRDS( "../03-data-rodeo/01-data-mca-recat.rds" ) ### Worse Status Questions ### ### Bar Plot for Worse Financial Effect ### # get p-value for plot t.fin.s <- table( d$worse_financial_status, d$fi_binary ) p.fin.s <- round( chisq.test( t.fin.s, simulate.p.value = T )$p.value, 2 ) p.fin.s <- ifelse( p.fin.s == 1, "0.99", p.fin.s ) # to avoid 1's p.fin.s <- ifelse( p.fin.s == 0, "'< 0.01'", p.fin.s ) # to avoid 1's p.fin.s <- str_replace( p.fin.s, "(\\.\\d)$", "\\10" ) # for significant digits # generate plot fin.s.plot <- d %>% filter( !is.na( worse_financial_status ) & !is.na( fi_binary ) ) %>% ggplot() + geom_bar( aes( fi_binary, fill = factor( worse_financial_status ) ), width = 0.35 ) + scale_fill_manual( values = c( "#F0E442", "#0072B2" ), # set manual colors breaks = c( "No", "Yes" ) ) + theme_classic() + theme( text = element_text( family = "Avenir" ), legend.position = c( 0.8, 0.8 ), legend.title = element_blank(), axis.title.x = element_blank(), axis.text.x = element_text( size = 12, face = "bold" ), axis.title.y = element_text( size = 12, face = "bold" ), plot.title = element_text( face = "italic" ) ) + ylab( "Frequency" ) + annotate("text", x = 2.2, y = 100, label = paste0( "italic(p) ==", p.fin.s ), # add annotated p-value with only p italicized parse = T, family = "Avenir", size = 5 ) + ggtitle( "Worse Financial Status Since Cancer Diagnosis" ) ### Bar Plot for Worse Health Insurance Effect ### # get p-value for plot t.hi.s <- table( d$worse_insurance, d$fi_binary ) p.hi.s <- round( chisq.test( t.hi.s, simulate.p.value = T )$p.value, 2 ) p.hi.s <- ifelse( p.hi.s == 1, "0.99", p.hi.s ) # to avoid 1's p.hi.s <- ifelse( p.hi.s == 0, "'< 0.01'", p.hi.s ) # to avoid 1's p.hi.s <- str_replace( p.hi.s, "(\\.\\d)$", "\\10" ) # for significant digits # generate plot hi.s.plot <- d %>% filter( !is.na( worse_insurance ) & !is.na( fi_binary ) ) %>% ggplot() + geom_bar( aes( fi_binary, fill = factor( worse_insurance ) ), width = 0.35 ) + scale_fill_manual( values = c( "#F0E442", "#0072B2" ), # set manual colors breaks = c( "No", "Yes" ) ) + theme_classic() + theme( text = element_text( family = "Avenir" ), legend.position = c( 0.8, 0.8 ), legend.title = element_blank(), axis.title.x = element_blank(), axis.text.x = element_text( size = 12, face = "bold" ), axis.title.y = element_text( size = 12, face = "bold" ), plot.title = element_text( face = "italic" ) ) + ylab( "Frequency" ) + annotate("text", x = 2.2, y = 100, label = paste0( "italic(p) ==", p.hi.s ), # add annotated p-value with only p italicized parse = T, family = "Avenir", size = 5 ) + ggtitle( "Worse Insurance Status Since Cancer Diagnosis" ) ### Bar Plot for Worse Employment Effect ### # get p-value for plot t.emp.s <- table( d$worse_employment_status, d$fi_binary ) p.emp.s <- round( chisq.test( t.emp.s, simulate.p.value = T )$p.value, 2 ) p.emp.s <- ifelse( p.emp.s == 1, "0.99", p.emp.s ) # to avoid 1's p.emp.s <- ifelse( p.emp.s == 0, "'< 0.01'", p.emp.s ) # to avoid 1's p.emp.s <- str_replace( p.emp.s, "(\\.\\d)$", "\\10" ) # for significant digits # generate plot emp.s.plot <- d %>% filter( !is.na( worse_employment_status ) & !is.na( fi_binary ) ) %>% ggplot() + geom_bar( aes( fi_binary, fill = factor( worse_employment_status ) ), width = 0.35 ) + scale_fill_manual( values = c( "#F0E442", "#0072B2" ), # set manual colors breaks = c( "No", "Yes" ) ) + theme_classic() + theme( text = element_text( family = "Avenir" ), legend.position = c( 0.8, 0.8 ), legend.title = element_blank(), axis.title.x = element_blank(), axis.text.x = element_text( size = 12, face = "bold" ), axis.title.y = element_text( size = 12, face = "bold" ), plot.title = element_text( face = "italic" ) ) + ylab( "Frequency" ) + annotate("text", x = 2.2, y = 100, label = paste0( "italic(p) ==", p.emp.s ), # add annotated p-value with only p italicized parse = T, family = "Avenir", size = 5 ) + ggtitle( "Worse Employment Status Since Cancer Diagnosis" ) ### Arrange into Single Plot ### worse.plot <- ggarrange( hi.s.plot, emp.s.plot + theme( legend.position = "none", legend.text = element_text( size = 19 )), fin.s.plot + theme( legend.position = "none"), labels = list( "A", "", ""), nrow = 3, ncol = 1 ) ggsave( "../04-tables-figures/worse-bar-plots.png", width = 7.36, height = 10.42 ) ### Effect Questions ### ### Bar Plot for Worse Financial Effect ### # get p-value for plot t.fin <- table( d$financial_status_effect, d$fi_binary ) p.fin <- round( chisq.test( t.fin, simulate.p.value = T )$p.value, 2 ) p.fin <- ifelse( p.fin == 1, "0.99", p.fin ) # to avoid 1's p.fin <- str_replace( p.fin, "(\\.\\d)$", "\\10" ) # for significant digits # generate plot fin.plot <- d %>% filter( !is.na( financial_status_effect ) & !is.na( fi_binary ) ) %>% ggplot() + geom_bar( aes( fi_binary, fill = factor( financial_status_effect ) ), width = 0.35 ) + scale_fill_manual( values = c( "#F0E442", "#0072B2" ), # set manual colors breaks = c( "Little/Somewhat/Not at all", "Quite a bit/Very much" ) ) + theme_classic() + theme( text = element_text( family = "Avenir" ), legend.position = c( 0.8, 0.8 ), legend.title = element_blank(), axis.title.x = element_blank(), axis.text.x = element_text( size = 12, face = "bold" ), axis.title.y = element_text( size = 12, face = "bold" ), plot.title = element_text( face = "italic" ) ) + ylab( "Frequency" ) + annotate("text", x = 1.9, y = 35, label = paste0( "italic(p) ==", p.fin ), # add annotated p-value with only p italicized parse = T, family = "Avenir", size = 5 ) + ggtitle( "Worse Financial Status Due to Cancer Diagnosis" ) ### Bar Plot for Worse Health Insurance Effect ### # get p-value for plot t.hi <- table( d$health_insurance_effect, d$fi_binary ) p.hi <- round( fisher.test( t.hi, simulate.p.value = T )$p.value, 2 ) p.hi <- ifelse( p.hi == 1, "0.99", p.hi ) # to avoid 1's p.hi <- str_replace( p.hi, "(\\.\\d)$", "\\10" ) # for significant digits # generate plot hi.plot <- d %>% filter( !is.na( health_insurance_effect ) & !is.na( fi_binary ) ) %>% ggplot() + geom_bar( aes( fi_binary, fill = factor( health_insurance_effect ) ), width = 0.35 ) + scale_fill_manual( values = c( "#F0E442", "#0072B2" ), # set manual colors breaks = c( "Little/Somewhat/Not at all", "Quite a bit/Very much" ) ) + theme_classic() + theme( text = element_text( family = "Avenir" ), legend.position = c( 0.8, 0.85 ), legend.title = element_blank(), axis.title.x = element_blank(), legend.text = element_text( size = 12 ), axis.text.x = element_text( size = 12, face = "bold" ), axis.title.y = element_text( size = 12, face = "bold" ), plot.title = element_text( face = "italic" ) ) + ylab( "Frequency" ) + annotate("text", x = 1.9, y = 9.5, label = paste0( "italic(p) ==", p.hi ), # add annotated p-value with only p italicized parse = T, family = "Avenir", size = 5 ) + ggtitle( "Worse Insurance Status Due to Cancer Diagnosis" ) ### Bar Plot for Worse Employment Effect ### # get p-value for plot t.emp <- table( d$employment_status_effect, d$fi_binary ) p.emp <- round( fisher.test( t.emp, simulate.p.value = T )$p.value, 2 ) p.emp <- ifelse( p.emp == 1, "0.99", p.emp ) # to avoid 1's p.emp <- str_replace( p.emp, "(\\.\\d)$", "\\10" ) # for significant digits # generate plot emp.plot <- d %>% filter( !is.na( employment_status_effect ) & !is.na( fi_binary ) ) %>% ggplot() + geom_bar( aes( fi_binary, fill = factor( employment_status_effect ) ), width = 0.35 ) + scale_fill_manual( values = c( "#F0E442", "#0072B2" ), # set manual colors breaks = c( "Little/Somewhat/Not at all", "Quite a bit/Very much" ) ) + theme_classic() + theme( text = element_text( family = "Avenir" ), legend.position = c( 0.8, 0.8 ), legend.title = element_blank(), axis.title.x = element_blank(), axis.text.x = element_text( size = 12, face = "bold" ), axis.title.y = element_text( size = 12, face = "bold" ), plot.title = element_text( face = "italic" ) ) + ylab( "Frequency" ) + annotate("text", x = 1.9, y = 20, label = paste0( "italic(p) ==", p.emp ), # add annotated p-value with only p italicized parse = T, family = "Avenir", size = 5 ) + ggtitle( "Worse Empoyment Status Due to Cancer Diagnosis" ) ### Arrange into Single Plot ### effect.plot <- ggarrange( hi.plot, emp.plot + theme( legend.position = "none", legend.text = element_text( size = 19 )), fin.plot + theme( legend.position = "none"), labels = list( "B", "", ""), nrow = 3, ncol = 1 ) ggsave( "../04-tables-figures/effect-bar-plots.png", width = 7.36, height = 10.42 ) ### Now Arrange Effect and Worse Plots into Single Plot ### all.plot <- ggarrange( worse.plot, effect.plot, nrow = 1, ncol = 2) ggsave( "../04-tables-figures/worse-effect-bar-plots.png", width = 9.72, height = 14.84 ) ### Correlation Matrix of Dim 2 with other Variables ### # create a matrix of variables to include in the correlation analysis d.cor <- d %>% filter( number_household >= 2 ) %>% #filter by no. in household given potential issues with CHAOS score select( mca.dim.2, chaos_score, age, yrs_since_dx, financial_skills_index,factg_total, factg_pwb, factg_ewb, factg_fwb, factg_swb ) %>% as.matrix() # generate the table (p-values also printed) rcor.obj <- rcorr(as.matrix(d.cor)) # retain the correlations and p-values matrices cor.mat <- round( rcor.obj$r, 2 ) p.mat <- rcor.obj$P # assign asteriks depending on the p-values matrix for( i in 1:nrow( cor.mat ) ){ for( j in 1:ncol( cor.mat ) ){ cor.mat[i,j] <- ifelse( p.mat[i,j] < 0.05, paste0( cor.mat[i,j], "*" ), cor.mat[i,j] ) } } write.table( cor.mat, "../04-tables-figures/financial-tox-correlation-matrix.txt", sep = "," )
/************************************************************************** FRISC 2.0: FRISC 2.0 je temeljen na procesoru FRISC 1.0 Autor arhitekture: Danko Basch, 30.XII.2005. Autor prve verzije modela za ATLAS: Danko Basch FRISC 1.0: Autor arhitekture: Mladen Tomic (mentor: Mario Kovac) koautori: Alan Goluban, Danko Basch Autor prve verzije modela za ATLAS: Mladen Tomic Prepravci prve verzije modela za ATLAS: Danko Basch Autori druge verzije modela za ATLAS: Danko Basch, Valentin Vidic **************************************************************************/ registers { PC/.32./, // Program Counter R[8] /.32./, // 8 registara opce namjene SR/.8./, // Status Register IIF/.1./, // Internal Interrupt Flag // ako je IIF=0, NMI je u toku i svi intovi su zabranjeni AR/.32./, // Address Register DR/.32./, // Data Register IR/.32./; // Instruction Register } variables { // KONSTANTE // Vrijednosti im se postavljaju u init // Sirina pristupa memoriji (za prikljucak SIZE) NONE/.2./, BYTE/.2./, HALFWORD/.2./, WORD/.2./, // Vrste naredaba (za varijablu instruction_type) ALU_instr/.2./, // Oznake tipa dohvacene naredbe: CTRL_instr/.2./, // Postavljaju se za vrijeme dekodiranja. MEM_instr/.2./, REG_instr/.2./, // Strojni kodovi naredaba (za razna dekodiranja) OR_opcode/.5./, AND_opcode/.5./, XOR_opcode/.5./, ADD_opcode/.5./, ADC_opcode/.5./, SUB_opcode/.5./, SBC_opcode/.5./, ROTL_opcode/.5./, ROTR_opcode/.5./, SHL_opcode/.5./, SHR_opcode/.5./, ASHR_opcode/.5./, CMP_opcode/.5./, MOVE_opcode/.5./, JP_opcode/.5./, CALL_opcode/.5./, JR_opcode/.5./, RET_opcode/.5./, HALT_opcode/.5./, LOAD_opcode/.5./, STORE_opcode/.5./, LOADB_opcode/.5./, STOREB_opcode/.5./, LOADH_opcode/.5./, STOREH_opcode/.5./, POP_opcode/.5./, PUSH_opcode/.5./, // O(ne)mogucenost razine pipelinea (za varijable FETCH i EXEC) DISABLED/.32./, ENABLED /.32./, // Boolean vrijednost uvjeta u upravljackim naredbama // (za varijablu condition) FALSE/.1./, TRUE /.1./, // POMOCNE: alu_src1/.32./, alu_src2/.32./, alu_res/.32./, alu_flags/.32./, instruction_type/.2./, // Oznaka tipa dohvacene naredbe op_code/.5./, // Operacijski kod naredbe condition/.1./, // Oznaka je li uvjet naredbe istinit tmp/.32./, // ZASTAVICE ZA STANJE // PREKIDA I PIPELINA: FETCH_stage/.32./, // Oznake omogucenosti/onemogucenosti za EXEC_stage /.32./, // razine FETCH i EXEC u pipelineu. nmi_pending/.1./, // nm-interrupt ceka? mi_pending/.1./, // m-interrupt ceka? fetched/.1./, // da li je dohvacena instrukcija? dma_executed/.1./, // da li se desio dma prijenos? // Za provjeru ispravnosti redoslijeda pokretanja: init, run initialized/.32./; } pins { A/.32./, // adresna sabirnica D/.32./, // data sabirnica RESET, READ, WRITE, SIZE/.2./, WAIT, BREQ, BACK, // DMA INT3, IACK, // interrupt nmi INT0, INT1, INT2; // interrupt mi } init { // KONSTANTE: // Sirina pristupa memoriji (za prikljucak SIZE) let NONE = %b 00; let BYTE = %b 01; let HALFWORD = %b 10; let WORD = %b 11; // Vrste naredaba (za varijablu instruction_type) let ALU_instr = 0; let CTRL_instr = 1; let MEM_instr = 2; let REG_instr = 3; // Strojni kodovi naredaba (za razna dekodiranja) let OR_opcode = %B 00001; let AND_opcode = %B 00010; let XOR_opcode = %B 00011; let ADD_opcode = %B 00100; let ADC_opcode = %B 00101; let SUB_opcode = %B 00110; let SBC_opcode = %B 00111; let ROTL_opcode = %B 01000; let ROTR_opcode = %B 01001; let SHL_opcode = %B 01010; let SHR_opcode = %B 01011; let ASHR_opcode = %B 01100; let CMP_opcode = %B 01101; // let _opcode = %B 01110; // Not used // let _opcode = %B 01111; // Not used let MOVE_opcode = %B 00000; let JP_opcode = %B 11000; let CALL_opcode = %B 11001; let JR_opcode = %B 11010; let RET_opcode = %B 11011; let HALT_opcode = %B 11111; let LOAD_opcode = %B 10110; let STORE_opcode = %B 10111; let LOADB_opcode = %B 10010; let STOREB_opcode = %B 10011; let LOADH_opcode = %B 10100; let STOREH_opcode = %B 10101; let POP_opcode = %B 10000; let PUSH_opcode = %B 10001; // O(ne)mogucenost razine pipelinea (za varijable FETCH i EXEC) let DISABLED = 1; let ENABLED = 0; // Boolean vrijednost uvjeta u upravljackim naredbama // (za varijablu condition) let FALSE = 0; let TRUE = 1; // STANJE PROCESORA: let IIF = 1; let PC = 0; let R[0] = 0; let R[1] = 0; let R[2] = 0; let R[3] = 0; let R[4] = 0; let R[5] = 0; let R[6] = 0; let R[7] = 0; let SR=0; let A=0; disable D; let READ=1; let WRITE=1; let SIZE=NONE; disable WAIT; disable BREQ; let BACK=1; disable RESET; disable INT0, INT1, INT2, INT3; let IACK=1; let initialized = %H 12345678; } check_condition { // ******** PROVJERA UVJETA ZA SKOK ******* decode( IR/.22..25./ ) { %B 0000: { // **** Unconditional TRUE let condition=1; } %B 0001: { // ******** N,M N=1 let condition=SR/.0./; } %B 0010: { // ******** NN,P N=0 not( SR/.0./, condition ); } %B 0011: { // ******** C,ULT C=1 let condition=SR/.1./; } %B 0100: { // ******** NC,UGE C=0 not( SR/.1./, condition ); } %B 0101: { // ******** V V=1 let condition=SR/.2./; } %B 0110: { // ******** NV V=0 not( SR/.2./, condition ); } %B 0111: { // ******** Z,EQ Z=1 let condition=SR/.3./; } %B 1000: { // ******** NZ,NE Z=0 not( SR/.3./, condition ); } %B 1001: { // ******** ULE C=1 ili Z=1 or( SR/.1./, SR/.3./, condition ); } %B 1010: { // ******** UGT C=0 i Z=0 nor( SR/.1./, SR/.3./, condition ); } %B 1011: { // ******** SLT (N xor V)=1 xor( SR/.0./, SR/.2./, condition ); } %B 1100: { // ******** SLE (N xor V)=1 ili Z=1 xor( SR/.0./, SR/.2./, condition ); or( condition, SR/.3./, condition ); } %B 1101: { // ******** SGE (N xor V)=0 nxor( SR/.0./, SR/.2./, condition ); } %B 1110: { // ******** SGT (N xor V)=0 i Z=0 xor( SR/.0./, SR/.2./, condition ); nor( condition, SR/.3./, condition ); } } } ispis_registara { print( "----------------------------------------------------", / ); print( " R0=",%8.h R[0], " R1=",%8.h R[1] ); print( " 210G210ZVCN", / ); print( " R2=",%8.h R[2], " R3=",%8.h R[3] ); print( " SR=", %1.b INT2, %1.b INT1, %1.b INT0, %8.b SR, / ); print( " R4=",%8.h R[4], " R5=",%8.h R[5], / ); print( " R6=",%8.h R[6], " R7=",%8.h R[7] ); print( " PC=", %8.h PC, " IIF=", %1.b IIF, / ); print( "----------------------------------------------------", / ); } REG_ispis { print( "MOVE " ); // PRINT source if( IR/.21./ = 1 ) { print( "SR, " ); } else { if( IR/.26./ = 0 ) { print( "R", %1.u IR/.17..19./, ", " ); } else { let tmp = (signed) IR/.0..19./; if (IR/.19./=0) { print( %8.h tmp, ", " ); } else { neg( tmp, tmp ); //immediate je negativan print ( "-", %8.h tmp, ", " ); } } } // PRINT destination if( IR/.20./ = 1 ) { print( "SR", / ); } else { print( "R", %1.u IR/.23..25./, / ); } } ALU_ispis { let op_code = IR/.27..31./; if( op_code == SBC_opcode ) { print( "SBC" ); } else if( op_code == ADD_opcode ) { print( "ADD" ); } else if( op_code == SUB_opcode ) { print( "SUB" ); } else if( op_code == ADC_opcode ) { print( "ADC" ); } else if( op_code == AND_opcode ) { print( "AND" ); } else if( op_code == XOR_opcode ) { print( "XOR" ); } else if( op_code == OR_opcode ) { print( "OR" ); } else if( op_code == ROTL_opcode ) { print( "ROTL" ); } else if( op_code == ROTR_opcode ) { print( "ROTR" ); } else if( op_code == SHL_opcode ) { print( "SHL" ); } else if( op_code == SHR_opcode ) { print( "SHR" ); } else if( op_code == ASHR_opcode ) { print( "ASHR" ); } else if( op_code == CMP_opcode ) { print( "CMP" ); } print ( " R", %1.u IR/.20..22./, ", " ); // source1 if ( IR/.26./ = 0 ) { //da li je source2 registar ili immediate print( "R", %1.u IR/.17..19./ ); } else { if (IR/.19./=0) { print( %8.h alu_src2 ); } else { neg( alu_src2, tmp ); //immediate je negativan print ( "-", %8.h tmp ); } } if ( op_code == CMP_opcode ) { print( / ); //za CMP nema destination registra } else { print ( ", R", %1.u IR/.23..25./, / ); } } ispis_uvjeta { switch (IR/.22..25./) { //0: print ( "" ); 1: print ( "_N/M" ); 2: print ( "_NN/P" ); 3: print ( "_C/ULT" ); 4: print ( "_NC/UGE" ); 5: print ( "_V" ); 6: print ( "_NV" ); 7: print ( "_Z/EQ" ); 8: print ( "_NZ/NE" ); 9: print ( "_ULE" ); 10: print ( "_UGT" ); 11: print ( "_SLT" ); 12: print ( "_SLE" ); 13: print ( "_SGE" ); 14: print ( "_SGT" ); } } CTRL_ispis { let op_code = IR/.27..31./; if( op_code == RET_opcode ) { print( "RET" ); if( IR/.0./=1 and IR/.1./=0 ) print( "I" ); if( IR/.0./=1 and IR/.1./=1 ) print( "N" ); call ispis_uvjeta; print ( / ); } else if( op_code == JR_opcode ) { print( "JR" ); call ispis_uvjeta; if( IR/.19./ == 0 ) { print( " +", %6.H IR/.0..18./ ); } else { neg( (signed) IR/.0..19./, tmp ); print( " -", %6.H tmp ); } add( PC, (signed) IR/.0..19./, tmp ); let tmp/.0..1./ = 0; print( " -> ", %8.H tmp, / ); } else if( op_code == CALL_opcode ) { print( "CALL"); call ispis_uvjeta; if (IR/.26./ = 0) { print ( " (R", %1.u IR/.17..19./, ")", / ); } else { let tmp = (signed) IR/.0..19./; let tmp/.0..1./ = 0; print ( " ", %8.H tmp, / ); } } else if( op_code == JP_opcode ) { print( "JP" ); call ispis_uvjeta; if (IR/.26./ = 0) { print ( " (R", %1.u IR/.17..19./, ")", / ); } else { let tmp = (signed) IR/.0..19./; let tmp/.0..1./ = 0; print ( " ", %8.H tmp, / ); } } else if( op_code == HALT_opcode ) { print( "HALT" ); call ispis_uvjeta; print ( / ); } } MEM_ispis { let op_code = IR/.27..31./; if( op_code == LOAD_opcode ) { print( "LOAD" ); } else if( op_code == STORE_opcode ) { print( "STORE" ); } else if( op_code == LOADB_opcode ) { print( "LOADB" ); } else if( op_code == STOREB_opcode ) { print( "STOREB" ); } else if( op_code == LOADH_opcode ) { print( "LOADH" ); } else if( op_code == STOREH_opcode ) { print( "STOREH" ); } else if( op_code == PUSH_opcode ) { print( "PUSH" ); print(" R", %1.u IR/.23..25./, / ); return; } else if( op_code == POP_opcode ) { print( "POP" ); print(" R", %1.u IR/.23..25./, / ); return; } print( " R", %1.u IR/.23..25./ ); if (IR/.26./ = 0 ) { print( ", (", %8.H (signed) IR/.0..19./, ")", /); } else { /////// (REGISTARSKO_INDIREKTNO_S_ODMAKOM) ///////// print( ", (R", %1.u IR/.20..22./ ); if( IR/.19./ == 0 ) { print( " +", %6.H IR/.0..18./ ); } else { neg( (signed) IR/.0..19./, tmp ); print( " -", %6.H tmp ); } print( ")", / ); } } ispis_naredbe { if ( instruction_type == ALU_instr ) { call ALU_ispis; return; } if ( instruction_type == CTRL_instr ) { call CTRL_ispis; return; } if ( instruction_type == MEM_instr ) { call MEM_ispis; return; } if ( instruction_type == REG_instr ) { call REG_ispis; return; } } dekodiraj { let op_code = IR/.27..31./; if( op_code >>= OR_opcode and op_code <<= CMP_opcode ) { let instruction_type = ALU_instr; } else if( op_code == MOVE_opcode ) { let instruction_type = REG_instr; } else if( op_code >>= POP_opcode and op_code <<= STORE_opcode ) { let instruction_type = MEM_instr; } else if( op_code >>= JP_opcode and op_code <<= RET_opcode ) { let instruction_type = CTRL_instr; } else if( op_code == HALT_opcode ) { let instruction_type = CTRL_instr; } else { print( "Nepostojeca instrukcija", / ); exit; } } fetch_rise { let AR = PC; let A = AR; disable D; let READ = 0; let SIZE = WORD; } exec_rise { trace.1 { call ispis_registara; } trace.2 { call ispis_naredbe; } trace.3 { waitkey; } let op_code = IR/.27..31./; if( instruction_type == CTRL_instr ) { if( condition == FALSE ) { return; } if( op_code == RET_opcode ) { let AR = R[7]; let AR/.0..1./ = 0; let A = AR; disable D; let READ = 0; let SIZE = WORD; } else if( op_code == CALL_opcode ) { sub( R[7], 4, R[7] ); let AR = R[7]; let AR/.0..1./ = 0; let DR = PC; let A = AR; let D = DR; let WRITE = 0; let SIZE = WORD; } else if( op_code == JR_opcode ) { // Ne radi ovdje nista } else if( op_code == JP_opcode ) { // Ne radi ovdje nista } else if( op_code == HALT_opcode ) { // Ne radi ovdje nista } return; } if( instruction_type == ALU_instr ) { if( op_code == SBC_opcode ) { not(SR/.1./,flagc); // C=-C subcf(alu_src1, alu_src2, alu_res); let alu_flags/.0./ = flags; not( flagc, alu_flags/.1./ ); let alu_flags/.2./ = flago; let alu_flags/.3./ = flagz; } else if( op_code == ADD_opcode ) { addf(alu_src1, alu_src2, alu_res); let alu_flags/.0./ = flags; let alu_flags/.1./ = flagc; let alu_flags/.2./ = flago; let alu_flags/.3./ = flagz; } else if( op_code == SUB_opcode ) { subf(alu_src1, alu_src2, alu_res); let alu_flags/.0./ = flags; not( flagc, alu_flags/.1./ ); let alu_flags/.2./ = flago; let alu_flags/.3./ = flagz; } else if( op_code == ADC_opcode ) { let flagc = SR/.1./; addcf(alu_src1, alu_src2, alu_res); let alu_flags/.0./ = flags; let alu_flags/.1./ = flagc; let alu_flags/.2./ = flago; let alu_flags/.3./ = flagz; } else if( op_code == AND_opcode ) { andf(alu_src1, alu_src2, alu_res); let alu_flags/.0./ = flags; let alu_flags/.1./ = 0; let alu_flags/.2./ = 0; let alu_flags/.3./ = flagz; } else if( op_code == XOR_opcode ) { xorf(alu_src1, alu_src2, alu_res); let alu_flags/.0./ = flags; let alu_flags/.1./ = 0; let alu_flags/.2./ = 0; let alu_flags/.3./ = flagz; } else if( op_code == OR_opcode ) { orf(alu_src1, alu_src2, alu_res); let alu_flags/.0./ = flags; let alu_flags/.1./ = 0; let alu_flags/.2./ = 0; let alu_flags/.3./ = flagz; } else if( op_code == ROTL_opcode ) { shiftlhf(alu_src1, alu_src2/.0..4./, alu_res); let alu_flags/.0./ = flags; let alu_flags/.1./ = flagx; let alu_flags/.2./ = 0; let alu_flags/.3./ = flagz; } else if( op_code == ROTR_opcode ) { shiftrlf(alu_src1, alu_src2/.0..4./, alu_res); let alu_flags/.0./ = flags; let alu_flags/.1./ = flagx; let alu_flags/.2./ = 0; let alu_flags/.3./ = flagz; } else if( op_code == SHL_opcode ) { shiftl0f(alu_src1, alu_src2/.0..4./, alu_res); let alu_flags/.0./ = flags; let alu_flags/.1./ = flagx; let alu_flags/.2./ = 0; let alu_flags/.3./ = flagz; } else if( op_code == SHR_opcode ) { shiftr0f(alu_src1, alu_src2/.0..4./, alu_res); let alu_flags/.0./ = flags; let alu_flags/.1./ = flagx; let alu_flags/.2./ = 0; let alu_flags/.3./ = flagz; } else if( op_code == ASHR_opcode ) { shiftrhf(alu_src1, alu_src2/.0..4./, alu_res); let alu_flags/.0./ = flags; let alu_flags/.1./ = flagx; let alu_flags/.2./ = 0; let alu_flags/.3./ = flagz; } else if( op_code == CMP_opcode ) { subf(alu_src1, alu_src2, alu_res); let alu_flags/.0./ = flags; not( flagc, alu_flags/.1./ ); let alu_flags/.2./ = flago; let alu_flags/.3./ = flagz; } return; } if( op_code == MOVE_opcode ) { // Ne radi ovdje nista return; } if( op_code >>= LOADB_opcode and op_code <<= STORE_opcode ) { ////// SVE LOAD i STORE NAREDBE ////// Odredi adresu za LOAD/STORE if( IR/.26./ == 0 ) { //// (APSOLUTNA ADRESA) let AR = (signed) IR/.0..19./; } else { //// (REGISTAR+OFSET) add( R[IR/.20..22./], (signed) IR/.0..19./, AR ); } ///// Podesi adresu za HALFWORD i WORD if( IR/.28..29./ == %B 11 ) { //// WORD let AR/.0..1./ = 0; } else if( IR/.28..29./ == %B 10 ) { //// HALFWORD let AR/.0./ = 0; } ///// Je li LOAD ili STORE? if( IR/.27./ == 0 ) { let A = AR; disable D; let READ = 0; let SIZE = IR/.28..29./; } else { ///// Pomakni podatak na pravu poziciju bajta ili polurijeci. ///// Na ostalim pozicijama u rijeci ostaje "smece". let DR = R[ IR/.23..25./ ]; let tmp = 0; let tmp/.3..4./ = AR/.0..1./; shiftlh( DR, tmp, DR ); let A = AR; let D = DR; let WRITE = 0; let SIZE = IR/.28..29./; } } else if( op_code == PUSH_opcode ) { sub( R[7], 4, R[7] ); let AR = R[7]; let AR/.0..1./ = 0; let DR = R[ IR/.23..25./ ]; let A = AR; let D = DR; let WRITE = 0; let SIZE = WORD; } else if( op_code == POP_opcode ) { let AR = R[7]; let AR/.0..1./ = 0; let A = AR; disable D; let READ = 0; let SIZE = WORD; } } fetch_1_fall { brkpt PC; add( PC, 4, PC ); let PC/.0..1./ = 0; wait( fall( clock ) and WAIT == 1 ); let DR = D; let READ = 1; let SIZE = NONE; } exec_fall { let op_code = IR/.27..31./; if( instruction_type==ALU_instr ) { let SR/.0..3./ = alu_flags/.0..3./; if( op_code !== CMP_opcode ) { // sve osim CMP let R[IR/.23..25./] = alu_res; } return; } if( instruction_type==CTRL_instr ) { /// Ako je uvjet lazan, nema se sto izvoditi if( condition == FALSE ) { return; } if( op_code == RET_opcode ) { wait( fall( clock ) and WAIT == 1 ); let DR = D; let READ = 1; let SIZE = NONE; add ( R[7], 4, R[7] ); let PC = DR; let PC/.0..1./ = 0; if( IR/.0./ = 1 ) { if (IR/.1./ = 0) { let SR/.7./ = 1; // ******** RETI } else { let IIF =1; // ******** RETN } } } else if( op_code == CALL_opcode ) { wait( fall( clock ) and WAIT == 1 ); let WRITE = 1; let SIZE = NONE; if( IR/.26./ = 0 ) { let PC = R[IR/.17..19./]; } else { let PC = (signed) IR/.0..19./; } let PC/.0..1./ = 0; } else if( op_code == JR_opcode ) { add( PC, (signed) IR/.0..19./, PC ); let PC/.0..1./ = 0; } else if( op_code == JP_opcode ) { if( IR/.26./ = 0 ) { let PC = R[IR/.17..19./]; } else { let PC = (signed) IR/.0..19./; } let PC/.0..1./ = 0; } else if( op_code == HALT_opcode ) { print("processor halted.", /); exit; } return; } if( op_code == MOVE_opcode ) { // write to destination if( IR/.20./ = 1 ) { let SR = alu_src2; } else { let R[ IR/.23..25./ ] = alu_src2; } return; } if( op_code >>= LOADB_opcode and op_code <<= STORE_opcode ) { ////// SVE LOAD i STORE NAREDBE ///// Je li LOAD ili STORE? if( IR/.27./ == 0 ) { wait( fall( clock ) and WAIT == 1 ); let DR = D; let READ = 1; let SIZE = NONE; ///// Pomakni podatak na pravu poziciju bajta ili polurijeci. ///// Na ostalim pozicijama u procitanoj rijeci je "smece". let tmp = 0; let tmp/.3..4./ = AR/.0..1./; shiftrh( DR, tmp, DR ); ////// Brisanje "smeca" za BAJTOVE i POLURIJECI if( IR/.28..29./ = %B 01 ) { ////// BAJT let DR/.8..31./ = 0; } else if( IR/.28..29./ = %B 10 ) { ////// POLURIJEC let DR/.16..31./ = 0; } let R[IR/.23..25./]=DR; } else { wait( fall( clock ) and WAIT == 1 ); let WRITE = 1; let SIZE = NONE; } } else if( op_code == PUSH_opcode ) { wait( fall( clock ) and WAIT == 1 ); let WRITE = 1; let SIZE = NONE; } else if( op_code == POP_opcode ) { wait( fall( clock ) and WAIT == 1 ); let DR = D; let READ = 1; let SIZE = NONE; add ( R[7], 4, R[7] ); let R[IR/.23..25./]=DR; } } fetch_2_fall { let IR = DR; call dekodiraj; // odredi tip naredbe if( instruction_type==ALU_instr ) { // Za ALU-naredbe // dohvati operande u alu let alu_src1 = R[ IR/.20..22./ ]; if( IR/.26./ = 0 ) { let alu_src2 = R[ IR/.17..19./ ]; } else { let alu_src2 = (signed) IR/.0..19./; } return; } if ( instruction_type==CTRL_instr ) { call check_condition; return; } if ( instruction_type==MEM_instr ) { // Ovdje ne radi nista return; } if ( instruction_type==REG_instr ) { // calculate source if( IR/.21./ = 1 ) { let alu_src2 = SR; let alu_src2 /.8./ = INT0; let alu_src2 /.9./ = INT1; let alu_src2 /.10./ = INT2; } else { if( IR/.26./ = 0 ) { let alu_src2 = R[ IR/.17..19./ ]; } else { let alu_src2 = (signed) IR/.0..19./; } } return; } } test_int { // da li je postavljen interrupt? let nmi_pending = 0; let mi_pending = 0; if (IIF = 0) { return; } if (INT3 = 0) { let nmi_pending = 1; return; } if (SR/.7./ = 0) { // GIE return; } if( (SR/.4./ = 1 and INT0 = 0) or (SR/.5./ = 1 and INT1 = 0) or (SR/.6./ = 1 and INT2 = 0) ) { let mi_pending = 1; return; } } push_pc { on(rise(clock)); // PC -> stog sub( R[7], 4, R[7] ); let AR = R[7]; let AR/.0..1./ = 0; let DR = PC; let A = AR; let D = DR; let WRITE = 0; let SIZE = WORD; wait( fall( clock ) and WAIT == 1 ); let WRITE = 1; let SIZE = NONE; } handle_interrupt { call test_int; if ( nmi_pending = 0 and mi_pending = 0 ) { // nema int-a return; } if (fetched = 1) { if (IR/.31./ = 1) { // dohvacena 2ciklusna return; // -> izvrsi je do kraja } else { // dohvacena 1ciklusna sub(PC, 4, PC); // -> zaboravi je } } if ( nmi_pending = 1 ) { trace.4 { print("Prihvacen non-maskable interrupt", /); } let IACK = 0; let IIF = 0; call push_pc; let IACK = 1; let PC = 12; // 12 je adresa za nonmaskable potprogram } if ( mi_pending = 1 ) { trace.4 { print("Prihvacen maskable interrupt", /); } let SR/.7./ = 0; // GIE = 0 call push_pc; // PC <- (8) on(rise(clock)); let AR = 8; // 8 je adresa za nonmaskable potprogram let A = AR; disable D; let READ = 0; let SIZE = WORD; wait( fall( clock ) and WAIT == 1 ); let DR = D; let READ = 1; let SIZE = NONE; let PC = DR; let PC/.0..1./ = 0; } // dohvati prvu instrukciju prekidnog let FETCH_stage = ENABLED; let EXEC_stage = DISABLED; return; } handle_dma { // trenutno je fall(clock) let dma_executed = 0; if (BREQ = 1) { return; } // potvrdi na sljedeci rise(clock) on( rise(clock) ); disable A; disable D; disable READ; disable WRITE; disable SIZE; let BACK = 0; // provjeri BREQ na fall(clock) wait( fall(clock) and BREQ = 1 ); let READ = 1; let WRITE =1; let SIZE = NONE; // podigi BACK na sljedeci rise(clock) let dma_executed = 1; } run { // Provjera je li izveden init prije run if( initialized !== %H 12345678 ) { print( /, /, "Morate napraviti inicijalizaciju pomocu init" ); print( /, "prije pokretanja simulacije sa run", /, / ); exit; } let initialized = %H ABCDEF01; // Pocetak simulacije let FETCH_stage = ENABLED; // Na pocetku se radi dohvat, let EXEC_stage = DISABLED; // ali se jos nema sto izvesti. forever { on( rise( clock ) ); if( dma_executed = 1) { let BACK = 1; } if( FETCH_stage = ENABLED ) { call fetch_rise; } if( EXEC_stage = ENABLED ) { call exec_rise; } on( fall( clock ) ); if( FETCH_stage = ENABLED ) { call fetch_1_fall; } if( EXEC_stage = ENABLED ) { call exec_fall; } not( FETCH_stage, fetched); // fetched = da li je dohvacena instrukcija // provjerava se u handle_interrupt // (ne moze se koristiti FETCH_stage // jer se on mijenja u donjoj if naredbi) if ( FETCH_stage = ENABLED ) { call fetch_2_fall; if (IR/.31./ = 1){ // dvociklusna instrukcija let FETCH_stage = DISABLED; } // nesto smo dohvatili: // -> izvrsi to u sljedecem ciklusu let EXEC_stage = ENABLED; } else { // fetch je bio onemogucen: // - omoguci ga za sljedeci ciklus // - nista nismo dohvatili // -> onemoguci exec za sljedeci ciklus let FETCH_stage = ENABLED; let EXEC_stage = DISABLED; } call handle_dma; // ako se dma desio nalazimo se na rise(clock) // a handle interrupt ocekuje fall(clock) if (dma_executed = 0) { call handle_interrupt; } } // end forever }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <%@ include file="../../include/head.jsp"%> <body class="hold-transition skin-blue sidebar-mini layout-boxed"> <div class="wrapper"> <!-- Main Header --> <%@ include file="../../include/main_header.jsp"%> <!-- Left side column. contains the logo and sidebar --> <%@ include file="../../include/left_column.jsp"%> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> 게시판 <small>조회페이지(페이징+검색)</small> </h1> <ol class="breadcrumb"> <li><i class="fa fa-edit"></i> article</li> <li class="active"> read</li> </ol> </section> <!-- Main content --> <section class="content container-fluid"> <div class="col-lg-12"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">글제목 : ${article.title}</h3> </div> <div class="box-body" style="height: 700px"> ${article.content} </div> <div class="box-footer"> <div class="user-block"> <img class="img-circle img-bordered-sm" src="/dist/img/user1-128x128.jpg" alt="user image"> <span class="username"> <a href="#">${article.writer}</a> </span> <span class="description"><fmt:formatDate pattern="yyyy-MM-dd a HH:mm" value="${article.regDate}"/></span> </div> </div> <div class="box-footer"> <form role="form" method="post"> <input type="hidden" name="articleNo" value="${article.articleNo}"> <input type="hidden" name="page" value="${searchCriteria.page}"> <input type="hidden" name="perPageNum" value="${searchCriteria.perPageNum}"> <input type="hidden" name="searchType" value="${searchCriteria.searchType}"> <input type="hidden" name="keyword" value="${searchCriteria.keyword}"> </form> <button type="submit" class="btn btn-primary listBtn"><i class="fa fa-list"></i> 목록</button> <div class="pull-right"> <button type="submit" class="btn btn-warning modBtn"><i class="fa fa-edit"></i> 수정</button> <button type="submit" class="btn btn-danger delBtn"><i class="fa fa-trash"></i> 삭제</button> </div> </div> </div> <div class="box box-warning"> <div class="box-header with-border"> <a class="link-black text-lg"><i class="fa fa-pencil margin-r-5"></i> 댓글작성</a> </div> <div class="box-body"> <form class="form-horizontal"> <div class="form-group margin"> <div class="col-sm-10"> <textarea class="form-control" id="newReplyText" rows="3" placeholder="댓글내용..." style="resize: none"></textarea> </div> <div class="col-sm-2"> <input class="form-control" id="newReplyWriter" type="text" placeholder="댓글작성자..."> </div> <hr/> <div class="col-sm-2"> <button type="button" class="btn btn-primary btn-block replyAddBtn"><i class="fa fa-save"></i> 저장</button> </div> </div> </form> </div> </div> <div class="box box-success collapsed-box"> <%--댓글 유무 / 댓글 갯수 / 댓글 펼치기, 접기--%> <div class="box-header with-border"> <a class="link-black text-lg"><i class="fa fa-comments-o margin-r-5 replyCount"></i> </a> <div class="box-tools"> <button type="button" class="btn btn-box-tool" data-widget="collapse"> <i class="fa fa-plus"></i> </button> </div> </div> <%--댓글 목록--%> <div class="box-body repliesDiv"> </div> <%--댓글 페이징--%> <div class="box-footer"> <div class="text-center"> <ul class="pagination pagination-sm no-margin"> </ul> </div> </div> </div> <%--댓글 수정 modal 영역--%> <div class="modal fade" id="modModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span></button> <h4 class="modal-title">댓글수정</h4> </div> <div class="modal-body" data-rno> <input type="hidden" class="replyNo"/> <%--<input type="text" id="replytext" class="form-control"/>--%> <textarea class="form-control" id="replyText" rows="3" style="resize: none"></textarea> </div> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">닫기</button> <button type="button" class="btn btn-primary modalModBtn">수정</button> </div> </div> </div> </div> <%--댓글 삭제 modal 영역--%> <div class="modal fade" id="delModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span></button> <h4 class="modal-title">댓글 삭제</h4> <input type="hidden" class="rno"/> </div> <div class="modal-body" data-rno> <p>댓글을 삭제하시겠습니까?</p> <input type="hidden" class="rno"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">아니요.</button> <button type="button" class="btn btn-primary modalDelBtn">네. 삭제합니다.</button> </div> </div> </div> </div> </div> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <!-- Main Footer --> <%@ include file="../../include/main_footer.jsp"%> </div> <!-- ./wrapper --> <%@ include file="../../include/plugin_js.jsp"%> <script id="replyTemplate" type="text/x-handlebars-template"> {{#each.}} <div class="post replyDiv" data-replyNo={{replyNo}}> <div class="user-block"> <%--댓글 작성자 프로필사진 : 추후 이미지 업로드기능 구현 예정--%> <img class="img-circle img-bordered-sm" src="/dist/img/user1-128x128.jpg" alt="user image"> <%--댓글 작성자--%> <span class="username"> <%--작성자 이름--%> <a href="#">{{replyWriter}}</a> <%--댓글 삭제 버튼--%> <a href="#" class="pull-right btn-box-tool replyDelBtn" data-toggle="modal" data-target="#delModal"> <i class="fa fa-times"> 삭제</i> </a> <%--댓글 수정 버튼--%> <a href="#" class="pull-right btn-box-tool replyModBtn" data-toggle="modal" data-target="#modModal"> <i class="fa fa-edit"> 수정</i> </a> </span> <%--댓글 작성일자--%> <span class="description">{{prettifyDate regDate}}</span> </div> <%--댓글 내용--%> <div class="oldReplyText">{{{replyText}}}</div> <br/> </div> {{/each}} </script> <script> $(document).ready(function () { var articleNo = "${article.articleNo}"; // 현재 게시글 번호 var replyPageNum = 1; // 댓글 등록일자 : 날짜/시간 2자리로 맞추기 Handlebars.registerHelper("prettifyDate", function (timeValue) { var dateObj = new Date(timeValue); var year = dateObj.getFullYear(); var month = dateObj.getMonth() + 1; var date = dateObj.getDate(); var hours = dateObj.getHours(); var minutes = dateObj.getMinutes(); // 2자리 숫자로 변환 month < 10 ? month = '0' + month : month; date < 10 ? date = '0' + date : date; hours < 10 ? hours = '0' + hours : hours; minutes < 10 ? minutes = '0' + minutes : minutes; return year + "-" + month + "-" + date + " " + hours + ":" + minutes; }); getReplies("/replies/" + articleNo + "/" + replyPageNum); function getReplies(repliesUri) { $.getJSON(repliesUri, function (data) { printReplyCount(data.pageMaker.totalCount); printReplies(data.replies, $(".repliesDiv"), $("#replyTemplate")); printReplyPaging(data.pageMaker, $(".pagination")); }); } // 댓글 갯수 출력 함수 function printReplyCount(totalCount) { var replyCount = $(".replyCount"); var collapsedBox = $(".collapsed-box"); if (totalCount <= 0) { replyCount.html(" 댓글이 없습니다. 의견을 남겨주세요"); collapsedBox.find(".btn-box-tool").remove(); return; } replyCount.html(" 댓글목록 (" + totalCount + ")"); collapsedBox.find(".box-tools").html( "<button type='button' class='btn btn-box-tool' data-widget='collapse'>" + "<i class='fa fa-plus'></i>" + "</button>" ); } // 댓글 출력 함수 function printReplies(replyArr, targetArea, templateObj) { var replyTemplate = Handlebars.compile(templateObj.html()); var html = replyTemplate(replyArr); $(".replyDiv").remove(); targetArea.html(html); } // 댓글 페이징 출력 함수 function printReplyPaging(pageMaker, targetArea) { var str = ""; if (pageMaker.prev) { str += "<li><a href='" + (pageMaker.startPage - 1) + "'>이전</a></li>"; } for (var i = pageMaker.startPage, len = pageMaker.endPage; i <= len; i++) { var strClass = pageMaker.criteria.page == i ? "class=active" : ""; str += "<li " + strClass + "><a href='" + i + "'>" + i + "</a></li>"; } if (pageMaker.next) { str += "<li><a href='" + (pageMaker.endPage + 1) + "'>다음</a></li>"; } targetArea.html(str); } // 댓글 페이지 번호 클릭 이벤트 $(".pagination").on("click", "li a", function (event) { event.preventDefault(); replyPageNum = $(this).attr("href"); getReplies("/replies/" + articleNo + "/" + replyPageNum); }); $(".replyAddBtn").on("click", function () { // 입력 form 선택자 var replyWriterObj = $("#newReplyWriter"); var replyTextObj = $("#newReplyText"); var replyWriter = replyWriterObj.val(); var replyText = replyTextObj.val(); // 댓글 입력처리 수행 $.ajax({ type : "post", url : "/replies/", headers : { "Content-Type" : "application/json", "X-HTTP-Method-Override" : "POST" }, dataType : "text", data : JSON.stringify({ articleNo : articleNo, replyWriter : replyWriter, replyText : replyText }), success: function (result) { console.log("result : " + result); if (result == "regSuccess") { alert("댓글이 등록되었습니다."); replyPageNum = 1; // 페이지 1로 초기화 getReplies("/replies/" + articleNo + "/" + replyPageNum); // 댓글 목록 호출 replyTextObj.val(""); // 댓글 입력창 공백처리 replyWriterObj.val(""); // 댓글 입력창 공백처리 } } }); }); // 댓글 수정을 위해 modal창에 선택한 댓글의 값들을 세팅 $(".repliesDiv").on("click", ".replyDiv", function (event) { var reply = $(this); $(".replyNo").val(reply.attr("data-replyNo")); $("#replyText").val(reply.find(".oldReplyText").text()); }); // modal 창의 댓글 수정버튼 클릭 이벤트 $(".modalModBtn").on("click", function () { var replyNo = $(".replyNo").val(); var replyText = $("#replyText").val(); $.ajax({ type : "put", url : "/replies/" + replyNo, headers : { "Content-Type" : "application/json", "X-HTTP-Method-Override" : "PUT" }, dataType : "text", data: JSON.stringify({ replyText : replyText }), success: function (result) { console.log("result : " + result); if (result == "modSuccess") { alert("댓글이 수정되었습니다."); getReplies("/replies/" + articleNo + "/" + replyPageNum); // 댓글 목록 호출 $("#modModal").modal("hide"); // modal 창 닫기 } } }) }); $(".modalDelBtn").on("click", function () { var replyNo = $(".replyNo").val(); $.ajax({ type: "delete", url: "/replies/" + replyNo, headers: { "Content-Type" : "application/json", "X-HTTP-Method-Override" : "DELETE" }, dataType: "text", success: function (result) { console.log("result : " + result); if (result == "delSuccess") { alert("댓글이 삭제되었습니다."); getReplies("/replies/" + articleNo + "/" + replyPageNum); // 댓글 목록 호출 $("#delModal").modal("hide"); // modal 창 닫기 } } }); }); var formObj = $("form[role='form']"); console.log(formObj); $(".modBtn").on("click", function () { formObj.attr("action", "/article/paging/search/modify"); formObj.attr("method", "get"); formObj.submit(); }); $(".delBtn").on("click", function () { formObj.attr("action", "/article/paging/search/remove"); formObj.submit(); }); $(".listBtn").on("click", function () { formObj.attr("action", "/article/paging/search/list"); formObj.attr("method", "get"); formObj.submit(); }); }); </script> </body> </html>
import 'package:flutter/material.dart'; import 'package:music_player_app/themes/dark_theme.dart'; import 'package:music_player_app/themes/light_theme.dart'; class ThemeProvider extends ChangeNotifier { static ThemeProvider instance = ThemeProvider(); ThemeData themeData = lightMode; bool get isDarkMode => themeData == darkMode; ThemeData get getCurrentTheme => themeData; set newTheme(ThemeData themeData) { this.themeData = themeData; notifyListeners(); } void toggleTheme() { if (themeData == lightMode) { themeData = darkMode; } else { themeData = lightMode; } notifyListeners(); } }
<!-- Массивы бывают многомерными, для этого в каждый элемент массива следует расположить еще один массив. Таким образом возможно реализовать n-мерный массив. --> <html> <head> <title>Двумерная матрица</title> <script> // Создание многомерного массива. let table = new Array(10); for (let i = 0; i < table.length; i++) { // В таблице 10 строк table[i] = new Array(10); // В каждой строке 10 столбцов } // Инициализация массива. for (let row = 0; row < table.length; row++) { for (let col = 0; col < table[row].length; col++) { if ((row + col) % 2 == 1) // table[row][col] = "1"; table[row][col] = "<img src='images/parquet1.jpg' width='50' height='50'/>"; else // table[row][col] = "0"; table[row][col] = "<img src='images/parquet2.jpg' width='50' height='50'/>"; //document.write(table[row][col]); //вывод заполненой ячейки сразу } // document.write("<br/>");//разрыв строки } table[8][1] = "<img src='images/parquet3.jpg' width='50' height='50'/>"; for (let row = 0; row < table.length; row++) { for (let col = 0; col < table[row].length; col++) { document.write(table[row][col]); } document.write("<br/>"); } let prod = table[8][1]; document.write("<hr/>" + prod); </script> </head> <body> </body> </html>
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WaveSpawner : MonoBehaviour { [SerializeField] private List<Transform> EnemyPrefabs; // List of enemy prefabs to spawn [SerializeField] private float spawnDelay; [SerializeField] private float BonusTime; // UI Elements [SerializeField] private Sprite playImage; [SerializeField] private Sprite pauseImage; private GameData.Map Map; private bool waveToggle = false; private float TimeToSpawnNewWave; private int currentWaveIndex = 0; // Current wave index private int totalEnemiesToSpawn; // Total enemies to spawn in the current wave private int enemiesDefeated = 0; // Number of defeated enemies private void Start() { Map = SaveManager.Instance.Data.map; foreach (Wave wave in Map.Waves) { // Add to the total enemies to spawn totalEnemiesToSpawn += wave.EnemyNumber; } } private void Update() { if (waveToggle && Time.time >= TimeToSpawnNewWave) { // Spawn the current wave SpawnWave(currentWaveIndex); currentWaveIndex++; if (currentWaveIndex < Map.Waves.Length) { // Spawn the current wave SpawnWave(currentWaveIndex); currentWaveIndex++; // Set the time to spawn the next wave TimeToSpawnNewWave = Time.time + Map.Waves[currentWaveIndex].TimeToSpawn + GameStats.waveInterval; } else { // All waves have been spawned, stop spawning waveToggle = false; } } } private void SpawnWave(int waveIndex) { Wave waveToSpawn = Map.Waves[waveIndex]; GameStats.Wave = waveIndex + 1; // Start spawning enemies with a delay StartCoroutine(SpawnEnemiesWithDelay(waveToSpawn.EnemyID, waveToSpawn.EnemyLevel, waveToSpawn.EnemyNumber)); } private IEnumerator SpawnEnemiesWithDelay(int enemyID, int enemyLevel, int count) { for (int i = 0; i < count; i++) { SpawnEnemy(enemyID, enemyLevel); yield return new WaitForSeconds(spawnDelay); } } private void SpawnEnemy(int enemyID, int enemyLevel) { Transform enemyPrefab = EnemyPrefabs.Find(enemy => enemy.GetComponent<Enemy>().EnemySO.ID == enemyID); if (enemyPrefab != null) { Transform enemy = Instantiate(enemyPrefab, Map.SpawnPointPosition, Quaternion.identity); enemy.GetComponent<Enemy>().Level = enemyLevel; // Subscribe to the enemy's death event enemy.GetComponent<EnemyHealthSystem>().OnEnemyDied += HandleEnemyDeath; } else { Debug.LogError("Enemy prefab with ID " + enemyID + " not found!"); } } /// <summary> /// Event handler for enemy death /// </summary> /// <param name="sender">Enemy which invoke the event.</param> /// <param name="e">Passed parameters.</param> private void HandleEnemyDeath(object sender, System.EventArgs e) { enemiesDefeated++; // Check if all enemies are defeated to trigger the Victory Panel if (enemiesDefeated == totalEnemiesToSpawn) { GetComponent<Victory>().ShowVictoryPanel(); } } /// <summary> /// Start or Stop an Enemy Wave. /// </summary> public void ToggleWave() { waveToggle = !waveToggle; if (waveToggle) { if (currentWaveIndex != 0 && TimeToSpawnNewWave > Time.time + BonusTime) { GameStats.Money += GameStats.earlyWaveBonusPoint; } TimeToSpawnNewWave = Time.time; // Start spawning immediately } } }
@isTest public with sharing class AFSExemptionTriggerHandlerTest { public static AFS_Exemption__c initialSetup() { AFS_Exemption__c exemp = new AFS_Exemption__c(); exemp.AFS_First_Name__c = 'Gwen'; exemp.AFS_Middle_Name__c = 'Elizabeth'; exemp.AFS_Last_Name__c = 'Stacy'; exemp.AFS_Social_Security_Number__c = '867530999'; insert exemp; exemp = [SELECT Id, Name, AFS_First_Name__c, AFS_Middle_Name__c, AFS_Last_Name__c FROM AFS_Exemption__c WHERE AFS_First_Name__c = 'Gwen' AND AFS_Last_Name__c = 'Stacy'][0]; System.debug('Exemption Found = ' + exemp); return exemp; } static testMethod void ssnFilledOut() { AFS_Exemption__c ssnPopulated = AFSExemptionTriggerHandlerTest.initialSetup(); System.debug('Populated SSN Test Exemption = ' + ssnPopulated); ssnPopulated.AFS_Last_4_SSN__c = '0999'; update ssnPopulated; ssnPopulated = [SELECT Id, Name, AFS_First_Name__c, AFS_Last_Name__c, AFS_Social_Security_Number__c, AFS_Last_4_SSN__c FROM AFS_Exemption__c WHERE AFS_First_Name__c = 'Gwen' AND AFS_Last_Name__c = 'Stacy'][0]; System.debug('Updated Populated SSN Test Exemption = ' + ssnPopulated); System.assert(ssnPopulated.AFS_Last_4_SSN__c == '0999', 'The Last 4 SSN are the same!'); } static testMethod void ssnUpdatedTest() { AFS_Exemption__c testExemption = AFSExemptionTriggerHandlerTest.initialSetup(); System.debug('Test Exemption = ' + testExemption); testExemption.AFS_Social_Security_Number__c = '867530991'; update testExemption; testExemption = [SELECT Id, Name, AFS_First_Name__c, AFS_Last_Name__c, AFS_Social_Security_Number__c, AFS_Last_4_SSN__c FROM AFS_Exemption__c WHERE AFS_First_Name__c = 'Gwen' AND AFS_Last_Name__c = 'Stacy'][0]; System.debug('Updated Test Exemption = ' + testExemption); System.assert(testExemption.AFS_Social_Security_Number__c == '867530991', 'The Social Security Numbers are the same!'); System.assert(testExemption.AFS_Last_4_SSN__c == '0991', 'The Last 4 SSN are the same!'); } static testMethod void clearSSNTest() { AFS_Exemption__c clearSSN = AFSExemptionTriggerHandlerTest.initialSetup(); System.debug('Clear SSN Test Exemption = ' + clearSSN); clearSSN.AFS_Last_4_SSN__c = '0999'; clearSSN.AFS_Person_ID__c = '0987654321'; update clearSSN; clearSSN = [SELECT Id, Name, AFS_First_Name__c, AFS_Last_Name__c, AFS_Social_Security_Number__c, AFS_Person_ID__c, AFS_Last_4_SSN__c FROM AFS_Exemption__c WHERE AFS_First_Name__c = 'Gwen' AND AFS_Last_Name__c = 'Stacy'][0]; System.debug('Exemption to have Social Security Number cleared: ' + clearSSN); System.assert(clearSSN.AFS_Person_ID__c == '0987654321', 'The Person IDs are the same'); System.assert(clearSSN.AFS_Social_Security_Number__c == null, 'The Social Security Number field has been cleared!'); } }
import { store } from '../../store/store'; import { getClient } from '../../utils'; import { gql } from 'graphql-request'; import moment, { Moment } from 'moment'; import React, { useState } from 'react'; import { Dimensions, View, ScrollView, Text } from 'react-native'; import { useQuery } from 'react-query'; import { tailwind } from 'tailwind'; import { StackedBarChart, Grid, XAxis, YAxis } from 'react-native-svg-charts'; const getDailyStats = (startDate: Moment | null, endDate: Moment | null) => { const client = getClient(store); const query = gql` query query($startDate: DateTime, $endDate: DateTime) { getDailyStats(startDate: $startDate, endDate: $endDate) { data { date basePay tip expenses mileage activeTime clockedInTime hourlyPay hourlyPayActive } nDays } } `; const vars = { startDate, endDate }; const res = client.request(query, vars); return res; }; export const WeeklyStats = ({ dates = { startDate: moment().startOf('week'), endDate: moment().endOf('week') }, }: { dates: { startDate: Moment | null; endDate: Moment | null }; }) => { const { status, data } = useQuery( ['stats', 'weeklyStats', dates.startDate, dates.endDate], () => getDailyStats(dates.startDate, dates.endDate), { onError: (err) => { console.log('error:', err); }, select: (data) => { const d = data.getDailyStats.data; const chartData = d.map((item) => { return { label: moment(item.date).format('dd'), // tip: Math.floor((Math.random() + 1) * 10), // basePay: Math.floor((Math.random() + 1) * 10), tip: item.tip, basePay: item.basePay, }; }); return chartData; }, } ); const screenWidth = Dimensions.get('window').width; const colors = ['#212121', '#757575bd']; const keys = ['basePay', 'tip']; const contentInset = { left: 10, top: 10, bottom: 10 }; //TODO: if no data, show some random bars and a message on top const sumPay = data?.reduce((a, b) => a + b.basePay, 0); return ( <View style={tailwind('rounded-lg p-2 w-full flex-col mt-2 mb-2')}> <View style={tailwind('flex-row rounded-lg ')}> {status == 'success' && ( <View style={tailwind('flex-row')}> {sumPay == 0 && ( <View style={tailwind('flex-col w-full absolute bg-gray-200 p-5 rounded-lg self-start justify-self-center')}> <Text style={tailwind('text-lg')}> No pay recorded for this week. Clock in to track your pay and see stats! </Text> </View> )} <YAxis data={data} numberOfTicks={3} svg={{ fontSize: 12, fill: 'black' }} style={{ marginVertical: 20 }} yAccessor={({ index }) => data[index].basePay + data[index].tip} formatLabel={(value) => { return `$${value}`; }} contentInset={contentInset} spacingInner={10} /> <View style={tailwind('flex-col')}> <StackedBarChart style={{ height: 200, width: screenWidth * 0.75 }} keys={keys} svg={{ strokeLinecap: 'round', strokeLinejoin: 'bevel', strokeWidth: 10, }} colors={colors} data={data} showGrid={false} animate={true} contentInset={contentInset} > <Grid /> </StackedBarChart> <XAxis data={data} style={{ marginHorizontal: 20 }} xAccessor={({ index }) => index} contentInset={contentInset} spacingInner={10} formatLabel={(value, index) => data[value].label} svg={{ fontSize: 12, fill: 'black' }} /> </View> </View> )} </View> <View style={tailwind('flex-row')}> <View style={tailwind('flex-row items-center pl-1 pr-1')}> <View style={[tailwind('rounded w-4 h-4'), { backgroundColor: '#212121' }]} ></View> <Text style={tailwind('text-base p-1 ')}>Base Pay</Text> </View> <View style={tailwind('flex-row items-center pl-1 pr-1')}> <View style={[tailwind('rounded w-4 h-4'), { backgroundColor: '#757575bd' }]} ></View> <Text style={tailwind('text-base p-1 ')}>Tips</Text> </View> </View> </View> ); };
<?php /** * 按产品统计的研发需求规模总数。 * Scale of story in product. * * 范围:product * 对象:story * 目的:scale * 度量名称:按产品统计的研发需求规模总数 * 单位:工时 * 描述:按产品统计的研发需求规模总数表示产品种所有研发需求的总规模。这个度量项可以反映团队需进行研发工作的规模,可以用于评估产品团队的研发需求规模管理和成果。 * 定义:产品中研发需求的规模数求和;过滤父研发需求;过滤已删除的研发需求;过滤已删除的产品; * * @copyright Copyright 2009-2023 禅道软件(青岛)有限公司(ZenTao Software (Qingdao) Co., Ltd. www.zentao.net) * @author qixinzhi <qixinzhi@easycorp.ltd> * @package * @uses func * @license ZPL(https://zpl.pub/page/zplv12.html) or AGPL(https://www.gnu.org/licenses/agpl-3.0.en.html) * @Link https://www.zentao.net */ class scale_of_story_in_product extends baseCalc { public $dataset = 'getDevStories'; public $fieldList = array('t1.product', 't1.estimate', 't1.parent'); public $result = array(); public function calculate($data) { $product = $data->product; $estimate = $data->estimate; $parent = $data->parent; if($parent == '-1') return false; if(!isset($this->result[$product])) $this->result[$product] = 0; $this->result[$product] += $estimate; } public function getResult($options = null) { $records = array(); foreach($this->result as $product => $value) { $records[] = array('product' => $product, 'value' => $value); } return $this->filterByOptions($records, $options); } }
package com.dilatush.monitor.monitors.yolink; import com.dilatush.monitor.monitors.AMonitor; import com.dilatush.mop.Mailbox; import com.dilatush.mop.Message; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import static com.dilatush.util.Conversions.fromCtoF; import static com.dilatush.util.General.getLogger; import static com.dilatush.util.General.isNull; /** * Instances of this class implement a monitor for YoLink temperature and humidity sensors. */ public class YoLink extends AMonitor { private final Logger LOGGER = getLogger(); private final String clientID; private final String secret; private final List<YoLinkTriggerDef> triggers; private final Map<String,Boolean> previous; private String accessToken; private Instant accessTokenExpires; /** * Create a new instance of this class, with the given mailbox and parameters. At a minimum, the parameters must include "clientID" and "secret". The parameters may * optionally include specifications for events triggered by reading from the sensors, as "triggers" mapped to a list of {@link YoLinkTriggerDef}s. * * @param _mailbox The MOP mailbox for this monitor to use. * @param _params The parameters for this monitor. * @param _interval the interval between runs for this monitor. */ public YoLink( final Mailbox _mailbox, final Map<String,Object> _params, final Duration _interval ) { super( _mailbox, _interval ); if( isNull( _params ) ) throw new IllegalArgumentException( "_params must be provided" ); clientID = (String) _params.get( "clientID" ); secret = (String) _params.get( "secret" ); var triggersParam = _params.get( "triggers" ); previous = new HashMap<>(); if( isNull( clientID, secret ) ) throw new IllegalArgumentException( "clientID and secret parameters must be supplied" ); triggers = new ArrayList<>(); if( triggersParam != null ) { if( !(triggersParam instanceof List<?> triggersRaw) ) throw new IllegalArgumentException( "triggers parameter supplied, but is not a List" ); for( var trig : triggersRaw ) { if( !(trig instanceof YoLinkTriggerDef trigger) ) throw new IllegalArgumentException( "triggers list contains something other than a YoLinkTriggerDef" ); triggers.add( trigger ); } } } /** * Perform the periodic monitoring. */ @Override protected void runImpl() { try { ensureAccessToken(); var devices = getDevices(); var states = getTempHumiditySensorsState( devices ); // make a map of the sensors by name... var statesByName = new HashMap<String,THState>(); for( var state : states ) statesByName.put( state.device.name, state ); sendStatistics( states ); sendEvents( states, statesByName ); sendStatus( states ); } catch( Exception _e ) { LOGGER.log( Level.SEVERE, "Failed while querying YoLink API: " + _e.getMessage(), _e ); sendEvent( Duration.ofHours( 6 ), "YoLink.apiFail", "?", "Failure querying YoLink API", "Failure while querying YoLink API: " + _e.getClass().getSimpleName() + ": " + _e.getMessage(), 8 ); } } /** * Send an event for each of the given sensor states containing the statistics to be inserted into a database. * * @param _states The current state of the sensors as reported by the YoLink API. */ private void sendStatistics( final List<THState> _states ) { // for each given state... for( var state : _states ) { // build our event message... Message msg = mailbox.createDirectMessage( "events.post", "event.post", false ); msg.putDotted( "tag", "YoLink_stats" ); msg.putDotted( "timestamp", System.currentTimeMillis() ); msg.putDotted( "fields.device_name", state.device.name ); msg.putDotted( "fields.model", state.device.model ); msg.putDotted( "fields.humidity", state.humidity ); msg.putDotted( "fields.temperature", state.temperature ); msg.putDotted( "fields.battery", state.battery ); // send it! mailbox.send( msg ); LOGGER.info( "Sent YoLink statistics message" ); } } /** * Publish a monitor message with the given states of the YoLink sensors. * * @param _states The current state of the YoLink sensors as reported by the YoLink API. */ private void sendStatus( final List<THState> _states ) { // create our status message... var message = mailbox.createPublishMessage( "yolink.monitor" ); // fill in the message interval... message.putDotted( "monitor.yolink.messageIntervalMs", interval.toMillis() ); // fill in the data... JSONObject sensors = new JSONObject(); message.putDotted( "monitor.yolink.sensors", sensors ); for( var state : _states ) { // fill in one sensor... var sensor = new JSONObject(); sensor.put( "online", state.online ); sensor.put( "temperature", state.temperature ); sensor.put( "humidity", state.humidity ); sensor.put( "battery", state.battery ); sensor.put( "name", state.device.name ); sensor.put( "model", state.device.model ); // stuff it into our sensors object... sensors.put( sensor.getString( "name" ), sensor ); } // send it! mailbox.send( message ); LOGGER.info( "Sent YoLink monitor message" ); } /** * Send events for any sensor whose current state and historical state match one of the triggers. * * @param _states The current state of the YoLink sensors as reported by the YoLink API. * @param _statesByName The current states mapped by device name. */ private void sendEvents( final List<THState> _states, final Map<String,THState> _statesByName ) { // iterate over all our triggers... for( YoLinkTriggerDef trigger : triggers ) { // iterate over all sensors, or just the named sensor... var sensorStates = new ArrayList<String>(); if( "?".equals( trigger.sensorName() ) ) for( var state : _states ) sensorStates.add( state.device.name ); else sensorStates.addAll( Arrays.asList( trigger.sensorName().split( "," ) ) ); for( var sensorName : sensorStates ) { LOGGER.finest( "Working on " + sensorName + " for trigger " + trigger.eventTag() ); // attempt to get the sensor state... var sensorState = _statesByName.get( sensorName ); // if we don't have a sensor state, then a name in a trigger doesn't exist in the YoLink data... if( sensorState == null ) { LOGGER.log( Level.WARNING, "Device name does not appear in YoLink data: " + sensorName ); continue; } // if this sensor is offline, and we're not checking the online field, bail out... if( ((!sensorState.online) && (trigger.field() != YoLinkTriggerField.ONLINE) ) ) continue; // get the current value... var value = getCurrentValue( sensorState, trigger.field() ); // get the previous and current trigger values... var prevTriggerName = trigger.eventTag() + "." + sensorName; var prevTrigger = previous.get( prevTriggerName ); var currTrigger = evaluateTrigger( value, trigger ); if( prevTrigger == null ) prevTrigger = currTrigger; // figure out whether to send an event... var sendIt = ((trigger.klass() == YoLinkTriggerClass.VALUE) && currTrigger) || ((trigger.klass() == YoLinkTriggerClass.TRANSITION) && currTrigger && !prevTrigger); // if we should, send the event... if( sendIt ) { sendEvent( value, sensorName, trigger ); LOGGER.finest( "Sent event " + trigger.eventTag() + " for " + sensorName ); } // update our previous trigger value... previous.put( prevTriggerName, currTrigger ); } } } /** * Send a triggered event. * * @param _value The current value of the sensor that is being triggered. * @param _sensorName The name of the sensor being triggered. * @param _trigger The trigger causing the event to be sent. */ private void sendEvent( final double _value, final String _sensorName, final YoLinkTriggerDef _trigger ) { // construct the subject and message, which may include the current value, lower bound, and upper bound... var subject = String.format( _trigger.eventSubject(), _value, _trigger.lowerBound(), _trigger.upperBound(), _sensorName ); var message = String.format( _trigger.eventMessage(), _value, _trigger.lowerBound(), _trigger.upperBound(), _sensorName ); // send the event... sendEvent( _trigger.minInterval(), _trigger.eventTag(), _sensorName, subject, message, _trigger.eventLevel() ); } /** * Evaluate the given trigger for the given value. * * @param _value The value to use when evaluating the trigger. * @param _trigger The trigger to evaluate. * @return {@code true} if the trigger evaluates as true. */ private boolean evaluateTrigger( final double _value, final YoLinkTriggerDef _trigger ) { return switch( _trigger.type() ) { case IN -> (_value >= _trigger.lowerBound() && (_value <= _trigger.upperBound() ) ); case OUT -> (_value < _trigger.lowerBound() || (_value > _trigger.upperBound() ) ); case BELOW -> (_value < _trigger.lowerBound() ); case ABOVE -> (_value > _trigger.upperBound() ); case EQUAL -> (_value == _trigger.lowerBound() ); case UNEQUAL -> (_value != _trigger.lowerBound() ); }; } /** * Returns the current value of the given sensor and field. The value returned depends on the field: * <ul> * <li>HUMIDITY: relative percentage, from 0.0 to 100.0.</li> * <li>TEMPERATURE: degrees Fahrenheit, from -20.0°F to 120.0°F.</li> * <li>BATTERY: levels of 0, 1, 2, 3, or 4.</li> * <li>ONLINE: 0 for offline, 1 for online.</li> * </ul> * * @param _state The current state of the sensor. * @param _field The field whose value is desired: HUMIDITY, TEMPERATURE, BATTERY, or ONLINE. * @return The value of the given field in the given sensor state. */ private double getCurrentValue( final THState _state, final YoLinkTriggerField _field ) { return switch( _field ) { case HUMIDITY -> _state.humidity; case TEMPERATURE -> _state.temperature; case BATTERY -> _state.battery; case ONLINE -> _state.online ? 1 : 0; }; } /** * Use the YoLink API to retrieve the current state of the given devices, which must be temperature and humidity sensors. * * @param _devices The list of devices to retrieve the current state of. * @return The list of the current states of the given devices. * @throws IOException On any I/O problem. * @throws JSONException On any JSON problem. */ private List<THState> getTempHumiditySensorsState( final List<Device> _devices ) throws IOException, JSONException { var result = new ArrayList<THState>(); for( Device device : _devices ) { // get the state... var req = new JSONObject(); req.put( "method", "THSensor.getState" ); req.put( "targetDevice", device.id ); req.put( "token", device.token ); var resp = post( "https://api.yosmart.com/open/yolink/v2/api", req.toString(), "application/json", true ); // if we don't see success, throw an exception... if( !"Success".equals( resp.get( "desc" ) ) ) { throw new IOException( "YoLink failed to return device state: " + resp.toString(4) ); } var dataObj = resp.getJSONObject( "data" ); var stateObj = dataObj.getJSONObject( "state" ); var state = new THState( device, dataObj.getBoolean( "online" ), stateObj.getInt( "battery" ), fromCtoF( stateObj.getDouble( "temperature" ) + stateObj.getDouble( "tempCorrection" ) ), stateObj.getDouble( "humidity" ) + stateObj.getDouble( "humidityCorrection" ) ); result.add( state ); } return result; } /** * Uses the YoLink API to retrieve the list of devices belonging to the configured client. * * @return The list of devices retrieved. * @throws IOException On any I/O problem. * @throws JSONException On any JSON problem. */ private List<Device> getDevices() throws IOException, JSONException { var req = "{\"method\":\"Home.getDeviceList\"}"; var resp = post( "https://api.yosmart.com/open/yolink/v2/api", req, "application/json", true ); // if the returned object doesn't say successful, throw an exception... if( !"Success".equals( resp.optString( "desc" ) ) ) throw new IOException( "YoLink didn't return a device list" ); // we got a device list, so munge it into something useful... var deviceArray = resp.getJSONObject( "data" ).getJSONArray( "devices" ); var deviceList = new ArrayList<Device>(); for( final Object _o : deviceArray ) { var deviceObj = (JSONObject) _o; var device = new Device( deviceObj.getString( "modelName" ), deviceObj.getString( "name" ), deviceObj.getString( "type" ), deviceObj.getString( "deviceId" ), deviceObj.getString( "deviceUDID" ), deviceObj.getString( "token" ) ); // if it's the hub, skip it... if( "YS1603-UC".equals( device.model ) ) continue; deviceList.add( device ); } return deviceList; } /** * Ensure that we have a current access token for the YoLink API. * * @throws IOException On any I/O problem. * @throws JSONException On any JSON problem. */ private void ensureAccessToken() throws IOException, JSONException { // if we've already got a token, and it isn't near expiration, our work is done... if( (accessToken != null) && (accessTokenExpires != null) && accessTokenExpires.minus( Duration.ofMinutes( 15 ) ).isAfter( Instant.now() ) ) return; // otherwise, request an access token from YoLink... var req = "grant_type=client_credentials&client_id=" + clientID + "&client_secret=" + secret; var resp = post( "https://api.yosmart.com/open/yolink/token", req, "application/x-www-form-urlencoded", false ); // if we got a response, but no access token or expiration, throw an exception... if( !resp.has( "access_token" ) ) throw new IOException( "YoLink failed to return an access token" ); if( !resp.has( "expires_in" ) ) throw new IOException( "YoLink failed to return an expiration time" ); // all is good; update our access token... accessToken = resp.getString( "access_token" ); accessTokenExpires = Instant.now().plus( Duration.ofSeconds( resp.getInt( "expires_in" ) ) ); } /** * Send a POST request to the YoLink API. * * @param _url The URL to post to. * @param _request The request to post. * @param _contentType The content type of the request. * @param _authorize {@code true} if the post should be authorized with the access token. * @return The JSON response to the post. * @throws IOException On any I/O problem. * @throws JSONException On any JSON problem. */ private JSONObject post( final String _url, final String _request, final String _contentType, final boolean _authorize ) throws IOException, JSONException { URL url = new URL( _url ); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod( "POST" ); con.setRequestProperty( "Accept", "application/json" ); con.setRequestProperty( "Content-Type", _contentType ); if( _authorize ) con.setRequestProperty( "Authorization", "Bearer " + accessToken ); con.setDoOutput( true ); try( OutputStream os = con.getOutputStream() ) { byte[] input = _request.getBytes( StandardCharsets.UTF_8 ); os.write( input, 0, input.length ); } if( con.getResponseCode() != 200 ) throw new IOException( "Response not ok: " + con.getResponseCode() ); try( BufferedReader br = new BufferedReader( new InputStreamReader( con.getInputStream(), StandardCharsets.UTF_8 ) ) ) { StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } return new JSONObject( response.toString() ); } } private record Device( String model, String name, String type, String id, String udid, String token ){} private record THState( Device device, boolean online, int battery, double temperature, double humidity ){} }
"use client"; import React from 'react'; import { Button, Divider, Dropdown, DropdownItem, DropdownMenu, DropdownSection, DropdownTrigger } from "@nextui-org/react"; import {SlOptions} from "react-icons/sl"; import {AiOutlineLike} from "react-icons/ai"; import {GoBookmark} from "react-icons/go"; import {IoShareOutline} from "react-icons/io5"; import {IoIosLink} from "react-icons/io"; import {FaXTwitter} from "react-icons/fa6"; import {FaInstagram, FaLinkedin} from "react-icons/fa"; import BlogCommentDrawer from "@/components/custom/drawers/BlogCommentDrawer"; import BlogCommentMobileDrawer from "@/components/custom/drawers/BlogCommentMobileDrawer"; const BlogActionButton = ({data, isDividerShown = true}: {data: any, isDividerShown?: boolean }) => { return ( <div className={"flex flex-col space-y-2"}> {isDividerShown && <Divider className={"w-[90%] self-center"}/>} <div className={"flex items-center justify-between md:px-6"}> <div className={"flex items-center gap-2"}> <div className={"flex items-center"}> <small className={"text-sm"}> 10 </small> <Button isIconOnly={true} variant={"light"} size={"sm"} className={"text-xl"} > <AiOutlineLike/> </Button> </div> <Divider orientation={"vertical"} className={"h-6"}/> <div className={"flex items-center"}> <small className={"text-sm"}> 10 </small> <BlogCommentDrawer data={data}/> </div> <div className={"flex items-center"}> <small className={"text-sm"}> 10 </small> <BlogCommentMobileDrawer/> </div> </div> <div className={"flex items-center gap-2"}> <Button isIconOnly={true} variant={"light"} size={"sm"} className={"text-xl"} > <GoBookmark/> </Button> <Dropdown showArrow radius="sm" backdrop={"blur"} classNames={{ base: "before:bg-default-200", // change arrow background content: "p-0 border-small border-divider bg-background", }} > <DropdownTrigger> <Button isIconOnly={true} variant={"light"} size={"sm"} className={"text-xl"} > <IoShareOutline/> </Button> </DropdownTrigger> <DropdownMenu aria-label={"user-actions"} variant={"flat"} className={"max-w-[260px] h-auto w-full pt-2"} itemClasses={{ base: [ "rounded-md", "text-default-500", "transition-opacity", "data-[hover=true]:text-foreground", "data-[hover=true]:bg-default-100", "dark:data-[hover=true]:bg-default-50", "data-[selectable=true]:focus:bg-default-50", "data-[pressed=true]:opacity-70", "data-[focus-visible=true]:ring-default-500", ], }} > <DropdownSection showDivider> <DropdownItem> <div className={"flex items-center gap-2"}> <IoIosLink /> <span>Copy Link</span> </div> </DropdownItem> </DropdownSection> <DropdownSection className={"w-full"}> <DropdownItem> <div className={"flex items-center gap-2"}> <FaLinkedin /> <span>Share on LinkedIn</span> </div> </DropdownItem> <DropdownItem> <div className={"flex items-center gap-2"}> <FaXTwitter /> <span>Share on X</span> </div> </DropdownItem> <DropdownItem> <div className={"flex items-center gap-2"}> <FaInstagram /> <span>Share on Instagram</span> </div> </DropdownItem> </DropdownSection> </DropdownMenu> </Dropdown> <Button isIconOnly={true} variant={"light"} size={"sm"} className={"text-xl"} > <SlOptions/> </Button> </div> </div> {isDividerShown && <Divider className={"w-[90%] self-center"}/>} </div> ); }; export default BlogActionButton;
// IIFE to create a pokemonRepository variable that is not global and can be accessed publicly // with functions add, addv, getAll, and findByName let pokemonRepository = (function () { let pokemonList = []; let apiUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=150'; let modalContainer = document.querySelector('#modal-container'); function add(pokemon) { if ( typeof pokemon === "object" && "name" in pokemon ) { pokemonList.push(pokemon); } else { console.log("pokemon is not correct"); } } // Function declaration for getAll function getAll() { return pokemonList; } // Function declaration for loadDetails function loadDetails(item) { let url = item.detailsUrl; return fetch(url).then(function (response) { return response.json(); }).then(function (details) { // Now we add the details to the item item.imageUrl = details.sprites.other.dream_world.front_default; item.height = details.height; item.weight = details.weight; item.abilities = details.abilities.map(function (ability) { return ability.ability.name; }).join(', '); item.buttonImage = details.sprites.front_default; item.types = details.types.map(function (type) { return type.type.name; }).join(', '); }).catch(function (e) { console.error(e); }); } // Function declaration for addListItem // Creating a list of pokemon function addListItem(pokemon) { let pokemonList = document.querySelector(".pokemon-list"); let listPokemon = document.createElement("li"); listPokemon.classList.add("list-group-item"); let button = document.createElement("button"); let pokemonImage = document.createElement("img"); pokemonImage.classList.add("button_pokemon_image"); button.classList.add("button-class", "btn", "btn-primary"); button.setAttribute("data-target", "#exampleModal"); button.setAttribute("data-toggle", "modal"); button.setAttribute("type", "button"); // fetch the pokemon detail and get the image url fetch(pokemon.detailsUrl) .then((response) => response.json()) .then((data) => { button.innerHTML = `<span>${pokemon.name}</span><img src="${data.sprites.front_shiny}"/>`; }) .catch((err) => console.log("Err: ", err)); listPokemon.appendChild(button); button.appendChild(pokemonImage); // pokemonImage.setAttribute("src", pokemon.buttonImage); pokemonImage.setAttribute("alt", "Image of " + pokemon.name); pokemonList.appendChild(listPokemon); addEventListenerButton(button, pokemon); } // Function declaration for addEventListenerButton // Adding an event listener to the button that opens the modal function addEventListenerButton(button, pokemon) { button.addEventListener("click", function() { loadDetails(pokemon) .then(function() { showModal(pokemon); }); }); } // Function declaration for loadList // getting data from the API function loadList() { return fetch(apiUrl).then(function (response) { return response.json(); }).then(function (json) { json.results.forEach(function (item) { let pokemon = { name: item.name, detailsUrl: item.url }; add(pokemon); console.log(pokemon); }); }).catch(function (e) { console.error(e); }) } // Declaration of showDetails Function function showDetails(pokemon) { // loadDetails(pokemon).then(function () { console.log(pokemon); const dialog = document.querySelector('dialog'); dialog.showModal(pokemon); } // Declaration of showModal Function // Bootstrap modal function showModal(pokemon) { let modalBody = $(".modal-body"); let modalTitle = $(".modal-title"); let modalHeader = $(".modal-header"); // clear existing content of the modal modalTitle.empty(); modalBody.empty(); //creating element for name in modal content let nameElement = $("<h1>" + pokemon.name + "</h1>"); // creating img in modal content let imageElement = $('<img class="modal-img mx-auto d-block img-fluid" style="height:400px" "width:400px">'); imageElement.attr("src", pokemon.imageUrl); // creating element for height in modal container let heightElement = $("<p>" + "height : " + pokemon.height + "</p>"); // creating element for weight in modal container let weightElement = $("<p>" + "weight : " + pokemon.weight + "</p>"); // creating element for type in modal container let typesElement = $("<p>" + "types : " + pokemon.types + " " + "</p>"); // creating element for abilities in modal container let abilitiesElement = $("<p>" + "abilities : " + pokemon.abilities + " " + "</p>") modalTitle.append(nameElement); modalBody.append(imageElement); modalBody.append(heightElement); modalBody.append(weightElement); modalBody.append(typesElement); modalBody.append(abilitiesElement); }; // implementing Search Functionality // Function declaration for findByName document.getElementById("searchBar").addEventListener("input", function() { let = query = this.value.toLowerCase(); // clear the current list let pokemonListElement = document.querySelector(".pokemon-list"); pokemonListElement.innerHTML = ""; // if the query is empty, show all pokemon if(query==""){ pokemonRepository.getAll().forEach(function(pokemon) { pokemonRepository.addListItem(pokemon); }); } else { let matchingPokemon = pokemonRepository.findByName(query); matchingPokemon.forEach(function(pokemon) { pokemonRepository.addListItem(pokemon); }); } }); function findByName(name) { let matchingPokemon = pokemonList.filter(function(pokemon) { return pokemon.name.toLowerCase().includes(query.toLowerCase()); }); return matchingPokemon; } return { add: add, getAll: getAll, findByName: findByName, addListItem: addListItem, showDetails: showDetails, addEventListenerButton: addEventListenerButton, loadList: loadList, loadDetails: loadDetails, showModal: showModal, // hideModal: hideModal }; })(); // End of IIFE pokemonRepository pokemonRepository.loadList().then(function() { pokemonRepository.getAll().forEach(function(pokemon) { pokemonRepository.addListItem(pokemon); }); });
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Switch', debugShowCheckedModeBanner: false, theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF1E1E1E)), useMaterial3: true, ), home: const MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({ super.key, }); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { bool isLightOn = false; var gradient = const [ Color(0xFF4B4B4B), Color(0xFF2F2F2F), Color(0xFF2C2C2C), ]; var gradientBg = const [ Color(0xFF282525), Color(0xFF2d2d2d), Color(0xFF2d2d2d), Color(0xFF282525), ]; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color(0xFF363636), body: Stack( children: [ Align( alignment: Alignment.center, child: Container( height: 220, width: 150, margin: const EdgeInsets.only(top: 70), decoration: BoxDecoration( color: const Color(0xFF595959), borderRadius: BorderRadius.circular(20), border: Border.all(width: 15, color: const Color(0xFF595959))), child: GestureDetector( onTap: () => setState(() { isLightOn = !isLightOn; }), child: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: gradientBg, stops: const [0, 0.2, 0.8, 1]), borderRadius: BorderRadius.circular(15), border: Border.all( color: const Color(0xFF1E1E1E), width: 1.5), ), child: AnimatedContainer( duration: const Duration(milliseconds: 180), margin: isLightOn ? const EdgeInsets.only(top: 20) : const EdgeInsets.only(bottom: 20), decoration: BoxDecoration( borderRadius: isLightOn ? const BorderRadius.vertical( top: Radius.circular(22), bottom: Radius.circular(15)) : const BorderRadius.vertical( top: Radius.circular(15), bottom: Radius.circular(22)), border: Border.all(color: const Color(0xFF2F2F2F)), gradient: LinearGradient( colors: isLightOn ? gradient : gradient.reversed.toList(), begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: const [0, 0.5, 1])), ), ), ), ), ), Positioned( top: 0, left: 0, right: 0, child: Container( decoration: isLightOn ? BoxDecoration( shape: BoxShape.circle, boxShadow: [ BoxShadow( color: Colors.amber.withOpacity(0.2), blurRadius: 200, spreadRadius: 180) ]) : null, child: Stack( children: [ Align( alignment: Alignment.topCenter, child: Image.asset( "assets/images/bulb.png", width: 100, height: 250, ), ), isLightOn ? Align( alignment: Alignment.topCenter, child: SizedBox( width: 100, height: 250, child: Container( margin: const EdgeInsets.only( left: 8, right: 8, top: 155, bottom: 0), decoration: BoxDecoration( shape: BoxShape.circle, boxShadow: [ BoxShadow( color: Colors.amber.withOpacity(0.3), spreadRadius: 7, blurRadius: 10), BoxShadow( color: Colors.amber.withOpacity(0.25), spreadRadius: 25, blurRadius: 25), BoxShadow( color: Colors.amber.withOpacity(0.3), spreadRadius: 55, blurRadius: 55) ], gradient: RadialGradient(colors: [ Colors.amber, Colors.amber.withOpacity(0.8), Colors.amber.withOpacity(0.7), Colors.amber.withOpacity(0.6), Colors.amber.withOpacity(0.0), ], stops: const [ 0.3, 0.6, 0.8, 0.95, 1 ]), ), ), ), ) : SizedBox() ], ), ), ), ], ), ); } }
@model AllMissionsQueryModel @{ ViewBag.Title = "All Missions"; } <h2 class="text-center">@ViewBag.Title</h2> <hr /> <form method="get"> <div class="row"> <div class="form-group col-md-3 d-flex justify-content-between"> <div class="form-group"> <label asp-for="MissionType"></label> <select asp-for="MissionType" class="form-control"> <option value="">All</option> @foreach (var missionType in Model.MissionTypes) { <option value="@missionType">@missionType</option> } </select> </div> <div class="form-group"> <label asp-for="MissionsPerPage"></label> <select asp-for="MissionsPerPage" class="form-control"> <option value="0">3</option> <option value="1">6</option> <option value="2">9</option> </select> </div> </div> <div class="form-group col-md-3"> <label asp-for="SearchString"></label> <input asp-for="SearchString" class="form-control" placeholder="..."> </div> <div class="form-group col-md-3"> <div class="form-group"> <label asp-for="MissionSorting"></label> <select asp-for="MissionSorting" class="form-control"> <option value="0">Newest</option> <option value="1">Oldest</option> <option value="2">Threat Level Ascending</option> <option value="3">Threat Level Descending</option> </select> </div> </div> <div class="col-md-3"> <div class="form-group mt-4 p-2"> <input type="submit" value="Search" class="btn btn-primary" /> </div> </div> </div> </form> @{ var previousPage = Model.CurrentPage - 1; if (previousPage < 1) { previousPage = 1; } var maxPage = Math.Ceiling((double)Model.TotalMissionsCount / Model.MissionsPerPage); } <div class="row mb-5"> <div class="col-md-6 d-grid gap-2 d-md-flex justify-content-md-start"> <a class="btn btn-primary @(Model.CurrentPage == 1 ? "disabled" : string.Empty)" asp-controller="Mission" asp-action="All" asp-route-currentPage="@previousPage" asp-route-category="@Model.MissionType" asp-route-searchTerm="@Model.SearchString" asp-route-sorting="@((int)Model.MissionSorting)"><<</a> </div> @{ var shouldButtonBeDisabled = Model.CurrentPage == maxPage || !Model.Missions.Any(); } <div class="col-md-6 d-grid gap-2 d-md-flex justify-content-md-end"> <a class="btn btn-primary @(shouldButtonBeDisabled ? "disabled" : string.Empty)" asp-controller="Mission" asp-action="All" asp-route-currentPage="@(Model.CurrentPage + 1)" asp-route-category="@Model.MissionType" asp-route-searchTerm="@Model.SearchString" asp-route-sorting="@((int)Model.MissionSorting)">>></a> </div> </div> @if (!Model.Missions.Any()) { <h2 class="text-center">No houses found by the given criteria!</h2> } <div class="row"> @foreach (var mission in Model.Missions) { <partial name="_MissionPartial" model="@mission" /> } </div>
import {body, param} from "express-validator"; import {UsersRepository} from "../repositories/users-repository"; import {container} from "../composition-root"; import {BlogsRepository} from "../repositories/blogs-repository"; import {LikeStatus} from "../types/types"; const usersRepository = new UsersRepository() export const nameValidation = body('name').trim().isLength({min: 1, max: 15}).isString() export const websiteUrlValidation = body('websiteUrl').trim().isLength({min: 0, max: 100}).isString() .matches(/^https:\/\/([a-zA-Z0-9_-]+\.)+[a-zA-Z0-9_-]+(\/[a-zA-Z0-9_-]+)*\/?$/) export const titleValidation = body('title').isString().trim().notEmpty().isLength({min: 1, max: 30}) export const shortDescriptionValidation = body('shortDescription').trim().isLength({min: 1, max: 100}) .notEmpty().isString() export const contentValidation = body('content').trim().isLength({min: 1, max: 1000}).notEmpty().isString() export const contentValidationForComment = body('content').trim().isLength({min: 20, max: 300}).notEmpty() .isString() export const bodyBlogIdValidation = body('blogId').trim().notEmpty() .custom(async v => { const blogRepo = container.resolve(BlogsRepository) const blog = await blogRepo.findBlogByBlogId(v) if (!blog) throw new Error() return true }) export const paramsBlogIdValidation = param('blogId').trim().notEmpty().isString() export const loginValidation = body('login').isString().trim().notEmpty().isLength({min: 3, max: 10}) .custom(async value => { const isValidUser = await usersRepository.findByLoginOrEmail(value) if (isValidUser) throw new Error('Login already in use') return true }) export const passwordValidation = body('password').trim().isLength({min: 6, max: 20}).isString() export const newPasswordValidation = body('newPassword').trim().isLength({min: 6, max: 20}).isString() export const emailValidation = body('email').trim().isLength({min: 3, max: 100}).isString() .matches(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/) export const isCodeAlreadyConfirmed = body('code').custom(async value => { const user = await usersRepository.findUserByConfirmationCode(value) if (user?.emailConfirmation.isConfirmed) throw new Error('Code is already confirmed') return true }) export const isEmailAlreadyConfirmed = body('email').custom(async value => { const user = await usersRepository.findByLoginOrEmail(value) if (user?.emailConfirmation.isConfirmed) throw new Error('E-mail is already confirmed') return true }) export const codeValidation = body('code').isString().trim().notEmpty().isUUID() export const passwordRecoveryCodeValidation = body('recoveryCode').isString().trim().notEmpty().isUUID() export const isEmailExist = body('email').trim().custom(async value => { await usersRepository.findByEmail(value) return true }) export const likeStatusValidation = body('likeStatus').isString().trim().notEmpty().isIn(['Like', 'Dislike', 'None'])
import React from "react"; import { FieldAction, FieldInput, FieldLabel, } from "@strapi/design-system/Field"; import { Stack } from "@strapi/design-system/Stack"; import Refresh from "@strapi/icons/Refresh"; import styled from "styled-components"; export default function Index({ name, value, onChange, intlLabel }) { const dateObj = new Date(); let year = dateObj.getFullYear(); let month = ("0" + (dateObj.getMonth() + 1)).slice(-2); let day = ("0" + dateObj.getDate()).slice(-2); let hours = ("0" + dateObj.getHours()).slice(-2); let minutes = ("0" + dateObj.getMinutes()).slice(-2); let seconds = ("0" + dateObj.getSeconds()).slice(-2); let slug_name = `post-${year}-${month}-${day}-${hours}-${minutes}-${seconds}`; const generateSlug = () => { onChange({ target: { name, value: slug_name } }); }; const clearGeneratedSlug = () => { onChange({ target: { name, value: "" } }); }; return ( <Stack spacing={1}> <FieldLabel>{intlLabel?.defaultMessage}</FieldLabel> <FieldInput label="slug" name="slug" onChange={(e) => onChange({ target: { name, value: e.target.value }, }) } value={value ? value : generateSlug()} endAction={ <FieldActionWrapper onClick={() => clearGeneratedSlug()}> <Refresh /> </FieldActionWrapper> } /> </Stack> ); } export const FieldActionWrapper = styled(FieldAction)` svg { height: 1rem; width: 1rem; path { fill: ${({ theme }) => theme.colors.neutral400}; } } svg:hover { path { fill: ${({ theme }) => theme.colors.primary600}; } } `;
// Copyright 2023 RISC Zero, Inc. // // 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. pub(crate) mod bonsai; pub(crate) mod external; #[cfg(feature = "prove")] pub(crate) mod local; use std::{path::PathBuf, rc::Rc}; use anyhow::Result; use risc0_binfmt::{MemoryImage, Program}; use risc0_zkvm_platform::{memory::GUEST_MAX_MEM, PAGE_SIZE}; use serde::{Deserialize, Serialize}; use self::{bonsai::BonsaiProver, external::ExternalProver}; use crate::{is_dev_mode, ExecutorEnv, Receipt, VerifierContext}; /// A Prover can execute a given [MemoryImage] or ELF file and produce a /// [Receipt] that can be used to verify correct computation. /// /// # Usage /// To produce a proof, you must minimally provide an [ExecutorEnv] and either /// an ELF file or a [MemoryImage]. See the /// [risc0_build](https://docs.rs/risc0-build/latest/risc0_build/) crate for /// more information on producing ELF files from Rust source code. /// /// ```rust /// use risc0_zkvm::{ /// default_prover, /// ExecutorEnv, /// GUEST_MAX_MEM, /// MemoryImage, /// PAGE_SIZE, /// Program, /// ProverOpts, /// VerifierContext, /// }; /// use risc0_zkvm_methods::FIB_ELF; /// /// # #[cfg(not(feature = "cuda"))] /// # { /// // A straightforward case with an ELF file /// let env = ExecutorEnv::builder().add_input(&[20]).build().unwrap(); /// let receipt = default_prover().prove_elf(env, FIB_ELF).unwrap(); /// /// // Or you can specify a context and options /// // (Using the defaults as we do here is equivalent to the above code.) /// let env = ExecutorEnv::builder().add_input(&[20]).build().unwrap(); /// let ctx = VerifierContext::default(); /// let opts = ProverOpts::default(); /// let receipt = default_prover().prove_elf_with_ctx(env, &ctx, FIB_ELF, &opts).unwrap(); /// /// // Or you can prove from a `MemoryImage` /// // (generating a `MemoryImage` from an ELF file in this way is equivalent /// // to the above code.) /// let program = Program::load_elf(FIB_ELF, GUEST_MAX_MEM as u32).unwrap(); /// let image = MemoryImage::new(&program, PAGE_SIZE as u32).unwrap(); /// let env = ExecutorEnv::builder().add_input(&[20]).build().unwrap(); /// let ctx = VerifierContext::default(); /// let opts = ProverOpts::default(); /// let receipt = default_prover().prove(env, &ctx, &opts, image).unwrap(); /// # } /// ``` pub trait Prover { /// Return a name for this [Prover]. fn get_name(&self) -> String; /// Prove the specified [MemoryImage]. fn prove( &self, env: ExecutorEnv<'_>, ctx: &VerifierContext, opts: &ProverOpts, image: MemoryImage, ) -> Result<Receipt>; /// Prove the specified ELF binary. fn prove_elf(&self, env: ExecutorEnv<'_>, elf: &[u8]) -> Result<Receipt> { self.prove_elf_with_ctx( env, &VerifierContext::default(), elf, &ProverOpts::default(), ) } /// Prove the specified [MemoryImage] with the specified [VerifierContext]. fn prove_elf_with_ctx( &self, env: ExecutorEnv<'_>, ctx: &VerifierContext, elf: &[u8], opts: &ProverOpts, ) -> Result<Receipt> { let program = Program::load_elf(elf, GUEST_MAX_MEM as u32)?; let image = MemoryImage::new(&program, PAGE_SIZE as u32)?; self.prove(env, ctx, opts, image) } } /// Options to configure a [Prover]. #[derive(Clone, Serialize, Deserialize)] pub struct ProverOpts { /// The hash function to use. pub hashfn: String, } impl Default for ProverOpts { fn default() -> Self { Self { hashfn: "sha-256".to_string(), } } } /// Return a default [Prover] based on environment variables, falling back to a /// default CPU-based prover. pub fn default_prover() -> Rc<dyn Prover> { if !is_dev_mode() && std::env::var("BONSAI_API_URL").is_ok() && std::env::var("BONSAI_API_KEY").is_ok() { return Rc::new(BonsaiProver::new("bonsai")); } if cfg!(feature = "prove") { #[cfg(feature = "prove")] return Rc::new(self::local::LocalProver::new("local")); } Rc::new(ExternalProver::new("ipc", get_r0vm_path())) } fn get_r0vm_path() -> PathBuf { todo!() }
import React, { useReducer } from "react"; import { TasksContext } from "./TasksContext"; import { TasksReducer } from "./TasksReducer"; const initialState = { todos: [ { id: 1, title: "Hey please works..this time....", completed: "To do", priority: "Low", }, { id: 2, title: "Hey please works..this time....", completed: "To do", priority: "Low", }, ], }; export const ACTIONS = { ADD_TODO: "ADD_TODO", EDIT_TODO: "EDIT_TODO", }; const TasksProvider = ({ children }) => { const [state, dispatch] = useReducer(TasksReducer, initialState); const addTodo = (newTasks) => { console.log(newTasks); dispatch({ type: ACTIONS.ADD_TODO, payload: newTasks, }); }; const editTodo = ({ id, completed }) => { console.log("edit", id, completed); dispatch({ type: ACTIONS.EDIT_TODO, payload: { id, completed }, }); }; return ( <TasksContext.Provider value={{ message: "Trying to focus...!!!", todos: state.todos, addTodo, editTodo, }} > {children} </TasksContext.Provider> ); }; export default TasksProvider;
//===- HandshakePlaceBuffers.h - Place buffers in DFG -----------*- C++ -*-===// // // Dynamatic is under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file declares the --handshake-place-buffers pass, including the pass's // driver which may need to be inherited from by other passes that incorporate a // buffer placement step within their logic. // //===----------------------------------------------------------------------===// #ifndef DYNAMATIC_TRANSFORMS_BUFFERPLACEMENT_PLACEBUFFERS_H #define DYNAMATIC_TRANSFORMS_BUFFERPLACEMENT_PLACEBUFFERS_H #include "circt/Dialect/Handshake/HandshakeOps.h" #include "dynamatic/Support/DynamaticPass.h" #include "dynamatic/Support/LLVM.h" #include "dynamatic/Support/Logging.h" #include "dynamatic/Support/TimingModels.h" #include "dynamatic/Transforms/BufferPlacement/BufferPlacementMILP.h" #include "dynamatic/Transforms/BufferPlacement/BufferingSupport.h" #include "dynamatic/Transforms/BufferPlacement/CFDFC.h" #include "mlir/Dialect/Func/IR/FuncOps.h" namespace dynamatic { namespace buffer { std::unique_ptr<dynamatic::DynamaticPass> createHandshakePlaceBuffers( StringRef algorithm = "on-merges", StringRef frequencies = "", StringRef timingModels = "", bool firstCFDFC = false, double targetCP = 4.0, unsigned timeout = 180, bool dumpLogs = false); #define GEN_PASS_DECL_HANDSHAKEPLACEBUFFERS #define GEN_PASS_DEF_HANDSHAKEPLACEBUFFERS #include "dynamatic/Transforms/Passes.h.inc" /// Public pass driver for the buffer placement pass. Unlike most other /// Dynamatic passes, users may wish to access the pass's internal state to /// derive insights useful for different kinds of IR processing. To facilitate /// users' workflow and minimize code duplication, this driver is public and /// exposes most of its behavior in protected virtual methods which may be /// overriden by sub-types of the pass. struct HandshakePlaceBuffersPass : public dynamatic::buffer::impl::HandshakePlaceBuffersBase< HandshakePlaceBuffersPass> { /// Trivial field-by-field constructor. HandshakePlaceBuffersPass(StringRef algorithm, StringRef frequencies, StringRef timingModels, bool firstCFDFC, double targetCP, unsigned timeout, bool dumpLogs); /// Called on the MLIR module provided as input. void runDynamaticPass() override; protected: #ifndef DYNAMATIC_GUROBI_NOT_INSTALLED /// Called for all buffer placement strategies that not require Gurobi to /// be installed on the host system. LogicalResult placeUsingMILP(); /// Checks a couple of invariants in the function that are required by our /// buffer placement algorithm. Fails when the function does not satisfy at /// least one invariant. virtual LogicalResult checkFuncInvariants(FuncInfo &info); /// Places buffers in the function, according to the logic dictated by the /// algorithm the pass was instantiated with. virtual LogicalResult placeBuffers(FuncInfo &info, TimingDatabase &timingDB); /// Identifies and extracts all existing CFDFCs in the function using /// estimated transition frequencies between its basic blocks. Fills the /// `cfdfcs` vector with the extracted cycles. CFDFC identification works by /// iteratively solving MILPs until the MILP solution indicates that no /// "executable cycle" remains in the circuit. virtual LogicalResult getCFDFCs(FuncInfo &info, Logger *logger, SmallVector<CFDFC> &cfdfcs); /// Computes an optimal buffer placement for a Handhsake function by solving /// a large MILP over the entire dataflow circuit represented by the /// function. Fills the `placement` map with placement decisions derived /// from the MILP's solution. virtual LogicalResult getBufferPlacement(FuncInfo &info, TimingDatabase &timingDB, Logger *logger, BufferPlacement &placement); #endif /// Called for all buffer placement strategies that do not require Gurobi to /// be installed on the host system. LogicalResult placeWithoutUsingMILP(); /// Instantiates buffers inside the IR, following placement decisions /// determined by the buffer placement MILP. virtual void instantiateBuffers(BufferPlacement &placement); }; } // namespace buffer } // namespace dynamatic #endif // DYNAMATIC_TRANSFORMS_BUFFERPLACEMENT_PLACEBUFFERS_H
"use client"; import React, { useEffect, useRef, useState } from "react"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { PaperPlaneIcon, ShadowInnerIcon } from "@radix-ui/react-icons"; import { postMessage } from "@/services/MessageService"; import { useApi } from "@/hooks/useApi"; function NewMessage() { const inputRef = useRef<HTMLInputElement>(null); const [isLoading, setIsLoading] = useState(false); async function handlePostMessage() { setIsLoading(true); if (!inputRef.current || !inputRef.current.value) { alert("Please type a message"); setIsLoading(false); inputRef.current?.focus(); return; } await postMessage({ message: inputRef.current.value }); setIsLoading(false); inputRef.current.value = ""; inputRef.current.focus(); } useEffect(() => { if (!inputRef.current) return; inputRef.current.focus(); }, []); return ( <div className="flex items-center justify-center gap-2"> <Input ref={inputRef} type="text" placeholder="Type a message" className="h-12" /> <Button variant="default" className="flex h-12 gap-2" onClick={handlePostMessage} > <> {isLoading ? ( <> Posting <ShadowInnerIcon className="animate-spin" /> </> ) : ( <> Post <PaperPlaneIcon /> </> )} </> </Button> </div> ); } export default NewMessage;
import '../../base/common/document_types.dart'; import '../../base/common/operators_def.dart'; import '../../base/operator_expression.dart'; import '../../query_expression/query_expression.dart'; import '../base/aggregation_stage.dart'; /// `$limit` aggregation stage /// /// ### Stage description /// /// lRestricts entire documents or content within documents from being /// outputted based on information stored in the documents themselves. /// /// Example: /// /// Dart code: /// ``` /// $limit(5).build() /// ``` /// Equivalent mongoDB aggregation stage: /// ``` /// {$limit: 5} /// ``` /// or /// ``` /// $limit.query(where..limit(5)).build() /// ``` /// Equivalent mongoDB aggregation stage: /// ``` /// { $redact: { /// $cond: { /// if: { $gt: [ { $size: { $setIntersection: [ "$tags", [ "STLW", "G" ] ] } }, 0 ] }, /// then: "$$DESCEND", /// else: "$$PRUNE" /// } /// } /// } /// ``` /// https://docs.mongodb.com/manual/reference/operator/aggregation/limit/ class $redact extends AggregationStage { /// Creates `$redact` aggregation stage /// /// [expr] - can be any valid expression as long as it resolves to the /// $$DESCEND, $$PRUNE, or $$KEEP system variables. $redact(OperatorExpression expr) : super(st$redact, valueToContent(expr)); $redact.raw(MongoDocument raw) : super.raw(st$redact, raw); }
import { MenuItem, useColorMode, useColorModeValue } from '@chakra-ui/react' import { MdOutlineLightMode, MdOutlineDarkMode } from 'react-icons/md' const MobileThemeToggle = ({}) => { const { colorMode, toggleColorMode } = useColorMode() return ( <MenuItem icon={ colorMode === 'light' ? ( <MdOutlineLightMode /> ) : ( <MdOutlineDarkMode /> ) } borderRadius="xl" transition="all 225ms ease-in-out" mb={2} _hover={{ bg: 'transparent', color: useColorModeValue('theme.bg', 'theme.secondary'), boxShadow: useColorModeValue('tabShadowLight', 'tabShadowDark') }} _focus={{ bg: 'transparent', color: useColorModeValue('theme.bg', 'theme.secondary'), boxShadow: useColorModeValue('tabShadowLight', 'tabShadowDark') }} _active={{ bg: 'transparent', boxShadow: useColorModeValue('tabShadowLight', 'tabShadowDark') }} onClick={toggleColorMode} > {colorMode === 'light' ? 'change to dark mode' : 'change to light mode'} </MenuItem> ) } export default MobileThemeToggle
import React, { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { Card } from 'react-bootstrap'; import '../css/list-item-role.css'; import axios from 'axios'; const ListItemAuthors = ({ key, element, setAuthors, refreshRate, setRefreshRate }) => { const navigate = useNavigate(); const { email, role, uid, username } = element; const [isBlocked, setIsBlocked] = useState(element.isBlocked); const handleBlockClick = async () => { try { const response = await axios.put(`https://newsua-217e80321b33.herokuapp.com/admin-block-user?uid=${uid}`); console.log(response.data); setAuthors(prevAuthors => prevAuthors.map(author => author.uid === uid ? { ...author, isBlocked: true } : author)); setRefreshRate(refreshRate + 1); setIsBlocked(true); } catch (error) { console.log(error); } }; const handleUnblockClick = async () => { try { setIsBlocked(false); const response = await axios.put(`https://newsua-217e80321b33.herokuapp.com/admin-unblock-user?uid=${uid}`); console.log(response.data); setAuthors(prevAuthors => prevAuthors.map(author => author.uid === uid ? { ...author, isBlocked: false } : author)); setRefreshRate(refreshRate + 1); } catch (error) { console.log(error); } }; const handleSetModeratorClick = async () => { try { const response = await axios.put(`https://newsua-217e80321b33.herokuapp.com/admin-set-moderator?uid=${uid}`); console.log(response.data); setAuthors(prevAuthors => prevAuthors.map(author => author.uid === uid ? { ...author, role: 'moderator' } : author)); setRefreshRate(1); } catch (error) { console.log(error); } } useEffect(() => { console.log(`Author ${element.username} is now ${isBlocked ? 'blocked' : 'unblocked'}`); }, [isBlocked]); return ( <Card className="list-item-role"> <div className='list-item-role-info'> <Card.Text className="list-item-role-info-username" >{username}</Card.Text> <Card.Text className="list-item-role-info-email" >{email}</Card.Text> </div> <div className='list-item-role-controls'> <button onClick={handleSetModeratorClick}>Надати модерку</button> <button onClick={isBlocked ? handleUnblockClick : handleBlockClick}> {isBlocked ? "Розблокувати" : "Заблокувати"} </button> </div> </Card> ); }; export default ListItemAuthors;
(module translator (lib "eopl.ss" "eopl") (require "lang.scm") (require "environments.scm") (provide translation-of-program) (define translation-of-program (lambda (pgm) (cases program pgm (a-program (exp1) (a-program (translation-of exp1 (init-env))))))) (define translation-of (lambda (exp env) (cases expression exp (const-exp (num) (const-exp num)) (var-exp (var) (var-exp var)) (diff-exp (exp1 exp2) (diff-exp (translation-of exp1 env) (translation-of exp2 env))) (zero?-exp (exp1) (zero?-exp (translation-of exp1 env))) (if-exp (exp1 exp2 exp3) (if-exp (translation-of exp1 env) (translation-of exp2 env) (translation-of exp3 env))) (let-exp (var exp1 body) (let-exp var (translation-of exp1 env) (translation-of body env))) ; ##################################################### ; ###### ENTER YOUR CODE HERE ; ###### THE LINES BELOW ARE PUT ONLY TO PROVIDE YOU ; ###### A WORKING CODE BASELINE. THEY ARE REQUIRED ; ###### TO CHANGE. ; ###### ; ###### Here, you need to translate the original ; ###### proc-exp, call-exp, and letrec-exp to the ; ###### nested versions. To understand how translation ; ###### works, you can check the lexaddr code in the ; ###### EOPL GUI. ; ###### In this part, you will also do the count ; ###### incrementation!!! ; ##################################################### ; ##################################################### ; ###### proc-nested-exp has variable name, the count, anonym and the body as arguments ; ##################################################### (proc-exp (var body) ) ; ##################################################### ; ###### call-nested-exp has operator, operand and the count as arguments ; ###### if the operator is an var-exp, it means that it is already ; ###### in the environment therefore count will be incremented, ; ###### else it will be initialized as 1 ; ###### Hint: for incrementing, you can use diff-exp ; ##################################################### (call-exp (rator rand) ) ; ##################################################### ; ###### count should be included in the nested version ; ##################################################### (letrec-exp (p-name b-var p-body letrec-body) ) ; ##################################################### (else (report-invalid-source-expression exp)) ))) (define report-invalid-source-expression (lambda (exp) (eopl:error 'value-of "Illegal expression in source code: ~s" exp))) )
package com.android.systemui.qs.tiles; import android.content.Intent; import android.content.res.Resources; import android.hardware.SensorPrivacyManager; import android.os.Handler; import android.os.Looper; import android.view.View; import android.widget.Switch; import androidx.appcompat.R$styleable; import androidx.lifecycle.LifecycleOwner; import com.android.internal.logging.MetricsLogger; import com.android.systemui.R$string; import com.android.systemui.plugins.ActivityStarter; import com.android.systemui.plugins.FalsingManager; import com.android.systemui.plugins.qs.QSTile; import com.android.systemui.plugins.statusbar.StatusBarStateController; import com.android.systemui.qs.QSHost; import com.android.systemui.qs.SettingObserver; import com.android.systemui.qs.logging.QSLogger; import com.android.systemui.qs.tileimpl.QSTileImpl; import com.android.systemui.statusbar.policy.BatteryController; import com.android.systemui.statusbar.policy.RotationLockController; import com.android.systemui.statusbar.policy.RotationLockControllerImpl; import com.android.systemui.util.settings.SecureSettings; public class RotationLockTile extends QSTileImpl<QSTile.BooleanState> implements BatteryController.BatteryStateChangeCallback { public final BatteryController mBatteryController; public final RotationLockController.RotationLockControllerCallback mCallback; public final RotationLockController mController; public final QSTile.Icon mIcon = QSTileImpl.ResourceIcon.get(17302827); public final SensorPrivacyManager mPrivacyManager; public final SensorPrivacyManager.OnSensorPrivacyChangedListener mSensorPrivacyChangedListener; public final SettingObserver mSetting; public int getMetricsCategory() { return R$styleable.AppCompatTheme_windowFixedWidthMinor; } public RotationLockTile(QSHost qSHost, Looper looper, Handler handler, FalsingManager falsingManager, MetricsLogger metricsLogger, StatusBarStateController statusBarStateController, ActivityStarter activityStarter, QSLogger qSLogger, RotationLockController rotationLockController, SensorPrivacyManager sensorPrivacyManager, BatteryController batteryController, SecureSettings secureSettings) { super(qSHost, looper, handler, falsingManager, metricsLogger, statusBarStateController, activityStarter, qSLogger); AnonymousClass2 r2 = new RotationLockController.RotationLockControllerCallback() { public void onRotationLockStateChanged(boolean z, boolean z2) { RotationLockTile.this.refreshState(Boolean.valueOf(z)); } }; this.mCallback = r2; this.mSensorPrivacyChangedListener = new RotationLockTile$$ExternalSyntheticLambda0(this); this.mController = rotationLockController; rotationLockController.observe((LifecycleOwner) this, r2); this.mPrivacyManager = sensorPrivacyManager; this.mBatteryController = batteryController; SecureSettings secureSettings2 = secureSettings; this.mSetting = new SettingObserver(secureSettings2, this.mHandler, "camera_autorotate", qSHost.getUserContext().getUserId()) { public void handleValueChanged(int i, boolean z) { RotationLockTile.this.handleRefreshState((Object) null); } }; batteryController.observe(getLifecycle(), this); } public void handleInitialize() { this.mPrivacyManager.addSensorPrivacyListener(2, this.mSensorPrivacyChangedListener); } public void onPowerSaveChanged(boolean z) { refreshState(); } public QSTile.BooleanState newTileState() { return new QSTile.BooleanState(); } public Intent getLongClickIntent() { return new Intent("android.settings.AUTO_ROTATE_SETTINGS"); } public void handleClick(View view) { boolean z = !((QSTile.BooleanState) this.mState).value; this.mController.setRotationLocked(!z); refreshState(Boolean.valueOf(z)); } public CharSequence getTileLabel() { return ((QSTile.BooleanState) getState()).label; } public void handleUpdateState(QSTile.BooleanState booleanState, Object obj) { boolean isRotationLocked = this.mController.isRotationLocked(); int i = 2; boolean z = !this.mBatteryController.isPowerSave() && !this.mPrivacyManager.isSensorPrivacyEnabled(2) && RotationLockControllerImpl.hasSufficientPermission(this.mContext) && this.mController.isCameraRotationEnabled(); booleanState.value = !isRotationLocked; booleanState.label = this.mContext.getString(R$string.quick_settings_rotation_unlocked_label); booleanState.icon = this.mIcon; booleanState.contentDescription = getAccessibilityString(isRotationLocked); if (isRotationLocked || !z) { booleanState.secondaryLabel = ""; } else { booleanState.secondaryLabel = this.mContext.getResources().getString(R$string.rotation_lock_camera_rotation_on); } booleanState.stateDescription = booleanState.secondaryLabel; booleanState.expandedAccessibilityClassName = Switch.class.getName(); if (!booleanState.value) { i = 1; } booleanState.state = i; } public void handleDestroy() { super.handleDestroy(); this.mSetting.setListening(false); this.mPrivacyManager.removeSensorPrivacyListener(2, this.mSensorPrivacyChangedListener); } public void handleSetListening(boolean z) { super.handleSetListening(z); this.mSetting.setListening(z); } public void handleUserSwitch(int i) { this.mSetting.setUserId(i); handleRefreshState((Object) null); } public static boolean isCurrentOrientationLockPortrait(RotationLockController rotationLockController, Resources resources) { int rotationLockOrientation = rotationLockController.getRotationLockOrientation(); if (rotationLockOrientation == 0) { if (resources.getConfiguration().orientation != 2) { return true; } return false; } else if (rotationLockOrientation != 2) { return true; } else { return false; } } public final String getAccessibilityString(boolean z) { return this.mContext.getString(R$string.accessibility_quick_settings_rotation); } /* access modifiers changed from: private */ public /* synthetic */ void lambda$new$0(int i, boolean z) { refreshState(); } }
#ifndef modes_h #define modes_h /* Project Scope */ #include "display/display.h" #include "display/displayEffects.h" /* Libraries */ #include <Button2.h> /* Arduino Core */ #include <Arduino.h> /* C++ Standard Library */ #include <memory> #include <vector> class GameOfLife; struct ButtonReferences { Button2& mode; Button2& select; Button2& left; Button2& right; }; class MainModeFunction { public: MainModeFunction(String name, PixelDisplay& display, ButtonReferences buttons) : _name(name), _display(display), buttons(buttons) {} // should be called by the parent when moving into this mode void moveInto(); // should be called by the parent when this mode is active void run(); // should be called by the parent when moving out of this mode void moveOut(); // indicates that this mode is ready to exit/return virtual bool finished() const { return _finished; } // get the name of this mode String getName() const { return _name; } protected: virtual void moveIntoCore(); virtual void moveOutCore() = 0; virtual void runCore() = 0; bool _finished = false; PixelDisplay& _display; ButtonReferences buttons; String _name; private: void clearAllButtonCallbacks(Button2& button); }; class Mode_ClockFace : public MainModeFunction { public: Mode_ClockFace(PixelDisplay& display, ButtonReferences buttons); protected: void moveIntoCore() override final; void runCore() override final; void moveOutCore() override final {} private: std::vector<std::unique_ptr<DisplayEffect>> faces; uint8_t clockfaceIndex = 0; std::vector<std::unique_ptr<FilterMethod>> filters; uint8_t filterIndex = 0; uint32_t lastFilterChangeTime = 0; uint32_t filterChangePeriod = 10000; ClockFaceTimeStruct timePrev; }; class Mode_Effects : public MainModeFunction { public: Mode_Effects(PixelDisplay& display, ButtonReferences buttons); protected: void moveIntoCore() override final; void runCore() override final; void moveOutCore() override final {} private: std::vector<std::shared_ptr<DisplayEffect>> effects; uint8_t effectIndex = 0; std::unique_ptr<GameOfLife> golTrainer; std::shared_ptr<GameOfLife> golActual; }; class Mode_SettingsMenu : public MainModeFunction { public: Mode_SettingsMenu(PixelDisplay& display, ButtonReferences buttons); protected: void moveIntoCore() override final; void runCore() override final; void moveOutCore() override final; private: void cycleActiveSetting(Button2& btn); void registerButtonCallbacks(); std::unique_ptr<TextScroller> menuTextScroller; std::vector<std::shared_ptr<MainModeFunction>> menuPages; std::shared_ptr<MainModeFunction> activeMenuPage = nullptr; uint8_t menuIndex = 0; }; class Mode_SettingsMenu_SetTime : public MainModeFunction { public: Mode_SettingsMenu_SetTime(PixelDisplay& display, ButtonReferences buttons); bool finished() const override; protected: void moveIntoCore() override final; void runCore() override final; void moveOutCore() override final {} private: int secondsOffset = 0; std::unique_ptr<TextScroller> textscroller; enum class TimeSegment { cancel, hour, minute, second, confirm, done }; TimeSegment currentlySettingTimeSegment = TimeSegment::hour; }; class Mode_SettingsMenu_SetBrightness : public MainModeFunction { public: Mode_SettingsMenu_SetBrightness(PixelDisplay& display, ButtonReferences buttons) : MainModeFunction("Set Brightness", display, buttons) {} protected: void moveIntoCore() override final {} void runCore() override final {} void moveOutCore() override final {} }; class ModeManager { public: ModeManager(PixelDisplay& display, ButtonReferences buttons); void cycleMode(); void run(); private: std::vector<std::unique_ptr<MainModeFunction>> modes; uint8_t modeIndex = 0; }; #endif // modes_h
// // BreedListViewModelTests.swift // TheCatAppTests // // Created by revangelista on 08/05/2024. // import XCTest @testable import TheCatApp final class BreedListViewModelTests: XCTestCase { private var mockedBreedRepository: MockedBreedRepository! private var sut: BreedListViewModel! override func setUp() { super.setUp() mockedBreedRepository = MockedBreedRepository() sut = BreedListViewModel(repository: mockedBreedRepository) } override func tearDown() { super.tearDown() mockedBreedRepository = nil sut = nil } func test_start_doesTheViewStateIsLoading() { let expectation = expectation(description: "waiting") Task { await self.sut.fetchBreeds(page: 0) XCTAssertFalse(self.sut.state.isSuccess) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func test_fetchBreeds_doesCreateCardsWithCorrectValue() { let mockedBreed = Breed.fixture(id: "cardItemId", name: "cardItemName") let mockedCardItem = CardItem(id: mockedBreed.id, title: mockedBreed.name) let expectation = expectation(description: "waiting") Task { self.mockedBreedRepository.onFetchBreeds = { _ in return [mockedBreed] } await self.sut.fetchBreeds(page: 0) XCTAssertEqual(self.sut.state.value?.first?.id, mockedCardItem.id) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func test_fetchBreeds_withGenericNetworkError_doesStateGeneric() { let expectation = expectation(description: "waiting") mockedBreedRepository.onFetchBreeds = { _ in throw NetworkError.generic } Task { await self.sut.fetchBreeds(page: 0) XCTAssertEqual(self.sut.state.error, .generic) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func test_fetchBreeds_withInvalidResponseNetworkError_doesStateGeneric() { let expectation = expectation(description: "waiting") mockedBreedRepository.onFetchBreeds = { _ in throw NetworkError.invalidResponse } Task { await self.sut.fetchBreeds(page: 0) XCTAssertEqual(self.sut.state.error, .generic) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func test_fetchBreeds_withServerError_doesStateServerError() { let expectation = expectation(description: "waiting") mockedBreedRepository.onFetchBreeds = { _ in throw NetworkError.serverError(0) } Task { await self.sut.fetchBreeds(page: 0) XCTAssertEqual(self.sut.state.error, .serverError) expectation.fulfill() } wait(for: [expectation], timeout: 1) } func test_fetchBreeds_withClientError_doesStateClientError() { let expectation = expectation(description: "waiting") mockedBreedRepository.onFetchBreeds = { _ in throw NetworkError.clientError(0) } Task { await self.sut.fetchBreeds(page: 0) XCTAssertEqual(self.sut.state.error, .clientError) expectation.fulfill() } wait(for: [expectation], timeout: 1) } } extension BreedListViewModelTests { class MockedBreedRepository: BreedRepositoryProtocol { var onFetchBreeds: ((_ page: Int) async throws -> [Breed])? func fetchBreeds(page: Int) async throws -> [Breed] { guard let request = try await onFetchBreeds?(page) else { throw ErrorViewType.generic } return request } func toggleFavorite(breed: Breed) { } func fetchAllFavorites() throws -> [Breed] { return [] } } }
-- Databricks notebook source -- MAGIC %md -- MAGIC ###Overview -- MAGIC This notebooks contains complete SPARK SQL / DELTA LAKE SQL Tutorial -- MAGIC ###Details -- MAGIC | Detail Tag | Information -- MAGIC |----|----- -- MAGIC | Notebook | SQL DRL HAVING Clause Statement details -- MAGIC | Originally Created By | Raveendra -- MAGIC | Reference And Credits | apache.spark.org & databricks.com -- MAGIC -- MAGIC ###History -- MAGIC |Date | Developed By | comments -- MAGIC |----|-----|---- -- MAGIC |23/05/2021|Ravendra| Initial Version -- MAGIC | Find more Videos | Youtube | <a href="https://www.youtube.com/watch?v=FpxkiGPFyfM&list=PL50mYnndduIHRXI2G0yibvhd3Ck5lRuMn" target="_blank"> Youtube link </a>| -- COMMAND ---------- -- MAGIC %md -- MAGIC #### HAVING clause -- MAGIC * Filters the results produced by GROUP BY based on the specified condition. Often used in conjunction with a GROUP BY clause. -- COMMAND ---------- -- MAGIC %md -- MAGIC #### Syntax -- MAGIC `__HAVING boolean_expression`__ -- MAGIC -- MAGIC * Parameters -- MAGIC -- MAGIC __`boolean_expression`__ -- MAGIC -- MAGIC * Specifies any expression that evaluates to a result type boolean. Two or more expressions may be combined together using the logical operators ( AND, OR ). -- MAGIC -- MAGIC __`Note`__ -- MAGIC -- MAGIC * The expressions specified in the HAVING clause can only refer to: -- MAGIC * * Constants -- MAGIC * * Expressions that appear in GROUP BY -- MAGIC * * Aggregate functions -- COMMAND ---------- DROP TABLE IF EXISTS dealer; CREATE TABLE dealer (id INT, city STRING, car_model STRING, quantity INT); INSERT INTO dealer VALUES (100, 'Bangalore', 'Honda Civic', 10), (100, 'Bangalore', 'Honda Accord', 15), (100, 'Bangalore', 'Honda CRV', 7), (200, 'Chennai', 'Honda Civic', 20), (200, 'Chennai', 'Honda Accord', 10), (200, 'Chennai', 'Honda CRV', 3), (300, 'Hyderabad', 'Honda Civic', 5), (300, 'Hyderabad', 'Honda Accord', 8); -- COMMAND ---------- -- MAGIC %md -- MAGIC * `HAVING` clause referring to column in `GROUP BY`. -- COMMAND ---------- select * from dealer -- COMMAND ---------- SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city order by sum ; -- COMMAND ---------- -- MAGIC %md -- MAGIC * `HAVING` clause referring to aggregate function. -- MAGIC -- COMMAND ---------- SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING sum(quantity) > 15; -- COMMAND ---------- -- MAGIC %md -- MAGIC * `HAVING` clause referring to aggregate function by its alias. -- MAGIC -- COMMAND ---------- SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING sum > 15; -- COMMAND ---------- -- MAGIC %md -- MAGIC * `HAVING` clause referring to a different aggregate function than what is present in -- MAGIC * `SELECT` list. -- COMMAND ---------- SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING max(quantity) > 15; -- COMMAND ---------- -- MAGIC %md -- MAGIC * `HAVING` clause referring to constant expression. -- COMMAND ---------- SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING 1 > 0 ORDER BY city; -- COMMAND ---------- -- MAGIC %md -- MAGIC * `HAVING` clause without a `GROUP BY` clause. -- MAGIC * While using HAVING clause without group by, we need to use aggregate functions in expression -- COMMAND ---------- SELECT id,sum(quantity) AS sum FROM dealer GROUP BY id HAVING sum(quantity) > 15; -- COMMAND ---------- SELECT sum(quantity) AS sum FROM dealer HAVING sum > 10; -- COMMAND ---------- -- MAGIC %md -- MAGIC * __`HAVING`__ Clause column should be in select list. otherwise it will throw exception -- MAGIC * __`EXCEPTION`__ : cannot resolve '`quantity`' given input columns: [sum]; -- MAGIC -- COMMAND ---------- SELECT sum(quantity) AS sum FROM dealer HAVING sum > 10;
"use client"; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler, } from "chart.js"; import { useState } from "react"; import { Line } from "react-chartjs-2"; ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler ); const dropdownData = ["This Week", "This Month", "This Year"]; export default function LineChart() { const [getSelected, setSelected] = useState(0); const d = { 0: [148, 140, 210, 120, 160, 120, 190, 170, 135, 210, 180, 249], 1: [140, 148, 120, 210, 140, 160, 140, 190, 210, 135, 249, 180], 2: [170, 190, 210, 135, 249, 180, 140, 148, 120, 210, 140, 160], }; const data = { labels: [ "Jan", "Feb", "Marc", "April", "May", "June", "July", "Agust", "Sept", "Oct", "Nov", "Dec", ], datasets: [ { label: "Dataset", backgroundColor: "rgba(251, 247, 237, 0.9)", borderColor: "red", data: d[getSelected], tension: 0.4, fill: true, }, ], }; const options = { scales: { y: { min: 0, max: 300, }, }, }; return ( <> <div className="ps-widget bgc-white bdrs4 p30 mb30 overflow-hidden position-relative"> <div className="navtab-style1"> <div className="d-sm-flex align-items-center justify-content-between"> <h4 className="title fz17 mb20">Profile Views</h4> <div className="page_control_shorting dark-color pr10 text-center text-md-end"> <div className="dropdown bootstrap-select show-tick"> <button type="button" className="btn dropdown-toggle btn-light" data-bs-toggle="dropdown" > <div className="filter-option"> <div className="filter-option-inner"> <div className="filter-option-inner-inner"> {dropdownData[getSelected]} </div> </div> </div> </button> <div className="dropdown-menu"> <div className="inner show"> <ul className="dropdown-menu inner show"> {dropdownData.map((item, i) => ( <li key={i} className={getSelected === i ? "selected active" : ""} > <a onClick={() => setSelected(i)} className={`dropdown-item ${ getSelected === i ? "selected active" : "" }`} > <span className="bs-ok-default check-mark" /> <span className="text">{item}</span> </a> </li> ))} </ul> </div> </div> </div> </div> </div> <Line options={options} data={data} /> </div> </div> </> ); }
/* * Copyright 2015 Mikhail Titov. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.raven.sched.impl; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import mockit.Expectations; import mockit.Mocked; import mockit.Verifications; import mockit.VerificationsInOrder; import mockit.integration.junit4.JMockit; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.raven.sched.Executor; import org.raven.sched.ExecutorService; import org.raven.sched.ExecutorServiceException; import org.raven.sched.Task; import org.raven.test.RavenCoreTestCase; import org.raven.tree.Node; /** * * @author Mikhail Titov */ @RunWith(JMockit.class) public class ExecutorServiceBalancerNodeTest extends RavenCoreTestCase { private ExecutorServiceBalancerNode balancer; private CountDownLatch executedTasks; @Before public void prepare() { balancer = new ExecutorServiceBalancerNode(); balancer.setName("executor balancer"); testsNode.addAndSaveChildren(balancer); } @Test(expected = ExecutorServiceException.class) public void executeOnStoppedWithoutFailover( @Mocked final Task task ) throws ExecutorServiceException { try { balancer.execute(task); } finally { new Verifications() {{ task.run(); times = 0; }}; } } @Test(expected = ExecutorServiceException.class) public void executeOnStoppedWithFailover( @Mocked final Task task ) throws ExecutorServiceException { try { balancer.setUseSystemExecutorAsFailover(true); balancer.execute(task); } finally { new Verifications() {{ task.run(); times = 0; }}; } } // @Test() // public void executeOnStoppedWithFailover( // @Mocked final Task task // ) throws ExecutorServiceException // { // balancer.setUseSystemExecutorAsFailover(true); // balancer.execute(task); // // new Verifications() {{ // task.run(); times = 1; // }}; // } // @Test(expected = ExecutorServiceException.class) public void executeOnSartedWithoutFailover( @Mocked final Task task ) throws ExecutorServiceException { assertTrue(balancer.start()); try { balancer.execute(task); } finally { new Verifications() {{ task.run(); times = 0; }}; } } @Test() public void executeOnStartedWithFailover( @Mocked final Task task ) throws ExecutorServiceException { balancer.setUseSystemExecutorAsFailover(true); assertTrue(balancer.start()); balancer.execute(task); new Verifications() {{ task.run(); times = 1; }}; } @Test(expected=ExecutorServiceException.class) public void executeWithStoppedExecutor( @Mocked final Task task ) throws Exception { addExecutor("e1", null, false); assertNotNull(balancer.getNode("e1")); assertFalse(balancer.getNode("e1").isStarted()); assertTrue(balancer.start()); balancer.execute(task); } @Test() public void executeWithStartedExecutor( @Mocked final Task task, @Mocked final Executor executor ) throws Exception { addExecutor("e1", executor, true); assertTrue(balancer.start()); balancer.execute(task); new Verifications() {{ executor.execute(task); times = 1; }}; } @Test() public void balancerTest( @Mocked final Task task, @Mocked final Executor executor, @Mocked final Executor executor1 ) throws Exception { addExecutor("e1", executor, true); addExecutor("e2", executor1, true); assertTrue(balancer.start()); balancer.execute(task); balancer.execute(task); balancer.execute(task); new VerificationsInOrder() {{ executor.execute(task); times = 1; executor1.execute(task); times = 1; executor.execute(task); times = 1; }}; } @Test() public void executeWithFailedExecutor( @Mocked final Task task, @Mocked final Executor executor, @Mocked final Executor executor1 ) throws Exception { new Expectations() {{ executor.execute(task); times = 1; result = new ExecutorServiceException("test"); }}; addExecutor("e1", executor, true); addExecutor("e2", executor1, true); assertTrue(balancer.start()); balancer.execute(task); new VerificationsInOrder() {{ executor.execute(task); times = 1; executor1.execute(task); times = 1; }}; } @Test(expected = ExecutorServiceException.class) public void maxExecutionTries( @Mocked final Task task, @Mocked final Executor executor, @Mocked final Executor executor1 ) throws Exception { new Expectations() {{ executor.execute(task); times = 1; result = new ExecutorServiceException("test"); executor1.execute(task); times = 1; result = new ExecutorServiceException("test"); }}; addExecutor("e1", executor, true); addExecutor("e2", executor1, true); assertTrue(balancer.start()); try { balancer.execute(task); } finally { new VerificationsInOrder() {{ executor.execute(task); times = 1; executor1.execute(task); times = 1; }}; } } @Test(expected = ExecutorServiceException.class) public void stopDynamicExecutorTest( @Mocked final Task task, @Mocked final Executor executor ) throws Exception { TestExecutor e1 = addExecutor("e1", executor, true); assertTrue(balancer.start()); try { balancer.execute(task); e1.stop(); balancer.execute(task); } finally { new Verifications() {{ executor.execute(task); times = 1; }}; } } @Test() public void startDynamicExecutorTest( @Mocked final Task task, @Mocked final Executor executor, @Mocked final Executor executor1 ) throws Exception { TestExecutor e1 = addExecutor("e1", executor, false); TestExecutor e2 = addExecutor("e2", executor1, true); assertTrue(balancer.start()); balancer.execute(task); e1.start(); e2.stop(); balancer.execute(task); new VerificationsInOrder() {{ executor1.execute(task); times = 1; executor.execute(task); times = 1; }}; } @Test() public void addDynamicExecutorTest( @Mocked final Task task, @Mocked final Executor executor, @Mocked final Executor executor1 ) throws Exception { TestExecutor e1 = addExecutor("e1", executor, true); assertTrue(balancer.start()); balancer.execute(task); addExecutor("e2", executor1, true); balancer.execute(task); new VerificationsInOrder() {{ executor.execute(task); times = 1; executor1.execute(task); times = 1; }}; } @Test() public void moveExecutorToBalancerTest( @Mocked final Task task, @Mocked final Executor executor, @Mocked final Executor executor1 ) throws Exception { TestExecutor e1 = addExecutor("e1", executor, true); TestExecutor e2 = addExecutor(testsNode, "e2", executor1, true); assertTrue(balancer.start()); balancer.execute(task); tree.move(e2, balancer, null); balancer.execute(task); new VerificationsInOrder() {{ executor.execute(task); times = 1; executor1.execute(task); times = 1; }}; } @Test(expected=ExecutorServiceException.class) public void moveExecutorFromBalancerTest( @Mocked final Task task, @Mocked final Executor executor ) throws Exception { TestExecutor e1 = addExecutor("e1", executor, true); assertTrue(balancer.start()); try { balancer.execute(task); tree.move(e1, testsNode, null); balancer.execute(task); } finally { new VerificationsInOrder() {{ executor.execute(task); times = 1; }}; } } @Test public void migrateDelayedTasksFromStoppedExecutor( @Mocked final Task task, @Mocked final Executor executor1 ) throws Exception { //creating normal executor ExecutorServiceNode executor = new ExecutorServiceNode(); executor.setName("executor"); balancer.addAndSaveChildren(executor); executor.setCorePoolSize(16); executor.setType(ExecutorService.Type.FORK_JOIN_POOL); assertTrue(executor.start()); assertTrue(balancer.start()); addExecutor("executor1", executor1, true); balancer.execute(60000, task); new Verifications(){{ executor1.execute(anyLong, (Task)any); times=0; }}; executor.stop(); new Verifications(){{ long d; executor1.execute(d = withCapture(), task); assertTrue(d>59000); }}; } @Test public void performanceTest() throws InterruptedException { ExecutorServiceNode executor = new ExecutorServiceNode(); executor.setName("executor"); balancer.addAndSaveChildren(executor); executor.setCorePoolSize(16); executor.setType(ExecutorService.Type.FORK_JOIN_POOL); assertTrue(executor.start()); assertTrue(balancer.start()); for (int i=0; i<5; ++i) runTest(i); } private void runTest(int number) throws InterruptedException { System.out.println("\n\nRUNING TEST NUMBER: "+number); int messagesCount = 1000000; executedTasks = new CountDownLatch(messagesCount); long ts = System.nanoTime(); for (int i=0; i<messagesCount; ++i) while (!balancer.executeQuietly(new PerformanceTask2())) Thread.sleep(1); long submitTs = System.nanoTime(); executedTasks.await(20, TimeUnit.SECONDS); long executedCount = messagesCount-executedTasks.getCount(); long finishTs = System.nanoTime(); System.out.println("Executed tasks count: "+executedCount); System.out.println("Submit time ns: "+(submitTs-ts)); System.out.println("Submit time ms: "+TimeUnit.NANOSECONDS.toMillis(submitTs-ts)); System.out.println("Test time ns: "+(finishTs-ts)); System.out.println("Test time ms: "+TimeUnit.NANOSECONDS.toMillis(finishTs-ts)); double messagesPerMs = (double)executedCount/TimeUnit.NANOSECONDS.toMillis(finishTs-ts); System.out.println("Messages per ms: "+messagesPerMs); System.out.println(); } private TestExecutor addExecutor(String name, Executor stub, boolean start) { return addExecutor(balancer, name, stub, start); } private TestExecutor addExecutor(Node owner, String name, Executor stub, boolean start) { TestExecutor executor = new TestExecutor(); executor.setName(name); owner.addAndSaveChildren(executor); executor.setExecutor(stub); if (start) assertTrue(executor.start()); return executor; } private ExecutorServiceBalancerNode createBalancer() { balancer = new ExecutorServiceBalancerNode(); balancer.setName("executor balancer2"); testsNode.addAndSaveChildren(balancer); return balancer; } private class PerformanceTask2 extends AbstractExecutorTask { @Override public void doRun() throws Exception { executedTasks.countDown(); } @Override public Node getTaskNode() { return testsNode; } @Override public String getStatusMessage() { return "Testing performance"; } } }
#pragma once #include <string> #include <string_view> #include "base/strings.h" #include "url_parser.h" namespace dash { class URL { public: URL(std::string url) : url_(std::move(url)) { TrimPrefixAll(&url_, ' '); TrimSuffixAll(&url_, ' '); http_parser_url_init(&parser_url_); parsed_ok = http_parser_parse_url(url_.c_str(), url_.length(), 0, &parser_url_) == 0; } [[nodiscard]] inline bool IsParsedOK() const { return parsed_ok; } [[nodiscard]] inline bool IsAbsoluteUrl() const { return !Host().empty(); } [[nodiscard]] inline bool HasPath() const { return parser_url_.field_data[3].len != 0; } [[nodiscard]] inline bool HasQueries() const { return parser_url_.field_data[4].len != 0; } [[nodiscard]] inline std::string Schema() const { return url_.substr(parser_url_.field_data[0].off, parser_url_.field_data[0].len); } [[nodiscard]] inline std::string Host() const { return url_.substr(parser_url_.field_data[1].off, parser_url_.field_data[1].len); } [[nodiscard]] inline std::string Port() const { return url_.substr(parser_url_.field_data[2].off, parser_url_.field_data[2].len); } [[nodiscard]] inline std::string Path() const { return url_.substr(parser_url_.field_data[3].off, parser_url_.field_data[3].len); } [[nodiscard]] inline std::string Query() const { return url_.substr(parser_url_.field_data[4].off, parser_url_.field_data[4].len); } /** * @brief AppendPath will append the extra path @param path into current url. * @return the new url * @note path should not contains whitespace. * */ [[nodiscard]] std::string AppendPath(std::string_view path) { std::string ret; do { if (path.empty()) { ret = url_; break ; } auto url_view = TrimSuffixAll(url_, '/'); auto path_view = TrimPrefixAll(path, '/'); path_view = TrimSuffixAll(path_view, '/'); ret.reserve(url_.size() + path_view.size() + 3); ret.append(url_view.data(), url_view.size()); if (!path_view.empty()) { ret.append("/"); ret.append(path_view.data(), path_view.size()); } if (HasQueries()) { ret.append("?"); ret.append(Query()); } } while (false); return ret; } /** * @brief AppendQuery will return the new url with the added query * */ [[nodiscard]] std::string AppendQuery(std::string_view query) { std::string ret; do { if (query.empty()) { ret = url_; break; } if (HasQueries()) { if (*(url_.rbegin()) == '&') { ret = url_ + std::string(query.data(), query.length()); } else { ret = url_ + "&" + std::string(query.data(), query.length()); } } else { if (*(url_.rbegin()) == '?') { ret = url_ + std::string(query.data(), query.length()); } else { ret = url_ + "?" + std::string(query.data(), query.length()); } }; } while (false); return ret; } private: std::string url_; bool parsed_ok = false; http_parser_url parser_url_; }; } // namespace dash
import Link from 'next/link'; import { css, Interpolation, Theme } from '@emotion/react'; import { User } from '../util/database'; import { AnchorHTMLAttributes } from 'react'; const headerStyles = css` padding: 12px 12px; margin: 12px; border-radius: 8px; /* background-image: linear-gradient( to right top, #006e5f, #007372, #007884, #007c95, #007fa4 ); */ background-image: linear-gradient(to right top, #043159, #10528e, #2a689f); border: 2px solid black; color: white; h3 { margin: 4px; padding: 8px; font-size: 20px; max-height: 42px; border: 2px solid #dc8409; border-radius: 8px; } a { color: white; text-decoration: none; margin: 4px; font-size: 20px; padding: 8px; max-height: 42px; max-width: max-content; display: inline-block; position: relative; :after { content: ''; position: absolute; width: 100%; transform: scaleX(0); height: 2px; bottom: 0; left: 0; background-color: #dc8409; transform-origin: bottom right; transition: transform 0.3s ease-out; } :hover:after { transform: scaleX(1); transform-origin: bottom left; } } @media only screen and (max-width: 800px) { width: 324px; margin: 12px auto; } `; const flexContainerStyles = css` display: flex; flex-direction: column; h3 { font-weight: 400; } `; const flexRowHeaderStyles = css` display: flex; justify-content: space-between; `; type Props = { userObject?: User; }; function Anchor({ children, ...restProps }: AnchorHTMLAttributes<HTMLAnchorElement> & { css?: Interpolation<Theme>; }) { return <a {...restProps}>{children}</a>; } export default function Header(props: Props) { return ( <header css={headerStyles}> {props.userObject ? ( <div css={flexRowHeaderStyles}> <div css={flexContainerStyles}> <Link href="/users/overview"> <a>Overview</a> </Link> <Link href="/createevent"> <a>Create New Event</a> </Link> </div> <div css={flexContainerStyles}> <h3> Hi{' '} <span data-test-id="logged-in-user"> {props.userObject.username} </span> </h3> <Anchor data-test-id="logout" href="/logout"> Logout </Anchor> </div> </div> ) : ( <div css={flexRowHeaderStyles}> <Link href="/"> <a>Splitify</a> </Link> <Link href="/register"> <a data-test-id="sign-up">Register</a> </Link> <Link href="/login"> <a data-test-id="login">Login</a> </Link> </div> )} </header> ); }
<template> <div class="main"> <h1>Este es mi primer componente en vue 👻</h1> <div> <h3>{{mi_primer_variable}}</h3> <h4>{{otra_variable}}</h4> <h5>{{variableEstatica}}</h5> <p>Aqui estoy utilizando una variable computada para hacer que {{otra_variable}} se convierta en {{double}}</p> <p>Aqui estoy utilizando variables computadas anidadas para que a {{otra_variable}} sea {{plusOne}} y al final se convierta en {{triple}}</p> </div> </div> </template> <script> const variableEstatica = 'Esto es una variable estatica 🤫' export default { name: 'MiComponente', data: () => ({ mi_primer_variable: 'Esta es mi primer variable 😃', otra_variable: 20, variableEstatica }), computed: { double () { return this.otra_variable * 2 }, plusOne () { return this.otra_variable + 1 }, triple () { return this.plusOne * 3 } } } </script> <style scoped> h1 { color: rgb(50,150,150); } </style>
<?php /** * @file * Tests for the qforms extra module. */ class QformsExtrsTestCase extends DrupalWebTestCase { // Here we do not test custom format we test only ordinary date format // In selenium test custom format is tested const dateFormat = 'Y.d.m'; private function getQformExtraDefinition() { return 'a:6:{s:23:"qforms_element_1_number";a:8:{s:4:"type";s:6:"number";s:2:"id";s:23:"qforms_element_1_number";s:6:"weight";s:1:"1";s:7:"visible";i:1;s:5:"title";s:20:"Enter your number id";s:11:"description";s:39:"Enter your number id for identification";s:8:"required";i:0;s:4:"size";s:0:"";}' . 's:22:"qforms_element_2_email";a:8:{s:4:"type";s:5:"email";s:2:"id";s:22:"qforms_element_2_email";s:6:"weight";s:1:"2";s:7:"visible";i:1;s:5:"title";s:19:"Your e-mail address";s:11:"description";s:56:"Please enter your e-mail address that we can contact you";s:8:"required";i:0;s:4:"size";s:0:"";}' . 's:20:"qforms_element_3_url";a:8:{s:4:"type";s:3:"url";s:2:"id";s:20:"qforms_element_3_url";s:6:"weight";s:1:"3";s:7:"visible";i:1;s:5:"title";s:17:"Your site address";s:11:"description";s:38:"If you have site you can enter address";s:8:"required";i:0;s:4:"size";s:0:"";}' . 's:21:"qforms_element_4_date";a:9:{s:4:"type";s:4:"date";s:2:"id";s:21:"qforms_element_4_date";s:6:"weight";s:1:"4";s:7:"visible";i:1;s:5:"title";s:21:"Dead line for support";s:11:"description";s:29:"Date till we must support you";s:8:"required";i:0;s:4:"size";s:0:"";s:6:"format";s:5:"' . self::dateFormat . '";}' . 's:23:"qforms_element_5_markup";a:5:{s:4:"type";s:6:"markup";s:2:"id";s:23:"qforms_element_5_markup";s:6:"weight";s:1:"5";s:7:"visible";i:1;s:6:"markup";s:49:"Our operator will contact you as soon as possible";}' . 's:22:"qforms_last_element_id";i:5;}'; } public static function getInfo() { return array( 'name' => 'Qforms extra functionality', 'description' => 'Tests functionalities of qforms extra module.', 'group' => 'Qforms extra' ); } protected function setUp() { parent::setUp('qforms', 'qforms_extra'); $perm = array('create qform content', 'edit own qform content', 'delete own qform content', 'view and submit qform'); $this->authUser = $this->drupalCreateUser($perm); $this->drupalLogin($this->authUser); } public function testQformExtraContent() { $this->addContent(); $this->drupalGet('node/1'); $passed = $this->assertText(t('Enter your number id')); $passed = $passed && $this->assertField('qforms_element_1_number', t('Founded input number.')); $passed = $passed && $this->assertText(t('Enter your number id for identification')); $this->assert($passed, t('First field of a type number is OK')); $passed = $this->assertText(t('Your e-mail address')); $passed = $passed && $this->assertField('qforms_element_2_email', t('Founded input email.')); $passed = $passed && $this->assertText(t('Please enter your e-mail address that we can contact you')); $this->assert($passed, t('Second field of a type email is OK')); $passed = $this->assertText(t('Your site address')); $passed = $passed && $this->assertFieldByName('qforms_element_3_url', 'http://', t('Founded input site with default value "http://".')); $passed = $passed && $this->assertText(t('If you have site you can enter address')); $this->assert($passed, t('Third field of a type url is OK')); $passed = $this->assertText(t('Dead line for support')); $passed = $passed && $this->assertField('qforms_element_4_date', t('Founded input date.')); $passed = $passed && $this-> assertText(t('Date till we must support you')); $this->assert($passed, t('First field of a type number is OK')); $passed = $this->assertText(t('Our operator will contact you as soon as possible'), t('Fifth field of type markup is OK')); $this->addData(); // Test view of the node previously populated with data. $this->drupalGet('node/1/qforms-result/1'); $passed = $this->assertFieldByName('qforms_element_1_number', 111, 'Number\'s value OK.'); $passed = $this->assertFieldByName('qforms_element_2_email', 'someuser@somesite.domain', 'Email\'s value OK.') && $passed; $passed = $this->assertFieldByName('qforms_element_3_url', 'http://somesite.domain', 'Url\'s value OK.') && $passed; $passed = $this->assertFieldByName('qforms_element_4_date', '2008.02.11', 'Date\'s value OK.') && $passed; $passed = $this->assert($passed, 'View is OK.'); // Try to submit invalid data. $this->addData(2, '11a', 'someuser#somesite', 'somesite.somedomain', '11-02-2011'); $passed = $this->assertText('You need to enter a valid number.', 'Number validation OK.'); $passed = $this->assertText('You need to enter a valid email address.', 'Email validation OK.') && $passed; $passed = $this->assertText('You need to enter a valid url.', 'Url validation OK.') && $passed; $passed = $this->assertText('You need to enter a valid date.', 'Date validation OK.') && $passed; $this->assert($passed, 'Validation is OK.'); } public function testExport() { module_load_include('inc', 'qforms', 'qforms.pages_export'); $this->addContent(); // After data has been submited. $this->addData(); $node = $this->drupalGetNodeByTitle(t('Support questionare')); $exported_results = qforms_results_submissions_export_base($node); $file_content = $exported_results['file_content']; $passed = (substr_count($file_content, 'Our operator will contact you as soon as possible') > 0) ? FALSE : TRUE; $this->assert($passed, t("Markup hasn't been exported")); } /** * Add qform content/node. */ public function addContent($qform_extra_def = NULL, $node_id = NULL) { $edit['title'] = t('Support questionare'); if ($qform_extra_def == NULL) { $qform_extra_def = $this->getQformExtraDefinition(); } if ($node_id == NULL) { $node_id = 1; } $this->drupalPost('node/add/qform', $edit, t('Save')); $this->assertText(t('Qform @title has been created.', array('@title' => $edit['title']))); $this->drupalGet('node/' . $node_id); $this->drupalGet('node/' . $node_id . '/edit'); qforms_db_delete_form($node_id); qforms_db_save_form($node_id, $qform_extra_def, ''); $this->drupalGet('node/' . $node_id . '/edit'); } /** * Popoulate form with data. */ public function addData($node_id = 1, $number = 111, $email = 'someuser@somesite.domain', $url = 'http://somesite.domain', $date = '2008.02.11') { $this->drupalGet('node/' . $node_id); $datas['qforms_element_1_number'] = $number; $datas['qforms_element_2_email'] = $email; $datas['qforms_element_3_url'] = $url; $datas['qforms_element_4_date'] = $date; $this->drupalPost('node/1', $datas, t('Submit')); $this->assertText(t('Submission results')); } }
/** * Loads a Wavefront .obj file with materials * * @author mrdoob / http://mrdoob.com/ * @author angelxuanchang */ THREE.OBJMTLLoader = function () {}; THREE.OBJMTLLoader.prototype = { constructor: THREE.OBJMTLLoader, /** * Load a Wavefront OBJ file with materials (MTL file) * * Loading progress is indicated by the following events: * "load" event (successful loading): type = 'load', content = THREE.Object3D * "error" event (error loading): type = 'load', message * "progress" event (progress loading): type = 'progress', loaded, total * * If the MTL file cannot be loaded, then a MeshLambertMaterial is used as a default * @param url - Location of OBJ file to load * @param mtlfileurl - MTL file to load (optional, if not specified, attempts to use MTL specified in OBJ file) * @param options - Options on how to interpret the material (see THREE.MTLLoader.MaterialCreator ) */ load: function ( url, mtlfileurl, options ) { var scope = this; var xhr = new XMLHttpRequest(); var mtlDone; // Is the MTL done (true if no MTL, error loading MTL, or MTL actually loaded) var obj3d; // Loaded model (from obj file) var materialsCreator; // Material creator is created when MTL file is loaded // Loader for MTL var mtlLoader = new THREE.MTLLoader( url.substr( 0, url.lastIndexOf( "/" ) + 1 ), options ); mtlLoader.addEventListener( 'load', waitReady ); mtlLoader.addEventListener( 'error', waitReady ); // Try to load mtlfile if ( mtlfileurl ) { mtlLoader.load( mtlfileurl ); mtlDone = false; } else { mtlDone = true; } function waitReady( event ) { if ( event.type === 'load' ) { if ( event.content instanceof THREE.MTLLoader.MaterialCreator ) { // MTL file is loaded mtlDone = true; materialsCreator = event.content; materialsCreator.preload(); } else { // OBJ file is loaded if ( event.target.status === 200 || event.target.status === 0 ) { var objContent = event.target.responseText; if ( mtlfileurl ) { // Parse with passed in MTL file obj3d = scope.parse( objContent ); } else { // No passed in MTL file, look for mtlfile in obj file obj3d = scope.parse( objContent, function( mtlfile ) { mtlDone = false; mtlLoader.load( mtlLoader.baseUrl + mtlfile ); } ); } } else { // Error loading OBJ file.... scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']', response: event.target.responseText } ); } } } else if ( event.type === 'error' ) { // MTL failed to load -- oh well, we will just not have material ... mtlDone = true; } if ( mtlDone && obj3d ) { // MTL file is loaded and OBJ file is loaded // Apply materials to model var materials=[]; if ( materialsCreator ) { var materials=[]; obj3d.traverse( function( object ) { if ( object instanceof THREE.Mesh ) { var materialNames=object.materialNames; for(var materialNameIndex=0;materialNameIndex<materialNames.length;materialNameIndex++) { var materialName=materialNames[materialNameIndex]; var material=materials[materialName]; if(!material) { material=materialsCreator.create(materialName); materials[materialName]=material; } material.name=materialName; materials.push(material); } var meshMaterial=new THREE.MeshFaceMaterial(materials); object.material=meshMaterial; } } ); } // Notify listeners scope.dispatchEvent( { type: 'load', content: obj3d } ); } } xhr.addEventListener( 'load', waitReady, false ); xhr.addEventListener( 'progress', function ( event ) { scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } ); }, false ); xhr.addEventListener( 'error', function () { scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } ); }, false ); xhr.onload = function() { $('.wrap-loading').hide(); }; xhr.open( 'GET', url, true ); xhr.send( null ); }, /** * Parses loaded .obj file * @param data - content of .obj file * @param mtllibCallback - callback to handle mtllib declaration (optional) * @return {THREE.Object3D} - Object3D (with default material) */ parse: function ( data, mtllibCallback ) { // fixes data = data.replace( /\ \\\r\n/g, '' ); // rhino adds ' \\r\n' some times. var replacement = '/f$1$2$4\n/f$2$3$4'; // quads to tris data = data.replace( /f( +\d+)( +\d+)( +\d+)( +\d+)/g, replacement ); data = data.replace( /f( +\d+\/\d+)( +\d+\/\d+)( +\d+\/\d+)( +\d+\/\d+)/g, replacement ); data = data.replace( /f( +\d+\/\d+\/\d+)( +\d+\/\d+\/\d+)( +\d+\/\d+\/\d+)( +\d+\/\d+\/\d+)/g, replacement ); data = data.replace( /f( +\d+\/\/\d+)( +\d+\/\/\d+)( +\d+\/\/\d+)( +\d+\/\/\d+)/g, replacement ); // function vector( x, y, z ) { return new THREE.Vector3( x, y, z ); } function uv( u, v ) { return new THREE.Vector2( u, v ); } function face3( a, b, c, normals ) { return new THREE.Face3( a, b, c, normals ); } function meshN( meshName, materialName ) { if ( geometry.vertices.length > 0 ) { geometry.mergeVertices(); geometry.computeCentroids(); geometry.computeFaceNormals(); geometry.computeBoundingSphere(); object.add( mesh ); geometry = new THREE.Geometry(); mesh = new THREE.Mesh( geometry, material ); verticesCount = 0; } if ( meshName !== undefined ) mesh.name = meshName; if ( materialName !== undefined ) { material = new THREE.MeshLambertMaterial(); material.name = materialName; mesh.material = material; } } var materials=[]; /* this.addMaterial=function addMaterial(materialName) { if(!materials[materialName]) { console.log("Create material " + materialName); //materials[materialName]=materialsCreator.create(materialName); } } */ var group = new THREE.Object3D(); var object = group; function MeshObject() { this.vertices=[]; this.faces=[]; this.normals=[]; this.uvs=[]; this.vertexUvs=[]; this.materialNames=[]; this.currentMaterialIndex=null; this.name="undefined"; //this.materials=[]; //this.material=new THREE.MeshFaceMaterial(); this.setCurrentMaterialName=function setCurrentMaterialName(materialName) { var materialIndex=this.materialNames.indexOf(materialName); if(materialIndex==-1) { this.materialNames.push(materialName); //this.materials.push(materials[materialName]); } this.currentMaterialIndex=this.materialNames.indexOf(materialName); } this.addVertex=function addVertex(x,y,z) { this.vertices.push(new THREE.Vector3(x,y,z)); } this.addNormal=function addNormal(x,y,z) { this.normals.push(new THREE.Vector3(x,y,z)); } this.addUV=function addUV(u,v) { this.uvs.push(new THREE.Vector2(u,v)); } this.addVertexUV=function addVertexUV(vertexUV) { this.vertexUvs.push([this.uvs[vertexUV[0]],this.uvs[vertexUV[1]],this.uvs[vertexUV[2]]]); } this.addFace=function addFace(vertices,normals) { var face=new THREE.Face3(vertices[0],vertices[1],vertices[2],normals,null,this.currentMaterialIndex); this.faces.push(face); } this.buildMesh=function buildMesh() { var geometry = new THREE.Geometry(); var material = new THREE.MeshFaceMaterial(); var faces=[]; var vertexUvs=[]; //Optimisation console.log(this.materialNames); for(var materialIndex=0;materialIndex<this.materialNames.length;materialIndex++) { for(var faceIndex=0;faceIndex<this.faces.length;faceIndex++) { var face=this.faces[faceIndex]; if(face.materialIndex==materialIndex) { faces.push(face); vertexUvs.push(this.vertexUvs[faceIndex]); } } } geometry.vertices=this.vertices; geometry.faces=faces; geometry.faceVertexUvs[0]=vertexUvs; geometry.mergeVertices(); geometry.computeCentroids(); geometry.computeFaceNormals(); geometry.computeBoundingSphere(); console.log("build Mesh"); var mesh = new THREE.Mesh(geometry,material); mesh.materialNames=this.materialNames; mesh.name=this.name; return mesh; } } var meshObject=new MeshObject(); var lastPattern=null; /* var geometry = new THREE.Geometry(); var material = new THREE.MeshLambertMaterial(); var mesh = new THREE.Mesh( geometry, material ); var vertices = []; var verticesCount = 0; var normals = []; var uvs = []; */ // v float float float var vertex_pattern = /v( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // vn float float float var normal_pattern = /vn( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // vt float float var uv_pattern = /vt( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/ // f vertex vertex vertex var face_pattern1 = /f( +\d+)( +\d+)( +\d+)/ // f vertex/uv vertex/uv vertex/uv var face_pattern2 = /f( +(\d+)\/(\d+))( +(\d+)\/(\d+))( +(\d+)\/(\d+))/; // f vertex/uv/normal vertex/uv/normal vertex/uv/normal var face_pattern3 = /f( +(\d+)\/(\d+)\/(\d+))( +(\d+)\/(\d+)\/(\d+))( +(\d+)\/(\d+)\/(\d+))/; // f vertex//normal vertex//normal vertex//normal var face_pattern4 = /f( +(\d+)\/\/(\d+))( +(\d+)\/\/(\d+))( +(\d+)\/\/(\d+))/; var lines = data.split( "\n" ); for ( var i = 0; i < lines.length; i ++ ) { var line = lines[i]; line = line.trim(); var result; if ( line.length === 0 || line.charAt( 0 ) === '#' ) continue; // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"] if ( ( result = vertex_pattern.exec( line ) ) !== null ) { /* if(lastPattern!="v") { if(meshObject) group.add(meshObject.buildMesh()); meshObject=new MeshObject(); } */ meshObject.addVertex(parseFloat(result[1]),parseFloat(result[2]),parseFloat(result[3])); lastPattern="v"; /* meshObject.vertices.push ( vector ( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) ) ); */ continue; } // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"] if ( ( result = normal_pattern.exec( line ) ) !== null ) { meshObject.addNormal(parseFloat(result[1]),parseFloat(result[2]),parseFloat(result[3])); lastPattern="vn"; /* meshObject.normals.push ( vector ( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) ) ); */ continue; } // ["vt 0.1 0.2", "0.1", "0.2"] if ( ( result = uv_pattern.exec( line ) ) !== null ) { meshObject.addUV(parseFloat(result[1]),parseFloat(result[2])); lastPattern="vt"; /* meshObject.uvs.push ( uv ( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ) ) ); */ continue; } // ["f 1 2 3", "1", "2", "3"] if ( ( result = face_pattern1.exec( line ) ) !== null ) { /* geometry.vertices.push ( vertices[ parseInt( result[ 1 ] ) - 1 ], vertices[ parseInt( result[ 2 ] ) - 1 ], vertices[ parseInt( result[ 3 ] ) - 1 ] ); geometry.faces.push(face3(verticesCount++,verticesCount++,verticesCount++)); */ var faceVertices=[parseInt(result[1])-1,parseInt(result[2])-1,parseInt(result[3])-1]; var faceVertexUV=[0,0,0]; meshObject.addFace(faceVertices,null); meshObject.addVertexUV(faceVertexUV); lastPattern="f"; continue; } // ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3"] if ( ( result = face_pattern2.exec( line ) ) !== null ) { /* geometry.vertices.push ( vertices[ parseInt( result[ 2 ] ) - 1 ], vertices[ parseInt( result[ 5 ] ) - 1 ], vertices[ parseInt( result[ 8 ] ) - 1 ] ); geometry.faces.push( face3(verticesCount++,verticesCount ++,verticesCount++)); geometry.faceVertexUvs[ 0 ].push ( [ uvs[ parseInt( result[ 3 ] ) - 1 ], uvs[ parseInt( result[ 6 ] ) - 1 ], uvs[ parseInt( result[ 9 ] ) - 1 ] ] ); */ var faceVertices=[parseInt(result[2])-1,parseInt(result[5])-1,parseInt(result[8])-1]; var faceVertexUV=[parseInt(result[3])-1,parseInt(result[6])-1,parseInt(result[9])-1]; meshObject.addFace(faceVertices,null); meshObject.addVertexUV(faceVertexUV); lastPattern="f"; continue; } // ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3"] if ( ( result = face_pattern3.exec( line ) ) !== null ) { /* geometry.vertices.push ( vertices[ parseInt( result[ 2 ] ) - 1 ], vertices[ parseInt( result[ 6 ] ) - 1 ], vertices[ parseInt( result[ 10 ] ) - 1 ] ); */ /* geometry.faces.push ( face3 ( verticesCount++, verticesCount++, verticesCount++, [ normals[ parseInt( result[ 4 ] ) - 1 ], normals[ parseInt( result[ 8 ] ) - 1 ], normals[ parseInt( result[ 12 ] ) - 1 ] ] ) ); geometry.faceVertexUvs[ 0 ].push ( [ uvs[ parseInt( result[ 3 ] ) - 1 ], uvs[ parseInt( result[ 7 ] ) - 1 ], uvs[ parseInt( result[ 11 ] ) - 1 ] ] ); */ var faceVertices=[parseInt(result[2])-1,parseInt(result[6])-1,parseInt(result[10])-1]; var faceNormals=[meshObject.normals[parseInt(result[4])-1],meshObject.normals[parseInt(result[8])-1],meshObject.normals[parseInt(result[12])-1]]; var faceVertexUV=[parseInt(result[3])-1,parseInt(result[7])-1,parseInt(result[11])-1]; meshObject.addFace(faceVertices,faceNormals); meshObject.addVertexUV(faceVertexUV); lastPattern="f"; //meshObject.addUV() continue; } // ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3"] if ( ( result = face_pattern4.exec( line ) ) !== null ) { /* geometry.vertices.push ( vertices[ parseInt( result[ 2 ] ) - 1 ], vertices[ parseInt( result[ 5 ] ) - 1 ], vertices[ parseInt( result[ 8 ] ) - 1 ] ); geometry.faces.push ( face3 ( verticesCount ++, verticesCount ++, verticesCount ++, [ normals[ parseInt( result[ 3 ] ) - 1 ], normals[ parseInt( result[ 6 ] ) - 1 ], normals[ parseInt( result[ 9 ] ) - 1 ] ] ) ); continue; */ var faceVertices=[parseInt(result[2])-1,parseInt(result[5])-1,parseInt(result[8])-1]; var faceNormals=[meshObject.normals[parseInt(result[3])-1],meshObject.normals[parseInt(result[6])-1],meshObject.normals[parseInt(result[9])-1]]; var faceVertexUV=[0,0,0]; meshObject.addFace(faceVertices,faceNormals); meshObject.addVertexUV(faceVertexUV); lastPattern="f"; continue; } // object if ( /^o /.test( line ) ) { /* object = new THREE.Object3D(); object.name = line.substring( 2 ).trim(); group.add( object ); */ lastPattern="o"; continue; } // group if ( /^g /.test( line ) ) { //meshN( line.substring( 2 ).trim(), undefined ); var groupName=line.substring( 2 ).trim(); meshObject.name=groupName; /*var newMeshObject=new MeshObject(); newMeshObject.name=groupName; newMeshObject.vertices=meshObject.vertices; newMeshObject.normals=meshObject.normals; newMeshObject.uvs=meshObject.uvs; newMeshObject.vertices=meshObject.meshObject;*/ /* this.vertices=[]; this.faces=[]; this.normals=[]; this.uvs=[]; this.vertexUvs=[]; this.materialNames=[]; this.currentMaterialIndex=null; this.name="undefined"; */ /* group.add(meshObject.buildMesh()); group.name=groupName; meshObject=new MeshObject(); meshObject.name=groupName; */ lastPattern="g"; continue; } // material if ( /^usemtl /.test( line ) ) { //meshN( undefined, line.substring( 7 ).trim() ); var materialName=line.substring( 7 ).trim(); //this.addMaterial(materialName); meshObject.setCurrentMaterialName(materialName); lastPattern="usemtl"; continue; } // mtl file if ( /^mtllib /.test( line ) ) { if ( mtllibCallback ) { var mtlfile = line.substring( 7 ); mtlfile = mtlfile.trim(); mtllibCallback( mtlfile ); } lastPattern="mtllib"; continue; } // Smooth shading if ( /^s /.test( line ) ) { lastPattern="s"; continue; } console.log( "THREE.OBJMTLLoader: Unhandled line " + line ); } //Add last object //meshN(undefined, undefined); //Create mesh //var outputMesh=meshObject.buildMesh(); //console.log(outputMesh); //console.log("Loading finished"); //if(meshObject.vertices.length>0) group.add(meshObject.buildMesh()); console.log(group);; return group; } }; THREE.EventDispatcher.prototype.apply( THREE.OBJMTLLoader.prototype );
import { useContext, useEffect } from 'react'; import OskariRPC from 'oskari-rpc'; import { ReactReduxContext } from 'react-redux'; import styled from 'styled-components'; import { useAppSelector } from '../../state/hooks'; import strings from '../../translations'; import { setActiveAnnouncements, setAllGroups, setAllTags, setAllThemesWithLayers, setChannel, setCurrentMapCenter, setCurrentState, setCurrentZoomLevel, setFeatures, setLegends, setLoading, setScaleBarState, setTagsWithLayers, setZoomRange, setGFILocations, setGFICroppingArea, setVKMData, setStartState, resetGFILocations, addMarkerRequest, removeMarkerRequest, setPointInfo } from '../../state/slices/rpcSlice'; import { setIsFullScreen, setGfiCroppingTypes, setIsGfiOpen, setMinimizeGfi, addToDrawToolMarkers, removeFromDrawToolMarkers, addToGeoJsonArray, } from '../../state/slices/uiSlice'; import { getActiveAnnouncements, updateLayers } from '../../utils/rpcUtil'; import SvLoder from '../../components/loader/SvLoader'; import './PublishedMap.scss'; import { theme } from '../../theme/theme'; const StyledPublishedMap = styled.div` position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; `; const StyledIframe = styled.iframe` width: 100%; height: 100%; border: none; `; const StyledLoaderWrapper = styled.div` position: absolute; top: 50%; left: 50%; z-index: 999; height: 100%; max-width: 200px; max-height: 200px; transform: translate(-50%, -50%); svg { width: 100%; height: 100%; fill: none; } `; const PublishedMap = () => { const { store } = useContext(ReactReduxContext); const { loading } = useAppSelector((state) => state.rpc); const language = useAppSelector((state) => state.language); const lang = language.current; const hideSpinner = () => { store.dispatch(setLoading(false)); }; useEffect(() => { const handleFullScreenChange = () => { if (document.webkitIsFullScreen) { store.dispatch(setIsFullScreen(true)); } else if (document.fullscreenElement) { store.dispatch(setIsFullScreen(true)); } else { store.dispatch(setIsFullScreen(false)); } }; store.dispatch(setLoading(true)); document.addEventListener('fullscreenchange', handleFullScreenChange); document.addEventListener( 'mozfullscreenchange', handleFullScreenChange ); document.addEventListener( 'webkitfullscreenchange', handleFullScreenChange ); document.addEventListener('msfullscreenchange', handleFullScreenChange); const iframe = document.getElementById('sv-iframe'); var handlers = []; var channel = OskariRPC.connect( iframe, process.env.REACT_APP_PUBLISHED_MAP_DOMAIN ); var synchronizer = OskariRPC.synchronizerFactory(channel, handlers); channel.onReady(() => { store.dispatch(setChannel(channel)); channel.getSupportedFunctions(function (data) { if (data.getSelectedAnnouncements) { channel.getSelectedAnnouncements(function (data) { store.dispatch( setActiveAnnouncements(getActiveAnnouncements(data)) ); }); } if (data.getTags) { channel.getTags(function (data) { store.dispatch(setAllTags(data)); }); } if (data.getTagsWithLayers) { channel.getTagsWithLayers(function (data) { store.dispatch(setTagsWithLayers(data)); }); } if (data.getGfiCroppingTypes) { channel.getGfiCroppingTypes(function (data) { store.dispatch(setGfiCroppingTypes(data)); }); } if (data.getThemesWithLayers) { channel.getThemesWithLayers(function (data) { store.dispatch(setAllThemesWithLayers(data)); }); } if (data.getZoomRange) { channel.getZoomRange(function (data) { store.dispatch(setZoomRange(data)); data.hasOwnProperty('current') && store.dispatch(setCurrentZoomLevel(data.current)); }); } if (data.getAllGroups) { channel.getAllGroups(function (data) { const arrangeAlphabetically = (x, y) => { if (x.name < y.name) { return -1; } if (x.name > y.name) { return 1; } return 0; }; store.dispatch( setAllGroups(data.sort(arrangeAlphabetically)) ); }); } updateLayers(store, channel); if (data.getCurrentState) { channel.getCurrentState(function (data) { store.dispatch(setCurrentState(data)); }); } if (data.getFeatures) { channel.getFeatures(function (data) { store.dispatch(setFeatures(data)); }); } if (data.getLegends) { // need use global window variable to limit legend updates window.legendUpdateTimer = setTimeout(function () { channel.getLegends(function (data) { store.dispatch(setLegends(data)); }); }, 500); } if (data.getMapPosition) { channel.getMapPosition((data) => { store.dispatch(setCurrentMapCenter(data)); }); } }); channel.getSupportedEvents(function (data) { if (data.MapClickedEvent && store.getState().ui.activeTool === null) { channel.handleEvent('MapClickedEvent', (data) => { store.getState().ui.activeTool !== strings.tooltips.drawingTools.marker && store.dispatch(resetGFILocations([])); store.dispatch(setPointInfo(data)); }); } channel.handleEvent('DrawingEvent', (data) => { if (store.getState().ui.activeTool) { if (data.isFinished && data.isFinished === true && data.geojson.features.length > 0) { store.getState().ui.activeTool !== strings.tooltips.drawingTools.marker && store.dispatch(addToGeoJsonArray(data)); } } }); channel.handleEvent('PointInfoEvent', (data) => { if (data.vkm !== null && store.getState().ui.activeSelectionTool === null && store.getState().ui.activeTool === null && store.getState().ui.selectedMarker !== 7) { store.dispatch(setMinimizeGfi(false)); store.dispatch(setVKMData(data)); store.dispatch(setIsGfiOpen(true)); var MARKER_ID = 'VKM_MARKER'; store.dispatch( addMarkerRequest({ x: data.coordinates.x, y: data.coordinates.y, markerId: MARKER_ID, shape: '<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" fill="#0064af" viewBox="0 0 384 512"><path d="M172.268 501.67C26.97 291.031 0 269.413 0 192 0 85.961 85.961 0 192 0s192 85.961 192 192c0 77.413-26.97 99.031-172.268 309.67-9.535 13.774-29.93 13.773-39.464 0zM192 272c44.183 0 80-35.817 80-80s-35.817-80-80-80-80 35.817-80 80 35.817 80 80 80z"/></svg>', size: 5, offsetX: 13, offsetY: 7, }) ); } if (store.getState().ui.activeTool === strings.tooltips.drawingTools.marker) { let marker_id = data.coordinates.x + data.coordinates.y + "_id"; const customMarker = { x: data.coordinates.x, y: data.coordinates.y, markerId: marker_id, shape: store.getState().ui.selectedMarker, msg: store.getState().ui.markerLabel, color: theme.colors.mainColor2, size: 5, offsetX: 0, offsetY: 7, } if (store.getState().ui.selectedMarker !== 7) { store.dispatch(addToDrawToolMarkers(customMarker)); store.getState().ui.selectedMarker !== 7 && store.dispatch( addMarkerRequest(customMarker) ); } } }) channel.handleEvent('DataForMapLocationEvent', (data) => { if (data.content && data.content.features) { data.content.features.forEach(f => { if (f.properties) { Object.keys(f.properties).forEach(k => { if (typeof f.properties[k] === 'object') { f.properties[k] = JSON.stringify(f.properties[k]); } }); } }); } // reformat data to same way croppings are // might need to be 'fixed' later const features = data.content; let geojson = {"geojson": features} let reformattedData = {}; reformattedData.content = [geojson]; data.content = reformattedData.content; if (store.getState().ui.activeSelectionTool === null && store.getState().ui.activeTool === null) { store.dispatch(resetGFILocations([])); const croppingArea = { type: 'Feature', geometry: { type: 'Point', coordinates: [data.x, data.y], }, }; store.dispatch(setGFICroppingArea(croppingArea)); store.dispatch(setMinimizeGfi(false)); store.dispatch(setIsGfiOpen(true)); store.dispatch(setGFILocations(data)); } }); if (data.MarkerClickEvent) { channel.handleEvent('MarkerClickEvent', (event) => { if(store.getState().ui.selectedMarker === 7 && store.getState().ui.drawToolMarkers.length > 0) { store.dispatch(removeMarkerRequest({markerId: event.id})); store.dispatch(removeFromDrawToolMarkers(event.id)); } }); } if (data.AfterMapMoveEvent) { channel.handleEvent('AfterMapMoveEvent', (event) => { store.dispatch(setCurrentMapCenter(event)); }); } if (data.SearchResultEvent) { channel.handleEvent('SearchResultEvent', (event) => {}); } if (data.ScaleBarEvent) { channel.handleEvent('ScaleBarEvent', function (data) { store.dispatch(setScaleBarState(data)); }); } if (data.UserLocationEvent) { channel.postRequest( 'MapModulePlugin.RemoveMarkersRequest', ['my_location'] ); channel.handleEvent('UserLocationEvent', (event) => { var data = { x: event.lon, y: event.lat, msg: '', shape: '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#0064af"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zM7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 2.88-2.88 7.19-5 9.88C9.92 16.21 7 11.85 7 9z"/><circle cx="12" cy="9" r="2.5"/></svg>', offsetX: 0, // center point x position from left to right offsetY: 10, // center point y position from bottom to up size: 100 }; channel.postRequest( 'MapModulePlugin.AddMarkerRequest', [data, 'my_location'] ); var routeSteps = [ { lon: event.lon, lat: event.lat, duration: 3000, zoom: 4, animation: 'zoomPan', }, { lon: event.lon, lat: event.lat, duration: 3000, zoom: 10, animation: 'zoomPan', }, ]; var stepDefaults = { zoom: 5, animation: 'fly', duration: 3000, srsName: 'EPSG:3067', }; channel.postRequest('MapTourRequest', [ routeSteps, stepDefaults, ]); }); } }); // save start state channel.getPublishedMapState(function (data) { store.dispatch(setStartState(data)); }); }); synchronizer.synchronize(); return () => { synchronizer.destroy(); }; }, [store]); return ( <StyledPublishedMap> {loading && ( <StyledLoaderWrapper> <SvLoder /> </StyledLoaderWrapper> )} <StyledIframe id="sv-iframe" title="iframe" src={process.env.REACT_APP_PUBLISHED_MAP_URL + '&lang=' + lang} allow="geolocation" onLoad={() => hideSpinner()} ></StyledIframe> </StyledPublishedMap> ); }; export default PublishedMap;
<?php declare(strict_types=1); namespace OrderService\Console\Commands; use Illuminate\Console\Command; use OrderService\UseCases\MarkOrderAsShipped as UseCase; use OrderService\ValueObjects\Exception\InvalidID; use OrderService\ValueObjects\ID; class MarkOrderAsShipped extends Command { /** * @var string */ protected $signature = 'order:shipped {id}'; /** * @var string */ protected $description = 'Mark an order as shipped'; /** * @var UseCase */ private $useCase; public function __construct(UseCase $useCase) { parent::__construct(); $this->useCase = $useCase; } public function handle(): void { /** @var string $argumentID */ $argumentID = $this->argument('id'); try { $id = ID::fromUUID($argumentID); } catch (InvalidID $e) { $this->output->error($e->getMessage()); return; } try { ($this->useCase)($id); } catch (\Throwable $e) { $this->output->error($e->getMessage()); return; } $this->output->success('Order has been marked as shipped'); } }
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_absolute_error, mean_squared_error import torch import torch.nn as nn # Define the LSTM model class MultiVariableLSTM(nn.Module): def __init__(self, input_size, hidden_size, num_layers, output_size): super(MultiVariableLSTM, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True) self.fc = nn.Linear(hidden_size, output_size) def forward(self, x): h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) out, _ = self.lstm(x, (h0, c0)) out = self.fc(out[:, -1, :]) return out # Function to calculate MAPE def mean_absolute_percentage_error(y_true, y_pred): return np.mean(np.abs((y_true - y_pred) / y_true)) * 100 # Load the data data = pd.read_excel("climatechangedata(1).xlsx") data['Year'] = pd.to_datetime(data['Year'], format='%Y') data = data.set_index('Year') # Selecting the variables for analysis variables = [ 'Carbon Dioxide (Million metric tons of CO2 equivalent)', 'Methane (Million metric tons of CO2 equivalent)', 'Nitrous Oxide (Million metric tons of CO2 equivalent)', 'Fluorinated Gases (Million metric tons of CO2 equivalent)', 'Total GHG (Million metric tons of CO2 equivalent)', 'Temperature (Celcius)', 'Forest Area (%)' ] device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Model Parameters input_size = len(variables) # Number of input features (7 columns) hidden_size = 128 num_layers = 2 output_size = 1 num_epochs = 100 learning_rate = 0.001 # Prepare data for LSTM scaler = MinMaxScaler(feature_range=(-1, 1)) scaled_data = scaler.fit_transform(data[variables]) scaled_data_tensor = torch.FloatTensor(scaled_data).unsqueeze(0).to(device) # Initialize LSTM model lstm_model = MultiVariableLSTM(input_size, hidden_size, num_layers, output_size).to(device) criterion = nn.MSELoss() optimizer = torch.optim.Adam(lstm_model.parameters(), lr=learning_rate) # Train the LSTM model for epoch in range(num_epochs): lstm_model.train() optimizer.zero_grad() outputs = lstm_model(scaled_data_tensor[:, :-1, :]) loss = criterion(outputs, scaled_data_tensor[:, 1:, 0]) # Predict next time step loss.backward() optimizer.step() if (epoch + 1) % 10 == 0: print(f'Epoch [{epoch + 1}/{num_epochs}], Loss: {loss.item():.4f}') # Forecast using the trained LSTM model with torch.no_grad(): lstm_model.eval() forecast = lstm_model(scaled_data_tensor[:, :-1, :]) print(forecast) forecast = forecast.cpu().numpy() #forecast = scaler.inverse_transform(forecast.reshape(-1, len(variables))) # Calculate metrics test_data = data[(data.index.year >= 2016) & (data.index.year <= 2023)][variables].values mae = mean_absolute_error(test_data, forecast) mape = mean_absolute_percentage_error(test_data, forecast) print(f"LSTM - MAE: {mae:.4f}, MAPE: {mape:.4f}%")
import { Injectable, inject } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http'; import { Observable, catchError, switchMap, throwError } from 'rxjs'; import { AuthService } from '../services/auth.service'; /** Auth interceptor. Intercepts request and adds JWT token to headers. */ @Injectable() export class RefreshTokenInterceptor<T> implements HttpInterceptor { private readonly authService = inject(AuthService); /** @inheritdoc */ public intercept(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> { return next.handle(req).pipe( catchError((error: unknown) => { if (error instanceof HttpErrorResponse && (error.status === 401 || error.message.includes('401'))) { return this.handleTokenError(req, next); } return throwError(() => error); }), ); } /** * Refresh token or logout, if refresh doesn't work. * @param request Request. * @param next Next handler. */ private handleTokenError(request: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> { return this.authService.isLoggedIn$ .pipe( switchMap(isLoggedIn => { if (isLoggedIn) { return this.authService.refreshToken().pipe( switchMap(() => next.handle(request)), catchError((error: unknown) => { if (error instanceof HttpErrorResponse && (error.status === 403 || error.message.includes('403'))) { this.authService.logout(); } return throwError(() => error); }), ); } return next.handle(request); }), ); } }
// // Created by gruzi on 15/03/2023. // #ifndef PROJECT_SOFTWARE_PRACTICUM2_METRONETVALIDATOR_H #define PROJECT_SOFTWARE_PRACTICUM2_METRONETVALIDATOR_H #include "MetroObject/IMetroObjectValidator.h" #include "Exceptions/MetronetInconsistentException.h" #include "Metronet.h" /** * @brief This serves as the Metronet validator, it checks for any inconsistencies but also errors in the Metronet class * @author Patryk Pilichowski * @author Daria Matviichuk * @date 15/03/2023 * @version 0.1 */ class MetronetValidator : IMetroObjectValidator { private: MetronetValidator* _initCheck; protected: /** * @brief a Metronet instance that we want to validate whenever we want to * */ const Metronet* const fMetronet; /** * @brief Gets metronet */ const Metronet* getMetronet() const; /** * @brief Checks if there are trams with the same line number and vehicle number * @pre: MetronetValidator is properly initialised * @return a boolean denoting if there are any duplicate trams in the metronet * */ bool noDuplicateTrams() const; /** * @brief Checks if all stations have a predecessor and a successor * @pre: MetronetValidator is properly initialised * @return a boolean denoting if the stations are properly linked * */ bool stationsLinked() const; /** * @brief Checks if for all trams there exists a station if the same track number as their line number * @pre: MetronetValidator is properly initialised * @return a boolean denoting if all trams have their track * */ bool tramsHaveSpoor() const; /** * @brief Checks if for all tracks there exists a tram with the same line number as their track number * @pre: MetronetValidator is properly initialised * @return a boolean denoting if all tracks have their tram * */ bool sporenHaveTrams() const; /** * @brief Checks if all trams have a start station that exists in the metronet but also if the station itself is * supported by the type of that tram. * @pre: MetronetValidator is properly initialised * @return a boolean denoting if all trams have a valid start station * */ bool tramsHaveValidBeginStation() const; /** * @brief For all trams calls the function validate() of a TramValidator instance * @pre: MetronetValidator is properly initialised * @return A boolean denoting if all trams are valid * */ bool validateTrams() const; /** * @brief For all stations calls the function validate() of a StationValidator instance * @pre: MetronetValidator is properly initialised * @return A boolean denoting if all stations are valid */ bool validateStations() const; public: bool properlyInitialized() const; /** * @brief Constructor of the MetronetValidator instance * @pre: MetronetValidator is properly initialised * @param metronet The instance of Metronet that we want to validate * */ MetronetValidator(const Metronet* const &metronet); /** * @brief Returns a string of the message in case validation failed * @pre: MetronetValidator is properly initialised * @param error A custom message telling what exactly went wrong * @return A string denoting failure of validation of a Metronet instance * */ std::string getInvalidationMessage(const std::string &error) const; /** * @brief Validates an instance of Metronet * @pre: MetronetValidator is properly initialised * @return A boolean denoting if the Metronet instance is valid or not * */ bool validate() const; }; #endif //PROJECT_SOFTWARE_PRACTICUM2_METRONETVALIDATOR_H
import { JoinedResult } from '../../models/result' import { ResultsAction, FETCH_RESULTS_FULFILLED, FETCH_RESULTS_PENDING, FETCH_RESULTS_REJECTED, } from '../actions/results' interface ResultsState { data: JoinedResult[] | undefined error: string | undefined loading: boolean } const initialState: ResultsState = { data: undefined, error: undefined, loading: false, } const resultsReducer = ( state = initialState, action: ResultsAction ): ResultsState => { const { type, payload } = action switch (type) { case FETCH_RESULTS_PENDING: return { data: undefined, error: undefined, loading: true, } case FETCH_RESULTS_FULFILLED: return { data: payload, error: undefined, loading: false, } case FETCH_RESULTS_REJECTED: return { data: undefined, error: payload, loading: false, } default: return state } } export default resultsReducer
TF(1) TF(1) NAME tf - TinyFugue, a MUD client SYNOPSIS tf [-ffile] [-lnq] [world] tf [-ffile] host port DESCRIPTION TinyFugue (also known as "Fugue" or "TF") is a line-based client designed for connecting to MUD servers (note: LP, DIKU, and other servers which use prompts require "/lp on"; see /help prompts). Most of the TF documentation is in the help file, which may be read online with the "/help" command. This manual page may be obsolete in certain areas; however, the helpfile will always be up to date. TinyFugue is larger than most MUD clients, but has many more features and is much more flexible. The goal is to provide the most functional- ity in a client that still maintains the user-friendliness of Tinytalk. Clients with extension languages such as Tcltt or VaporTalk can do a little more in certain areas, but are considerably harder to use and learn. TF provides most of these abilities in such a manner that learning to use any one function is relatively easy. Because I am continually adding new features and changing the code, TF sometimes becomes less stable in a new release. Versions labled "alpha" are generally not as well tested as "beta" versions, so they have the potential for more bugs. For this reason, I leave some older versions at the site where I distribute TF, which do not have all the current features but may have fewer bugs than the most recent release. COMMAND LINE ARGUMENTS With no arguments, TF will try to connect to the first world defined in the configuration file(s). With a world argument, TF will try to connect to world, as defined in the configuration file. If world is omitted, it will try to connect to the first world defined in your configuration files. With host and port arguments, TF will define a temporary world and try to connect to it. The host may be an IP number or regular name format. OPTIONS -ffile Load file instead of $HOME/.tfrc at startup. -f Do not load any personal configuration file. The library will still be loaded. -l Disable automatic login. -n Do not connect to any world at startup. -q Quiet login (overrides %{quiet} flag). FEATURES Among other things, TF allows you to: Divide the screen into two parts, for input and output, with flexible handling of input (/visual mode). Connect to multiple worlds and switch between them. Wrap MUD output at the edge of the screen. Edit text in the input buffer. Recall previous commands. Modify key sequences used to perform editing functions. Bind commands to key sequences. Define complex macros to perform MUD tasks easily. Create triggers which automatically perform certain tasks when certain output is received from the MUD. Modify existing macros using either a command format or interactive editing. Support "portals" that automatically switch from world to world. Hilite or color all or part of a line that matches a certain pattern. Gag lines that match certain patterns. Suppress frequently repeated text ("spamming"). Automatically log into a character on a world. Send a text file to the MUD in flexible ways, or echo it locally. Send the output of a system command to the MUD, or echo it locally. Send text previously received from the MUD to the MUD, or echo it locally. Repeat a MUD or TF command a number of times. Do the above four things at varying intervals, or at a rapid-fire rate. Log a session to a file. Separate LP and Diku style prompts from normal output. Page output using a --More-- prompt. Recall previously received text. CONFIGURATION FILES TF will attempt to read two files when starting. The first is a public configuration file "stdlib.tf", located in TFLIBDIR. TFLIBDIR is defined when TF is installed, and is often /usr/local/lib/tf.lib, or under the home directory of the installer. This library contains many macros and definitions essential to the correct operation of TF. Next, TF will attempt to read your personal configuration file, $HOME/.tfrc, in which you can put any TF commands you want executed automatically at startup. Two of the most useful commands to use in a TF configuration file are /addworld and /load. For backward compatability, TF will also try to read the TinyTalk con- figuration file. Its name defautls to $HOME/.tinytalk, or can be defined by the TINYTALK environment variable. This file may start with a list of worlds that will be defined as if with /addworld. HISTORY Anton Rang (Tarrant) in February of 1990 released Tinytalk, the first Tinyclient with any great number of features, including hiliting and suppression of text, simple triggers, and separating input and output on the screen. Leo Plotkin (Grod) made rather extensive modifications to Tinytalk to produce Tinywar, which was plagued with some serious bugs and was never officially released (the phrase "Tinywar doesn't exist" is often quoted), and is now an unsupported client. TF began when Greg Hudson (Explorer_Bob) merged many of the new features of Tinywar back into TinyTalk, and added many new features of his own, most notably the split screen. Some of the code in Greg's releases was contributed by Leo Plotkin. After Greg moved on to VaporTalk, Ken Keys (Hawkeye) took over design and maintenance of TF in July 1991, and con- tinues to make improvements in features and performance. The code size of TF has surpassed 300K (unstripped), and is signifi- gantly larger than Tinytalk. It is, in fact, more than three times the size of a number of existing servers. As of version 3.0, it has 66 builtin commands and 57 library commands, each documented in the help- file. It has been stated that TF is the most-used client in MUDdom at the current time. I haven't taken a poll, but I wouldn't be surprised. REVIEWS TF has significantly changed the tinyclient world. It has a number of merits and a number of flaws, and has frequently been criticized (mostly out of boredom; nobody takes this business too seriously) as having too many features and being too damn big. "Tinywar doesn't exist; TinyFugue merely shouldn't." -- Coined by Woodlock, I believe. "TinyFugue is a work of art." -- Binder, obviously after having too much to drink. "TinyFugue is the biggest hack since the platform it was built on." -- Explorer_Bob, in one of his lucid moments. The New York Times, the Christian Science Monitor and the Washington Post all refused to comment. COPYRIGHT Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2002, 2006-2007 Ken Keys TinyFugue (aka "tf") is protected under the terms of the GNU General Public License. See the file "COPYING" for details. TF is currently supported by Ken Keys, who may be contacted by e-mail at kenkeys@users.sourceforge.net or kkeys@ucsd.edu. BACKWARD INCOMPATIBILTIES VERSION 3.2 /rand has been replaced with rand(). Color names can no longer be user defined (but color codes still can). The "=" operator does comparison, not assignment. VERSION 3.1 Added type argument to WORLD and LOGIN hooks. VERSION 3.0 Backslashes in macros are interpreted slightly differently than in pre- vious versions. Turning on the "backslash" flag will enable the old behavior. VERSION 2.1 The CONNECT hook is now called before the LOGIN hook. In 2.0, CONNECT was called after autologin. VERSION 2.0 In versions prior to 2.0, <space> was used to scroll the pager; 2.0 uses <tab> as the default, to allow the pager to be nonblocking. Tinytalk style name gags and hilites are no longer supported. You must use the '*' wildcard explicitly, as in '/hilite hawkeye*'. Tinytalk style page and whisper hilites are no longer supported. How- ever, /hilite_page and /hilite_whisper macros are provided in the default macro library. The .tinytalk file may not be supported in the future; use .tfrc instead. The '-' command line option in versions prior to 2.0 is no longer sup- ported, and has been replaced with '-l'. BUGS When unterbamfing, the old connection should not be closed until the new connection succeeds. If a shell quote (/quote !) reads a partial line from the pipe, the read will block until the rest of the line is read. WARNINGS The Surgeon General has determined that MUDding can be detrimental to your GPA. LOCAL TF(1)
<?php namespace App\Livewire\Componentes\Paneladmin; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; use Livewire\Component; use Livewire\WithFileUploads; use Illuminate\Support\Facades\Session; use Illuminate\Validation\ValidationException; class Recetaedit extends Component { use WithFileUploads; public $verForm; public $idReceta; public $nombre; public $tpoPrepar; public $tpoCoccion; public $tpoFinal; public $txtSubtit; public $txtParrafos; public $txtIngrediente; public $imagen; public $imagenAntig; public $vecIngredientes = []; public $vecDescripRecetas = []; private function LimpiarCampos(){ Session::forget('vectorDescripVacio'); Session::forget('vectorIngredientes'); $this->reset([ 'nombre', 'tpoPrepar', 'tpoCoccion', 'tpoFinal', 'txtSubtit', 'txtParrafos', 'txtIngrediente', 'imagen', 'vecDescripRecetas', 'vecIngredientes', ]); $this->resetErrorBag(); } public function GrabarIngrediente(){ $validatedData = $this->validate( [ 'txtIngrediente' => 'required|min:5|max:100', ], [ 'txtIngrediente.required'=> 'Debe ingresar ingrediente', 'txtIngrediente.min'=> 'El nombre del ingrediente debe tener como mínimo 5 caracteres', 'txtIngrediente.max'=> 'El nombre del ingrediente debe tener como máximo 100 caracteres', ] ); Session::forget('vectorIngredientes'); $this->vecIngredientes[] = ['clave' => uniqid() , 'valor' => $this->txtIngrediente ]; $this->reset([ 'txtIngrediente' ]); } public function EliminarIngrediente($varClave){ $ingredientesAux = []; foreach($this->vecIngredientes as $it ){ if ($it['clave'] != $varClave) { $ingredientesAux[] = $it; } } $this->vecIngredientes = []; $this->vecIngredientes = $ingredientesAux; } public function GrabarSubTit(){ $validatedData = $this->validate( [ 'txtSubtit' => 'required|min:3|max:100', ], [ 'txtSubtit.required'=> 'Debe ingresar un subtítulo', 'txtSubtit.min'=> 'El subtítulo debe tener como mínimo 5 caracteres', 'txtSubtit.max'=> 'El subtítulo debe tener como máximo 100 caracteres', ] ); Session::forget('vectorDescripVacio'); $this->vecDescripRecetas[] = ['clave' => uniqid() , 'tag'=> 't', 'valor' => $this->txtSubtit ]; $this->reset([ 'txtSubtit' ]); } public function GrabarParrafos(){ $validatedData = $this->validate( [ 'txtParrafos' => 'required|min:5|max:500', ], [ 'txtParrafos.required'=> 'Debe ingresar un texto de descripción', 'txtParrafos.min'=> 'El párrafo debe tener como mínimo 5 caracteres', 'txtParrafos.max'=> 'El párrafo debe tener como máximo 500 caracteres', ] ); Session::forget('vectorDescripVacio'); $this->vecDescripRecetas[] = ['clave' => uniqid() , 'tagHtml'=> 'p', 'valor' => $this->txtParrafos ]; $this->reset([ 'txtParrafos' ]); } public function EliminarItem($varClave){ $descripRecetasAux = []; foreach($this->vecDescripRecetas as $it ){ if ($it['clave'] != $varClave) { $descripRecetasAux[] = $it; } } $this->vecDescripRecetas = []; $this->vecDescripRecetas = $descripRecetasAux; } public function Cancelar(){ $this->LimpiarCampos(); $this->verForm=false; } public function Grabar(){ $errorListasVacias = false; Session::forget('vectorDescripVacio'); Session::forget('vectorIngredientes'); if (count($this->vecDescripRecetas) == 0){ Session::put('vectorDescripVacio', 'No ha ingresado una descripción de la receta'); $errorListasVacias = true; } if (count($this->vecIngredientes) == 0){ Session::put('vectorIngredientes', 'No ha ingresado ningún Ingrediente'); $errorListasVacias = true; } if($this->imagen){ $validatedData = $this->validate( [ 'nombre' => 'required|min:5|max:100', 'imagen' => 'image|max:1024', ], [ 'nombre.required'=> 'Debe ingresar el Nombre de la Receta', 'nombre.min'=> 'El nombre de la receta debe tener como mínimo 5 caracteres', 'nombre.max'=> 'El nombre de la receta debe tener como máximo 100 caracteres', 'imagen.image'=> 'Debe subir un archivo de imagen', 'imagen.max'=> 'La imagen debe tener un tamaño máximo de 1MB', ] ); } else { $validatedData = $this->validate( [ 'nombre' => 'required|min:5|max:100', ], [ 'nombre.required'=> 'Debe ingresar el Nombre de la Receta', 'nombre.min'=> 'El nombre de la receta debe tener como mínimo 5 caracteres', 'nombre.max'=> 'El nombre de la receta debe tener como máximo 100 caracteres', ] ); } if ($errorListasVacias == true) throw ValidationException::withMessages(['listasVacias'=>'Listas sin datos']); if($this->imagen){ $rutaArchivo = public_path('img/recetas/' . $this->imagenAntig); if (File::exists($rutaArchivo)) { File::delete($rutaArchivo); } $pathImg = $this->imagen->store('recetas', 'pathImg'); DB::table('bd_laoctava_recetas') ->where('id', $this->idReceta) ->update([ 'nombre' => $this->nombre, 'tiempoPreparacion' => $this->tpoPrepar, 'tiempoCoccion' => $this->tpoCoccion, 'tiempoTotal' => $this->tpoFinal, 'pathImg' => basename($pathImg), 'idUsr' => auth()->user()->email, 'updated_at' => now(), ]); DB::table('bd_laoctava_recetas_descrip') ->where('idReceta', $this->idReceta) ->delete(); DB::table('bd_laoctava_recetas_ingredientes') ->where('idReceta', $this->idReceta) ->delete(); foreach($this->vecDescripRecetas as $it ){ DB::table('bd_laoctava_recetas_descrip')->insert([ 'idReceta' => $this->idReceta, 'tagHtml' => $it['tagHtml'], 'estilos' => '', 'parrafo' => $it['valor'], 'created_at' => now(), 'updated_at' => now(), ]); } $nroIng=1; foreach($this->vecIngredientes as $it ){ DB::table('bd_laoctava_recetas_ingredientes')->insert([ 'idReceta' => $this->idReceta, 'nroIngrediente' => $nroIng, 'descIngrediente' => $it['valor'], 'created_at' => now(), 'updated_at' => now(), ]); $nroIng++; } } else { DB::table('bd_laoctava_recetas') ->where('id', $this->idReceta) ->update([ 'nombre' => $this->nombre, 'tiempoPreparacion' => $this->tpoPrepar, 'tiempoCoccion' => $this->tpoCoccion, 'tiempoTotal' => $this->tpoFinal, 'idUsr' => auth()->user()->email, 'updated_at' => now(), ]); DB::table('bd_laoctava_recetas_descrip') ->where('idReceta', $this->idReceta) ->delete(); DB::table('bd_laoctava_recetas_ingredientes') ->where('idReceta', $this->idReceta) ->delete(); foreach($this->vecDescripRecetas as $it ){ DB::table('bd_laoctava_recetas_descrip')->insert([ 'idReceta' => $this->idReceta, 'tagHtml' => $it['tagHtml'], 'estilos' => '', 'parrafo' => $it['valor'], 'created_at' => now(), 'updated_at' => now(), ]); } $nroIng=1; foreach($this->vecIngredientes as $it ){ DB::table('bd_laoctava_recetas_ingredientes')->insert([ 'idReceta' => $this->idReceta, 'nroIngrediente' => $nroIng, 'descIngrediente' => $it['valor'], 'created_at' => now(), 'updated_at' => now(), ]); $nroIng++; } } $this->dispatch('actualiz-lista-recetas'); $this->verForm=false; } public function VerForm(){ $this->verForm=true; $dtosReceta = []; $descripRecetas = []; $ingredientes = []; $dtosReceta = DB::table('bd_laoctava_recetas') ->where('id', $this->idReceta) ->first(); $this->nombre = $dtosReceta->nombre; $this->tpoPrepar = $dtosReceta->tiempoPreparacion; $this->tpoCoccion = $dtosReceta->tiempoCoccion; $this->tpoFinal = $dtosReceta->tiempoTotal; $this->imagenAntig = $dtosReceta->pathImg; $ingredientes = DB::table('bd_laoctava_recetas_ingredientes') ->where('idReceta', $this->idReceta) ->get(); foreach($ingredientes as $it ){ $this->vecIngredientes[] = ['clave' => uniqid() , 'valor' => $it->descIngrediente ]; } $descripRecetas = DB::table('bd_laoctava_recetas_descrip') ->where('idReceta', $this->idReceta) ->get(); foreach($descripRecetas as $it ){ $this->vecDescripRecetas[] = ['clave' => uniqid() , 'tagHtml'=>$it->tagHtml, 'valor' => $it->parrafo ]; } } public function CerrarForm(){ $this->verForm=false; } public function render() { return view('livewire.componentes.paneladmin.recetaedit'); } }
// // ComicsEndpoint.swift // KingtakWongDisneyCruise // // Created by Kingtak Justin Wong on 4/4/22. // import Foundation class ComicEndpoint: BaseNetworkClass, NetworkEndpointProtocol { typealias dataType = ComicResponse //Endpoints are statically defined here to help define getting to the end var endPoint = "comics" /** This is built locally to help facilitate differences in how building the URL can happen depending on the endpoint information. This could make this extremely complex but since its really just buliding it on a few properties, this can be set for now.... can potentionally be optimized later depending on use case */ var baseURL: URLComponents? { var url = URLComponents(string: "\(self.credential.urlBase)\(self.endPoint)") let timestamp = "\(Date().timeIntervalSince1970)" let hash = "\(timestamp)\(self.credential.privateAPIKey)\(self.credential.apitoken)".md5() let authItems = [ URLQueryItem(name: "ts", value: timestamp), URLQueryItem(name: "apikey", value: self.credential.apitoken), URLQueryItem(name: "hash", value: hash) ] url?.queryItems = authItems return url } func updatedUrl(offset: Int, limit: Int? = nil) -> URL? { guard var newURL = self.baseURL else { return nil } newURL.queryItems?.append(URLQueryItem(name: "offset", value: "\(offset)")) if let newLimit = limit { newURL.queryItems?.append(URLQueryItem(name: "limit", value: "\(newLimit)")) } return newURL.url } override init(credential: Credential) { super.init(credential: credential) } }