text
stringlengths
184
4.48M
import { Column, Entity, Index, OneToMany, OneToOne, PrimaryGeneratedColumn } from 'typeorm'; import { Account, AccountRelation, AccountRelationDocument, Contract, GeneratedDocument, Infringement, LeaseContract, ManualPayment, Nomination, TimeStamped, VehicleDocument, } from '@entities'; import { OcrDetails } from '@modules/shared/models/ocr-details.model'; import { ApiProperty } from '@nestjs/swagger'; @Entity() export class Document extends TimeStamped { @PrimaryGeneratedColumn() @Index({ unique: true }) @ApiProperty() documentId: number; @Column('text') @ApiProperty() storageName: string; @Column('text') @ApiProperty() fileName: string; @Column('text') @ApiProperty() fileDirectory: string; // relative to Config.get.storage() @Column('jsonb', { nullable: true, default: null }) @ApiProperty({ type: () => OcrDetails, description: 'Results from contract OCR' }) ocr: OcrDetails; @OneToOne((type) => Contract, (contract) => contract.document) // Lease Contract @ApiProperty({ type: 'object', description: 'Contract' }) contract: Contract; @OneToOne((type) => LeaseContract, (lease) => lease.redirectionDocument) // Substitute Lease Contract @ApiProperty({ type: 'object', description: 'LeaseContract' }) leaseContract: LeaseContract; @OneToMany((type) => VehicleDocument, (vehicleDocument) => vehicleDocument.document) // Vehicle Documents [Registration] (not used for much right now) @ApiProperty({ type: 'object', description: 'Vehicle Documents [Registration] (not used for much right now)' }) vehicleDocuments: VehicleDocument[]; @OneToOne((type) => Infringement, (infringement) => infringement.document) // Scan of Infringement @ApiProperty({ type: 'object', description: 'Infringement' }) infringement: Infringement; @OneToOne((type) => ManualPayment, (payment) => payment.document) // Scan of Receipt @ApiProperty({ type: 'object', description: 'ManualPayment' }) manualPayment: ManualPayment; @OneToMany((type) => Nomination, (nomination) => nomination.mergedDocument) // Power of Attorney + (Lease Contract || Lease Contract Substitute) + Redirection Document @ApiProperty({ type: 'object', description: 'Nomination[]' }) nominationMerged: Nomination[]; @OneToMany((type) => Nomination, (nomination) => nomination.redirectionDocument) // Automatically Generated Document for Redirection @ApiProperty({ type: 'object', description: 'Nomination[]' }) nominationRedirection: Nomination[]; @OneToOne((type) => Account, (account) => account.powerOfAttorney) // Power of Attorney for an account @ApiProperty({ type: 'object', description: 'Account' }) account: Account; @OneToOne((type) => GeneratedDocument, (generatedDocument) => generatedDocument.document) @ApiProperty({ type: 'object', description: 'GeneratedDocument' }) generatedDocument: GeneratedDocument; @OneToMany((type) => AccountRelationDocument, (document) => document.document) @ApiProperty({ type: 'object', description: 'AccountRelation' }) relations: AccountRelation[]; static findPowerOfAttorneyByAccount(accountId: number) { return this.createQueryBuilder('document') .innerJoinAndSelect('document.account', 'account') .where('account.accountId = :accountId', { accountId }); } static findByContract(contractId: number) { return this.createQueryBuilder('document') .innerJoinAndSelect('document.contract', 'contract') .where('contract.contractId = :contractId', { contractId }); } static findLeaseContractSubstituteDocument(contractId: number) { return this.createQueryBuilder('document') .innerJoinAndSelect('document.leaseContract', 'leaseContract') .where('leaseContract.contractId = :contractId', { contractId }); } static findRedirectionByNomination(nominationId: number) { return this.createQueryBuilder('document') .innerJoinAndSelect('document.nominationRedirection', 'nomination') .where('nomination.nominationId = :nominationId', { nominationId }); } static findByDocumentId(documentId: number) { return this.createQueryBuilder('document').where('document.documentId = :documentId', { documentId }); } }
--- title: Great Woocommerce Hero Section in 2023 – key elements draft: true author: WP-Tactics type: post date: 2023-04-16T12:44:09+00:00 url: /great-woocommerce-hero-section-site-2023/ rank_math_internal_links_processed: - 1 rank_math_seo_score: - 72 rank_math_focus_keyword: - woocommerce hero section rank_math_analytic_object_id: - 25 rank_math_description: - 'What key elements make a great Woocommerce hero section? Six steps for building the best one in 2023 and convert your visitors to customers. ' rank_math_title: - %title% %sep% %sitename% rank_math_primary_category: - 1 rank_math_og_content_image: - 'a:2:{s:5:"check";s:32:"14f0e9c40dbcad1dd4638a689f3f231d";s:6:"images";a:1:{i:0;i:206;}}' wpaicg_toc_title: - Table of Contents wpaicg_toc_title_tag: - h2 wpaicg_intro_title_tag: - h2 wpaicg_conclusion_title_tag: - h2 categories: - All tips and tricks - E-commerce - SEO - Woocommerce --- <figure class="wp-block-image size-full"><img decoding="async" loading="lazy" width="768" height="512" src="https://wordpress-tactics.com/wp-content/uploads/2023/04/festertues_e-commerce_header_section_3_83e25617-904e-40b6-b14d-bc604271b82a.png" alt="woocommerce hero section" class="wp-image-206" srcset="https://wordpress-tactics.com/wp-content/uploads/2023/04/festertues_e-commerce_header_section_3_83e25617-904e-40b6-b14d-bc604271b82a.png 768w, https://wordpress-tactics.com/wp-content/uploads/2023/04/festertues_e-commerce_header_section_3_83e25617-904e-40b6-b14d-bc604271b82a-300x200.png 300w" sizes="(max-width: 768px) 100vw, 768px" /></figure> The Woocommerce hero section is the first thing that visitors see when they land on your website. It&#8217;s the most prominent section of your homepage, and it&#8217;s responsible for making a great first impression on your potential customers. A well-designed hero section can not only capture the attention of your visitors but also communicate your brand identity and values. In this article, we&#8217;ll discuss the key elements that a great hero section of an e-commerce site should have. ## 1. Clear Value Proposition {.wp-block-heading} Your WooCommerce hero section should clearly communicate the unique value that your products or services provide to your customers. This can be achieved through the use of clear and concise messaging that highlights the key benefits of your products or services. For example, if you&#8217;re selling beauty products, your hero section might include messaging that communicates the transformative power of your products and how they can help your customers look and feel their best. ## 2. Engaging Visuals {.wp-block-heading} The use of high-quality visuals such as images, videos, or animations can capture the attention of your visitors and communicate your brand identity. Your hero section should include visuals that are relevant to your products or services and are visually appealing. For example, if you&#8217;re selling outdoor gear, your hero section might include a high-quality image of someone hiking in the mountains, which not only communicates the benefits of your products but also creates an emotional connection with your visitors. ## 3. Clear Call-to-Action {.wp-block-heading} A prominent call-to-action button that encourages visitors to take action, such as &#8220;Shop Now&#8221; or &#8220;Learn More,&#8221; can increase the chances of conversion. Your call-to-action should be prominently displayed in your woocommerce hero section and should be easy to find and click. The text on your call-to-action button should be clear and concise, and the button should be visually appealing to encourage visitors to click. ## 4. Mobile Optimization {.wp-block-heading} As more and more people are browsing the internet on their mobile devices, it&#8217;s essential to ensure that your hero section is optimized for mobile screens. This means that your hero section should be responsive and adjust to fit the screen size of the device that your visitors are using. Your hero section should be easy to navigate on mobile devices, and your call-to-action button should be easy to click on small screens. ## 5. Brand Consistency {.wp-block-heading} Your woocommerce hero section should be consistent with your brand identity, including your brand colors, typography, and messaging. By ensuring brand consistency, you can create a hero section that not only captures the attention of your visitors but also communicates your brand identity and values. While these elements are crucial, it&#8217;s also essential to remember that your hero section should be designed with your target audience in mind. Consider the demographics of your target audience, their interests, and their browsing habits when designing your hero section. By doing so, you can create a hero section that resonates with your visitors and encourages them to explore your website further. In conclusion, the woocommerce hero section of your e-commerce site is one of the most important elements of your website design. By including a clear value proposition, engaging visuals, a clear call-to-action, mobile optimization, and brand consistency, you can create a hero section that captures the attention of your visitors and communicates your brand identity and values. With careful consideration of your target audience, you can create a woocommerce hero section that encourages visitors to explore your website and ultimately make a purchase. ## 6. Customer Reviews and Social Proof {.wp-block-heading} Including customer reviews or social proof in your woocommerce hero section is an effective way to build trust with your visitors and encourage them to make a purchase. Customer reviews and social proof can provide valuable insights into your products and services, which can help potential customers make more informed purchasing decisions. An excellent example of social proof can be seen on the website of the beauty brand Glossier. Their hero section features a prominent quote from a customer review, which serves as a powerful endorsement of their products and encourages visitors to explore their website further. ## Conclusion {.wp-block-heading} In conclusion, the hero section of your e-commerce site is a crucial element that can make or break the first impression of your brand. To create a woocommerce hero section that captures the attention of your visitors and communicates your brand identity and values &#8211; and, of course, converts visitors to customer, the key elements you need are: * Clear value proposition: Your hero section should clearly communicate the unique value that your products or services provide to your customers. * Engaging visuals: The use of high-quality visuals such as images, videos, or animations can capture the attention of your visitors and communicate your brand identity. * Clear call-to-action: A prominent call-to-action button that encourages visitors to take action, such as &#8220;Shop Now&#8221; or &#8220;Learn More,&#8221; can increase the chances of conversion. * Mobile optimization: As more and more people are browsing the internet on their mobile devices, it&#8217;s essential to ensure that your woocommerce hero section is optimized for mobile screens. * Brand consistency: Your hero section should be consistent with your brand identity, including your brand colors, typography, and messaging. * Customer reviews and social proof: Including customer reviews or social proof can help build trust with your visitors and encourage them to make a purchase. And, most importantly, creating a high converting e-commerce website is not a one-time job &#8211; you will need to always monitor your visitors behavior and analytics data so you can further enhance the effectiveness of your woocommerce hero section and encourage visitors to explore your website and make a purchase. Remember to keep your target audience in mind when designing your hero section, and you&#8217;ll be on your way to creating a successful e-commerce site.
import { MutableRefObject } from 'react'; type RefOrElem<E extends HTMLElement | null | undefined> = MutableRefObject<E> | E; export declare function getElement<E extends HTMLElement | null | undefined>(e?: RefOrElem<E>): E | null | undefined; interface ScrollToOptions { /** * Adds an extra few number of pixels to add some "padding" to * the top of the scroll (i.e., does not scroll the element to * the edge of the parent). * * Note: a negative offset will push the element DOWN a bit from * the top, while a positive offset will scroll the element PAST * the top by that amount. */ additionalOffset?: number; /** Allows for returning a dynamic offset. */ computeOffset?: (container: HTMLElement, elem: HTMLElement) => number | null | undefined; } export type ScrollType = 'scrollInto' | 'scrollTo'; export type ScrollOptionsType<T extends ScrollType> = T extends 'scrollInto' ? ScrollIntoViewOptions : T extends 'scrollTo' ? ScrollToOptions : never; interface UseScrollIntoViewOptions<T extends ScrollType = 'scrollInto'> { child: RefOrElem<HTMLElement | null | undefined>; container: RefOrElem<HTMLElement | null | undefined>; /** @default false (i.e., not disabled, check if should scroll into view) */ disabled?: boolean; options?: ScrollOptionsType<T>; /** @default scrollInto */ type?: T; } export declare function useScrollIntoView<T extends ScrollType = 'scrollInto'>({ child, container, disabled, options, type }: UseScrollIntoViewOptions<T>): void; export {};
import { useDispatch, useSelector } from "react-redux"; import { Link, useNavigate } from "react-router-dom"; import logo_utc2 from "../../assets/logo_utc2.png"; import { handleLogoutAdmin } from "../../redux/authAdmin/authAdminAction"; import CustomButton from "../../components/CustomButton"; const HeaderAdmin = () => { const authAdmin = useSelector((state) => state.authAdmin); const navigate = useNavigate(); const dispatch = useDispatch(); const pathname = window.location.pathname; const onClickLogout = () => { const confirmed = window.confirm("Bạn có chắc chắn muốn đăng xuất?"); if (confirmed) { dispatch(handleLogoutAdmin(navigate)); } }; return ( <div className="topbar w-full flex items-center justify-between py-3 md:py-3 px-4 bg-white"> <Link to="/" className="flex gap-2 items-center"> <div className="p-1 md:p-2 w-16 rounded text-white"> <img src={logo_utc2} alt="" /> </div> <span className="text-xl md:text-2xl text-[#065ad8] font-semibold"> Admin UTC2 Social </span> </Link> <div className="flex gap-4 items-center text-ascent-1 text-md md:text-xl"> <div> <CustomButton onClick={() => onClickLogout()} title="Đăng xuất" containerStyles="text-sm text-ascent-1 px-4 md:px-6 py-1 md:py-2 border border-[#666] rounded-full" /> </div> </div> </div> ); }; export default HeaderAdmin;
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Panel } from 'react-bootstrap'; import { getPlayer } from '../../redux/player/playerActions'; import AddFriend from '../../components/Friend/AddFriend.jsx'; import './Player.scss'; /** * Player component * View /player/:id */ class Player extends Component { /** * Hook called before component mounted * Fetch room */ componentWillMount() { this.props.getPlayer(this.props.match.params.id); } /** * Hook called before component mounted * Fetch room */ componentDidUpdate() { if (+this.props.match.params.id !== this.props.player.id) { this.props.getPlayer(this.props.match.params.id); } } /** * render * @returns {JSX} return jsx */ render() { let mode = 'add'; if (this.props.friendRequestListId.indexOf(this.props.player.id) !== -1) { mode = 'accept'; } else if (this.props.friendListId.indexOf(this.props.player.id) !== -1) { mode = 'refuse'; } else if (this.props.user.id === this.props.player.id) { mode = undefined; } return ( <div> { mode ? (<AddFriend mode={mode} friend={this.props.player} className="add-friend"/>) : undefined } <Panel header={(<h3>Player name</h3>)}> {this.props.player.nickname} </Panel> <Panel header={(<h3>Player email</h3>)}> {this.props.player.email} </Panel> </div> ); } } Player.propTypes = { player: React.PropTypes.object, }; const mapStateToProps = (state) => ({ player: state.player, friendRequestListId: state.friendRequest.map((friend) => friend.id), friendListId: state.friends.map((friend) => friend.id), user: state.user, }); const mapDispatchToProps = (dispatch) => ({ getPlayer: (id) => dispatch(getPlayer(id)), }); export default connect(mapStateToProps, mapDispatchToProps)(Player);
// Copyright © 2019 NAME HERE <EMAIL ADDRESS> // // 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. // Config subcommands for the ginsight CLI package config import ( "github.com/spf13/cobra" ) // config.Cmd represents the root config command var Cmd = &cobra.Command{ Use: "config", Short: "Configure the Insight CLI", Long: `Manage Insight CLI config settings`, RunE: func(cmd *cobra.Command, args []string) error { if cmd.Flags().Changed("add") { CmdAdd.SetArgs(args) return CmdAdd.Execute() } if cmd.Flags().Changed("validate") { CmdValidate.SetArgs(args) return CmdValidate.Execute() } numArgs := len(args) if numArgs == 1 { CmdShow.SetArgs(args) return CmdShow.Execute() } cmd.Help() return nil }, } func init() { Cmd.Flags().BoolP("add", "a", false, "name") Cmd.Flags().BoolP("validate", "", false, "validate your configuration") }
use std::ops::{Add, Mul, AddAssign, Index, IndexMut}; // クレート内のモジュールへのアクセスはcrate::で行う。 use crate::vector::*; use crate::One, Transpose}; use rand::Rng; use rand::distributions::{Distribution, Standard}; #[derive(Debug, Clone)] pub struct Matrix<T, const ROWS: usize, const COLS: usize> { pub data: [[T; COLS]; ROWS], } impl<T: Default + Copy, const ROWS: usize, const COLS: usize> Default for Matrix<T, ROWS, COLS> { fn default() -> Self { let data = [[T::default(); COLS]; ROWS]; Matrix {data} } } impl<T: Default + Copy, const ROWS: usize, const COLS: usize> Matrix<T, ROWS, COLS> { pub fn new() -> Self { Self { data: [[T::default(); COLS]; ROWS], } } pub fn nrow(&self) -> usize { ROWS } pub fn ncol(&self) -> usize { COLS } } impl<T: Add<Output = T> + Default + One + Copy, const ROWS: usize, const COLS: usize> One for Matrix<T, ROWS, COLS> { fn one() -> Self { let mut data = [[T::default(); COLS]; ROWS]; let minvalue = if ROWS < COLS {ROWS} else {COLS}; for i in 0..minvalue { data[i][i] = T::one(); } Self {data} } } impl<T: Add<Output = T> + Default + Copy, const ROWS: usize, const COLS: usize> Index<usize> for Matrix<T, ROWS, COLS> { type Output = [T; COLS]; fn index(&self, index: usize) -> &Self::Output { &self.data[index] } } impl<T: Add<Output = T> + Default + Copy, const ROWS: usize, const COLS: usize> IndexMut<usize> for Matrix<T, ROWS, COLS> { fn index_mut(&mut self, index: usize) -> &mut [T; COLS] { &mut self.data[index] } } impl<T: Add<Output = T> + Default + Copy, const ROWS: usize, const COLS: usize> Add for Matrix<T, ROWS, COLS> { type Output = Self; fn add(self, other: Self) -> Self { let mut result = Self::new(); for i in 0..ROWS { for j in 0..COLS { result.data[i][j] = self.data[i][j] + other.data[i][j]; } } result } } // Matrix * Matrix = Matrix // Tはmulできて、addAssignできて、コピーできて、デフォルトがあるtype impl<T: Mul<Output = T> + AddAssign + Default + Copy, const ROWS: usize, const COLS: usize> Mul<Matrix<T, ROWS, COLS>> for Matrix<T, ROWS, COLS> { type Output = Self; fn mul(self, other: Self) -> Self { let mut result = Self::new(); for i in 0..ROWS { for j in 0..COLS { let mut x = T::default(); for k in 0..ROWS { x += self.data[i][k] * other.data[k][j] } result.data[i][j] = x; } } result } } impl<T: Mul<Output = T> + AddAssign + Default + Copy, const ROWS: usize, const COLS: usize> Mul<Vector<T, COLS>> for Matrix<T, ROWS, COLS> { type Output = Vector<T, ROWS>; fn mul(self, other: Vector<T, COLS>) -> Vector<T, ROWS> { // (ROWS, COLS) * (COLS, 1) = (ROWS, 1) let mut result = Vector::<T, ROWS>::new(); for i in 0..ROWS { let mut x = T::default(); for j in 0..COLS { x += self.data[i][j] * other.data[j] } result.data[i] = x; } result } } impl<T: Mul<Output = T> + AddAssign + Default + Copy, const ROWS: usize, const COLS: usize> Mul<T> for Matrix<T, ROWS, COLS> { type Output = Self; fn mul(self, other: T) -> Matrix<T, ROWS, COLS> { // (ROWS, COLS) * (COLS, 1) = (ROWS, 1) let mut result = Matrix::<T, ROWS, COLS>::new(); for i in 0..ROWS { for j in 0..COLS { result.data[i][j] = self.data[i][j] * other; } } result } } /// random matrix impl<T: Default + Copy, const ROWS: usize, const COLS: usize> Distribution<Matrix<T, ROWS, COLS>> for Standard where Standard: Distribution<T> { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Matrix<T, ROWS, COLS> { let mut result = Matrix::<T, ROWS, COLS>::default(); for i in 0..ROWS { for j in 0..COLS { let x: T = rng.gen(); result.data[i][j] = x; } } result } } impl<T: Default + Copy, const ROWS: usize, const COLS: usize> Transpose for Matrix<T, ROWS, COLS> { type Output = Matrix<T, COLS, ROWS>; fn transpose(self) -> Self::Output { let mut result = Matrix::<T, COLS, ROWS>::default(); for i in 0..ROWS { for j in 0..COLS { result.data[j][i] = self.data[i][j]; } } result } } use std::fmt; // 出力 impl<T: fmt::Display, const ROWS: usize, const COLS: usize> fmt::Display for Matrix<T, ROWS, COLS> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut s = format!("{}x{} Matrix\n", ROWS, COLS); for i in 0..ROWS { for j in 0..COLS { s += &format!("{:>5} ", self.data[i][j]); } s += &format!("\n"); } write!(f, "{}", s) } }
import { Directive } from '@angular/core'; import { AbstractControl, FormControl, NG_VALIDATORS, ValidatorFn, Validators } from '@angular/forms'; @Directive({ selector: '[appBiggerDayValidator]', providers: [ { provide: NG_VALIDATORS, useClass: BiggerDayValidatorDirective, multi: true } ] }) export class BiggerDayValidatorDirective implements Validators { validator: ValidatorFn; nowDate: Date = new Date(); constructor() { this.validator = this.biggerDayValidator(); } validate(c: FormControl): any { return this.validator(c); } biggerDayValidator(): ValidatorFn { return (control: AbstractControl) => { // If control doesn't have value if (!control.value){ return null; } // Get date value else{ try{ const dateData: Date = new Date(control.value); if (dateData > this.nowDate){ return{dateError: true, // message: 'DATE_GREATER_THAN_NOW_DATE', message: 'Ngày chọn không thể lớn hơn ngày hiện tại'}; } // Error free else{ return null; } } catch { return{dateError: true, message: 'DATE_PARSE_ERROR'}; } } }; } }
import 'package:flutter/material.dart'; import 'package:skywatch/core/constants/constants.dart'; import 'package:skywatch/core/resources/resources.dart'; class WindSpeedAndHumidityWidget extends StatelessWidget { const WindSpeedAndHumidityWidget({ required this.windSpeed, required this.humidity, required this.fontColor, super.key, }); final String windSpeed; final String humidity; final Color fontColor; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset( IconPaths.windIconPath, color: fontColor, width: SizeConstants.xlarge, ), Text( '${windSpeed}mph', style: TextStyle( color: fontColor, fontSize: SizeConstants.large, ), ), const SizedBox(width: SizeConstants.medium), Image.asset( IconPaths.humidityIconPath, color: fontColor, width: SizeConstants.xlarge, ), Text( '$humidity%', style: TextStyle( color: fontColor, fontSize: SizeConstants.large, ), ), ], ); } }
import React, { useEffect, useState } from 'react' import axios from 'axios' import {Link} from 'react-router-dom' const ListaUsuario = () => { const [lista, setLista] = useState([]) useEffect(()=>{ const getUsuarios = async()=>{ const res = await axios.get('http://localhost:4000/api/usuarios') setLista(res.data) } getUsuarios(); },[lista]) const eliminarUsuario=async(id)=>{ await axios.delete('http://localhost:4000/api/usuarios/'+ id) } return ( <div className='row'> { lista.map(list => ( <div className='col-md-4 p-2' key={list._id}> <div className='card'> <div className='card-header'> <h5>Nombre: {list.nombre}</h5> </div> <div className='card-body'> <p>Apellido: {list.apellido}</p> <p>Edad: {list.edad}</p> <p>Telefono: {list.telefono}</p> <p>Correo: {list.correo}</p> </div> <div className='card-footer'> <button className='btn btn-danger' onClick={()=>eliminarUsuario(list._id)}> Eliminar </button> <Link className='btn btn-primary m-1' to={'/edit/'+ list._id}> Editar </Link> </div> </div> </div> )) } </div> ) } export default ListaUsuario
import React from 'react'; import {Card, CardBody, CardFooter, Image, Skeleton, Badge} from "@nextui-org/react"; export default function TopSeller({title, slug, list, isLoading}) { let filterItems = list.filter(({attributes}) => attributes.region.data.attributes.slug === slug); return (<div className='container mx-auto mb-10'> <diiv className='text-5xl text-center'>{title}</diiv> <div className="gap-2 grid grid-cols-2 sm:grid-cols-4 mt-5"> {filterItems.map(({id:_id, attributes : item }, index) => ( <Card shadow="sm" key={`${slug}-product-${_id}`} isPressable onPress={() => console.log("item pressed")}> <CardBody className="overflow-visible p-0"> <Image shadow="sm" radius="lg" width="100%" alt={item.title} className="w-full object-cover h-[250px]" src={`${process.env.NEXT_PUBLIC_HOSTAPI}${item.images.data[0].attributes.url}`} /> </CardBody> <CardFooter className="text-small justify-between"> <lable className='capitalize'>{item.title}</lable> <p className="text-default-500">{parseInt(item.price).toLocaleString('es-MX', {style: 'currency',currency: 'MXN'})}</p> </CardFooter> </Card> ))} {filterItems.length <= 0 && !isLoading && <div className='text-center'>No hay productos disponibles</div>} {isLoading && <> <Skeleton className="rounded-lg"><div className="h-[250px] rounded-lg bg-default-300"></div></Skeleton> <Skeleton className="rounded-lg"><div className="h-[250px] rounded-lg bg-default-300"></div></Skeleton> <Skeleton className="rounded-lg"><div className="h-[250px] rounded-lg bg-default-300"></div></Skeleton> </>} </div> </div>) }
import { CircularProgress } from "@mui/material"; import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js"; import React, { useEffect, useState } from "react"; import useAuth from "../../../hooks/useAuth"; const CheckoutForm = ({ orders }) => { const { price, name, _id } = orders; const { user } = useAuth(); const stripe = useStripe(); const elements = useElements(); const [error, setError] = useState(""); const [success, setSuccess] = useState(""); const [processing, setProcessing] = useState(false); const [clientSecret, setClientSecret] = useState(""); useEffect(() => { fetch("https://honda-show-room.onrender.com/create-payment-intent", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ price }), }) .then((res) => res.json()) .then((data) => setClientSecret(data.clientSecret)); }, [price]); const handleSubmit = async (e) => { e.preventDefault(); if (!stripe || !elements) { return; } const card = elements.getElement(CardElement); if (card == null) { return; } setProcessing(true); const { error, paymentMethod } = await stripe.createPaymentMethod({ type: "card", card, }); if (error) { setError(error.message); setSuccess(""); } else { setError(""); setSuccess("your pament processed successfully"); } // payment intent const { paymentIntent, error: intentError } = await stripe.confirmCardPayment(clientSecret, { payment_method: { card: card, billing_details: { name: name, email: user.email, }, }, }); if (intentError) { setError(intentError.message); } else { setError(""); setProcessing(false); // save to database const payment = { amount: paymentIntent.amount, created: paymentIntent.created, last4: paymentMethod.card.last4, transaction: paymentIntent.client_secret.slice("_secret")[0], }; const url = `https://honda-show-room.onrender.com/orders/${_id}`; fetch(url, { method: "PUT", headers: { "content-type": "application/json", }, body: JSON.stringify(payment), }) .then(() => {}) .then(() => {}); } }; return ( <div> <form onSubmit={handleSubmit}> <CardElement options={{ style: { base: { fontSize: "16px", color: "#424770", "::placeholder": { color: "#aab7c4", }, }, invalid: { color: "#9e2146", }, }, }} /> {processing ? ( <CircularProgress></CircularProgress> ) : ( <button type="submit" disabled={!stripe || success}> Pay ${price} </button> )} </form> {error && <p style={{ color: "red" }}>{error}</p>} {success && <p style={{ color: "green" }}>{success}</p>} </div> ); }; export default CheckoutForm;
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Campaign extends Model { protected $table = "campaigns"; protected $fillable = [ 'name', 'description', 'url', 'icon', 'screenshot', 'release_date', 'end_date', 'status_id', 'category_id', 'product_manager_id', 'deleted_at', ]; protected $hidden = [ 'deleted_at', ]; public function categories() { return $this->belongsToMany(Category::class, 'pivot_campaign_categories', 'campaign_id', 'category_id'); } public function productManagers() { return $this->belongsToMany(User::class, 'pivot_campaign_product_managers', 'campaign_id', 'product_manager_id'); } public function status() { return $this->belongsTo(Status::class); } public function files() { return $this->hasMany(File::class); } }
import 'dart:convert'; import 'package:sqflite/sqflite.dart' as sql; import 'package:sqflite/sqflite.dart'; class SqlHelper { static Future<void> createTables(sql.Database database) async { await database.execute(""" CREATE TABLE IF NOT EXISTS recipes( recipe_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT, description TEXT, prep_time INTEGER, cook_time INTEGER, refrigerate_time INTEGER, additional_time INTEGER, total_time INTEGER, serving INTEGER, recipe_yield TEXT ) """); await database.execute(""" CREATE TABLE IF NOT EXISTS nutritions( recipe_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT, value TEXT, FOREIGN KEY (recipe_id) REFERENCES recipes(recipe_id) ) """); await database.execute(""" CREATE TABLE IF NOT EXISTS steps( recipe_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, step TEXT, FOREIGN KEY (recipe_id) REFERENCES recipes(recipe_id) ) """); await database.execute(""" CREATE TABLE IF NOT EXISTS ingredients( recipe_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, ingredient TEXT, FOREIGN KEY (recipe_id) REFERENCES recipes(recipe_id) ) """); await database.execute(""" CREATE TABLE IF NOT EXISTS recipe_images( recipe_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, img_url TEXT, FOREIGN KEY (recipe_id) REFERENCES recipes(recipe_id) ) """); await database.execute(""" CREATE TABLE IF NOT EXISTS catagories( recipe_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT, FOREIGN KEY (recipe_id) REFERENCES recipes(recipe_id) ) """); await database.execute(""" CREATE TABLE IF NOT EXISTS favorite( recipe_slug TEXT ) """); } static Future<sql.Database> db() async { return sql.openDatabase( 'Millions_Recipe', version: 1, onCreate: (sql.Database database, int version) async { await createTables(database); }, ); } static Future<int> createRecipes( String name, String description, String prepTime, String cookTime, String refrigerateTime, String additionalTime, String totalTime, String serving, String recipeYield) async { final db = await SqlHelper.db(); final data = { 'name': name, 'description': description, 'prep_time': prepTime, 'cook_time': cookTime, 'refrigerate_time': refrigerateTime, 'additional_time': additionalTime, 'total_time': totalTime, 'serving': serving, 'recipe_yield': recipeYield }; final id = await db.insert('recipes', data, conflictAlgorithm: sql.ConflictAlgorithm.replace); return id; } static Future<int> insertFavorite(String slug) async { final db = await SqlHelper.db(); final data = {'recipe_slug': slug}; final id = await db.insert('favorite', data, conflictAlgorithm: sql.ConflictAlgorithm.replace); return id; } static Future<int> deleteFavorite(String slug) async { final db = await SqlHelper.db(); final deletedRows = await db .delete('favorite', where: 'recipe_slug = ?', whereArgs: [slug]); return deletedRows; } static Future<bool> isRecipeFavorite(String slug) async { final db = await SqlHelper.db(); final count = Sqflite.firstIntValue(await db.rawQuery( 'SELECT COUNT(*) FROM favorite WHERE recipe_slug = ?', [slug], )); return count! > 0; } static Future<int> insertNutrition( int recipeId, String name, String value, ) async { final db = await SqlHelper.db(); final data = { 'recipe_id': recipeId, 'name': name, 'value': value, }; final insertedId = await db.insert( 'nutritions', data, conflictAlgorithm: sql.ConflictAlgorithm.replace, ); return insertedId; } static Future<int> insertStep( int recipeId, List<Map<String, String>> steps, ) async { final db = await SqlHelper.db(); final stepsJson = jsonEncode(steps); final data = { 'recipe_id': recipeId, 'step': stepsJson, }; final insertedId = await db.insert( 'steps', data, conflictAlgorithm: sql.ConflictAlgorithm.replace, ); return insertedId; } static Future<int> insertIngredient( int recipeId, List<Map<String, String>> ingredients, ) async { final db = await SqlHelper.db(); final ingredientsJson = jsonEncode(ingredients); final data = { 'recipe_id': recipeId, 'ingredient': ingredientsJson, }; final insertedId = await db.insert( 'ingredients', data, conflictAlgorithm: sql.ConflictAlgorithm.replace, ); return insertedId; } static Future<void> insertRecipeImage(int recipeId, List imageUrls) async { final db = await SqlHelper.db(); final imageUrlJson = jsonEncode(imageUrls); final data = { 'recipe_id': recipeId, 'img_url': imageUrlJson, }; await db.insert( 'recipe_images', data, conflictAlgorithm: sql.ConflictAlgorithm.replace, ); } static Future<int> insertCategory( int recipeId, String name, ) async { final db = await SqlHelper.db(); final data = { 'recipe_id': recipeId, 'name': name, }; final insertedId = await db.insert( 'categories', data, conflictAlgorithm: sql.ConflictAlgorithm.replace, ); return insertedId; } static Future<dynamic> getRecipeById(int id) async { final db = await SqlHelper.db(); final insertedData = await db.query('recipes', where: 'recipe_id = ?', whereArgs: [id], limit: 1); if (insertedData.isNotEmpty) { return insertedData.first; } else { return {}; } } }
import 'package:sqflite/sqflite.dart'; import 'package:todo/features/dashboard/data/task_model.dart'; import 'package:path/path.dart'; class LocalStorage{ static Database? _database; Future<Database> get database async { if (_database != null) return _database!; _database = await init(); return _database!; } init() async{ String path = join(await getDatabasesPath(), "tasks.db"); return await openDatabase( path, version: 1, onCreate: (db, version) async { await db.execute( "CREATE TABLE tasks (id TEXT PRIMARY KEY, name TEXT, description TEXT, date TEXT, status INTEGER)", ); }, ); } Future<void> insertTask(Task task) async { final db = await database; await db.insert('tasks', task.toMap()); } Future<List<Task>> getTasks() async { final db = await database; final List<Map<String, dynamic>> maps = await db.query('tasks'); return List.generate(maps.length, (i) { return Task.fromMap(maps[i]); }); } Future<void> updateTask(Task task) async { final db = await database; await db.update( 'tasks', task.toMap(), where: 'id = ?', whereArgs: [task.id], ); } Future<void> deleteTask(String id) async { final db = await database; await db.delete( 'tasks', where: 'id = ?', whereArgs: [id], ); } }
import React, { useState, useEffect } from 'react'; import Swal from 'sweetalert2'; import { registerUser, getUsers } from '../api/api'; interface Employee { username: string; email: string; rol: string; password: string; direccion: string; telefono: string; } const AddEmployee: React.FC = () => { const [employee, setEmployee] = useState<Employee>({ username: '', email: '', rol: '', password: '', direccion: '', telefono: '', }); const [employeesList, setEmployeesList] = useState<Employee[]>([]); useEffect(() => { const fetchUsers = async () => { try { const users = await getUsers(); setEmployeesList(users); } catch (error) { console.error("Error al obtener los administradores:", error); } }; fetchUsers(); }, []); const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { const { name, value } = event.target; setEmployee((prev) => ({ ...prev, [name]: value })); }; const handleSubmit = async () => { console.log('Administrador añadido:', employee); try { const response = await registerUser(employee.username, employee.password, employee.email, 'Admin', employee.direccion, employee.telefono, 1); if (response) { Swal.fire({ icon: 'success', title: '¡Registrado exitosamente!', text: 'Administrador añadido correctamente.' }); setEmployee({ username: '', email: '', password: '', rol: '', direccion: '', telefono: '', }); // Refresca la lista de administradores después de añadir uno nuevo const updatedUsers = await getUsers(); setEmployeesList(updatedUsers); } } catch (error) { Swal.fire({ icon: 'error', title: 'Error al registrar', text: `Hubo un error al registrar al administrador: ${error}` }); } }; return ( <div className="container mx-auto px-4 py-10"> <h1 className="text-2xl font-semibold mb-6">Añadir Empleados</h1> <div className="bg-white p-6 rounded-lg shadow-md"> <div className="mb-4"> <label className="block text-sm font-medium text-gray-700 mb-2" htmlFor="username">Nombre de Usuario:</label> <input name="username" value={employee.username} onChange={handleInputChange} placeholder="Nombre de Usuario" className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" id="username" /> </div> <div className="mb-4"> <label className="block text-sm font-medium text-gray-700 mb-2" htmlFor="email">Email:</label> <input name="email" value={employee.email} onChange={handleInputChange} placeholder="Email" type="email" className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" id="email" /> </div> <div className="mb-4"> <label className="block text-sm font-medium text-gray-700 mb-2" htmlFor="email">Direccion:</label> <input name="direccion" value={employee.direccion} onChange={handleInputChange} placeholder="Direccion" type="direccion" className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" id="direccion" /> </div> <div className="mb-4"> <label className="block text-sm font-medium text-gray-700 mb-2" htmlFor="email">Telefono:</label> <input name="telefono" value={employee.telefono} onChange={handleInputChange} placeholder="Telefono" type="telefono" className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" id="direccion" /> </div> <div className="mb-4"> <label className="block text-sm font-medium text-gray-700 mb-2" htmlFor="password">Contraseña:</label> <input name="password" value={employee.password} onChange={handleInputChange} placeholder="Contraseña" type="password" className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" id="password" /> </div> <button onClick={handleSubmit} className="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2" > Añadir Administrador </button> </div> {/* Lista de administradores */} <h2 className="text-2xl font-semibold mb-6">Lista de Empleados</h2> <div className="bg-white p-6 rounded-lg shadow-md overflow-x-auto"> {employeesList.length === 0 ? ( <p className="text-gray-500">No hay administradores registrados aún.</p> ) : ( <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Nombre de usuario </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Email </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {employeesList.filter(e => e.rol === 'Admin').map((e, index) => ( <tr key={index}> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm font-medium text-gray-900">{e.username}</div> </td> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm text-gray-500">{e.email}</div> </td> </tr> ))} </tbody> </table> )} </div> </div> ); }; export default AddEmployee;
const { Schema, model } = require('mongoose'); const Joi = require('joi'); const { handleMongooseErrors } = require('../helper'); const emailRegexp = /^[a-z0-9]+@[a-z]+\.[a-z]{2,3}$/; const userSchema = new Schema( { name: { type: String, required: true, }, email: { type: String, match: emailRegexp, unique: true, required: true, }, password: { type: String, minlength: 6, required: true, }, token: { type: String, default: '', }, avatar_url: { type: String, required: true, }, verification_code: { type: String, required: true, }, verify: { type: Boolean, default: false, }, }, { versionKey: false, timestamps: true }, ); userSchema.post('save', handleMongooseErrors); const registerSchema = Joi.object({ name: Joi.string().required(), email: Joi.string().pattern(emailRegexp).required(), password: Joi.string().min(6).required(), }); const loginSchema = Joi.object({ email: Joi.string().pattern(emailRegexp).required(), password: Joi.string().min(6).required(), }); const verifySchema = Joi.object({ email: Joi.string().pattern(emailRegexp).required(), }); const schemas = { registerSchema, loginSchema, verifySchema, }; const User = model('user', userSchema); module.exports = { User, schemas, };
import { FastifyPluginAsync } from "fastify"; import { API_KEY, BASE_URL } from "../../config"; import { appIDSchema } from "./schema"; const lookups: FastifyPluginAsync = async (fastify, _opts): Promise<void> => { // Route to handle GET requests to retrieve app ID fastify.get("/appid", appIDSchema, async (_request, reply) => { try { // Send a GET request to the external API to retrieve the app ID const response = await fetch(`${BASE_URL}/config/entity`, { method: "GET", headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", }, }); // Check if the request was successful if (response.ok) { // If successful, parse the response body as JSON const appid = await response.json(); // Return the retrieved app ID return appid; } else { // If unsuccessful, throw an error with the response status throw new Error(`Failed to retrieve app ID: ${response.statusText}`); } } catch (error: any) { // Handle errors console.error("Error retrieving app ID:", error); // Log the error for debugging // Return a generic error message with a 500 status code return reply.status(500).send({ message: "Internal server error" }); } }); }; export default lookups;
<template> <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible"> <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px"> <el-form-item label="评论人" prop="userId"> <el-input v-model="dataForm.userId" placeholder="评论人"></el-input> </el-form-item> <el-form-item label="评论人" prop="userName"> <el-input v-model="dataForm.userName" placeholder="评论人"></el-input> </el-form-item> <el-form-item label="评论头像" prop="cover"> <el-input v-model="dataForm.cover" placeholder="评论头像"></el-input> </el-form-item> <el-form-item label="评论内容" prop="content"> <el-input v-model="dataForm.content" placeholder="评论内容"></el-input> </el-form-item> <el-form-item label="父评论" prop="parentId"> <el-input v-model="dataForm.parentId" placeholder="父评论"></el-input> </el-form-item> <el-form-item label="游戏id" prop="gameId"> <el-input v-model="dataForm.gameId" placeholder="游戏id"></el-input> </el-form-item> <el-form-item label="是否热门,默认为0" prop="isHot"> <el-input v-model="dataForm.isHot" placeholder="是否热门,默认为0"></el-input> </el-form-item> <el-form-item label="排序" prop="sort"> <el-input v-model="dataForm.sort" placeholder="排序"></el-input> </el-form-item> <el-form-item label="" prop="createTime"> <el-input v-model="dataForm.createTime" placeholder=""></el-input> </el-form-item> <el-form-item label="" prop="updateTime"> <el-input v-model="dataForm.updateTime" placeholder=""></el-input> </el-form-item> </el-form> <span slot="footer" class="dialog-footer"> <el-button @click="visible = false">取消</el-button> <el-button type="primary" @click="dataFormSubmit()">确定</el-button> </span> </el-dialog> </template> <script> export default { data () { return { visible: false, dataForm: { id: 0, userId: '', userName: '', cover: '', content: '', parentId: '', gameId: '', isHot: '', sort: '', createTime: '', updateTime: '' }, dataRule: { userId: [ { required: true, message: '评论人不能为空', trigger: 'blur' } ], userName: [ { required: true, message: '评论人不能为空', trigger: 'blur' } ], cover: [ { required: true, message: '评论头像不能为空', trigger: 'blur' } ], content: [ { required: true, message: '评论内容不能为空', trigger: 'blur' } ], parentId: [ { required: true, message: '父评论不能为空', trigger: 'blur' } ], gameId: [ { required: true, message: '游戏id不能为空', trigger: 'blur' } ], isHot: [ { required: true, message: '是否热门,默认为0不能为空', trigger: 'blur' } ], sort: [ { required: true, message: '排序不能为空', trigger: 'blur' } ], createTime: [ { required: true, message: '不能为空', trigger: 'blur' } ], updateTime: [ { required: true, message: '不能为空', trigger: 'blur' } ] } } }, methods: { init (id) { this.dataForm.id = id || 0 this.visible = true this.$nextTick(() => { this.$refs['dataForm'].resetFields() if (this.dataForm.id) { this.$http({ url: this.$http.adornUrl(`/game/content/info/${this.dataForm.id}`), method: 'get', params: this.$http.adornParams() }).then(({data}) => { if (data && data.code === 0) { this.dataForm.userId = data.content.userId this.dataForm.userName = data.content.userName this.dataForm.cover = data.content.cover this.dataForm.content = data.content.content this.dataForm.parentId = data.content.parentId this.dataForm.gameId = data.content.gameId this.dataForm.isHot = data.content.isHot this.dataForm.sort = data.content.sort this.dataForm.createTime = data.content.createTime this.dataForm.updateTime = data.content.updateTime } }) } }) }, // 表单提交 dataFormSubmit () { this.$refs['dataForm'].validate((valid) => { if (valid) { this.$http({ url: this.$http.adornUrl(`/game/content/${!this.dataForm.id ? 'save' : 'update'}`), method: 'post', data: this.$http.adornData({ 'id': this.dataForm.id || undefined, 'userId': this.dataForm.userId, 'userName': this.dataForm.userName, 'cover': this.dataForm.cover, 'content': this.dataForm.content, 'parentId': this.dataForm.parentId, 'gameId': this.dataForm.gameId, 'isHot': this.dataForm.isHot, 'sort': this.dataForm.sort, 'createTime': this.dataForm.createTime, 'updateTime': this.dataForm.updateTime }) }).then(({data}) => { if (data && data.code === 0) { this.$message({ message: '操作成功', type: 'success', duration: 1500, onClose: () => { this.visible = false this.$emit('refreshDataList') } }) } else { this.$message.error(data.msg) } }) } }) } } } </script>
const Joi = require('joi'); const express = require('express') const helmet = require('helmet') const morgan = require('morgan') const config = require('config') const stratDebug = require('debug')('app:start') const dbDebug = require('debug')('app:db') const pug = require('pug') const logger = require('./logger') const users = require('./routes/users') const home = require('./routes/home') const about = require('./routes/aboutus') const app = express(); app.use(express.json()) app.use(express.urlencoded({extended:true})) app.use(express.static('public')) app.use(logger); app.use(function (req,res,next) { console.log("Middleware2"); next() }); app.use(helmet()) app.use('/api/users',users) app.use('/',home) app.use('/aboutus',about) if(app.get('env') == 'production'){ app.use(morgan('tiny')) } app.set('view engine','pug') app.set('views','./views') console.log(`NODE ENV ${process.env.NODE_ENV}`); console.log(`get ENV ${app.get('env')}`); console.log(`config data ${config.get('name')}`); console.log(`config data ${config.get('mail.host')}`); console.log(`config data ${config.get('mail.password')}`); stratDebug('app start'); dbDebug('db CONNECTED'); const port = process.env.PORT || 3000; app.listen(port,() => console.log(`listing on ${port}`))
package com.example.schedule; import java.time.LocalDateTime; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; /** * @author: BYDylan * @date: 2023/11/7 * @description: 动态设置定时任务,后续可通过数据库或接口形式更新 cron 变量 */ @Slf4j @Component public class DynamicSchedule implements SchedulingConfigurer { @Value("${cron.dynamic}") private String cron; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { // 动态使用cron表达式设置循环间隔 taskRegistrar.addTriggerTask(() -> log.info("current time: {}", LocalDateTime.now()), triggerContext -> { // 使用CronTrigger触发器,可动态修改cron表达式来操作循环规则 CronTrigger cronTrigger = new CronTrigger(cron); return cronTrigger.nextExecution(triggerContext); }); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Forms</title> </head> <body> <form onsubmit="savetoCrudstorage(event)"> <h2 style="text-align:center;color:tomato">Book a Call</h2> <h5 style="text-align:center">Book a call slot and out representative will call you within 1hr of selected time</h5> <hr width="100%" size="4px"> <div class="wrapper"> <div class="input"> <label for:"fullname" style="text-align:left">Name:</label><br> <input id="name" type="text" required><br><br> <label for:"email">Email:</label><br> <input type="email" id="emailID" required><br><br> <label for="quantity">Phone:</label><br> <input id="phone" required><br><br> <label for="call-time">Time for Call:</label><br> </div> <div class="date"> <input id="date" type="date" > <input id="time" type="time" > <br><br> <button>Submit</button> </div> </div> </form> <ul id="ul"> </ul> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script> <script src="appointment_app.js"></script> </body> </html> function savetoCrudstorage(event) { event.preventDefault(); let userDetails = { Name: document.getElementById("name").value, Email: document.getElementById("emailID").value, Number: document.getElementById("phone").value, Date: document.getElementById("date").value, Time: document.getElementById("time").value, }; axios .post( "https://crudcrud.com/api/0253131b10474448a8dcf21e1e6ea812/mudassir", userDetails ) .then((response) => { showNewUseronScreen(response.data); }) .catch((err) => console.log(err)); } window.addEventListener("DOMContentLoaded", () => { axios .get("https://crudcrud.com/api/0253131b10474448a8dcf21e1e6ea812/mudassir") .then((response) => { for (let i = 0; i < response.data.length; i++) { showNewUseronScreen(response.data[i]); } }) .catch((err) => console.log(err)); }); function showNewUseronScreen(user) { document.getElementById("emailID").value = ""; document.getElementById("name").value = ""; document.getElementById("phone").value = ""; document.getElementById("date").value = ""; document.getElementById("time").value = ""; const d = document.getElementById("ul"); const li = `<li id="${user._id}"> ${user.Name} - ${user.Email} - ${user.Number} - ${user.Date} - ${user.Time} <button onclick = "editUser('${user.Email}','${user.Name}','${user.Number}','${user.Date}','${user.Time}','${user._id}')"> Edit </button> <button onclick = "deleteUser('${user._id}')"> Delete </button> </li>`; d.innerHTML = d.innerHTML + li; } function removeUserfromScreen(userId) { let parent = document.getElementById("ul"); let child = document.getElementById(userId); if (child) { parent.removeChild(child); } } function deleteUser(userId) { axios .delete( `https://crudcrud.com/api/0253131b10474448a8dcf21e1e6ea812/mudassir/${userId}` ) .then((response) => { removeUserfromScreen(userId); }); } function editUser(Email, Name, Number, Date, Time, userId) { document.getElementById("emailID").value = Email; document.getElementById("name").value = Name; document.getElementById("phone").value = Number; document.getElementById("date").value = Date; document.getElementById("time").value = Time; deleteUser(userId); }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>Nuevo préstamo</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous" /> </head> <body class="pt-5"> <header th:insert="~{headertemplate :: header}"></header> <div class="container pt-5"> <h1>Crear préstamo</h1> <hr /> <div class="row justify-content-center"> <form action="#" method="post" th:action="@{/prestamos/save_prestamo}"> <div class="mb-3"> <label for="lector" class="form-label">Lectores</label> <select class="form-select form-select-lg" name="lector" id="lector"> <option selected value="-1">Escoge un lector</option> <option th:each=" lector : ${lectores}" th:value="${lector.Id}" th:text="'Lector: ' + ${lector.nombre} + ' | ' + ${lector.Id}" ></option> </select> </div> <div class="mb-3"> <label for="libro" class="form-label">Libro</label> <select class="form-select form-select-lg" name="libro" id="libro"> <option selected value="-1">Escoge un libro</option> <option th:each=" libro : ${libros}" th:value="${libro.Id}" th:text="'Libro: ' + ${libro.titulo} + ' | Ejemplares Disponibles: ' + ${libro.countEjemplaresDisponibles}" ></option> </select> </div> <button type="submit" class="btn btn-primary">Guardar</button> <a class="btn btn-dark text-center mt-2 m-3 mb-3" th:href="@{/}" >Cancelar</a > </form> </div> </div> <footer th:insert="~{footertemplate :: footer}"></footer> </body> </html>
@extends('layouts.app') @section('content') <div class="container"> <!-- Outer Row --> <div class="row justify-content-center"> <div class="col-xl-10 col-lg-12 col-md-9"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <!-- Nested Row within Card Body --> <div class="row"> <div class="col-lg-6 d-none d-lg-block bg-login-image"></div> <div class="col-lg-6"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Selamat datang kembali!</h1> </div> <form method="POST" action="{{ route('login') }}" class="user"> @csrf <div class="form-group"> <input id="email" type="email" class="form-control form-control-user @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus placeholder="Masukkan Alamat Email"> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div class="form-group"> <input id="password" type="password" class="form-control form-control-user @error('password') is-invalid @enderror" name="password" required autocomplete="current-password" placeholder="Masukkan Password"> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div class="form-group"> <div class="custom-control custom-checkbox small"> <input type="checkbox" class="custom-control-input" id="customCheck"> <label class="custom-control-label" for="customCheck">Ingat saya</label> </div> </div> <button type="submit" class="btn btn-primary btn-user btn-block"> Login </button> <hr> <a href="" class="btn btn-google btn-user btn-block"> <i class="fab fa-google fa-fw"></i> Login Dengan Google </a> </form> <div class="text-center mt-3"> <a class="small" href="{{ route('password.request') }}"> {{ __('Lupa password anda?') }} </a> </div> <div class="text-center"> <a class="small" href="{{ route('register') }}">Buat akun!</a> </div> </div> </div> </div> </div> </div> </div> </div> </div> @endsection
<!DOCTYPE html> <html lang="en" ng-app="toDoApp"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>AngularJs To Do App</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional bootstrap theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <!-- Custom ToDo CSS --> <link rel="stylesheet" href="styles.css"> </head> <body ng-controller="MainCtrl"> <!-- emmet shortcut - .container>.row>.col-md-6.md-offset-3 --> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>Angular To Do App</h1> <br> <div class="well"> <form name="newTodoForm" ng-submit="addTodo()" class="form-group"> <label>What do you need to do</label> <br> <input type="text" placeholder="Add Your Task" ng-model="newFormData.title" class="form-control"required> <br> <label>What kind of todo is this?</label> <div ng-repeat="kind in kinds"> <input type="radio" ng-model="newFormData.newKind" ng-value="kind" class="form-control">{{kind}}<br> </div> <br> <button type="submit" class="btn btn-default" ng-disabled="newForm.$invalid">submit</button> <!-- ng-disabled="newForm.$invalid disables the submit button whatever was required isn't true yet --> </form> </div> <button ng-click="clearCompleted()"> Clear Completed </button> <h2>Current To Do List</h2> <h3 ng-pluralize count="todos.length" when="{'0': 'Add a task', 'one': 'You got one thing to do today, one...', 'other': 'Get going, you have {} things to do today'}"> </h3> <br> <br> <ul class="list-group"> <div ng-repeat="todo in todos" class="well"> <input type="checkbox" ng-model="todo.done"> <span ng-class="{ 'done' : todo.done }">&nbsp&nbsp{{todo.title}} -- posted on {{todo.created_at | date : 'EEEE, MMMM d, yyyy'}} category: {{todo.kind}} </span> </div> </ul> </div> </div> </div> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <!-- Bootstrap JS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <!-- Angularjs 1.4.4 --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script> <!-- Custom To Do JS --> <script type="text/javascript" src="app.js"></script> </body> </html>
import Document, { Head, Html, Main, NextScript } from 'next/document' import * as React from 'react' export default class MyDocument extends Document { render() { return ( <Html lang="en"> <Head> {/* PWA primary color */} {/* <meta name="theme-color" content={theme.palette.primary.main} /> */} <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ) } } // `getInitialProps` belongs to `_document` (instead of `_app`), // it's compatible with static-site generation (SSG). MyDocument.getInitialProps = async (ctx) => { // Resolution order // // On the server: // 1. app.getInitialProps // 2. page.getInitialProps // 3. document.getInitialProps // 4. app.render // 5. page.render // 6. document.render // // On the server with error: // 1. document.getInitialProps // 2. app.render // 3. page.render // 4. document.render // // On the client // 1. app.getInitialProps // 2. page.getInitialProps // 3. app.render // 4. page.render const originalRenderPage = ctx.renderPage // You can consider sharing the same emotion cache between all the SSR requests to speed up performance. // However, be aware that it can have global side effects. ctx.renderPage = () => originalRenderPage({ enhanceApp: (App: any) => function EnhanceApp(props) { return <App {...props} /> }, }) const initialProps = await Document.getInitialProps(ctx) return { ...initialProps, // Styles fragment is rendered after the app and page rendering finish. } }
LISP AND SYMBOLIC COMPUTATION: An International Journal, 5:4, 295-326, 1992 cfl 1992 Kluwer Academic Publishers - Manufactured in The Netherlands Syntactic Abstraction in Scheme* R. KENT DYBVIG ([email protected]) ROBERT HIEB# CARL BRUGGEMAN ([email protected]) Indiana University Computer Science Department Bloomington, IN 47405 (Received: August, 1992) (Revised: March, 1993) Keywords: Syntactic Abstraction, Macros, Program Transformation, Hygienic Macros Abstract. Naive program transformations can have surprising effects due to the interaction between introduced identifier references and previously existing identifier bindings, or between introduced bindings and previously existing references. These interactions can result in inadvertent binding, or capturing, of identifiers. A further complication is that transformed programs may have little resemblance to original programs, making correlation of source and object code difficult. This article describes an efficient macro system that prevents inadvertent capturing while maintaining the correlation between source and object code. The macro system allows the programmer to define program transformations using an unrestricted, general-purpose language. Previous approaches to the capturing problem have been inadequate, overly restrictive, or inefficient, and the problem of source-object correlation has been largely unaddressed. The macro system is based on a new algorithm for implementing syntactic transformations and a new representation for syntactic expressions. 1. Introduction A fundamental problem with traditional Lisp macro systems is that theydo not respect lexical scoping. When one expression is substituted for another, apparent bindings can be shadowed, resulting in unintended cap-ture of identifier references. The capturing problem, which is the source of many serious and difficult to find bugs, was first addressed by Kohlbecker,Friedman, Felleisen, and Duba [17]. To solve the capturing problem, they proposed a hygiene condition for macros and an elegant algorithm for en*This material is based on work supported by the National Science Foundation under grant number CCR-8803432.# Robert Hieb died in an automobile accident in April 1992. 296 DYBVIG, HIEB, AND BRUGGEMAN forcing this condition. A problem of equal practical importance is that Lisp macro systems can-not track source code through the macro-expansion process. Reliable correlation of source code and macro-expanded code is necessary if the compiler,run-time system, and debugger are to communicate with the programmer in terms of the original source program. The effort invested in compilersto correlate source and optimized object code [7, 14, 19] is wasted if the macro expander loses the correlation of source and expanded code beforecompilation begins. The correlation techniques applied to optimizing compilers do not extend to macro processors because these techniques requirethat the entire set of possible code transformations be known a priori. This article presents a macro system for Scheme that enforces hygieneautomatically while maintaining the correlation between source and object code. The macro system supports macros written in a general purpose pro-gramming language (Scheme) as well as macros written in high-level pattern languages such as extend-syntax [8, 15, 16] and syntax-rules [6].Local macros are referentially transparent in the sense that free identifiers appearing in the output of a local macro are scoped where the macro defini-tion appears [5]. No keywords are reserved; keywords for core forms such as lambda as well as macro keywords defined by the program can be rebound,either as new macro keywords or as variables. The system supports a controlled form of identifier capture that allows most common "capturing"macros to be written without violating the spirit of hygiene. The system is based on a new representation for syntactic expressions and a new algo-rithm for implementing syntactic transformations. The algorithm has at its core a modified version of the Kohlbecker, Friedman, Felleisen, and Duba(KFFD) algorithm. Unlike the KFFD algorithm, the new algorithm adds only constant overhead to the macro expansion process. Other systems have been proposed that share some of the features listedabove; many of these systems are described in the following section. No other system proposed to date, however,* enforces hygiene with constant overhead for macros written in a fullgeneral-purpose language, * solves the source-object correlation problem for variables and con-stants as well as structured expressions, * supplies a hygiene-preserving mechanism for controlled identifier cap-ture, * maintains referential transparency for all local macros, or* provides automatic syntax checking, input destructuring, and output restructuring for low-level macros. The remainder of this article is structured as follows. Section 2 discussesrelated work. Section 3 describes the interface to our macro system and SYNTACTIC ABSTRACTION IN SCHEME 297 examples of its use. Section 4 describes our algorithm. It begins with a vari-ant of the KFFD algorithm applied to abstract syntax, demonstrates how delaying part of the work of this algorithm reduces expansion overhead to aconstant, describes how controlled identifier captures are implemented, and shows how the correlation between source and object code is maintained.Section 5 summarizes the article and presents our conclusions. 2. Background Inadvertent capturing of identifier references occurs in one of two ways.First, an identifier binding introduced by a macro can capture references to identifiers of the same name within the subexpressions of the macro call.For example, consider the expression 1 (let ((t "okay"))(or2 #f t )) where or2 is a two-subexpression version of or to be expanded as follows (or2 e1 e2) ) (let ((t e1)) (if t t e2)) The expression should evaluate to "okay". A naive expansion of the ex-pression, however, produces (let ((t "okay"))(let ((t #f )) (if t t t ))) This evaluates to #f, since the reference to t in the macro call is capturedby the binding for t inserted during expansion. Second, an identifier reference introduced by a macro can be capturedby identifier bindings for the same name within the context of the macro call. For example, the expression (let ((if #f ))(or2 if "okay")) should also evaluate to "okay"2, but a naive expansion produces 1For readability, keywords are shown in boldface, variables in italic, and constants in Roman. 2This example presumes that keywords, such as if, are not reserved. 298 DYBVIG, HIEB, AND BRUGGEMAN (let ((if #f ))(let ((t if )) (if t t "okay"))) This results in an attempt to apply the nonprocedure #f, causing a run-time error. Various ad hoc techniques have been developed to help prevent unin-tended identifier captures. Capturing problems have been avoided by using generated names, special naming conventions, or the careful use of lexi-cal scoping combined with local procedure definitions. With each of these techniques, the programmer must do something special to avoid captur-ing, making capturing the default even though capturing is rarely desired. What is worse, macros that can cause unintended captures often do not doso immediately but lie dormant, waiting for an unsuspecting programmer to insert just the right (wrong!) identifier name into a macro call or itscontext. This insidious problem was first addressed by Kohlbecker, Friedman,Felleisen, and Duba [17], who present an algorithm in which the macro system automatically renames bound variables to prevent inadvertent cap-turing. The fundamental notion underlying the KFFD algorithm is alpha equivalence, which equates terms that differ only in the names of boundvariables. Alpha equivalence is the basis of Barendregt's variable convention, which assumes that the bound variables in terms used in definitionsand proofs are always chosen to be different from the free variables [2, page 26]. The KFFD algorithm respects the variable convention and thus issaid to be "hygienic." It traverses each expression after it is rewritten in order to give identifiers "time stamps," which are used during alpha con-version to distinguish identifiers that are introduced at different times in the transformation process. Unfortunately, since the algorithm completelytraverses each expression after it is rewritten, the time complexity of the macro expansion process increases from linear to quadratic with respect tothe number of expressions present in the source code or introduced during macro expansion. This is a serious problem for large programs that makeheavy use of macros, i.e., nearly all large Scheme programs. Clinger and Rees [5] present an algorithm for hygienic macro transfor-mations that does not have the quadratic time complexity of the KFFD algorithm. Their algorithm marks only the new identifiers introduced ateach iteration of the macro transformation process, rather than all of the identifiers as in the KFFD algorithm. Their system, however, allows macrosto be written only in a restricted high-level specification language in which it is easy to determine where new identifiers will appear in the outputof a macro. Since some macros cannot be expressed using this language, SYNTACTIC ABSTRACTION IN SCHEME 299 they have developed a low-level interface that requires new identifiers to bemarked explicitly [4]. Bawden and Rees [3] approach the capturing problem from a differentangle. Rather than providing automatic hygiene, their system forces the programmer to make explicit decisions about the resolution of free iden-tifier references and the scope of identifier bindings. Borrowing from the notion that procedures can be represented by closures that encapsulate lex-ical environments, they allow the programmer to create syntactic closures that encapsulate syntactic environments. The result is a system that allowsthe programmer to avoid unwanted capturing. Unlike traditional closures, however, syntactic closures and their environments must be constructedexplicitly. As a result, the mechanism is difficult to use and definitions created using it are hard to understand and verify. Hanson [13] alleviates thisproblem somewhat by demonstrating that the restricted high-level specification language supported by Clinger and Rees can be built on top of anextended version of syntactic closures. For a large class of macros, those that cannot be written in this high-level specification language, both the Clinger/Rees and syntactic closures approaches place responsibility for enforcing hygiene on the macro writerrather than on the underlying transformation algorithm. Furthermore, the pattern matching, destructuring, and restructuring facilities provided bythe specification language must be completely abandoned for the same class of macros. Both low-level interfaces are completely different in style andusage from the high-level specification language. Macros defined in the high-level specification language are referentiallytransparent [18] in the sense that a macro-introduced identifier refers to the binding lexically visible where the macro definition appears rather than tothe top-level binding or to the binding visible where the macro call appears. This extends hygiene to local macros, which were not supported by theKFFD algorithm. Like automatic hygiene, this transparency is not present in either the syntactic closures or the Clinger/Rees low-level interfaces. Griffin [12] describes a theory of syntactic definitions in the context ofinteractive proof development systems. He supports high-level definitions of derived notations in such a way that the definitions have certain formalproperties that make them easy to reason about. As a result, however, his system is very restrictive with respect to the sort of macros that can bedefined. Dybvig, Friedman, and Haynes [10, 11] address the source-object correla-tion problem, demonstrating that their proposed macro expansion protocol, expansion-passing style, is capable of maintaining source-object correlationeven in the presence of arbitrary user-defined macros. Their mechanism, however, does not enforce hygiene and handles only structured expressions; 300 DYBVIG, HIEB, AND BRUGGEMAN in particular, it does not handle variable references. The Revised4 Report on Scheme [6] includes an appendix that contains aproposed macro system for Scheme. The high-level system (syntax-rules) described therein is a version of Kohlbecker's extend-syntax [8, 15, 16]with the same restrictions imposed by Clinger and Rees [5]. The revisedreport appendix also describes a low-level system that, although it auto-matically preserves hygiene and referential transparency, requires manual destructuring of the input and restructuring of the output. The low-levelsystem described in the revised-report appendix was proposed by the authors of this article and is the predecessor of the system described here. Thenew system provides only a high-level pattern language, similar to the one provided by syntax-rules, which is nonetheless powerful enough to pro-vide the functionality of a "low-level" system while maintaining automatic hygiene, referential transparency, and source-object correlation. 3. The language The macro system supports the set of syntactic forms and procedures shownin Figure 1. Each of these forms and procedures is described in this section. All extended syntactic forms, or macro calls, take the form (keyword subform . . . ) where keyword is an identifier that names a macro. The syntax of eachsubform is determined by the macro and can vary significantly from macro to macro3. When the macro expander encounters a macro call, the macrocall expression is passed to the associated transformer to be processed. The expansion process is repeated for the result returned by the transformeruntil no macro calls remain. New syntactic forms, or macros, are defined by associating keywords withtransformation procedures, or transformers. Top-level syntactic definitions are created using define-syntax. (define-syntax keyword transformer-expression ) transformer-expression must be an expression that evaluates to a trans-former. The scope of syntactic definitions can be limited by using the lexical bind-ing forms let-syntax and letrec-syntax 4. In both cases keyword denotes 3Although not shown, macro calls can also take the form of improper lists. 4Also, internal define-syntax forms may appear wherever internal define forms are permitted, in which case the definitions behave as if introduced by letrec-syntax. SYNTACTIC ABSTRACTION IN SCHEME 301 Macro calls: (keyword subform . . . ) Macro definition and binding: (define-syntax keyword transformer-expression)(let-syntax ((keyword transformer-expression) . . . ) body)( letrec-syntax ((keyword transformer-expression) . . . ) body) Destructuring and restructuring: (syntax-case input-expression (literal . . . )(pattern fender expression) . . . )(syntax template) (syntax-object->datum syntax-object)(datum ->syntax-object identifier datum) Predicates: (identifier? object)(free-identifier=? identifier 1 identifier2)(bound-identifier=? identifier 1 identifier2) Figure 1: Syntactic forms and procedures provided by the macro system. new syntax in body; for letrec-syntax the binding scope also includes eachtransformer-expression. (let-syntax ((keyword transformer-expression ) . . . ) body )(letrec-syntax ((keyword transformer-expression ) . . . ) body ) At the language level, the fundamental characteristic of the macro sys-tem is the abstract nature of the arguments passed to macro transformers. The argument to a macro transformer is a syntax object. A syntax ob-ject contains contextual information about an expression in addition to its structure. This contextual information is used by the expander to maintainhygiene and referential transparency. Traditional Lisp macro systems use ordinary list-structured data to represent syntax. Although such list struc-tures are convenient to manipulate, crucial syntactic information cannot be maintained. For example, the ability to distinguish between different iden-tifiers that share the same name is of paramount importance. Information to allow these distinctions to be drawn is contained within each abstractsyntax object, so that transformers can compare identifiers according to their intended use as free identifiers, bound identifiers, or symbolic data. 302 DYBVIG, HIEB, AND BRUGGEMAN Syntax objects may contain other syntactic information that is not ofdirect interest to the macro writer. In our system, for example, syntax objects can contain source annotations that allow the evaluator to correlatethe final object code with the original source code that produced it. Or, as discussed in Section 4, syntax objects may contain information that forefficiency reasons has not yet been fully processed. Transformers decompose their input using syntax-case and rebuild theiroutput using syntax. A syntax-case expression takes the following form: (syntax-case input-expression (literal . . . ) clause . . . ) Each clause takes one of the following two forms: (pattern output-expression )(pattern fender output-expression ) syntax-case first evaluates input-expression, then attempts to match theresulting value with the pattern from the first clause. This value is usually a syntax object, but it may be any Scheme list structure. If the value matchesthe pattern, and there is no fender present, output-expression is evaluated and its value returned as the value of the syntax-case expression. If thevalue does not match the pattern, the value is compared against the next clause, and so on. An error is signaled if the value does not match any ofthe patterns. Patterns consist of list structures, identifiers, and constants. Each iden-tifier within a pattern is either a literal, a pattern variable, or an ellipsis. The identifier ... is an ellipsis. Any identifier other than ... is a literalif it appears in the list of literals (literal . . . ) in the syntax-case expression; otherwise it is a pattern variable. Literals serve as auxiliary keywords,such as else in case and cond expressions. List structure within a pattern specifies the basic structure required of the input, pattern variablesspecify arbitrary substructure, and literals and constants specify atomic pieces that must match exactly. Ellipses specify repeated occurrences ofthe subpatterns they follow. An input form F matches a pattern P if and only if* P is a pattern variable; or* P is a literal identifier and F is an identifier with the same binding;or * P is a pattern list (P1 . . . Pn) and F is a list of n forms that match P1 through Pn, respectively; or* P is an improper pattern list (P1 P2 . . . Pn . Pn+1) and F is a list orimproper list of n or more forms that match P1 through Pn, respec-tively, and whose nth "cdr" matches Pn+1; or SYNTACTIC ABSTRACTION IN SCHEME 303 * P is of the form (P1 . . . Pn Pn+1 ...) where F is a proper list of atleast n elements, the first n of which match P1 through Pn, respec-tively, and each remaining element of F matches Pn+1; or* P is a pattern datum5 and F is equal to P in the sense of the equal?procedure. If the optional fender is present, it serves as an additional constraint onacceptance of a clause. If the value of input-expression matches the pattern for a given clause, the corresponding fender is evaluated. If fender evaluatesto a true value, the clause is accepted; otherwise the clause is rejected as if the input had failed to match the pattern. Fenders are logically a partof the matching process, i.e., they specify additional matching constraints beyond the basic structure of an expression. Pattern variables contained within a clause's pattern are bound to the cor-responding pieces of the input value within the clause's fender (if present) and output-expression. Pattern variables occupy the same name space asprogram variables and keywords; bindings created by syntax-case can shadow (and be shadowed by) program variable and keyword bindings aswell as other pattern variable bindings. Pattern variables, however, can be referenced only within syntax expressions. Scheme syntax expressionshave the following form: (syntax template ) A syntax form returns a Scheme object in much the same way as quoteor quasiquote, with two important differences: the values of pattern variables appearing within template are inserted into template, and contextualsyntactic information contained within template is retained. All list structure within template remains ordinary list structure in the output, and allother items (including identifiers that do not represent pattern variables) are inserted without further interpretation. Contextual information asso-ciated with the values of inserted pattern variables and any nonlist items from the template is retained in the output. A template is a pattern variable, a literal identifier, a pattern datum, alist of subtemplates ( S1 . . . Sn), or an improper list (S1 S2 . . . Sn . T ). Eachsubtemplate Si is either a template or a template followed by an ellipsis.The final element T of an improper subtemplate list is a template. A subtemplate followed by an ellipsis expands into zero or more occur-rences of the subtemplate. The subtemplate must contain at least one pattern variable that was in a subpattern followed by an ellipsis in the in-put. (Otherwise, the expander could not determine how many times the 5A pattern datum is any nonlist, nonsymbol datum. 304 DYBVIG, HIEB, AND BRUGGEMAN subform should be repeated in the output.) This generalizes in a naturalway to nested ellipses [8]. There is one exception to this rule: the special template ( ... ... ) expands into .... This is used by macro-definingmacros to introduce ellipses into the defined macros. (See the definition of be-like-begin later in this section.) A pattern variable that occurs in a syntax template is replaced by thesubform it matched in the syntax-case expression that established the pattern variable's binding. Pattern variables that occur in subpatternsfollowed by one or more ellipses may occur only in subtemplates that are followed by (at least) as many ellipses. These pattern variables are replacedin the output by the subforms they matched in the input, distributed as specified. The definition for or below demonstrates the use of define-syntax,syntax-case, and syntax. (define-syntax or(lambda (x ) (syntax-case x ()(( ) (syntax #f )) (( e ) (syntax e ))(( e1 e2 e3 ... ) (syntax (let ((t e1 )) (if t t (or e2 e3 ... )))))))) The input patterns specify that the input must consist of the keyword6and zero or more subexpressions. If there is more than one subexpression (third clause), the expanded code must both test the value of the firstsubexpression and return the value if it is not false. In order to avoid evaluating the expression twice, the macro introduces a binding for thetemporary variable t. Because the expansion algorithm maintains hygiene automatically, this binding is visible only within code introduced by themacro and not within subforms of the macro call. The combined expressive power of syntax-case, syntax, and patternvariables renders a low-level macro system unnecessary. Unlike restricted rewrite-rule systems such as the Revised4 Report on Scheme syntax-rulessystem, input patterns are associated with output expressions rather than output templates. Arbitrary transformations may be performed since anoutput expression may be any Scheme expression. The only restriction is 6An underscore, which is an ordinary pattern variable, is used by convention for the keyword position to remind the macro writer and anyone reading the macro definition that the keyword position never fails to contain the expected keyword and need not be matched. SYNTACTIC ABSTRACTION IN SCHEME 305 that "raw" symbols cannot appear in the output of a transformer; identi-fiers must be introduced using syntax (or datum ->syntax-object, which isdescribed later). Unlike other low-level proposals, syntax-case relieves the programmer of the tedium of pattern matching, destructuring, and restruc-turing expressions, and it provides a level of syntax checking that macro programmers usually do not provide. The functionality of syntax-rules is subsumed by syntax-case. In fact,syntax-rules is easily defined as a macro: (define-syntax syntax-rules(lambda (x ) (syntax-case x ()(( (i ... ) ((keyword . pattern ) template ) ... ) (syntax (lambda (x )(syntax-case x (i ... ) ((dummy . pattern ) (syntax template ))... ))))))) The unreferenced pattern variable dummy is used in place of each keywordsince the Revised 4 Report on Scheme requires that the first position of each syntax-rules pattern be ignored. Just as the binding for t was not visiblein e2 e3 ... in or above, the pattern variable binding for dummy is not visible within template. Although the examples in this article employ syntax-case rather thansyntax-rules, some could use syntax-rules, and the choice of which to use in those cases is a matter of taste. Local macro definitions are referentially transparent in the sense dis-cussed in Section 2. Identifiers within a syntax expression, like ordinary identifier references, refer to the closest enclosing lexical binding. For ex-ample, (let ((/ +))(let-syntax ((divide (lambda (x ) (syntax-case x ()(( e 1 e2) (syntax (/ e1 e2)))))))(let ((/ *)) (divide 6 3)))) returns 9 since the / inserted by the macro divide refers to the outer letbinding, rather than 2, as would be the case if the reference were made global, or 18, as would be the case if the reference were captured by theinner let binding. 306 DYBVIG, HIEB, AND BRUGGEMAN It is an error to generate a reference to an identifier that is not presentwithin the context of a macro call, which can happen if the "closest enclosing lexical binding" for an identifier inserted into the output of a macrodoes not also enclose the macro call. For example, (let-syntax ((divide (lambda (x )(let ((/ +)) (syntax-case x ()(( e 1 e2) (syntax (/ e1 e2))))))))(let ((/ *)) (divide 2 1))) results in an "invalid reference" error, since the occurrence of / in theoutput of divide is a reference to the variable / bound by the let expression within the transformer. Symbolic names alone do not distinguish identifiers unless the identi-fiers are used only as symbolic data. The predicates free-identifier=? and bound-identifier=? are used to compare identifiers according to their in-tended use as free references or bound identifiers in a given context. The predicate free-identifier=? is used to determine whether two identifierswould be equivalent if they appeared as free identifiers in the output of a transformer. Because identifier references are lexically scoped, this means(free-identifier=? id 1 id 2) is true if and only if the identifiers id 1 and id 2refer to the same lexical or top-level binding7. Literal identifiers appearing in syntax-case patterns (such as else in case and cond) are matchedusing free-identifier=?. Similarly, the predicate bound-identifier=? is used to determine if twoidentifiers would be equivalent if they appeared as bound identifiers in the output of a transformer. In other words, if bound-identifier=? returns truefor two identifiers, then a binding for one will capture references to the other within its scope. In general, two identifiers are bound-identifier=? only ifboth are present in the original program or both are introduced by the same macro application (perhaps implicitly; see datum->syntax-object be-low). The predicate bound-identifier=? can be used for detecting duplicate identifiers in a binding construct, or for other preprocessing of a bindingconstruct that requires detecting instances of the bound identifiers. Two identifiers that are bound-identifier=? are also free-identifier=?, buttwo identifiers that are free-identifier=? may not be bound-identifier=?. An identifier introduced by a macro transformer may refer to the sameenclosing binding as an identifier not introduced by the transformer, but an introduced binding for one will not capture references to the other. 7All variables are assumed to have top-level bindings, whether defined (yet) or not. SYNTACTIC ABSTRACTION IN SCHEME 307 The definition for a simplified version of cond8 below demonstrates howan auxiliary keyword, in this case else, is handled using the literals list of syntax-case: (define-syntax cond(lambda (x ) (syntax-case x (else)(( (else e1 e2 ... )) (syntax (begin e1 e2 ... ))) (( (e0 e1 e2 ... )) (syntax (if e0 (begin e1 e2 ... ))))(( (e0 e1 e2 ... ) c1 c2 ... ) (syntax (if e0 (begin e1 e2 ... ) (cond c1 c2 ... ))))))) The definition above is equivalent to the following, which looks for elseusing free-identifier=? within a fender: (define-syntax cond(lambda (x ) (syntax-case x ()(( (e0 e1 e2 ... )) (and (identifier? (syntax e0 ))(free-identifier=? (syntax e0 ) (syntax else))) (syntax (begin e1 e2 ... )))(( (e0 e1 e2 ... )) (syntax (if e0 (begin e1 e2 ... )))) (( (e0 e1 e2 ... ) c1 c2 ... )(syntax (if e0 (begin e1 e2 ... ) (cond c1 c2 ... ))))))) The predicate identifier?, used prior to the free-identifier=? check in thefender, returns true if and only if its argument is an identifier. With either definition for cond, else is not recognized as an auxiliarykeyword if an enclosing lexical binding for else exists. For example, (let ((else #f ))(cond (else (display "oops")))) does not print "oops", since else is bound locally and is therefore notfree-identifier=? to the identifier else appearing in the definition for cond. 8The simplified version requires at least one output expression per clause and does not support the auxiliary keyword =>. 308 DYBVIG, HIEB, AND BRUGGEMAN The following definition for unnamed let uses bound-identifier=? to de-tect duplicate identifiers: (define-syntax let(lambda (x ) (define unique-ids?(lambda (ls ) (or (null? ls )(and (let notmem? ((x (car ls )) (ls (cdr ls ))) (or (null? ls )(and (not (bound-identifier=? x (car ls ))) (notmem? x (cdr ls )))))(unique-ids? (cdr ls )))))) (syntax-case x ()(( ((i v ) ... ) e1 e2 ... ) (if (unique-ids? (syntax (i ... )))(syntax ((lambda (i ... ) e1 e2 ... ) v ... )) (error (syntax-object->datum x )"duplicate identifier found")))))) For this macro to be completely robust, it should also ensure that thebound variables are indeed identifiers using the predicate identifier?. With the definition for let above, the expression (let ((a 3) (a 4)) (+ a a )) causes a "duplicate identifier found" error, whereas (let-syntax ((dolet (lambda (x )(syntax-case x () (( b) (let ((a 3) (b 4)) (+ a b)))))))(dolet a )) evaluates to 7, since the identifier a introduced by dolet and the identifiera extracted from the macro call are not bound-identifier=?. It is also possible to compare identifiers intended to be used as symbolicdata. The procedure syntax-object ->datum strips all syntactic informationfrom a syntax object and returns the corresponding Scheme "datum." Identifiers stripped in this manner are converted to their symbolic names, whichcan then be compared with eq?. Thus, symbolic-identifier=? might be defined as follows: SYNTACTIC ABSTRACTION IN SCHEME 309 (define symbolic-identifier=?(lambda (x y ) (eq? (syntax-object->datum x )(syntax-object ->datum y )))) Two identifiers that are free-identifier=? are symbolic-identifier=?; in orderto refer to the same binding, two identifiers must have the same name. The converse is not always true. It is occasionally useful to define macros that introduce bindings for iden-tifiers that are not supplied explicitly in each macro call. For example, we might wish to define a loop macro that binds the variable exit to an es-cape procedure within the loop body. Strict automatic hygiene, however, would prevent an introduced binding for exit from capturing references toexit within the loop body. Previous hygienic systems have provided mechanisms for explicit capturing, typically by allowing a macro to insert a symbolinto an expansion as if it were part of the original source program [17]. Unfortunately, this means that macros cannot reliably expand into macrosthat use explicit capturing. Our system provides a more consistent way to accommodate such macros.A macro may construct implicit identifiers that behave as if they were present in the macro call. Implicit identifiers are created by providing theprocedure datum ->syntax-object with a template identifier and a symbol.The template identifier is typically the macro keyword itself, extracted from the input, and the symbol is the symbolic name of the identifier tobe constructed. The resulting identifier behaves as if it were introduced when the template identifier was introduced. For example, the loop macromentioned above may be defined as follows: (define-syntax loop(lambda (x ) (syntax-case x ()((k e1 ... ) (with-syntax ((exit-id (datum->syntax-object(syntax k ) 'exit)))(syntax (call-with-current-continuation (lambda (exit-id )(let f () e1 ... (f )))))))))) (The with-syntax form is like let but introduces pattern variable bindingsrather than program variable bindings within the scope of its body. Its definition is shown later.) 310 DYBVIG, HIEB, AND BRUGGEMAN This same mechanism may be used to create aggregate identifier namestypically required when defining structure-definition constructs such as Common Lisp's defstruct [1] as macros. The procedure below constructsan implicit identifier using an aggregate name of the form "hstructure namei-hfield namei," from a structure name identifier s-id and a field nameidentifier f-id: (define aggregate-identifier(lambda (s-id f-id ) (let ((s-sym (symbol->string (syntax-object->datum s-id )))(f-sym (symbol ->string (syntax-object->datum f-id ))))(let ((sym (string ->symbol (string-append s-sym "-" f-sym ))))(datum ->syntax-object s-id sym ))))) A defstruct form would expand into a set of definitions, including accessorsfor each field whose names are constructed using aggregate-identifier. As its name implies, datum->syntax-object can convert an arbitrary da-tum into a syntax object, i.e., the second argument need not be a symbol. Converting a nonsymbol datum into a syntax object has the effect oftreating each symbol contained within the datum as an implicit identifier. The convenience of this feature is illustrated by the following definition forinclude, an expand-time version of load. (include "filename") expands into a begin expression containing the expressions found in the file namedby "filename". (define-syntax include(lambda (x ) (define read-file(lambda (fn k ) (let ((p (open-input-file fn )))(let f ((x (read p))) (if (eof-object? x )(begin (close-input-port p) '()) (cons (datum->syntax-object k x )(f (read p)))))))) (syntax-case x ()((k filename ) (let ((fn (syntax-object->datum (syntax filename ))))(with-syntax (((exp ... ) (read-file fn (syntax k )))) (syntax (begin exp ... )))))))) The definition for include uses datum->syntax-object to place the expres-sions read from "filename" into the proper lexical context so that identifier SYNTACTIC ABSTRACTION IN SCHEME 311 references and definitions within those expressions are scoped where theinclude form appears. For example, if the file "f-def.ss" contains the expression (define f (lambda () x )), the expression (let ((x "okay"))(include "f-def.ss") (f )) evaluates to "okay". The with-syntax expression used in the loop and include examplesabove is the most convenient mechanism for establishing pattern variable bindings when no syntax matching is required. syntax-case can always beused instead, although doing so results in less readable code as illustrated by the following version of loop: (define-syntax loop(lambda (x ) (syntax-case x ()((k e1 ... ) (syntax-case (datum->syntax-object (syntax k ) 'exit) ()(exit-id (syntax (call-with-current-continuation (lambda (exit-id )(let f () e1 ... (f ))))))))))) Given that syntax-case can be used in this manner, it is not surprisingthat with-syntax can be defined as a macro in terms of syntax-case: (define-syntax with-syntax(lambda (x ) (syntax-case x ()(( ((p e0 ) ... ) e1 e2 ... ) (syntax (syntax-case (list e0 ... ) ()((p ... ) (begin e1 e2 ... )))))))) A local macro may be written in terms of an existing syntactic form orprocedure of the same name using let-syntax. The following shows how one might restrict if expressions within a given expression to require the"else" (alternative) part: 312 DYBVIG, HIEB, AND BRUGGEMAN (let-syntax ((if (lambda (x )(syntax-case x () (( e1 e2 e3 ) (syntax (if e1 e2 e3 )))))))(if 1 2 3)) The expression above evaluates to 2. If the body were (if 1 2), however, asyntax error would be reported. Although the definition above looks simple enough, there are a few sub-tle ways in which an attempt to write this macro might go wrong. If letrec-syntax were used in place of let-syntax, the identifier if insertedinto the local macro's output would refer to the local if rather than the top-level if, and expansion would loop indefinitely. If the definition werespecified as (let-syntax ((if (lambda (x )(syntax-case x () ((if e1 e2 e3 ) (syntax (if e1 e2 e3 )))))))(if 1 2 3)) expansion would again loop indefinitely. The identifier if appearing at thestart of the pattern is treated as a pattern variable, since it is not listed in the literals list of the syntax-case expression. Thus, it is bound to thecorresponding identifier if from the input expression, which denotes the local binding of if. Placing if in the list of literals in an attempt to patchup the latter version does not work either: (let-syntax ((if (lambda (x )(syntax-case x (if ) ((if e1 e2 e3 ) (syntax (if e1 e2 e3 )))))))(if 1 2 3)) This causes syntax-case to compare the literal if in the pattern, whichis scoped outside of the let-syntax expression, with the if in the input expression, which is scoped inside the let-syntax. Since they do not referto the same binding, they are not free-identifier=?, and a syntax error results. The conventional use of underscore ( ) in place of the macro keywordhelps the macro writer to avoid situations like these in which the wrong identifier is matched against or inserted by accident. It is sometimes necessary for a macro that generates a macro definitionto insert one or more ellipses into the generated macro definition. This is done using the "escape sequence" ( ... ... ), as the simple example belowdemonstrates: SYNTACTIC ABSTRACTION IN SCHEME 313 (define-syntax be-like-begin(lambda (x ) (syntax-case x ()(( name ) (syntax (define-syntax name(lambda (x ) (syntax-case x ()(( e0 e1 ( ... ... )) (syntax (begin e0 e1 ( ... ... )))))))))))) With be-like-begin defined in this manner, (be-like-begin sequence)would have the same effect as (define-syntax sequence(lambda (x ) (syntax-case x ()(( e0 e1 ... ) (syntax (begin e0 e1 ... )))))) That is, a sequence expression would be equivalent to a begin expression. Additional syntax-case examples appear in [9]. 4. The algorithm 4.1. Traditional macro systems Traditional Lisp macro systems rely on programs and data having the samerepresentation, both textually and as internal structures. This shared representation is exploited not only for macro expansion but also for programevaluation; most Lisp systems provide an evaluation procedure so that programs can construct and execute programs. Consequently, the concretesyntax of Lisp is best seen as consisting of internal data structures rather than text. We assume a concrete syntax of expressions (e 2 Exp) defined asa data type consisting of an unspecified set of constants ( c 2 Const), sym-bols ( s 2 Sym), and structures built by pairing. The following signaturespecifies the abstract data type Exp: Sym ae ExpConst ae Exp cons : Exp * Exp ! Expcar : Exp ! Exp cdr : Exp ! Exppair? : Exp ! Bool sym? : Exp ! Bool 314 DYBVIG, HIEB, AND BRUGGEMAN expand : Exp * Env ! ExpandedExp expand(e, r) =case parse( e, r) of:constant( c) ! symbolic-data(c),variable( s) ! variable(s),application( e1, e2) ! application(expand(e1, r), expand(e2, r)),symbolic-data( e) ! symbolic-data(e),function( s, e) ! function(s, expand(e, r[s := Variable])),macro-application( s, e) ! expand (t(e), r) where t = r(s) Figure 2: A traditional macro-expansion algorithm. The subset Sym (symbols) of Exp are atomic elements. Const includes suchtraditional Lisp constants as booleans, numbers and the empty list. The variables e, s, and c range over Exp, Sym and Const, respectively. Theusual equations for elements of Exp hold: car (cons(e1, e2)) = e1cdr (cons( e1, e2)) = e2pair? (cons( e1, e2)) = Truesym? (cons( e1, e2)) = Falsepair? ( s) = Falsesym? ( s) = Truepair? ( c) = Falsesym? ( c) = False Figure 2 shows a traditional expansion algorithm for a simplified lan-guage. The expander is assumed to be part of a standard evaluation process where the value of a program e is obtained by eval (expand (e, rinit)). Thesymbols quote and lambda are bound to Special in the initial expansion environment rinit; all other symbols are bound to Variable. r 2 Env = Sym ! Transformer + {Variable} + {Special } t 2 Transformer = Exp ! Exp Macro expansion and parsing are inextricably intertwined in Lisp. Al-though Figure 2 shows the expander driving the parser, the relationship could just as well be reversed. The parser is shown in Figure 3. Patternmatching is used to hide the details of accessing the expression parts. The constructors (such as symbolic-data) used to communicate the output of theparser to the expander are not fully specified (their definition is trivial). SYNTACTIC ABSTRACTION IN SCHEME 315 parse : Exp * Env ! ParsedExp parse([[c]], r) = constant(c)parse([[ s]], r) = variable(s) if r(s) = Variableparse([[( e1 e2)]], r) = application(e1, e2) if e1 /2 Symparse([[( s e)]], r) = application(s, e) if r(s) = Variableparse([[( s e)]], r) = macro-application(s, e) if r(s) 2 Transformerparse([[(quote e)]], r) = symbolic-data(e) if r([[quote]]) = Specialparse([[(lambda s e)]], r) = function(s, e) if r([[lambda]]) = Special Figure 3: A traditional macro-expansion parser. The constructors of ExpandedExp are used to communicate the output ofthe expander to the evaluator. This expansion algorithm clearly has serious hygiene problems. It doesnot prevent free identifiers inserted by a macro application from being captured by program bindings, nor does it prevent bindings introduced bymacros from capturing free identifiers in the program. 4.2. A substitution-based macro system In the *-calculus, alpha conversion is used to circumvent hygiene problemscaused by program transformations. Since the actual name of a bound variable is immaterial, a binding expression can be converted into an equivalentexpression in which different names are used for the bound variables. Our algorithm uses alpha conversion to preserve hygiene during macro expan-sion. Whether an identifier is being used as symbolic data or as a program vari-able, pattern variable, or keyword cannot be determined until after macro expansion. Since the name of an identifier used as symbolic data is impor-tant, naive alpha conversion is not viable in traditional macro expansion algorithms. Our algorithm makes alpha conversion possible by abandoningthe traditional Lisp identification of variables and symbols. Instead, we introduce a new type of object, the identifier, which maintains both symbolicnames and binding names until an identifier's role in a program is determined. Alpha conversion is accomplished by replacing only the bindingnames of bound identifiers. Figure 4 shows the substitution-based macro-expansion algorithm. Theparser, shown in Figure 5, has been modified to operate on identifiers rather than symbols and to recognize several new forms: let-syntax, letrec-syntax, syntax, and plambda. To simplify the presentation, let-syntax 316 DYBVIG, HIEB, AND BRUGGEMAN expand : Exp * Env ! ExpandedExp expand(e, r) =case parse( e, r) of:variable( i) ! variable(resolve(i)),application( e1, e2) ! application(expand(e1, r), expand (e2, r)),symbolic-data( e) ! symbolic-data(strip(e)),syntax-data( e) ! symbolic-data(e),function( i, e) ! function(s, expand(subst(e, i, s), r0))where r0 = r[s := Variable] and s is fresh,pfunction( i, e) ! function(s, expand(subst(e, i, s), r0))where r0 = r[s := PVariable] and s is fresh,macro-application( i, e) ! expand(mark (t(mark(e, m)), m), r)where t = r(resolve(i)) and m is fresh,syntax-binding( i, e1, e2) ! expand(subst(e2, i, s), r[s := t])where t = eval (expand (e1, r)) and s is fresh,rec-syntax-binding( i, e1, e2) ! expand(subst(e2, i, s), r[s := t])where t = eval (expand (subst(e1, i, s), r))and s is fresh Figure 4: A substitution-based macro-expansion algorithm. and letrec-syntax are each restricted to a single binding. We have alsorestricted the subform of a syntax expression to a single identifier. If the identifier is a pattern variable, the syntax form evaluates to the value ofthe pattern variable; otherwise, the result is the identifier itself. The unrestricted version is a straightforward generalization. We have also chosento add plambda, which binds a single pattern variable within it's body, rather than syntax-case, which can be defined in terms of plambda andexpose, which is defined later. Pattern variables are bound to PVariable in the expansion environment. Env = Sym ! Transformer + {Variable} + {PVariable} + {Special } The function resolve is used by expand to complete alpha substitutionand determine the actual binding name of an identifier. The binding name is used in the output for program variables and to look up transformers forsyntactic keywords. When expanding a binding expression, subst replaces the binding name of the bound identifier with a fresh binding name. Todistinguish new identifiers introduced by a transformer, both input to the transformer and output from the transformer are freshly marked. Sinceidentical marks cancel each other, only new syntax retains the mark 9. The 9For the simplified language considered here it would be adequate to mark only the SYNTACTIC ABSTRACTION IN SCHEME 317 parse : Exp * Env ! ParsedExp parse([[c]], r) = symbolic-data(c)parse([[ i]], r) = variable(i) if r(resolve(i)) = Variableparse([[( e1 e2)]], r) = application(e1, e2) if e1 /2 Symparse([[( i e)]], r) = application(i, e)if r(resolve(i)) = Variableparse([[( i e)]], r) = macro-application(i, e)if r(resolve(i)) 2 Transformerparse([[(quote e)]], r) = symbolic-data(e) if r([[quote]]) = Specialparse([[(lambda i e)]], r) = function(i, e) if r([[lambda]]) = Specialparse([[(plambda i e)]], r) = pfunction(i, e)if r([[plambda]]) = Specialparse([[(syntax i)]], r) = syntax-data(i)if r(resolve(i)) 6= PVariableparse([[(syntax i)]], r) = variable(i) if r(resolve(i)) = PVariableparse([[(let-syntax ( i e1) e2)]], r) = syntax-binding(i, e1, e2)if r([[let-syntax]]) = Specialparse([[(letrec-syntax ( i e1) e2)]], r) = rec-syntax-binding(i, e1, e2)if r([[letrec-syntax]]) = Special Figure 5: A substitution-based macro-expansion parser. expander handles two sorts of data, symbolic (introduced by quote expres-sions) and syntactic (introduced by syntax expressions). Symbolic data is stripped of identifier substitutions and markings, whereas syntactic data isleft intact. Since mark and subst both generate elements of Exp, they can be treatedas constructors in an extended Exp algebra. mark : Exp * Mark ! Expsubst : Exp * Ident * Sym ! Exp Marks (m 2 Mark ) can be any countably infinite set. Identifiers (i 2 Ident )are a subset of the expanded Exp domain. An identifier is a symbol that has been subjected to zero or more marking and substitution operations.That is, an identifier is a symbol s, a marked identifier mark (i, m), or asubstitution subst( i1, i2, s). The intent of subst (e, i, s) is to replace thebinding name of the identifier i in the expression e with the symbol s. input to the transformer. This approach, however, would not work for more complex language constructs in which internal definitions are expanded separately and then recombined into a binding expression. It would also cause complexity problems for the delayed substitution mechanism described in Section 4.4. 318 DYBVIG, HIEB, AND BRUGGEMAN Since marking and substitution operations are of interest only insofar asthey affect identifiers, it is convenient to think of them as identity operations on constants and as being immediately propagated to the components of apair. For now, we assume that this is the case, although later we abandon this assumption in order to avoid complexity problems. mark (c, m) = c (1)subst ( c, i, s) = c (2)mark (cons( e1, e2), m) = cons(mark (e1, m), mark (e2, m)) (3)subst (cons( e1, e2), i, s) = cons(subst (e1, i, s), subst(e2, i, s)) (4) The function resolve is used to determine the binding name of an identi-fier. It resolves substitutions using the criterion that a substitution should take place if and only if both identifiers have the same marks and the samebinding name. resolve : Ident ! Symresolve( s) = sresolve(mark ( i, m)) = resolve(i) resolve(subst(i1, i2, s)) = 8!: s if marksof (i1) = marksof (i2)and resolve( i1) = resolve(i2)resolve( i1) otherwise The auxiliary function marksof determines an identifier's mark set: marksof : Ident ! MarkSetmarksof ( s) = ;marksof (mark ( i, m)) = marksof (i) [* {m}marksof (subst( i1, i2, s)) = marksof (i1) The operator [* forms an exclusive union, which cancels identical marks. The function strip simply undoes marking and substitution operations: strip : Exp ! Expstrip( s) = sstrip( c) = cstrip(cons( e1, e2)) = cons(strip(e1), strip(e2))strip(mark ( e, m)) = strip(e)strip(subst ( e, i, s)) = strip(e) Two identifiers i1 and i2 are free-identifier=? if and only if resolve(i1) =resolve( i2). Two identifiers i1 and i2 are bound-identifier=? if and only ifresolve(subst ( i1, i2, s)) = s for a fresh symbol s. SYNTACTIC ABSTRACTION IN SCHEME 319 So far the Exp algebra has been considered abstractly. A concrete alge-bra must ensure that the primitive accessors behave as specified. By virtue of equations (1)-(4), constants and pairs can use traditional representa-tions. Identifiers can be represented as distinguished triples of the form hs1, s2, {m . . .}i, where s1 is the symbolic name, s2 is the binding name,and { m . . .} is a (possibly empty) set of marks. This representation takesadvantage of strip requiring only the symbolic name of an identifier and resolve requiring only the final binding name of an identifier. Intermedi-ate substitutions and substitutions that cannot succeed can be discarded without affecting the behavior of the accessors. The mark set for an identi-fier i is just marksof (i). Marks can be represented as integers. Given thisrepresentation of identifiers, implementation of the primitive operators is straightforward. mark (i, m) adds its mark to the mark field of i unless itis already present, in which case it removes it. subst( i1, i2, s) replaces thebinding name field of i1 with s if the binding names and the marks of i1and i2 are the same, otherwise it leaves the identifier unchanged. strip(i)extracts the symbolic name of an identifier, whereas resolve( i) extracts thebinding name of an identifier. For example, consider the expansion of the expression (let ((if #f )) (or2 if t )) where or2 is the two-subexpression version of or from Section 2, definedas follows: (define-syntax or2(lambda (x ) (syntax-case x ()(( e1 e2 ) (syntax (let ((t e1 )) (if t t e2 ))))))) The expression should evaluate to the top-level value of the variable t, as-suming that t is bound at top-level. As the expansion unfolds, observe how substitution and marking prevent the binding for if in the source expressionfrom interfering with the macro's use of if and the macro's binding for t from interfering with the source expression's reference to t. For simplicity, we assume that let is handled directly by the expander;with a little more tedium we could first expand it into the corresponding lambda application. As described above, identifiers are represented as ordered triples: 320 DYBVIG, HIEB, AND BRUGGEMAN horiginal name, binding name, {mark . . . }i The original input is thus (hlet, let, {}i ((hif, if, {}i #f ))(hor2 , or2, {}i hif, if, {}i ht, t, {}i)) On the first step, since let has no binding other than its original bind-ing in the top-level environment, the bound variable from the outer let expression is replaced with the generated name G1, and the occurrence ofthe identifier within the scope of the let expression is replaced with a new identifier that contains both the generated and original names: (let ((G1 #f ))(hor2 , or2, {}i hif, G1, {}i ht, t, {}i)) Existence of this binding for G1 is also recorded in the lexical expand-timeenvironment. Next, the transformer for or2 is invoked, with identifiers in its input marked by mark m1: (hor2, or2, {m1}i hif, G1, {m1}i ht, t, {m1}i) The transformer for or2 produces (hlet, let, {}i ((ht, t, {}i hif, G1, {m1}i))(hif , if, {}i ht, t, {}i ht, t, {}i ht, t, {m1}i)) Next, within the output from the or2 transformer, identifiers not markedwith m1 are so marked while the m1 mark is removed from the others (sinceidentical marks cancel). (hlet, let, {m1}i ((ht, t, {m1}i hif, G1, {}i))(hif , if, {m1}i ht, t, {m1}i ht, t, {m1}i ht, t, {}i)) Only the binding name is relevant when an identifier's binding is determinedin the expand-time environment, so even though the mark m1 has beenattached to the identifier let, it still resolves to the top-level definition for let. Therefore, the bound identifier is replaced with a generated name andoccurrences of the identifier (with the same binding name and marks) are replaced with a new identifier within the scope of the let expression: SYNTACTIC ABSTRACTION IN SCHEME 321 (let ((G2 hif, G1, {}i))(hif , if, {m1}i ht, G2, {m1}i ht, G2, {m1}i ht, t, {}i)) Existence of this binding for G2 is also recorded in the lexical expand-timeenvironment, which still also holds a record of the binding for G1. Since G1 is recorded as a lexically bound variable in the expand-timeenvironment, the occurrence of hif , G1, {}i expands into a reference to G1.Thus, the output expression so far consists of (let ((G1 #f ))(let ((G2 G1)) (hif, if, {m1}i ht, G2, {m1}i ht, G2, {m1}i ht, t, {}i))) with the last line as yet unexpanded. Since the binding name of the iden-tifier hif , if, {m1}i is if, the last line is recognized as an if expression: (let ((G1 #f ))(let ((G2 G1)) (if ht, G2, {m1}i ht, G2, {m1}i ht, t, {}i))) Only the three variable references within this if expression remain to beexpanded. The binding name, G2, for the first and second of these is recorded as a lexical variable in the expand-time environment so both sim-ply expand into G2. The binding name for the third is t, which has no binding in the lexical expand-time environment; therefore it expands intoa top-level reference to t. Thus, the final output from the expander is (let ((G1 #f ))(let ((G2 G1)) (if G2 G2 t))) 4.3. Capturing The procedure datum->syntax-object must construct "implicit identifiers"that behave as if they had appeared in place of the template identifier when the template identifier was first introduced. That is, if datum->syntax-objectis called with an identifier i1 and a symbol s2, where the symbolic nameof i1 is s1, datum->syntax-object should create the identifier i2 that wouldhave resulted had s2 appeared in place of s1 in the original input. Thefollowing definition for imp-id captures this semantics: 322 DYBVIG, HIEB, AND BRUGGEMAN imp-id : Ident * Sym ! Identimp-id ( s1, s2) = s2imp-id (mark ( i, m), s) = mark (imp-id (i, s), m)imp-id (subst( i1, i2, s1), s2) = subst(imp-id (i1, s2), i2, s1) Supporting imp-id means that the representation of identifiers cannotomit failed substitutions, since the new accessor imp-id can observe them. Intermediate substitutions are still unimportant, however, and substitu-tions that fail because of mismatched marks can still be discarded. Thus the representation of identifiers as triples can be adapted by replacing thebinding name in an identifier triple with an environment that maps Sym to Sym. resolve must then apply the environment to the symbolic nameto get the binding name. imp-id ( i, s) simply builds a new identifier triplefrom s and the environment and marks from i. 4.4. A lazy substitution-based macro system The substitution-based macro system has the virtue of providing an in-tuitive, alpha substitution-based solution to the hygiene problem. Unfortunately, its implementation as suggested above is too expensive. Theexpense arises from the desire to make pairs transparent to hygiene operations. To maintain this transparency, every mark or substitution operationmust be propagated immediately to all the identifiers in an expression. Consequently, the overhead incurred by the hygienic algorithm at each ex-pansion step that uses these operations is proportional to the size of the expression, compared to constant overhead in a traditional system. This isprecisely the source of the complexity problem for the KFFD algorithm. We solve this problem by making substitutions and markings "lazy" onstructured expressions. Eventually, the work of propagating identifier operations must be done. If Exp were being used only as syntax, it would bereasonable to let structure accessors do the work. For instance, we could have car (mark (cons( e1, e2), m)) = mark (e1, m). Rather than alter the definitions of car and other accessors, however, weprovide an accessor that exposes the outermost structure of an expression by pushing identifier information down to its constituent parts: expose : Exp ! Expexpose( i) = iexpose(mark (cons( e1, e2), m)) = cons(mark (e1, m), mark (e2, m))etc. SYNTACTIC ABSTRACTION IN SCHEME 323 The functionality of expose is required only by syntax-case, which usesexpose to destructure the input value as far as necessary to match against the input patterns. It remains to construct a concrete Exp algebra. Expressions with pendingsubstitutions or marks can be represented as distinguished triples (wrapped expressions) of the form he, u, {m . . .}i, where e is an expression, u is anenvironment mapping Ident to Sym, and { m . . .} is a set of zero or moremarks. Pushing a substitution onto a wrapped expression involves updating the wrapped expression's environment with the new substitution. Mark-ing a wrapped expression involves adding the mark to the mark set of the wrapped expression or removing it if the mark is already in the set. Markingalso requires adding (removing) the mark to (from) the mark sets of each identifier in the wrapped expression's environment. Pairs, symbols, andconstants can use traditional representations. To avoid complexity problems, additional constraints must be imposed. In particular, the expressioncomponent of a wrapped expression must not be another wrapped expression. This property can be maintained by having expose combine marksets and environments when it pushes a wrapping onto another wrapped expression. Since marks "stick" only to new elements introduced by macrotransformers, a wrapped expression will have more than one mark only if it is generated by a macro whose definition was itself generated by a macro.In practice the mark field of a wrapped expression rarely has more than one mark. Consequently, handling marks is cheap and the complexity problemscaused by "eager" mark propagation are avoided. 4.5. Source-object correlation The lazy substitution model can be adapted easily to support source-objectcorrelation. We allow an expression to be annotated with information about its source by extending Exp with an additional constructor: source : Exp * Annotation ! Exp An annotation (a 2 Annotation) is an unspecified data structure that pro-vides information about the source of an expression, such as its location in a file. Source annotations can be passed along by the expander to the evaluator,where they can be used to provide debugging information. Thus we might add to the definition of expand : expand (source(e, a), r) = source(expand (e, r), a) The expander can also use source annotations to report errors it detects. 324 DYBVIG, HIEB, AND BRUGGEMAN Otherwise, operations ignore or drop source annotations. For instance: expose(source(e, a)) = expose(e)mark (source( e, a), m) = source(mark (e, m), a)id? (source( e, a)) = id? (e)resolve(source( i, a)) = resolve(i) Since expose drops annotations, they are invisible to procedures that needto examine the structure of an expression. Previously constants were the sole class of expressions unaffected by syntactic operations. Since constantscan also be annotated, however, they too must be "exposed" before they can be examined. Source annotations can be implemented by adding anotherfield to the wrapped expression structure of Section 4.4. 5. Conclusions The macro system described in this article, syntactic closures as augmentedby Hanson [3, 13], and the Clinger and Rees "explicit renaming" system [4, 5] are all compatible with the "high-level" facility (syntax-rules)described in the Revised 4 Report on Scheme [6]. Thus, the three systems differ primarily in the treatment of "low-level" macros. Our system extendsautomatic hygiene and referential transparency to the low level, whereas the other systems require explicit renaming of identifiers or construction ofsyntactic closures, which is tedious and error-prone. In addition, we have extended the automatic syntax checking, input destructuring, and outputrestructuring previously available only to high-level macros to the low level. In fact, our system draws no distinction between high- and low-level macros,so there is never a need to completely rewrite a macro originally written in a high-level style because it needs to perform some low-level operation.We have also provided a mechanism for correlating source and object code and introduced a hygiene-preserving mechanism for controlled identifiercapture, both of which are unique to our system. An important aspect of our work is its thoroughgoing treatment of identi-fiers. Since identifiers cannot be treated as simple symbolic data in hygienic systems, the macro writer must be given tools that respect their essentialproperties. We provide tools for introducing new identifiers in a hygienic and referentially-transparent manner, for constructing macros that implic-itly bind or reference identifiers, and for comparing identifiers according to their intended use as free identifiers, bound identifiers, or symbolic data. Although our work is designed to provide a macro system with automatichygiene for Scheme and other Lisp dialects, it could be adapted to languages in which programs and data do not share the same structure. An abstractsyntax object representing each syntactic construct in the language must SYNTACTIC ABSTRACTION IN SCHEME 325 be provided, along with appropriate accessors and constructors. Accessorswould be responsible for propagating identifier information to the subpieces of an abstract syntax object. The macro system described in this article has been implemented andthe implementation is available via "ftp" from cs.indiana.edu. Contact the first author for details. Acknowledgements: The authors would like to thank Dan Friedman andan anonymous reviewer for their helpful comments on earlier versions of this article. References 1. Steele Jr., Guy L. Common Lisp, the Language. Digital Press, secondedition (1990). 2. Barendregt, H. P. The Lambda Calculus: Its Syntax and Semantics.Elsevier Science Publishers, revised edition (1984). 3. Bawden, Alan and Rees, Jonathan. Syntactic closures. In Proceedings of the 1988 ACM Conference on Lisp and Functional Programming(July 1988) 86-95. 4. Clinger, William. Hygienic macros through explicit renaming. LISP Pointers, 4, 4 (1991). 5. Clinger, William and Rees, Jonathan. Macros that work. In Conference Record of the Eighteenth Annual ACM Symposium on Principles of Programming Languages (January 1991) 155-162. 6. Clinger, William, Rees, Jonathan, et al. The revised4 report on thealgorithmic language Scheme. LISP Pointers, 4, 3 (1991). 7. Coutant, D., Meloy, S., and Ruscetta, M. DOC: A practical approachto source-level debugging of globally optimized code. In Proceedings of the SIGPLAN '88 Conference on Programming Language Design and Implementation (July 1988) 125-134. 8. Dybvig, R. Kent. The Scheme Programming Language. Prentice-Hall(1987). 9. Dybvig, R. Kent. Writing Hygienic Macros in Scheme with SyntaxCase. Technical Report 356, Indiana Computer Science Department(June 1992). 326 DYBVIG, HIEB, AND BRUGGEMAN 10. Dybvig, R. Kent, Friedman, Daniel P., and Haynes, Christopher T.Expansion-passing style: Beyond conventional macros. In Proceedings of the 1986 ACM Conference on Lisp and Functional Programming(1986) 143-150. 11. Dybvig, R. Kent, Friedman, Daniel P., and Haynes, Christopher T.Expansion-passing style: A general macro mechanism. Lisp and Symbolic Computation, 1, 1 (1988) 53-75. 12. Griffin, Timothy G. Definition and Top-Down Refinement for Interactive Proof Development Systems. PhD thesis, Cornell University(August 1988). 13. Hanson, Chris. A syntactic closures macro facility. LISP Pointers, 4, 4(1991). 14. Hennessy, J. Symbolic debugging of optimized code. ACM Transactions on Programming Languages and Systems, 4, 3 (July 1982) 323-344. 15. Kohlbecker, Eugene. Syntactic Extensions in the Programming Language Lisp. PhD thesis, Indiana University, Bloomington (August1986). 16. Kohlbecker, Eugene and Wand, Mitchell. Macro-by-example: Deriv-ing syntactic transformations from their specifications. In Conference Record of the Fourteenth Annual ACM Symposium on Principles of Programming Languages (1987) 77-84. 17. Kohlbecker, Eugene, Friedman, Daniel P., Felleisen, Matthias, andDuba, Bruce. Hygienic macro expansion. In Proceedings of the 1986 ACM Conference on Lisp and Functional Programming (1986) 151-161. 18. Stoy, Joseph E. Denotational Semantics: The Scott-Strachey Approach to Programming Language Theory. MIT Press (1977). 19. Zellweger, P. An interactive high-level debugger for control-flow op-timized programs. In Proceedings of the ACM Software Engineering Symposium on High-Level Debugging (August 1983) 159-171.
import React from 'react'; import { render, screen } from '@testing-library/react'; import { describe, test, expect } from "@jest/globals"; import Box from '../src/box'; describe('Box Component', () => { test('should render children', () => { render(<Box>Test</Box>); expect(screen.getByText('Test')).toBeInTheDocument(); }); test('should apply data-space attribute', () => { const testSpaceValue = '1'; render(<Box space={testSpaceValue}>Test</Box>); screen.debug(); const box = screen.getByText('Test').closest('div'); expect(box).toHaveAttribute('data-space', testSpaceValue); }); test('should apply data-border attribute', () => { const testBorderValue = 'thin'; render(<Box border={testBorderValue}>Test</Box>); screen.debug(); const box = screen.getByText('Test').closest('div'); expect(box).toHaveAttribute('data-border', testBorderValue); }); test('does not apply data-space or data-border attributes when not provided', () => { render(<Box>Test</Box>); const box = screen.getByText('Test').closest('div'); expect(box).not.toHaveAttribute('data-space'); expect(box).not.toHaveAttribute('data-border'); }); test('passes additional props to the div element', () => { const title = "Box Title"; render(<Box title={title}>Test</Box>); const box = screen.getByText('Test').closest('div'); expect(box).toHaveAttribute('title', title); }); test('applies the correct class to the box', () => { render(<Box>Test</Box>); const box = screen.getByText('Test').closest('div'); expect(box).toHaveClass('box'); }); test('renders multiple children correctly', () => { render( <Box> <span>Child 1</span> <span>Child 2</span> </Box> ); expect(screen.getByText('Child 1')).toBeInTheDocument(); expect(screen.getByText('Child 2')).toBeInTheDocument(); }); test('applies custom styles when provided', () => { const customStyles = { backgroundColor: 'blue' }; render(<Box style={customStyles}>Test</Box>); const box = screen.getByText('Test').closest('div'); expect(box).toHaveStyle('background-color: blue'); }); // Other tests... });
<?php /** * Contains the progress-manager * * @package FrameWorkSolution * @subpackage progress * * Copyright (C) 2003 - 2012 Nils Asmussen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * This is the central class in the progress-package. It controls the progress. * By "progress" is meant a long task that can't be executed all in one and will * therefore be splitted into multiple parts which are each executable in a reasonable * time. * <br> * The manager takes a storage-object which is responsible for storing the current position. * Additionally you may (or should if this should make sense ;)) add listeners to get informed * about the current state of the operation. * * @package FrameWorkSolution * @subpackage progress * @author Nils Asmussen <[email protected]> */ final class FWS_Progress_Manager extends FWS_Object { /** * The storage-object for the position * * @var FWS_Progress_Storage */ private $_storage; /** * An array of listeners for this progress-manager * * @var array */ private $_listener = array(); /** * The number of operations per cycle * * @var integer */ private $_ops_per_cycle = 100; /** * The current position of the task * * @var int */ private $_position = -1; /** * The total number of operations * * @var int */ private $_total = false; /** * Indicates wether the task has been finished * * @var boolean */ private $_finished = false; /** * Constructor * * @param FWS_Progress_Storage $storage the storage-implementation */ public function __construct($storage) { parent::__construct(); if(!($storage instanceof FWS_Progress_Storage)) FWS_Helper::def_error('instance','storage','FWS_Progress_Storage',$storage); $this->_storage = $storage; } /** * Adds the given listener to the list so that it will be informed if something happened. * * @param FWS_Progress_Listener $l the listener */ public function add_listener($l) { if(!($l instanceof FWS_Progress_Listener)) FWS_Helper::def_error('instance','l','FWS_Progress_Listener',$l); $this->_listener[] = $l; } /** * @return integer the number of operations per cycle */ public function get_ops_per_cycle() { return $this->_ops_per_cycle; } /** * Sets the number of operations per cycle. * * @param integer $value the new value */ public function set_ops_per_cycle($value) { if(!FWS_Helper::is_integer($value) || $value <= 0) FWS_Helper::def_error('intgt0','value',$value); $this->_ops_per_cycle = $value; } /** * Returns the percentage of completion. This method should be called <b>after</b> * #run_task()! * * @return float the percentage of completion */ public function get_percentage() { if($this->_finished) return 100; if($this->_position == -1) return 0; return min(100,$this->_total > 0 ? (100 / ($this->_total / $this->_position)) : 100); } /** * @return int the current position (the number of already executed operations) */ public function get_position() { if($this->_position == -1) return 0; return $this->_position; } /** * Tests wether the progress is currently running, that means it has been started but is * not finished. * * @return boolean true if it is running */ public function is_running() { return !$this->_finished && $this->_storage->get_position() != -1; } /** * @return boolean wether the task is finished */ public function is_finished() { return $this->_finished; } /** * Runs the given task. * * @param FWS_Progress_Task $task the task to run */ public function run_task($task) { if(!($task instanceof FWS_Progress_Task)) FWS_Helper::def_error('instance','task','FWS_Progress_Task',$task); $position = $this->_storage->get_position(); if($position == -1) $position = 0; $this->_total = $task->get_total_operations(); $task->run($position,$this->_ops_per_cycle); // are we finished? if($position + $this->_ops_per_cycle >= $this->_total) { // clear up and inform the listeners $this->_position = -1; $this->_finished = true; $this->_storage->clear(); foreach($this->_listener as $l) $l->progress_finished(); } else { // store the position $this->_position = $position + $this->_ops_per_cycle; $this->_storage->store_position($this->_position); foreach($this->_listener as $l) $l->cycle_finished($position,$this->_total); } } protected function get_dump_vars() { return get_object_vars($this); } } ?>
import React from 'react'; import { useDispatch } from 'react-redux'; import { addToCart, removeToCart } from 'redux/carts/actions'; const PokemonsCardSmall = ({ pokemon }) => { const dispatch = useDispatch() const addOneQuantity = (e) => { e.stopPropagation() dispatch(addToCart(pokemon.pokemonId, pokemon.pokemonName, pokemon.pokemonColor, pokemon.pokemonPrice, pokemon.pokemonImage, 1)) } const removeOneQuantity = (e) => { e.stopPropagation() dispatch(removeToCart(pokemon.pokemonId, 1)) } const removePokemonToCart = (e) => { e.stopPropagation() dispatch(removeToCart(pokemon.pokemonId, pokemon.quantity)) } return ( <div className='PokemonsCardSmall'> <img src={`${pokemon.pokemonImage}`} alt={`small ${pokemon.pokemonName}`} /> <div className='item-infos'> <span className='price'>{pokemon.pokemonPrice}€</span> <span className='txt'>x</span> <div className='quantity'> <div className='remove-one link' onClick={e => removeOneQuantity(e)}><i className="fa-solid fa-minus"></i></div> <span>{pokemon.quantity}</span> <div className='add-one link' onClick={e => addOneQuantity(e)}><i className="fa-solid fa-plus"></i></div> </div> <span className='txt'>:</span> <span className='total-price'>{pokemon.pokemonPrice * pokemon.quantity}€</span> <div className='btn-remove-item link' onClick={e => removePokemonToCart(e)}> <i className="fa-solid fa-trash-can"></i> </div> </div> <div className='bg-overlay' style={{ background: `linear-gradient(to left, ${pokemon.pokemonColor}, white 75%)` }} /> </div> ); }; export default PokemonsCardSmall;
import 'dart:io'; import 'package:collection/collection.dart'; import '../utils/day_interface.dart'; import '../solutions/index.dart'; void main(List<String> arguments) { //read arguments and assign them to variables String inputDay = ''; String parts = ''; final String argSeperator = '='; //initialize day classes final days = <AbstractDay>[ Day06(), Day07(), ]; String getArgumentValue({required String argument}) { return argument.split(argSeperator).last; } void printAllSolution({required bool enabled}) { if (enabled) { for (final day in days) { day.printSolutions(); } return; } exit(0); } void printSolutionForDay(int day, DayPart part) { final daySolution = days.firstWhereOrNull((e) => e.day == day); if (daySolution == null) { print('No solution found for day $day'); } else { daySolution.printSolutions(part: part); } } // parse argument input if (arguments.isNotEmpty) { for (final argument in arguments) { if (argument.contains('day')) { inputDay = getArgumentValue(argument: argument); } if (argument.contains('part')) { parts = getArgumentValue(argument: argument); switch (parts) { case 'all': printAllSolution(enabled: true); break; case '1': printSolutionForDay(int.parse(inputDay), DayPart.part1); break; case '2': printSolutionForDay(int.parse(inputDay), DayPart.part2); break; } } } } else { print('No arguments found! please use this tool by like:\nday=6 part=all'); } }
""" Trainable lightning model classes and is mapped from :py:class:`fleet.torch_.schemas.TorchModelSpec` as well as auxiliary classes and functions. """ from typing import TYPE_CHECKING, Dict, List, Tuple, Union import lightning.pytorch as pl import networkx as nx import torch import torch.nn import fleet.exceptions from fleet import data_types from fleet.dataset_schemas import ColumnConfig from fleet.metrics import Metrics from fleet.model_builder.component_builder import AutoBuilder from fleet.model_builder.model_schema_query import get_dependencies from fleet.model_builder.optimizers import Optimizer from fleet.model_builder.schemas import TorchModelSchema from fleet.model_builder.utils import DataInstance, collect_args if TYPE_CHECKING: from fleet.dataset_schemas import TorchDatasetConfig def if_str_make_list(x: Union[str, List[str]]) -> List[str]: """Treat something that can be either str of List[str] as List[str] Converts str to single element lists Args: x: input Returns: List[str] """ if isinstance(x, str): return [x] return x def _adapt_loss_args( loss_fn: type, args: Tuple[torch.Tensor, torch.Tensor] ) -> Tuple[torch.Tensor, torch.Tensor]: # CrossEntropyLoss requires targets to be longs if isinstance( loss_fn, (torch.nn.CrossEntropyLoss), ): return (args[0], args[1].long()) # BCEWithLogitsLoss requires targets to be floats elif isinstance( loss_fn, (torch.nn.BCEWithLogitsLoss), ): return (args[0], args[1].float()) return args class CustomModel(pl.LightningModule): """Neural network model encoded by a ModelSchema""" dataset_config: "TorchDatasetConfig" optimizer: Optimizer loss_dict: dict metrics_dict: Dict[str, Metrics] def __init__( self, config: Union[TorchModelSchema, str], dataset_config: "TorchDatasetConfig", use_gpu=False, ): super().__init__() if isinstance(config, str): config = TorchModelSchema.parse_raw(config) self.save_hyperparameters({"config": config.json()}) layers_dict = {} self.config = config self.layer_configs = {layer.name: layer for layer in config.layers} for layer in config.layers: layer_instance = layer.create() if isinstance(layer_instance, AutoBuilder): layer_instance.set_from_model_schema( dataset_config=dataset_config, config=config, deps=list(get_dependencies(layer)), ) layers_dict[layer.name] = layer_instance self.dataset_config = dataset_config self._model = torch.nn.ModuleDict(layers_dict) self.graph = config.make_graph() self.topo_sorting = list(nx.topological_sort(self.graph)) self.loss_dict = {} self.metrics_dict = {} is_multilabel = len(dataset_config.target_columns) > 1 and all( [ target_column.column_type == "binary" for target_column in dataset_config.target_columns ] ) for target_column in dataset_config.target_columns: if not target_column.loss_fn: raise ValueError( f"{target_column.name}.loss_fn cannot be None" ) # This is safe as long ModelSchema was validated loss_fn_class = eval(target_column.loss_fn) self.loss_dict[target_column.name] = loss_fn_class() # Set up metrics for training and validation if target_column.column_type == "regression": self.metrics_dict[target_column.name] = Metrics( "regression", use_gpu=use_gpu ) else: self.metrics_dict[target_column.name] = Metrics( "multilabel" if is_multilabel else "multiclass", num_classes=len(target_column.data_type.classes.keys()), num_labels=len(dataset_config.target_columns) if is_multilabel else None, use_gpu=use_gpu, ) def set_optimizer(self, optimizer: Optimizer): """Sets parameters that only are given in training configuration Parameters that are set: - optimizer Args: training_request: """ self.optimizer = optimizer @staticmethod def _call_model(model, args): if isinstance(args, dict): return model(**args) if isinstance(args, list): return model(*args) return model(args) def forward(self, input_: DataInstance): # type: ignore """Forward pass of the model Runs the foward pass through the layers ordered by the topological sorting on self.topo_sorting attribute. If it finds a featurizer, ignores because it already evaluated by the dataset. If it finds a target column output (out_module), ignores on topo_sorting iteration then evaluate this for each target column on self.config.dataset.target_columns iteration. Args: input_: input data (x) Returns: dictionary with the output layers outputs """ out_layers = map( lambda x: x.out_module, self.dataset_config.target_columns ) for node_name in self.topo_sorting: if node_name not in self.layer_configs: continue # is a featurizer, already evaluated by dataset if node_name in out_layers: continue # is a target column output, evaluated separately layer = self.layer_configs[node_name] args = collect_args(input_, layer.forward_args.dict()) try: input_[layer.name] = CustomModel._call_model( self._model[node_name], args ) except Exception as exc: def shape(k): if isinstance(k, list): return str([shape(v) for v in k]) if hasattr(k, "shape"): return f"shape={k.shape}" elif hasattr(k, "__len__"): return f"len={len(k)}" else: return str(k) if isinstance(args, dict): args_shapes = [(k, shape(v)) for k, v in args.items()] else: args_shapes = [shape(v) for v in args] raise fleet.exceptions.LayerForwardError( ( "Failed to call a module on the batch:", f"node_name={node_name}", f"layer={layer}", # args shapes f"args-shapes={args_shapes}", ) ) from exc result = {} for target_column in self.dataset_config.target_columns: layer = self.layer_configs[target_column.out_module] args = collect_args(input_, layer.forward_args.dict()) result[target_column.name] = self._call_model( self._model[target_column.out_module], args ) return result def configure_optimizers(self): if not self.optimizer: raise ValueError( "using model without setting attributes from training request" ) assert self.optimizer.class_path.startswith( "torch.optim." ), "invalid start string for optimizer class_path" params = self.parameters() return self.optimizer.create(params) def test_step(self, batch, _batch_idx): predictions = self(batch) losses = {} for target_column in self.dataset_config.target_columns: args = ( predictions[target_column.name].squeeze(), batch[target_column.name].squeeze(), ) loss_fn = self.loss_dict[target_column.name] args = _adapt_loss_args(loss_fn, args) losses[target_column.name] = loss_fn(*args) self.log( f"test/loss/{target_column.name}", losses[target_column.name] ) loss = sum(losses.values()) return loss def validation_step(self, batch, _batch_idx): prediction: Dict[str, torch.Tensor] = self(batch) losses = {} for target_column in self.dataset_config.target_columns: args = ( prediction[target_column.name].squeeze(), batch[target_column.name].squeeze(), ) loss_fn = self.loss_dict[target_column.name] args = _adapt_loss_args(loss_fn, args) losses[target_column.name] = loss_fn(*args) metrics_dict = self.metrics_dict[ target_column.name ].get_validation_metrics( prediction[target_column.name], batch[target_column.name], target_column.name, ) self.log_dict( metrics_dict, batch_size=len(batch[target_column.name]), on_epoch=True, on_step=False, ) self.log( f"val/loss/{target_column.name}", losses[target_column.name] ) loss = sum(losses.values()) return loss def training_step(self, batch, _batch_idx): prediction: Dict[str, torch.Tensor] = self(batch) losses = {} for target_column in self.dataset_config.target_columns: args = ( prediction[target_column.name].squeeze(), batch[target_column.name].squeeze(), ) loss_fn = self.loss_dict[target_column.name] args = _adapt_loss_args(loss_fn, args) losses[target_column.name] = loss_fn(*args) metrics_dict = self.metrics_dict[ target_column.name ].get_training_metrics( prediction[target_column.name], batch[target_column.name], target_column.name, ) self.log_dict( { **metrics_dict, f"train/loss/{target_column.name}": losses[ target_column.name ], }, batch_size=len(batch[target_column.name]), on_epoch=True, on_step=False, ) loss = sum(losses.values()) return loss def _get_classes(self, target_column: ColumnConfig): classes = None if isinstance(target_column.data_type, data_types.CategoricalDataType): classes = list( map( lambda entry: entry[1], sorted(target_column.data_type.classes.items()), ) ) return classes def predict_step(self, batch, _batch_idx=0, dataloader_idx=0): """ Runs the forward pass using self.forward, then, for classifier models, normalizes the predictions using a non-linearity like sigmoid or softmax. """ predictions = self(batch) def prepare_tensor(tensor): item = tensor.detach().cpu().numpy().tolist() if not isinstance(item, list): return [item] return item for target_column in self.dataset_config.target_columns: if target_column.column_type == "multiclass": probs = prepare_tensor( torch.nn.functional.softmax( predictions[target_column.name].squeeze(), dim=-1 ) ) predictions[target_column.name] = { "probs": probs, "classes": self._get_classes(target_column), } elif target_column.column_type == "binary": probs = prepare_tensor( torch.sigmoid(predictions[target_column.name].squeeze()) ) predictions[target_column.name] = { "probs": probs, "classes": self._get_classes(target_column), } else: predictions[target_column.name] = prepare_tensor( predictions[target_column.name] ) return predictions
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Benchmark.h> #include <folly/init/Init.h> #include "velox/benchmarks/ExpressionBenchmarkBuilder.h" #include "velox/functions/lib/Re2Functions.h" #include "velox/functions/prestosql/registration/RegistrationFunctions.h" using namespace facebook; using namespace facebook::velox; using namespace facebook::velox::functions; using namespace facebook::velox::functions::test; using namespace facebook::velox::memory; using namespace facebook::velox; int main(int argc, char** argv) { folly::Init init(&argc, &argv); memory::MemoryManager::initialize({}); exec::registerStatefulVectorFunction("like", likeSignatures(), makeLike); // Register the scalar functions. prestosql::registerAllScalarFunctions(""); // exec::register ExpressionBenchmarkBuilder benchmarkBuilder; const vector_size_t vectorSize = 1000; auto vectorMaker = benchmarkBuilder.vectorMaker(); auto makeInput = [&](vector_size_t vectorSize, bool padAtHead, bool padAtTail) { return vectorMaker.flatVector<std::string>(vectorSize, [&](auto row) { // Strings in even rows contain/start with/end with a_b_c depends on // value of padAtHead && padAtTail. if (row % 2 == 0) { auto padding = std::string(row / 2 + 1, 'x'); if (padAtHead && padAtTail) { return fmt::format("{}a_b_c{}", padding, padding); } else if (padAtHead) { return fmt::format("{}a_b_c", padding); } else if (padAtTail) { return fmt::format("a_b_c{}", padding); } else { return std::string("a_b_c"); } } else { return std::string(row, 'x'); } }); }; auto substringInput = makeInput(vectorSize, true, true); auto prefixInput = makeInput(vectorSize, false, true); auto suffixInput = makeInput(vectorSize, true, false); benchmarkBuilder .addBenchmarkSet( "like_substring", vectorMaker.rowVector({"col0"}, {substringInput})) .addExpression("like_substring", R"(like(col0, '%a\_b\_c%', '\'))") .addExpression("strpos", R"(strpos(col0, 'a_b_c') > 0)"); benchmarkBuilder .addBenchmarkSet( "like_prefix", vectorMaker.rowVector({"col0"}, {prefixInput})) .addExpression("like_prefix", R"(like(col0, 'a\_b\_c%', '\'))") .addExpression("starts_with", R"(starts_with(col0, 'a_b_c'))"); benchmarkBuilder .addBenchmarkSet( "like_suffix", vectorMaker.rowVector({"col0"}, {suffixInput})) .addExpression("like_suffix", R"(like(col0, '%a\_b\_c', '\'))") .addExpression("ends_with", R"(ends_with(col0, 'a_b_c'))"); benchmarkBuilder .addBenchmarkSet( "like_generic", vectorMaker.rowVector({"col0"}, {substringInput})) .addExpression("like_generic", R"(like(col0, '%a%b%c'))"); benchmarkBuilder.registerBenchmarks(); benchmarkBuilder.testBenchmarks(); folly::runBenchmarks(); return 0; }
/** @format */ import { forwardRef } from "react"; import { useDispatch, useSelector } from "react-redux"; import Snackbar from "@mui/material/Snackbar"; import MuiAlert from "@mui/material/Alert"; import { clearSnackbar } from "../../store/actions/ui.action"; const Alert = forwardRef(function Alert(props, ref) { return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />; }); const WarningSnackbar = () => { const dispatch = useDispatch(); const { warningSnackbarMessage, warningSnackbarOpen } = useSelector( (state) => state.ui ); function handleClose() { dispatch(clearSnackbar()); } return ( <Snackbar open={warningSnackbarOpen} autoHideDuration={4000} onClose={handleClose} > <Alert onClose={handleClose} severity="warning" sx={{ width: "100%" }}> {warningSnackbarMessage} </Alert> </Snackbar> ); }; export default WarningSnackbar;
library(data.table) library(lubridate) library(readxl) source("private/hash_fn.r") source("R/outcome_functions.R") ### Script to build analysis dataset for table 5.2 in SAP - cohort of 'NHS111 contact' from outcomes found in previous script ## ID for demographics file used as single source of truth for attaching patient_ids on datasets demo_file_id <- "FILE0115974_2021-03-18-163613" # Read in NHS111 data -------------------------------------------------------- nhs111_data <- readRDS(file = paste("data/datasets/cohort", demo_file_id, "nhs111_data_ssot_dr_outcomes.rds", sep = "_")) nhs111_outcome_data <- readRDS(file = paste("data/datasets/cohort", demo_file_id, "nhs111_reduced_outcome_data.rds", sep = "_")) stopifnot(nhs111_data[, .N] == nhs111_outcome_data[, .N]) # NHS111 fields to retain ---------------------------------------------------- ## Add in NHS Pathways version before removing time as V19.8.3 went live at 10:30 on 2020-06-02 nhs111_data[call_datetime < as.POSIXct("2020-06-02 10:30:00", tz = "UTC"), pathway_iteration := 1L] nhs111_data[call_datetime >= as.POSIXct("2020-06-02 10:30:00", tz = "UTC"), pathway_iteration := 2L] unwanted_cols_single <- c("age_years", "called_back", "hospital_attended", "clinical_dx_code", "clinical_dx_Desc", "clinical_assessment_time", "final_symptom_code", "final_symptom_desc", "final_symptom_group", "first_pathway_selected", "non_clinical_dx_code", "non_clinical_dx_desc", "passed_to_clinician", "sex") wanted_cols_single <- setdiff(names(nhs111_data), unwanted_cols_single) nhs111_cohort_desc_data <- nhs111_data[, ..wanted_cols_single] setnames(nhs111_cohort_desc_data, setdiff(colnames(nhs111_cohort_desc_data), c("record_ID", "patient_id", "nhs111_priest_clinical_desc_grouping", "ssot_ethnicity_group", "ssot_ethnicity_desc", "ssot_iod19_decile", "ssot_gender", "ssot_core_priest_patient", "ssot_calculated_age", "dr_covid_related_death_code", "dr_death_within_7_days_contact", "dr_death_within_30_days_contact", "dr_died", "crit_care_cc_within_7_days_contact", "crit_care_cc_within_30_days_contact", "time_to_deterioration", "time_to_deterioration_lables", "any_adverse_outcome", "patient_call_record_order", "last_final_dx_desc", "last_priest_clinical_desc_grouping", "last_patient_call_record_order", "pathway_iteration")), paste("nhs111", setdiff(colnames(nhs111_cohort_desc_data), c("record_ID", "patient_id", "nhs111_priest_clinical_desc_grouping", "ssot_ethnicity_group", "ssot_ethnicity_desc", "ssot_iod19_decile", "ssot_gender", "ssot_core_priest_patient", "ssot_calculated_age", "dr_covid_related_death_code", "dr_death_within_7_days_contact", "dr_death_within_30_days_contact", "dr_died", "crit_care_cc_within_7_days_contact", "crit_care_cc_within_30_days_contact", "time_to_deterioration", "time_to_deterioration_lables", "any_adverse_outcome", "patient_call_record_order", "last_final_dx_desc", "last_priest_clinical_desc_grouping", "last_patient_call_record_order", "pathway_iteration")), sep = "_")) stopifnot(uniqueN(nhs111_cohort_desc_data[, record_ID]) == nhs111_data[, .N]) # Merge tables ------------------------------------------------------------ nhs111_analysis_table <- merge(nhs111_cohort_desc_data, nhs111_outcome_data, by = "record_ID", all.x = TRUE) stopifnot(nhs111_analysis_table[, .N] == nhs111_cohort_desc_data[, .N]) ## Pseudo the record number stopifnot(nhs111_outcome_data[is.na(record_ID) | record_ID == "", .N] == 0) nhs111_analysis_table[, ':=' (record_id = fn_pseudonymiseValues(as.character(record_ID), salt_filename = "private/salt1.txt"))][, record_ID := NULL] ## Order and add order col, before removing call time (leaving date only) ## record_id added as a 'tie-breaker' so sort will always return the same results setorder(nhs111_analysis_table, patient_id, nhs111_call_datetime, record_id, na.last = TRUE) nhs111_analysis_table[, patient_call_record_order := 1:.N, by = patient_id] nhs111_analysis_table[, nhs111_call_datetime := as.Date(nhs111_call_datetime)] # Number of contacts per patient ------------------------------------------ nhs111_analysis_table[, total_records_for_patient := .N, by = patient_id] ## Remove excluded patient nhs111_analysis_table_excluded_removed <- removeExcludedPatient(nhs111_analysis_table) ## Save output with date save_date <- Sys.Date() write.csv(nhs111_analysis_table_excluded_removed, file = paste0("data/data_for_stats/cohort_", save_date, "_nhs111.csv"))
#!/usr/bin/env Rscript # NOTE: to install phyloseq, please use the following code instead of the usual "install.packages" function: if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("phyloseq") library(phyloseq) library(ape) # importing trees library(tidyverse) library(vegan) #### Load data #### # Change file paths as necessary metafp <- "mpt_export/mpt_metadata.tsv" meta <- read_delim(metafp, delim="\t") otufp <- "mpt_export/feature-table.txt" otu <- read_delim(file = otufp, delim="\t", skip=1) taxfp <- "mpt_export/taxonomy.tsv" tax <- read_delim(taxfp, delim="\t") phylotreefp <- "mpt_export/tree.nwk" phylotree <- read.tree(phylotreefp) #### Format OTU table #### # OTU tables should be a matrix # with rownames and colnames as OTUs and sampleIDs, respectively # Note: tibbles do not allow rownames so if you imported with read_delim, change back # save everything except first column (OTU ID) into a matrix otu_mat <- as.matrix(otu[,-1]) # Make first column (#OTU ID) the rownames of the new matrix rownames(otu_mat) <- otu$`#OTU ID` # Use the "otu_table" function to make an OTU table OTU <- otu_table(otu_mat, taxa_are_rows = TRUE) class(OTU) #### Format sample metadata #### # Save everything except sampleid as new data frame samp_df <- as.data.frame(meta[,-1]) # Make sampleids the rownames rownames(samp_df)<- meta$'sample-id' # Make phyloseq sample data with sample_data() function SAMP <- sample_data(samp_df) class(SAMP) #### Formatting taxonomy #### # Convert taxon strings to a table with separate taxa rank columns tax_mat <- tax %>% select(-Confidence)%>% separate(col=Taxon, sep="; " , into = c("Domain","Phylum","Class","Order","Family","Genus","Species")) %>% as.matrix() # Saving as a matrix # Save everything except feature IDs tax_mat <- tax_mat[,-1] # Make sampleids the rownames rownames(tax_mat) <- tax$`Feature ID` # Make taxa table TAX <- tax_table(tax_mat) class(TAX) #### Create phyloseq object #### # Merge all into a phyloseq object mpt <- phyloseq(OTU, SAMP, TAX, phylotree) #### Looking at phyloseq object ##### # View components of phyloseq object with the following commands otu_table(mpt) sample_data(mpt) tax_table(mpt) phy_tree(mpt) #### Accessor functions #### # These functions allow you to see or summarise data # If we look at sample variables and decide we only want some variables, we can view them like so: sample_variables(mpt) # colnames(sample_data(atamaca)) get_variable(mpt, c("body.site","year","subject")) # equivalent to "select" in tidyverse ## Let's say we want to filter OTU table by sample. # We can first view sample names: sample_names(mpt) # How many samples do we have? nsamples(mpt) # What is the sum of reads in each sample? sample_sums(mpt) # Save the sample names of the 3 samples with the most reads getsamps <- names(sort(sample_sums(mpt), decreasing = TRUE)[1:3]) # filter to see taxa abundances for each sample get_taxa(mpt, getsamps) ## Conversely, let's say we want to compare OTU abundance of most abundant OTU across samples # Look at taxa names taxa_names(mpt) # How many taxa do we have? ntaxa(mpt) # What is the total read count for each taxa? taxa_sums(mpt) # Let's find the top 3 most abundant taxa gettaxa <- names(sort(taxa_sums(mpt), decreasing = TRUE)[1:3] ) get_sample(mpt, gettaxa) ######### ANALYZE ########## # Remove non-bacterial sequences, if any mpt_filt <- subset_taxa(mpt, Domain == "d__Bacteria" & Class!="c__Chloroplast" & Family !="f__Mitochondria") # Remove ASVs that have less than 5 counts total mpt_filt_nolow <- filter_taxa(mpt_filt, function(x) sum(x)>5, prune = TRUE) # Remove samples with less than 100 reads mpt_filt_nolow_samps <- prune_samples(sample_sums(mpt_filt_nolow)>100, mpt_filt_nolow) # Remove samples where month is na mpt_final <- subset_samples(mpt_filt_nolow_samps, !is.na(month) ) # Rarefy samples # rngseed sets a random number. If you want to reproduce this exact analysis, you need # to set rngseed the same number each time # t transposes the table to use rarecurve function # cex decreases font size rarecurve(t(as.data.frame(otu_table(mpt_final))), cex=0.1) mpt_rare <- rarefy_even_depth(mpt_final, rngseed = 1, sample.size = 1000) ##### Saving ##### save(mpt_final, file="mpt_final.RData") save(mpt_rare, file="mpt_rare.RData") #### Full list of processor functions #### # There are also several functions you can use to process your data subset_samples(mpt, year == 2008) # Subset taxa uses the taxonomy table to subset by taxonomy mpt_alphaonly <- subset_taxa(mpt, Class=="c__Alphaproteobacteria") as.data.frame(tax_table(mpt_alphaonly)) %>% select(Class) # Subset samples uses the sample data table to filter samples subset_samples(mpt, month>3) # Note: will automatically filter out NAa ## The more general version of subset is "prune_samples" and "prune_taxa" # prune takes either a logical or character vector and filters taxa/samples based on this # Useful if you do external calculations to determine which samples to keep # Filter taxa uses functions to filter out groups # You can also use filter taxa to produce a vector of logicals, then use "prune_taxa" random_taxa <- taxa_names(mpt)[1:10] prune_taxa(random_taxa, mpt) # example with sample data-- filtering out samples that have at least one Alphaproteobacteria alpha_sums <- sample_sums(mpt_alphaonly) prune_samples(alpha_sums>0, mpt) # Can sum by taxonomy to get species-level, genus-level etc taxa tables mpt_Family <- tax_glom(mpt, taxrank = "Family", NArm=FALSE) # You can also merge targetted samples and taxa together using these functions merge_samples(mpt, group="subject") merge_taxa() ?merge_samples # For merging entire phyloseq objects together (different datasets merged into one) merge_phyloseq()
import { Box, Container, Typography } from "@mui/material"; import { Link, useNavigate } from "react-router-dom"; import { RegisterForm } from "../../components/RegisterForm"; import { useSigninCheck } from "reactfire"; export const RegisterPage = () => { const { data: signInData } = useSigninCheck(); const navigate = useNavigate(); const userName = signInData?.user?.displayName; const signedIn = signInData?.signedIn; const isUserSignedIn = signedIn && userName; if (isUserSignedIn) { navigate("/"); } return ( <Container> <Box sx={{ display: "flex", flexDirection: "column", alignItems: "center", }} > <Typography my={1} color="primary" variant="h4" fontWeight="bold"> Register new Bookly Account </Typography> <Box width={1 / 2} my={1}> <RegisterForm /> </Box> <Typography my={1} color="primary" component={Link} to="/login"> Click to Login! </Typography> </Box> </Container> ); };
#include<iostream> #include<string> using namespace std; class account { private : double balance; public : void set_bal(double bal); double get_bal(); bool deposite(double amount); bool withdraw(double amount); }; void account :: set_bal(double bal){ balance = bal; } double account :: get_bal(){ return balance; } bool account :: deposite(double amount){ balance +=amount; return true; } bool account :: withdraw(double amount){ if((balance -amount)>0){ balance -=amount; return true; } else { return false; } } int main(){ account my_bank; my_bank.set_bal(4000.0); if(my_bank.deposite(500.0)){ cout<<" My deposite is ok"<<endl; } else { cout<<"Deposite not Ok"<<endl; } if(my_bank.withdraw(200)){ cout<<" Yeap! My withdraw is Good : "; cout<<my_bank.get_bal()<<endl; } else{ cout<<" Sorrow ,Withdraw not ok"<<endl; } if(my_bank.withdraw(5000)){ cout<<" Yeap! My withdraw is Good "<<endl; } else{ cout<<" Sorrow ,Withdraw not ok"<<endl; } return 0; }
import { useState } from 'react'; import Card from 'src/components/card/Card'; import Button from 'src/components/button/Button'; import PackageTag from './PackageTag'; import PackageTextFeature from './PackageTextFeature'; import PackageApps from './PackageApps'; import BonusFeature from './BonusFeature'; import TikTokFeature from './TikTokFeature'; import PrimeFeature from './PrimeFeature'; import PackageItemFooter from './PackageItemFooter'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faChevronDown } from '@fortawesome/free-solid-svg-icons'; import 'src/styles/packages/package-item.scss'; const apps = [ { type: 'whatsApp' }, { type: 'facebook', description: 'Fotos' }, { type: 'messenger' }, { type: 'instagram', description: 'Fotos' }, { type: 'waze' }, { type: 'spotify' }, ]; const PackageItem = ({ packageData }) => { const price = packageData?.price?.split('.'); const [openMore, setOpenMore] = useState(false); return ( <Card className='package-item'> {packageData.bestSeller ? <PackageTag /> : null} <PackageTextFeature className='package-item__header' text={packageData.title} subText={packageData?.subtitle} /> <div className='package-item__section'> <PackageTextFeature className='package-item__speed' text={packageData.speed} subText={packageData.speedCharacteristic} /> <div className="package-item__divider" /> <div className='package-item__text-feature'> <p> <span className='package-item__price-before'>S/</span> <span className='package-item__price-unity'> {price?.[0] ?? ''} </span> <span className='package-item__price-tenths'> .{price?.[1] ?? ''} x 2 meses </span> </p> <small className='package-item__regular-price'> Precio regular S/{packageData.regularPrice} </small> </div> </div> {packageData.installFree ? ( <PackageTextFeature className='package-item__install' text='Instalación gratis' subText='Previa evaluación crediticia' /> ) : null} <div className="package-item__actions"> <Button size='medium'>Comprar en línea</Button> <Button size='medium' outline> Llámame ahora </Button> </div> <PackageApps className={`${openMore ? 'package-item__apps-container--mobile-open' : ''}`} apps={apps} /> {packageData?.bonusIncluded ? <BonusFeature className={`${openMore ? 'package-item__feature--mobile-open' : ''}`} /> : null} {packageData?.tiktokIncluded ? <TikTokFeature className={`${openMore ? 'package-item__feature--mobile-open' : ''}`} /> : null} <PrimeFeature className={`${openMore ? 'package-item__feature--mobile-open' : ''}`} /> <div className={`divider ${openMore ? 'divider--mobile-open' : ''}`} /> <PackageItemFooter className={`${openMore ? 'package-item__footer--mobile-open' : ''}`} uploadSpeed={packageData.uploadSpeed} downloadSpeed={packageData.downloadSpeed} /> <div className={`package-item__more-btn ${openMore ? 'package-item__more-btn--open' : ''}`}> <button type="button" onClick={() => setOpenMore(!openMore)}> {openMore ? 'Ver menos' : 'Ver más beneficios'} <FontAwesomeIcon icon={faChevronDown} /> </button> </div> </Card> ); }; export default PackageItem;
// Implementation with plain callbacks function emitRandomNumber(callback, attempt = 1) { const attempts = 10; console.log(`Attempt #${attempt}. emitRandomNumber is called.`); setTimeout(() => { console.log("2 seconds have lapsed."); let randomNumber = Math.floor(Math.random() * 100); callback(randomNumber); if (attempt < attempts && randomNumber < 80) { emitRandomNumber(callback, attempt + 1); } }, 2000); } function processNumber(num) { console.log(`Random number generated is ${num}${num >= 80 ? '!!!' : ''}`); } // Implementation using a Promise object; this is also reused when invoked as an action function emitRandomNumberAsPromise() { const attempts = 10; let attempt = 1; return new Promise((resolve, reject) => { let action = setInterval(() => { console.log(`Attempt #${attempt}. emitRandomNumber is called.`); console.log("2 seconds have lapsed."); let randomNumber = Math.floor(Math.random() * 100); processNumber(randomNumber); if (randomNumber >= 80 || attempt === attempts) { clearInterval(action); resolve(); return; } attempt++; }, 2000); }); } function emitRandomNumberViaPromise() { emitRandomNumberAsPromise(); } async function emitRandomNumberAsync() { await emitRandomNumberAsPromise(); }
import { Popup } from "./Popup.js"; export class PopupWithForm extends Popup { constructor ({popupSelector, handleSubmit}) { super(popupSelector); this._handleFormSubmit = handleSubmit; this._popupForm = this._popup.querySelector('.popup__form'); this._inputList = this._popupForm.querySelectorAll('.popup__input'); } getInputValues() { this._formValues = {}; this._inputList.forEach(input => { this._formValues[input.id] = input.value; }); return this._formValues; } setInputValues(data) { this._inputList.forEach(function (input) { input.value = data[input.id]; }); } setEventListeners () { super.setEventListeners(); this._popupForm.addEventListener("submit", evt => this._handleFormSubmit(evt)); } close () { super.close(); this._popupForm.reset(); } }
<div> <h2 id="page-heading" data-cy="CountyRecordLegalHeading"> <span>County Record Legals</span> <div class="d-flex justify-content-end"> <button class="btn btn-info mr-2" (click)="loadPage()" [disabled]="isLoading"> <fa-icon icon="sync" [spin]="isLoading"></fa-icon> <span>Refresh List</span> </button> <button id="jh-create-entity" data-cy="entityCreateButton" class="btn btn-primary jh-create-entity create-county-record-legal" [routerLink]="['/county-record-legal/new']" > <fa-icon icon="plus"></fa-icon> <span> Create a new County Record Legal </span> </button> </div> </h2> <jhi-alert-error></jhi-alert-error> <jhi-alert></jhi-alert> <div class="alert alert-warning" id="no-result" *ngIf="countyRecordLegals?.length === 0"> <span>No countyRecordLegals found</span> </div> <div class="table-responsive" id="entities" *ngIf="countyRecordLegals && countyRecordLegals.length > 0"> <table class="table table-striped" aria-describedby="page-heading"> <thead> <tr jhiSort [(predicate)]="predicate" [(ascending)]="ascending" (sortChange)="loadPage()"> <th scope="col" jhiSortBy="id"><span>ID</span> <fa-icon icon="sort"></fa-icon></th> <th scope="col" jhiSortBy="legal"><span>Legal</span> <fa-icon icon="sort"></fa-icon></th> <th scope="col" jhiSortBy="recordKey"><span>Record Key</span> <fa-icon icon="sort"></fa-icon></th> <th scope="col" jhiSortBy="countyRecord.id"><span>County Record</span> <fa-icon icon="sort"></fa-icon></th> <th scope="col"></th> </tr> </thead> <tbody> <tr *ngFor="let countyRecordLegal of countyRecordLegals; trackBy: trackId" data-cy="entityTable"> <td> <a [routerLink]="['/county-record-legal', countyRecordLegal.id, 'view']">{{ countyRecordLegal.id }}</a> </td> <td>{{ countyRecordLegal.legal }}</td> <td>{{ countyRecordLegal.recordKey }}</td> <td> <div *ngIf="countyRecordLegal.countyRecord"> <a [routerLink]="['/county-record', countyRecordLegal.countyRecord?.id, 'view']">{{ countyRecordLegal.countyRecord?.id }}</a> </div> </td> <td class="text-right"> <div class="btn-group"> <button type="submit" [routerLink]="['/county-record-legal', countyRecordLegal.id, 'view']" class="btn btn-info btn-sm" data-cy="entityDetailsButton" > <fa-icon icon="eye"></fa-icon> <span class="d-none d-md-inline">View</span> </button> <button type="submit" [routerLink]="['/county-record-legal', countyRecordLegal.id, 'edit']" class="btn btn-primary btn-sm" data-cy="entityEditButton" > <fa-icon icon="pencil-alt"></fa-icon> <span class="d-none d-md-inline">Edit</span> </button> <button type="submit" (click)="delete(countyRecordLegal)" class="btn btn-danger btn-sm" data-cy="entityDeleteButton"> <fa-icon icon="times"></fa-icon> <span class="d-none d-md-inline">Delete</span> </button> </div> </td> </tr> </tbody> </table> </div> <div *ngIf="countyRecordLegals && countyRecordLegals.length > 0"> <div class="row justify-content-center"> <jhi-item-count [params]="{ page: page, totalItems: totalItems, itemsPerPage: itemsPerPage }"></jhi-item-count> </div> <div class="row justify-content-center"> <ngb-pagination [collectionSize]="totalItems" [(page)]="ngbPaginationPage" [pageSize]="itemsPerPage" [maxSize]="5" [rotate]="true" [boundaryLinks]="true" (pageChange)="loadPage($event)" ></ngb-pagination> </div> </div> </div>
<?php session_start(); if (!isset($_SESSION["emp_id"])) { header("Location: ../login"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Homepage</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script> <style> #navbar-item { background: url(quadsel_logo.png) no-repeat center center; background-size: cover; width: 130px; height: 48px; } </style> </head> <body> <nav class="navbar has-shadow" role="navigation" aria-label="main navigation"> <div class="navbar-brand"> <a class="navbar-item" id="navbar-item" href="./"></a> <a role="button" class="navbar-burger" aria-label="menu" aria-expanded="false" data-target="mainNav"> <span aria-hidden="true"></span> <span aria-hidden="true"></span> <span aria-hidden="true"></span> </a> </div> <div id="mainNav" class="navbar-menu"> <div class="navbar-end"> <a class="navbar-item" href="./"> Analytics </a> <a class="navbar-item" href="./employee"> Employee </a> <a class="navbar-item" href="./visitors"> Visitors </a> <a class="navbar-item button is-danger mt-2" href="../logout"> Logout </a> </div> </div> </nav> <div class="container p-6"> <h1 class="title is-1 has-text-centered">Average Check In Time & Check Out Time </h1> <div class="container is-flex is-centered is-justify-content-center mt-6"> <table class="table is-bordered is-striped"> <thead class='has-background-primary'> <tr> <th>Check-In</th> <th>Check-Out</th> </tr> </thead> <tbody> <?php include_once('./charts/checkinout.php'); $check_data = getCheckInOutData(); $check_in_time = "--:--:--"; $check_out_time = "--:--:--"; foreach ($check_data as $key => $value) { $check_in_time = date('H:i:s', strtotime($value["avg_check_in"])); $check_out_time = date('H:i:s', strtotime($value["avg_check_out"])); } ?> <tr> <td> <?php echo $check_in_time; ?> </td> <td> <?php echo $check_out_time; ?> </td> </tr> </tbody> </table> </div> <div class="container is-flex is-centered is-justify-content-center has-text-centered mt-6"> <form action="./holidays/index.php" method="post" class="container has-text-centered" enctype="multipart/form-data"> <input type="file" class="input is-info" accept=".xlsx,.xls" name="holiday_data" /> <button type="submit" class="button is-primary mt-6" name="holiday_submit">Submit</button> </form> </div> <div class="container p-6"> <h1 class="title is-1 has-text-centered">Employee attendance for <?php $currentYear = date('Y'); $currentMonthF = date('F'); $formattedDate = $currentMonthF . ' ' . $currentYear; echo $formattedDate; ?> </h1> <canvas id="acquisitions"></canvas> </div> </div> <?php include_once('./charts/attendance.php'); $analytics_data = getAttendanceData(); include_once('./charts/attendance.php'); $emp_count_data = getEmployeeCount(); if ($_SERVER["REQUEST_METHOD"] == "POST") { $submit_btn = filter_input(INPUT_POST, 'holiday_submit', FILTER_SANITIZE_STRING); if (isset($submit_btn)) { $holiday_data = filter_input(INPUT_POST, 'holiday_data', FILTER_SANITIZE_STRING); if (isset($holiday_data)) { header("Location: ./holidays"); } else { echo "File input not found or upload error."; } } } ?> <script> document.addEventListener('DOMContentLoaded', () => { let date = [], emp_count = [], abs_count = []; try { const TOTAL_EMPLOYEE_COUNT = <?php echo json_encode($emp_count_data); ?>["count"]; const data = <?php echo json_encode($analytics_data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE); ?>; date = Object.keys(data); emp_count = Object.values(data); emp_count.forEach(count => abs_count.push(TOTAL_EMPLOYEE_COUNT - count)); } catch (error) { console.error('Error parsing or processing JSON data:', error); } new Chart(document.getElementById('acquisitions'), { type: 'bar', data: { datasets: [{ label: 'Present Count', data: emp_count, order: 2, borderColor: '#36A2EB', backgroundColor: '#9BD0F5', }, { label: 'Absent Count', data: abs_count, type: 'line', order: 1, borderColor: '#FF6384', backgroundColor: '#FFB1C1', }], labels: date }, }); const $navbarBurgers = Array.from(document.querySelectorAll('.navbar-burger')); $navbarBurgers.forEach(el => { el.addEventListener('click', () => { const target = el.dataset.target; const $target = document.getElementById(target); el.classList.toggle('is-active'); $target.classList.toggle('is-active'); }); }); }); </script> </body> </html>
import Document, { Html, Head, Main, NextScript } from 'next/document' class MyDocument extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx); return { ...initialProps } } render() { return ( <Html> <Head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rsuite/4.3.4/styles/rsuite-default.min.css" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } export default MyDocument;
<!doctype html> <html> <head> </head> <body> <h3>Look the console of your browser</h3> <div> This maker will allow you to easily create setters and getters for all the properties in a given object.<br/> The source code:<br/> <pre id='sc'></pre> The output is in your console. </div> <script src='../../dist/maker.js'></script> <script id='sampleCode'> var o= { name: 'felipe', age: 28, desc: 'a nice guy' }; make.setAndGettable(o); // or it could be make.setAndGetable(o); /* you could also pass options, like: make.setAndGetable(o, { specificOnly: true // no generic set or get will be created }); */ console.log(o); var Person= function(){ this.name= ''; this.age= -1; this.desc= ''; make.setAndGettable(this, { filterIn: function(prop, value){ switch(prop){ case 'age': if(isNaN(value) || value < 0 || value >130){ console.warn('invalid age to set!'); throw new Error('invalid value to set'); } break; default: if(value === '' || value === void 0){ console.warn('invalid value to set! '+value); throw new Error('invalid value to set'); } } return value; }, filterOut: function(prop, value){ switch(prop){ case 'name': return 'Hi, my name is '+value; break; case 'age': return 'You are not supposed to know my age!'; } return value; } }); return this; }; var p1 = new Person(); var p2 = new Person(); p1.name= 'Felipe'; p1.setAge(28).setDesc('a programmer'); p2.set('name', 'Moura').set('age', 19).set('desc', 'something here'); console.log(p1); console.log(p2); </script> <script> setTimeout(function(){ document.getElementById('sc').innerHTML= document.getElementById('sampleCode').text; }, 100); </script> </body> </html>
import type { GetStaticProps, NextPage } from "next"; import Head from "next/head"; import Link from "next/link"; import About from "../components/About"; import ContactMe from "../components/ContactMe"; import Header from "../components/Header"; import Hero from "../components/Hero"; import Projects from "../components/Projects"; import Skills from "../components/Skills"; import WorkExperience from "../components/WorkExperience"; import { Experience, PageInfo, Project, Skill, Social } from "../typings"; import { fetchExperiences } from "../utils/fetchExperiences"; import { fetchPageInfo } from "../utils/fetchPageInfo"; import { fetchProjects } from "../utils/fetchProjects"; import { fetchSkills } from "../utils/fetchSkills"; import { fetchSocials } from "../utils/fetchSocials"; type Props = { pageInfo: PageInfo; experiences: Experience[]; skills: Skill[]; projects: Project[]; socials: Social[]; }; const Home = ({ pageInfo, experiences, projects, skills, socials }: Props) => { return ( <div className="bg-[rgb(36,36,36)] text-white h-screen snap-y snap-mandatory overflow-y-scroll z-0 overflow-x-hidden scrollbar scrollbar-track-gray-400/20 scrollbar-thumb-[#F7AB0A]/80"> <Head> <title>TS Portfolio</title> <meta name="description" content="Generated by create next app" /> <link rel="icon" href="/favicon.ico" /> </Head> <Header socials={socials} /> <section className="snap-start" id="hero"> <Hero pageInfo={pageInfo} /> </section> <section className="snap-center" id="about"> <About pageInfo={pageInfo} /> </section> <section className="snap-center" id="experience"> <WorkExperience experiences={experiences} /> </section> <section className="snap-start" id="skills"> <Skills skills={skills} /> </section> <section className="snap-start" id="projects"> <Projects projects={projects} /> </section> <section className="snap-start" id="contact"> <ContactMe /> </section> <Link href="#hero"> <footer className="sticky bottom-5 w-full cursor-pointer"> <div className="flex items-center justify-center"> <div className="h-10 w-10 rounded-full filter grayscale hover:grayscale-0"> TOP </div> </div> </footer> </Link> </div> ); }; export default Home; export const getStaticProps: GetStaticProps<Props> = async () => { const pageInfo: PageInfo = await fetchPageInfo(); const experiences: Experience[] = await fetchExperiences(); const skills: Skill[] = await fetchSkills(); const projects: Project[] = await fetchProjects(); const socials: Social[] = await fetchSocials(); return { props: { pageInfo, experiences, skills, projects, socials, }, }; };
package edu.hw4; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.*; public class AnimalTest { private AnimalTest() {} private final List<Animal> animalList = new ArrayList<>(); @BeforeEach public void clearList() { animalList.clear(); } @Test @DisplayName("Test heightSortAnimal function") public void testHeightSortAnimal() { animalList.add(Animal.builder().height(155).build()); animalList.add(Animal.builder().height(7).build()); animalList.add(Animal.builder().height(34).build()); animalList.add(Animal.builder().height(26).build()); animalList.add(Animal.builder().height(59).build()); List<Integer> res = AnimalUtils.heightSortAnimal(animalList) .stream().map(Animal::height).toList(); assertThat(res).containsExactly(7, 26, 34, 59, 155); } @Test @DisplayName("Test weightSortAnimal function") public void testWeightSortAnimal() { animalList.add(Animal.builder().weight(10).build()); animalList.add(Animal.builder().weight(1).build()); animalList.add(Animal.builder().weight(25).build()); animalList.add(Animal.builder().weight(17).build()); List<Integer> res = AnimalUtils.weightSortAnimal(animalList, 3) .stream().map(Animal::weight).toList(); assertThat(res).containsExactly(25, 17, 10); } @Test @DisplayName("Test countAnimalType function") public void testCountAnimalType() { animalList.add(Animal.builder().type(Animal.Type.DOG).build()); animalList.add(Animal.builder().type(Animal.Type.FISH).build()); animalList.add(Animal.builder().type(Animal.Type.DOG).build()); animalList.add(Animal.builder().type(Animal.Type.CAT).build()); animalList.add(Animal.builder().type(Animal.Type.FISH).build()); animalList.add(Animal.builder().type(Animal.Type.FISH).build()); Map<Animal.Type, Long> res = AnimalUtils.countAnimalType(animalList); // создает объект entry, который представляет пару ключ-значение в мапе assertThat(res).contains(entry(Animal.Type.FISH, 3L), entry(Animal.Type.DOG, 2L), entry(Animal.Type.CAT, 1L)); } @Test @DisplayName("Test getLongestNameAnimal function") public void testGetLongestNameAnimal() { animalList.add(Animal.builder().name("Bobik").build()); animalList.add(Animal.builder().name("Yap").build()); animalList.add(Animal.builder().name("Panamochka").build()); animalList.add(Animal.builder().name("Murzik").build()); Animal res = AnimalUtils.getLongestNameAnimal(animalList); assertThat(res.name()).isEqualTo("Panamochka"); } @Test @DisplayName("Test countGenders function") public void testCountGenders() { animalList.add(Animal.builder().sex(Animal.Sex.M).build()); animalList.add(Animal.builder().sex(Animal.Sex.M).build()); animalList.add(Animal.builder().sex(Animal.Sex.F).build()); animalList.add(Animal.builder().sex(Animal.Sex.M).build()); Animal.Sex res = AnimalUtils.countGenders(animalList); assertThat(res).isEqualTo(Animal.Sex.M); } @Test @DisplayName("Test getHeaviestAnimal function") public void testGetHeaviestAnimal() { animalList.add(Animal.builder().type(Animal.Type.FISH).weight(15).build()); animalList.add(Animal.builder().type(Animal.Type.FISH).weight(5).build()); animalList.add(Animal.builder().type(Animal.Type.FISH).weight(30).build()); animalList.add(Animal.builder().type(Animal.Type.BIRD).weight(44).build()); Map<Animal.Type, Animal> res = AnimalUtils.getHeaviestAnimal(animalList); assertThat(res).contains( entry(Animal.Type.FISH, Animal.builder().type(Animal.Type.FISH).weight(30).build()), entry(Animal.Type.BIRD, Animal.builder().type(Animal.Type.BIRD).weight(44).build()) ); } @Test @DisplayName("Test getEldestAnimal function") public void getEldestAnimal() { animalList.add(Animal.builder().age(10).build()); animalList.add(Animal.builder().age(7).build()); animalList.add(Animal.builder().age(2).build()); animalList.add(Animal.builder().age(15).build()); Animal actual = AnimalUtils.getEldestAnimal(animalList, 3); assertThat(actual.age()).isEqualTo(10); } @Test @DisplayName("Test findHeaviestAnimalBelowKHeight function") public void testFindHeaviestAnimalBelowKHeight() { animalList.add(Animal.builder().height(10).weight(40).build()); animalList.add(Animal.builder().height(25).weight(15).build()); animalList.add(Animal.builder().height(100).weight(150).build()); animalList.add(Animal.builder().height(50).weight(40).build()); Optional<Animal> res = AnimalUtils.findHeaviestAnimalBelowKHeight(animalList, 50); assertThat(res.get()).isEqualTo(Animal.builder().height(10).weight(40).build()); } @Test @DisplayName("sumOfPaws") public void testSumOfPaws() { animalList.add(Animal.builder().type(Animal.Type.DOG).build()); animalList.add(Animal.builder().type(Animal.Type.FISH).build()); animalList.add(Animal.builder().type(Animal.Type.BIRD).build()); animalList.add(Animal.builder().type(Animal.Type.CAT).build()); animalList.add(Animal.builder().type(Animal.Type.SPIDER).build()); animalList.add(Animal.builder().type(Animal.Type.SPIDER).build()); Integer res = AnimalUtils.sumOfPaws(animalList); assertThat(res).isEqualTo(26); } @Test @DisplayName("Test findAnimalsWithMismatchedAgeAndLegs function") public void testFindAnimalsWithMismatchedAgeAndLegs() { animalList.add(Animal.builder().type(Animal.Type.CAT).age(4).build()); animalList.add(Animal.builder().type(Animal.Type.DOG).age(5).build()); animalList.add(Animal.builder().type(Animal.Type.BIRD).age(4).build()); animalList.add(Animal.builder().type(Animal.Type.FISH).age(0).build()); List<Animal> res = AnimalUtils.findAnimalsWithMismatchedAgeAndLegs(animalList); assertThat(res.stream().map(Animal::age).collect(Collectors.toList())).containsExactly(5, 4); } @Test @DisplayName("Test findAnimalsThatCanBiteAndTall function") public void testFindAnimalsThatCanBiteAndTall() { animalList.add(Animal.builder().bites(true).height(110).build()); animalList.add(Animal.builder().bites(true).height(90).build()); animalList.add(Animal.builder().bites(false).height(120).build()); List<Animal> res = AnimalUtils.findAnimalsThatCanBiteAndTall(animalList); assertThat(res).hasSize(1); } @Test @DisplayName("Test countAnimalsWhoseWeightExceedsHeight function") public void testCountAnimalsWhoseWeightExceedsHeight() { animalList.add(Animal.builder().weight(120).height(100).build()); animalList.add(Animal.builder().weight(120).height(120).build()); animalList.add(Animal.builder().weight(90).height(100).build()); animalList.add(Animal.builder().weight(130).height(100).build()); Long res = AnimalUtils.countAnimalsWhoseWeightExceedsHeight(animalList); assertThat(res).isEqualTo(2); } @Test @DisplayName("Test animalsWhoseNamesConsistOfMoreTwoWords function") public void testAnimalsWhoseNamesConsistOfMoreTwoWords() { animalList.add(Animal.builder().name("One Two Three").build()); animalList.add(Animal.builder().name("Tyler Durden").build()); animalList.add(Animal.builder().name("Super Dora Dura").build()); animalList.add(Animal.builder().name("Ryan").build()); List<Animal> res = AnimalUtils.animalsWhoseNamesConsistOfMoreTwoWords(animalList); assertThat(res.stream().map(Animal::name).collect(Collectors.toList())).containsExactly( "One Two Three", "Super Dora Dura" ); } @Test @DisplayName("Test isDogWithHeightGreaterBelowK function") public void testIsDogWithHeightGreaterBelowK() { animalList.add(Animal.builder().type(Animal.Type.DOG).height(120).build()); animalList.add(Animal.builder().type(Animal.Type.DOG).height(80).build()); animalList.add(Animal.builder().type(Animal.Type.CAT).height(100).build()); boolean actual = AnimalUtils.isDogWithHeightGreaterBelowK(animalList, 90); assertThat(actual).isEqualTo(true); } @Test @DisplayName("Test getSumOfWeightByTypeAndAgeRange function") public void testGetSumOfWeightByTypeAndAgeRange() { animalList.add(Animal.builder().type(Animal.Type.DOG).weight(35).age(10).build()); animalList.add(Animal.builder().type(Animal.Type.DOG).weight(50).age(8).build()); animalList.add(Animal.builder().type(Animal.Type.SPIDER).weight(1).age(5).build()); animalList.add(Animal.builder().type(Animal.Type.FISH).weight(300).age(50).build()); Map<Animal.Type, Integer> res = AnimalUtils.getSumOfWeightByTypeAndAgeRange(animalList, 5, 10); assertThat(res.get(Animal.Type.DOG)).isEqualTo(85); assertThat(res.get(Animal.Type.SPIDER)).isEqualTo(1); } @Test @DisplayName("Test sortAnimalsByTypeGenderAndName function") public void testSortAnimalsByTypeGenderAndName() { animalList.add(Animal.builder().type(Animal.Type.BIRD).sex(Animal.Sex.F).name("Bird1").build()); animalList.add(Animal.builder().type(Animal.Type.BIRD).sex(Animal.Sex.M).name("Bird3").build()); animalList.add(Animal.builder().type(Animal.Type.BIRD).sex(Animal.Sex.F).name("Bird2").build()); animalList.add(Animal.builder().type(Animal.Type.CAT).sex(Animal.Sex.F).name("Cat").build()); List<Animal> res = AnimalUtils.sortAnimalsByTypeGenderAndName(animalList); assertThat(res).containsExactly( Animal.builder().type(Animal.Type.CAT).sex(Animal.Sex.F).name("Cat").build(), Animal.builder().type(Animal.Type.BIRD).sex(Animal.Sex.M).name("Bird3").build(), Animal.builder().type(Animal.Type.BIRD).sex(Animal.Sex.F).name("Bird1").build(), Animal.builder().type(Animal.Type.BIRD).sex(Animal.Sex.F).name("Bird2").build() ); } @Test @DisplayName("Test isSpidersBiteMoreThanDogs function") public void testIsSpidersBiteMoreThanDogs() { animalList.add(Animal.builder().type(Animal.Type.SPIDER).bites(true).build()); animalList.add(Animal.builder().type(Animal.Type.DOG).bites(true).build()); animalList.add(Animal.builder().type(Animal.Type.SPIDER).bites(true).build()); animalList.add(Animal.builder().type(Animal.Type.DOG).bites(true).build()); animalList.add(Animal.builder().type(Animal.Type.DOG).bites(true).build()); boolean actual = AnimalUtils.isSpidersBiteMoreThanDogs(animalList); assertThat(actual).isEqualTo(false); } @Test @DisplayName("Test getHeaviestFishIn function") public void testGetHeaviestFishIn() { animalList.add(Animal.builder().type(Animal.Type.FISH).weight(100).build()); animalList.add(Animal.builder().type(Animal.Type.DOG).weight(100).build()); List<Animal> animalList2 = new ArrayList<>(); animalList2.add(Animal.builder().type(Animal.Type.CAT).weight(200).build()); List<Animal> animalList3 = new ArrayList<>(); animalList3.add(Animal.builder().type(Animal.Type.FISH).weight(300).build()); Animal res = AnimalUtils.getHeaviestFishIn(animalList, animalList2, animalList3); assertThat(res).isEqualTo(animalList3.get(0)); } @Test @DisplayName("Test getAnimalsErrorMap function") public void testGetAnimalsErrorMap() { animalList.add(Animal.builder().weight(-35).height(-50).age(0).name("Laura").build()); animalList.add(Animal.builder().weight(-1).height(2).age(0).name("Snowy").build()); animalList.add(Animal.builder().weight(12).height(13).age(10).name("Normic").build()); Map<String, Set<ValidationError>> res = AnimalUtils.getAnimalsErrorMap(animalList); assertThat(res) .containsExactly( entry( "Laura", Set.of( new ValidationError(ValidationError.ErrorType.AGE), new ValidationError(ValidationError.ErrorType.HEIGHT), new ValidationError(ValidationError.ErrorType.WEIGHT) ) ), entry( "Snowy", Set.of( new ValidationError(ValidationError.ErrorType.WEIGHT), new ValidationError(ValidationError.ErrorType.AGE) ) ) ); } @Test @DisplayName("Test getReadableAnimalsErrorMap function") public void getReadableAnimalsErrorMap() { animalList.add(Animal.builder().name("Biba").age(-1).weight(120).height(-20).build()); animalList.add(Animal.builder().name("Boba").age(1).weight(120).height(20).build()); Map<String, String> actual = AnimalUtils.getReadableAnimalsErrorMap(animalList); assertThat(actual) .hasEntrySatisfying("Biba", val -> assertThat(val).isIn("AGE, HEIGHT", "HEIGHT, AGE")); } }
// // Created by 21527 on 22/09/20. // #ifndef DETOUR_DEMO_FILEWINDOW_H #define DETOUR_DEMO_FILEWINDOW_H #include <windows.h> #include <QDebug> #include <QDialog> #include <QLabel> #include <QLayout> #include <QTextEdit> #include <QPushButton> #include <QDialogButtonBox> #include <QMessageBox> class FileWindow : public QDialog { Q_OBJECT public: explicit FileWindow(HANDLE fileHandle, QWidget *parent = nullptr) : QDialog(parent) { this->setWindowFlags(Qt::Window); this->resize(800, 600); this->setWindowTitle("修改文件内容"); auto layout = new QVBoxLayout(this); auto textEdit = new QTextEdit(this); auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); layout->addWidget(textEdit); layout->addWidget(buttonBox); this->setLayout(layout); // 读取文件内容 DWORD fileSize = GetFileSize(fileHandle, nullptr); QByteArray fileContent((int) fileSize, 0); DWORD readSize = 0; BOOL status = ReadFile(fileHandle, fileContent.data(), fileSize, &readSize, nullptr); if(!status) QMessageBox::critical(this, "错误", "读取文件内容失败"); else textEdit->setText(fileContent); // 保存文件内容 connect(buttonBox, &QDialogButtonBox::accepted, this, [this, fileHandle, textEdit]() { SetFilePointer(fileHandle, 0, nullptr, FILE_BEGIN); QByteArray fileContent = textEdit->toPlainText().toUtf8(); DWORD writeSize = 0; BOOL status = WriteFile(fileHandle, fileContent.data(), fileContent.size(), &writeSize, nullptr); SetEndOfFile(fileHandle); if(status == FALSE) QMessageBox::critical(this, "错误", "保存文件失败"); else QMessageBox::information(this, "提示", "保存文件成功,写入字节数:" + QString::number(writeSize)); this->close(); }); connect(buttonBox, &QDialogButtonBox::rejected, this, [this]() { this->close(); }); }; ~FileWindow() override = default;; }; #endif //DETOUR_DEMO_FILEWINDOW_H
/** * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * ``` * http://www.apache.org/licenses/LICENSE-2.0 * ``` * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.android.healthconnect.controller.permissions.connectedapps import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.healthconnect.controller.permissions.api.RevokeAllHealthPermissionsUseCase import com.android.healthconnect.controller.permissions.connectedapps.searchapps.SearchHealthPermissionApps import com.android.healthconnect.controller.service.IoDispatcher import com.android.healthconnect.controller.shared.app.ConnectedAppMetadata import com.android.healthconnect.controller.utils.postValueIfUpdated import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.launch @HiltViewModel class ConnectedAppsViewModel @Inject constructor( private val loadHealthPermissionApps: LoadHealthPermissionApps, private val searchHealthPermissionApps: SearchHealthPermissionApps, private val revokeAllHealthPermissionsUseCase: RevokeAllHealthPermissionsUseCase, @IoDispatcher val ioDispatcher: CoroutineDispatcher ) : ViewModel() { companion object { private const val TAG = "ConnectedAppsViewModel" } private val _connectedApps = MutableLiveData<List<ConnectedAppMetadata>>() val connectedApps: LiveData<List<ConnectedAppMetadata>> get() = _connectedApps private val _disconnectAllState = MutableLiveData<DisconnectAllState>(DisconnectAllState.NotStarted) val disconnectAllState: LiveData<DisconnectAllState> get() = _disconnectAllState init { loadConnectedApps() } fun loadConnectedApps() { viewModelScope.launch { _connectedApps.postValueIfUpdated(loadHealthPermissionApps.invoke()) } } fun searchConnectedApps(searchValue: String) { viewModelScope.launch { _connectedApps.postValueIfUpdated( searchHealthPermissionApps.search(loadHealthPermissionApps.invoke(), searchValue)) } } fun disconnectAllApps(apps: List<ConnectedAppMetadata>): Boolean { try { viewModelScope.launch(ioDispatcher) { _disconnectAllState.postValue(DisconnectAllState.Loading) apps.forEach { app -> revokeAllHealthPermissionsUseCase.invoke(app.appMetadata.packageName) } loadConnectedApps() _disconnectAllState.postValue(DisconnectAllState.Updated) } return true } catch (ex: Exception) { Log.e(TAG, "Failed to update permissions!", ex) } return false } sealed class DisconnectAllState { object NotStarted : DisconnectAllState() object Loading : DisconnectAllState() object Updated : DisconnectAllState() } }
<template lang=""> <div class="app"> <Navbar></Navbar> <div class="row"> <div class="col-sm-4 offset-sm-4"> <div v-if="alert.message" :class="`alert ${alert.type}`">{{alert.message}}</div> </div> </div> <router-view></router-view> </div> </template> <script> import { mapState, mapActions } from 'vuex' export default { name: 'app', components: { Navbar: () => import('./Components/Header/Navbar.vue') }, computed: { ...mapState({ alert: state => state.alert }) }, methods: { ...mapActions({ clearAlert: 'alert/clear' }) }, watch: { $route (to, from){ // clear alert on location change this.clearAlert(); } } } </script>
from django.shortcuts import get_object_or_404 from posts.models import Group, Post from rest_framework import filters, permissions, viewsets from rest_framework.pagination import LimitOffsetPagination from .permissions import IsAuthorOrReadOnly from .serializers import (CommentSerializer, FollowSerializer, GroupSerializer, PostSerializer) class GroupViewSet(viewsets.ReadOnlyModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = ( permissions.IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly ) pagination_class = LimitOffsetPagination def perform_create(self, serializer): serializer.save(author=self.request.user) class CommentViewSet(viewsets.ModelViewSet): serializer_class = CommentSerializer permission_classes = ( permissions.IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly ) def get_queryset(self): post = get_object_or_404(Post, id=self.kwargs.get('post_id')) return post.comments.all() def perform_create(self, serializer): post = get_object_or_404(Post, id=self.kwargs.get('post_id')) serializer.save(author=self.request.user, post=post) class FollowViewSet(viewsets.ModelViewSet): serializer_class = FollowSerializer permission_classes = (permissions.IsAuthenticated,) filter_backends = (filters.SearchFilter,) search_fields = ('following__username',) def get_queryset(self): follows = self.request.user.follower.all() return follows def perform_create(self, serializer): serializer.save(user=self.request.user)
import { DeleteIcon } from '@chakra-ui/icons' import { Box, Center, Flex, IconButton, Text, useColorModeValue, } from '@chakra-ui/react' import React from 'react' import { useDropzone } from 'react-dropzone' import type { FileUploadProps } from './FileUpload.types' export const FileUpload: React.FunctionComponent<FileUploadProps> = (props) => { const { onRemove, onUpload, value } = props const { getInputProps, getRootProps, isDragActive } = useDropzone({ maxFiles: 1, multiple: false, onDrop: (files) => { onUpload(files[0]) }, }) const borderColor = useColorModeValue( isDragActive ? 'teal.300' : 'gray.300', isDragActive ? 'teal.500' : 'gray.500', ) return ( <Box> {value ? ( <Flex align="center" flex={{ base: 1 }} justify="space-between" > <Text> {value.name} </Text> <IconButton aria-label="Delete Image" icon={<DeleteIcon />} onClick={onRemove} /> </Flex> ) : ( <Center _hover={{ bg: 'gray.100' }} bg={isDragActive ? 'gray.100' : 'transparent'} border="3px dashed" borderColor={borderColor} borderRadius={4} cursor="pointer" p={10} transition="background-color 0.2s ease" {...getRootProps()} > <input {...getInputProps()} /> <Text align="center"> { isDragActive ? 'Drop the files here ...' : 'Drag \'n\' drop files here, or click to select files' } </Text> </Center> )} </Box> ) }
--- title: "LIA_MIA_Horizon_task_analysis" author: "Yuyan" date: "`r Sys.Date()`" output: html_document --- note: this script was copied from EXP analysis and needs to be updated for LIA/MIA analysis. The data files are ready in the processed_data/horizon_task folder under LIA_MIA_Analysis. So I can read them in directly. ```{r setup, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, cache=TRUE) ``` # Source ```{r, include=FALSE} source('Setup.R') # this script must be run first as it will clear the environment ``` ```{r, include=FALSE} # specify model predictors for data cleaning (i.e., missing data & standardization) # vars <- c('quic_total', 'standard_score', 'sparse_income_num') vars <- c('quic_p_mon', 'quic_p_predict', 'quic_p_env', 'quic_phy_env', 'quic_safety_sec', 'quic_total', 'standard_score', 'sparse_income_num') # vars <- c('quic_p_mon', 'quic_p_predict', 'quic_p_env', 'quic_phy_env', 'quic_safety_sec', 'quic_total', 'harsh', 'standard_score', 'sparse_income_num', 'kid_age', 'pss_total') source('Functions.R') source('ReadData.R') ``` # Functions ```{r, cache=TRUE, include=FALSE, message=FALSE} # notes: 'statistics' in the summary tables refers to 't value' in lm models and 'z value' in glmer models # covariates = "harsh + standard_score + sparse_income_num" # covariates = "standard_score + sparse_income_num" # quic_subscales <- c("quic_total", "quic_p_mon", "quic_p_predict", "quic_p_env", "quic_phy_env", "quic_safety_sec") # quic_subscales <- c("quic_total") lm_fun = function(response, key_var, data, covariates) { predictors <- paste(key_var, covariates, sep = " + ") formula = as.formula( paste(paste(response, "~"), predictors ) ) print(formula) lm(formula, data = data) } glmer_fun = function(response, key_var, random_structure, data, covariates) { control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) predictors <- paste(key_var, covariates, random_structure, sep = " + ") formula = as.formula( paste(paste(response, "~"), predictors ) ) print(formula) glmer(formula, data = data, family = binomial, control = control) } lmer_fun = function(response, key_var, random_structure, data, covariates) { control=lmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e6),check.nobs.vs.nRE = "ignore") predictors <- paste(key_var, covariates, random_structure, sep = " + ") formula = as.formula( paste(paste(response, "~"), predictors ) ) print(formula) lmer(formula, data = data, control = control) } run_hr_mod <- function(quic_subscales, method, analysis) { if (method == "lm") { if (analysis == "directed_exploration") { response <- c("total_horizon")} if (analysis == "rewards") { response <- c("mean_r")} # EXP models <- quic_subscales %>% map(lm_fun, response = response, data = hr_lm_EXP) EXP_summary <- map_dfr(models, tidy) %>% filter(str_detect(term, "^quic")) # LIA models <- quic_subscales %>% map(lm_fun, response = response, data = hr_lm_LIA) LIA_summary <- map_dfr(models, tidy) %>% filter(str_detect(term, "^quic")) %>% select(-term) # join data summary <- cbind(EXP_summary, LIA_summary) return(summary) } if (method == "glmer") { if (analysis == "strategic_exploration") { response <- c("chose_high_info_value") key_var <- lapply(quic_subscales, function(x) paste(x, "*horizon*conflict_str")) random_structure = "(1 + horizon + conflict_str | id)" } if (analysis == "random_exploration") { response <- c("chose_high_info_value") key_var <- lapply(quic_subscales, function(x) paste(x, "*mean_diff_adjusted")) random_structure = "(1 | id)" } if (analysis == "habitual_responding_uncertainty") { response <- c("habitual_responding") key_var <- lapply(quic_subscales, function(x) paste(x, "*fourth_choice_is_high_info_value_option")) random_structure = "(1 + fourth_choice_is_high_info_value_option | id)" } if (analysis == "habitual_responding_reward") { response <- c("habitual_responding") key_var <- lapply(quic_subscales, function(x) paste(x, "*fourth_choice_is_high_mean_option")) random_structure = "(1 + fourth_choice_is_high_mean_option | id)" } if (analysis == "fourth_choice_uncertainty") { response <- c("chose_high_info_value") key_var <- lapply(quic_subscales, function(x) paste(x, "*fourth_choice_is_high_info_value_option")) random_structure = "(1 + fourth_choice_is_high_info_value_option | id)" } if (analysis == "reward_maximization") { response <- c("chose_high_mean_c10_long") key_var <- lapply(quic_subscales, function(x) paste(x, "*mean_diff_adjusted")) random_structure = "(1 | id)" } # EXP models <- key_var %>% map(glmer_fun, response = response, random_structure = random_structure, data = hr_glmem_EXP) EXP_summary <- map_dfr(models, tidy) %>% filter(str_detect(term, "^quic")) %>% select(-c(effect, group)) # LIA models <- key_var %>% map(glmer_fun, response = response, random_structure = random_structure, data = hr_glmem_LIA) LIA_summary <- map_dfr(models, tidy) %>% filter(str_detect(term, "^quic")) %>% select(-c(effect, group)) %>% select(-term) # join data summary <- cbind(EXP_summary, LIA_summary) return(summary) } if (method == "lmer") { if (analysis == "reaction_time") { response <- c("rt5") key_var <- lapply(quic_subscales, function(x) paste(x, "*horizon*conflict_str")) random_structure = "(1 + horizon + conflict_str | id)" } # EXP models <- key_var %>% map(lmer_fun, response = response, random_structure = random_structure, data = hr_glmem_EXP) EXP_summary <- map_dfr(models, tidy) %>% filter(str_detect(term, "^quic")) %>% select(-c(effect, group)) # LIA models <- key_var %>% map(lmer_fun, response = response, random_structure = random_structure, data = hr_glmem_LIA) LIA_summary <- map_dfr(models, tidy) %>% filter(str_detect(term, "^quic")) %>% select(-c(effect, group)) %>% select(-term) # join data summary <- cbind(EXP_summary, LIA_summary) return(summary) } } summarize_models = function(output) { directed_exploration_sum <- run_hr_mod(quic_subscales, 'lm', 'directed_exploration') %>% mutate(analysis = "directed_exploration") rewards_sum <- run_hr_mod(quic_subscales, 'lm', 'rewards') %>% mutate(analysis = "rewards") strategic_exploration_sum <- run_hr_mod(quic_subscales, 'glmer', 'strategic_exploration') %>% mutate(analysis = "strategic_exploration") random_exploration_sum <- run_hr_mod(quic_subscales, 'glmer', 'random_exploration') %>% mutate(analysis = "random_exploration") habitual_responding_uncertainty_sum <- run_hr_mod(quic_subscales, 'glmer', 'habitual_responding_uncertainty') %>% mutate(analysis = "habitual_responding_uncertainty") habitual_responding_reward_sum <- run_hr_mod(quic_subscales, 'glmer', 'habitual_responding_reward') %>% mutate(analysis = "habitual_responding_reward") fourth_choice_uncertainty_sum <- run_hr_mod(quic_subscales, 'glmer', 'fourth_choice_uncertainty') %>% mutate(analysis = "fourth_choice_uncertainty") reward_maximization_sum <- run_hr_mod(quic_subscales, 'glmer', 'reward_maximization') %>% mutate(analysis = "reward_maximization") reaction_time_sum <- run_hr_mod(quic_subscales, 'lmer', 'reaction_time') %>% mutate(analysis = "reaction_time") model_sum <- bind_rows(directed_exploration_sum, rewards_sum, strategic_exploration_sum, random_exploration_sum, habitual_responding_uncertainty_sum, habitual_responding_reward_sum, fourth_choice_uncertainty_sum, reward_maximization_sum, reaction_time_sum) write.csv(model_sum, file.path(EXP_hr_dir, output)) } ``` # Correlations ### EXP ```{r} df_cor_EXP <- q_EXP %>% select(quic_total,standard_score,sparse_income_num,negstress,new_negstress,cdi) chart.Correlation(df_cor_EXP, histogram = TRUE, method = "pearson") df_cor_anx <- q_EXP %>% filter_at(vars('total_masc'),all_vars(!is.na(.))) %>% select(quic_total,standard_score,sparse_income_num,negstress,new_negstress,cdi,total_masc:sep_pan) chart.Correlation(df_cor_anx, histogram = TRUE, method = "pearson") df_cor_anx <- q_EXP %>% filter_at(vars('rcmas_totanxt'),all_vars(!is.na(.))) %>% select(quic_total,standard_score,sparse_income_num,negstress,new_negstress,cdi,rcmas_totanxt:liet) chart.Correlation(df_cor_anx, histogram = TRUE, method = "pearson") quic_scale <- q_EXP %>% select("quic_p_mon", "quic_p_predict", "quic_p_env", "quic_phy_env", "quic_safety_sec", "quic_total", "quic_use") chart.Correlation(quic_scale, histogram = TRUE, method = "pearson") ``` ### LIA ```{r} df_cor <- df_covar %>% select(quic_total,standard_score,sparse_income_num,pss_total) chart.Correlation(df_cor, histogram = TRUE, method = "pearson") quic_scale <- df_covar %>% select(starts_with("quic")) chart.Correlation(quic_scale, histogram = TRUE, method = "pearson") ``` # Models ```{r} # prepare data source('PrepHrData_MF.R') # prep horizon task model free data for analysis # source('PrepHrData_MB.R') # prep horizon task model based data for analysis # source('PrepTrData.R') # prep orchard task data for analysis # source('PrepOSFData.R') # prep data for OSF sharing ``` ```{r eval=FALSE} # run models source('Models.R') ``` ##### run models ```{r} # covariates <- as.character() run_models_fun <- function(study, with_control, var) { if (study == "EXP") { control_var <- "anxiety" data_lm <- hr_lm_EXP data_glm <- hr_glmem_EXP } else { control_var <- "pss_total" data_lm <- hr_lm_LIA data_glm <- hr_glmem_LIA } if (with_control == 0) {covariates = "standard_score + sparse_income_num"} else {covariates = paste0("standard_score + sparse_income_num + ", control_var)} # assign(covariates, covariates, envir = .GlobalEnv) print(covariates) for (i in 1:nrow(model_setup)) { var_name <- var_setup$var_name[var_setup$key_vars==var] mod_name <- paste0("mod_hr_", ifelse(study == "EXP", "", "LIA_"), var_name, "_", model_setup[i, "analysis"], ifelse(with_control == 1, "_withcontrol", "")) response <- model_setup[i, "response"] key_var <- paste0(var, model_setup[i, "term"]) type <- model_setup[i, "type"] random_structure <- model_setup[i, "random_structure"] if (type == "lm") {mod <- lm_fun(response, key_var, data_lm, covariates)} else if (type == "glmer") {mod <- glmer_fun(response, key_var, random_structure, data_glm, covariates)} else if (type == "lmer") {mod <- lmer_fun(response, key_var, random_structure, data_glm, covariates)} assign(mod_name, mod, envir = .GlobalEnv) saveRDS(get(mod_name), file.path(EXP_hr_dir, paste0("models/", mod_name, ".rds"))) } } ``` ```{r eval=FALSE} # run models analysis <- c("directed_exploration", "rewards", "strategic_exploration", "habitual_responding_info", "habitual_responding_reward", "habitual_responding", "fourth_choice", "reward_maximization", "reaction_time", "reaction_time_info", "reaction_time_reward") type <- c("lm", "lm", "glmer", "glmer", "glmer", "glmer", "glmer", "glmer", "lmer", "lmer", "lmer") response <- c("total_horizon", "mean_r", "chose_high_info_value", "habitual_responding", "habitual_responding", "chose_high_info_value", "chose_high_info_value", "chose_high_mean_c10_long", "rt5", "rt5", "rt5") term <- c("", "", "*horizon*conflict_str", "*fourth_choice_is_high_info_value_option", "*fourth_choice_is_high_mean_option", "*habitual_responding", "*fourth_choice_is_high_info_value_option", "*mean_diff_adjusted", "*horizon*conflict_str", "*fourth_choice_is_high_info_value_option", "*fourth_choice_is_high_mean_option") random_structure <-c(NA, NA, "(1 + horizon + conflict_str | id)", "(1 + fourth_choice_is_high_info_value_option | id)", "(1 + fourth_choice_is_high_mean_option | id)", "(1 + habitual_responding|id)", "(1 + fourth_choice_is_high_info_value_option | id)", "(1 | id)", "(1 + horizon + conflict_str | id)", "(1 + fourth_choice_is_high_info_value_option|id)", "(1 + fourth_choice_is_high_mean_option|id)") model_setup <- data.frame(analysis, type, response, term, random_structure) var_name <- c('mon', 'pred', 'env', 'phys', 'safe', 'quic', 'le') key_vars <- c('quic_p_mon', 'quic_p_predict', 'quic_p_env', 'quic_phy_env', 'quic_safety_sec', 'quic_total', 'new_negstress') var_setup <- data.frame(var_name, key_vars) var_name <- c('mon') key_vars <- c('quic_p_mon') var_setup <- data.frame(var_name, key_vars) key_vars %>% map(run_models_fun, study = "EXP", with_control = 0) key_vars %>% map(run_models_fun, study = "EXP", with_control = 1) head(key_vars, -1) %>% map(run_models_fun, study = "LIA", with_control = 0) head(key_vars, -1) %>% map(run_models_fun, study = "LIA", with_control = 1) ``` ##### read in models ```{r} # Make a vector of all your file paths file_paths <- list.files(path = file.path(EXP_hr_dir, "models"), pattern = "\\.rds", full.names = TRUE) # Make a vector of file names file_names <- gsub(pattern = "\\.rds$", replacement = "", x = basename(file_paths)) # Read all your data into a list data_list <- lapply(file_paths, readRDS) # Assign file names to list elements names(data_list) <- file_names ``` ##### summarize models ```{r} # note: need to use different arguments for lm, glmer, and lmer models # lm & lmer: conf.int = TRUE # glmer: conf.int = TRUE, exp = TRUE (to obtain odds ratios) # for the interpretation of regresion df and residual df, refer to this source: # https://www.freecodecamp.org/news/https-medium-com-sharadvm-how-to-read-a-regression-table-661d391e9bd7-708e75efc560/#:~:text=Residual%20df%20is%20the%20total,number%20of%20variables%20being%20estimated. tidy_mod_fun <- function(model_list) { for (i in (1:length(model_list))) { name <- names(model_list)[[i]] mod <- model_list[[i]] if (str_detect(name, "LIA")) {study = "LIA"} else {study = "EXP"} if (str_detect(name, "control")) {withcontrol = TRUE} else {withcontrol = FALSE} if (class(mod) == "glmerMod") { tibble <- mod %>% tidy(conf.int = TRUE, exp = TRUE) } else { tibble <- mod %>% tidy(conf.int = TRUE) } if(class(mod) == "lm") { df1 <- glance(data_list[[i]])$df df2 <- glance(data_list[[i]])$df.residual } else { df1 <- NA df2 <- NA} tibble <- tibble %>% mutate(study = study, name = name, withcontrol = withcontrol, df1 = df1, df2 = df2) summary <- bind_rows(summary, tibble) } return(summary) } summary <- tibble() summary <- tidy_mod_fun(data_list) %>% filter(!is.na(std.error)) %>% select(-c(effect, group, df)) ``` ##### subscales ```{r} extract_keyterms_fun <- function(vars) { table <- tibble() for (i in 1:length(vars)) { var = vars[[i]] for (i in 1:nrow(model_setup)) { if (model_setup$term[[i]] == "") {coef = var} else {coef = model_setup$term[[i]] %>% str_replace_all("\\*", ":") %>% paste0(var, .)} analysis = model_setup$analysis[[i]] if (analysis == "strategic_exploration") { parts <- str_split(coef, ":", simplify = TRUE) coef <- c(paste0(parts[[1]], ":", parts[[2]]), paste0(parts[[1]], ":", parts[[3]]), paste0(parts[[1]],":",parts[[2]],":",parts[[3]])) } print(coef) table_tmp <- summary %>% filter(str_detect(name, analysis)) %>% filter(str_detect(term, coef)) table <- rbind(table, table_tmp) } } return (table) } summary_subscales <- extract_keyterms_fun(key_vars) ``` ```{r} # subset based on model types and with_control multiple_correction_fun <- function(analysis, with_control, negate_LIA = TRUE) { tmp <- summary_subscales %>% filter(str_detect(name, analysis) & withcontrol == with_control & str_detect(name, "LIA", negate = negate_LIA)) %>% mutate(adjusted_ps = round(p.adjust(p.value, "BH"), 3)) %>% select(name, adjusted_ps, everything()) return(tmp) } subscales_EXP <- model_setup$analysis %>% map(multiple_correction_fun, with_control = FALSE, negate_LIA = TRUE) subscales_LIA <- model_setup$analysis %>% map(multiple_correction_fun, with_control = FALSE, negate_LIA = FALSE) ``` ##### EXP -- life event scale # sample glmer models ```{r} ### habitual responding guided by information control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_le_habitual_responding_info <- glmer(habitual_responding ~ fourth_choice_is_high_info_value_option*new_negstress + standard_score + sparse_income_num + (1 + fourth_choice_is_high_info_value_option |id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_le_habitual_responding_info, file.path(EXP_hr_dir, "models/mod_hr_le_habitual_responding_info.rds")) ### habitual responding guided by reward control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_le_habitual_responding_reward <- glmer(habitual_responding ~ fourth_choice_is_high_mean_option*new_negstress + standard_score + sparse_income_num + (1 + fourth_choice_is_high_mean_option|id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_le_habitual_responding_reward, file.path(EXP_hr_dir, "models/mod_hr_le_habitual_responding_reward.rds")) ### strategic exploration & temporal discounting control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_le_strategic_exploration <- glmer(chose_high_info_value ~ horizon*conflict_str*new_negstress + standard_score + sparse_income_num + (1 + horizon + conflict_str|id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_le_strategic_exploration, file.path(EXP_hr_dir, "models/mod_hr_le_strategic_exploration.rds")) ### reward maximization and task understanding (chose the high mean option at c10 as a function of reward differential) control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_le_success <- glmer(chose_high_mean_c10_long ~ mean_diff_adjusted*new_negstress + standard_score + sparse_income_num + (1 + mean_diff_adjusted|id), data = hr_glmem_EXP, family = binomial, control = control, na.action = na.omit) saveRDS(mod_hr_le_success, file.path(EXP_hr_dir, "models/mod_hr_le_success.rds")) ``` ```{r eval=FALSE} ### quic and directed exploration mod_hr_le_directed_exploration <- lm(total_horizon ~ new_negstress + standard_score + sparse_income_num, data = hr_lm_EXP) saveRDS(mod_hr_le_directed_exploration, file.path(EXP_hr_dir, "models/mod_hr_le_directed_exploration.rds")) ### quic and rewards gained mod_hr_le_rewards <- lm(mean_r ~ new_negstress + standard_score + sparse_income_num, data = hr_lm_EXP) saveRDS(mod_hr_le_rewards, file.path(EXP_hr_dir, "models/mod_hr_le_rewards.rds")) ### strategic exploration & temporal discounting control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_le_strategic_exploration <- glmer(chose_high_info_value ~ horizon*conflict_str*new_negstress + standard_score + sparse_income_num + (1 + horizon + conflict_str|id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_le_strategic_exploration, file.path(EXP_hr_dir, "models/mod_hr_le_strategic_exploration.rds")) ### habitual responding guided by information control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_le_habitual_responding_info <- glmer(habitual_responding ~ fourth_choice_is_high_info_value_option*new_negstress + standard_score + sparse_income_num + (1 + fourth_choice_is_high_info_value_option |id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_le_habitual_responding_info, file.path(EXP_hr_dir, "models/mod_hr_le_habitual_responding_info.rds")) ### habitual responding guided by reward control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_le_habitual_responding_reward <- glmer(habitual_responding ~ fourth_choice_is_high_mean_option*new_negstress + standard_score + sparse_income_num + (1 + fourth_choice_is_high_mean_option|id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_le_habitual_responding_reward, file.path(EXP_hr_dir, "models/mod_hr_le_habitual_responding_reward.rds")) ### exploration modulated by habitual responding control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_le_habitual_responding <- glmer(chose_high_info_value ~ habitual_responding*new_negstress + standard_score + sparse_income_num + (1 + habitual_responding|id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_le_habitual_responding, file.path(EXP_hr_dir, "models/mod_hr_le_habitual_responding.rds")) ### exploration modulated by whether the fourth choice is on the uncertain side control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_le_fourth_choice <- glmer(chose_high_info_value ~ fourth_choice_is_high_info_value_option*new_negstress + standard_score + sparse_income_num + (1 + fourth_choice_is_high_info_value_option|id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_le_fourth_choice, file.path(EXP_hr_dir, "models/mod_hr_le_fourth_choice.rds")) ### reward maximization and task understanding (chose the high mean option at c10 as a function of reward differential) control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_le_success <- glmer(chose_high_mean_c10_long ~ mean_diff_adjusted*new_negstress + standard_score + sparse_income_num + (1 + mean_diff_adjusted|id), data = hr_glmem_EXP, family = binomial, control = control, na.action = na.omit) saveRDS(mod_hr_le_success, file.path(EXP_hr_dir, "models/mod_hr_le_success.rds")) ### overall reaction time (impulsivity) control=lmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e6),check.nobs.vs.nRE = "ignore") mod_hr_le_reaction_time1 <- lmer(rt5 ~ horizon*conflict_str*new_negstress + standard_score + sparse_income_num + (1 + horizon + conflict_str|id), data = hr_glmem_EXP, control = control) saveRDS(mod_hr_le_reaction_time1, file.path(EXP_hr_dir, "models/mod_hr_le_reaction_time1.rds")) ### reaction time for info-guided habitual responding control=lmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e6),check.nobs.vs.nRE = "ignore") mod_hr_le_reaction_time2 <- lmer(rt5 ~ fourth_choice_is_high_info_value_option*new_negstress + standard_score + sparse_income_num + (1 + fourth_choice_is_high_info_value_option|id), data = hr_glmem_EXP, control = control) saveRDS(mod_hr_le_reaction_time2, file.path(EXP_hr_dir, "models/mod_hr_le_reaction_time2.rds")) ### reaction time for reward-guided habitual responding control=lmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e6),check.nobs.vs.nRE = "ignore") mod_hr_le_reaction_time3 <- lmer(rt5 ~ fourth_choice_is_high_mean_option*new_negstress + standard_score + sparse_income_num + (1 + fourth_choice_is_high_mean_option|id), data = hr_glmem_EXP, control = control) saveRDS(mod_hr_le_reaction_time3, file.path(EXP_hr_dir, "models/mod_hr_le_reaction_time3.rds")) ### habitual responding guided by information or reward # control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) # mod_hr_le_habitual_responding_info_reward <- glmer(habitual_responding ~ fourth_choice_is_high_info_value_option*fourth_choice_is_high_mean_option*new_negstress + standard_score + sparse_income_num + (1|id), data = hr_glmem, family = binomial, control = control) ### random exploration # control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) # mod_hr_le_random_exploration <- glmer(chose_high_info_value ~ mean_diff_adjusted*new_negstress + standard_score + sparse_income_num + (1 + mean_diff_adjusted|id), data = hr_glmem_EXP, family = binomial, control = control) # saveRDS(mod_hr_le_random_exploration, file.path(EXP_hr_dir, "models/mod_hr_le_random_exploration.rds")) ``` ##### EXP -- control for anxiety ```{r eval=FALSE} ### quic and directed exploration mod_hr_anx_directed_exploration <- lm(total_horizon ~ quic_total + anxiety + standard_score + sparse_income_num, data = hr_lm_EXP) saveRDS(mod_hr_anx_directed_exploration, file.path(EXP_hr_dir, "models/mod_hr_anx_directed_exploration.rds")) ### quic and rewards gained mod_hr_anx_rewards <- lm(mean_r ~ quic_total + anxiety + standard_score + sparse_income_num, data = hr_lm_EXP) saveRDS(mod_hr_anx_rewards, file.path(EXP_hr_dir, "models/mod_hr_anx_rewards.rds")) ### exploration modulated by whether the fourth choice is on the uncertain side control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_anx_fourth_choice <- glmer(chose_high_info_value ~ fourth_choice_is_high_info_value_option*quic_total + anxiety + standard_score + sparse_income_num + (1 + fourth_choice_is_high_info_value_option|id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_anx_fourth_choice, file.path(EXP_hr_dir, "models/mod_hr_anx_fourth_choice.rds")) ### exploration modulated by habitual responding control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_anx_habitual_responding <- glmer(chose_high_info_value ~ habitual_responding*quic_total + anxiety + standard_score + sparse_income_num + (1 + habitual_responding|id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_anx_habitual_responding, file.path(EXP_hr_dir, "models/mod_hr_anx_habitual_responding.rds")) ### habitual responding guided by information control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_anx_habitual_responding_info <- glmer(habitual_responding ~ fourth_choice_is_high_info_value_option*quic_total + anxiety + standard_score + sparse_income_num + (1 + fourth_choice_is_high_info_value_option |id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_anx_habitual_responding_info, file.path(EXP_hr_dir, "models/mod_hr_anx_habitual_responding_info.rds")) ### habitual responding guided by reward control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_anx_habitual_responding_reward <- glmer(habitual_responding ~ fourth_choice_is_high_mean_option*quic_total + anxiety + standard_score + sparse_income_num + (1 + fourth_choice_is_high_mean_option|id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_anx_habitual_responding_reward, file.path(EXP_hr_dir, "models/mod_hr_anx_habitual_responding_reward.rds")) ### strategic exploration & temporal discounting control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_anx_strategic_exploration <- glmer(chose_high_info_value ~ horizon*conflict_str*quic_total + anxiety + standard_score + sparse_income_num + (1 + horizon + conflict_str|id), data = hr_glmem_EXP, family = binomial, control = control) saveRDS(mod_hr_anx_strategic_exploration, file.path(EXP_hr_dir, "models/mod_hr_anx_strategic_exploration.rds")) ### reward maximization and task understanding (chose the high mean option at c10 as a function of reward differential) control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_hr_anx_success <- glmer(chose_high_mean_c10_long ~ mean_diff_adjusted*quic_total + anxiety + standard_score + sparse_income_num + (1 + mean_diff_adjusted|id), data = hr_glmem_EXP, family = binomial, control = control, na.action = na.omit) saveRDS(mod_hr_anx_success, file.path(EXP_hr_dir, "models/mod_hr_anx_success.rds")) ``` ##### LIA -- control for PSS ```{r eval=FALSE} ### quic and directed exploration mod_LIA_hr_pss_directed_exploration <- lm(total_horizon ~ quic_total + pss_total + standard_score + sparse_income_num, data = hr_lm_LIA) saveRDS(mod_LIA_hr_pss_directed_exploration, file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_directed_exploration.rds")) ### quic and rewards gained mod_LIA_hr_pss_rewards <- lm(mean_r ~ quic_total + pss_total + standard_score + sparse_income_num, data = hr_lm_LIA) saveRDS(mod_LIA_hr_pss_rewards, file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_rewards.rds")) ### habitual responding guided by information control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_LIA_hr_pss_habitual_responding_info <- glmer(habitual_responding ~ fourth_choice_is_high_info_value_option*quic_total + pss_total + standard_score + sparse_income_num + (1 + fourth_choice_is_high_info_value_option |id), data = hr_glmem_LIA, family = binomial, control = control) saveRDS(mod_LIA_hr_pss_habitual_responding_info, file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_habitual_responding_info.rds")) ### habitual responding guided by reward control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_LIA_hr_pss_habitual_responding_reward <- glmer(habitual_responding ~ fourth_choice_is_high_mean_option*quic_total + pss_total + standard_score + sparse_income_num + (1 + fourth_choice_is_high_mean_option|id), data = hr_glmem_LIA, family = binomial, control = control) saveRDS(mod_LIA_hr_pss_habitual_responding_reward, file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_habitual_responding_reward.rds")) ### strategic exploration control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_LIA_hr_pss_strategic_exploration <- glmer(chose_high_info_value ~ horizon*conflict_str*quic_total + pss_total + standard_score + sparse_income_num + (1 + horizon + conflict_str|id), data = hr_glmem_LIA, family = binomial, control = control) saveRDS(mod_LIA_hr_pss_strategic_exploration, file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_strategic_exploration.rds")) ### reward maximization and task understanding (chose the high mean option at c10 as a function of reward differential) control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e7)) mod_LIA_hr_pss_success <- glmer(chose_high_mean_c10_long ~ mean_diff_adjusted*quic_total + pss_total + standard_score + sparse_income_num + (1 + mean_diff_adjusted|id), data = hr_glmem_LIA, family = binomial, control = control, na.action = na.omit) saveRDS(mod_LIA_hr_pss_success, file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_success.rds")) ### overall reaction time (impulsivity) control=lmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e6),check.nobs.vs.nRE = "ignore") mod_LIA_hr_pss_reaction_time1 <- lmer(rt5 ~ horizon*conflict_str*quic_total + pss_total + standard_score + sparse_income_num + (1 + horizon + conflict_str|id), data = hr_glmem_LIA, control = control) saveRDS(mod_LIA_hr_pss_reaction_time1, file.path(EXP_hr_dir, "models/mod_LIA_hr_pss_reaction_time1.rds")) ``` # Outputs ##### EXP ```{r} print("QUIC & directed exploration") mod_hr_directed_exploration <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_directed_exploration.rds")) sjPlot::tab_model(mod_hr_directed_exploration, file = file.path(EXP_hr_dir,"plots/mod_hr_directed_exploration.doc")) # summary(mod_hr_directed_exploration) print("QUIC & strategic exploration, temporal discounting") mod_hr_strategic_exploration <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_strategic_exploration.rds")) sjPlot::tab_model(mod_hr_strategic_exploration, file = file.path(EXP_hr_dir,"plots/mod_hr_strategic_exploration.doc")) # summary(mod_hr_strategic_exploration) print("QUIC & habitual responding guided by information") mod_hr_habitual_responding_info <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_habitual_responding_info.rds")) sjPlot::tab_model(mod_hr_habitual_responding_info, file = file.path(EXP_hr_dir,"plots/mod_hr_habitual_responding_info.doc")) # summary(mod_hr_habitual_responding_info) print("QUIC & habitual responding guided by reward") mod_hr_habitual_responding_reward <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_habitual_responding_reward.rds")) sjPlot::tab_model(mod_hr_habitual_responding_reward, file = file.path(EXP_hr_dir,"plots/mod_hr_habitual_responding_reward.doc")) # summary(mod_hr_habitual_responding_reward) print("QUIC & rewards gained") mod_hr_rewards <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_rewards.rds")) sjPlot::tab_model(mod_hr_rewards, file = file.path(EXP_hr_dir,"plots/mod_hr_rewards.doc")) # summary(mod_hr_rewards) print("QUIC & reward maximization and task understanding") mod_hr_success <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_success.rds")) sjPlot::tab_model(mod_hr_success, file = file.path(EXP_hr_dir,"plots/mod_hr_success.doc")) # summary(mod_hr_success) print("QUIC & overall reaction time") mod_hr_reaction_time1 <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_reaction_time1.rds")) sjPlot::tab_model(mod_hr_reaction_time1, file = file.path(EXP_hr_dir,"plots/mod_hr_reaction_time1.doc")) # summary(mod_hr_reaction_time1) ``` ##### EXP -- life event scale ```{r} print("LE & directed exploration") assign(paste0("mod_hr_directed_exploration", "_le")) mod_hr_le_directed_exploration <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_le_directed_exploration.rds")) # sjPlot::tab_model(mod_hr_le_directed_exploration) sjPlot::tab_model(mod_hr_le_directed_exploration, file = file.path(EXP_hr_dir,"plots/mod_hr_le_directed_exploration.doc")) # summary(mod_hr_le_directed_exploration) print("LE & strategic exploration, temporal discounting") mod_hr_le_strategic_exploration <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_le_strategic_exploration.rds")) # sjPlot::tab_model(mod_hr_le_strategic_exploration) sjPlot::tab_model(mod_hr_le_strategic_exploration, file = file.path(EXP_hr_dir,"plots/mod_hr_le_strategic_exploration.doc")) # summary(mod_hr_le_strategic_exploration) print("LE & habitual responding guided by information") mod_hr_le_habitual_responding_info <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_le_habitual_responding_info.rds")) # sjPlot::tab_model(mod_hr_le_habitual_responding_info) sjPlot::tab_model(mod_hr_le_habitual_responding_info, file = file.path(EXP_hr_dir,"plots/mod_hr_le_habitual_responding_info.doc")) # summary(mod_hr_le_habitual_responding_info) print("LE & habitual responding guided by reward") mod_hr_le_habitual_responding_reward <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_le_habitual_responding_reward.rds")) # sjPlot::tab_model(mod_hr_le_habitual_responding_reward) sjPlot::tab_model(mod_hr_le_habitual_responding_reward, file = file.path(EXP_hr_dir,"plots/mod_hr_le_habitual_responding_reward.doc")) # summary(mod_hr_le_habitual_responding_reward) print("LE & rewards gained") mod_hr_le_rewards <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_le_rewards.rds")) # sjPlot::tab_model(mod_hr_le_rewards) sjPlot::tab_model(mod_hr_le_rewards, file = file.path(EXP_hr_dir,"plots/mod_hr_le_rewards.doc")) # summary(mod_hr_le_rewards) print("LE & reward maximization and task understanding") mod_hr_le_success <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_le_success.rds")) # sjPlot::tab_model(mod_hr_le_success) sjPlot::tab_model(mod_hr_le_success, file = file.path(EXP_hr_dir,"plots/mod_hr_le_success.doc")) # summary(mod_hr_le_success) print("LE & overall reaction time") mod_hr_le_reaction_time1 <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_le_reaction_time1.rds")) # sjPlot::tab_model(mod_hr_le_reaction_time1) sjPlot::tab_model(mod_hr_le_reaction_time1, file = file.path(EXP_hr_dir,"plots/mod_hr_le_reaction_time1.doc")) # summary(mod_hr_le_reaction_time1) ``` ##### EXP -- control for anxiety ```{r} print("QUIC & directed exploration, control for anxiety") mod_hr_anx_directed_exploration <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_anx_directed_exploration.rds")) # sjPlot::tab_model(mod_hr_anx_directed_exploration) sjPlot::tab_model(mod_hr_anx_directed_exploration, file = file.path(EXP_hr_dir,"plots/mod_hr_anx_directed_exploration.doc")) # summary(mod_hr_anx_directed_exploration) print("QUIC & strategic exploration, temporal discounting, control for anxiety") mod_hr_anx_strategic_exploration <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_anx_strategic_exploration.rds")) # sjPlot::tab_model(mod_hr_anx_strategic_exploration) sjPlot::tab_model(mod_hr_anx_strategic_exploration, file = file.path(EXP_hr_dir,"plots/mod_hr_anx_strategic_exploration.doc")) # summary(mod_hr_anx_strategic_exploration) print("QUIC & habitual responding guided by information, control for anxiety") mod_hr_anx_habitual_responding_info <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_anx_habitual_responding_info.rds")) # sjPlot::tab_model(mod_hr_anx_habitual_responding_info) sjPlot::tab_model(mod_hr_anx_habitual_responding_info, file = file.path(EXP_hr_dir,"plots/mod_hr_anx_habitual_responding_info.doc")) # summary(mod_hr_anx_habitual_responding_info) print("QUIC & habitual responding guided by reward, control for anxiety") mod_hr_anx_habitual_responding_reward <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_anx_habitual_responding_reward.rds")) # sjPlot::tab_model(mod_hr_anx_habitual_responding_reward) sjPlot::tab_model(mod_hr_anx_habitual_responding_reward, file = file.path(EXP_hr_dir,"plots/mod_hr_anx_habitual_responding_reward.doc")) # summary(mod_hr_anx_habitual_responding_reward) print("QUIC & rewards gained, control for anxiety") mod_hr_anx_rewards <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_anx_rewards.rds")) # sjPlot::tab_model(mod_hr_anx_rewards) sjPlot::tab_model(mod_hr_anx_rewards, file = file.path(EXP_hr_dir,"plots/mod_hr_anx_rewards.doc")) # summary(mod_hr_anx_rewards) print("QUIC & reward maximization and task understanding, control for anxiety") mod_hr_anx_success <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_anx_success.rds")) # sjPlot::tab_model(mod_hr_anx_success) sjPlot::tab_model(mod_hr_anx_success, file = file.path(EXP_hr_dir,"plots/mod_hr_anx_success.doc")) # summary(mod_hr_anx_success) # print("QUIC & overall reaction time, control for anxiety") # mod_hr_anx_reaction_time1 <- read_rds(file.path(EXP_hr_dir, "models/mod_hr_anx_reaction_time1.rds")) # sjPlot::tab_model(mod_hr_anx_reaction_time1) # sjPlot::tab_model(mod_hr_anx_reaction_time1, file = file.path(EXP_hr_dir,"plots/mod_hr_anx_reaction_time1.doc")) # summary(mod_hr_anx_reaction_time1) ``` ##### LIA ```{r} print("QUIC & directed exploration") mod_LIA_hr_directed_exploration <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_directed_exploration.rds")) # sjPlot::tab_model(mod_LIA_hr_directed_exploration) sjPlot::tab_model(mod_LIA_hr_directed_exploration, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_directed_exploration.doc")) # summary(mod_LIA_hr_directed_exploration) print("QUIC & strategic exploration, temporal discounting") mod_LIA_hr_strategic_exploration <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_strategic_exploration.rds")) # sjPlot::tab_model(mod_LIA_hr_strategic_exploration) sjPlot::tab_model(mod_LIA_hr_strategic_exploration, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_strategic_exploration.doc")) # summary(mod_LIA_hr_strategic_exploration) print("QUIC & habitual responding guided by information") mod_LIA_hr_habitual_responding_info <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_habitual_responding_info.rds")) # sjPlot::tab_model(mod_LIA_hr_habitual_responding_info) sjPlot::tab_model(mod_LIA_hr_habitual_responding_info, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_habitual_responding_info.doc")) # summary(mod_LIA_hr_habitual_responding_info) print("QUIC & habitual responding guided by reward") mod_LIA_hr_habitual_responding_reward <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_habitual_responding_reward.rds")) # sjPlot::tab_model(mod_LIA_hr_habitual_responding_reward) sjPlot::tab_model(mod_LIA_hr_habitual_responding_reward, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_habitual_responding_reward.doc")) # summary(mod_LIA_hr_habitual_responding_reward) print("QUIC & rewards gained") mod_LIA_hr_rewards <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_rewards.rds")) # sjPlot::tab_model(mod_LIA_hr_rewards) sjPlot::tab_model(mod_LIA_hr_rewards, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_rewards.doc")) # summary(mod_LIA_hr_rewards) print("QUIC & reward maximization and task understanding") mod_LIA_hr_success <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_success.rds")) # sjPlot::tab_model(mod_LIA_hr_success) sjPlot::tab_model(mod_LIA_hr_success, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_success.doc")) # summary(mod_LIA_hr_success) print("QUIC & overall reaction time") mod_LIA_hr_reaction_time1 <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_reaction_time1.rds")) # sjPlot::tab_model(mod_LIA_hr_reaction_time1) sjPlot::tab_model(mod_LIA_hr_reaction_time1, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_reaction_time1.doc")) # summary(mod_LIA_hr_reaction_time1) ``` ##### LIA -- control for PSS ```{r} print("QUIC & directed exploration, control for PSS") mod_LIA_hr_pss_directed_exploration <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_directed_exploration.rds")) # sjPlot::tab_model(mod_LIA_hr_pss_directed_exploration) sjPlot::tab_model(mod_LIA_hr_pss_directed_exploration, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_pss_directed_exploration.doc")) # summary(mod_LIA_hr_pss_directed_exploration) print("QUIC & strategic exploration, temporal discounting, control for PSS") mod_LIA_hr_pss_strategic_exploration <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_strategic_exploration.rds")) # sjPlot::tab_model(mod_LIA_hr_pss_strategic_exploration) sjPlot::tab_model(mod_LIA_hr_pss_strategic_exploration, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_pss_strategic_exploration.doc")) # summary(mod_LIA_hr_pss_strategic_exploration) print("QUIC & habitual responding guided by information, control for PSS") mod_LIA_hr_pss_habitual_responding_info <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_habitual_responding_info.rds")) # sjPlot::tab_model(mod_LIA_hr_pss_habitual_responding_info) sjPlot::tab_model(mod_LIA_hr_pss_habitual_responding_info, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_pss_habitual_responding_info.doc")) # summary(mod_LIA_hr_pss_habitual_responding_info) print("QUIC & habitual responding guided by reward, control for PSS") mod_LIA_hr_pss_habitual_responding_reward <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_habitual_responding_reward.rds")) # sjPlot::tab_model(mod_LIA_hr_pss_habitual_responding_reward) sjPlot::tab_model(mod_LIA_hr_pss_habitual_responding_reward, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_pss_habitual_responding_reward.doc")) # summary(mod_LIA_hr_pss_habitual_responding_reward) print("QUIC & rewards gained, control for PSS") mod_LIA_hr_pss_rewards <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_rewards.rds")) # sjPlot::tab_model(mod_LIA_hr_pss_rewards) sjPlot::tab_model(mod_LIA_hr_pss_rewards, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_pss_rewards.doc")) # summary(mod_LIA_hr_pss_rewards) print("QUIC & reward maximization and task understanding, control for PSS") mod_LIA_hr_pss_success <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_success.rds")) # sjPlot::tab_model(mod_LIA_hr_pss_success) sjPlot::tab_model(mod_LIA_hr_pss_success, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_pss_success.doc")) # summary(mod_LIA_hr_pss_success) print("QUIC & overall reaction time, control for PSS") mod_LIA_hr_pss_reaction_time1 <- read_rds(file.path(LIA_hr_dir, "models/mod_LIA_hr_pss_reaction_time1.rds")) # sjPlot::tab_model(mod_LIA_hr_pss_reaction_time1) sjPlot::tab_model(mod_LIA_hr_pss_reaction_time1, file = file.path(LIA_hr_dir,"plots/mod_LIA_hr_pss_reaction_time1.doc")) # summary(mod_LIA_hr_pss_reaction_time1) ```
import 'package:cv_checker/AppUtils/appColors.dart'; import 'package:cv_checker/AppUtils/lists.dart'; import 'package:flutter/material.dart'; import '../Services/commonService.dart'; class CandidateCard extends StatefulWidget { final String id; final String jobSeekerName; final String? email; final String? image; final String? createdDate; final String? modifiedDate; final int jobSector; final String jobSectorLabel; final int educationLevel; final String educationLevelLabel; final int experienceLevel; final String experienceLevelLabel; final Map item; const CandidateCard({Key? key, required this.id, required this.jobSeekerName, this.email, this.image, required this.item, required this.createdDate, this.modifiedDate, required this.jobSector, required this.jobSectorLabel, required this.educationLevel, required this.educationLevelLabel, required this.experienceLevel, required this.experienceLevelLabel, }) : super(key: key); @override State<CandidateCard> createState() => _CandidateCardState(); } class _CandidateCardState extends State<CandidateCard> { List images = Lists.randomImages; @override Widget build(BuildContext context) { images.shuffle(); var imagePath = images[0]; return Card( child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( flex: 1, child: Padding( padding: const EdgeInsets.all(8.0), child: CircleAvatar( key: UniqueKey(), backgroundColor: Colors.white, radius: 40, child: AspectRatio( aspectRatio: 1 / 1, child: ClipRRect( borderRadius:BorderRadius.circular(40), child: Image.asset(imagePath) ), ), ), ) ), Expanded( flex: 2, child: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Text(widget.jobSeekerName, style: Theme.of(context).textTheme .bodyMedium), ), Text(widget.jobSectorLabel, style: Theme.of(context).textTheme .labelSmall), Text(widget.educationLevelLabel, style: Theme.of(context) .textTheme .labelSmall), Text(widget.experienceLevelLabel, style: Theme.of(context) .textTheme .labelSmall), const SizedBox(height: 8,), ], ), ) ), Padding( padding: const EdgeInsets.fromLTRB(8,16,16,8), child: SizedBox( width: 80, height: 30, child: Container( decoration: BoxDecoration( color: AppColors.primaryColor.withOpacity(0.7), ), child: Center( child: Text(CommonService().experienceString (widget.experienceLevel), style: TextStyle( color: Colors.white, fontSize: 10, )), ) ), ), ) ], ), ); } }
#/*########################################################################## # Copyright (C) 2004-2023 European Synchrotron Radiation Facility # # This file is part of the PyMca X-ray Fluorescence Toolkit developed at # the ESRF. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # #############################################################################*/ __author__ = "V.A. Sole" __contact__ = "[email protected]" __license__ = "MIT" __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" import sys import logging import time import weakref from PyMca5.PyMcaGui import PyMcaQt as qt QTVERSION = qt.qVersion() _logger = logging.getLogger(__name__) SOURCE_EVENT = qt.QEvent.registerEventType() try: import thread except ImportError: import _thread as thread class SourceEvent(qt.QEvent): def __init__(self, ddict=None): if ddict is None: ddict = {} self.dict = ddict qt.QEvent.__init__(self, SOURCE_EVENT) class QSource(qt.QObject): sigUpdated = qt.pyqtSignal(object) def __init__(self): qt.QObject.__init__(self, None) #no parent self.surveyDict = {} self.selections = {} self.setPollTime(0.7) # 700 milliseconds self.pollerThreadId = None def setPollTime(self, pollTime): """Set polling time (in seconds)""" self._pollTime = max(pollTime, 0.1) return self._pollTime def getPollTime(self): return self._pollTime def addToPoller(self, dataObject): """Set polling for data object""" sourceName = dataObject.info['SourceName'] if sourceName != self.sourceName: raise KeyError("Trying to survey key %s on wrong source %s" % (self.sourceName,dataObject.info['SourceName'])) #that is general to any source key = dataObject.info['Key'] reference = id(dataObject) def dataObjectDestroyed(ref, dataObjectKey=key, dataObjectRef=reference): _logger.debug('data object destroyed, key was %s', dataObjectKey) _logger.debug('data object destroyed, ref was 0x%x', dataObjectRef) _logger.debug("self.surveyDict[key] = %s", self.surveyDict[key]) n = len(self.surveyDict[dataObjectKey]) if n > 0: ns = list(range(n)) newlist = [] for i in ns: try: if len(dir(self.surveyDict[dataObjectKey][i])): newlist.append(self.surveyDict[dataObjectKey][i]) except ReferenceError: pass self.surveyDict[dataObjectKey] = newlist if len(self.surveyDict[dataObjectKey]) == 0: del self.surveyDict[dataObjectKey] _logger.debug("SURVEY DICT AFTER DELETION = %s", self.surveyDict) return # create a weak reference to the dataObject and we call it dataObjectRef dataObjectRef=weakref.proxy(dataObject, dataObjectDestroyed) try: _logger.debug("Dealing with data object reference %s", dataObjectRef) if key not in self.surveyDict: self.surveyDict[key] = [dataObjectRef] self.selections[key] = [(id(dataObjectRef), dataObjectRef.info)] elif dataObjectRef not in self.surveyDict[key]: _logger.debug("dataObject reference ADDED") self.surveyDict[key].append(dataObjectRef) self.selections[key].append((id(dataObjectRef), dataObjectRef.info)) else: _logger.debug("dataObject reference IGNORED") except KeyError: print("ADDING BECAUSE OF KEY ERROR") self.surveyDict[key] = [dataObjectRef] self.selections[key] = [(id(dataObjectRef), dataObjectRef.info)] except ReferenceError: _logger.debug("NOT ADDED TO THE POLL dataObject = %s", dataObject) return if self.pollerThreadId is None: # start a new polling thread _logger.debug("starting new thread") self.pollerThreadId = thread.start_new_thread(self.__run, ()) def __run(self): _logger.debug("In QSource __run method") while len(self.surveyDict) > 0: #for key in self.surveyDict is dangerous # runtime error: dictionary changed during iteration # a mutex is needed _logger.debug("In loop") dummy = list(self.surveyDict.keys()) eventsToPost = {} #for key in self.surveyDict: for key in dummy: if key not in eventsToPost: eventsToPost[key] = [] if self.isUpdated(self.sourceName, key): _logger.debug("%s %s is updated", self.sourceName, key) try: if len(self.surveyDict[key]): #there are still instances of dataObjects event = SourceEvent() event.dict['Key'] = key event.dict['event'] = 'updated' event.dict['id'] = self.surveyDict[key] scanselection = False info = self.surveyDict[key][0].info if "scanselection" in info: scanselection = info['scanselection'] elif "selectiontype" in info: _logger.debug("selectiontype %s", info["selectiontype"]) if info["selectiontype"] == "1D": scanselection = True if (key == 'SCAN_D') or scanselection: event.dict['scanselection'] = True else: event.dict['scanselection'] = False eventsToPost[key].append(event) else: del self.surveyDict[key] del self.selections[key] except Exception: _logger.debug("error in loop %s", sys.exc_info()) del self.surveyDict[key] del self.selections[key] pass for key in eventsToPost: for event in eventsToPost[key]: qt.QApplication.postEvent(self, event) qt.QApplication.instance().processEvents() time.sleep(self._pollTime) _logger.debug("woke up") self.pollerThreadId = None self.selections = {}
import * as uws from 'uWebSockets.js' import {HttpRequest, HttpResponse, us_socket_context_t} from 'uWebSockets.js' import {lstatSync, readdirSync} from "fs" import {resolve} from "path" import chalk from 'chalk' import {Client} from './client' import {clientsStore} from './clients-store' import {listenersStore} from './listeners-store' import {env} from '../env' //import {dataSource} from "../index"; //import {UserEntity} from '../database/entity/user.entity' export const GetUws = async () => { const socketUnityOptions: uws.AppOptions = {} const socketUnity = uws.App(socketUnityOptions) const files: string[] = readdirSync(resolve(__dirname, 'events')) for (const file of files) { const filePath: string = resolve(__dirname, 'events', file) if (lstatSync(filePath).isFile()) { await import(filePath) } } console.info(chalk.green.bold(files.length, 'listeners loaded')) socketUnity.ws('/', { /* Options */ compression: 0 , maxPayloadLength: 16 * 1024 * 1024 , idleTimeout: 0 /* Handlers */ , upgrade: (res: HttpResponse, req: HttpRequest, context: us_socket_context_t) => { const clientIps: string[] = req.getHeader('x-forwarded-for').split(',') let clientIp: string | null = null if (clientIps.length) clientIp = clientIps[0] res.upgrade( {clientIp: clientIp} , req.getHeader('sec-websocket-key') , req.getHeader('sec-websocket-protocol') , req.getHeader('sec-websocket-extensions') , context, ) } , open: async (ws: uws.WebSocket) => { const client: Client = new Client(ws) console.log('WebSocket Socket client connected !', client.socketId) client.emit('socket:connected') }, message: async (ws, raw, isBinary) => { if (isBinary) { console.error('data is binary') return } const buffer: Buffer = Buffer.from(raw) const data: { ev: string, id: string, data: string } = JSON.parse(buffer.toString()) const client: Client | undefined = clientsStore.getBySocketId(data.id) if (!client) { console.error(`client not found for socket ID ${data.id}, ev ${data.ev}`) ws.close() return } try { if (!data.ev || data.ev.trim() === '') { throw new Error('event not specified !') } await listenersStore.exec(data.ev, client, data.data == "" ? "" : JSON.parse(data.data)) } catch (e) { const str: string = (e as string).toString() console.info(`error:', ${str}, ${data.ev}`) client.emit('err', str) } }, /*drain: (_ws) => { },*/ close: async (ws: uws.WebSocket/*, _code: number, _raw: ArrayBuffer*/) => { clientsStore.delete(ws.id) console.log('closing socket ', ws.id) /*await dataSource.manager.createQueryBuilder() .update(UserEntity).set({socket_id: null}) .where('socket_id = :sid', {sid: ws.id}).execute()*/ try { ws.close() }catch (err){ //ignored } }, }) socketUnity.listen(env.PORT, (listenSocket: any) => { console.info(listenSocket) if (listenSocket) { console.info('>', chalk.green(`Listening uws requests on port ${chalk.blue(env.PORT)}!`)) } else { console.info('Start failed, clients can\'t connect') } }) }
package com.dx.facade.report.param.report.profitandloss; import com.baomidou.mybatisplus.annotation.TableField; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDateTime; @Data //@TableName("dwm_member_net_amount_day") @ApiModel(value = "VenueProfitDay", description = "场馆盈亏统计天表") public class VenueNetAmountDayRespDTO implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty("日期,比如20210531") @TableField(value = "statics_date") private Integer staticsDate; @ApiModelProperty("场馆名称") private String venueName; @ApiModelProperty("场馆类型") private String venueType; @ApiModelProperty("注单数") @TableField("bet_count") private Long betCount; @ApiModelProperty("投注人数") @TableField(value = "member_count") private Long memberCount; @ApiModelProperty("投注金额") @TableField("bet_amount") private BigDecimal betAmount; @ApiModelProperty("有效投注") @TableField("valid_bet_amount") private BigDecimal validBetAmount; @ApiModelProperty("盈亏金额") @TableField("net_amount") private BigDecimal netAmount; @ApiModelProperty("资料创建时间") @TableField("created_at") private LocalDateTime createdAt; @ApiModelProperty("更新时间") @TableField("updated_at") private LocalDateTime updatedAt; }
# Python Classes and Objectives Welcome to the Python Classes and Objectives project! This project is designed to help you understand the concept of classes in Python, a fundamental aspect of object-oriented programming (OOP). By the end of this project, you'll have a strong foundation in creating and using classes, as well as an understanding of the objectives behind using classes in Python. ## Table of Contents - [Introduction to Classes](#introduction-to-classes) - [Creating a Class](#creating-a-class) - [Creating Objects (Instances)](#creating-objects-instances) - [Attributes and Methods](#attributes-and-methods) - [Inheritance](#inheritance) - [Encapsulation](#encapsulation) - [Objectives of Using Classes](#objectives-of-using-classes) - [Conclusion](#conclusion) ## Introduction to Classes Classes are a cornerstone of object-oriented programming, providing a blueprint for creating objects with shared attributes and behaviors. This project will guide you through the basics of classes and their usage in Python. ## Creating a Class Learn how to define a class using the `class` keyword, create a constructor using the `__init__` method, and establish attributes that store data associated with instances of the class. ## Creating Objects (Instances) Discover how to instantiate objects from a class, providing specific values for the attributes defined in the class's constructor. ## Attributes and Methods Explore how to define attributes (data members) that store information within objects, and methods (functions) that allow objects to perform specific actions. ## Inheritance Understand the concept of inheritance, which enables the creation of new classes that inherit attributes and methods from existing classes. This promotes code reuse and hierarchical structure. ## Encapsulation Learn about encapsulation, a principle that involves restricting access to certain components of an object. Discover how to achieve encapsulation using naming conventions. ## Objectives of Using Classes Understand the key objectives and benefits of using classes in Python: - **Modularity**: Organize code into manageable, reusable units. - **Abstraction**: Hide complex implementation details behind a simple interface. - **Encapsulation**: Bundle data and methods together to control access. - **Inheritance**: Promote code reuse and establish relationships between classes. - **Polymorphism**: Allow different classes to be treated as instances of a common superclass. ## Conclusion By completion of this project, I've gain a solid understanding of Python classes and their significance in object-oriented programming. It well-equipped me be able to create organized, maintainable, and efficient code using classes to encapsulate data and behavior. Happy coding!
const router = require('express').Router(); const { Post, User, Comment } = require('../../models'); const sequelize = require('../../config/connection'); const withAuth = require('../../utils/auth'); router.get('/', async (req, res) => { try { const PostData = await Post.findAll({ attributes: [ 'id', 'title', 'content', 'created_at' ], order: [ ['created_at', 'DESC'] ], include: [ { model: User, attributes: ['username'] }, { model: Comment, attributes: ['id', 'comment_input', 'user_id', 'post_id', 'created_at'], include: { model: User, attributes: ['username'] } } ] }); res.json(PostData); } catch (err) { console.error(err); res.status(500).json(err); } }); router.get('/:id', async (req, res) => { try { const PostData = await Post.findOne({ where: { id: req.params.id }, attributes: [ 'id', 'content', 'title', 'created_at' ], include: [ { model: User, attributes: ['username'] }, { model: Comment, attributes: ['id', 'comment_input', 'user_id', 'post_id', 'created_at'], include: { model: User, attributes: ['username'] } } ] }); if (!PostData) { res.status(404).json({ message: 'No post found with this id' }); return; } res.json(dbPostData); } catch (err) { console.error(err); res.status(500).json(err); } }); router.post('/', withAuth, async (req, res) => { try { const PostData = await Post.create({ title: req.body.title, content: req.body.content, user_id: req.session.user_id }); res.json(PostData); } catch (err) { console.error(err); res.status(500).json(err); } }); router.put('/:id', withAuth, async (req, res) => { try { const [updatedRowsCount, updatedPost] = await Post.update( { title: req.body.title, content: req.body.content }, { where: { id: req.params.id }, returning: true } ); if (!updatedPost || updatedRowsCount === 0) { res.status(404).json({ message: 'No post found with this id' }); return; } res.json({ message: 'Post updated successfully', updatedPost }); } catch (err) { console.error(err); res.status(500).json(err); } }); router.delete('/:id', withAuth, async (req, res) => { try { const deletedRowsCount = await Post.destroy({ where: { id: req.params.id } }); if (deletedRowsCount === 0) { res.status(404).json({ message: 'No post found with this id' }); return; } res.json({ message: 'Post deleted successfully' }); } catch (err) { console.error(err); res.status(500).json(err); } }); module.exports = router;
<?php declare(strict_types = 1); namespace PruebaTecnicaPh\Apps\Mb\Backend\Command\DomainEvents\RabbitMq; use PruebaTecnicaPh\Shared\Domain\Bus\Event\DomainEventSubscriber; use PruebaTecnicaPh\Shared\Infrastructure\Bus\Event\DomainEventSubscriberLocator; use PruebaTecnicaPh\Shared\Infrastructure\Bus\Event\RabbitMq\RabbitMqQueueNameFormatter; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use function Lambdish\Phunctional\each; final class GenerateSupervisorRabbitMqConsumerFilesCommand extends Command { protected static $defaultName = 'pruebatecnicaph:domain-events:rabbitmq:generate-supervisor-files'; private const EVENTS_TO_PROCESS_AT_TIME = 200; private const NUMBERS_OF_PROCESSES_PER_SUBSCRIBER = 1; private const SUPERVISOR_PATH = __DIR__ . '/../../../../build/supervisor'; private $locator; public function __construct(DomainEventSubscriberLocator $locator) { parent::__construct(); $this->locator = $locator; } protected function configure(): void { $this ->setDescription('Generate the supervisor configuration for every RabbitMQ subscriber') ->addArgument('command-path', InputArgument::OPTIONAL, 'Path on this is gonna be deployed', '/var/www'); } protected function execute(InputInterface $input, OutputInterface $output) { $path = (string) $input->getArgument('command-path'); each($this->configCreate($path), $this->locator->all()); } private function configCreate(string $path): callable { return function (DomainEventSubscriber $subscriber) use ($path) { $queueName = RabbitMqQueueNameFormatter::format($subscriber); $subscriberName = RabbitMqQueueNameFormatter::shortFormat($subscriber); $fileContent = str_replace( [ '{subscriber_name}', '{queue_name}', '{path}', '{processes}', '{events_to_process}', ], [ $subscriberName, $queueName, $path, self::NUMBERS_OF_PROCESSES_PER_SUBSCRIBER, self::EVENTS_TO_PROCESS_AT_TIME ], $this->template() ); file_put_contents($this->fileName($subscriberName), $fileContent); }; } private function template(): string { return <<<EOF [program:pruebatecnicaph_{queue_name}] command = {path}/apps/mb/backend/bin/console pruebatecnicaph:domain-events:rabbitmq:consume --env=prod {queue_name} {events_to_process} process_name = %(program_name)s_%(process_num)02d numprocs = {processes} startsecs = 1 startretries = 10 exitcodes = 2 stopwaitsecs = 300 autostart = true EOF; } private function fileName(string $queue) { return sprintf('%s/%s.ini', self::SUPERVISOR_PATH, $queue); } }
--- title: Utwórz przypisania zasobów w Aspose.Tasks linktitle: Utwórz przypisania zasobów w Aspose.Tasks second_title: Aspose.Tasks API Java description: Dzięki temu samouczkowi krok po kroku dowiedz się, jak bez wysiłku tworzyć przypisania zasobów w Aspose.Tasks dla języka Java. Efektywne zarządzanie zasobami projektu stało się proste. type: docs weight: 14 url: /pl/java/resource-assignments/create-resource-assignments/ --- ## Wstęp W zarządzaniu projektami przydział zasobów odgrywa kluczową rolę w efektywnym przydzielaniu zasobów do różnych zadań. Aspose.Tasks dla Java zapewnia potężne rozwiązanie do programowego zarządzania zasobami projektu i ich przypisaniami. W tym samouczku odkryjemy, jak krok po kroku tworzyć przypisania zasobów za pomocą Aspose.Tasks dla Java. ## Warunki wstępne Zanim zagłębimy się w tworzenie przypisań zasobów przy użyciu Aspose.Tasks dla Java, upewnij się, że posiadasz następujące elementy: ### Środowisko programistyczne Java Upewnij się, że w systemie jest zainstalowany zestaw Java Development Kit (JDK). Możesz pobrać i zainstalować JDK z[Tutaj](https://www.oracle.com/java/technologies/javase-jdk11-downloads.html). ### Aspose.Tasks dla biblioteki Java Pobierz bibliotekę Aspose.Tasks dla Java z[strona pobierania](https://releases.aspose.com/tasks/java/). Postępuj zgodnie z instrukcjami instalacji, aby skonfigurować bibliotekę w projekcie Java. ## Importuj pakiety W swoim kodzie Java zaimportuj niezbędne pakiety z Aspose.Tasks dla Java, aby wykorzystać jego funkcjonalność: ```java import com.aspose.tasks.Project; import com.aspose.tasks.Resource; import com.aspose.tasks.ResourceAssignment; import com.aspose.tasks.Task; ``` ## Krok 1: Utwórz obiekt projektu Utwórz instancję a`Project`obiekt, który reprezentuje plik projektu, z którym pracujesz: ```java Project project = new Project(); ``` ## Krok 2: Dodaj zadanie do projektu Dodaj zadanie do projektu za pomocą`addChild` metoda zadania głównego: ```java Task task = project.getRootTask().getChildren().add("Task"); ``` ## Krok 3: Dodaj zasób do projektu Dodaj zasób do projektu za pomocą metody`add` metoda`Resources` kolekcja: ```java Resource rsc = project.getResources().add("Rsc"); ``` ## Krok 4: Utwórz przydział zasobów Utwórz przypisanie zasobu dla zadania i zasobu za pomocą narzędzia`add` metoda`ResourceAssignments` kolekcja: ```java ResourceAssignment assn = project.getResourceAssignments().add(task, rsc); ``` ## Wniosek W tym samouczku nauczyliśmy się, jak tworzyć przypisania zasobów w Aspose.Tasks dla Java. Wykonując poniższe kroki, można efektywnie zarządzać alokacją zasobów w aplikacjach do zarządzania projektami. ## Często zadawane pytania ### P: Czy mogę modyfikować przydziały zasobów po utworzeniu? O: Tak, możesz aktualizować przypisania zasobów za pomocą metod Aspose.Tasks for Java dostępnych w bibliotece. ### P: Czy Aspose.Tasks for Java jest kompatybilny z różnymi formatami plików projektów? O: Oczywiście, Aspose.Tasks dla Java obsługuje różne formaty plików projektów, w tym MPP, XML i inne. ### P: Czy Aspose.Tasks dla Java wymaga licencji do użytku komercyjnego? O: Tak, potrzebujesz ważnej licencji, aby używać Aspose.Tasks dla Java w projektach komercyjnych. Licencję można uzyskać ze strony internetowej Aspose. ### P: Czy mogę używać Aspose.Tasks dla Java w moich aplikacjach internetowych? O: Tak, możesz zintegrować Aspose.Tasks for Java ze swoimi aplikacjami internetowymi w celu dynamicznego zarządzania zasobami projektu. ### P: Gdzie mogę znaleźć dodatkowe wsparcie dla Aspose.Tasks dla Java? O: Możesz odwiedzić[Forum Aspose.Tasks](https://forum.aspose.com/c/tasks/15) w celu uzyskania pomocy technicznej lub zapytań dotyczących biblioteki.
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using z5.ms.common.attributes; namespace z5.ms.common.abstractions { /// <summary>Error model</summary> /// <remarks>https://wiki.axinom.com/display/PA/Error+Handling</remarks> [JsonObject(MemberSerialization.OptIn, Title = "error")] public class Error { /// <summary>Unique integer error code</summary> [JsonProperty("code", Required = Required.Always, NullValueHandling = NullValueHandling.Ignore)] public int Code { get; set; } = 1; /// <summary>Error message in Neutral system language</summary> [JsonProperty("message", Required = Required.Always, NullValueHandling = NullValueHandling.Ignore)] public string Message { get; set; } //TODO Rename or extend to better reflect purpose as optional additional error information /// <summary>If input fields were available for this API call, validation errors per field will be included.</summary> [JsonProperty("fields", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)] public List<ErrorField> Fields { get; set; } /// <inheritdoc /> public override string ToString() => $"[Error - code: {Code}, message: {Message}]"; } /// <summary>Validation message for a specific field.</summary> public class ErrorField { /// <summary>The property name of the validated field.</summary> [JsonProperty("field", Required = Required.Always)] public string Field { get; set; } /// <summary>The value of the validated field.</summary> [JsonProperty("value", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)] public string Value { get; set; } /// <summary>The validation message for the corresponding field.</summary> [JsonProperty("message", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)] public string Message { get; set; } } /// <summary>Error code extensions</summary> public static class ErrorExtensions { /// <summary> /// Get error model from one of the listed error codes in Error Codes enumerations. /// Usage: ErrorCodes.Success.GetError(), MenuErrorCodes.Unavailable.GetError(). /// </summary> /// <param name="enumValue">A value from error codes enumeration</param> /// <param name="message">Optional message text</param> /// <returns>Error model with integer code and error message in neutral language</returns> public static Error GetError(this Enum enumValue, string message = null) => new Error { Code = Convert.ToInt32(enumValue), Message = String.IsNullOrEmpty(message) ? enumValue.GetTitle() : message }; /// <summary> /// Set specified fields to be error's fields /// </summary> /// <param name="error">Error object that needs fields to be attached</param> /// <param name="errorFields">Fields that will be added to Error</param> /// <returns>Error with specified fields.</returns> public static Error WithFields(this Error error, params ErrorField[] errorFields) { error.Fields = new List<ErrorField>(); error.Fields.AddRange(errorFields.ToList()); return error; } } }
import React, { useState } from "react"; import { View, StyleSheet, Image, Text, Alert } from "react-native"; import {TextInput,Button} from 'react-native-paper' import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import { Formik } from 'formik'; import * as Yup from 'yup' import auth from '@react-native-firebase/auth'; import firestore from '@react-native-firebase/firestore'; import { useNavigation } from "@react-navigation/native"; import { primaryColor } from "../assets/color"; import { TouchableOpacity } from "react-native-gesture-handler"; function Signup() { const [show, setShow] = useState(true) const navigation = useNavigation() //signup const handleSignUp = async values => { const { email, password } = values; try { const userCredential = await auth().createUserWithEmailAndPassword(email, password); const userId = userCredential.user.uid; await firestore().collection('users').doc(email).set({ email: email, userId: userId, }); navigation.navigate('Login'); } catch (error) { console.error('Error signing up:', error); Alert.alert('Thông báo',error) } }; const validateSchema = Yup.object().shape({ email: Yup.string().email('Email không hợp lệ').required('Vui lòng nhập email'), password: Yup.string().min(6, 'Mật khẩu phải có ít nhất 6 ký tự').matches( /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/, 'Mật khẩu phải chứa ít nhất 1 chữ hoa, 1 chữ thường, 1 số, và 1 ký tự đặc biệt').required('Vui lòng nhập mật khẩu'), confirmpassword: Yup.string() .oneOf([Yup.ref('password'), null], 'Mật khẩu không khớp') .required('Vui lòng nhập lại mật khẩu'), }) return ( <View style={styles.container}> <Image source={{uri: 'https://nhainonline.vn/wp-content/uploads/2023/03/goi-y-nhung-logo-hoa-qua-sach.png'}} style={styles.img}/> <Text style={styles.title}>Create new account</Text> <Formik initialValues={{ email : '', password : '', confirmpassword : '' }} onSubmit={values => handleSignUp(values)} validationSchema={validateSchema} > {({handleBlur,handleChange,handleSubmit,values,touched,errors}) =>( <View> <TextInput label="Email" placeholder="Enter your email address" value={values.email} onChangeText={handleChange('email')} onBlur={handleBlur('email')} style={styles.txtInput} /> {touched.email && errors.email && <Text style={{ color: 'red',marginLeft:15 }}>{errors.email}</Text>} <TextInput label="Password" placeholder="Enter your password" value={values.password} onChangeText={handleChange('password')} onBlur={handleBlur('password')} style={styles.txtInput} secureTextEntry={show} right={<TextInput.Icon icon= 'eye' onPress={()=> setShow(!show)}/>} /> {touched.password && errors.password && <Text style={{ color: 'red',marginLeft:15 }}>{errors.password}</Text>} <TextInput label="Confirm Password" placeholder="Enter your confirm password" value={values.confirmpassword} onChangeText={handleChange('confirmpassword')} onBlur={handleBlur('confirmpassword')} style={styles.txtInput} secureTextEntry={show} right={<TextInput.Icon icon= 'eye' onPress={()=> setShow(!show)}/>} /> {touched.confirmpassword && errors.confirmpassword && <Text style={{ color: 'red',marginLeft:15 }}>{errors.confirmpassword}</Text>} <Button mode="contained" style={styles.btn} onPress={handleSubmit}> <Text style={styles.txtBtn}>Đăng ký</Text> </Button> <TouchableOpacity style={{alignItems:'center'}} onPress={()=>{navigation.navigate('Login')}}> <Text style={styles.txt}> Already have account? <Text style={styles.txtLink}>Sign in</Text> </Text> </TouchableOpacity> </View> )} </Formik> </View> ); } const styles = StyleSheet.create({ container:{ flex:1, backgroundColor:'#fff' }, img:{ width:200, height:200, alignSelf:'center', marginBottom:20 }, title:{ textAlign:'center', fontSize:25, fontWeight:'bold', color:'#000', marginLeft:10, marginBottom:20 }, txt:{ fontSize:20, color:'#000', }, txtInput:{ marginLeft:10, marginRight:10, marginTop:10, }, txtLink:{ fontSize:20, color:'#27A2F0', alignSelf:'flex-end', marginRight:10, marginTop:10, marginBottom:30 }, btn:{ borderRadius:0, borderWidth:1, backgroundColor:primaryColor, marginLeft:10, marginRight:10, marginBottom:20, paddingTop:5, paddingBottom:5 }, txtBtn:{ fontSize:20, color:'#fff', }, wrapBtn:{ flexDirection:'row', justifyContent:'center', }, btnSocial:{ borderRadius:20, backgroundColor:'#fff', marginLeft:10, marginRight:10, marginBottom:20, paddingTop:15, paddingBottom:15 }, txtBtn:{ fontSize:20, color:'#fff', }, }) export default Signup;
<template> <Transition name="view"> <div v-if="showView"> <h4 class="view-name">{{ viewName }}</h4> <hr class="red"> <div class="row app-options-bar"> <div class="col buttons-component"> <ButtonBarComponent @onCreate="handleCreate" /> </div> <div class="col search-component"> <SearchComponent @onSearch="handleSearch" /> </div> </div> <DataTableComponent v-if="!levelsByArea.loading" rowId="clave" :columns="columns" :data="levelsByArea.data" :pagination="levelsByArea.pagination" showDelete showEdit @onPaginate="handlePaginate" @onEdit="handleEdit" @onDelete="handleDelete" @onCreate="handleCreate" /> </div> </Transition> </template> <script setup lang="ts"> import { onMounted, ref } from 'vue' import { useLevelsByArea } from '@/composables/useLevelsByArea' import DataTableComponent from '@/components/DataTableComponent.vue' import router from '@/router' import SearchComponent from '@/components/SearchComponent.vue' import ButtonBarComponent from '@/components/ButtonBarComponent.vue' const viewName = 'Niveles por Area' const { levelsByArea, getLevelsByArea, searchLevelsByArea } = useLevelsByArea() const searchText = ref<string>('') const showView = ref(false) const handleCreate = () => router.push({ name: 'crear-nivel-area' }) const handleEdit = (data: any) => router.push({ name: 'editar-nivel-area', params: { id: data } }) const handleDelete = (data: any) => router.push({ name: 'eliminar-nivel-area', params: { id: data } }) const handlePaginate = (page: number) => { if (searchText.value) { searchLevelsByArea(searchText.value, page) } else { getLevelsByArea({ page }) } } const handleSearch = (term: any) => { searchText.value = term searchLevelsByArea(term, 1) } const columns = [ { title: 'Clave', data: 'clave', align: 'center' }, { title: 'Nombre', data: 'nombre', align: 'left' }, ] onMounted(() => { getLevelsByArea({ page: 1 }).then(() => showView.value = true) }) </script> <style lang="scss" scoped></style>
package net.jenske.hyttebooking.controller; import jakarta.validation.Valid; import net.jenske.hyttebooking.controller.exception.ResourceNotFoundException; import net.jenske.hyttebooking.model.User; import net.jenske.hyttebooking.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; @RestController @CrossOrigin(origins = "http://localhost:8081") @RequestMapping(path = "/api", produces = MediaType.APPLICATION_JSON_VALUE) public class UserController { @Autowired UserRepository userRepository; /** * Gets all users. * * @return a list of users */ @GetMapping("/users") public ResponseEntity<List<User>> getAllUsers(@RequestParam(required = false) String email) { try { List<User> users = new ArrayList<User>(); if (email == null) users.addAll(userRepository.findAll()); else users.addAll(userRepository.findByEmailContaining(email)); if (users.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } return new ResponseEntity<>(users, HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Gets user by id. * * @param id the unique identifier of the user to be retrieved * @return a list of users */ @GetMapping("/users/{id}") public ResponseEntity<User> getUserById(@PathVariable("id") long id) { User user = userRepository.findById(id). orElseThrow(() -> new ResourceNotFoundException("User not found for this id: " + id)); return ResponseEntity.ok(user); } /** * Creates a new user in the system. * * @param user the user object to be created * @return the newly created user with a 201 status code, or an error message if the creation fails */ @PostMapping("/users") public ResponseEntity<User> createUser(@Valid @RequestBody User user) { try { Optional<User> existingUser = userRepository.findByEmail(user.getEmail()); if (existingUser.isPresent()) { return new ResponseEntity<>(existingUser.get(), HttpStatus.OK); // User already exists } User _user = userRepository .save(new User(user.getFirstName(), user.getLastName(), user.getEmail(), user.getSub())); return new ResponseEntity<>(_user, HttpStatus.CREATED); } catch (Exception e) { throw new ResourceNotFoundException(e.getMessage()); } } /** * Updates an existing user's details in the system. * * @param id the unique identifier of the user to update * @param user the updated user information * @return the updated user, or a not found response if the user with the specified ID doesn't exist */ @PutMapping("/users/{id}") public ResponseEntity<User> updateUser(@Valid @PathVariable("id") long id, @RequestBody User user) { Optional<User> userData = userRepository.findById(id); if (userData.isPresent()) { User _user = userData.get(); _user.setFirstName(user.getFirstName()); _user.setLastName(user.getLastName()); _user.setEmail(user.getEmail()); return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } /** * Deletes a user from the system. * * @param id the unique identifier of the user to be deleted * @return a 204 status code if the deletion is successful, or an error message if the deletion fails */ @DeleteMapping("/users/{id}") public ResponseEntity<HttpStatus> deleteUser(@PathVariable("id") long id) { User user = userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id)); userRepository.delete(user); return ResponseEntity.noContent().build(); } }
# coding=UTF8 import threading import time import traceback from queue import Queue from typing import List from common.logger import logger from qqsdk.message import GeneralMsg, GroupMsg, GroupNudgeMsg from qqsdk.message.msghandler import MsgHandler Thread = threading.Thread class EventListener(Thread): interval = 0.1 running = True msg_handlers: List[MsgHandler] def __init__(self): self.msgs = Queue() self.thread_lock = threading.Lock() super(EventListener, self).__init__(daemon=True) def add_msg(self, msg: GeneralMsg): msg.qq_client = self self.msgs.put(msg) def pause(self): with self.thread_lock: self.running = False def restore(self): with self.thread_lock: self.running = True def run(self): while self.running: try: self.__run() except Exception as e: logger.error(f"EventListener出现异常 {e}:{traceback.format_exc()}") def __run(self): # logger.debug("等待消息") msg: GeneralMsg = self.msgs.get() # logger.debug(f"收到消息 {msg.msg}") for handler in self.msg_handlers: # logger.debug(f"检查消息处理器 {handler.name}") if not handler.check_enabled(): # logger.debug(f"消息处理器未启用 {handler.name}") continue if hasattr(msg, "group"): if not handler.check_enabled(msg.group.qq): # logger.debug(f"消息处理器未在群{msg.group.name}启用 {handler.name}") continue paused_secs = 0 while msg.is_paused: paused_secs += 1 if paused_secs >= 30: break time.sleep(1) if msg.is_over: # logger.debug(f"消息已经处理完毕 {msg.msg}") break if handler.check_type(msg): # logger.debug(f"消息处理器 {handler.name} 符合消息类型,开始处理消息 {msg.msg}") try: if handler.is_async: threading.Thread(target=lambda: handler.handle(msg), daemon=True).start() else: handler.handle(msg) except Exception as e: # logger.error(f"处理消息时出现异常 {e}:{traceback.format_exc()}") msg.resume() else: pass # logger.debug(f"消息处理器 {handler.name} 不符合消息类型 {msg.msg_type}") time.sleep(self.interval)
import Link from "next/link"; import { graphql } from "../services/lib/graphql/generated"; import { FragmentType, useFragment, } from "../services/lib/graphql/generated/fragment-masking"; import Avatar from "./avatar"; import CoverImage from "./cover-image"; import DateComponent from "./date"; export const BlogPostFragment = graphql(/* GraphQL */ ` fragment HeroPostItem on BlogPost { slug title heroImage { url } publishDate author { name image { url } } } `); export const HeroPost = (props: { hero: FragmentType<typeof BlogPostFragment>; }) => { const {title, slug, heroImage, publishDate, author} = useFragment(BlogPostFragment, props.hero); return ( <section> <div className="mb-8 md:mb-16"> <CoverImage title={title} slug={slug} url={heroImage.url} /> </div> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28"> <div> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight"> <Link href={`/posts/${slug}`} className="hover:underline"> {title} </Link> </h3> <div className="mb-4 md:mb-0 text-lg"> <DateComponent dateString={publishDate} /> </div> </div> <div> {author && <Avatar name={author.name} picture={author.image} />} </div> </div> </section> ); }
import { useState, useEffect } from "react"; import { Box, Typography } from "@mui/material"; import { Videos } from "./"; import { useParams } from "react-router-dom"; import data from "../utils/data.json"; const SearchFeed = () => { const [videos, setvideos] = useState([]); const { searchTerm } = useParams(); useEffect(() => { let newData = data.filter(function (el) { return el.videoName.includes(searchTerm); }); setvideos(newData); }, [searchTerm]); return ( <Box p={2} sx={{ overflowY: "auto", height: "90vh", flex: 2 }}> <Typography variant="h4" fontWeight="bold" mb={2} sx={{ color: "white" }}> Search Results For{" "} <span style={{ color: "#f31503" }}>{searchTerm}</span> videos </Typography> <Videos videos={videos} /> </Box> ); }; export default SearchFeed;
sqrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) Return the positive square-root of an array, element-wise. Parameters ---------- x : array_like The values whose square-roots are required. out : ndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or `None`, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. where : array_like, optional Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone. **kwargs For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`. Returns ------- y : ndarray An array of the same shape as `x`, containing the positive square-root of each element in `x`. If any element in `x` is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in `x` are real, so is `y`, with negative elements returning ``nan``. If `out` was provided, `y` is a reference to it. See Also -------- lib.scimath.sqrt A version which returns complex numbers when given negative reals. Notes ----- *sqrt* has--consistent with common convention--as its branch cut the real "interval" [`-inf`, 0), and is continuous from above on it. A branch cut is a curve in the complex plane across which a given complex function fails to be continuous. Examples -------- >>> np.sqrt([1,4,9]) array([ 1., 2., 3.]) >>> np.sqrt([4, -1, -3+4J]) array([ 2.+0.j, 0.+1.j, 1.+2.j]) >>> np.sqrt([4, -1, numpy.inf]) array([ 2., NaN, Inf])
// Libraries import React from 'react'; // CSS import './index.styles.css'; interface IProps { className?: string; href?: string; children?: React.ReactNode; } const Link: React.FC<IProps> = ({ className = '', href = '', children = <></> }) => { const handleClick = (event: React.MouseEvent) => { event.preventDefault(); window.history.pushState({}, '', href); const pathEvent = new PopStateEvent('popstate'); window.dispatchEvent(pathEvent); }; return ( <a className={className} href={href} onClick={handleClick}> {children} </a> ); }; export default Link;
import React from "react"; import type { AppProps } from "next/app"; import { ChainId, Web3sdkioProvider } from "@web3sdkio/react"; import Head from "next/head"; import Web3sdkioGuideFooter from "../components/guide/Web3sdkioGuideFooter"; import "./styles/globals.css"; // This is the chainId your dApp will work on. const activeChainId = ChainId.Mumbai; function MyApp({ Component, pageProps }: AppProps) { return ( <Web3sdkioProvider desiredChainId={activeChainId}> <Head> <title>web3sdkio Signature Based Minting</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="web3sdkio Example Repository to Showcase signature based minting on an NFT Collection contract" /> <meta name="keywords" content="web3sdkio signature based minting" /> </Head> <Component {...pageProps} /> <Web3sdkioGuideFooter /> </Web3sdkioProvider> ); } export default MyApp;
package com.teamx.hatlyDriver.ui.fragments.wallet import android.os.Bundle import android.view.View import android.widget.AbsListView import androidx.core.content.res.ResourcesCompat import androidx.navigation.navOptions import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.teamx.hatlyDriver.BR import com.teamx.hatlyDriver.MainApplication import com.teamx.hatlyDriver.R import com.teamx.hatlyDriver.baseclasses.BaseFragment import com.teamx.hatlyDriver.data.remote.Resource import com.teamx.hatlyDriver.databinding.FragmentTransactionBinding import com.teamx.hatlyDriver.localization.LocaleManager import com.teamx.hatlyDriver.utils.snackbar import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class TranscationHistoryFragment : BaseFragment<FragmentTransactionBinding, WalletViewModel>() { override val layoutId: Int get() = R.layout.fragment_transaction override val viewModel: Class<WalletViewModel> get() = WalletViewModel::class.java override val bindingVariable: Int get() = BR.viewModel var isScrolling = false var currentItems = 0 var totalItems = 0 var scrollOutItems = 0 lateinit var transactionHistoryAdapter: TransactionAdapter lateinit var transactionHistoryArrayList: ArrayList<com.teamx.hatlyDriver.data.dataclasses.transactionHistory.Doc> override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) options = navOptions { anim { enter = R.anim.enter_from_left exit = R.anim.exit_to_left popEnter = R.anim.nav_default_pop_enter_anim popExit = R.anim.nav_default_pop_exit_anim } } if (!MainApplication.localeManager!!.getLanguage() .equals(LocaleManager.Companion.LANGUAGE_ENGLISH) ) { mViewDataBinding.imgBack.setImageDrawable( ResourcesCompat.getDrawable( resources, R.drawable.stripe_ic_arrow_right_circle, requireActivity().theme ) ) } else { mViewDataBinding.imgBack.setImageDrawable( ResourcesCompat.getDrawable( resources, R.drawable.back_arrow, requireActivity().theme ) ) } mViewDataBinding.imgBack.setOnClickListener { popUpStack() } mViewModel.trancationHisotory(10, 1) if (!mViewModel.transactionHistoryResponse.hasActiveObservers()) { mViewModel.transactionHistoryResponse.observe(requireActivity()) { when (it.status) { Resource.Status.LOADING -> { loadingDialog.show() } Resource.Status.AUTH -> { loadingDialog.dismiss() onToSignUpPage() } Resource.Status.SUCCESS -> { loadingDialog.dismiss() it.data?.let { data -> data.docs.forEach { transactionHistoryArrayList.add(it) } transactionHistoryAdapter.notifyDataSetChanged() } } Resource.Status.ERROR -> { loadingDialog.dismiss() mViewDataBinding.root.snackbar(it.message!!) } } } } transactionHistoryArrayList = ArrayList() val linearLayoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) mViewDataBinding.recTrans.layoutManager = linearLayoutManager transactionHistoryAdapter = TransactionAdapter(transactionHistoryArrayList) mViewDataBinding.recTrans.adapter = transactionHistoryAdapter mViewDataBinding.recTrans.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { isScrolling = true } } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) currentItems = linearLayoutManager.childCount totalItems = linearLayoutManager.itemCount scrollOutItems = linearLayoutManager.findFirstVisibleItemPosition() if (isScrolling && (currentItems + scrollOutItems == totalItems)) { isScrolling = false; // fetchData() } } }) } }
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import 'hardhat/console.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol'; import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; contract RewardDistributor is EIP712, Ownable { using SafeERC20 for IERC20; // Whether the reward is ERC20 token or not (if not, ETH is used) bool public isUsingERC20Token; // ERC20 token address to use as rewards address public token; // Mapping between addresses and the total reward amounts given to them so far mapping(address => uint256) public cumulativeClaimedAmounts; event Claimed(address indexed account, uint256 cumulativeAmount, uint256 amount); constructor(bool isUsingERC20Token_, address token_) payable EIP712('stamp-rally-poc', '0.0.1') { isUsingERC20Token = isUsingERC20Token_; token = token_; console.log('Deploying a distributor'); } function resetClaimedAmount(address account) public onlyOwner { cumulativeClaimedAmounts[account] = 0; } function claim( address account, uint256 cumulativeAmount, bytes calldata signature ) public { // Check signature require(_verify(_hash(account, cumulativeAmount), signature), 'Invalid signature'); console.log(account, 'claimed', cumulativeAmount); // Check if there is a reward to claim uint256 preclaimed = cumulativeClaimedAmounts[account]; require(preclaimed < cumulativeAmount, 'Nothing to claim'); cumulativeClaimedAmounts[account] = cumulativeAmount; // Send the token uint256 amount = cumulativeAmount - preclaimed; if (isUsingERC20Token) { IERC20(token).safeTransfer(account, amount); } else { (bool success, ) = (account).call{value: amount}(''); require(success, 'Failed to transfer eth'); } emit Claimed(account, cumulativeAmount, amount); } function _hash(address account, uint256 cumulativeAmount) internal view returns (bytes32) { return _hashTypedDataV4( keccak256( abi.encode( keccak256('Reward(address account,uint256 cumulativeAmount)'), account, cumulativeAmount ) ) ); } function _verify(bytes32 digest, bytes calldata signature) internal view returns (bool) { return owner() == ECDSA.recover(digest, signature); } // receive() is required for the contract to receive ETH receive() external payable {} }
import { IReportSection, ReportSectionInfo } from "./baseHistoryReportSection"; import { PatienDataModelService } from "../../patienDataModelService"; import { ReportSectionNames } from "../../../constants/reportSectionNames"; export class AssessmentSection implements IReportSection { constructor(private patienDataModelService: PatienDataModelService) { } getHtmlString(reportSectionInfo: ReportSectionInfo): Promise<string> { const patientAdmissionModel = JSON.parse(reportSectionInfo.admission.AdmissionData).patientRoot; const assessments = this.getAssessments(patientAdmissionModel, reportSectionInfo.sectionName); if (!assessments) { return Promise.resolve(""); } const assessmentsTemplate = ` <div style="margin-top:15px;line-height:1em;" id="${ReportSectionNames.assessment}"> <div><b>Assessment:</b><div> <ul style="list-style-type:square;">${assessments}</ul> </div>`; return Promise.resolve(assessmentsTemplate); } private getAssessments(patientAdmissionModel: any, sectionName: string): string { const patientAdmissionSection = this.patienDataModelService .getPatientAdmissionSectionByName(sectionName, patientAdmissionModel); const assessments = patientAdmissionSection.value; if (!assessments || !assessments.length) { return ""; } let assessmentListItems = ""; for (let i = 0; i < assessments.length; i++) { const assessment = assessments[i]; if (assessment.IsDelete) { continue; } assessmentListItems += ` <li> <div><b>${assessment.Diagnosis}</b></div> <div>${assessment.Notes}</div> </li>`; } return assessmentListItems; } }
# C 中的 textheight()函数 > 原文:[https://www.geeksforgeeks.org/textheight-function-c/](https://www.geeksforgeeks.org/textheight-function-c/) 头文件 graphics.h 包含 **textheight()** 函数,以像素为单位返回输入字符串的高度。 **语法:** ```cpp int textheight(char *string); ``` **示例:** ```cpp Input : string = "Hello Geek ! Have a good day." Output : ``` 下面是 textheight()函数的实现。 ```cpp // C Implementation for textheight() #include <graphics.h> #include <stdio.h> // driver code int main() {     // gm is Graphics mode which is     // a computer display mode that     // generates image using pixels.     // DETECT is a macro defined in     // "graphics.h" header file     int gd = DETECT, gm, color, height;     char arr[100];     // initgraph initializes the     // graphics system by loading a     // graphics driver from disk     initgraph(&gd, &gm, "");     // textheight function     height = textheight("Hello Geek ! Have a good day.");     //sprintf stands for “String print”.     //Instead of printing on console,     //it store output on char buffer     //which are specified in sprintf     sprintf(arr, "Textheight is = %d", height);     //outtext function displays text     //at current position.     outtext(arr);     getch();     // closegraph function closes the     // graphics mode and deallocates     // all memory allocated by     // graphics system .     closegraph();     return 0; } ``` 输出:
Brand Identity Package _Cloudfuse Creations_ _Objectives_<br /> To design a fully operational identity package based off your logo. The identity package will include a letterhead, envelope and a business card. Be sure to use consistent design elements throughout the identity package and pay close attention to detail. _Research_<br /> Start by researching successful examples of existing identity packages in books like Print’s Best Letterheads and Business Cards or on the web at www.commarts. Pay close attention to linking design elements throughout the identity and how they work together as a group. Did the package use a second font? What kind/size of paper was used? What point size were the fonts? How is the negative space activated? _Process_<br /> • Begin by creating eight thumbnails<br /> • Concentrate on branding your system through repetition<br /> • Scale contrast will help add visual interest<br /> • Write out all information before starting<br /> • Letterhead, card and envelope equals one thumb<br /> • Supporting elements must work off your logo<br /> • Don’t forget about paper and folds as elements<br /> • Negative space activation is very important<br /> • Digitize your concepts using InDesign<br /> • Use tabs and as few text boxes as possible<br /> • Package your project to include fonts and imagery
/** * Задача 4. * * Вручную создать имплементацию функции `some`. * Логика работы ручной имплементации должна быть такой-же, * как и у встроенного метода. * * Заметки: * - Встроенный метод Array.prototype.some использовать запрещено. * * Генерировать ошибки, если: * - В качестве первого аргумента был передан не массив; * - В качестве второго аргумента была передана не функция. * * Заметки: * - Второй аргумент встроенного метода some (thisArg) имплементировать не нужно. */ const array = [1, 2, 'str', 4, 5, 6]; const some = function (array, cb) { for (let i = 0; i < array.length; i++) { const result = cb (array[i], i, array); if (result) { return true; } } return false; } const result = some(array, (element, index, arrayRef) => { // console.log(`${index}:`, element, arrayRef); return typeof element === 'string'; }); console.log(result); // true
import { ColumnDef, flexRender, getCoreRowModel, getSortedRowModel, SortingState, useReactTable } from '@tanstack/react-table'; import { DeleteButton } from 'components/atoms/DeleteButton'; import { EditButton } from 'components/atoms/EditButton'; import { SortButton } from 'components/atoms/SortButton'; import { deleteArea } from 'lib/api-routes/my-api'; import { parseDate } from 'lib/utils/parse-date'; import { useRouter } from 'next/router'; import { useState, useEffect, useMemo } from 'react'; import { useMutation, useQueryClient } from 'react-query'; import { AcceptButton } from '../atoms/AcceptButton'; declare module '@tanstack/react-table' { interface TableMeta { updateData: (rowIndex: number, columnId: string, value: unknown) => void; } } type Area = { id: number; name: string; width: number; height: number; createdAt: string; updatedAt: string; }; type AreasTableType = { apiResponse: any; taskId?: number; localizationId?: number; dataQuery: | 'allTasksData' | 'tasksData' | 'localizationsParentData' | 'localizationsInProjectData'; }; const AreasTable = ({ data: apiResponse, taskId = undefined, localizationId = undefined, dataQuery }: AreasTableType) => { const [data, setTableData] = useState(() => []); const [sorting, setSorting] = useState<SortingState>([]); const router = useRouter(); const query = router.query; useEffect(() => { const dataFlat = taskId ? apiResponse.map((x) => x.area) : apiResponse; setTableData(dataFlat); }, [apiResponse]); const columns = useMemo<ColumnDef<Area>[]>( () => [ { header: 'ID', accessorKey: 'id', maxSize: 5, cell: ({ getValue, row }) => row.original?.id }, { header: 'Nazwa', accessorKey: 'name', maxSize: 25, cell: ({ getValue, row }) => row.original?.name }, { header: 'Szerokość', accessorKey: 'width', maxSize: 25, cell: ({ getValue, row }) => row.original?.width }, { header: 'Wysokość', accessorKey: 'height', maxSize: 25, cell: ({ getValue, row }) => row.original?.height }, { header: 'Utworzono', accessorKey: 'createdAt', maxSize: 25, cell: ({ getValue, row }) => parseDate(row.original?.createdAt) }, // { // header: 'Aktualizacja', // accessorKey: 'updatedAt', // maxSize: 45, // cell: ({ getValue, row }) => parseDate(row.original?.updatedAt) // }, { header: ' ', minSize: 10, cell: ({ row }) => { return ( <span className="flex justify-end "> <span className="flex w-20 justify-end "> <DeleteButton onClick={() => { deleteAreaData(row.original?.id); }} /> </span> </span> ); } } ], [] ); const queryClient = useQueryClient(); const mutationDelete = useMutation(deleteArea, { onSuccess: () => { // Invalidate and refetch queryClient.invalidateQueries([dataQuery]); } }); const deleteAreaData = (areaId) => { mutationDelete.mutate({ areaId }); }; const tableInstance = useReactTable({ data, columns, getCoreRowModel: getCoreRowModel(), state: { sorting }, onSortingChange: setSorting, getSortedRowModel: getSortedRowModel() }); return ( <div className="mt-8 flex flex-col"> <div className="-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8"> <div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8"> <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg"> <table className="min-w-full divide-y divide-gray-300"> <thead className="bg-gray-50"> {tableInstance.getHeaderGroups().map((headerGroup) => ( <tr key={headerGroup.id}> {headerGroup.headers.map((header) => { return ( <th {...{ style: { width: `${header.column.getSize()}%` } }} scope="col" key={header.id} className="text-left text-sm font-semibold text-gray-900 py-3.5 pl-4 pr-4 hover:bg-gray-100 hover:transition-all"> <div {...{ className: header.column.getCanSort() ? 'cursor-pointer select-none flex' : '', onClick: header.column.getToggleSortingHandler() }}> {flexRender(header.column.columnDef.header, header.getContext())} {{ asc: <SortButton direction="asc" />, desc: <SortButton direction="desc" /> }[header.column.getIsSorted() as string] ?? null} </div> </th> ); })} </tr> ))} </thead> <tbody className="divide-y divide-gray-200 bg-white"> {tableInstance.getRowModel().rows.map((row) => ( <tr key={row.original.id} className="hover:bg-slate-50 transition-colors"> {row.getVisibleCells().map((cell) => ( <td key={cell.id} className="whitespace-nowrap py-4 pl-4 pr-4 text-sm text-gray-500 "> {flexRender(cell.column.columnDef.cell, cell.getContext())} </td> ))} </tr> ))} </tbody> </table> </div> </div> </div> </div> ); }; export default AreasTable;
import React, {useState} from 'react'; import { Container, Navbar, NavbarBrand, Nav } from 'reactstrap'; import {useHistory} from 'react-router-dom'; import './NavMenu.css'; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {faUser} from "@fortawesome/free-solid-svg-icons"; import { faShoppingBag } from '@fortawesome/free-solid-svg-icons'; import {getCartItems, getProductsInCart} from "../api/cart"; const NavMenu = ({ username, userId }) => { const [showUsername, setShowUsername] = useState(false); const history = useHistory(); const handleHomeClick = () => { history.push('/'); } const handleCartClick = async () => { history.push('/viewCart'); }; const handleUserClick = () => { history.push('/login'); }; const handleIconHover = () => { setShowUsername(true); }; const handleIconLeave = () => { setShowUsername(false); }; return ( <header> <Navbar color="dark" dark expand="md" className="fixed-top"> <Container> <NavbarBrand className="nav-icon" onClick={handleHomeClick}>Shop</NavbarBrand> <Nav className="ml-auto" navbar> <div> <FontAwesomeIcon icon={faShoppingBag} className="nav-icon mx-5" onClick={handleCartClick} /> {showUsername && <div className="username">{username}</div>} <FontAwesomeIcon icon={faUser} className="nav-icon" onClick={handleUserClick} onMouseEnter={handleIconHover} onMouseLeave={handleIconLeave} /> </div> </Nav> </Container> </Navbar> </header> ); } export default NavMenu;
namespace Result { export type Ok<T> = { readonly ok: true; readonly value: T }; export type Err<E> = { readonly ok: false; readonly error: E }; export type Result<T, E> = Ok<T> | Err<E>; export function ok<T>(t: T): Ok<T> { return { value: t, ok: true }; } export function err<E>(e: E): Err<E> { return { error: e, ok: false }; } } export default Result;
package queryBuilder import ( "strconv" ) const ( ascending string = "ASC" descending string = "DESC" ) // Offset sets the 'OFFSET' clause // example: OFFSET 5 func (qb *QueryBuilder) Offset(offset uint32) { if offset == 0 { return } qb.query += "OFFSET" + " " + strconv.Itoa(int(offset)) + "\n" qb.clauses.isOffset = true } // Limit sets the 'LIMIT' clause // example: LIMIT 10 func (qb *QueryBuilder) Limit(limit uint32) { if limit == 0 { return } qb.query += "LIMIT" + " " + strconv.Itoa(int(limit)) + "\n" qb.clauses.isLimit = true } // OrderBy sets the 'ORDER BY' clause // example: ORDER BY created_at DESC func (qb *QueryBuilder) OrderBy(column string, isDescending bool) error { err := qb.clauses.validateOrderBy() if err != nil { return err } sortStatement := getSortStatement(isDescending) qb.query += "ORDER BY" + " " + column + " " + sortStatement + "\n" qb.clauses.isOrderBy = true return nil } func (qb *QueryBuilder) GroupBy(column string) { qb.query += "GROUP BY" + " " + column + "\n" qb.clauses.isGroupBy = true } func getSortStatement(isDescending bool) string { orderByParameter := ascending if isDescending { orderByParameter = descending } return orderByParameter }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../public/styles.css"> <title>Chat</title> <style> body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; height: 100vh; } h2 { text-align: center; } #userList, #chatSection { background-color: #fff; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); padding: 20px; margin: 20px; } #users { list-style: none; padding: 0; margin: 0; } #messages { list-style: none; padding: 0; margin: 0; max-height: 200px; overflow-y: auto; } #form { display: flex; margin-top: 10px; } #m { flex: 1; padding: 8px; box-sizing: border-box; } button { padding: 8px; background-color: #007bff; color: #fff; border: none; border-radius: 4px; cursor: pointer; margin-left: 10px; } a { text-decoration: none; color: #007bff; margin-top: 20px; } </style> </head> <body> <script> var username = '<%= username %>'; var userId = '<%= userId %>'; </script> <h2>Welcome, <span id="welcomeUsername"></span>!</h2> <div id="userList"> <h3>Users:</h3> <ul id="users"></ul> </div> <div id="chatSection"> <h3>Chat Section</h3> <ul id="messages"> <% messages.forEach(message => { %> <li><%= message.username %>: <%= message.content %></li> <% }); %> </ul> <form id="form" onsubmit="sendMessage(); return false;"> <input id="m" autocomplete="off" /> <button type="submit">Send</button> </form> </div> <a href="/" style="text-decoration: none; color: #007bff;">Logout</a> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script> $(function () { const socket = io(); $('#welcomeUsername').text(username); socket.emit('setUsername', '<%= username %>'); socket.emit('getUsers'); socket.on('userList', function (users) { const userList = $('#users'); userList.empty(); users.forEach(user => { userList.append($('<li>').text(user.username)); }); }); socket.on('chat message', function (msg) { const messages = $('#messages'); messages.append($('<li>').text(msg.username + ': ' + msg.message)); window.scrollTo(0, document.body.scrollHeight); }); window.sendMessage = function () { const input = $('#m'); const message = input.val(); if (message.trim() !== '') { socket.emit('chat message', message); input.val(''); } }; }); </script> </body> </html>
import React, { useState, useEffect, useContext } from 'react'; import { useNavigate } from "react-router"; import { styled } from '@mui/material/styles'; import Grid from '@mui/material/Grid'; import Paper from '@mui/material/Paper'; import Typography from '@mui/material/Typography'; import ButtonBase from '@mui/material/ButtonBase'; import Button from '@mui/material/Button'; import Navbar from "./navbar/Header"; import { auth, db } from "../context/firebase"; import { query, collection, getDocs, where } from "firebase/firestore"; import { useAuthState } from "react-firebase-hooks/auth"; import { MessageContext } from "../context/MessageContext"; const API_URL = "https://msg-api.vercel.app/messages"; const Img = styled('img')({ margin: 'auto', display: 'block', maxWidth: '100%', maxHeight: '100%', }); export default function Home() { const navigate = useNavigate(); const [user, loading, error] = useAuthState(auth); const [name, setName] = useState(""); // const navigate = useNavigate(); const fetchUserByName = async () => { try { const q = query(collection(db, "users"), where("uid", "==", user?.uid)); const doc = await getDocs(q); const data = doc.docs[0].data(); console.log(data); setName(data.displayName); } catch (err) { console.error(err); alert("An error occured while fetching user data"); } }; useEffect(() => { if (loading) return; fetchUserByName(); }, [user, loading]); console.log("USER IS", `${name}`); function getMessagesByOwner(MESSAGES, owner) { const temp = MESSAGES.filter((message) => (message.owner === owner)); if (temp.length === 0) { return [{ "id": 123456789, "subject": "No Message Found", "content": "You have no new Message. Check again later", "isRead": true, "owner": "Me" }];//MESSAGES.filter((message) => (message.owner === "Undefined")); } else { return temp; } } const Msgs = React.useContext(MessageContext); const Data = getMessagesByOwner(Msgs, name); console.log(Data); var total = Data.length; let counter = 0; for (let i = 0; i < Data.length; i++) { if (Data[i].isRead === false) { counter++; } }; return ( <> <Navbar /> <h1> PROFILE </h1> <Paper sx={{ p: 2, margin: 'auto', maxWidth: 600, flexGrow: 1, backgroundColor: (theme) => theme.palette.mode === 'dark' ? '#1A2027' : '#fff', }} > <Grid container spacing={2}> <Grid item> <ButtonBase sx={{ width: 128, height: 128 }}> <Img alt="complex" src="https://cquipsplus.ca/wp-content/themes/cera/assets/images/avatars/user-avatar.png" /> </ButtonBase> </Grid> <Grid item xs={12} sm container> <Grid item xs container direction="column" spacing={2}> <Grid item xs> <Typography gutterBottom variant="subtitle1" component="div"> Hello <h2>{name}</h2> </Typography> <Typography variant="body2" gutterBottom> <span> You have <h1>{counter}</h1> </span><span>Unread out of <h1>{total}</h1> total </span> </Typography> <Typography variant="body2" color="text.secondary"> </Typography> </Grid> <Grid item> <Typography sx={{ cursor: 'pointer' }} variant="body2"> <Button variant="outlined" onClick={ () => navigate(`/list/`, { state: { dat: Data } }) }> Message_List </Button> </Typography> </Grid> </Grid> <Grid item> <Typography variant="subtitle1" component="div"> ... </Typography> </Grid> </Grid> </Grid> </Paper> </> ); }
package baekjoon; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Number11659 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); StringBuilder sb = new StringBuilder(); int N = Integer.parseInt(st.nextToken()); // 수의 개수 int M = Integer.parseInt(st.nextToken()); // 합을 구해야하는 횟수 int[] arr = new int[N+1]; // 수를 담을 배열 // 배열 초기화 (누적합을 해주면서 초기화) st = new StringTokenizer(br.readLine()); for (int i=1; i<=N; i++) { arr[i] = arr[i-1] + Integer.parseInt(st.nextToken()); } // 누적합이 된 배열에서 i번째 부터 j번째까지의 값을 구한다. while (M-- > 0) { st = new StringTokenizer(br.readLine()); int i = Integer.parseInt(st.nextToken()); int j = Integer.parseInt(st.nextToken()); sb.append(arr[j] - arr[i-1]).append('\n'); } System.out.println(sb); } }
import React, { useState } from 'react'; import propTypes from 'prop-types'; import Swal from 'sweetalert2'; import { useSelector } from 'react-redux'; import connect from '../../axios/axios.config'; import base64ToRawFile from '../../utils/base64ToRawFile'; import createFormData from '../../utils/createFormData'; import './slider.css'; import { PATH_ENDPOINT_SLIDES, STATUS_CREATED, } from '../../constants/constants'; const imgFormats = ['image/jpeg', 'image/jpg', 'image/png']; const AddSlider = ({ setToggleMenu, getDataSlides }) => { const [image, setImage] = useState(null); const [description, setDescription] = useState(''); const [warnImg, setWarnImg] = useState(false); const [warnDesc, setWarnDesc] = useState(null); const [disabled, setDisabled] = useState(false); const handleFetch = async () => { setDisabled(true); const imageRawFile = base64ToRawFile(image, 'nD3jR19Ha'); const formData = createFormData({ organizationId: 1, description, image: imageRawFile, }); try { const response = await connect.post(PATH_ENDPOINT_SLIDES, formData); if (response.status === STATUS_CREATED) { await Swal.fire({ text: 'Slide Creado', icon: 'success', }); setImage(null); setDescription(''); getDataSlides(); setToggleMenu(0); } setDisabled(false); } catch (err) { Swal.fire({ text: 'Error!', icon: 'error', }); setImage(null); setDescription(''); getDataSlides(); setToggleMenu(0); setDisabled(false); } }; const inputsValidate = () => { let noErrors = true; if (!image) { setWarnImg(true); noErrors = false; } if (description === '') { setWarnDesc('Ingrese una descripcion'); noErrors = false; } if (noErrors) { handleFetch(); } }; const handleFile = async (file) => { // eslint-disable-next-line no-undef const reader = new FileReader(); reader.addEventListener('load', () => setImage(reader.result), false); reader.readAsDataURL(file.target.files[0]); }; const theme = useSelector((state) => state.theme.dataThemeDefault); return ( <div className="mainContainer"> {image ? <img className="addImgStyle" alt="Imagen" /> : null} <div className="formContainer"> <p className="addTitleStyle" style={{ color: theme.lettersColor }}> Descripción de la imagen </p> <textarea className={warnDesc ? 'areatextStyle1' : 'areatextStyle'} placeholder="Agregue una descripcion" value={description} onChange={(e) => { setDescription(e.target.value); setWarnDesc(null); }} /> {warnDesc ? <p className="warnTxtStyle">{warnDesc}</p> : null} <input className={warnImg ? 'inputFileStyle1' : 'inputFileStyle'} type="file" accept={imgFormats} multiple={false} onChange={(file) => { handleFile(file); setWarnImg(null); }} /> <div style={{ margin: '20px auto 10px auto', display: 'flex', justifyContent: 'center', }} className="inline clearfix " > <button style={{ margin: '0 10px', backgroundColor: 'red' }} type="submit" className="btn btn-primary" onClick={() => { setImage(null); setDescription(''); setToggleMenu(0); }} disabled={disabled} > Cancelar </button> <button type="submit" className="btn btn-primary mb-5" onClick={inputsValidate} disabled={disabled} > Enviar </button> </div> </div> </div> ); }; AddSlider.propTypes = { setToggleMenu: propTypes.func.isRequired, getDataSlides: propTypes.func.isRequired, }; export default AddSlider;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Assignment 5 - About Me </title> <meta name="author" content="Taylor Powell"> <meta name="description" content="This is my list assignment, naming my dogs!"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="dcont"> <div class="des"> <!-- Slideshow container --> <div class="slideshow-container"> <!-- Full-width images with number and caption text --> <div class="mySlides fade"> <div class="numbertext">1 / 3</div> <img src="img/lyra.jpg" style="width:100%"> <div class="text">Lyra</div> </div> <div class="mySlides fade"> <div class="numbertext">2 / 3</div> <img src="img/stella.jpg" style="width:100%"> <div class="text">Stella</div> </div> <div class="mySlides fade"> <div class="numbertext">3 / 3</div> <img src="img/odin.jpg" style="width:100%"> <div class="text">Odin</div> </div> </div> <br> <!--<img src="imgs/hs.PNG" height=500px>--> <h1>My Dogs</h1> <p>They were born and raised in <address>Kalispell, MT</address></p> <p>We have three of them, their names are: </p> <ol> <li><strong>Lyra: </strong> a purebred beagle</li> <li><strong>Stella: </strong> a purebred beagle</li> <li><strong>Odin: </strong> a black lab/retriever mix</li> </ol> </div> </div> </div> </body> </html> <script> let slideIndex = 0; showSlides(); function showSlides() { let i; let slides = document.getElementsByClassName("mySlides"); for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } slideIndex++; if (slideIndex > slides.length) {slideIndex = 1} slides[slideIndex-1].style.display = "block"; setTimeout(showSlides, 4000); // Change image every 2 seconds } </script>
package com.bank.authorization.controller; import com.bank.authorization.dto.AuditDto; import com.bank.authorization.service.AuditService; import io.micrometer.core.annotation.Timed; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping("/api/auth-audit") @RequiredArgsConstructor public class AuditController { private final AuditService auditService; @Timed("getAllAudit") @GetMapping @Operation(summary = "Получить список аудитов", description = "Получить список всех аудитов") @ApiResponse(responseCode = "200", description = "Успешная операция", content = @Content(mediaType = "application/json", schema = @Schema(implementation = AuditDto.class))) public ResponseEntity<List<AuditDto>> showAll() { final List<AuditDto> auditDtoList = auditService.getAll(); return ResponseEntity.status(HttpStatus.OK).body(auditDtoList); } @PostMapping @Operation(summary = "Создать новый аудит", description = "Создать новый аудит") @ApiResponse(responseCode = "201", description = "Успешная операция") @ApiResponse(responseCode = "400", description = "Неверный запрос", content = @Content) @ApiResponse(responseCode = "403", description = "Нет прав", content = @Content) public ResponseEntity<AuditDto> create(@Valid @RequestBody AuditDto auditDto) { auditService.add(auditDto); return ResponseEntity.status(HttpStatus.CREATED).body(auditDto); } @GetMapping("/{id}") @Operation(summary = "Получить аудит по ID", description = "Получить аудит по ID") @ApiResponse(responseCode = "200", description = "Успешная операция") @ApiResponse(responseCode = "404", description = "Аудит не найден", content = @Content) public ResponseEntity<AuditDto> getById(@PathVariable Long id) { final AuditDto auditDto = auditService.getById(id); return ResponseEntity.status(HttpStatus.OK).body(auditDto); } @PutMapping @Operation(summary = "Редактировать аудит", description = "Редактировать аудит") @ApiResponse(responseCode = "200", description = "Успешная операция") @ApiResponse(responseCode = "404", description = "Аудит не найден", content = @Content) @ApiResponse(responseCode = "400", description = "Неверный запрос", content = @Content) @ApiResponse(responseCode = "403", description = "Нет прав", content = @Content) public ResponseEntity<AuditDto> update(@Valid @RequestBody AuditDto auditDto) { auditService.update(auditDto); return ResponseEntity.status(HttpStatus.OK).body(auditDto); } @DeleteMapping("/{id}") @Operation(summary = "Удалить аудит по ID", description = "Удалить аудит по ID") @ApiResponse(responseCode = "204", description = "Аудит удален") @ApiResponse(responseCode = "404", description = "Аудит не найден", content = @Content) @ApiResponse(responseCode = "403", description = "Нет прав", content = @Content) public ResponseEntity<AuditDto> delete(@PathVariable Long id) { auditService.deleteById(id); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } }
import React, { useState } from 'react' import { Button, Card, Grid } from '@mui/material' interface IUserApi { profileUrl: string; userName: string; userCountry: string; userEmail: string; userPhone: string; handleChangeUser: () => void; } export function UserApi(props: IUserApi) { const { profileUrl, userName, userCountry, userEmail, userPhone, handleChangeUser } = props; const [showEmail, setShowEmail] = useState<boolean>(true); return ( <Card className="rounded my-4 justify-center max-w-lg"> <Grid container p={4}> <Grid item lg={4} xl={4} xs={6}> <img src={profileUrl} alt="user-profile" className="h-28 w-28 rounded-full border-2 border-pink-600 " /> </Grid> <Grid item lg={8} xl={8} xs={6} > <span className="font-bold block text-gray-900 mt-2">Nome: {userName}</span> <span className="text-gray-900 text-opacity-60">País: {userCountry}</span> { showEmail ? ( <span className="text-gray-900 text-opacity-60 block">Email: {userEmail}</span> ) : ( <span className="text-gray-900 text-opacity-60 block">Telefone: {userPhone}</span> ) } </Grid> <Grid item lg={6} xl={6} xs={6} mt={2}> <Button variant="outlined" onClick={() => setShowEmail(!showEmail)} > Mudar informação </Button> </Grid> <Grid item lg={6} xl={6} xs={6} mt={2}> <Button variant="contained" onClick={() => handleChangeUser()} > Trocar Usuário </Button> </Grid> </Grid> </Card> ) }
package com.project.Fabo.service.impl; import java.util.Optional; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.project.Fabo.entity.AddProductAdmin; import com.project.Fabo.entity.ClientProduct; import com.project.Fabo.repository.AddProductAdminRepository; import com.project.Fabo.repository.ClientProductRepository; import com.project.Fabo.service.AddProductAdminService; @Service public class AddProductAdminServiceImpl implements AddProductAdminService{ private AddProductAdminRepository addProductAdminRepository; private ClientProductRepository clientProductRepository; public AddProductAdminServiceImpl(AddProductAdminRepository addProductAdminRepository, ClientProductRepository clientProductRepository) { this.addProductAdminRepository = addProductAdminRepository; this.clientProductRepository = clientProductRepository; } @Value("${max.file.size}") private long maxFileSize; @Override public AddProductAdmin saveAddProductAdmin(AddProductAdmin addProductAdmin) { // Save the invoice to generate the auto-incremented numeric part AddProductAdmin savedaddProductAdmin = addProductAdminRepository.save(addProductAdmin); // Update the formatted invoice number based on the saved invoice ID savedaddProductAdmin.setFormattedProductNumber(savedaddProductAdmin.getId()); return addProductAdminRepository.save(addProductAdmin); } @Override public AddProductAdmin getAddProductAdminById(Long id) { return addProductAdminRepository.findById(id).get(); } public void saveCommentAndStatusById(Long id, String commentText, String clientVisible, String requestStatus) { // Fetch the existing record by ID from the database Optional<AddProductAdmin> productAdminOptional = addProductAdminRepository.findById(id); // Check if the record exists if (productAdminOptional.isPresent()) { AddProductAdmin productAdmin = productAdminOptional.get(); // Update fields based on clientVisible and save to the database if (clientVisible.equals("Yes")) { productAdmin.setInternalComments(commentText); } else { productAdmin.setCommentsToClient(commentText); productAdmin.setInternalComments(commentText); } productAdmin.setStatus(requestStatus); // Save the updated productAdmin record back to the database addProductAdminRepository.save(productAdmin); // Now update the status in the clientProduct entity Optional<ClientProduct> clientProductOptional = clientProductRepository.findById(id); if (clientProductOptional.isPresent()) { ClientProduct clientProduct = clientProductOptional.get(); clientProduct.setStatus(requestStatus); clientProduct.setExternalComments(commentText); clientProductRepository.save(clientProduct); // Save the updated clientProduct entity } else { // Handle case when the clientSupport ID doesn't exist // You might throw an exception or handle it according to your application logic throw new IllegalArgumentException("Client Product ID not found: " + id); } } else { // Handle case when the supportAdmin ID doesn't exist // You might throw an exception or handle it according to your application logic throw new IllegalArgumentException("Product Admin ID not found: " + id); } } public void deleteAddProductAdminById(Long id) { Optional<AddProductAdmin> productAdminOptional = addProductAdminRepository.findById(id); if (productAdminOptional.isPresent()) { AddProductAdmin productAdmin = productAdminOptional.get(); productAdmin.setActiveStatus(false); // Marking as inactive addProductAdminRepository.save(productAdmin); } else { throw new IllegalArgumentException("Product Admin ID not found: " + id); } } }
// import logo from './logo.svg'; import { BrowserRouter,Route,Routes } from 'react-router-dom'; import './App.css'; import Home from './Component/Home/Home'; import Nav from './Component/Nav/Nav'; import Login from './Component/LoginSignup/Login'; import Register from './Component/LoginSignup/Register'; import CoursesPage from './Component/CoursesPage/CoursesPage'; import { useEffect } from 'react'; import { setData } from './Component/store/coursesSlice'; import { useDispatch} from 'react-redux'; import Cart from './Component/Cart/Cart'; import jwt_decode from 'jwt-decode'; import { setUserinfo } from './Component/store/userSlice'; function App() { const dispatch = useDispatch(); useEffect(() => { const fetchDataFromAPI = async () => { try { const response = await fetch('https://udemy-server-i52o.onrender.com/courses'); const result = await response.json(); dispatch(setData(result)); } catch (error) { console.error('Error fetching data:', error); } }; fetchDataFromAPI(); }, [dispatch]); const token = localStorage.getItem('token'); console.log("token",token) useEffect(() => { if (token) { try { const decoded = jwt_decode(token); console.log("token decode",decoded) dispatch(setUserinfo(decoded)) } catch (error) { console.error('Error decoding token:', error); } } }, [token,dispatch]); return ( <div className="App"> <BrowserRouter> <Nav/> <Routes> <Route path="/" element={<Home />}></Route> <Route path='/register' element={<Register />}></Route> <Route path="/login" element={<Login />}></Route> <Route path="/course/:name" element={<CoursesPage/>}></Route> <Route path='/cart' element={<Cart />}></Route> {/* <Route path='/search' element={<SearchPage />}></Route> <Route path='/mylearn' element={<Mylearning />}></Route> */} </Routes> </BrowserRouter> </div> ); } export default App;
using System.Security.Cryptography; using System.Text; using System.Text.Json; using API.Entities; using Microsoft.EntityFrameworkCore; namespace API.Data { public static class Seed { public static void SeedUsers(this DataContext dataContext) { if (dataContext.Users.Any()) return; //return from this if we do have any users. var userData = System.IO.File.ReadAllText("Data/UserSeedData.json"); var users = JsonSerializer.Deserialize<List<AppUser>>(userData); foreach (var user in users) { using var hmac = new HMACSHA512(); user.UserName = user.UserName.ToLower(); user.PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes("Password")); user.PasswordSalt = hmac.Key; dataContext.Users.Add(user); } dataContext.SaveChangesAsync(); } } }
import React, { useContext, useEffect, useRef, useState } from 'react' import audioDb from './Data' // create context hook const appContext = React.createContext(); const AppProvider = ({ children }) => { const myRef = useRef(); let [songNum, setSongNum] = useState(0) const [songDetails, setSongDetails] = useState( { title: "", artis: "", img: "", audio: "", ref: myRef, } ) const [duration, setDuration] = useState({ curTime: 0, duration: 4.00, percentage: 1, }) const [isPlay, setIsPlay] = useState(false); const updateSong = (index) => { const { title, artist, img, audio } = audioDb[index]; setSongDetails({ title: title, artis: artist, img: img, audio: audio, ref: myRef, }) } const pauseMusic = () => { setIsPlay(false); myRef.current.pause(); } const secToMin = (sec) => { let min = Math.floor(sec / 60); let secRem = Math.floor(sec % 60); min = min < 10 ? `0${min}` : `${min}`; secRem = secRem < 10 ? `0${secRem}` : `${secRem}` return `${min}:${secRem}`; } const timeUpdate = (e) => { setDuration({ curTime: secToMin(e.target.currentTime), duration: secToMin(e.target.duration), percentage: Math.floor((e.target.currentTime / e.target.duration) * 100), }) if (e.target.currentTime === e.target.duration) { nextCLickHandler(); } } const playMusic = () => { setIsPlay(true); myRef.current.play(); } const nextCLickHandler = () => { let songcount = (songNum + 1) % audioDb.length; setSongNum(songcount); setIsPlay(false) } const prevClickHandler = () => { let songcount = (songNum - 1 + audioDb.length) % audioDb.length; setSongNum(songcount); setIsPlay(false) } const playclickHanlder = () => { isPlay ? pauseMusic() : playMusic() } useEffect(() => { updateSong(songNum); }, [songNum]) return <appContext.Provider value={{ duration, songDetails, nextCLickHandler, prevClickHandler, timeUpdate, playclickHanlder, isPlay }}> {children} </appContext.Provider> } const useGlobalHook = () => { return useContext(appContext); } export { useGlobalHook, AppProvider }
package com.fptu.exe.controllers; import com.fptu.exe.entities.AccountEntity; import com.fptu.exe.payload.request.LoginRequest; import com.fptu.exe.payload.response.BaseResponse; import com.fptu.exe.security.jwt.JwtHelper; import com.fptu.exe.services.LoginService; import com.google.gson.Gson; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @CrossOrigin @RestController @RequestMapping("/login") public class LoginController { @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtHelper jwtHelper; @Autowired private LoginService loginService; private Gson gson = new Gson(); private Logger logger = LoggerFactory.getLogger(LoginController.class); @Operation(summary = "Login") @ApiResponses(value = { @ApiResponse(responseCode = "400", description = "Can't found account! Bad Request!"), @ApiResponse(responseCode = "200", description = "Login Successfully!"), @ApiResponse(responseCode = "500", description = "Internal error") }) @PostMapping("") public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) { String email = loginRequest.getEmail(); String password = loginRequest.getPassword(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(email, password); // System.out.println(token); Authentication authentication = authenticationManager.authenticate(token); logger.info("authentication: " + authentication); String json = gson.toJson(authentication.getAuthorities()); AccountEntity account = loginService.checkLogin(email, password); if (!account.isStatus()) { // String jwtToken = jwtService.generateToken(account.getRole(), account); BaseResponse baseResponse = new BaseResponse(); baseResponse.setMessage("Tài khoản chưa đăng ký hoặc chưa được kích hoạt"); return new ResponseEntity<>(baseResponse, HttpStatus.BAD_REQUEST); } else { String jwtToken = jwtHelper.generateToken(account.getRole(), account); BaseResponse baseResponse = new BaseResponse(); baseResponse.setData(jwtToken); return new ResponseEntity<>(baseResponse, HttpStatus.OK); } } }
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.cts.verifier.managedprovisioning; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.view.View; import android.view.View.OnClickListener; import com.android.cts.verifier.ArrayTestListAdapter; import com.android.cts.verifier.DialogTestListActivity; import com.android.cts.verifier.R; import java.util.Set; public class CrossProfilePermissionControlActivity extends DialogTestListActivity { static final String ACTION_CROSS_PROFILE_PERMISSION_CONTROL = "com.android.cts.verifier.managedprovisioning.action.CROSS_PROFILE_PERMISSION_CONTROL"; private static final String TEST_APP_PACKAGE_NAME = "com.android.cts.crossprofilepermissioncontrol"; private static final String OPEN_TEST_APP_ACTION = "com.android.cts.verifier.managedprovisioning.action.OPEN_CROSS_PROFILE_TEST_APP"; protected DevicePolicyManager mDpm; public CrossProfilePermissionControlActivity() { super(R.layout.provisioning_byod, R.string.provisioning_byod_cross_profile_permission_control, R.string.provisioning_byod_cross_profile_permission_control_info, R.string.provisioning_byod_cross_profile_permission_control_instruction); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDpm = getSystemService(DevicePolicyManager.class); mPrepareTestButton.setText( R.string.provisioning_byod_cross_profile_permission_control_prepare_button); mPrepareTestButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { allowTestApp(); } }); } protected void allowTestApp() { mDpm.setCrossProfilePackages(getAdminComponent(), Set.of(TEST_APP_PACKAGE_NAME)); } protected ComponentName getAdminComponent() { return DeviceAdminTestReceiver.getReceiverComponentName(); } protected void setupInteractAcrossProfilesDisabledByDefault(ArrayTestListAdapter adapter) { adapter.add(new DialogTestListItem( this, R.string.provisioning_byod_cross_profile_permission_disabled_by_default, getTestIdPrefix() + "interactAcrossProfilesDisabledByDefault", R.string.provisioning_byod_cross_profile_permission_disabled_by_default_instruction, new Intent(Settings.ACTION_MANAGE_CROSS_PROFILE_ACCESS))); } protected void setupInteractAcrossProfilesEnabled(ArrayTestListAdapter adapter) { adapter.add(new DialogTestListItem( this, R.string.provisioning_byod_cross_profile_permission_enabled, getTestIdPrefix() + "interactAcrossProfilesEnabled", R.string.provisioning_byod_cross_profile_permission_enabled_instruction, new Intent(OPEN_TEST_APP_ACTION))); } protected void setupInteractAcrossProfilesDisabled(ArrayTestListAdapter adapter) { adapter.add(new DialogTestListItem(this, R.string.provisioning_byod_cross_profile_permission_disabled, getTestIdPrefix() + "DisableUnredactedNotifications", R.string.provisioning_byod_cross_profile_permission_disabled_instruction, new Intent(OPEN_TEST_APP_ACTION))); } protected String getTestIdPrefix() { return "BYOD_"; } @Override protected void setupTests(ArrayTestListAdapter adapter) { setupInteractAcrossProfilesDisabledByDefault(adapter); setupInteractAcrossProfilesEnabled(adapter); setupInteractAcrossProfilesDisabled(adapter); } }
package br.com.bln.estudospringbatch.application.commandline; import br.com.bln.estudospringbatch.adapter.gateway.repository.origem.PessoaRepository; import br.com.bln.estudospringbatch.application.utils.FileHelper; import br.com.bln.estudospringbatch.domain.entity.origem.PessoaEntity; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Log4j2 @Component @Order(2) public class MigrarCargaOrigemCommandLineRunner implements CommandLineRunner { @PersistenceContext(unitName = "persistenceUnitOrigem") private EntityManager entityManagerOrigem; @Autowired private PessoaRepository pessoaRepository; @Override @Transactional(value = "origemTransactionManager") public void run(String... args) throws Exception { Boolean existeCargaOrigem = (Boolean) entityManagerOrigem.createNativeQuery("SELECT count(*) > 0 FROM tb_pessoa").getSingleResult(); inserirRegistroArquivoMigracao(existeCargaOrigem); inserirRegistrosAleatorios(existeCargaOrigem, 999945); } private void inserirRegistroArquivoMigracao(Boolean existeCargaOrigem) { if (!existeCargaOrigem) { log.info("## Iniciando SQL para inserir registros DB_ORIGEM..."); try { String scriptTabelas = FileHelper.getFileInResources("db/banco-origem-carga-inicial.sql"); entityManagerOrigem.createNativeQuery(scriptTabelas).executeUpdate(); } catch (Exception e) { log.error("## Erro ao migrar scrips para o banco de origem."); e.printStackTrace(); throw e; } } } private void inserirRegistrosAleatorios(Boolean existeCargaOrigem, int quantidadeRegistrosParaInserir) { if (!existeCargaOrigem) { log.info(String.format("## Iniciando inserção de '%s' no banco!", quantidadeRegistrosParaInserir)); List<PessoaEntity> pessoaEntityList = new ArrayList<>(); for (int i = 0; i < quantidadeRegistrosParaInserir; i++) { pessoaEntityList.add( PessoaEntity.builder() .nome(UUID.randomUUID().toString()) .login(UUID.randomUUID().toString()) .senha(UUID.randomUUID().toString()) .apelido(UUID.randomUUID().toString()) .build() ); } pessoaRepository.saveAll(pessoaEntityList); log.info("## Inserção concluida!"); } } }
import { AuthorizationStatus } from '../../const'; import { AuthInfo } from '../../types/auth-info.props'; import { UserProcess } from '../../types/state.props'; import { checkAuthAction, loginAction, logoutAction } from '../api-actions'; import { userProcess } from './user-process'; describe('UserProcess Slice', () => { const initialState: UserProcess = { authorizationStatus: AuthorizationStatus.Unknown, authInfo: {} as AuthInfo }; const fakeAuthInfo = { name: 'Oliver.conner', avatarUrl: 'https://url-to-image/image.jpg', email: '[email protected]', token: 'T2xpdmVyLmNvbm5lckBnbWFpbC5jb20=' }; describe('checkAuthAction', () => { it('should set "authorizationStatus" to "NO_AUTH" with "checkAuthAction.rejected', () => { const expectedState = { ...initialState, authorizationStatus: 'NO_AUTH' }; const result = userProcess.reducer(initialState, checkAuthAction.rejected); expect(result).toEqual(expectedState); }); it('should set "authorizationStatus" to "AUTH" and payload on "authInfo" with "checkAuthAction.fulfilled', () => { const expectedState = { ...initialState, authorizationStatus: 'AUTH', authInfo: fakeAuthInfo }; const result = userProcess.reducer(initialState, checkAuthAction.fulfilled(fakeAuthInfo, '', undefined)); expect(result).toEqual(expectedState); }); }); describe('loginAction', () => { it('should set "authorizationStatus" to "NO_AUTH" with "loginAction.rejected', () => { const expectedState = { ...initialState, authorizationStatus: 'NO_AUTH' }; const result = userProcess.reducer(initialState, loginAction.rejected); expect(result).toEqual(expectedState); }); it('should set "authorizationStatus" to "AUTH" and payload on "authInfo" with "loginAction.fulfilled', () => { const expectedState = { ...initialState, authorizationStatus: 'AUTH', authInfo: fakeAuthInfo }; const result = userProcess.reducer(initialState, loginAction.fulfilled(fakeAuthInfo, '', {login: '', password: ''})); expect(result).toEqual(expectedState); }); }); describe('logoutAction', () => { it('should set "authorizationStatus" to "NO_AUTH" with "logoutAction.fulfilled', () => { const expectedState = { ...initialState, authorizationStatus: 'NO_AUTH' }; const result = userProcess.reducer(initialState, logoutAction.fulfilled(undefined, '', undefined)); expect(result).toEqual(expectedState); }); }); });
package com.bfs.quizlet.controller; import com.bfs.quizlet.domain.User; import com.bfs.quizlet.service.LoginService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.Optional; @Controller public class LoginController { private final LoginService loginService; public LoginController(LoginService loginService) { this.loginService = loginService; } // = @RequestMapping(method = RequestMethod.GET). // 所有对login的GET request都会match到这里 eg. 打开/login页面的时候 @GetMapping("/login") public String getLogin(HttpServletRequest request, Model model) { HttpSession session = request.getSession(false); // redirect to /home if user is already logged in if (session != null && session.getAttribute("user") != null) { return "redirect:/home"; } return "login"; } // = @RequestMapping(method = RequestMethod.POST). // 所有对login的POST request都会match到这里 eg. 用户输入账户密码后点submit // validate that we are always getting a new session after login @PostMapping("/login") public String postLogin(@RequestParam String email, @RequestParam String password, HttpServletRequest request) { Optional<User> possibleUser = loginService.validateLogin(email, password); if(possibleUser.isPresent()) { HttpSession oldSession = request.getSession(false); // invalidate old session if it exists if (oldSession != null) oldSession.invalidate(); // generate new session HttpSession newSession = request.getSession(true); // store user details in session newSession.setAttribute("user", possibleUser.get()); return "redirect:/home"; } else { // if user details are invalid return "login"; } } @GetMapping("/register") public String getRegisterPage(HttpServletRequest request, Model model) { HttpSession session = request.getSession(false); // // redirect to /home if user is already logged in // if (session != null && session.getAttribute("user") != null) { // return "redirect:/home"; // } // if user is already logged in, invalidate session if (session != null && session.getAttribute("user") != null) { session.invalidate(); } return "register"; } @PostMapping("/register") public String postRegister(@RequestParam String firstname, @RequestParam String lastname, @RequestParam String email, @RequestParam String password, @RequestParam String phone, HttpServletRequest request) { System.out.println("Here: In postRegister"); Optional<User> possibleUser = loginService.userExist(email); if(possibleUser.isPresent()) { // User Already Exist System.out.println("User Already Exist"); return "redirect:/register-fail"; } else { // User Not Exist, create new user loginService.createNewUser(firstname, lastname, email, password, phone, true, false); System.out.println("Register Successful"); return "redirect:/register-success"; } } @GetMapping("/register-fail") public String getUserExist(HttpServletRequest request, Model model) { return "register-fail"; } @GetMapping("/register-success") public String getRegisterSuccess(HttpServletRequest request, Model model) { return "register-success"; } @GetMapping("/logout") public String logout(HttpServletRequest request, Model model) { HttpSession oldSession = request.getSession(false); // invalidate old session if it exists if(oldSession != null) oldSession.invalidate(); return "login"; } }
import 'package:flutter/material.dart'; class MyContainer extends StatelessWidget { final Color color; final Widget child; final Function()? onPress; MyContainer( {this.color = Colors.white, this.child = const Center(), this.onPress}); @override Widget build(BuildContext context) { return GestureDetector( onTap: onPress, child: Container( margin: EdgeInsets.all(10), decoration: BoxDecoration( color: color, borderRadius: BorderRadius.circular(10), ), child: child, ), ); } }
/* Basic_touchscreen_draw example for e-radionica Inkplate 6PLUS For this example you will need only USB cable and Inkplate 6PLUS Select "Inkplate 6PLUS(ESP32)" from Tools -> Board menu. Don't have "Inkplate 6PLUS(ESP32)" option? Follow our tutorial and add it: https://e-radionica.com/en/blog/add-inkplate-6-to-arduino-ide/ This example shows you how to use Inkplate 6PLUS touchscreen. Once the code is uploaded, try drawing on the screen :) Want to learn more about Inkplate? Visit www.inkplate.io Looking to get support? Write on our forums: http://forum.e-radionica.com/en/ 11 February 2021 by e-radionica.com */ // Next 3 lines are a precaution, you can ignore those, and the example would also work without them #ifndef ARDUINO_INKPLATE6PLUS #error "Wrong board selection for this example, please select Inkplate 6PLUS in the boards menu." #endif #include "Inkplate.h" // Select to draw a line on screen or filled circle #define DRAW_LINE // #define DRAW_CIRCLE Inkplate display(INKPLATE_1BIT); #ifdef DRAW_LINE uint16_t xOld, yOld; #endif void setup() { // put your setup code here, to run once: Serial.begin(115200); display.begin(); display.display(); // Init touchscreen and power it on after init (send false as argument to put it in deep sleep right after init) if (display.tsInit(true)) { Serial.println("Touchscreen init ok"); } else { Serial.println("Touchscreen init fail"); while (true) ; } } void loop() { // Check if there is any touch detected if (display.tsAvailable()) { uint8_t n; uint16_t x[2], y[2]; // See how many fingers are detected (max 2) and copy x and y position of each finger on touchscreen n = display.tsGetData(x, y); if (n != 0) { #ifdef DRAW_LINE // Draw line from old point to new display.drawLine(xOld, yOld, x[0], y[0], BLACK); // Save coordinates to use as old next time xOld = x[0]; yOld = y[0]; #endif #ifdef DRAW_CIRCLE // Draw circle on touch event coordinates display.fillCircle(x[0], y[0], 20, BLACK); #endif display.partialUpdate(); } } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ibm.research.drl.dpt.datasets.schema.impl; import com.ibm.research.drl.dpt.datasets.schema.IPVSchemaFieldType; import com.ibm.research.drl.dpt.datasets.schema.IPVSchema; import com.ibm.research.drl.dpt.datasets.schema.IPVSchemaField; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * The type Simple schema. * */ public class SimpleSchema implements IPVSchema, Serializable { private final String id; private final List<SimpleSchemaField> fields; /** * Instantiates a new Simple schema. * * @param id the id */ public SimpleSchema(String id) { this(id, new ArrayList<SimpleSchemaField>()); } /** * Instantiates a new Simple schema. * * @param id the id * @param fields the fields */ public SimpleSchema(String id, List<SimpleSchemaField> fields) { this.id = id; this.fields = fields; } /** * Add schema field simple schema. * * @param field the field * @return the simple schema */ public SimpleSchema addSchemaField(SimpleSchemaField field) { if (!fieldExists(field)) fields.add(field); return this; } /** * Add schema field simple schema. * * @param name the name * @param type the type * @return the simple schema */ public SimpleSchema addSchemaField(String name, IPVSchemaFieldType type) { return addSchemaField(new SimpleSchemaField(name, type)); } private boolean fieldExists(SimpleSchemaField other) { for (IPVSchemaField field : fields) { if (field.getName().equals(other.getName())) return true; } return false; } @Override public String getSchemaIdentifier() { return id; } @Override public List<? extends IPVSchemaField> getFields() { return fields; } @Override public String toString() { return "SimpleSchema{ " + id + ", [" + fields + "]}"; } }