text
stringlengths
184
4.48M
! compute func(X)=A*X^2+B*X+C real function func(x,a,b,c) implicit none real x real, optional :: a,b,c real ra, rb, rc real w,y,z,sum,sum1 w = ra y = 1.5 z = 3.0 if ( present(a) ) then ra=a else ra=0.0 end if if ( present(b) ) then rb=b else rb=0.0 end if if ( present(c) ) then rc=c else rc=0.0 end if ! func(x)=A*X^2+B*X+C sum = ra*x**2 + rb*x + rc ! func = sum / (rb * y - z) sum1 = y * ra + 2 * y - z func = sum / sum1 ! func = sum / (y + z - 3 * y) ! error func = sum / (2 * y - z) ! error return end ! Compute func(X)=A*X^2+B*X+C in a subroutine subroutine funcs(x, a, b, c) implicit none real :: x real, optional :: a, b, c real :: ra, rb, rc, w, y, z, sum, sum1 w = ra y = 2.0 z = 4.0 ! Check if 'a' is provided, if not set to 0 if (present(a)) then ra = a else ra = 0.0 end if ! Check if 'b' is provided, if not set to 0 if (present(b)) then rb = b else rb = 0.0 end if ! Check if 'c' is provided, if not set to 0 if (present(c)) then rc = c else rc = 0.0 end if ! Calculate the function sum = ra * x**2 + rb * x + rc ! Introduce division by zero error x = sum / (2 * y - z) ! error return end subroutine funcs program main implicit none interface real function func(x, a, b, c) implicit none real, intent(in) :: x real, optional :: a, b, c end function func end interface interface subroutine funcs(x, a, b, c) implicit none real, intent(inout) :: x real, optional :: a, b, c end subroutine funcs end interface real :: sum1,x ! Call function func with potential division by zero error sum1 = func(2.0, 0.0, 2.0, 0.0) x = 2.0 ! Call subroutine funcs with potential division by zero error call funcs(x, 0.0, 2.0, 0.0) stop end program main
import { Button } from "@chakra-ui/button"; import { Box, Text } from "@chakra-ui/layout"; import { Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, } from "@chakra-ui/modal"; import React from "react"; import { useState } from "react"; import { useEffect } from "react"; import { API_URL, BASE_URL } from "../../global/Constant"; import apiFunctions from "../../global/GlobalFunction"; const RevenueModal = (props) => { let userId = localStorage.getItem("user_id"); const [amount, setAmount] = useState(); const [loading, setLoading] = useState(false); let currencySymbol = localStorage.getItem("currencySymbol"); async function totalRevenue() { try { let filterOrdersByDate = await apiFunctions.GET_REQUEST( BASE_URL + API_URL.TOTAL_REVENUE + userId ); let res = filterOrdersByDate.data.totalAmount; setAmount(res); setLoading(true); return true; } catch (err) { console.log("An error occurred while fetching carts", err.message); } } useEffect(() => { totalRevenue(); }, []); return ( <> <Modal isOpen={props.isOpen} onClose={props.onClose}> <ModalOverlay /> <ModalContent className="center-modal"> {loading ? ( <Box> <ModalHeader>Total Revenue</ModalHeader> <ModalCloseButton /> <ModalBody pb={6}> <Text> Total Revenue {currencySymbol} {amount} </Text> </ModalBody> </Box> ) : ( <div className="loading-screen-modal"> <div className="loading-spinner-modal"> </div> </div> )} </ModalContent> </Modal> </> ); }; export default RevenueModal;
import urlJoin from 'url-join'; import { ClinicianInviteRequest, ClinicianInviteResponse } from 'types/entities'; import { Result, failure, success } from 'types/httpResponses'; import serviceLogger from '../logger.js'; import { getAppConfig } from '../config.js'; import axiosClient from './axiosClient.js'; import { createInvitePiData, deleteInvitePiData } from './das/pi.js'; import { createInviteConsentData } from './das/consent.js'; const logger = serviceLogger.forModule('CreateService'); // PI-DAS const createParticipantPiData = async ({ name, email, }: { name: string; email: string; }): Promise<any> => { // TODO: add Type instead of any const { piDasUrl } = getAppConfig(); // TODO: add error handling const result = await axiosClient.post(urlJoin(piDasUrl, 'participants'), { name, email, }); return result.data.participant; }; // KEYS-DAS // TODO: add Type instead of any const createParticipantOhipKey = async (participantId: string): Promise<any> => { const { keysDasUrl } = getAppConfig(); // TODO: add error handling const result = await axiosClient.post(urlJoin(keysDasUrl, 'ohip-keys'), { participantId, }); return result.data.ohipKey; }; // PHI-DAS const saveParticipantOhipNumber = async ({ ohipPrivateKey, ohipNumber, }: { ohipPrivateKey: string; ohipNumber: string; }): Promise<any> => { // TODO: add Type instead of any const { phiDasUrl } = getAppConfig(); // TODO: add error handling const result = await axiosClient.post(urlJoin(phiDasUrl, 'ohip'), { ohipPrivateKey, ohipNumber, }); return result.data.ohipData.ohipNumber; }; // CONSENT-DAS const createParticipantConsentData = async ({ participantId, emailVerified, }: { participantId: string; emailVerified: boolean; }): Promise<any> => { // TODO: add Type instead of any const { consentDasUrl } = getAppConfig(); // TODO: add error handling const result = await axiosClient.post(urlJoin(consentDasUrl, 'participants'), { participantId, emailVerified, }); return result.data.participant; }; // separates data along concerns to store in respective DASes export const createParticipant = async ({ name, email, ohipNumber, emailVerified, }: { name: string; email: string; ohipNumber: string; emailVerified: boolean; }): Promise<any> => { // TODO: add Type instead of any const participantPiData = await createParticipantPiData({ name, email }); const participantId = participantPiData.id; const participantOhipKey = await createParticipantOhipKey(participantId); const ohipPrivateKey = participantOhipKey.ohipPrivateKey; const participantOhipNumber = await saveParticipantOhipNumber({ ohipPrivateKey, ohipNumber, }); const participantConsentData = await createParticipantConsentData({ participantId, emailVerified, }); return { ...participantPiData, ohipNumber: participantOhipNumber, emailVerified: participantConsentData.emailVerified, }; }; export type CreateInviteFailureStatus = 'SYSTEM_ERROR' | 'INVITE_EXISTS'; /** * Creates clinician invite in the PI DAS first to get an inviteId, * then uses the same inviteId to create a corresponding entry in the Consent DAS. * Makes a request to delete the created invite in PI DAS if an error occurs during * creation of entry in Consent DAS. * @async * @param data Clinician Invite request * @returns {ClinicianInviteResponse} Created Clinician Invite data */ export const createInvite = async ({ participantFirstName, participantLastName, participantEmailAddress, participantPhoneNumber, participantPreferredName, guardianName, guardianPhoneNumber, guardianEmailAddress, guardianRelationship, clinicianFirstName, clinicianLastName, clinicianInstitutionalEmailAddress, clinicianTitleOrRole, consentGroup, consentToBeContacted, }: ClinicianInviteRequest): Promise<Result<ClinicianInviteResponse, CreateInviteFailureStatus>> => { /** * Steps: * 1) Creates invite in PI DAS * 2) If error creating PI invite, returns the resulting `failure()` with an error status and message * 3) If success, creates invite in Consent DAS with the same ID * 4) If error creating Consent invite, deletes the previously created PI invite, * and returns the resulting `failure()` with an error status and message * 5) If success, parses the combination of PI and Consent invites to validate response object * 6) If error parsing, returns `failure()` with a SYSTEM_ERROR and Zod error message * 7) If success, returns created invite */ try { const piInviteResult = await createInvitePiData({ participantFirstName, participantLastName, participantEmailAddress, participantPhoneNumber, participantPreferredName, guardianName, guardianPhoneNumber, guardianEmailAddress, guardianRelationship, }); if (piInviteResult.status !== 'SUCCESS') { return piInviteResult; } const consentInviteResult = await createInviteConsentData({ id: piInviteResult.data.id, clinicianFirstName, clinicianLastName, clinicianInstitutionalEmailAddress, clinicianTitleOrRole, consentGroup, consentToBeContacted, }); if (consentInviteResult.status !== 'SUCCESS') { // Unable to create invite in Consent DB, rollback invite already created in PI const deletePiInvite = await deleteInvitePiData(piInviteResult.data.id); if (deletePiInvite.status !== 'SUCCESS') { logger.error('Error deleting existing PI invite', deletePiInvite.message); return failure('SYSTEM_ERROR', 'An unexpected error occurred.'); } return consentInviteResult; } const invite = ClinicianInviteResponse.safeParse({ ...piInviteResult.data, ...consentInviteResult.data, }); if (!invite.success) { logger.error('Received invalid data in create invite response', invite.error.issues); return failure('SYSTEM_ERROR', invite.error.message); } return success(invite.data); } catch (error) { logger.error('Unexpected error handling create invite response', error); return failure('SYSTEM_ERROR', 'An unexpected error occurred.'); } };
import * as React from "react"; import Box from "@mui/material/Box"; import Slider from "@mui/material/Slider"; import TextField from "@mui/material/TextField"; import IconButton from "@mui/material/IconButton"; import AddIcon from "@mui/icons-material/Add"; import RemoveIcon from "@mui/icons-material/Remove"; export default function CustomSlider() { const [value, setValue] = React.useState(30); const handleSliderChange = (event, newValue) => { setValue(newValue); }; const handleInputChange = (event) => { setValue(event.target.value === "" ? "" : Number(event.target.value)); }; const handleBlur = () => { if (value < 0) { setValue(0); } else if (value > 100) { setValue(100); } }; const handleIncrement = () => { if (value < 100) { setValue(value + 1); } }; const handleDecrement = () => { if (value > 0) { setValue(value - 1); } }; return ( <Box sx={{ width: 300 }}> <Slider value={typeof value === "number" ? value : 0} onChange={handleSliderChange} aria-labelledby="input-slider" min={0} max={100} /> <Box sx={{ display: "flex", alignItems: "center", mt: 2 }}> <IconButton onClick={handleDecrement} aria-label="decrement"> <RemoveIcon /> </IconButton> <TextField value={value} size="small" onChange={handleInputChange} onBlur={handleBlur} inputProps={{ step: 1, min: 0, max: 100, type: "number", "aria-labelledby": "input-slider", }} /> <IconButton onClick={handleIncrement} aria-label="increment"> <AddIcon /> </IconButton> </Box> </Box> ); }
// // UserPreferenceViewController.swift // PalavraViva // // Created by Reinaldo Neto on 26/11/23. // import Firebase import UIKit enum MenuType { case primary case secondary } class UserPreferenceViewController: UIViewController { @IBOutlet var fontSizeDescriptionLabel: UILabel! @IBOutlet var fontSizeLabel: UILabel! @IBOutlet var sliderComponent: UISlider! @IBOutlet var logoutButton: UIButton! @IBOutlet var primaryVersionButton: UIButton! @IBOutlet var secondaryVersionButton: UIButton! override func viewDidLoad() { super.viewDidLoad() configElements() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } func configElements() { fontSizeDescriptionLabel.text = "Tamanho da Fonte" fontSizeLabel.text = String(UserPreferences.getFontSize()) sliderComponent.addTarget(self, action: #selector(onSliderValChanged(slider:event:)), for: .valueChanged) sliderComponent.minimumValue = 10 sliderComponent.maximumValue = 48 sliderComponent.value = Float(UserPreferences.getFontSize()) configPrimaryMenu() configSecondaryMenu() logoutButton.tintColor = .red } func handleElementMenuPrimary(version: Versions) { if version.rawValue != UserPreferences.getPrimaryVersion() { UserPreferences.updateUserDefaults(version.rawValue, .primaryVersion) NotificationCenter.default.post(name: .changePrimaryVersion, object: nil) } } func handleElementMenuSecondary(version: Versions) { if version.rawValue != UserPreferences.getSecondaryVersion() { UserPreferences.updateUserDefaults(version.rawValue, .secondaryVersion) NotificationCenter.default.post(name: .changeSecondaryVersion, object: nil) } } func configMenuAndElements(title: String, versionSelected: String,_ type: MenuType) -> UIMenu { var elements: [UIAction] = [] Versions.allCases.forEach({ version in let el = UIAction(title: UserPreferences.versionName(version), state: version.rawValue == versionSelected ? .on : .off) { _ in type == .primary ? self.handleElementMenuPrimary(version: version) : self.handleElementMenuSecondary(version: version) } elements.append(el) }) return UIMenu(title: title, children: elements) } func configPrimaryMenu() { let versionSelected = UserPreferences.getPrimaryVersion() let menu = configMenuAndElements(title: "Versão principal", versionSelected: versionSelected, .primary) primaryVersionButton.showsMenuAsPrimaryAction = true primaryVersionButton.menu = menu } func configSecondaryMenu() { let versionSelected = UserPreferences.getSecondaryVersion() let menu = configMenuAndElements(title: "Versão de consulta", versionSelected: versionSelected, .secondary) secondaryVersionButton.showsMenuAsPrimaryAction = true secondaryVersionButton.menu = menu } @objc func onSliderValChanged(slider: UISlider, event: UIEvent) { if let touchEvent = event.allTouches?.first { switch touchEvent.phase { case .moved: fontSizeLabel.text = "\(Int(slider.value))" case .ended: changeFontSizeUserPreference(Int(slider.value)) default: break } } } func changeFontSizeUserPreference(_ value: Int) { if value != UserPreferences.getFontSize() { UserPreferences.updateUserDefaults(value, .fontSize) NotificationCenter.default.post(name: .changeFontSize, object: nil) } } @IBAction func tappedLogout(_ sender: UIButton) { let okAction = UIAlertAction(title: "OK", style: .destructive) { [weak self] _ in guard let self else { return } self.handleLogout() } let cancelAction = UIAlertAction(title: "Cancelar", style: .default, handler: nil) Alert.setNewAlert(target: self, title: "Alerta", message: "Você realmente deseja fazer o logout do app?", actions: [cancelAction, okAction]) } func handleLogout() { do { try Auth.auth().signOut() UserAuth.removeSavedToken() RootNavigationController.shared.navigationController()?.popToRootViewController(animated: true) } catch { Alert.setNewAlert(target: self, title: "Error", message: "Erro ao realizar o logout: \(error.localizedDescription)") } } }
import { readFile } from 'node:fs/promises'; import { describe, test } from 'node:test'; import { URL } from 'node:url'; import { expect } from 'chai'; import { FrameHeader } from './frame-header.js'; import { ID3v2Header } from './id3-v2-header.js'; describe('FrameHeader', () => { test('correctly returns values for Buffer [0xFF, 0xFB, 0xA0, 0x40]', () => { const headerBuffer = Buffer.from([ 0b1111_1111, 0b1111_1011, 0b1010_0000, 0b0100_0000, ]); const expectedOutput = { IsFrameHeader: true, Version: 1, Layer: 3, Bitrate: 160, SampleRateFrequency: 44100, Padding: false, SamplesCount: 1152, FrameLength: 522, }; const frameHeader = new FrameHeader(headerBuffer); expect(frameHeader.toJSON()).to.deep.equal(expectedOutput); }); test('correctly asserts if a buffer is NOT a frame header', () => { const headerBuffer = Buffer.from([ 0b1110_1111, // 0xEF 0b1111_1011, 0b1010_0000, 0b0100_0000, ]); const frameHeader = new FrameHeader(headerBuffer); expect(frameHeader.IsFrameHeader).to.equal(false); }); test('correctly return error "Invalid MP3 Version"', () => { const headerBuffer = Buffer.from([ 0b1111_1111, 0b1110_1011, // incorrect version bits -> null 0b1010_0000, 0b0100_0000, ]); const frameHeader = new FrameHeader(headerBuffer); expect(() => frameHeader.toJSON()).to.throw('Invalid MP3 Version'); }); test('correctly return error "Invalid MP3 Layer"', () => { const headerBuffer = Buffer.from([ 0b1111_1111, 0b1111_1001, // incorrect layer bits -> null 0b1010_0000, 0b0100_0000, ]); const frameHeader = new FrameHeader(headerBuffer); expect(() => frameHeader.toJSON()).to.throw('Invalid MP3 Layer'); }); test('correctly return error "Invalid MP3 Bitrate"', () => { const headerBuffer = Buffer.from([ 0b1111_1111, 0b1111_1011, 0b0000_0000, // incorrect bitrate (free) -> null 0b0100_0000, ]); const frameHeader = new FrameHeader(headerBuffer); expect(() => frameHeader.toJSON()).to.throw(`Invalid MP3 Bitrate: 0`); }); test('correctly return error "Invalid MP3 Sampling Rate Frequency"', () => { const headerBuffer = Buffer.from([ 0b1111_1111, 0b1111_1011, 0b1010_1100, // incorrect Sampling Rate Frequency (free) -> null 0b0100_0000, ]); const frameHeader = new FrameHeader(headerBuffer); expect(() => frameHeader.toJSON()).to.throw(`Invalid MP3 Sampling Rate Frequency`); }); test('correctly parses the sample.mp3', async () => { const fileURL = new URL('../fixtures/sample.mp3', import.meta.url); const buffer = await readFile(fileURL); const id3 = new ID3v2Header(buffer); const frame1 = buffer.subarray(id3.Size); const expectedOutput1 = { IsFrameHeader: true, Version: 1, Layer: 3, Bitrate: 64, SampleRateFrequency: 44100, Padding: false, SamplesCount: 1152, FrameLength: 208, }; const frameHeader1 = new FrameHeader(frame1); expect(frameHeader1.toJSON()).to.deep.equal(expectedOutput1); const frame2 = frame1.subarray(frameHeader1.FrameLength); const expectedOutput2 = { IsFrameHeader: true, Version: 1, Layer: 3, Bitrate: 32, SampleRateFrequency: 44100, Padding: false, SamplesCount: 1152, FrameLength: 104, }; const frameHeader2 = new FrameHeader(frame2); expect(frameHeader2.toJSON()).to.deep.equal(expectedOutput2); }); });
// src/components/RecipeDetailPage.js import React, { useState, useEffect } from 'react'; import { useParams } from 'react-router-dom'; import { doc, setDoc, deleteDoc, getDoc } from 'firebase/firestore'; import { useAuthState } from 'react-firebase-hooks/auth'; import axios from 'axios'; import { auth, db } from '../firebaseConfig'; const SPOONACULAR_API_KEY = '227cf6531f45458d89bfcd85753201c0'; const RecipeDetailPage = () => { const { id } = useParams(); const [user] = useAuthState(auth); const [recipe, setRecipe] = useState(null); const [nutrition, setNutrition] = useState(null); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(false); const [isFavorite, setIsFavorite] = useState(false); const fetchRecipe = async () => { setIsLoading(true); try { // Fetch Recipe Details const recipeResponse = await axios.get( `https://api.spoonacular.com/recipes/${id}/information`, { params: { apiKey: SPOONACULAR_API_KEY, }, } ); setRecipe(recipeResponse.data); // Fetch Nutrition Information const nutritionResponse = await axios.get( `https://api.spoonacular.com/recipes/${id}/nutritionWidget.json`, { params: { apiKey: SPOONACULAR_API_KEY, }, } ); setNutrition(nutritionResponse.data); if (user) { checkIfFavorite(); } } catch (error) { console.error('Error fetching recipe details:', error.response?.data || error.message); setError('Error fetching recipe details, please try again later.'); } finally { setIsLoading(false); } }; const checkIfFavorite = async () => { const favoriteRef = doc(db, `users/${user.uid}/favorites`, id); const docSnap = await getDoc(favoriteRef); setIsFavorite(docSnap.exists()); }; const handleToggleFavorite = async () => { if (!user) { alert('You must be logged in to save favorites.'); return; } const favoriteRef = doc(db, `users/${user.uid}/favorites`, id); if (isFavorite) { // Remove from favorites try { await deleteDoc(favoriteRef); alert(`${recipe.title} has been removed from your favorites.`); setIsFavorite(false); } catch (err) { console.error('Error removing from favorites:', err.message); alert('Error removing from favorites, please try again later.'); } } else { // Add to favorites const favoriteData = { id: recipe.id, title: recipe.title, image: recipe.image, }; try { await setDoc(favoriteRef, favoriteData); alert(`${recipe.title} has been added to your favorites!`); setIsFavorite(true); } catch (err) { console.error('Error adding to favorites:', err.message); alert('Error adding to favorites, please try again later.'); } } }; useEffect(() => { fetchRecipe(); }, [id]); const formatInstructions = (instructions) => { if (!instructions || !Array.isArray(instructions) || instructions.length === 0) { return 'Instructions not available.'; } return instructions[0].steps.map((step) => step.step); }; const displayInfo = (label, value) => { if (value !== undefined && value !== -1 && value !== 'Not available') { return ( <p className="flex-1 mb-2 md:mb-0 bg-gray-100 py-2 px-4 rounded-md text-center mx-2"> <strong>{label}:</strong> {value} </p> ); } return null; }; if (isLoading) { return <p>Loading...</p>; } if (error) { return <p className="text-red-600">{error}</p>; } if (!recipe) { return <p>Recipe not found.</p>; } const { servings = 'Not available', readyInMinutes = 'Not available', preparationMinutes, cookingMinutes, extendedIngredients = [], analyzedInstructions = [], } = recipe; const instructionList = formatInstructions(analyzedInstructions); return ( <div className="max-w-2xl mx-auto my-10 p-8 bg-white rounded-lg shadow-md"> <h2 className="text-2xl font-bold text-center mb-4">{recipe.title}</h2> <img src={recipe.image} alt={recipe.title} className="w-full mb-6 rounded-md shadow-lg" /> <div className="flex flex-col md:flex-row md:justify-between mb-6"> {displayInfo('Servings', servings)} {displayInfo('Ready in Minutes', readyInMinutes)} {displayInfo('Preparation Time', preparationMinutes !== -1 ? preparationMinutes : 'Not available')} {displayInfo('Cooking Time', cookingMinutes !== -1 ? cookingMinutes : 'Not available')} </div> <h3 className="text-xl font-semibold mb-2">Ingredients</h3> <ul className="list-disc list-inside bg-gray-100 p-4 rounded-lg mb-6"> {extendedIngredients.map((ingredient) => ( <li key={ingredient.id}>{ingredient.original}</li> ))} </ul> <h3 className="text-xl font-semibold mb-2">Instructions</h3> <ol className="list-decimal list-inside bg-gray-100 p-4 rounded-lg mb-6 leading-relaxed"> {Array.isArray(instructionList) && instructionList.length > 0 ? instructionList.map((instruction, index) => ( <li key={index}>{instruction}</li> )) : <li>Instructions not available.</li>} </ol> {nutrition && ( <div className="mb-6"> <h3 className="text-xl font-semibold mb-2">Nutritional Information</h3> <ul className="list-disc list-inside bg-gray-100 p-4 rounded-lg"> <li><strong>Calories:</strong> {nutrition.calories}</li> <li><strong>Carbs:</strong> {nutrition.carbs}</li> <li><strong>Fat:</strong> {nutrition.fat}</li> <li><strong>Protein:</strong> {nutrition.protein}</li> </ul> </div> )} <button onClick={handleToggleFavorite} className={`w-full py-2 rounded-md text-white ${isFavorite ? 'bg-red-500 hover:bg-red-600' : 'bg-blue-500 hover:bg-blue-600'}`} > {isFavorite ? 'Remove from Favorites' : 'Add to Favorites'} </button> </div> ); }; export default RecipeDetailPage;
import React, { useState } from "react"; import reactDom from "react-dom"; import { useDispatch } from "react-redux"; import { actionCreators } from "../../redux"; import AddIcon from "@mui/icons-material/Add"; import DeleteIcon from "@mui/icons-material/Delete"; import styles from "./modal.module.css"; import { IconButton } from "@mui/material"; const Modal = ({setShow, profile}) => { const dispatch = useDispatch(); const [dp, setDp] = useState(""); const [image, setImage] = useState(profile.profilepic); const [error, setError] = useState(""); const onPicChange = (e) => { setImage(e.target.files[0]); setDp(URL.createObjectURL(e.target.files[0])); }; const onRemove = (e) => { e.preventDefault(); setDp(""); setImage(""); }; const onUpload = () => { if (image === "") { setError("Upload a valid image"); } else if(image === profile.profilepic) { setShow(false); } else { dispatch(actionCreators.addDp(image)); setShow(false); } }; return reactDom.createPortal( <> <div className={styles.backdrop}></div> <div className={styles.modal}> <div className={styles.imagePreview}> {dp !== "" && ( <IconButton className={styles.deletebtn} onClick={onRemove}> <DeleteIcon style={{ color: "red" }} /> </IconButton> )} {dp !== "" ? ( <img src={dp} alt="Profile" className={styles.image} /> ) : ( <label htmlFor="dp"> <AddIcon className={styles.addIcon} /> </label> )} <input type="file" id="dp" onChange={onPicChange} /> </div> <button className={styles.uploadbtn} onClick={onUpload}>Upload</button> <button className={styles.cancelbtn} onClick={()=> setShow(false)}>Cancel</button> {error !== "" && <h3>{error}</h3>} </div> </>, document.getElementById("modal") ); }; export default Modal;
<!DOCTYPE html> <html lang="en"> <head> <!-- Meta Information --> <title>Tweeter - Home Page</title> <!-- External CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" type="text/css" /> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Bungee&family=Source+Sans+Pro:wght@200&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <!-- App CSS --> <link rel="stylesheet" href="/styles/layout.css" type="text/css" /> <link rel="stylesheet" href="/styles/nav.css" type="text/css" /> <link rel="stylesheet" href="/styles/header.css" type="text/css" /> <link rel="stylesheet" href="/styles/new-tweet.css" type="text/css" /> <link rel="stylesheet" href="/styles/tweet-container.css" type="text/css" /> <!-- External JS --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/timeago.js/4.0.2/timeago.min.js"></script> <!-- App JS --> <script type="text/javascript" src="/scripts/client.js"></script> <script type="text/javascript" src="/scripts/composer-char-counter.js"></script> <!-- <script type="text/javascript" src="/node_modules/timeago.js"></script> --> </head> <body> <!-- Top nav bar (fixed) --> <nav> <span class="nav-logo">tweeter</span> <div> <div><strong>Write</strong> a new tweet</div> <div class="nav-right"> <i class="fa-solid fa-angles-down fa-xl"></i> </div> </div> </nav> <header class="profile"> <div> <img src="/images/profile-hex.png"> </div> <div> <h2 class="name">Eric Duncan</h2> </div> </header> <!-- Page-specific (main) content here --> <main class="container"> <section class="new-tweet"> <br> <div class="error-messages-div"> <span class="error-messages"></span> <span class="error-messages-icon"></span> </div> <br> <form class="tweet-box"> <label class="label" for="tweet-text"> <strong>What are you humming about?</strong></label> <br> <textarea name="text" id="tweet-text"></textarea> <div class="button-and-counter"> <button class="button" type="submit"> Tweet </button> <output class="counter" name="counter" for="tweet-text"><strong>140</strong></output> </div> </form> <div class="tweet-container"> <span> <article class="tweet"> <div class="user-username"> <div>USER</div> <div>@USERNAME</div> </div> <section> This is a Tweet </section> <footer> <span> X DAYS AGO </span> <div class="emojis"> <i class="fa-solid fa-flag" id="flag-emoji"></i> <i class="fa-solid fa-retweet" id="retweet-emoji"></i> <i class="fa-solid fa-heart" id="heart-emoji"></i> </div> </footer> </article> </span> </div> </section> </main> </body> </html>
<x-organism.modal id="supplierModal" :tipe="__('xl')" :title="__('Data Supplier')"> <x-molecules.table-datatable id="suppliersDatatables"> <x-slot name="thead"> <tr class="text-start text-black-50 fw-bolder fs-7 text-uppercase gs-0 border-1"> <th class="text-center" width="10%">ID</th> <th class="text-center">Nama</th> <th class="none">Telepon</th> <th class="text-center">Alamat</th> <th class="text-center none">NPWP</th> <th class="text-center none">Email</th> <th class="none">Keterangan</th> <th class="text-center" width="15%">Actions</th> </tr> </x-slot> <tbody class="text-gray-600 fw-bold border"> </tbody> </x-molecules.table-datatable> </x-organism.modal> @push('custom-scripts') <script> "use strict"; // class definition var dataSupplier = function (){ // shared variables var table; var dt; // private functions var initDatatable = function(){ dt = $("#suppliersDatatables").DataTable({ language : { "lengthMenu": "Show _MENU_", }, dom : "<'row'" + "<'col-sm-6 d-flex align-items-center justify-conten-start'l>" + "<'col-sm-6 d-flex align-items-center justify-content-end'f>" + ">" + "<'table-responsive'tr>" + "<'row'" + "<'col-sm-12 col-md-5 d-flex align-items-center justify-content-center justify-content-md-start'i>" + "<'col-sm-12 col-md-7 d-flex align-items-center justify-content-center justify-content-md-end'p>" + ">", searchDelay : 500, processing : true, serverSide : true, searching : true, order : [], responsive: true, stateSave: true, select: { style: 'os', selector: 'td:first-child', className: 'row-selected' }, ajax : { url : "{{route('datatables.supplier.set')}}", method : 'PATCH', }, columns : [ {data:'supplier_jenis_id'}, {data:'nama'}, {data:'telepon'}, {data:'alamat'}, {data:'npwp'}, {data:'email'}, {data:'keterangan'}, {data:'actions'}, ], columnDefs : [ { targets : -1, orderable : false, className: "text-center" }, { targets : 2, className: "text-center" } ], }); table = dt.$; dt.on('draw', function (){ KTMenu.createInstances(); }); } // Public methods return { init: function () { initDatatable(); } } }(); // on document ready KTUtil.onDOMContentLoaded(function () { dataSupplier.init(); }); // reload table function reload() { $('#suppliersDatatables').DataTable().ajax.reload(); } let supplierModal = new bootstrap.Modal(document.getElementById('supplierModal'), { keyboard: false }) // show by livewire window.livewire.on('showSupplier', function (){ supplierModal.show(); }); // hide by livewire window.livewire.on('hideSupplier', function (){ supplierModal.hide(); }) function setSupplier(id) { Livewire.emit('setSupplier', id); } </script> @endpush
import { getOrderId } from "../../utils/API"; import { IData } from "../../utils/types"; import { AppThunk } from "../store"; import { AppDispatch } from "../store"; export const WS_CONNECTION_START:'WS_CONNECTION_START' = 'WS_CONNECTION_START'; export const WS_CONNECTION_SUCCESS:'WS_CONNECTION_SUCCESS' = 'WS_CONNECTION_SUCCESS'; export const WS_CONNECTION_ERROR:'WS_CONNECTION_ERROR' = 'WS_CONNECTION_ERROR'; export const WS_CONNECTION_CLOSED:'WS_CONNECTION_CLOSED' = 'WS_CONNECTION_CLOSED'; export const WS_GET_MESSAGE:'WS_GET_MESSAGE' = 'WS_GET_MESSAGE'; export const WS_SEND_MESSAGE:'WS_SEND_MESSAGE' = 'WS_SEND_MESSAGE'; export const GET_ORDER_ID:'GET_ORDER_ID' = 'GET_ORDER_ID'; export const WS_AUTH_CONNECTION_START:'WS_AUTH_CONNECTION_START' = 'WS_AUTH_CONNECTION_START'; export const WS_AUTH_CONNECTION_CLOSED:'WS_AUTH_CONNECTION_CLOSED' = 'WS_AUTH_CONNECTION_CLOSED'; export const WS_AUTH_CONNECTION_SUCCESS:'WS_AUTH_CONNECTION_SUCCESS' = 'WS_AUTH_CONNECTION_SUCCESS'; export const WS_AUTH_CONNECTION_ERROR:'WS_CONNECTION_ERROR' = 'WS_CONNECTION_ERROR'; export const CLOSED_ORDER_ID:'CLOSED_ORDER_ID' = 'CLOSED_ORDER_ID' interface IPayload{ total:number; totalToday:number; orders:Array<IData> } interface IGetDataProfile { type: typeof GET_ORDER_ID; payload: IData } interface IWsConnectionSuccess { type: typeof WS_CONNECTION_SUCCESS; } interface IWsConnectionStart{ type: typeof WS_CONNECTION_START; } interface IWsConnectionError { type: typeof WS_CONNECTION_ERROR; } interface IWsConnectionClosed { type: typeof WS_CONNECTION_CLOSED; } interface IWsGetMessage { type: typeof WS_GET_MESSAGE; payload: IPayload } interface IWsAuthConnectionSuccess { type: typeof WS_AUTH_CONNECTION_SUCCESS; } interface IClosedOrderId{ type: typeof CLOSED_ORDER_ID; } export type TWsActions = |IGetDataProfile |IWsConnectionSuccess |IWsConnectionError |IWsConnectionClosed |IWsGetMessage |IWsAuthConnectionSuccess |IClosedOrderId |IWsConnectionStart export function getDataProfile(data:IData):IGetDataProfile { return { type: GET_ORDER_ID,payload:data}; } export const getOrderIdData:AppThunk = (id: string) => { return function (dispatch:AppDispatch) { getOrderId(id) .then((res) => { const ApiData = res.orders[0]; dispatch(getDataProfile(ApiData)); }) .catch((err) => { console.log(`Ошибка при загрузке ингредиентов: ${err}`); }); }; }
const mongoose = require('mongoose'); const { model, Schema } = mongoose; const Invoice = require('../invoice/model') const orderSchema = Schema({ status: { type: String, enum: ['waiting_payment', 'processing', 'in_delivery', 'delivered'], default: 'waiting_payment' }, delivery:{ type: Number, default: 0, }, delivery_address:{ provinsi: { type: String, require: [true, 'provinsi harus di isi'], }, kabupaten:{ type: String, require: [true, 'kabupaten harus di isi'], }, kecamatan:{ type: String, require: [true, 'kecamatan harus di isi'], }, kelurahan: { type: String, require: [true, 'kelurahan harus di isi'], }, detail: { type: String, require: [true, 'detail harus di isii'], } }, user: { type: Schema.Types.ObjectId, ref: 'User', }, order_items: [{ type: Schema.Types.ObjectId, ref: 'order_number' }] }, {timestamps: true}) // orderSchema.plugins(AutoIncrement, { inc_field: 'order_number'}); orderSchema.virtual('items_count').get(function () { return this.order_items.reduce((total, item) => total + parseInt(item.qty), 0) }) orderSchema.post('save', async function (){ let sub_total = this.order_items.reduce((total, item) => total += (item.price * item.qty), 0) let invoice = new Invoice({ user: this.user, order: this._id, sub_total: sub_total, delivery_fee: parseInt(this.delivery_fee), total: parseInt(sub_total + this.delivery_fee), delivery_address: this.delivery_address, }) await invoice.save() }) module.exports = model('Order', orderSchema)
import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { DbService } from 'src/db/db.service'; @Injectable() export class JwtStrategy extends PassportStrategy( Strategy, 'jwt', //name of the strategy ) { constructor( config: ConfigService, private db: DbService, ) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: config.get('JWT_SECRET'), }); } async validate(payload: { sub: number; email: string; }) { const user = await this.db.user.findUnique({ where: { id: payload.sub, }, }); delete user.hash; return user; } }
Day1 Core Java8 version Eclipse > mars/neon versions and intellij Spring 5.x version in our training Spring 5.x version is compatable with jdk1.8. We are going to use maven 3.x version for building the projects. In some projects we are going to use Gradle. spring 1.x,2.x,3.x,4.x,5.x,6.x latest version for spring : 6.0.7 GA release GA stands for general availability. means available for public use https://spring.io/projects/spring-framework https://docs.spring.io/spring-framework/docs/5.3.26/javadoc-api/ https://spring.academy/learning-path---for certification path ---------------------------------------------------------------------------------- Before Spring,we are having CORBA,EJB and structs fw. Why we need to learn Spring? Using Spring we can design coding for below: 1)Using spring we can learn Spring cloud which is used for Microservices/cloud development. 2)for designing a microservice,we are going to use Springboot for which spring is prereq. 3)used to handle Dependency injection issues,to handle business logic.....etc what is spring? -Spring is not a programming lang. -Intially spring was started as a project.Now people are calling as Spring fw. -Spring fw came up with so many modules. Below are some of the modules: Spring RMI,Spring ORM,Spring JDBC,Spring Vault,Spring MVC....etc Main drawback with spring is development time.We dont have necessary dev tools by default with spring. ---------------------------------- use below approach only for springboot app development :https://start.spring.io/ Note: kotlin is a programming languge mainly used for Andriod development. ----------------- Spring intro Spring RMI Spring Dependency injection and its ways AOP basics Spring MVC >>>> Servlets and jsp are mainly used for web development. If we want to run a Servlet Program,we need a Catalina container.or catalina is a software which knows how to run a servlet program. If we want to run a JSP program,we need jasper container.Jasper is a s/w which knows how to run a jsp program. Apache Tomcat is a web server. Tomcat= Catalina+Jasper+Middleware services. To run a Spring program we need IOC container. >> A obj= new A(); class A{ B b1;//we had hardcoded the classname } class B{ public void add()//non static method { System.out.println("....Hi...."); } } A is tightly coupled with B class. tightly coupled means there is huge dependency.Exa: Visnu is dependent on Srini and srini is dependent on visnu Srini can work without visnu.then it is loosely coupled. Here from above code,A class is depending on B class.Now in future if we change the classname of B to "Bat".then what will happen? To handle above scenario,industry came up with a design pattern/Solution called as "Dependency injection". To work on dependency injection,we are going to use "IOC container". IOC---inversion of control In dependency injection,instead of hard coding the dependencies in code,instead we are going to inject dependencies thru some xml or properties files. Dependency injection can be implemented thru IOC container.Spring resolves the above issue with SPring IOC. Spring had given 2 IOC containers into the market. 1)BeanFactory 2)ApplicationContext3 To work on Spring,mainly we need to know POJO class. POJO means plain old java Object. A class is apojo class if it follows below rules: 1)setters and getters for variables 2)every variable shld be private 3)all methods shld be public. Input to your ioc container is a POJO class and a xml file. Scaffolding: Process of creating a new project structure is called as Scaffolding. In maven,groupid means package name,Artifactid means projectname. MAjority of the projects use the below naming convention for package name: com.<company/customername>.modulename Example: com.comcast.backend infosys com.infosys.backend >>>>>>>>>>>>>>>>>>>> Day 2: To design a spring app,we need to follow below steps: 1)Always create maven/gradle project for Spring. 2)Always add your dependencies in pom.xml instead of adding to buildpath. 3)In spring,we need to maintain beans in a separate package. 4)Make sure pom.xml file is valid and clean. 5)Always make sure your project is pointing out to jdk1.8. Maven/gradle is build tool. MAven will read your pom.xml file while building the project.pom.xml file is a configuration file. Wen u run a desktop app,the final output will be jar file. Wen u run a Web app,the final output will be war file. Wen u run a enterprise app,the final output will be ear file. Spring Core----jar file Spring MVC-----war file --------------------------------------------------------------------------- src/main/resources---->this is a place where we are going to place or create spring configuration files. src/main/java----->this is a place where we are going to place java files. src/test/java----->this is a place where we are going to create test class. target----->this is a place where jar/war file will be created after building the project. ---------------------------- <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context/ http://www.springframework.org/schema/context/spring-context.xsd"> </beans> Whene ever we are creeating a pojo class or bean,then that class data shld be inserted in beans tag. ApplicationContext ctx1 = new ClassPathXmlApplicationContext("beans.xml"); //this line will initiate spring ioc container //It will start reading the beans.xml file ApplicationContext and then it will allocate memory. ClassPathXmlApplicationContext is implementation of the interface MyBean bn = (MyBean) ctx1.getBean("myname");//getbean will fetch/find the bean with name "myname" from memory and assigns the same to bn. bn.display(); ---------------------- setter injections constructor injections If we wan t to initialize any varaible values in a class we can do it in 2 ways. 1)setter injection---Java bean with setters and getterss 2)constructor injection---we are going to create a constructor and ar going to initiliza values thru beans.xml. >>constrcutors are mainly used for initilizing class level variables. >> Pojo classes are also called as java beans or business classes. >>Till now we are providing metadata in beans.xml file. In spring we can proivide meta data or configuration data in 3 ways. 1)xml 2)Annotations--recommended 3)Java config--not recommended If we want to learn spring properly from basics,xml is right approach. >>>Every container will have lifecycle phases. Human lifecycle: birth>>Education>works>marriage>>>death >>spring jdbc,rom mapper spring collections setters and getters Bean lifecycle scopes Spring ORM and spring hibernate Monday: Spring MVC and AOP basics,rmi Day3:
--- title: "These Common JavaScript Mistakes Reduce Performance Drastically" date: "2022-02-19T13:44:41.800Z" tags: "javascript, optimization" description: "JavaScript doesn’t provide any memory management primitives. Instead, memory is managed by the JavaScript VM through a memory reclaim process. That process is known as Garbage Collection. Since we can’t force it to run, how do we know it will work properly? What do we know about it? Script execution is paused during the process. It frees memory for unreachable resources. It is non-deterministic. It will not inspect the whole memory in one go but will run in multiple cycles. It is unpredictable. It will execute when necessary." cover_image: "20220219134441-javascript-memory-mistakes.png" --- How can we prevent our web app from leaking memory? We have to avoid the retention of unnecessary resources. Let’s look at the most common scenarios where this might happen. # Timer Listeners Let’s look at the `setInterval` timer. It is a commonly used Web API feature. The return of `setInterval` is an interval ID which we can use to cancel the interval. We can call `clearInterval` once the Component unmounts. # Event Listeners When using `addEventListener`, we need to use `removeEventListener` to remove it. # Observers > “The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport).” — [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) Once you are done observing the object, you need to cancel out the monitor process. # Holding DOM References DOM nodes are not free from memory leaks either. You need to be careful not to hold references of them. # Conclusion It is recommended to periodically run the browser profiler tools on your web application. That is the only way to be sure that nothing is leaking and left behind. The Chrome Developer `performance` tab is the place to start detecting some anomalies. After you have spotted an issue, you can dig deeper into it with the `profiler` tab by taking snapshots and comparing them. > ** Don’t forget to clap 👏 in the comment section below if you learned something new**
<mat-sidenav-container class="sidenav-container"> <mat-sidenav #drawer class="sidenav" fixedInViewport [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'" [mode]="(isHandset$ | async) ? 'over' : 'side'" [opened]="(isHandset$ | async) === false"> <button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()" *ngIf="isHandset$ | async"> <mat-icon aria-label="Side nav toggle icon">menu</mat-icon> </button> <br> <mat-nav-list class="nav-list"> <img class="logo" mat-card-image src="../../assets/mainlogo.png"> <img class="adminvector" mat-card-image src="../../assets/customervector.png"> <h1 class="sidetitle">{{fname}}</h1> <div class="dashboardside" (click)="goDashboard()"> <mat-list-item (click)="closeSideNav()"> <mat-icon class="nav-icon" aria-hidden="false" aria-label>home</mat-icon> <a class="dashboard-btn">Home</a> </mat-list-item> </div> <div class="bookingside" routerLink="/booking"> <mat-list-item (click)="closeSideNav()"> <mat-icon class="nav-icon" aria-hidden="false" aria-label="">insert_invitation</mat-icon> <a class="booking-btn">Book a Service</a> </mat-list-item> </div> <div class="profileside" routerLink="/profile"> <mat-list-item (click)="closeSideNav()"> <mat-icon class="nav-icon" aria-hidden="false" aria-label="">account_circle</mat-icon> <a class="profile-btn">Profile</a> </mat-list-item> </div> <div class="logoutside" (click)="logout()"> <mat-list-item (click)="closeSideNav()"> <mat-icon class="nav-icon">exit_to_app</mat-icon> <a class="logout-btn">Logout</a> </mat-list-item> </div> </mat-nav-list> </mat-sidenav> <mat-sidenav-content> <mat-toolbar> <button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()" *ngIf="isHandset$ | async"> <mat-icon aria-label="Side nav toggle icon">menu</mat-icon> </button> </mat-toolbar> <div class="container"> <!--REQUEST SUMMARY------------------------------------------------> <div> <button class="backBtn" routerLink="/dashboard" mat-icon-button> <mat-icon class="backicon">chevron_left</mat-icon> </button> <div> <button mat-raised-button (click)="open(cancelReason)" class="cancelBtn">Cancel Request</button> </div> <mat-card class="summary"> <div> <img class="remindervector" mat-card-image src="../../assets/reminder.png"> <h1 class="title">Booking Details</h1> <label class="label">View your booking details.</label> </div> <table class="table"> <thead> <tr> <th class="header1">First Name</th> <th class="header1">Last Name</th> <th class="header1">Contact Number</th> <th class="header1">Address</th> </tr> </thead> <tbody> <tr> <td class="body1">{{data.service_firstname}}</td> <td class="body1">{{data.service_lastname}}</td> <td class="body1">{{data.service_phoneNumber}}</td> <td class="body1">{{data.service_address}}</td> </tr> </tbody> <thead> <tr> <th class="header2">Address Details</th> <th class="header2">City</th> <th class="header2">Property Type</th> <th class="header2">Barangay</th> </tr> </thead> <tbody> <tr> <td class="body2">{{data.service_addressDetails}}</td> <td class="body2">{{data.service_city}}</td> <td class="body2">{{data.service_property_type}}</td> <td class="body2">{{data.service_barangay}}</td> </tr> </tbody> </table> <table class="table"> <thead> <tr> <th class="header1">Appliance</th> <th class="header1">Service</th> <th class="header1">Brand</th> <th class="header1">Unit Type</th> </tr> </thead> <tbody> <tr> <td class="body1">{{data.service_appliance}}</td> <td class="body1">{{data.service_type}}</td> <td class="body1">{{data.service_brand}}</td> <td class="body1">{{data.service_unitType}}</td> </tr> </tbody> <thead> <tr> <th class="header2">Unit Problem</th> <th class="header2">Scheduled Date</th> <th class="header2">Time Slot</th> <th class="header2">Instruction</th> </tr> </thead> <tbody> <tr> <td class="body2">{{data.service_unitProb}}</td> <td class="body2">{{data.service_date | date}}</td> <td class="body2">{{data.service_timeslot}}</td> <td class="body2">{{data.service_instruction}}</td> </tr> </tbody> <thead> <tr> <th class="header2">Special Instruction/Request</th> </tr> </thead> <tbody> <tr> <td class="body2">{{data.special_instruct}}</td> </tr> </tbody> </table> </mat-card> </div> </div> </mat-sidenav-content> </mat-sidenav-container> <ng-template #cancelReason let-c="close" let-d="dismiss"> <div class="modal-header"> <h4 class="modal-title" id="modal-basic-title">Cancel request?</h4> <button type="button" class="close" aria-label="Close" (click)="d('Cross click')"> <span aria-hidden="true">&times;</span> </button> </div> <form [formGroup]="cancelreasonForm"> <div class="modal-body"> <div> <h6>Please share the reason to serve you better next time </h6> <button mat-stroked-button class="radioBtn" value="Schedule conflict"> <input type="radio" value="Schedule conflict" formControlName="reason" required>&nbsp;Conflict of Schedule. </button> <button mat-stroked-button class="radioBtn" value="Problem went away"> <input type="radio" value="Problem went away" formControlName="reason" required>&nbsp;Problem went away. </button> <button mat-stroked-button class="radioBtn" value="Found another provider"> <input type="radio" value="Found another provider" formControlName="reason" required>&nbsp;Found another provider. </button> <button mat-stroked-button class="radioBtn" value="Personal emergency"> <input type="radio" value="Personal emergency" formControlName="reason" required>&nbsp;Personal emergency. </button> </div> </div> <div class="modal-footer"> <button type="button" id="close" class="btn btn-outline-primary" (click)="c('Close')">Keep my booking</button> <button type="button" class="btn btn-outline-danger" (click)="getConfirmation()">Cancel Request</button> </div> </form> </ng-template>
#! /usr/bin/env python3 """ Unit tests for convert_to_morse_code.py """ from hypothesis import given, strategies as st from convert_to_morse_code import convert_to_morse_code import unittest class Test_convert_to_morse_code(unittest.TestCase): """ Class to test that the convert_to_morse_code class works as intended """ @given(st.text(alphabet=list(convert_to_morse_code ._MORSE_LETTERS_DICT.keys()))) def test_to_morse_code_valid(self, text: str) -> None: """ test with valid input""" try: code = convert_to_morse_code.to_morse_code(text) self.assertIsInstance(code, list) self.assertTrue(all(isinstance(code, int) for code in code)) except ValueError: self.fail() @given(st.text(min_size=1).filter(lambda x: any (c not in convert_to_morse_code ._MORSE_LETTERS_DICT for c in x))) def test_to_morse_code_invalid(self, text: str) -> None: """ test with invalid input. Use the lambda function in .filter() to ensure string x has at least one char not in List """ with self.assertRaises(ValueError): convert_to_morse_code.to_morse_code(text)
--- id: FACe-FacturaE-e-invoicing-spain title: B2G e-invoicing in Spain - Mandatory Requirement for Entities since 2015 keywords: [B2G e-invoicing, Mandatory e-invoicing, Law 25/2013, Spain e-invoicing regulation, Spanish Tax Authority, Ministerio de Hacienda y Función Pública, B2B e-invoicing, FACeB2B platform, General Entry Point, GEP, Electronic invoicing, Draft law Ley Crea y Crece, Mandatory B2B e-invoicing] sidebar_label: FACe - Spain description: Discover the latest updates on B2G and B2B e-invoicing regulations in Spain. Learn about the mandatory requirements under Law 25/2013 and the upcoming changes proposed by the draft law Ley Crea y Crece. Explore the role of the Spanish Tax Authority and the FACeB2B platform in facilitating electronic invoicing. Get insights into the planned implementation timeline and find out how these developments will impact businesses, including detailed requirements and technical specifications. Stay ahead of the curve and prepare your organization for the mandatory adoption of e-invoicing in Spain. tags: - Spain - Einvoicing --- <table > <tr> <td align="left"><b>Country</b></td> <td align="left">Spain</td> </tr> <tr> <td align="Left">Status - B2G</td> <td align="left">Mandatory</td> </tr> <tr> <td align="Left">Status - B2B</td> <td align="left">Mandatory<sup>*</sup></td> </tr> <tr> <td align="Left">Status - B2C</td> <td align="left">NA</td> </tr> <tr> <td align="left">Formats</td> <td align="left">FacturaE</td> </tr> <tr> <td align="left">Authority</td> <td align="left">Ministerio de Hacienda y Función Pública</td> </tr> <tr> <td align="left">Network name</td> <td align="left">FACe</td> </tr> <tr> <td align="left">Legislation</td> <td align="left">Ley Crea y Crece</td> </tr> </table> ## Overview Since 2015, certain entities in Spain have been required to comply with Law 25/2013, making B2G e-invoicing mandatory. This regulation applies to all transactions between suppliers and recipients, where the transaction value exceeds EUR 5,000. The Spanish Tax Authority, known as the Ministerio de Hacienda y Función Pública, oversees this e-invoicing mandate. Currently, B2B e-invoicing is voluntary, and to facilitate this process, the FACeB2B platform, functioning as a General Entry Point (GEP), has been launched. It aims to encourage entrepreneurs to adopt electronic invoicing. However, significant changes are on the horizon. As per the draft law, Ley Crea y Crece (Creation and Growth of Companies), B2B e-invoicing will soon become mandatory. The implementation will occur gradually over the next few years. While the detailed requirements and technical specifications are not yet available, information about the planned activities has been shared. To finalize the changes, social consultations will be conducted until March 2023, following which the final framework will be presented. The timeline for implementation is likely to unfold as follows: * Taxpayers with a turnover exceeding EUR 8 million: Beginning of 2024 i.e. one year after regulatory development approval * All other entrepreneurs: Beginning of 2025 i.e. two years after regulatory development approval These upcoming changes emphasize the increasing importance of e-invoicing in Spain and the need for businesses to prepare for the mandatory requirements in the coming years. ## About FACe FACe serves as the primary gateway for submitting electronic invoices to General Administration bodies. This efficient system allows users to seamlessly send invoices to registered public administration entities capable of receiving such documents. The FACE platform facilitates the seamless referral of electronic invoices to administration bodies. By leveraging this system, invoices are promptly dispatched to the intended recipients. This streamlined process benefits providers by standardizing the electronic invoice format and consolidating all General Government Administration agencies, along with numerous other public administrations (including 18 out of 19 autonomous regions, over 8,000 local entities, and 40 universities), into a single, centralized location. Suppliers can effortlessly submit electronic invoices in the facturae 3.2 format through the user-friendly web portal (face.gob.es). Additionally, a web services interface is available for automated invoice submission directly from their financial management systems. It also provides public administrations with: * a management portal accessible through the Portal of Local Authorities , Autonomous Regions Portal and Administrative Management Portal , where recipients can manage, download and report the processing status of the invoices to the supplier; and * web services interfaces enabling automatic receipt of invoices in their financial management systems. ## Mandatory Compliance and Legal Framework According to Law 25/2013 of 27 December, which promotes electronic invoicing and mandates invoice accounting in the public sector, electronic invoicing became mandatory for Spanish public administrations starting from January 15, 2015. ## Important websites |Website| Link| |--|--| |FACe Portal |[face](https://face.gob.es/en)| |Portal of Local Authorities |[Site](https://ssweb.seap.minhap.es/portalEELL/)| |Autonomous Regions Portal |[Site](https://ssweb.seap.minhap.es/portalCCAA/)| |Administrative Management Portal|[Site](https://portalage.seap.minhap.es/)| ## Reference links * [SII](https://sede.agenciatributaria.gob.es/Sede/iva/suministro-inmediato-informacion/informacion-general.html) * [About FACe](https://joinup.ec.europa.eu/collection/spain-center-technology-transfer/solution/general-entry-point-general-administration-e-invoices-face/about)
import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: '', redirectTo: '/recipes', pathMatch: 'full', }, { path: 'recipes', loadChildren: () => import('./modules/recipe.module').then((mod) => mod.RecipeModule), }, { path: 'shopping-list', loadChildren: () => import('./modules/shopping.module').then((mod) => mod.ShoppingModule), }, { path: 'auth', loadChildren: () => import('./modules/auth.module').then((mod) => mod.AuthModule), }, { path: '**', loadChildren: () => import('./modules/error.module').then((mod) => mod.ErrorModule), }, ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules, initialNavigation: 'enabledBlocking' }), ], exports: [RouterModule], }) export class AppRoutingModule {}
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouteReuseStrategy } from '@angular/router'; import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { AngularFireModule } from 'angularfire2'; import { AngularFireAuthModule } from 'angularfire2/auth'; import { AngularFireDatabaseModule } from '@angular/fire/database'; import { AngularFireStorageModule } from 'angularfire2/storage'; import { AngularFirestoreModule } from '@angular/fire/firestore'; const firebaseConfig = { apiKey: "AIzaSyDy_7YbCmNNfsODpqOLvro-IaXHcH6AboA", authDomain: "login-98297.firebaseapp.com", databaseURL: "https://login-98297.firebaseio.com", projectId: "login-98297", storageBucket: "", messagingSenderId: "227966016116", appId: "1:227966016116:web:a246ca789a355846" }; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [ BrowserModule, IonicModule.forRoot(), AppRoutingModule, AngularFireModule.initializeApp(firebaseConfig), AngularFireAuthModule, AngularFireDatabaseModule, AngularFireStorageModule, AngularFirestoreModule], providers: [ StatusBar, SplashScreen, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule {}
// define // define web page------------------------- #define ServerVersion "2.0" String webpage = ""; bool SPIFFS_present = false; //---------------------------------------- void append_page_header() { webpage = F("<!DOCTYPE html><html>"); webpage += F("<head>"); webpage += F("<title>File Server</title>"); // NOTE: 1em = 16px webpage += F("<meta name='viewport' content='user-scalable=yes,initial-scale=1.0,width=device-width'>"); webpage += F("<style>"); webpage += F("body{max-width:80%;margin:0 auto;font-family:arial;font-size:105%;text-align:center;color:blue;background-color:#F7F2Fd;}"); webpage += F("ul{list-style-type:none;margin:0.1em;padding:0;border-radius:0.375em;overflow:hidden;background-color:#dcade6;font-size:1em;}"); webpage += F("li{float:left;border-radius:0.375em;border-right:0.06em solid #bbb;}last-child {border-right:none;font-size:85%}"); webpage += F("li a{display: block;border-radius:0.375em;padding:0.44em 0.44em;text-decoration:none;font-size:85%}"); webpage += F("li a:hover{background-color:#EAE3EA;border-radius:0.375em;font-size:85%}"); webpage += F("section {font-size:0.88em;}"); webpage += F("h1{color:white;border-radius:0.5em;font-size:1em;padding:0.2em 0.2em;background:#558ED5;}"); webpage += F("h2{color:orange;font-size:1.0em;}"); webpage += F("h3{font-size:0.8em;}"); webpage += F("table{font-family:arial,sans-serif;font-size:0.9em;border-collapse:collapse;width:85%;}"); webpage += F("th,td {border:0.06em solid #dddddd;text-align:left;padding:0.3em;border-bottom:0.06em solid #dddddd;}"); webpage += F("tr:nth-child(odd) {background-color:#eeeeee;}"); webpage += F(".rcorners_n {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:20%;color:white;font-size:75%;}"); webpage += F(".rcorners_m {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:50%;color:white;font-size:75%;}"); webpage += F(".rcorners_w {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:70%;color:white;font-size:75%;}"); webpage += F(".column{float:left;width:50%;height:45%;}"); webpage += F(".row:after{content:'';display:table;clear:both;}"); webpage += F("*{box-sizing:border-box;}"); webpage += F("footer{background-color:#eedfff; text-align:center;padding:0.3em 0.3em;border-radius:0.375em;font-size:60%;}"); webpage += F("button{border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:20%;color:white;font-size:130%;}"); webpage += F(".buttons {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:15%;color:white;font-size:80%;}"); webpage += F(".buttonsm{border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:9%; color:white;font-size:70%;}"); webpage += F(".buttonm {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:15%;color:white;font-size:70%;}"); webpage += F(".buttonw {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:40%;color:white;font-size:70%;}"); webpage += F("a{font-size:75%;}"); webpage += F("p{font-size:75%;}"); webpage += F("</style></head><body><h1>File Server "); webpage += String(ServerVersion) + "</h1>"; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void append_page_footer(){ // Saves repeating many lines of code for HTML page footers webpage += F("<ul>"); webpage += F("<li><a href='/'>Home</a></li>"); // Lower Menu bar command entries webpage += F("<li><a href='/download'>Download</a></li>"); webpage += F("<li><a href='/upload'>Upload</a></li>"); //webpage += F("<li><a href='/stream'>Stream</a></li>"); webpage += F("<li><a href='/delete'>Delete</a></li>"); webpage += F("<li><a href='/dir'>Directory</a></li>"); webpage += F("<li><a href='/fs_read'>HomeFS</a></li>"); webpage += F("</ul>"); webpage += "<footer>Copy@right XuankyAutomation - Date 10 May 2021 - Email:[email protected]</footer>"; webpage += F("</body></html>"); } //--------------------------------------------------------------------------- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void SendHTML_Header(){ server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server.sendHeader("Pragma", "no-cache"); server.sendHeader("Expires", "-1"); server.setContentLength(CONTENT_LENGTH_UNKNOWN); server.send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. append_page_header(); server.sendContent(webpage); webpage = ""; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void SendHTML_Content(){ server.sendContent(webpage); webpage = ""; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void SendHTML_Stop(){ server.sendContent(""); server.client().stop(); // Stop is needed because no content length was sent } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void ReportSPIFFSNotPresent(){ SendHTML_Header(); webpage += F("<h3>No SPIFFS Card present</h3>"); webpage += F("<a href='/'>[Back]</a><br><br>"); append_page_footer(); SendHTML_Content(); SendHTML_Stop(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void ReportFileNotPresent(String target){ SendHTML_Header(); webpage += F("<h3>File does not exist</h3>"); webpage += F("<a href='/"); webpage += target + "'>[Back]</a><br><br>"; append_page_footer(); SendHTML_Content(); SendHTML_Stop(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void ReportCouldNotCreateFile(String target){ SendHTML_Header(); webpage += F("<h3>Could Not Create Uploaded File (write-protected?)</h3>"); webpage += F("<a href='/"); webpage += target + "'>[Back]</a><br><br>"; append_page_footer(); SendHTML_Content(); SendHTML_Stop(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void DownloadFile(String filename){ if (SPIFFS_present) { File download = Filesystem.open("/"+filename, "r"); if (download) { server.sendHeader("Content-Type", "text/text"); server.sendHeader("Content-Disposition", "attachment; filename="+filename); server.sendHeader("Connection", "close"); server.streamFile(download, "application/octet-stream"); download.close(); } else ReportFileNotPresent("download"); } else ReportSPIFFSNotPresent(); } //------------------------------------------------------------------------- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void SelectInput(String heading1, String command, String arg_calling_name){ SendHTML_Header(); webpage += F("<h3>"); webpage += heading1 + "</h3>"; webpage += F("<FORM action='/"); webpage += command + "' method='post'>"; // Must match the calling argument e.g. '/chart' calls '/chart' after selection but with arguments! webpage += F("<input type='text' name='"); webpage += arg_calling_name; webpage += F("' value=''><br>"); webpage += F("<type='submit' name='"); webpage += arg_calling_name; webpage += F("' value=''><br><br>"); webpage += F("<a href='/'>[Back]</a><br><br>"); append_page_footer(); SendHTML_Content(); SendHTML_Stop(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ String file_size(int bytes){ String fsize = ""; if (bytes < 1024) fsize = String(bytes)+" B"; else if(bytes < (1024*1024)) fsize = String(bytes/1024.0,3)+" KB"; else if(bytes < (1024*1024*1024)) fsize = String(bytes/1024.0/1024.0,3)+" MB"; else fsize = String(bytes/1024.0/1024.0/1024.0,3)+" GB"; return fsize; } //-------------------------------------------------------------------------- // All supporting functions from here... //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void HomePage(){ SendHTML_Header(); webpage += F("<a href='/download'><button>Download</button></a>"); webpage += F("<a href='/upload'><button>Upload</button></a>"); webpage += F("<a href='/stream'><button>Stream</button></a>"); webpage += F("<a href='/delete'><button>Delete</button></a>"); webpage += F("<a href='/dir'><button>Directory</button></a>"); webpage += F("<a href='/'><button>Home</button></a>"); append_page_footer(); SendHTML_Content(); SendHTML_Stop(); // Stop is needed because no content length was sent } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void File_Download(){ // This gets called twice, the first pass selects the input, the second pass then processes the command line arguments if (server.args() > 0 ) { // Arguments were received if (server.hasArg("download")) DownloadFile(server.arg(0)); } else SelectInput("Enter filename to download","download","download"); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void File_Upload(){ append_page_header(); webpage += F("<h3>Select File to Upload</h3>"); webpage += F("<FORM action='/fupload' method='post' enctype='multipart/form-data'>"); webpage += F("<input class='buttons' style='width:40%' type='file' name='fupload' id = 'fupload' value=''><br>"); webpage += F("<br><button class='buttons' style='width:10%' type='submit'>Upload File</button><br>"); webpage += F("<a href='/'>[Back]</a><br><br>"); append_page_footer(); server.send(200, "text/html",webpage); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ File UploadFile; void handleFileUploadFS(){ // upload a new file to the Filing system HTTPUpload& uploadfile = server.upload(); // See https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WebServer/srcv // For further information on 'status' structure, there are other reasons such as a failed transfer that could be used if(uploadfile.status == UPLOAD_FILE_START) { String filename = uploadfile.filename; if(!filename.startsWith("/")) filename = "/"+filename; //Serial.print("Upload File Name: "); Serial.println(filename); Filesystem.remove(filename); UploadFile = Filesystem.open(filename, "w"); } else if (uploadfile.status == UPLOAD_FILE_WRITE) { if(UploadFile) UploadFile.write(uploadfile.buf, uploadfile.currentSize); // Write the received bytes to the file } else if (uploadfile.status == UPLOAD_FILE_END) { if(UploadFile) // If the file was successfully created { UploadFile.close(); // Close the file again //Serial.print("Upload Size: "); Serial.println(uploadfile.totalSize); webpage = ""; append_page_header(); webpage += F("<h3>File was successfully uploaded</h3>"); webpage += F("<h2>Uploaded File Name: "); webpage += uploadfile.filename+"</h2>"; webpage += F("<h2>File Size: "); webpage += file_size(uploadfile.totalSize) + "</h2><br>"; append_page_footer(); server.send(200,"text/html",webpage); } else { ReportCouldNotCreateFile("upload"); } } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #ifdef ESP32 void printDirectory(const char * dirname, uint8_t levels){ unsigned int usedtotalbytes=0; String usedtotalsize, freesize; unsigned int freesizeint=0;int bytes; String Filename; File root = LITTLEFS.open(dirname); if(!root){ return; } if(!root.isDirectory()){ return; } File file = root.openNextFile(); while(file){ if (webpage.length() > 1000) { SendHTML_Content(); } if(file.isDirectory()){ webpage += "<tr><td>"+String(file.isDirectory()?"Dir":"File")+"</td><td>"+String(file.name())+"</td><td></td> <td></td><td></td> </tr>"; printDirectory(file.name(), levels-1); } else { Filename = String(file.name()); Filename = Filename.substring(1); webpage += "<tr><td>"+Filename+"</td>"; webpage += "<td>"+String(file.isDirectory()?"Dir":"File")+"</td>"; bytes = file.size(); String fsize = file_size(bytes); // ham chuyen doi webpage += "<td>"+fsize+"</td>"; webpage += "<td> <a href=/download?download="+Filename+">Download</a> </td>"; webpage += "<td> <a href=/delete?delete="+String(file.name())+">Delete</a> </td></tr>"; } file = root.openNextFile(); usedtotalbytes+= bytes; } file.close(); usedtotalsize =file_size(usedtotalbytes); // convert function freesizeint =1572864-usedtotalbytes; //1.5MB flash size freesize =file_size(freesizeint); webpage += "<tr> <td>Used Size</td> <td>"+String(usedtotalbytes*100/1572864)+"%</td> <td>"+usedtotalsize+ +"</td> <td>Free Size</td> <td>" + String(freesizeint*100/1572864)+"%"+"</td></tr>"; //Serial.println(String(totalsize)); } //----------- void SPIFFS_dir(){ if (SPIFFS_present) { File root = LITTLEFS.open("/"); if (root) { root.rewindDirectory(); SendHTML_Header(); webpage += F("<h3 class='rcorners_m'>SD Card Contents</h3><br>"); webpage += F("<table align='center'>"); webpage += F("<tr><th>Name/Type</th><th style='width:20%'>Type File/Dir</th><th>File Size</th> <th>Download</th><th>Delete</th></tr>"); printDirectory("/",0); webpage += F("</table>"); SendHTML_Content(); root.close(); } else { SendHTML_Header(); webpage += F("<h3>No Files Found</h3>"); } append_page_footer(); SendHTML_Content(); SendHTML_Stop(); // Stop is needed because no content length was sent } else ReportSPIFFSNotPresent(); } #endif //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #ifdef ESP8266 void SPIFFS_dir(){ String str; if (SPIFFS_present) { Dir dir = LittleFS.openDir("/"); SendHTML_Header(); webpage += F("<h3 class='rcorners_m'>SPIFFS Card Contents</h3><br>"); webpage += F("<table align='center'>"); webpage += F("<tr><th>Name/Type</th><th style='width:40%'>File Size</th> <th>Download</th><th>Delete</th></tr>"); while (dir.next()) { //Serial.print(dir.fileName()); webpage += "<tr><td>"+String(dir.fileName())+"</td>"; str = dir.fileName(); //str = substring(1);// (from)or (from,to) if(dir.fileSize()) { File f = dir.openFile("r"); //Serial.println(f.size()); int bytes = f.size(); String fsize = file_size(bytes); webpage += "<td>"+fsize+"</td>"; webpage += "<td> <a href=/download?download="+String(dir.fileName())+">Download</a> </td>"; webpage += "<td> <a href=/delete?delete="+String(dir.fileName())+">Delete</a> </td></tr>"; f.close(); } str += String(dir.fileSize()); str += "\r\n"; //Serial.println(str); } webpage += F("</table>"); SendHTML_Content(); append_page_footer(); SendHTML_Content(); SendHTML_Stop(); // Stop is needed because no content length was sent } else ReportSPIFFSNotPresent(); } #endif //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void SPIFFS_file_stream(String filename) { if (SPIFFS_present) { File dataFile = Filesystem.open("/"+filename, "r"); if (dataFile) { if (dataFile.available()) { // If data is available and present String dataType = "application/octet-stream"; if (server.streamFile(dataFile, dataType) != dataFile.size()) {Serial.print(F("Sent less data than expected!")); } } dataFile.close(); // close the file: } else ReportFileNotPresent("Cstream"); } else ReportSPIFFSNotPresent(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void File_Stream(){ if (server.args() > 0 ) { // Arguments were received if (server.hasArg("stream")) SPIFFS_file_stream(server.arg(0)); } else SelectInput("Enter a File to Stream","stream","stream"); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void SPIFFS_file_delete(String filename) { // Delete the file if (SPIFFS_present) { SendHTML_Header(); File dataFile = Filesystem.open("/"+filename, "r"); if (dataFile) { if (Filesystem.remove(filename)){ webpage += "<h3>File "+filename.substring(2)+ " has been erased</h3>"; webpage += F("<a href='/delete'>[Back]</a><br><br>"); } else { webpage += F("<h3>File was not deleted - error</h3>"); webpage += F("<a href='delete'>[Back]</a><br><br>"); } } else ReportFileNotPresent("delete"); append_page_footer(); SendHTML_Content(); SendHTML_Stop(); } else ReportSPIFFSNotPresent(); } void File_Delete(){ if (server.args() > 0 ) { // Arguments were received if (server.hasArg("delete")) SPIFFS_file_delete("/"+server.arg(0)); } else SelectInput("Select a File to Delete","delete","delete"); } //----------------------------------------------------------- // LOG DATA TO FPSFFS //--------------------------Writing SPIFFS ESP 32/ ESP8266
import { ActionMap, BotError, CallBackHandler, CommandHandler, MessageHandler } from './types'; import { unpackData, getFormattedSettingsMessage, getHiddenMessage, getMessageData, getValueFromMessageBody, getMessage, } from './helpers'; import * as services from './services'; import { ACTION, commandsList, MODE } from './constants'; import bot from './index'; import { startKeyboard, settingsKeyboard, addWordDialogKeyboard, sendWordKeyBoard, } from './helpers/keyboards'; export const sendEntireWord = async (telegramId: number) => { const { word, mode } = await services.getUserWords(telegramId); if (!word || !mode) throw new BotError('Sorry, you have no words at all'); const message = getMessage(word.word); await bot.sendMessage(telegramId, message, { parse_mode: 'HTML', reply_markup: sendWordKeyBoard(mode), }); }; export const showSettings = async (telegramId: number) => { const user = await services.getUser(telegramId); if (!user) return; const { mode, period, language } = user; const formattedSettings = getFormattedSettingsMessage('Current settings', { mode, period, language, }); await bot.sendMessage(telegramId, formattedSettings, { parse_mode: 'HTML', reply_markup: settingsKeyboard, }); }; const mapping: ActionMap = { [ACTION.DEFAULT]: async ({ button, value, hiddenValue, screen, user }) => { return getMessageData(button, value ? value : hiddenValue, screen, user); }, [ACTION.ADD_WORD]: async ({ button, value, hiddenValue, screen, user }) => { return getMessageData(button, value ? value : hiddenValue, screen, user); }, [ACTION.SET_LANGUAGE]: async ({ telegramId, value, button, hiddenValue, screen }) => { const updatedUser = await services.updateUser({ telegramId, language: value }); return getMessageData(button, value ? value : hiddenValue, screen, updatedUser); }, [ACTION.SET_MODE]: async ({ telegramId, value, button, hiddenValue, screen }) => { const updatedUser = await services.updateUser({ telegramId, mode: value }); return getMessageData(button, value ? value : hiddenValue, screen, updatedUser); }, [ACTION.SET_PERIOD]: async ({ telegramId, value, button, hiddenValue, screen }) => { const updatedUser = await services.updateUser({ telegramId, period: Number(value) }); return getMessageData(button, value ? value : hiddenValue, screen, updatedUser); }, [ACTION.ADD_WORD_CONFIRM]: async ({ telegramId, button, hiddenValue, screen, user }) => { const word = await services.addWord(hiddenValue, telegramId); const message = getMessage(word, `I added word "${word.text}" to your list\n`); return getMessageData(button, message, screen, user); }, [ACTION.ADD_WORD_TRANSLATE]: async ({ telegramId, button, hiddenValue, screen, user }) => { const translations = (await services.findTranslate(hiddenValue, telegramId)).join(','); const message = `Translations for word "${hiddenValue}" are here!!!`; return getMessageData(button, message, screen, user, translations); }, [ACTION.ADD_TRANSLATION_CONFIRM]: async ({ telegramId, button, value, screen, user }) => { const word = await services.addWord(value, telegramId); const message = getMessage(word, `I added word "${word.text}" to your list\n`); return getMessageData(button, message, screen, user); }, [ACTION.ADD_WORD_REFUSE]: async ({ value, button, hiddenValue, screen, user }) => { return getMessageData(button, value ? value : hiddenValue, screen, user); }, [ACTION.WORD_SHOW]: async ({ telegramId, button, screen, user }) => { const { word, mode } = await services.getUserWords(telegramId); if (!word || !mode) throw new BotError('Sorry, you have no words at all'); const message = getMessage(word.word); await services.updateUser({ telegramId, lastSendTime: true }); return getMessageData(button, message, screen, user); }, [ACTION.CHANGE_MODE]: async ({ telegramId, button, screen, user, value, hiddenValue }) => { const mode = user.mode === MODE.START ? MODE.STOP : MODE.START; const updatedUser = await services.updateUser({ telegramId, mode }); const word = await services.getWord(hiddenValue); if (!word) throw new BotError('There is no word!!!'); const message = getMessage(word); return getMessageData(button, message, screen, updatedUser); }, }; export const onCallbackQuery: CallBackHandler = async (query) => { const messageId = query.message?.message_id; const chatId = query.message?.chat.id; const { data, from: { id, first_name, username }, } = query; const user = await services.getUser(id); // TODO: remove user creation from this place await services.addUser(id, first_name, username); if (!messageId) throw new Error('There is no messageId!!!'); if (!data) throw new Error('There is no data!!!'); if (!user) throw new Error('There is no user!!!'); const { button, value, screen, action } = unpackData(data); const hiddenValue = query.message?.entities ? getValueFromMessageBody(query?.message?.entities[0]) : ''; const messageData = await mapping[action as ACTION]({ value, telegramId: id, hiddenValue, button, screen, user, }); try { await bot.editMessageText(messageData.message, { ...messageData.options, message_id: messageId, chat_id: chatId, }); } catch (error) { console.log('error in onCallbackQuery'); console.log(error); // TODO: do resend only if error appears because of the same word onCallbackQuery(query); } }; export const onStart: CommandHandler = async (msg) => { const { id, first_name, username } = msg.chat; await services.addUser(id, first_name, username); await bot.sendMessage(id, `Hello, ${msg.chat.username}`, { reply_markup: startKeyboard, }); }; export const onMessage: MessageHandler = async (msg) => { const text = msg.text; if (!text) throw new Error("I'm a little confused"); const isWordSkippable = commandsList.reduce((acc, item) => acc || item.command === text, false); if (isWordSkippable) return; const hiddenMessage = getHiddenMessage(text); const message = `${hiddenMessage}Add word "${text}" to your list`; await bot.sendMessage(msg.chat.id, message, { reply_markup: addWordDialogKeyboard, parse_mode: 'HTML', disable_web_page_preview: true, }); }; export const onTest: CommandHandler = (msg) => sendEntireWord(msg.chat.id); export const onSettings: CommandHandler = (msg) => showSettings(msg.chat.id);
import React, { FC } from "react"; import { UseFormRegisterReturn } from "react-hook-form"; type InputItem = { sr: string; placeholder: string; type: string; registerReturn: any; errors: string | undefined; key: string; }; const InputItemComponent: FC<InputItem> = (inputItem) => { return ( <div className="mb-1 last:mb-0" key={inputItem.key}> <label> <span className="sr-only">{inputItem.sr}</span> <input type={inputItem.type} placeholder={inputItem.placeholder} {...inputItem.registerReturn} className="outline rounded-md py-2 px-4 w-full" /> <p className="h-6">{inputItem.errors}</p> </label> </div> ); }; export default InputItemComponent;
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/mainColor_purple" tools:context=".ui.login.LoginActivity"> <ImageView android:id="@+id/iv_imageLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/image_welcome" android:src="@drawable/image_login_register" app:layout_constraintBottom_toTopOf="@+id/linearLayout" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/background_login_register" android:orientation="vertical" android:padding="40dp" app:layout_constraintBottom_toBottomOf="parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:minLines="2" android:text="Welcome\nBack" android:textColor="@color/black" android:textSize="20dp" android:textStyle="bold" /> <TextView android:id="@+id/tv_email_or_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="Email or Phone number" android:textColor="@color/black" android:textSize="15sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv_sign_to_started" /> <com.google.android.material.textfield.TextInputLayout android:id="@+id/textInputPhone" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv_email_or_phone"> <EditText android:id="@+id/et_emailPhone" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:autofillHints="phone" android:background="@drawable/background_button" android:backgroundTint="@color/background_textInput" android:inputType="text" android:textColor="@color/black" android:textStyle="bold" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:id="@+id/tv_password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="Password" android:textColor="@color/black" android:textSize="15sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textInputPhone" /> <com.google.android.material.textfield.TextInputLayout android:id="@+id/textInputPassword" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv_password" app:passwordToggleEnabled="true"> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:autofillHints="password" android:background="@drawable/background_button" android:backgroundTint="@color/background_textInput" android:inputType="textPassword" android:textColor="@color/black" android:textStyle="bold" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:id="@+id/tv_forgotPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end" android:text="Forgot Password?" android:textColor="@color/black" android:textSize="15sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv_sign_to_started" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/btnLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:background="@drawable/background_button" android:backgroundTint="@color/buttonColorYellow" android:text="Login" android:textAllCaps="false" android:textColor="@color/black" android:textStyle="bold" app:layout_constraintBottom_toTopOf="@+id/textView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> <TextView android:id="@+id/tvRegisterOption" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="10dp" android:layout_marginBottom="50dp" tools:text="Already have an account ? Log In" android:textSize="15dp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
<!DOCTYPE html> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="t" tagdir="/WEB-INF/tags" %> <t:generic_page title="Register/Login page"> <jsp:attribute name="body_area"> <div class="relativeContainer"> <div id="signup"> <h1 class="text-center margin-h20 clearfix">Sign up</h1> <form action="<c:url value="/register"/>" method="POST" class="box-center width40 fieldset-mt20"> <fieldset class="form-group"> <label for="nameinput">Name</label> <input type="text" class="form-control" id="nameinput" name="name" placeholder="Enter name" required /> </fieldset> <fieldset class="form-group"> <label for="surnameinput">Surname</label> <input type="text" class="form-control" id="surnameinput" name="surname" placeholder="Enter surname" /> </fieldset> <fieldset class="form-group"> <label for="emailinput">Email</label> <input type="email" class="form-control" id="emailinput" name="email" placeholder="Enter email" required /> </fieldset> <fieldset class="form-group"> <label for="usernameinput">Username</label> <input type="text" class="form-control" id="usernameinput" name="username" placeholder="Enter username" required /> </fieldset> <fieldset class="form-group"> <label for="passwordinput">Password</label> <input type="password" class="form-control" id="passwordinput" name="password" placeholder="Enter password" required /> </fieldset> <fieldset class="form-group"> <label for="passwordinput">Repeat Password</label> <input type="password" class="form-control" id="repeatpasswordinput" name="repeat-password" placeholder="Repeat password" required /> </fieldset> <span class="error-msg" id="error-signup-msg"></span> <button type="submit" class="btn btn-primary">Create my account</button> </form> </div> <div id="signin"> <h1 class="text-center margin-h20 clearfix">Sign in</h1> <form action="<c:url value="/login"/>" method="POST" class="box-center width40 fieldset-mt20"> ${error} <fieldset class="form-group"> <label for="usernameinput">Username</label> <input type="text" class="form-control" id="usernameinput" name="username" placeholder="Enter username" required /> </fieldset> <fieldset class="form-group"> <label for="passwordinput">Password</label> <input type="password" class="form-control" id="passwordinput" name="password" placeholder="Enter password" required /> </fieldset> <span class="error-msg" id="error-signin-msg"></span> <button type="submit" class="btn btn-primary">Sign In</button> <div class="navbar-right margin-t10 margin-r5"> <span>You don't have an account yet ?</span> <a href="#" id="signuplnk">Sign Up</a> </div> </form> </div> </div> </jsp:attribute> </t:generic_page>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>js是基于对象的,没得类的概念,所有要实现继承,需要使用js的原型prototype机制或者使用applay和call的方法</p> <p>子类通过prototype =父类,从而实现继承</p> <script> function Father(){ this.name="蒲大", this.age="32" } Father.prototype.getAge=function(){ return this.age } function Son(){ this.age=18 } Son.prototype=new Father() let son=new Son() console.log("儿子",son); console.log(son.name); //蒲大 console.log(son.age); //18 console.log(son.getAge()); //18 </script> </body> </html>
<!DOCTYPE html> <!-- This is a starter template page. Use this page to start your new project from scratch. This page gets rid of all links and provides the needed markup only. --> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ATLANTIC HOTEL</title> <link rel="icon" type="image/png" href="../assets/dist/img/logo-atl.png"> <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback"> <!-- Font Awesome Icons --> <link rel="stylesheet" href="../assets/plugins/fontawesome-free/css/all.min.css"> <!-- Theme style --> <link rel="stylesheet" href="../assets/dist/css/adminlte.min.css"> </head> <body class="hold-transition layout-top-nav layout-navbar-fixed"> <div class="wrapper"> <!-- Navbar --> <nav class="main-header navbar navbar-expand-md navbar-light navbar-white"> <div class="container"> <a href="" class="navbar-brand"> <img src="../assets/dist/img/logo-atl.png" alt="AdminLTE Logo" class="brand-image img-square" > <span class="brand-text font-weight-light">ATLANTIC HOTEL</span> </a> <button class="navbar-toggler order-1" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse order-3" id="navbarCollapse"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a href="index.php" class="nav-link">Dashboard</a> </li> <li class="nav-item"> <a href="pesanan.php" class="nav-link">Pesanan</a> </li> <li class="nav-item"> <a href="logout.php" class="nav-link">Logout</a> </li> </ul> </div> </div> </nav> <!-- /.navbar --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0">Data Pemesanan</h1> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> <!-- Main content --> <div class="content"> <div class="container"> <div class="col-md-12"> <div class="card card-outline card-info"> <div class="card-header"> <form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post"> <div class="form-group"> <label for="sel1">Cari:</label> <?php $kata_kunci=""; if (isset($_POST['kata_kunci'])) { $kata_kunci=$_POST['kata_kunci']; } ?> <input type="text" name="kata_kunci" value="<?php echo $kata_kunci;?>" /> <button type="submit" class="btn btn-info" > <i class="fa fa-search"></i> </button> </div> </form> </div> <div class="card-body"> <table class="table table-bordered"> <thead> <tr> <th style="width: 10px">NO.</th> <th>Nama Tamu</th> <th>Tanggal Check In</th> <th>Tanggal Check Out</th> <th>Jumlah Kamar</th> <th>Jenis Kamar</th> <th>Status</th> <th>Aksi</th> </tr> </thead> <tbody> <?php include '../koneksi.php'; if (isset($_POST['kata_kunci'])) { $kata_kunci=trim($_POST['kata_kunci']); $sql="select * from pesanan where nama_tamu like '%".$kata_kunci."%' or check_in like '%".$kata_kunci."%' or check_out like '%".$kata_kunci."%' order by nama_tamu desc"; }else { $sql="select * from pesanan order by nama_tamu desc"; } $no = 1; $data = mysqli_query($koneksi, $sql); while($d = mysqli_fetch_array($data)){ ?> <tr> <td><?php echo $no++; ?></td> <td><?php echo $d['nama_tamu']; ?></td> <td><?php echo $d['check_in']; ?></td> <td><?php echo $d['check_out']; ?></td> <td><?php echo $d['jml_kamar']; ?></td> <td> <?php $kamar = mysqli_query($koneksi, "select * from kamar"); while ($a = mysqli_fetch_array($kamar)) { if ($a['id_kamar'] == $d['id_kamar']) { ?> <?php echo $a['jenis_kamar']; ?> <?php } } ?> </td> <td> <?php if ($d['status'] == 1) { ?> <span class="badge bg-warning">Belum Di Konfirmasi</span> <?php } else { ?> <span class="badge bg-success">Sudah Di Konfirmasi</span> <?php } ?> </td> <td> <form action="aksi_konfirmasi.php" method="POST" > <input type="hidden" name="id_pesanan" value="<?php echo $d['id_pesanan']; ?>"> <input type="hidden" name="status" value="2"> <button class="btn btn-sm btn-info">Konfirmasi</button> </form> </br> <a href="cetak.php?id=<?php echo $d['id_pesanan']; ?>"><button class="btn btn-sm btn-dark">Cetak</button></a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div><!-- /.container-fluid --> </div> <!-- /.content --> </div> <!-- /.content-wrapper --> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Control sidebar content goes here --> </aside> <!-- /.control-sidebar --> </div> <!-- ./wrapper --> <!-- REQUIRED SCRIPTS --> <!-- jQuery --> <script src="../assets/plugins/jquery/jquery.min.js"></script> <!-- Bootstrap 4 --> <script src="../assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- AdminLTE App --> <script src="../assets/dist/js/adminlte.min.js"></script> </body> </html>
from datetime import datetime from odoo import models, fields, api, _ from odoo.exceptions import UserError from odoo.exceptions import ValidationError class RoomsAccommodationsAlfolk(models.Model): _name = 'folk.rooms.accommodations' _inherit = ["mail.thread", "mail.activity.mixin"] _rec_name = "room_id" room_id = fields.Many2one("folk.rooms", "Room", tracking=True, domain=[('status', '=', 'available')]) # floor_id = fields.Many2one("folk.floor", "Floor", store=True, string="Floor") # customer_id = fields.Many2one('res.partner', store=True, string="Customer Name", tracking=True) customer_name = fields.Many2one('res.partner', store=True, string="Customer Name", tracking=True) # check_in = fields.Date("Check In Date", store=True, tracking=True) # check_out = fields.Date("Check Out Date", store=True, tracking=True) bed_reserve_from = fields.Date("Reservation From", store=True, tracking=True, default=datetime.today()) bed_reserve_to = fields.Date("Reservation To", store=True, tracking=True, default=datetime.today()) responsible_id = fields.Many2one('hr.employee', store=True, tracking=True) status = fields.Selection([("available", "Available"), ("occupied", "Occupied")], "Status", default="available", compute="check_room_availability", tracking=True, ) # bed_ids = fields.Many2many('folk.beds', string="beds", store=True, tracking=True) bed_id = fields.Many2one('folk.beds', string="Bed", store=True, tracking=True) # @api.depends('bed_reserve_from', 'bed_reserve_to', 'bed_id') def check_room_availability(self): for bed in self: if bed.bed_reserve_from and bed.bed_reserve_to and bed.bed_id: self.status = "occupied" elif bed.bed_reserve_from and not bed.bed_reserve_to and bed.bed_id: self.status = "occupied" elif not bed.bed_reserve_from and not bed.bed_reserve_to and bed.bed_id: self.status = "available" @api.constrains('bed_reserve_from', 'bed_reserve_to') def check_in_out(self): for rec in self: if rec.bed_reserve_from and rec.bed_reserve_to: if rec.bed_reserve_to < rec.bed_reserve_from: raise ValidationError(_("Date Of Reservation From Must Be Before Date Of Reservation TO")) @api.constrains('bed_reserve_from', 'bed_reserve_to') def check_bed_availability(self): # search_bed = self.env['folk.rooms.accommodations'].search() for rec in self: if rec.bed_reserve_from and rec.bed_reserve_to and rec.bed_id: raise ValidationError(_("This Bed Is Occupied")) # @api.constrains('status') # def check_availability_bed(self): # for rec in self: # if rec.status == 'occupied': # raise ValidationError(_("Sorry! You Can Not Reserve This bed")) # record.description = "Test for partner %s" % record.partner_id.name
// // Created by Samuel Manchajm & Quentin Valakou on 18/05/2023. // #ifndef NF16_P23_2_TP4_H #define NF16_P23_2_TP4_H #define MAX 70 //Maximum de caractères pour un nom #define LONGLIGNE 300 // Maximum de caractères dans une ligne // Structures et types struct Position { int numeroLigne; int ordre; int numeroPhrase; struct Position *suivant; }; typedef struct Position T_Position; struct Noeud { char *mot; int nbOccurences; T_Position *listePositions; struct Noeud *filsGauche; struct Noeud *filsDroit; }; typedef struct Noeud T_Noeud; struct Index { T_Noeud *racine; int nbMotsDistincts; int nbMotsTotal; }; typedef struct Index T_Index; // Structures particulières pour les questions 6 et 7 // Création d'une double liste chainee composée de phrase avec une phrase composée de mots struct Mot { char *mot; struct Mot *suivant; int ordre; int ligne; }; typedef struct Mot T_Mot; struct Phrase { struct Mot *listeMot; struct Phrase *suivant; int indice; int nbMots; }; typedef struct Phrase T_Phrase; struct listePhrases { struct Phrase *listePhrase; int nbLignes; }; typedef struct listePhrases T_listePhrases; typedef struct LectureTexte { char* mot; struct LectureTexte* suivant; }T_LectureTexte; void afficherIndex(T_Index index); /* ******************************** * Fonctions principales ******************************** */ // Création et initialisation des structures T_Position *creerPosition(int numeroLigne, int ordre, int numeroPhrase); T_Noeud *creerNoeud(char *mot, int nbOccurences); T_Index *creerIndex(); // Ajout d'une position dans une liste de position T_Position *ajouterPosition(T_Position *listeP, int ligne, int ordre, int phrase); // Ajout d'une occurence dans l'arbre (ajout d'un noeud) int ajouterOccurence(T_Index *index, char *mot, int ligne, int ordre, int phrase); // Indexation de tous les mots du fichier int indexerFichier(T_Index *index, char *filename); // Affichage de tous les mots de l'index void afficherIndex(T_Index index); // Recherche d'un mot dans l'index T_Noeud* rechercherMot(T_Index *index, char* character); T_Noeud *rechercherMotOccurence(T_Index *index, char *mot); // Affichage de toutes les occurences d'un mot //void afficherOccurencesMot(T_Index *index, char *mot); void afficherOccurencesMot(T_Index *index, char *mot, T_listePhrases *texte); // Construction du texte à partir d'un index de type ABR //void construireTexte(T_Index *index, char *filename); void construireTexte(T_Index *index, char *filename, T_listePhrases *texte); /* ******************************** * Fonctions utilitaires ******************************** */ // Comparaison de deux mots int comparaison(int ligne1, int ordre1, int ligne2, int ordre2); void parcours_recherche(T_Noeud* noeud, char lettre, char* tab, int i); void parcours_affichage(T_Noeud* noeud, char lettre); // Fonctions d'indexations de la liste chainee T_listePhrases *indexerListe(T_Index *index); // DONE int parcoursABR(T_Noeud *noeud, T_listePhrases * liste); // DONE int ajouterPhraseMot(T_listePhrases *index, char *mot, int numPhrase, int ordre, int ligne); // DONE int ajouterMot(T_Phrase *phrase, char *mot, int ordre, int ligne); // DONE void menu(); void viderABR(T_Noeud *noeud); void viderIndex(T_Index *index); void viderListePhrases(T_listePhrases *listePhrases); #endif //NF16_P23_2_TP4_H
#include <SDL2/SDL.h> #include <stdio.h> #include <stdbool.h> // Screen dimensions const int SCREEN_WIDTH = 800; const int SCREEN_HEIGHT = 600; // Function declarations bool init(); void closeSDL(); void renderText(const char* message, SDL_Color color, int x, int y); // Global variables SDL_Window* gWindow = NULL; SDL_Renderer* gRenderer = NULL; SDL_Surface* gScreenSurface = NULL; SDL_Surface* gTextSurface = NULL; TTF_Font* gFont = NULL; // Initialize SDL bool init() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); return false; } gWindow = SDL_CreateWindow("CodeQuest: The C Adventure", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (gWindow == NULL) { printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); return false; } gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED); if (gRenderer == NULL) { printf("Renderer could not be created! SDL_Error: %s\n", SDL_GetError()); return false; } if (TTF_Init() == -1) { printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError()); return false; } gFont = TTF_OpenFont("path/to/your/font.ttf", 28); if (gFont == NULL) { printf("Failed to load font! SDL_ttf Error: %s\n", TTF_GetError()); return false; } return true; } // Clean up SDL void closeSDL() { TTF_CloseFont(gFont); gFont = NULL; SDL_DestroyRenderer(gRenderer); SDL_DestroyWindow(gWindow); gWindow = NULL; gRenderer = NULL; TTF_Quit(); SDL_Quit(); } // Render text to the screen void renderText(const char* message, SDL_Color color, int x, int y) { SDL_Surface* textSurface = TTF_RenderText_Solid(gFont, message, color); SDL_Texture* textTexture = SDL_CreateTextureFromSurface(gRenderer, textSurface); SDL_Rect renderQuad = { x, y, textSurface->w, textSurface->h }; SDL_RenderCopy(gRenderer, textTexture, NULL, &renderQuad); SDL_FreeSurface(textSurface); SDL_DestroyTexture(textTexture); } int main(int argc, char* args[]) { if (!init()) { printf("Failed to initialize!\n"); } else { bool quit = false; SDL_Event e; SDL_Color textColor = { 255, 255, 255 }; while (!quit) { while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { quit = true; } } SDL_SetRenderDrawColor(gRenderer, 0, 0, 0, 255); SDL_RenderClear(gRenderer); renderText("Welcome to CodeQuest: The C Adventure!", textColor, 50, 50); SDL_RenderPresent(gRenderer); } } closeSDL(); return 0; }
// Por qual motivo o código abaixo retorna com erros? { var cor = "preto"; const marca = "Fiat"; let portas = 4; console.log(cor, marca, portas); // * Tem que ficar no mesmo bloco ou escopo. } // Como corrigir o erro abaixo? const dois = 2; // * Como é usado em diferentes funções tem que ser uma variável global. function somarDois(x) { return x + dois; } function dividirDois(x) { return x / dois; } console.log(somarDois(4)); console.log(dividirDois(6)); // O que fazer para total retornar 500? const numero = 50; // * Foi mudado de var para const para ele não for pego no for. // * Mudado de var para let, que é o apropriado para usar em loops. for (let numero = 0; numero < 10; numero++) { console.log(numero); } const total = 10 * numero; console.log(total);
import 'package:animate_do/animate_do.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:carousel_slider/carousel_slider.dart'; import 'package:flutter/material.dart'; import 'package:movies123/core/network/end-points.dart'; import 'package:movies123/features/movies/presentation/controller/cubit/movies_cubit.dart'; class BuildNowPlayingMovies extends StatelessWidget { const BuildNowPlayingMovies({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Column( children: [ FadeIn( duration: const Duration(milliseconds: 3), child: CarouselSlider( options: CarouselOptions( height: 350.0, enableInfiniteScroll: true, //autoPlay: true, viewportFraction: 1.0, ), items: MoviesCubit.get(context).movies.map( (item) { return GestureDetector( key: const Key('openMovieMinimalDetail'), onTap: () { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => MovieDetailScreen(id: item.id),),); }, child: Stack( children: [ ShaderMask( shaderCallback: (rect) { return const LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ // fromLTRB Colors.transparent, Colors.black, Colors.black, Colors.transparent, ], stops: [0, 0.3, 0.5, 1], ).createShader( Rect.fromLTRB(0, 0, rect.width, rect.height), ); }, blendMode: BlendMode.dstIn, child: MoviesCubit.get(context).movies[0].backdropPath!=null ? CachedNetworkImage( height: 650.0, imageUrl: imageUrl(item.backdropPath!), fit: BoxFit.fill, ) : Image.asset('assets/images/person.png'), ), Align( alignment: Alignment.bottomCenter, child: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ Padding( padding: const EdgeInsets.only(bottom: 10.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon( Icons.circle, color: Colors.redAccent, size: 16.0, ), const SizedBox(width: 4.0), Text( 'Now Playing'.toUpperCase(), style: const TextStyle( fontSize: 16.0, color: Colors.white ), ), ], ), ), Text( item.title, textAlign: TextAlign.center, style: const TextStyle( fontSize: 24, color: Colors.white ), ), Padding( padding: const EdgeInsets.all(20.0), child: Text( item.overview, textAlign: TextAlign.justify, style: const TextStyle( fontSize: 10, color: Colors.white ), ), ), ], ), ), ], ), ); }, ).toList(), ), ), ], ); } }
import React, { FunctionComponent } from "react"; import SearchPanel from "./SearchPanel"; import List from "./List"; import useDebounce from "../../hooks/useDebounce"; import { Button, Typography } from "antd"; import { useProjects } from "../../hooks/apis/project"; import { useUser } from "../../hooks/apis/user"; import { useTitle } from "../../hooks/useTitle"; import { useUrlQueryParam } from "../../hooks/useUrlQueryParam"; import { Row } from "../../components/lib"; import { useProjectModal } from "../../hooks/useProjectModal"; export const apiUrl = process.env.REACT_APP_API_URL export interface Project{ id: number; pin: boolean; name: string; personId?: string; organization?: string; created?: number; } export interface Param{ name?: string; personId?: string; } interface OwnProps {} type Props = OwnProps; const ProjectList: FunctionComponent<Props> = () => { useTitle('项目列表') // 从url中获取query对象 const [ param, setParam ] = useUrlQueryParam(['name','personId']); const debParam = useDebounce(param,200); let { error, isError, isLoading, projectList} = useProjects(debParam); let { userList } = useUser(); const {open} = useProjectModal() return (<div style={{padding: '3.2rem',flex:1}}> <Row between={true}> <h1>项目列表</h1> <Button onClick={open}>创建项目</Button> </Row> <SearchPanel param={param} setParam={setParam} users={userList}/> {isError && <Typography.Text type={"danger"}>{error?.message}</Typography.Text>} {/* loading为Table组件上的属性,通过属性继承的方式将其映射到List组件上 */} <List loading={isLoading} users={userList} dataSource={projectList || []}/> </div>); }; export default ProjectList;
class ListsController < ApplicationController before_action :find_list, only:[:show, :edit, :destroy] def index @lists = List.all @list = List.new end def show @bookmark = Bookmark.new end def new # @list = List.new end def create @lists = List.all @list = List.new(list_params) if @list.save redirect_to lists_path else render 'index' end end def edit end def destroy @list.destroy redirect_to lists_path # redirect_to lists_path end private def find_list @list = List.find(params[:id]) end def list_params params.require(:list).permit(:name) end end
import React from "react"; class AddTask extends React.Component { state = { tasks: [ {id: 1, taskName: "Do the dishes", done: false, show : false}, {id: 2, taskName: "Do my homework", done: false, show : false}, {id: 3, taskName: "Go run errands", done: false, show : false}, {id: 4, taskName: "Go to the drogstore", done: false, show : false} ], anotherTask: " " } handleChange = (event) =>{ const value = event.currentTarget.value; this.setState({anotherTask : value}); } handleSubmit = (event) =>{ event.preventDefault(); const id = new Date().getTime(); const nextTask = this.state.anotherTask; const task = { id: id, taskName: nextTask, done: false, show: false }; //A copy of tasks -- tasks is a table const newTab = this.state.tasks.slice(); newTab.push(task); this.setState({tasks: newTab}); } render() { return ( <div className="add--task"> <h1>Your personal todo-list</h1> <form className="adding--box"> <input value = {this.state.anotherTask} type="text" placeholder="Add task here..." onChange = {this.handleChange} /> <button onChange = {this.handleSubmit} className="bg-color"> <i className ="fas fa-plus-circle"></i> </button> </form> </div> ) } } export default AddTask;
import { StringDict } from "../common"; import { ExtraField } from "./extras/extras"; import { Page } from "./page"; import type { Prediction } from "./prediction"; import { Product } from "./product"; /** * * @typeParam DocT an extension of a `Prediction`. Is generic by default to * allow for easier optional `PageT` generic typing. * @typeParam PageT an extension of a `DocT` (`Prediction`). Should only be set * if a document's pages have specific implementation. */ export abstract class Inference< DocT extends Prediction = Prediction, PageT extends DocT = DocT > { /** A boolean denoting whether a given inference result was rotated. */ isRotationApplied?: boolean; /** Name and version of a given product. */ product: Product; /** Wrapper for a document's pages prediction. */ pages: Page<PageT>[] = []; /** A document's top-level `Prediction`. */ prediction!: DocT; /** Extraneous fields relating to specific tools for some APIs. */ extras?: ExtraField[] = []; /** Name of a document's endpoint. Has a default value for OTS APIs. */ endpointName?: string; /** A document's version. Has a default value for OTS APIs. */ endpointVersion?: string; constructor(rawPrediction: StringDict) { this.isRotationApplied = rawPrediction?.is_rotation_applied ?? undefined; this.product = rawPrediction?.product; } /** * Default string representation. */ toString() { let pages = ""; if (this.pages.toString().length > 0) { pages = ` Page Predictions ${this.pages.map((e: Page<PageT>) => e.toString() || "").join("\n")}`; } return `Inference ######### :Product: ${this.product.name} v${this.product.version} :Rotation applied: ${this.isRotationApplied ? "Yes" : "No"} Prediction ========== ${this.prediction.toString().length === 0 ? "" : this.prediction.toString() + "\n"}${pages}`; } /** * Takes in an input string and replaces line breaks with `\n`. * @param outStr string to cleanup * @returns cleaned out string */ static cleanOutString(outStr: string): string { const lines = / \n/gm; return outStr.replace(lines, "\n"); } } /** * Factory to allow for static-like property access syntax in TypeScript. * Used to retrieve endpoint data for standard products. */ export class InferenceFactory { /** * Builds a blank product of the given type & sends back the endpointName & endpointVersion parameters of OTS classes. * Note: this is needed to avoid passing anything other than the class of the object to the parse()/enqueue() call. * @param inferenceClass Class of the product we are using * @returns {Inference} An empty instance of a given product. */ public static getEndpoint<T extends Inference>( inferenceClass: new (httpResponse: StringDict) => T ): [string, string] { if (inferenceClass.name === "CustomV1") { throw new Error( "Cannot process custom endpoint as OTS API endpoints. Please provide an endpoint name & version manually." ); } const emptyProduct = new inferenceClass({ prediction: {}, pages: [], }) as T; if ( !emptyProduct.endpointName || !emptyProduct.endpointVersion || emptyProduct.endpointName.length === 0 || emptyProduct.endpointVersion.length === 0 ) { throw new Error( `Error during endpoint verification, no endpoint found for product ${inferenceClass.name}.` ); } return [emptyProduct.endpointName, emptyProduct.endpointVersion]; } }
require('dotenv').config() const express = require('express') const cors = require('cors') const app = express() app.use(cors()); app.use(express.json()) const userRouter = require('./routes/use.routes') app.get('/', (req, res) => { res.send('Hello World!'); }); const socketIo = require('socket.io') const http = require('http'); const server = http.createServer(app) const io = socketIo(server, { cors: { origin: 'http://localhost:3000', methods: ['Get', 'POST'] }, }); io.on('connection', (socket) => { console.log(`user with ${socket.id} connected`) socket.on('disconnect', () => { console.log(`user with ${socket.id} disconnected`) }) socket.on('join', (data) => { socket.join(data) console.log(`user with ${socket.id} join room in room ${data}`) }) socket.on('sendMessage', (data) => { socket.to(data.room).emit('getMessage', data) }) }) const start = (port) => { server.listen(port, () => console.log(`hello from server on ${port}`)) } module.exports = { start, app }
import matchSorter from 'match-sorter'; import { Column, FilterValue, Hooks, IdType, Row, useFilters, useFlexLayout, useGlobalFilter, useResizeColumns, useRowSelect, useSortBy, useTable } from 'react-table'; import { ProjectData } from '../../types'; import React, { useCallback, useContext, useEffect, useMemo } from 'react'; import { DefaultColumnFilter, extraColumns } from './columns'; import MaUTable from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import { Rows } from './Rows'; import { ProjectDataContext } from '../../containers/Root'; import { Popups } from './Popups'; import { TableHead } from '../../common/TableHead'; import { PageBar } from '../../common/PageBar'; import { ScanState } from '../../hooks/useScan'; import { useHistory } from 'react-router'; import { ProjectStatus } from '../../types/Project'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import { animated, useSpring } from 'react-spring'; import PauseIcon from '@material-ui/icons/Pause'; import PlayArrowIcon from '@material-ui/icons/PlayArrow'; import RefreshIcon from '@material-ui/icons/Refresh'; import DeleteForeverIcon from '@material-ui/icons/DeleteForever'; import Brightness7Icon from '@material-ui/icons/Brightness7'; import Brightness4Icon from '@material-ui/icons/Brightness4'; import DeleteIcon from '@material-ui/icons/Delete'; import { Toolbar } from '../../common/Toolbar'; function fuzzyTextFilterFn( rows: Row<ProjectData>[], id: IdType<any>, filterValue: FilterValue ) { return matchSorter(rows, filterValue, { keys: [row => row.values[id]] }); } interface TableProps { columns: Array<Column<ProjectData>>; onDeleteRow: (project: ProjectData) => void; onDeleteProjects: (projects: ProjectData[]) => void; } export function Table({ columns, onDeleteRow, onDeleteProjects }: TableProps) { const { projects = [], foldersScanned, stopScan, state: { scanning }, toggleDarkMode, pauseScan, resetScan, resumeScan, darkMode } = useContext(ProjectDataContext); const finished = scanning === ScanState.Finished; const props = useSpring({ foldersScanned }); const activeProjects = useMemo( () => projects.filter( project => project.status !== ProjectStatus.Deleted ), [projects] ); const deletedProjects = useMemo( () => projects.filter( project => project.status === ProjectStatus.Deleted ), [projects] ); const loading = scanning === ScanState.Loading; const history = useHistory(); function cancelScan() { stopScan(); history.push('/home'); } function deleteAll() { if (!activeProjects?.length) { return; } onDeleteProjects(activeProjects); } const toggleScan = useCallback(() => { if (loading) { pauseScan(); return; } resumeScan(); }, [loading, pauseScan, resetScan]); const filterTypes = React.useMemo( () => ({ // Add a new fuzzyTextFilterFn filter type. fuzzyText: fuzzyTextFilterFn, // Or, override the default text filter to use // "startWith" text: ( rows: Array<Row<ProjectData>>, id: IdType<string>, filterValue: FilterValue ) => { return rows.filter(row => { const rowValue = row.values[id]; return rowValue !== undefined ? String(rowValue) .toLowerCase() .startsWith(String(filterValue).toLowerCase()) : true; }); } }), [] ); const defaultColumn = useMemo( () => ({ width: 150, minWidth: 150, Filter: DefaultColumnFilter, maxWidth: 400 }), [] ); const defaultSortBy = useMemo( () => [ { id: 'size', desc: false } ], [] ); // Use the state and functions returned from useTable to build your UI // @ts-ignore let { getTableProps, headerGroups, rows, preGlobalFilteredRows, setGlobalFilter, toggleAllRowsSelected, prepareRow, isAllRowsSelected, toggleRowSelected, selectedFlatRows, state: { selectedRowIds, globalFilter } } = useTable( { autoResetSelectedRows: false, autoResetSortBy: false, autoResetGlobalFilter: false, autoResetFilters: false, columns, filterTypes, initialState: { sortBy: defaultSortBy }, getRowId: React.useCallback(row => row.path, []), defaultColumn, data: activeProjects }, useFilters, useGlobalFilter, useFlexLayout, useSortBy, useResizeColumns, useRowSelect, (hooks: Hooks<ProjectData>) => extraColumns({ hooks, onDeleteRow }) ); // when we delete stuff, we want to reset all selected state. useEffect(() => { if (!deletedProjects.length) { return; } toggleAllRowsSelected(!deletedProjects.length); }, [deletedProjects]); function handleDeleteSelected() { onDeleteProjects( selectedFlatRows.map((row: Row<ProjectData>) => row.original) ); } const onResetScan = useCallback(() => { toggleAllRowsSelected(false); resetScan(); }, [resetScan, toggleAllRowsSelected]); const subtitle = useMemo( () => ( <span> Scanned {finished ? ' total of ' : ''} <animated.span> {props.foldersScanned.interpolate(x => parseInt(x).toLocaleString() )} </animated.span>{' '} folders {finished ? '' : ' so far...'} </span> ), [finished, props] ); // Render the UI for your table return ( <> <PageBar loading={loading} title={scanning ? 'Scanning' : 'Node Cleaner'} subtitle={subtitle} > <Tooltip title={'Back'}> <IconButton edge="start" aria-label="delete selected" onClick={cancelScan} > <ArrowBackIcon /> </IconButton> </Tooltip> {!finished && ( <Tooltip title={loading ? 'Pause' : 'Resume'}> <IconButton onClick={toggleScan}> {loading ? <PauseIcon /> : <PlayArrowIcon />} </IconButton> </Tooltip> )} <Tooltip title={'Rescan'}> <IconButton onClick={onResetScan}> <RefreshIcon /> </IconButton> </Tooltip> <Tooltip title={loading ? 'Scanning' : 'Delete All'}> <span> <IconButton disabled={!projects.length || loading} aria-label="delete selected" onClick={deleteAll} > <DeleteForeverIcon /> </IconButton> </span> </Tooltip> <Tooltip title={'Toggle Light/Dark Theme'}> <IconButton onClick={toggleDarkMode}> {darkMode ? <Brightness7Icon /> : <Brightness4Icon />} </IconButton> </Tooltip> </PageBar> <Toolbar preGlobalFilteredRows={preGlobalFilteredRows} globalFilter={globalFilter} projects={projects} setGlobalFilter={setGlobalFilter} selectedFlatRows={selectedFlatRows} selectedRowIds={selectedRowIds} > <Tooltip title="Delete Selected"> <IconButton aria-label="delete selected" onClick={handleDeleteSelected} > <DeleteIcon /> </IconButton> </Tooltip> </Toolbar> <MaUTable component="div" {...getTableProps()}> <TableHead headerGroups={headerGroups} /> <TableBody component="div"> <Rows isAllRowsSelected={isAllRowsSelected} toggleAllRowsSelected={toggleAllRowsSelected} rows={rows} toggleRowSelected={toggleRowSelected} prepareRow={prepareRow} /> </TableBody> </MaUTable> {!!projects.length && ( <Popups toggleAllRowsSelected={toggleAllRowsSelected} /> )} </> ); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>All About Module Pattern</title> </head> <body> <header id="target"></header> <script> // Module pattern is easy to use and creates encapsulation of code, used mostly as singleton style objects whhere only one instancce exists // Module Patterns is good for Services and Teesting/TDD // Creating a Module, using IIFE: (function() { "use strict"; console.log("Inside IIFE Pattern Module"); })(); // Exporting module, basically assigns module to a variable that we can later on call to use modules method through that variable let myModule = (function() { function sayHello() { console.log("Saying Hello from module"); } return { sayHello, publicMethod: function() {console.log("Hello again from IIFE");} } // exposing sayHello() to code outside our module, which becomes a public method })(); myModule.sayHello(); myModule.publicMethod(); // Private Methods and Properties, JavaScript doesn't have a private keyword but using Closures we can create private methods and properties/private state: myModule = (function() { "use strict"; let _privateProperty = "This is Private Property"; function _privateMethod() { console.log(_privateProperty); } return { publicMethod: function() { _privateMethod(); } } })(); myModule.publicMethod(); // outputs correctly as expected // myModule._privateMethod(); // not accessible for Closures // as our private methods are not returned they are not accesible outside of this module, only our public methods has given access to access our private methods or properties if needed be // that gives us ability to craete and keep private state, encapsulation within code, please notice that private methods are using a "_" as a naming convention for it to be identified easily // Revealing Module Pattern, it's one of most popular ways of creating modules, using return statement we can return an object literl that reveals only methods or properties that needs to be available publicly myModule = (function() { "use strict"; let _privateProperty = "Private Property"; let publicProperty = "Public Property"; function _privateMethod() {console.log(_privateProperty);} function publicMethod() {_privateMethod();} return { publicMethod: publicMethod, publicProperty: publicProperty }; })(); myModule.publicMethod(); console.log("<>",myModule.publicProperty); // myModule._privateMethod(); // protected by module closure console.log(myModule._privateProperty) // protected by module closure // benefits to Revealing Module Pattern is that we can look at bottom of our modules and quickly see what is publicly available for use // More on Module Pattern, modulee is created mostly as an IIFE with a function inside: let someModule = ( function() {} )(); // everything with that said function is bound to that module and accessible to them only, module also emulates "private", "public" by creating metioned scope and exposing thhose things tat are declared internally within module // Private functions are memebers of given entity that can be seen only within said entity, whereas Public one's can be seen from outside given entity let formatter = ( function() { let log = msg => console.log([Date.now()], msg); } )(); // as you can see formatter.log(..) isn't accessible from outside that module, beecause our module doesn;t return anything, and that's why returning "undfined" // formatter.log("Hello"); // accessing a module is actually accessing whatever it returns, log function can be treated as a private function, and can be accessed within module formatter = ( function() { let log = msg => console.log([Date.now()], msg); let makeUppercase = text => text.toUpperCase(); } )(); // thats just another privatee method that doesn;t have access outside of module, thus appear exposing a module // Expose a module, by returning an object literal with intended properties and methods in it formatter = ( function() { let log = msg => console.log([Date.now()], msg); let makeUppercase = text => text.toUpperCase(); let makingLowercase = text => { log("making lowercase"); return text.toLowerCase(); } return { makeUppercase, makingLowercase }; } )(); console.log(formatter.makeUppercase("dothis")); console.log(formatter.makingLowercase(formatter.makeUppercase("dothis"))); // Modules can house not only functions but arrays, objects and primitives as well: formatter = ( function() { let timesRun = 0; let setTimesRun = () => { log("Setting times run ...."); // ++timesRun; return ++timesRun; } let log = msg => console.log([Date.now()], msg); let makeUppercase = text => text.toUpperCase(); let makingLowercase = text => { log("making lowercase"); return text.toLowerCase(); } return { makeUppercase, makingLowercase, timesRun, // setTimesRun setTimesRun }; } )(); console.log(formatter.makingLowercase("WHATNOW")); console.log(formatter.timesRun); // 0, can be overritten from outsidde as it's publicly exposed formatter.timesRun = 11; console.log(formatter.timesRun); console.log(formatter.setTimesRun()) // things that are exposed publicy can be changed deliberately and it's one of it's drawbacks // reference types works differently, you can define it and will be poppulated as you go: formatter = ( function() { let timesRun = []; let log = msg => console.log([Date.now()], msg); let makeUppercase = text => { log("Making Uppercase"); timesRun.push(null); return text.toUpperCase(); } let makingLowercase = text => { log("making lowercase"); return text.toLowerCase(); } return { makeUppercase, makingLowercase, timesRun, }; } )(); console.log(formatter.makeUppercase("dothis")); console.log(formatter.makeUppercase("dothis")); console.log(formatter.timesRun); // Declaring Module Dependencies, modules are mostly closed entities but sometimes you might need to work with DOM obbject, to achieve that module may have dependencies: formatter = ( function() { let timesRun = []; let log = msg => console.log([Date.now()], msg); let makeUppercase = text => { log("Making Uppercase"); timesRun.push(null); return text.toUpperCase(); } let makingLowercase = text => { log("making lowercase"); return text.toLowerCase(); } let writeToDom = (selector, message) => { // document.querySelector(selector).innerHTML = message; } return { makeUppercase, makingLowercase, timesRun, writeToDom }; } )(); formatter.writeToDom("#target", "Wassup Wassup"); // document is available only when DOM is accessible, running that on a server would produce an error, how to avoid that from happening, solution check first if document exists or not formatter.writeToDom = (selector, message) => { if(!!document && "querySelector" in document) { document.querySelector(selector).innerHTML = message; } } formatter.writeToDom("#target", "Ohh Yeah"); // but we can do better, by decalring our modules dependencies and inject them as we go: formatter = ( function(doc) { let timesRun = []; let log = msg => console.log([Date.now()], msg); let makeUppercase = text => { log("Making Uppercase"); timesRun.push(null); return text.toUpperCase(); } let makingLowercase = text => { log("making lowercase"); return text.toLowerCase(); } let writeToDom = (selector, message) => { if(!!doc && "querySelector" in doc) { doc.querySelector(selector).innerHTML = message; } } return { makeUppercase, makingLowercase, timesRun, writeToDom }; } )(document); // now it doesn't shadow, it's declaring dependencies as it calling module's IIFE, no chance of breaking formatter.writeToDom("#target", "what now"); // let's test with a document mock: let documentMock = (() => ({ querySelector: (selector) => ({ innerHTML: null }), }))(); formatter = ( function(doc) { let timesRun = []; let log = msg => console.log([Date.now()], msg); let makeUppercase = text => { log("Making Uppercase"); timesRun.push(null); return text.toUpperCase(); } let makingLowercase = text => { log("making lowercase"); return text.toLowerCase(); } let writeToDom = (selector, message) => { doc.querySelector(selector).innerHTML = message; } return { makeUppercase, makingLowercase, timesRun, writeToDom }; } )(document || documentMock); // even if you dont put in an extra conditional checkin with this, it'll run smoothly as we are providing dependenciees and spares as well to be safe </script> </body> </html>
-------------------------------------------------------------------------------- -- Event_Filter Component Implementation Spec -------------------------------------------------------------------------------- -- Includes: with Event; with Command; with Event_Filter_Entry; with Event_Filter_Entry_Enums; with Protected_Variables; -- The Event Filter component is used to filter out event IDs from leaving the system. The component takes in a range of IDs package Component.Event_Filter.Implementation is use Event_Filter_Entry_Enums; -- The component class instance record: type Instance is new Event_Filter.Base_Instance with private; -------------------------------------------------- -- Subprogram for implementation init method: -------------------------------------------------- -- -- Init Parameters: -- event_Id_Start_Range : Event_Types.Event_Id - The event ID that begins the range of ids that the component will include for filtering of events. -- event_Id_End_Range : Event_Types.Event_Id - The event ID that ends the range of ids that the component will include for filtering of events. -- event_Filter_List : Event_Filter_Entry.Event_Id_List - A list of event IDs that are filtered by default -- overriding procedure Init (Self : in out Instance; Event_Id_Start_Range : in Event_Types.Event_Id; Event_Id_End_Range : in Event_Types.Event_Id; Event_Filter_List : in Event_Filter_Entry.Event_Id_List := (1 .. 0 => 0)); private -- Protected boolean for sending the state packet package Protected_Boolean is new Protected_Variables.Generic_Variable (Boolean); protected type Protected_Event_Filter_Entries is -- Procedures requiring full mutual exclusion: -- This package is used only with this component and is wrapped as a protected object to protect the manipulation of entry data for each ID on its filtered state. procedure Init (Event_Id_Start : in Event_Types.Event_Id; Event_Id_Stop : in Event_Types.Event_Id; Event_Filter_List : in Event_Filter_Entry.Event_Id_List); procedure Destroy; -- Procedure to set the filter state by command. procedure Set_Filter_State (Id : in Event_Types.Event_Id; New_State : in Event_Filter_State.E; Status : out Event_Filter_Entry.Event_Entry_Status); -- Procedure to determine if the event needs to be filtered and if so, reports that to the component for further handling. procedure Filter_Event (Id : in Event_Types.Event_Id; Status : out Event_Filter_Entry.Filter_Status); -- Procedure to set the global state of the component for filtering or not. procedure Set_Global_Enable_State (New_Global_State : in Global_Filter_State.E); -- Procedure to get the global state of the component. function Get_Global_Enable_State return Global_Filter_State.E; -- Getters for filtered and unfiltered counts function Get_Event_Filtered_Count return Unsigned_32; function Get_Event_Unfiltered_Count return Unsigned_32; -- Getter for maintaining the known range of IDs for the component to filter function Get_Event_Start_Stop_Range (Event_Stop_Id : out Event_Types.Event_Id) return Event_Types.Event_Id; -- Function to get the entry state array for packetizing function Get_Entry_Array return Basic_Types.Byte_Array_Access; private Event_Filter_Package : Event_Filter_Entry.Instance; end Protected_Event_Filter_Entries; -- The component class instance record: type Instance is new Event_Filter.Base_Instance with record Event_Entries : Protected_Event_Filter_Entries; -- Packet variables for sending the state packet Send_Event_State_Packet : Protected_Boolean.Variable; -- Event Filter count for lifetime of component. Tracked in the package, and a copy is stored here so that we dont send the data product if we dont have to Total_Event_Filtered_Count : Unsigned_32 := Unsigned_32'First; -- Event unfiltered count for lifetime of component. Tracked in the package, and a copy is stored here so that we dont send the data product if we dont have to. Does not include invalid id counts. Total_Event_Unfiltered_Count : Unsigned_32 := Unsigned_32'First; end record; --------------------------------------- -- Set Up Procedure --------------------------------------- -- Null method which can be implemented to provide some component -- set up code. This method is generally called by the assembly -- main.adb after all component initialization and tasks have been started. -- Some activities need to only be run once at startup, but cannot be run -- safely until everything is up and running, ie. command registration, initial -- data product updates. This procedure should be implemented to do these things -- if necessary. overriding procedure Set_Up (Self : in out Instance); --------------------------------------- -- Invokee connector primitives: --------------------------------------- -- This is the base tick for the component. Upon reception the component will record the number of events that have been filtered and send the state packet if it was requested. overriding procedure Tick_T_Recv_Sync (Self : in out Instance; Arg : in Tick.T); -- Events are received synchronously on this connector and are passed along or filtered. overriding procedure Event_T_Recv_Sync (Self : in out Instance; Arg : in Event.T); -- This is the command receive connector. overriding procedure Command_T_Recv_Sync (Self : in out Instance; Arg : in Command.T); --------------------------------------- -- Invoker connector primitives: --------------------------------------- -- This procedure is called when a Event_Forward_T_Send message is dropped due to a full queue. overriding procedure Event_Forward_T_Send_Dropped (Self : in out Instance; Arg : in Event.T) is null; -- This procedure is called when a Event_T_Send message is dropped due to a full queue. overriding procedure Event_T_Send_Dropped (Self : in out Instance; Arg : in Event.T) is null; -- This procedure is called when a Command_Response_T_Send message is dropped due to a full queue. overriding procedure Command_Response_T_Send_Dropped (Self : in out Instance; Arg : in Command_Response.T) is null; -- This procedure is called when a Data_Product_T_Send message is dropped due to a full queue. overriding procedure Data_Product_T_Send_Dropped (Self : in out Instance; Arg : in Data_Product.T) is null; -- This procedure is called when a Packet_T_Send message is dropped due to a full queue. overriding procedure Packet_T_Send_Dropped (Self : in out Instance; Arg : in Packet.T) is null; ----------------------------------------------- -- Command handler primitives: ----------------------------------------------- -- Description: -- These are the commands for the event filter component. -- Enable the event filter for a specific event ID. overriding function Filter_Event (Self : in out Instance; Arg : in Event_Filter_Single_Event_Cmd_Type.T) return Command_Execution_Status.E; -- Disable the event filter for a specific event ID. overriding function Unfilter_Event (Self : in out Instance; Arg : in Event_Filter_Single_Event_Cmd_Type.T) return Command_Execution_Status.E; -- Enable the event filtering for a specific range of event IDs. overriding function Filter_Event_Range (Self : in out Instance; Arg : in Event_Filter_Id_Range.T) return Command_Execution_Status.E; -- Disable the event filtering for a specific range of event IDs. overriding function Unfilter_Event_Range (Self : in out Instance; Arg : in Event_Filter_Id_Range.T) return Command_Execution_Status.E; -- Enable the component to filter events that have been set to be filtered. overriding function Enable_Event_Filtering (Self : in out Instance) return Command_Execution_Status.E; -- Disable the component so that all events will not be filtered. The event states will be maintained for when re-enabled. overriding function Disable_Event_Filtering (Self : in out Instance) return Command_Execution_Status.E; -- Dump a packet for the state of all events pertaining to if they are filtered or not. overriding function Dump_Event_States (Self : in out Instance) return Command_Execution_Status.E; -- Invalid command handler. This procedure is called when a command's arguments are found to be invalid: overriding procedure Invalid_Command (Self : in out Instance; Cmd : in Command.T; Errant_Field_Number : in Unsigned_32; Errant_Field : in Basic_Types.Poly_Type); end Component.Event_Filter.Implementation;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>浏览器调用视频与音频</title> <style> #c1 { border: 1px solid black; } </style> </head> <body>我要在这里获取浏览器的摄像头 <video id="v1" width="800px" height="600px"></video> <button type="button" id="btn1" onclick="takePhoto()">拍照</button> <canvas width="800px" height="600px" id="c1" style="display:none"></canvas> <img src="" id="img1" width="800px" height="600px"> </body> <script> var v1 = document.querySelector("#v1"); var c1 = document.querySelector("#c1"); var img1 = document.querySelector("#img1"); //我们在这里要根据不同的浏览器去调用不同的方法 navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; navigator.getMedia({ video: true, //使用摄像头对象 audio: false //不使用音频 }, function (stream) { //去年11月的时候 // v1.src=URL.createObjectURL(stream); 去年11月都还是这么写 //获取成功以后 v1.srcObject = stream; //新的方法 v1.play(); }, function (err) { //获取失败以后 console.log(err); }); function takePhoto() { //console.log(c1); var ctx = c1.getContext("2d"); //画一个图片,在这里,我们是直接从视频里面进行了截图 ctx.drawImage(v1, 0, 0, 800, 600); //把canvas里面的图片转换成base64格式 img1.src = c1.toDataURL("image/jpeg"); } </script> </html>
package by.framework.lab4; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import javax.swing.JPanel; @SuppressWarnings("serial") public class PaintPanel extends JPanel { private ArrayList<GraphicPoint> points; private double scaleX; private double scaleY; private boolean showAxis = true; private boolean showMarkers = true; private boolean rotate = false; private boolean findSq = false; private boolean showMarkedPoints = false; private BasicStroke graphicsStroke; private BasicStroke axisStroke; private BasicStroke markerStroke; private Font axisFont; private BasicStroke sqStroke; private Font sqFont; private AffineTransform transform; private double minX, maxX, minY, maxY; private double dx = 0, dy = 0; PaintPanel() { setBackground(Color.GRAY); float[] dash2 = {20, 5, 5, 5, 5, 5, 10, 5, 10, 5}; graphicsStroke = new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10f, dash2, 0f); axisStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, null, 0.0f); markerStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, null, 0.0f); axisFont = new Font("Serif", Font.BOLD, 14); sqStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, null, 0.0f); axisFont = new Font("Serif", Font.PLAIN, 12); } public void paintGraphic(ArrayList<GraphicPoint> points) { this.points = null; this.points = points; repaint(); } public void setShowAxis(boolean show) { showAxis = show; repaint(); } public void setShowMarkers(boolean show) { this.showMarkers = show; repaint(); } public void setRotate(boolean rotate) { this.rotate = rotate; repaint(); } public void setFindSq(boolean find) { this.findSq = find; repaint(); } public void setShowMarkedPoints(boolean show) { this.showMarkedPoints = show; repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); if(points == null || points.isEmpty()) return; Graphics2D canvas = (Graphics2D) g; Stroke oldStroke = canvas.getStroke(); Color oldColor = canvas.getColor(); Paint oldPaint = canvas.getPaint(); Font oldFont = canvas.getFont(); maxX = points.get(points.size()-1).getX(); minX = points.get(0).getX(); maxY = points.get(0).getY(); minY = points.get(0).getY(); for(int i = 1; i < points.size(); i++) { if(minY > points.get(i).getY()) minY = points.get(i).getY(); if(maxY < points.get(i).getY()) maxY = points.get(i).getY(); } scaleX = getSize().getWidth()/(maxX - minX); scaleY = getSize().getHeight()/(maxY - minY); System.out.println(getSize().getWidth() + " " + getSize().getHeight()); System.out.println(this.getSize().getWidth() + " " + this.getSize().getHeight()); dx = 0; dy = 0; if(rotate) { double X = getSize().getWidth()/2.0; double Y = getSize().getHeight()/2.0; scaleX = getSize().getHeight()/(maxX - minX); scaleY = getSize().getWidth()/(maxY - minY); double angle = -Math.PI/2.; dx = (Y - X) / scaleX; dy = (X - Y) / scaleY; if(transform == null) { transform = canvas.getTransform(); } // transform.translate(X, Y); // transform.rotate(angle); // transform.translate(-X, -Y); // canvas.setTransform(transform); // transform.translate(X, Y); // transform.rotate(3*angle); // transform.translate(-X, -Y); canvas.rotate(angle, X, Y); } else { // if(transform == null) transform = canvas.getTransform(); // transform.rotate(0); // canvas.setTransform(transform); } System.out.println(); if(showAxis) paintAxis(canvas); printGraphic(canvas); if(findSq) paintSq(canvas); if(showMarkers) paintMarkers(canvas); canvas.setFont(oldFont); canvas.setPaint(oldPaint); canvas.setColor(oldColor); canvas.setStroke(oldStroke); } private void printGraphic(Graphics2D canvas) { canvas.setStroke(graphicsStroke); canvas.setColor(Color.RED); GeneralPath graphics = new GeneralPath(); boolean not_first = true; for(GraphicPoint graphicPoint : points) { Point2D.Double point = xyToPoint(graphicPoint.getX(), graphicPoint.getY()); if(not_first) { graphics.moveTo(point.getX(), point.getY()); not_first = false; } else { graphics.lineTo(point.getX(), point.getY()); } } canvas.draw(graphics); } private void paintMarkers(Graphics2D g2) { g2.setStroke(markerStroke); g2.setColor(Color.RED); g2.setPaint(Color.RED); for(GraphicPoint p : points) { if(showMarkedPoints) { Double fx = Math.abs(p.getY()); StringBuffer buff = new StringBuffer(fx.toString()); int dot = buff.lastIndexOf("."); if(dot > 0 ) buff.replace(dot, dot + 1, ""); boolean flag = true; for(int i = 1; i < buff.length(); i++) { char c1 = buff.charAt(i - 1); char c2 = buff.charAt(i); // int c3 = c2 - c1; if(c1 > c2) { // || c3 != 1 flag = false; break; } } if(flag) { g2.setColor(Color.BLUE); g2.setPaint(Color.BLUE); } else { g2.setColor(Color.RED); g2.setPaint(Color.RED); } } Point2D.Double point = xyToPoint(p.getX(), p.getY()); Point2D.Double corner = shiftPoint(point, 2, 2); Ellipse2D.Double ellipse = new Ellipse2D.Double(); ellipse.setFrameFromCenter(point, corner); g2.draw(ellipse); g2.fill(ellipse); double W = 5; double W2 = W*2; Point2D.Double pointLine = shiftPoint(xyToPoint(p.getX(), p.getY()), -W, W); GeneralPath line = new GeneralPath(); line.moveTo(pointLine.getX(), pointLine.getY()); line.lineTo(line.getCurrentPoint().getX() + W2, line.getCurrentPoint().getY() - W2); g2.draw(line); pointLine = shiftPoint(xyToPoint(p.getX(), p.getY()), 0, W); line = new GeneralPath(); line.moveTo(pointLine.getX(), pointLine.getY()); line.lineTo(line.getCurrentPoint().getX(), line.getCurrentPoint().getY() - W2); g2.draw(line); pointLine = shiftPoint(xyToPoint(p.getX(), p.getY()), W, W); line = new GeneralPath(); line.moveTo(pointLine.getX(), pointLine.getY()); line.lineTo(line.getCurrentPoint().getX() - W2, line.getCurrentPoint().getY() - W2); g2.draw(line); pointLine = shiftPoint(xyToPoint(p.getX(), p.getY()), W, 0); line = new GeneralPath(); line.moveTo(pointLine.getX(), pointLine.getY()); line.lineTo(line.getCurrentPoint().getX() - W2, line.getCurrentPoint().getY()); g2.draw(line); } } private void paintAxis(Graphics2D g2) { g2.setStroke(axisStroke); g2.setColor(Color.BLACK); g2.setPaint(Color.BLACK); g2.setFont(axisFont); FontRenderContext context = g2.getFontRenderContext(); if(minX <= 0.0 && maxX >= 0.0) { g2.draw(new Line2D.Double(xyToPoint(0, maxY), xyToPoint(0, minY))); GeneralPath arrow = new GeneralPath(); Point2D.Double lineEnd = xyToPoint(0, maxY); arrow.moveTo(lineEnd.getX(), lineEnd.getY()); arrow.lineTo(arrow.getCurrentPoint().getX()+5, arrow.getCurrentPoint().getY()+20); arrow.lineTo(arrow.getCurrentPoint().getX()-10, arrow.getCurrentPoint().getY()); arrow.closePath(); g2.draw(arrow); g2.fill(arrow); Rectangle2D bounds = axisFont.getStringBounds("y", context); Point2D.Double labelPos = xyToPoint(0, maxY); g2.drawString("y", (float)labelPos.getX() + 10, (float)(labelPos.getY() - bounds.getY())); } if(minY <= 0.0 && maxY >= 0.0) { Line2D.Double lineX = new Line2D.Double(xyToPoint(minX, 0), xyToPoint(maxX, 0)); g2.draw(lineX); GeneralPath arrow = new GeneralPath(); Point2D.Double lineEnd = xyToPoint(maxX, 0); arrow.moveTo(lineEnd.getX(), lineEnd.getY()); arrow.lineTo(arrow.getCurrentPoint().getX()-20, arrow.getCurrentPoint().getY()-5); arrow.lineTo(arrow.getCurrentPoint().getX(), arrow.getCurrentPoint().getY()+10); arrow.closePath(); g2.draw(arrow); g2.fill(arrow); Rectangle2D bounds = axisFont.getStringBounds("x", context); Point2D.Double labelPos = xyToPoint(maxX, 0); g2.drawString("x", (float)(labelPos.getX() - bounds.getWidth() - 10), (float)(labelPos.getY() + bounds.getY())); } } private void paintSq(Graphics2D g2) { ArrayList<Integer> nulls = new ArrayList<Integer>(); for(int i = 1; i < points.size(); i++) { if(Math.abs(0-points.get(i).getY()) <= 1E-10) { nulls.add(i); } } if(nulls.size() < 2) return; FontRenderContext context = g2.getFontRenderContext(); for(int i = 0; i < nulls.size() - 1; i++) { g2.setStroke(sqStroke); g2.setColor(Color.YELLOW); g2.setPaint(Color.YELLOW); g2.setFont(sqFont); Double S = (points.get(nulls.get(i)).getY()/2.) * (points.get(nulls.get(i) + 1).getX() - points.get(nulls.get(i)).getX()); for(int j = nulls.get(i) + 1; j < nulls.get(i+1); j++) { S += (points.get(j).getY()/2.) * (points.get(j + 1).getX() - points.get(j - 1).getX()); } S += (points.get(nulls.get(i+1)).getY()/2.) * (points.get(nulls.get(i+1)).getX() - points.get(nulls.get(i+1) - 1).getX()); GeneralPath sq = new GeneralPath(); Point2D.Double start = xyToPoint(points.get(nulls.get(i)).getX(), points.get(nulls.get(i)).getY()); sq.moveTo(start.getX(), start.getY()); for(int j = nulls.get(i) + 1; j <= nulls.get(i+1); j++) { Point2D.Double np = xyToPoint(points.get(j).getX(), points.get(j).getY()); sq.lineTo(np.getX(), np.getY()); } sq.closePath(); g2.draw(sq); g2.fill(sq); g2.setColor(Color.BLUE); g2.setPaint(Color.BLUE); StringBuffer sS = new StringBuffer(((Double)Math.abs(S)).toString()); Rectangle2D bounds = axisFont.getStringBounds(sS.substring(0, 4), context); Point2D.Double labelPos = xyToPoint( (points.get(nulls.get(i + 1)).getX() + points.get(nulls.get(i)).getX())/2.0, 0); double w = points.get(nulls.get(i + 1) - 1).getY()>0?-1:1; g2.drawString(sS.substring(0, 4), (float)(labelPos.getX() - bounds.getWidth()/2.), (float)(labelPos.getY() + w*bounds.getHeight())); } } protected Point2D.Double xyToPoint(double x, double y) { double deltaX = x - minX; double deltaY = maxY - y; return new Point2D.Double((-dx + deltaX)*scaleX, (-dy + deltaY)*scaleY); } protected Point2D.Double shiftPoint(Point2D.Double src, double deltaX, double deltaY) { Point2D.Double dest = new Point2D.Double(); dest.setLocation(src.getX() + deltaX, src.getY() + deltaY); return dest; } }
--- title: Brawlhalla Stats API description: 'Documentation for api.brawltools.com' layout: ../../../layouts/Layout.astro --- # GetPlayerMatches Fetches the matches a player played at a specific tournament. ## Request ### Syntax ```https://api.brawltools.com/v1/player/match``` ### Query Parameters - **EntrantSmashIds** - *Integer[]* - Required. The SmashId ID of the player(s). - **EventSlug** - *String* - Required. The identifying Start.gg slug of a tournament. ## Response ### Sample Response ```json { "playerMatches": [ { "matchId": 62467451, "scores": [ 0, 3 ], "legends": [ [ "MORDEX", "MORDEX", "TEZCA" ], [ "KAYA", "KAYA", "KAYA" ] ], "maps": [ "Small Brawlhaven", "Small Brawlhaven", "Demon Island" ], "opponent": [ { "smashId": 1335570, "brawlhallaId": 9144432, "name": "lores" } ] }, { "matchId": 62465933, "scores": [ 3, 2 ], "legends": [ [ "" ], [ "" ] ], "maps": [ "" ], "opponent": [ { "smashId": 1749170, "brawlhallaId": 30226535, "name": "Raydish" } ] }, { "matchId": 62465929, "scores": [ 3, 1 ], "legends": [ [ "" ], [ "" ] ], "maps": [ "" ], "opponent": [ { "smashId": 346817, "brawlhallaId": 173537, "name": "Pavelski" } ] }, { "matchId": 62465924, "scores": [ 3, 0 ], "legends": [ [ "" ], [ "" ] ], "maps": [ "" ], "opponent": [ { "smashId": 558195, "brawlhallaId": 2926802, "name": "Kresuu" } ] }, { "matchId": 62465862, "scores": [ 2, 3 ], "legends": [ [ "TEZCA", "TEZCA", "TEZCA", "TEZCA", "TEZCA" ], [ "", "", "", "", "" ] ], "maps": [ "Demon Island", "Small Brawlhaven", "Small Brawlhaven", "Western Air Temple", "Apocalypse" ], "opponent": [ { "smashId": 468521, "brawlhallaId": 2277541, "name": "Wess" } ] }, { "matchId": 62412946, "scores": [ 3, 0 ], "legends": [ [ "" ], [ "" ] ], "maps": [ "" ], "opponent": [ { "smashId": 328252, "brawlhallaId": 919693, "name": "Blew" } ] }, { "matchId": 62412942, "scores": [ 3, 0 ], "legends": [ [ "" ], [ "" ] ], "maps": [ "" ], "opponent": [ { "smashId": 612859, "brawlhallaId": null, "name": "CrossyChainsaw" } ] }, { "matchId": 62412934, "scores": [ 0, -1 ], "legends": [ [ "" ], [ "" ] ], "maps": [ "" ], "opponent": [ { "smashId": 3475893, "brawlhallaId": null, "name": "marcopolo080908" } ] } ] } ``` ### Response Elements This response body can contain the following fields in JSON. - **PlayerMatches** - *Object[]* - An object containing statistics on a player's recent matches. This is a <a href="../../datatypes/playermatch.md">PlayerMatch</a> datatype.
import React from "react"; import validation from "./validation.js"; import {ContainerGlobal, Inicio,Titulos,ImgRyM,ContData,Data,LoginButton, Info,TitleInfo,Publi,ImgHenry} from "./Form.js"; const Form = ({login}) => { const [userData, setUserData] = React.useState({ username: '', password: '' }); const [errors, setErrors] = React.useState({ username: '', password: '' }); const handleInputChange = (event) =>{ const prop = event.target.name; const value = event.target.value; setUserData({...userData,[prop]: value,}); validation({...userData,[prop]: value,},setErrors,errors); //Valido los datos ingresados y le envío errors y setErrors. }; const handleSubmit = (event) =>{ event.preventDefault(); login(userData); } return ( <ContainerGlobal> <Inicio> <Titulos> <h1>Welcome to Rick and Morty API</h1> <ImgRyM src="https://static.posters.cz/image/hp/66133.jpg"/> <h3>Made by Gonzalo Nicolás Púa</h3> </Titulos> <ContData onSubmit={handleSubmit}> <Data> <label htmlFor="username">Username:</label> <input type='text' name="username" value={userData.username} onChange={handleInputChange}/> </Data> <Data> <label htmlFor="password">Password:</label> <input type='text' name="password" value={userData.password} onChange={handleInputChange}/> </Data> <LoginButton>Login</LoginButton> </ContData> </Inicio> <Info> <TitleInfo> <h3>Full Stack Developer Career</h3> </TitleInfo> <p>-Carrera destinada a aquellos que quieran obtener grandes conocimientos acerca del Desarrollo Web (Back-end & Front-end).</p> <h4>Modules to finish:</h4> <ul> <li>Module 1: Approved</li> <li>Module 2: Approved</li> <li>Module 3: Approved</li> <li>Module 4: Pending...</li> </ul> <Publi> <ImgHenry src="https://avatars.githubusercontent.com/u/57154655?s=200&v=4"/> <p>Patrocinado por <a target="_blank" rel="noopener noreferrer" href="https://www.soyhenry.com/">soyHenry</a>.</p> </Publi> </Info> </ContainerGlobal> ) } export default Form;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700" rel="stylesheet"> <title>Информационная система «Анимация и спецэффекты в Blender»</title> <link rel="shortcut icon" href="assets\images\icon_logo.png" type="image/png"> <!-- Bootstrap core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Additional CSS Files --> <link rel="stylesheet" href="assets/css/fontawesome.css"> <link rel="stylesheet" href="assets/css/style.css"> <link rel="stylesheet" href="assets/css/owl.css"> </head> <body class="is-preload"> <!-- Wrapper --> <div id="wrapper"> <!-- Main --> <div id="main"> <div class="inner"> <!-- Header --> <header id="header"> <!-- TABS --> <div class="topnav"> <a href="index.html">Главная</a> <a href="teorya_g2_1.html" class="active">Теория</a> <a href="practik_g2_1.html">Практика</a> <a href="test.html">Тестирование</a> <a href="ssilki.html">Полезные ссылки</a> </div> <div class="logo"> <a href="index.html">Blender</a> </header> <!-- контент --> <h3>Управление камерой в Blender</h3> <br> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\1.jpg" alt="1"></figure></div> <br> <h3>Как планировать сцены и настраивать камеру</h3> <br> <p> Прежде чем начать работу с камерой, важно спланировать композицию сцены. Оптимальный вариант — создать раскадровку ролика. Определить, какие элементы будут находиться в кадре, как они будут расположены относительно камеры, какая будет у камеры траектория, какие объекты в кадре будут двигаться, а какие останутся статичными. </p> <p> Если вы когда-нибудь присутствовали на съемочной площадке, знаете, как долго и тщательно режиссер и оператор выставляют кадр, композицию и свет. После того как всё выставят, делают тестовые проезды камеры и только после этого на площадку выходят актеры. По сути, мы с вами выступаем в роли режиссеров и операторов, только в 3D-софте. </p> <p> С теорией покончено, давайте откроем программу и приступим к созданию камеры в сцене. Всего несколько шагов нас отделяет от крутой и динамичной анимации камеры. </p> <br> <h2>Шаг 1. Создаем камеру</h2> <br> <p> 1. Выберите место, где вы хотите разместить камеру в сцене.<br> 2. Нажмите Shift + A, чтобы вызвать меню добавления объектов.<br> 3. Выберите Camera из списка объектов. </p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\2.jpg" alt="1"></figure></div> <br> <h2>Шаг 2. Настраиваем камеру</h2> <br> <p> Переходим к настройкам камеры. Выбираем размер кадра: для горизонтального видео это обычно 1920×1080, количество кадров в секунду — Frame Rate. </p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\3.jpg" alt="1"></figure></div> <br> <h2>Шаг 3. Настраиваем фокусное расстояние</h2> <br> <p> Переходим во вкладку Data и настраиваем Focal Length. </p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\4.jpg" alt="1"></figure></div> <p> Фокусное расстояние (Focal Length) — это параметр камеры, который определяет, насколько близким или далеким кажется объект на снимке. Короткое фокусное расстояние позволяет снимать широкие сцены, а длинное — делает объекты крупными и сфокусированными на заднем плане. </p> <p>Сравниваем фокусное расстояние — focal length 1</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\5.jpg" alt="1"></figure></div> <p>Сравниваем фокусное расстояние — focal length 2</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\6.jpg" alt="1"></figure></div> <p>Вот пример с фотографией, чтобы стало понятно, что Focal Length не работает как зум — этот параметр искажает пространство.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\7.jpg" alt="1"></figure></div> <p> Если захотелось узнать, как правильно подбирать фокусное расстояние в своих роликах, пишите в комментариях. </p> <br> <h3>Как перемещать камеру</h3> <br> <p>Сначала заходим в режим просмотра. Для этого нажимаем 0 на Numpad. Так же выходим из режима камеры. Перемещать камеру можно несколькими способами.</p> <p>Первый способ — использовать панель инструментов.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\8.jpg" alt="1"></figure></div> <p> Перемещаем ползунок осей XYZ, чтобы перемещаться в пространстве. Перемещаем ползунок вращения, чтобы вращать камеру. </p> <p> Можно использовать горячие клавиши. При нажатии клавиши G + X/Y/Z можем перемещаться по определенной оси. При нажатии клавиши R можем вращать камеру. При нажатии клавиши R + X/Y/Z можем вращать камеру по определенной оси. </p> <p>Переходим в режим камеры. Сверху во вкладке Orientation меняем параметр Global на Local.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\9.jpg" alt="1"></figure></div> <p>Нажимаем клавишу G и перемещаемся с помощью движения мыши или тачпада.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\9.gif" alt="1"></figure></div> <br> <h3>Какие есть техники анимации камеры</h3> <br> <p>В Blender есть несколько способов анимировать камеру.</p> <br> <h3>Ключевые кадры</h3><br> <p>Один из таких способов — выбрать ключевые кадры.</p> <br> <h2>Шаг 1. Создаем ключи</h2> <br> <p>Чтобы сделать анимацию камеры, воспользуемся ключевыми кадрами на таймлайне. По умолчанию панель таймлайна находится внизу. Выбираем необходимый кадр и нажимаем клавишу I. Появляется панель, где выбираем, на какой параметр ставим ключ.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\10.jpg" alt="1"></figure></div> <p>Перемещаемся вперед по таймлайну, ставим ключи анимации. Нажимаем пробел, чтобы проиграть анимацию.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\11.gif" alt="1"></figure></div> <br> <h2>Шаг 2. Настраиваем графики анимации</h2> <br> <p>Чтобы сделать анимацию более плавной, используем Graph Editor. Нажимаем на кнопку в левом углу и выбираем Graph Editor.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\11.jpg" alt="1"></figure></div> <p>Переходим в режим редактирования графиков. Можно настраивать все графики одновременно.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\12.jpg" alt="1"></figure></div> <p>Или каждый параметр по отдельности.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\13.jpg" alt="1"></figure></div> <br> <h3>Пути движения</h3> <br> <p>Вы можете создавать пути движения для камеры, чтобы она перемещалась по определенному маршруту.</p> <br> <h2>Шаг 1. Создаем пути движения</h2><br> <p>Создаем путь, по которому будет двигаться камера. Это может быть кривая Безье, я выбрал окружность.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\14.jpg" alt="1"></figure></div> <p>Переходим в вид сверху, увеличиваем радиус окружности и ставим камеру точно на окружность.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\15.jpg" alt="1"></figure></div> <h2>Шаг 2. Соединяем камеру и путь движения</h2><br> <p>Создаем иерархию зависимости. Соединяем камеру и окружность. Главное — соблюдать порядок. <strong>Камера</strong> движется по <strong>окружности.</strong> С зажатым Ctrl выбираем<strong> камеру,</strong> затем <strong>окружность.</strong></p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\16.jpg" alt="1"></figure></div> <p>Нажимаем Ctrl + P, выбираем Follow Path.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\17.jpg" alt="1"></figure></div> <p>Получилось привязать камеру к траектории. Теперь нужно указать точку, на которую будет направлен объектив камеры.</p> <br> <h2>Шаг 3. Создаем точку слежения</h2> <br> <p><strong>Add — Empty — Plain axis</strong>.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\18.jpg" alt="1"></figure></div> <p>Главное — расположить точку в том месте, за которым камера должна следить на всем пути передвижения. В моем случае это центр тела персонажа.</p> <p>Заходим во вкладку Constraint, выбираем параметр Track To.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\19.jpg" alt="1"></figure></div> <p>В параметре Target выбираем <strong>Empty</strong>.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\20.jpg" alt="1"></figure></div> <p>Запускаем анимацию.</p> <div class="kontent"><figure><img src="assets\images\Глава2\Теория\2_1\21.gif" alt="1"></figure></div> <br><br> <h2>Главное об управлении камерой в Blender</h2> <br> <p>Управление камерой в Blender — важный аспект создания трехмерной графики и анимации. Путем планирования, анимации и использования продвинутых методов работы с камерой вы сможете создавать качественные и красивые сцены. Не бойтесь экспериментировать и искать новые способы использования камеры для достижения желаемых результатов.</p> <p>Как планировать сцену и настраивать камеру в Blender:</p> <ol> <li>Продумываем композицию и создаем сцену.&nbsp;</li> <li>Добавляем камеру.</li> <li>Настраиваем ракурс</a>, фокусное расстояние, положение камеры.</li> <li>Создаем анимацию камеры по ключам или траектории.</li> <br> <div class="right"><a href="teorya_g2_2.html"><button>Следующая страницы </button></a></div> </div> </div> <!-- Sidebar --> <div id="sidebar"> <div class="inner"> <!-- Search Box --> <section id="search" class="alt"> <form method="get" action="#"> <input type="text" name="search" id="search" placeholder="Поиск..." /> </form> </section> <!-- Menu --> <nav id="menu"> <ul> <li> <span class="opener">Глава 1 <br>«Знакомство с анимацией в Blender»</span> <ul class="submenu"> <li><a href="teorya.html" >Устройство Blender 3D <input type="checkbox"/></a></li> <li><a href="teorya_g1_2.html">Горячие клавиши в Blender <input type="checkbox"/></a></li> <li><a href="teorya_g1_3.html">Виды анимации <input type="checkbox"/></a></li> <li><a href="teorya_g1_4.html">Как делать анимацию в Blender <input type="checkbox"/></a></li> <li><a href="teorya_g1_5.html">Анимация с помощью ключевых кадров и интерполяция <input type="checkbox"/></a></li> <li><a href="teorya_g1_6.html">Аниация с помощью драйверов <input type="checkbox"/></a></li> <li><a href="teorya_g1_7.html">Рендеринг и экспорт <input type="checkbox"/></a></li> </ul> </li> <span class="opener">Глава 2<br> «Камеры и освещение»</span> <ul class="submenu"> <li><a href="teorya_g2_1.html">Управление камерой в Blender <input type="checkbox"/></a></li> <li><a href="teorya_g2_2.html">Настройка света в Blender <input type="checkbox"/></a></li> </ul> </li> <li> <span class="opener">Глава 3<br> «Простейшая анимация в Blender»</span> <ul> <li><a href="teorya_g3_1.html">Принципы анимации в Blender <input type="checkbox"/></a></li> <li><a href="teorya_g3_1.html">Основы анимации в Blender <input type="checkbox"/></a></li> </ul> </li> <li> <span class="opener">Глава 4 <br>«Физика в Blender»</span> <ul> <li><a href="teorya_g4_1.html">Физика в Blender <input type="checkbox"/></a></li> <li><a href="teorya_g4_2.html">Rigid Body - твердое тело <input type="checkbox"/></a></li> <li><a href="teorya_g4_3.html">Cloth - ткань <input type="checkbox"/></a></li> <li><a href="teorya_g4_4.html">Soft Body - мягкое тело <input type="checkbox"/></a></li> <li><a href="teorya_g4_5.html">Fluid - жидкость <input type="checkbox"/></a></li> <li><a href="teorya_g4_6.html">Dynamic Paint - динамическая кисть <input type="checkbox"/></a></li> </ul> </li> <li> <span class="opener">Глава 5<br> «Система частиц»</span> <ul> <li><a href="teorya_g5_1.html">Система частиц общая информация <input type="checkbox"/></a></li> <li><a href="teorya_g5_2.html">Emitter <input type="checkbox"/></a></li> <li><a href="teorya_g5_3.html">Hair <input type="checkbox"/></a></li> </ul> </li> <li> <span class="opener">Глава 6 <br>«2D-анимация и Моушн-графика»</span> <ul> <li><a href="teorya_g6_1.html">2D-анимация: принципы <input type="checkbox"/></a></li> <li><a href="teorya_g6_2.html">Моушн-графика <input type="checkbox"/></a></li> <li><a href="teorya_g6_3.html">Моушн-графика в Blender (примеры работ) <input type="checkbox"/></a></li> </ul> </li> <li> <span class="opener">Глава 7 <br>«Анимация и спецэффекты текста» </span> <ul> <li><a href="teorya_g7_1.html">Текст в Blender <input type="checkbox"/></a></li> <li><a href="teorya_g7_2.html">Основные типы анимации текста <input type="checkbox"/></a></li> <li><a href="teorya_g7_3.html">Примеры анимации текста <input type="checkbox"/></a></li> </ul> </li> <li> <span class="opener">Глава 8<br> «Модификаторы, аддоны и ноды»</span> <ul> <li><a href="teorya_g8_1.html">Модификаторы в Blender <input type="checkbox"/></a></li> <li><a href="teorya_g8_2.html">Аддоны в Blender <input type="checkbox"/></a></li> <li><a href="teorya_g8_3.html">Ноды в Blender <input type="checkbox"/></a></li> </ul> </li> <li> <span class="opener">Глава 9<br> «Персонажная анимация»</span> <ul> <li><a href="teorya_g9_1.html">Риггинг в Blender <input type="checkbox"/></a></li> <li><a href="teorya_g9_2.html">Прямая и обратная кинематика <input type="checkbox"/></a></li> <li><a href="teorya_g9_3.html">Адон Rigify <input type="checkbox"/></a></li> </ul> </li> <li> <span class="opener">Глава 10<br> «Трекинг в Blender»</span> <ul> <li><a href="teorya_g10_1.html">Motion tracking <input type="checkbox"/></a></li> <li><a href="teorya_g10_2.html">Примеры создания VFX эффектов в Blender <input type="checkbox"/></a></li> </ul> </li> </nav> <a href="https://www.nntu.ru/structure/view/podrazdeleniya/kafedra-graficheskie-informacionnye-sistemy"> <br>© Кафедра ГИС <br> НГТУ им. Р.Е. Алексеева</a> </div> <!-- Back to top --> <div class='back-to-top' id='back-to-top' title='Back to top'><i class='fa fa-chevron-up' ></div> <!-- Scripts --> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <script src="assets/js/browser.min.js"></script> <script src="assets/js/breakpoints.min.js"></script> <script src="assets/js/transition.js"></script> <script src="assets/js/owl-carousel.js"></script> <script src="assets/js/custom.js"></script> <script src="assets/js/back-to-top.js"></script> </body> </html>
<!DOCTYPE html> <html> <body> <div> <p>Look at console!</p> </div> <script> // first example class Pizza0 { constructor(pizzaType, pizzaSize) { this.type = pizzaType; this.size = pizzaSize; this.crust = 'original'; this.toppings = []; } get pizzaCrust() { return this.crust; } set pizzaCrust(pizzaCrust) { this.crust = pizzaCrust; } getSize() { return this.size; } setSize(pizzaSize) { this.size = pizzaSize; } getToppings() { return this.toppings; } setToppings(topping) { this.toppings.push(topping); } bake() { console.log( `Baking a ${this.size} ${this.type} ${this.crust} crust pizza.` ); } } const myPizza = new Pizza0('pepperoni', 'small'); //created in constructor - like object's own fields, others - like inherited console.log(myPizza); myPizza.bake(); // not a best practice myPizza.type = 'supreme'; // good practice myPizza.pizzaCrust = 'thin'; myPizza.setSize('big'); myPizza.bake(); console.log(myPizza.pizzaCrust); console.log(myPizza.getSize()); myPizza.setToppings('sousage'); myPizza.setToppings('olives'); console.log(myPizza.getToppings()); // second example: inheritance // parent/super class class Pizza { constructor(pizzaSize) { this.size = pizzaSize; this.crust = 'original'; } getCrust() { return this.crust; } setCrust(pizzaCrust) { this.crust = pizzaCrust; } } console.log(new Pizza('medium')); // child class class SpecialtyPizza extends Pizza { constructor(pizzaSize) { super(pizzaSize); this.type = 'The Works'; } slice() { console.log(`Our ${this.type} ${this.size} pizza has 8 slices.`); } } const mySpecialty = new SpecialtyPizza('medium'); console.log(mySpecialty); // super's fields like it's own mySpecialty.slice(); // third example: encapsulation class PizzaEncaps { constructor(pizzaSize) { this._size = pizzaSize; this._crust = 'original'; // marked as "private" by naming convenction, but still accessable } getCrust() { return this._crust; } setCrust(pizzaCrust) { this._crust = pizzaCrust; } } // 4 example: Factory Function // an old method that literally prevent access to private fields function pizzaFactory(pizzaSize) { const crust = 'original'; const size = pizzaSize; return { bake: () => console.log(`Baking a ${size} ${crust} crust pizza.`) } } const myPizza2 = pizzaFactory('small'); myPizza2.bake(); // 5 example: real encapsulation, new way // now we declare public $ private fields above the constructor // supported by 93.4% browsers globally (06/11/23) caniuse.com class PizzaPrivates { crust = 'original'; // public field #size; // private field constructor(pizzaSize) { this.#size = pizzaSize; } getCrust() { return this.crust; } setCrust(pizzaCrust) { this.crust = pizzaCrust; } hereYouGo() { console.log( `Here's your ${this.crust} crust ${this.#size} pizza.` ); } } const myPizza3 = new PizzaPrivates('large'); console.log(myPizza3); myPizza3.hereYouGo(); console.log(myPizza3.crust); // not recomended, but working console.log(myPizza3.getCrust()); // works how it should // Uncaught SyntaxError: Private field '#size' must be declared in an enclosing class //console.log(myPizza3.#size); </script> </body> </html>
import logo from './logo.svg'; import LandingPage from './components/LandingPage'; import React, { useState } from 'react'; import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom'; import { Container} from 'react-bootstrap'; import SignUp from './components/SignUp'; import NavBar from './components/NavBar'; import Dashboard from './components/DashBoard'; import Login from './components/Login'; import Logout from './components/Logout'; import AdminDashboard from './components/AdminDashboard'; import './App.css'; import Footer from './components/footer'; import AllCodes from './components/ViewAllCodes'; import AddCodes from './components/AddCodes'; import AddDecorder from './components/AddDecorder'; import Subscribe from './components/Subscribe'; import MyDecoders from './components/MyDecoders'; function App() { const [isAuthenticated, setIsAuthenticated] = useState(false); const [username, setUsername] = useState(''); const handleLogin = (username) => { setIsAuthenticated(true); setUsername(username) }; const handleLogout = () => { setIsAuthenticated(false); setUsername(''); localStorage.removeItem('jwtToken'); } return ( <Router> <NavBar isAuthenticated={isAuthenticated} username={username} handleLogout={handleLogout} /> <div className="main-container"> <Routes> <Route path="/" element={<LandingPage />} /> <Route path="/signup" element={<SignUp handleLogin={handleLogin} />} /> <Route path="/login" element={<Login handleLogin={handleLogin} />} /> <Route path="/logout" element={<Logout onLogout={handleLogout} />} /> {isAuthenticated && ( <> <Route path="/dashboard" element={<Dashboard />} /> <Route path="/admin/dashboard" element={<AdminDashboard />} /> <Route path="/admin/dashboard/all-codes" element={<AllCodes />} /> <Route path="/admin/dashboard/add-code" element={<AddCodes />} /> <Route path="/dashboard/add-decorder" element={<AddDecorder />} /> <Route path="/subscribe/:duration" element={<Subscribe />} /> <Route path="/my-decoders" element={<MyDecoders />} /> </> )} </Routes> </div> <Footer /> </Router> ); } export default App;
// Example for the anonymous function below; setInterval(function(){ console.log("I am an anonymous function!"); console.log("This is cool!"); }, 2000); // 3 // I am an anonymous function! // This is cool! // I am an anonymous function! // This is cool! // I am an anonymous function! // This is cool! // I am an anonymous function! // This is cool! clearInterval(3);//to stop it. // Another example for anonymous function var callback = function(a, b){ console.log(a + b); // 'foobar' }; window.setTimeout(function(){ callback('foo', 'bar'); }, 1000); //answer is// foobar // Oooorrrr other one; window.setTimeout(callback, 1000, 'foo', 'bar'); // answer also is// foobar // We can create a function that takes in time in minutes, // and then pass that to the setInterval function: function minutesToMilliseconds(minutes) { return minutes * 60 * 1000; } setInterval(function () { console.log('test'); }, minutesToMilliseconds(5)); // Other example; function sing() { console.log("twinkle, twinkle...."); console.log("how I wonder...."); } var intervalId = setInterval(sing, 1000); setTimeout(function() { clearInterval(intervalId); }, 5000);
; This is a template for creating program headers that PAULMON2 can ; recognize. Using this header, you can make your programs appear ; in the "Run" command's menu and/or make your programs run automatically ; when the system is reset (useful if you put your code in non-volatile ; memory). You can also make programs which are plug-in commands to ; PAULMON2, either adding new fuctionality or replacing the built-in ; commands with your own customized versions. .equ locat, 0x8000 ;Location for this program .org locat .db 0xA5,0xE5,0xE0,0xA5 ;signiture bytes .db 35,255,0,0 ;id (35=prog, 249=init, 253=startup, 254=cmd) .db 0,0,0,0 ;prompt code vector .db 0,0,0,0 ;reserved .db 0,0,0,0 ;reserved .db 0,0,0,0 ;reserved .db 0,0,0,0 ;user defined .db 255,255,255,255 ;length and checksum (255=unused) .db "Program Name",0 .org locat+64 ;executable code begins here ; PAULMON2 will only recognize this header if it begin on a 256-byte ; page boundry. PAULMON2 can be configured to avoid seaching certain ; ranges of memory, if your copy of PAULMON2 is configured this way ; remember to write your programs/commands in areas where it is allowed ; to scan for them. ; To create ordinary programs (that show up in the R command's list), ; just use these lines as they are, but change the string to the ; name of your program. ; If your program is stored in non-volatile memory, you can switch ; the 35 byte to 253 and PAULMON2 will automatically run your program ; when it starts up. If your program hasn't changed the stack pointer, ; it can just terminate in a RET instruction and PAULMON2 will start ; up normally. ; To create plug-in commands for PAULMON2, change the 35 to 254. The ; keystroak that is to run your command much be specified in place of ; the 255 byte, for example: ; .db 254,'W',0,0 ;a new command assigned to the 'W' key ; if the key is a letter, it must be uppercase. If you use a key which ; conflicts with the built-in commands, your new command will override ; the built-in one... so be careful. ; When PAULMON2 runs your plug-in command, R6 & R7 will contain the ; value of the memory pointer, which you can change if you like. When ; your command is finished, it should terminate in a RET instruction. ; If the stack pointer is different from what it what when PAULMON2 ; called your command, you will almost certainly crash the machine. ; Apart from SP, R6, and R7, and the return value on the stack, you ; may use whatever memory you need. If your command needs to store ; data to be used next time it is run, 08-0F and 20-2F are areas which ; PAULMON2 (in it's default configuration) will not use. ; The "prompt code vector" is a feature where programs or commands in ; memory have an opportunity to run and add some text to the prompt ; that PAULMON2 prints before accepting each new command. The first ; two bytes must be 165 and 100, and the second two are the actual ; location PAULMON2 should call. If your prompt modifing code crashes ; or doesn't return properly, PAULMON2 will not work, so be careful ; when using this feature, particularily if downloading to non-volatile ; memory! ; If you create nifty plug-in commands, please consider contributing ; them to other users. Email [email protected] about getting your ; plug-in commans on the PAULMON2 web page.
require 'rails_helper' describe 'User create custom room rates' do it 'successfully' do # Arrange user = User.create!(name: 'João', email: '[email protected]', password: 'password', role: 1) guesthouse_owner = user.build_guesthouse_owner guesthouse = guesthouse_owner.build_guesthouse(corporate_name: 'Pousada Nascer do Sol LTDA.', brand_name: 'Pousada Nascer do Sol', registration_code: '47032102000152', phone_number: '15983081833', email: '[email protected]', description: 'Pousada com vista linda para a serra', pets: true, use_policy: 'Não é permitido fumar nas dependências da pousada', checkin_hour: '14:00', checkout_hour: '12:00', active: true) guesthouse.build_address(street: 'Rua das Flores, 1000', neighborhood: 'Vila Belo Horizonte' , city: 'Itapetininga', state: 'SP', postal_code: '01001-000') PaymentMethod.create!(method: 'credit_card') PaymentMethod.create!(method: 'debit_card') PaymentMethod.create!(method: 'pix') guesthouse.payment_methods = PaymentMethod.all guesthouse.save! guesthouse.rooms.create!([{ name: 'Quarto Primavera', description: 'Quarto com vista para a serra', size: 30, max_people: 2, daily_rate: 100, bathroom: true, balcony: true, air_conditioning: true, tv: true, wardrobe: true, safe: true, accessible: true, available: true }, { name: 'Quarto Verão', description: 'Quarto com vista para o mar', size: 30, max_people: 2, daily_rate: 100, bathroom: true, balcony: true, air_conditioning: true, tv: true, wardrobe: true, safe: true, accessible: true, available: false }]) # Act login_as user visit guesthouse_room_path(guesthouse, guesthouse.rooms.first) click_on 'Criar Diária por Período' fill_in 'Valor', with: 100 fill_in 'Data de início', with: '01/01/2021' fill_in 'Data de término', with: '31/01/2021' click_on 'Criar Diária por Período' # Assert expect(page).to have_content('Diárias por Período') within 'section#room_rates' do expect(page).to have_content('Valor', count: 1) expect(page).to have_content('Período', count: 3) expect(page).to have_content('R$ 100,00') expect(page).to have_content('01/01/2021 - 31/01/2021') end end context 'when there is a custom rate already registered' do it 'successfully' do user = User.create!(name: 'João', email: '[email protected]', password: 'password', role: 1) guesthouse_owner = user.build_guesthouse_owner guesthouse = guesthouse_owner.build_guesthouse(corporate_name: 'Pousada Nascer do Sol LTDA.', brand_name: 'Pousada Nascer do Sol', registration_code: '47032102000152', phone_number: '15983081833', email: '[email protected]', description: 'Pousada com vista linda para a serra', pets: true, use_policy: 'Não é permitido fumar nas dependências da pousada', checkin_hour: '14:00', checkout_hour: '12:00', active: true) guesthouse.build_address(street: 'Rua das Flores, 1000', neighborhood: 'Vila Belo Horizonte' , city: 'Itapetininga', state: 'SP', postal_code: '01001-000') PaymentMethod.create!(method: 'credit_card') PaymentMethod.create!(method: 'debit_card') PaymentMethod.create!(method: 'pix') guesthouse.payment_methods = PaymentMethod.all guesthouse.save! guesthouse.rooms.create!([{ name: 'Quarto Primavera', description: 'Quarto com vista para a serra', size: 30, max_people: 2, daily_rate: 100, bathroom: true, balcony: true, air_conditioning: true, tv: true, wardrobe: true, safe: true, accessible: true, available: true }, { name: 'Quarto Verão', description: 'Quarto com vista para o mar', size: 30, max_people: 2, daily_rate: 100, bathroom: true, balcony: true, air_conditioning: true, tv: true, wardrobe: true, safe: true, accessible: true, available: false }]) guesthouse.rooms.first&.room_rates&.create!([{ start_date: '2021-01-15', end_date: '2021-01-31', daily_rate: 100 }, { start_date: '2021-02-01', end_date: '2021-02-28', daily_rate: 200 }]) # Act login_as user visit guesthouse_room_path(guesthouse, guesthouse.rooms.first) click_on 'Criar Diária por Período' fill_in 'Valor', with: 100 fill_in 'Data de início', with: '01/01/2021' fill_in 'Data de término', with: '14/01/2021' click_on 'Criar Diária por Período' # Assert expect(page).to have_content('Diária cadastrada com sucesso') expect(page).to have_content('Diárias por Período') within 'section#room_rates' do expect(page).to have_content('Valor', count: 3) expect(page).to have_content('Período', count: 5) expect(page).to have_content('R$ 100,00') expect(page).to have_content('01/01/2021 - 14/01/2021') expect(page).to have_content('15/01/2021 - 31/01/2021') expect(page).to have_content('01/02/2021 - 28/02/2021') end end end it 'and must fill in all fields' do # Arrange user = User.create!(name: 'João', email: '[email protected]', password: 'password', role: 1) guesthouse_owner = user.build_guesthouse_owner guesthouse = guesthouse_owner.build_guesthouse(corporate_name: 'Pousada Nascer do Sol LTDA.', brand_name: 'Pousada Nascer do Sol', registration_code: '47032102000152', phone_number: '15983081833', email: '[email protected]', description: 'Pousada com vista linda para a serra', pets: true, use_policy: 'Não é permitido fumar nas dependências da pousada', checkin_hour: '14:00', checkout_hour: '12:00', active: true) guesthouse.build_address(street: 'Rua das Flores, 1000', neighborhood: 'Vila Belo Horizonte' , city: 'Itapetininga', state: 'SP', postal_code: '01001-000') PaymentMethod.create!(method: 'credit_card') PaymentMethod.create!(method: 'debit_card') PaymentMethod.create!(method: 'pix') guesthouse.payment_methods = PaymentMethod.all guesthouse.save! guesthouse.rooms.create!([{ name: 'Quarto Primavera', description: 'Quarto com vista para a serra', size: 30, max_people: 2, daily_rate: 100, bathroom: true, balcony: true, air_conditioning: true, tv: true, wardrobe: true, safe: true, accessible: true, available: true }, { name: 'Quarto Verão', description: 'Quarto com vista para o mar', size: 30, max_people: 2, daily_rate: 100, bathroom: true, balcony: true, air_conditioning: true, tv: true, wardrobe: true, safe: true, accessible: true, available: false }]) # Act login_as user visit guesthouse_room_path(guesthouse, guesthouse.rooms.first) click_on 'Criar Diária por Período' fill_in 'Valor', with: '' fill_in 'Data de início', with: '' fill_in 'Data de término', with: '' click_on 'Criar Diária por Período' # Assert expect(page).to have_content('Não foi possível cadastrar a diária') expect(page).to have_content('Valor da diária não pode ficar em branco') expect(page).to have_content('Data de início não pode ficar em branco') expect(page).to have_content('Data de término não pode ficar em branco') end context 'when dates is overlapping others periods' do it 'does not create' do # Arrange user = User.create!(name: 'João', email: '[email protected]', password: 'password', role: 1) guesthouse_owner = user.build_guesthouse_owner guesthouse = guesthouse_owner.build_guesthouse(corporate_name: 'Pousada Nascer do Sol LTDA.', brand_name: 'Pousada Nascer do Sol', registration_code: '47032102000152', phone_number: '15983081833', email: '[email protected]', description: 'Pousada com vista linda para a serra', pets: true, use_policy: 'Não é permitido fumar nas dependências da pousada', checkin_hour: '14:00', checkout_hour: '12:00', active: true) guesthouse.build_address(street: 'Rua das Flores, 1000', neighborhood: 'Vila Belo Horizonte' , city: 'Itapetininga', state: 'SP', postal_code: '01001-000') PaymentMethod.create!(method: 'credit_card') PaymentMethod.create!(method: 'debit_card') PaymentMethod.create!(method: 'pix') guesthouse.payment_methods = PaymentMethod.all guesthouse.save! guesthouse.rooms.create!([{ name: 'Quarto Primavera', description: 'Quarto com vista para a serra', size: 30, max_people: 2, daily_rate: 100, bathroom: true, balcony: true, air_conditioning: true, tv: true, wardrobe: true, safe: true, accessible: true, available: true }, { name: 'Quarto Verão', description: 'Quarto com vista para o mar', size: 30, max_people: 2, daily_rate: 100, bathroom: true, balcony: true, air_conditioning: true, tv: true, wardrobe: true, safe: true, accessible: true, available: false }]) guesthouse.rooms.first&.room_rates&.create!([{ start_date: '2021-01-15', end_date: '2021-01-31', daily_rate: 100 }, { start_date: '2021-02-01', end_date: '2021-02-28', daily_rate: 200 }]) # Act login_as user visit guesthouse_room_path(guesthouse, guesthouse.rooms.first) click_on 'Criar Diária por Período' fill_in 'Valor', with: 100 fill_in 'Data de início', with: '01/01/2021' fill_in 'Data de término', with: '16/01/2021' click_on 'Criar Diária por Período' # Assert expect(page).to have_content('Não foi possível cadastrar a diária') expect(page).to have_content('Essas datas estão sobrepostas a uma diária já cadastrada') end end # TODO - cannot access this page by typing the url end
const { expect } = require("chai"); const { ethers } = require("hardhat"); const { encode } = require("rlp"); function toHex(buf) { buf = buf.toString('hex'); if (buf.substring(0, 2) == "0x") return buf; return "0x" + buf.toString("hex"); }; function get_validators_hash(users, epoch) { let hash = ethers.utils.hexZeroPad(epoch, 32); for (let i = 0; i < users.length; i++) { hash = ethers.utils.solidityKeccak256(["bytes32", "address"], [hash, users[i]]); } return hash; } describe("XChainDaoEpoch", () => { let dao; let daoToken; let factory; let accounts; const zeroAddr = '0x0000000000000000000000000000000000000000'; beforeEach(async () => { const XChainDao = await ethers.getContractFactory("XchainDaoTester"); dao = await XChainDao.deploy(); await dao.deployed(); const Token = await ethers.getContractFactory("TestERC20"); daoToken = await Token.deploy(); await daoToken.deployed(); const ValidatorDelegationFactory = await ethers.getContractFactory("ValidatorDelegationFactory"); factory = await ValidatorDelegationFactory.deploy(); await factory.deployed(); accounts = await ethers.getSigners(); const signerAddrs = accounts.map(function(signer) { return signer.address; }).slice(0, 5); await dao.initialize(signerAddrs, factory.address, daoToken.address, 0); await dao.setMaxSize(3); expect(await dao.getSigner(0, 0)).to.equal(signerAddrs[0]); }); it("stake in the first epoch", async () => { const alice = accounts[5]; await daoToken.mint(alice.address, 1000); await daoToken.connect(alice).approve(dao.address, 1000); await dao.connect(alice).stake(alice.address, zeroAddr, zeroAddr, 1000); const bob = accounts[6]; await daoToken.mint(bob.address, 2000); await daoToken.connect(bob).approve(dao.address, 2000); await dao.connect(bob).stake(bob.address, alice.address, zeroAddr, 2000); const carol = accounts[7]; await daoToken.mint(carol.address, 3000); await daoToken.connect(carol).approve(dao.address, 3000); await dao.connect(carol).stake(carol.address, bob.address, zeroAddr, 3000); const dave = accounts[8]; await daoToken.mint(dave.address, 4000); await daoToken.connect(dave).approve(dao.address, 4000); await dao.connect(dave).stake(dave.address, carol.address, zeroAddr, 4000); let validators = await dao.getAll(); expect(validators[0]).to.equal(dave.address); expect(validators[3]).to.equal(alice.address); await dao.startNewEpochTest([2, 0, 1]); let hashStr = get_validators_hash([bob.address, dave.address, carol.address], 1); // https://github.com/ethers-io/ethers.js/issues/468 let messageHashBinary = ethers.utils.arrayify(hashStr); let signedMsg = await accounts[0].signMessage(messageHashBinary); let splitSig = ethers.utils.splitSignature(signedMsg); await dao.signForValidators(splitSig.v, splitSig.r, splitSig.s, "0"); signedMsg = await accounts[1].signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.signForValidators(splitSig.v, splitSig.r, splitSig.s, "1"); signedMsg = await accounts[2].signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.signForValidators(splitSig.v, splitSig.r, splitSig.s, "2"); signedMsg = await accounts[3].signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.signForValidators(splitSig.v, splitSig.r, splitSig.s, "3"); await dao.startNewEpochTest([2, 0, 1]); expect(await dao.getSignerCount(2)).to.equal(3); let firstSigner = [bob, carol, dave].reduce(function (p, v) { return ( p.address > v.address ? p : v ); }); expect(await dao.getSigner(2, 0)).to.equal(firstSigner.address); let signers = await dao.getNextSigners(2); expect(signers[0]).to.equal(bob.address); expect(signers[1]).to.equal(dave.address); expect(signers[2]).to.equal(carol.address); // unstake expect(await daoToken.balanceOf(alice.address)).to.equal(0); await dao.connect(alice).unstake(carol.address, zeroAddr); expect(await daoToken.balanceOf(alice.address)).to.equal(1000); expect(await daoToken.balanceOf(bob.address)).to.equal(0); expect(await dao.getSignerCount(2)).to.equal(3); await dao.connect(bob).unstake(carol.address, zeroAddr); expect(await dao.getSignerCount(2)).to.equal(3); expect(await daoToken.balanceOf(bob.address)).to.equal(0); await expect( dao.connect(bob).claimUnstake() ).to.be.revertedWith("unbond not expired"); expect(await dao.size()).to.equal(2); validators = await dao.getAll(); expect(validators[0]).to.equal(dave.address); expect(validators[1]).to.equal(carol.address); await dao.startNewEpochTest([0, 1]); hashStr = get_validators_hash([dave.address, carol.address], 3); // https://github.com/ethers-io/ethers.js/issues/468 messageHashBinary = ethers.utils.arrayify(hashStr); signedMsg = await dave.signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.connect(dave).signForValidators(splitSig.v, splitSig.r, splitSig.s, "1"); signedMsg = await carol.signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.connect(carol).signForValidators(splitSig.v, splitSig.r, splitSig.s, "2"); signedMsg = await bob.signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.connect(bob).signForValidators(splitSig.v, splitSig.r, splitSig.s, "0"); expect(await dao.getSignerCount(3)).to.equal(3); signers = await dao.getCurrentSigners(3); expect(signers[0]).to.equal(bob.address); expect(signers[1]).to.equal(dave.address); expect(signers[2]).to.equal(carol.address); await dao.startNewEpochTest([0, 1]); expect(await dao.getSignerCount(4)).to.equal(2); await dao.connect(bob).claimUnstake(); expect(await daoToken.balanceOf(bob.address)).to.equal(2000); }); it("delegator stake & unstake", async () => { const alice = accounts[5]; await daoToken.mint(alice.address, 1000); await daoToken.connect(alice).approve(dao.address, 1000); await dao.connect(alice).stake(alice.address, zeroAddr, zeroAddr, 1000); const bob = accounts[6]; await daoToken.mint(bob.address, 2000); await daoToken.connect(bob).approve(dao.address, 2000); await dao.connect(bob).stake(bob.address, alice.address, zeroAddr, 2000); const carol = accounts[7]; await daoToken.mint(carol.address, 3000); await daoToken.connect(carol).approve(dao.address, 3000); await dao.connect(carol).stake(carol.address, bob.address, zeroAddr, 3000); const dave = accounts[8]; await daoToken.mint(dave.address, 4000); await daoToken.connect(dave).approve(dao.address, 4000); await dao.connect(dave).stake(dave.address, carol.address, zeroAddr, 4000); // buy voucher const edward = accounts[9]; await daoToken.mint(edward.address, 3000); const ValidatorDelegation = await ethers.getContractFactory("ValidatorDelegation"); const bobDelegationAddress = await dao.getValidatorDelegationAddress(bob.address); const bobValidatorDelegation = await ValidatorDelegation.attach(bobDelegationAddress); await daoToken.connect(edward).approve(dao.address, 3000); await bobValidatorDelegation.connect(edward).buyVoucher(1500, 0, dave.address, carol.address); const aliceDelegationAddress = await dao.getValidatorDelegationAddress(alice.address); const aliceValidatorDelegation = await ValidatorDelegation.attach(aliceDelegationAddress); await aliceValidatorDelegation.connect(edward).buyVoucher(1500, 0, carol.address, zeroAddr); let delegators = await aliceValidatorDelegation.getDelegators(); expect(delegators[0]).to.equal(edward.address); await dao.startNewEpochTest([1, 0, 2]); let hashStr = get_validators_hash([bob.address, dave.address, carol.address], 1); // https://github.com/ethers-io/ethers.js/issues/468 let messageHashBinary = ethers.utils.arrayify(hashStr); let signedMsg = await accounts[0].signMessage(messageHashBinary); let splitSig = ethers.utils.splitSignature(signedMsg); await dao.signForValidators(splitSig.v, splitSig.r, splitSig.s, "0"); signedMsg = await accounts[1].signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.signForValidators(splitSig.v, splitSig.r, splitSig.s, "1"); signedMsg = await accounts[2].signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.signForValidators(splitSig.v, splitSig.r, splitSig.s, "2"); signedMsg = await accounts[3].signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.signForValidators(splitSig.v, splitSig.r, splitSig.s, "3"); await dao.startNewEpochTest([1, 0, 2]); expect(await dao.getSignerCount(2)).to.equal(3); let firstSigner = [bob, carol, dave].reduce(function (p, v) { return ( p.address > v.address ? p : v ); }); expect(await dao.getSigner(2, 0)).to.equal(firstSigner.address); await dao.connect(alice).unstake(carol.address, zeroAddr); await dao.connect(bob).unstake(carol.address, zeroAddr); // sellVouncher expect(await daoToken.balanceOf(edward.address)).to.equal(0); await aliceValidatorDelegation.connect(edward).sellVoucher(1500, 3000, carol.address, zeroAddr); // alice is not a signer expect(await daoToken.balanceOf(edward.address)).to.equal(1500); delegators = await aliceValidatorDelegation.getDelegators(); expect(delegators[0]).to.equal(zeroAddr); // buyVoucher after the validator unstake await daoToken.connect(edward).approve(dao.address, 1500); await bobValidatorDelegation.connect(edward).buyVoucher(1500, 0, dave.address, carol.address); await bobValidatorDelegation.connect(edward).sellVoucher(3000, 6000, dave.address, carol.address); delegators = await bobValidatorDelegation.getDelegators(); expect(delegators[0]).to.equal(edward.address); await dao.startNewEpochTest([0, 1]); // unstake bobValidatorDelegation.connect(edward).unstakeClaimTokens(); expect(await daoToken.balanceOf(edward.address)).to.equal(3000); delegators = await bobValidatorDelegation.getDelegators(); expect(delegators[0]).to.equal(zeroAddr); hashStr = get_validators_hash([dave.address, carol.address], 3); // https://github.com/ethers-io/ethers.js/issues/468 messageHashBinary = ethers.utils.arrayify(hashStr); signedMsg = await dave.signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.connect(dave).signForValidators(splitSig.v, splitSig.r, splitSig.s, "1"); signedMsg = await carol.signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.connect(carol).signForValidators(splitSig.v, splitSig.r, splitSig.s, "2"); signedMsg = await bob.signMessage(messageHashBinary); splitSig = ethers.utils.splitSignature(signedMsg); await dao.connect(bob).signForValidators(splitSig.v, splitSig.r, splitSig.s, "0"); await dao.startNewEpochTest([0, 1]); expect(await dao.getSignerCount(4)).to.equal(2); }); });
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react' interface IUseLocalStorage<T> { key: string defaultValue: T } export const useLocalStorage = <T>({ key, defaultValue }: IUseLocalStorage<T>): [T, Dispatch<SetStateAction<T>>, boolean] => { const [isLoading, setIsLoading] = useState(false) const [value, setValue] = useState<T>(defaultValue) const isMounted = useRef(false) useEffect(() => { setIsLoading(true) try { const item = window.localStorage.getItem(key) if (item) { setValue(JSON.parse(item)) } } catch (error) { console.log(error) } finally { setIsLoading(false) } return () => { isMounted.current = false } }, [key]) useEffect(() => { if (isMounted.current) { window.localStorage.setItem(key, JSON.stringify(value)) } else { isMounted.current = true } }, [key, value]) return [value, setValue, isLoading] }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>动脑学院装饰者模式</title> </head> <body> </body> </html> <script> function Man () { console.log('我是一个自认为很美的女生'); } Man.prototype = { sayName: function() { console.log('我是张瑞'); }, ability: function() { console.log('100分') }, technology: function() { console.log('我是大神'); } }; //创建装饰器 var Decorator = function(man) { this.man = man; } //装饰器需要实现man中需要被装饰的方法 Decorator.prototype = { sayName: function() { this.man.sayName(); }, ability: function() { this.man.ability(); }, technology: function() { this.man.technology(); } } //我们为每一个功能创建一个装饰对象。重写原有方法 var ViagraMan = function(man) { Decorator.call(this, man); console.log('获得BUFF的能力增强了'); } ViagraMan.prototype = new Decorator(man); ViagraMan.prototype.sayName = function() { console.log('我是有viagra能力而不需要viagra能力的张瑞'); } ViagraMan.prototype.ability = function() { this.man.ability(); console.log('能力增强到200'); } var DNMan = function(man) { Decorator.call(this, man); console.log('获得动脑加成!'); } DNMan.prototype = new Decorator(man); DNMan.prototype.sayName = function() { console.log('我是河南的张瑞'); } DNMan.prototype.getLession = function() { console.log('在学习动脑学院公开课'); } var man = new Man(); man.sayName(); man.ability(); man.technology(); var haibushi = new ViagraMan(man); haibushi.sayName(); haibushi.ability(); haibushi.technology(); //装饰器的参数对象是可以任意的可以是灵活的 装饰器可以额外添加功能 var abu = new DNMan(haibushi); abu.sayName(); abu.ability(); abu.technology(); //es6 @符号是一个语法糖 //es7 //方法装饰器 function sayYourName(target, key, descriptor) { descriptor.value = () => { console.log('我是张瑞') } console.log('前端工程师'); return descriptor; } class Man { @sayYourName toString() { } } const man = new Man(); man.toString(); //类装饰器 function isMaster(target) { target.isMaster = true; } @isMaster class Man { } console.log(Man['isMaster']); function Man(){} Object.defineProperty(Man.prototype, p:'toString', attributes: { value: function(){}, enumerable: true, configurable: true, writable: true }); function sayYourName(target, key, descriptor) { descriptor.value = () =>{ console.log('我是张瑞'); } console.log('web前端工程师'); return descriptor; } var descriptor = { value: function() {}, enumerable: true, configurable: true, writable: true }; var description = sayYourName(Man.prototype, key:'toString', descriptor); Object.defineProperty(Man.prototype, p:'toString', description); </script>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <script type="text/javascript"> $(document).ready(function () { $("#addRecordForm").validate({ submitHandler: function (form) { $(form).ajaxSubmit({ success: function (html) { $("#recordsTable").DataTable().ajax.reload(null, false); showSuccessMessage(html); closeForm(); return false; }, error: function (xhr) { if (xhr.status == 409) { showErrorMessage(xhr.responseText); } } }); }, errorPlacement: function (error, element) { validPlaceError(error, element); }, success: function (label, element) { validPlaceSuccess(label, element); } }); $("#addRecordForm").submit(function (e) { e.preventDefault(); $(this).valid(); return false; }); }) </script> <div class="panel panel-default"> <div class="panel-heading"> <p class="panel-title">Добавление записи</p> </div> <div class="panel-body"> <div class="col-md-8"> <form:form modelAttribute="record" id="addRecordForm" method="post" action="saveRecord"> <form:hidden path="id"/> <form:hidden path="user"/> <form:hidden path="version"/> <div class="form-group"> <label class="control-label">Фамилия: </label> <form:input path="surname" id="surname" cssClass="required form-control"/> <span class="help-block"></span> </div> <div class="form-group"> <label class="control-label">Имя: </label> <form:input path="name" id="name" cssClass="required form-control"/> <span class="help-block"></span> </div> <div class="form-group"> <label class="control-label">Телефон: </label> <form:input path="phone" id="phone" cssClass="required form-control"/> <span class="help-block"></span> </div> <div class="form-group"> <label class="control-label">Адрес: </label> <form:input path="address" id="address" cssClass="form-control"/> </div> <div class="form-group"> <button type="submit" class="btn btn-success">Сохранить</button> <button type="button" onclick="closeForm()" class="btn btn-default">Отмена</button> </div> </form:form> </div> </div> </div>
// Filter categories function... document.addEventListener('DOMContentLoaded', function() { // We load the DOM content... const categoryCheckboxes = document.querySelectorAll('.category-checkbox'); // Select checkboxes... const imageContainers = document.querySelectorAll('.image-box'); // Select image's boxes... categoryCheckboxes.forEach(function(checkbox) { // We pass the checkboxes as arguments... // Attach event listener to the checkbox element // The function will be executed each time the checkbox's state changes (checked or unchecked) checkbox.addEventListener('change', function() { // Create an array from all checkboxes (Array.from(categoryCheckboxes)) // Filter the array to only include checked checkboxes // Map the array to create a new array of the values of the checked checkboxes const selectedCategories = Array.from(categoryCheckboxes) .filter(function(checkbox) { return checkbox.checked; }) .map(function(checkbox) { return checkbox.value; }); // Loop through each image container... imageContainers.forEach(function(container) { // Get the category assigned to this container (data-category attribute) const category = container.getAttribute('data-category'); // If no categories are selected, or if the category of this container is included in the selected categories... if (selectedCategories.length === 0 || selectedCategories.includes(category)) { // Make this container visible container.style.display = 'flex'; } else { // Hide this container container.style.display = 'none'; } }); }); }); });
import SwiftUI import SDWebImageSwiftUI import AVKit struct PostCardImage: View { var post: PostModel @State private var audioPlayer: AVPlayer? var body: some View { VStack(alignment: .leading) { HStack { if let profileUrl = post.profile, let url = URL(string: profileUrl) { WebImage(url: url) .resizable() .aspectRatio(contentMode: .fill) .scaledToFit() .clipShape(Circle()) .frame(width: 60, height: 60, alignment: .center) .shadow(color: .gray, radius: 3) } else { Image(systemName: "person.circle.fill") .resizable() .aspectRatio(contentMode: .fill) .scaledToFit() .clipShape(Circle()) .frame(width: 60, height: 60, alignment: .center) .shadow(color: .gray, radius: 3) } VStack(alignment: .leading, spacing: 4) { Text(post.username).font(.headline) Text((Date(timeIntervalSince1970: post.date)).timeAgo() + " ago").font(.subheadline).foregroundColor(.gray) }.padding(.leading, 10) }.padding(.leading) .padding(.top, 16) Text(post.caption) .lineLimit(nil) .padding(.leading, 16) .padding(.trailing, 32) if let mediaType = post.mediaType, mediaType == "audio", let audioUrl = post.mediaUrl, let url = URL(string: audioUrl) { Button(action: { toggleAudioPlayback(url: url) }) { Image(systemName: audioPlayer?.rate == 0 ? "pause.circle.fill" : "play.circle.fill") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 60, height: 60) .foregroundColor(.blue) } .padding(.top, 8) } else if let mediaUrl = post.mediaUrl, let url = URL(string: mediaUrl) { WebImage(url: url) .resizable() .aspectRatio(contentMode: .fill) .frame(width: UIScreen.main.bounds.size.width, height: 400, alignment: .center) .clipped() } else { Image(systemName: "photo.fill") .resizable() .aspectRatio(contentMode: .fill) .frame(width: UIScreen.main.bounds.size.width, height: 400, alignment: .center) .clipped() } } } func toggleAudioPlayback(url: URL) { print("Toggling") if audioPlayer == nil || audioPlayer?.rate == 0 { print("Attempting \(url)") let asset = AVAsset(url: url) let playerItem = AVPlayerItem(asset: asset) audioPlayer = AVPlayer(playerItem: playerItem) audioPlayer?.play() } else { print("Pausing") audioPlayer?.pause() } } init(post: PostModel) { self.post = post setupAudioSession() } func setupAudioSession() { do { try AVAudioSession.sharedInstance().setCategory(.playback) try AVAudioSession.sharedInstance().setActive(true) } catch { print("Failed to set up audio session: \(error)") } } }
import * as z from "zod" import { HeadphoneTypes, EnclosureType } from "@prisma/client" import { CompleteSetup, RelatedSetupModel } from "./index" export const HeadphonesModel = z.object({ id: z.string(), type: z.nativeEnum(HeadphoneTypes), frequency_response: z.number().int().array(), microphone: z.boolean().nullish(), wireless: z.boolean().nullish(), description: z.string().nullish(), amazonLink: z.string().nullish(), name: z.string(), imageUrl: z.string().nullish(), noise_cancellation: z.boolean().nullish(), enclosure_type: z.nativeEnum(EnclosureType), color: z.string().nullish(), }) export interface CompleteHeadphones extends z.infer<typeof HeadphonesModel> { setups: CompleteSetup[] } /** * RelatedHeadphonesModel contains all relations on your model in addition to the scalars * * NOTE: Lazy required in case of potential circular dependencies within schema */ export const RelatedHeadphonesModel: z.ZodSchema<CompleteHeadphones> = z.lazy(() => HeadphonesModel.extend({ setups: RelatedSetupModel.array(), }))
import { vec2, vec3 } from "gl-matrix"; import { isDefined, isGoodNumber, isNumber } from "./typeChecks"; export const RIGHT = /*@__PURE__*/ vec3.fromValues(1, 0, 0); export const UP = /*@__PURE__*/ vec3.fromValues(0, 1, 0); export const FWD = /*@__PURE__*/ vec3.fromValues(0, 0, -1); export const Pi = /*@__PURE__*/ Math.PI; export const HalfPi = /*@__PURE__*/ 0.5 * Pi; export const Tau = /*@__PURE__*/ 2 * Pi; export const TWENTY_FOUR_LOG10 = /*@__PURE__*/ 55.2620422318571; export const LOG1000 = /*@__PURE__*/ 6.90775527898214; export const LOG2_DIV2 = /*@__PURE__*/ 0.346573590279973; export const EPSILON_FLOAT = /*@__PURE__*/ 1e-8; export const TIME_MAX = 8640000000000000; export const TIME_MIN = -TIME_MAX; /** * Find the median of an array of numbers. * Returns null on an empty array. * Assumes the array is sorted. * Returns the value of the middle element in an odd-length array. * Returns the midpoint between the middle-most two values of an even-length array. **/ export function calculateMedian(arr) { if (arr.length === 0) { return null; } if (arr.length % 2 === 0) { const mid = Math.floor(arr.length / 2) - 1; return arr[mid] / 2 + arr[mid + 1] / 2; } const mid = (arr.length - 1) / 2; return arr[mid]; } /** * Calculates the arithmetic mean of an array of numbers. * Returns null on an empty array. **/ export function calculateMean(arr) { if (arr.length === 0) { return null; } let accum = 0; for (const value of arr) { accum += value / arr.length; } return accum; } /** * Calculates the statistical variance of an array of numbers. * Returns null for arrays smaller than 2 elements. **/ export function calculateVariance(arr) { if (arr.length < 2) { return null; } const mean = calculateMean(arr); const squaredDiffs = arr .map((x) => (x - mean) ** 2) .reduce((acc, x) => acc + x, 0); return squaredDiffs / (arr.length - 1); } /** * Calculates the standard deviation of an array of numbers. * Returns null for arrays smaller than 2 elements. **/ export function calculateStandardDeviation(arr) { if (arr.length < 2) { return null; } const variance = calculateVariance(arr); return Math.sqrt(variance); } export function xy2i(x, y, width, components = 1) { return components * (x + width * y); } export function vec22i(vec, width, components = 1) { return xy2i(vec[0], vec[1], width, components); } export function i2vec2(vec, i, width, components = 1) { const stride = width * components; const p = i % stride; const x = Math.floor(p / components); const y = Math.floor(i / stride); vec2.set(vec, x, y); } export function radiansClamp(radians) { return ((radians % Tau) + Tau) % Tau; } export function degreesClamp(radians) { return ((radians % 360) + 360) % 360; } /** * Force a value onto a range */ export function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); } /** * Convert degress to radians * @param degrees */ export function deg2rad(degrees) { return degrees * Tau / 360; } /** * Convert radias to degress * @param radians */ export function rad2deg(radians) { return radians * 360 / Tau; } /** * Returns the number with the largest magnitude. * @param a * @param b */ export function maxly(...numbers) { let max = 0; for (const n of numbers) { if (Math.abs(n) > max) { max = n; } } return max; } /** * Returns the number with the smallest magnitude. * @param numbers */ export function minly(...numbers) { let min = Number.MAX_VALUE; for (const n of numbers) { if (Math.abs(n) < min) { min = n; } } return min; } /** * Translate a value into a range. */ export function project(v, min, max) { const delta = max - min; if (delta === 0) { return 0; } else { return (v - min) / delta; } } /** * Translate a value out of a range. */ export function unproject(v, min, max) { return v * (max - min) + min; } export function formatNumber(value, digits = 0) { if (isNumber(value)) { return value.toFixed(digits); } else { return ""; } } export function parseNumber(value) { if (/\d+/.test(value)) { return parseFloat(value); } else { return null; } } export function formatVolume(value) { if (isNumber(value)) { return clamp(unproject(value, 0, 100), 0, 100).toFixed(0); } else { return ""; } } export function parseVolume(value) { if (/\d+/.test(value)) { return clamp(project(parseInt(value, 10), 0, 100), 0, 1); } else { return null; } } /** * Pick a value that is proportionally between two values. */ export function lerp(a, b, p) { return (1 - p) * a + p * b; } export class Point { constructor(x = 0, y = 0) { this.x = x; this.y = y; Object.seal(this); } set(x, y) { this.x = x; this.y = y; } copy(p) { if (isDefined(p)) { this.x = p.x; this.y = p.y; } } toCell(character, scroll, gridBounds) { this.x = Math.round(this.x / character.width) + scroll.x - gridBounds.x; this.y = Math.floor((this.y / character.height) - 0.25) + scroll.y; } inBounds(bounds) { return bounds.left <= this.x && this.x < bounds.right && bounds.top <= this.y && this.y < bounds.bottom; } clone() { return new Point(this.x, this.y); } toString() { return `(x:${this.x}, y:${this.y})`; } } export class Size { constructor(width = 0, height = 0) { this.width = width; this.height = height; Object.seal(this); } set(width, height) { this.width = width; this.height = height; } copy(s) { if (isDefined(s)) { this.width = s.width; this.height = s.height; } } clone() { return new Size(this.width, this.height); } toString() { return `<w:${this.width}, h:${this.height}>`; } } export class Rectangle { constructor(x = 0, y = 0, width = 0, height = 0) { this.point = new Point(x, y); this.size = new Size(width, height); Object.freeze(this); } get x() { return this.point.x; } set x(x) { this.point.x = x; } get left() { return this.point.x; } set left(x) { this.point.x = x; } get width() { return this.size.width; } set width(width) { this.size.width = width; } get right() { return this.point.x + this.size.width; } set right(right) { this.point.x = right - this.size.width; } get y() { return this.point.y; } set y(y) { this.point.y = y; } get top() { return this.point.y; } set top(y) { this.point.y = y; } get height() { return this.size.height; } set height(height) { this.size.height = height; } get bottom() { return this.point.y + this.size.height; } set bottom(bottom) { this.point.y = bottom - this.size.height; } get area() { return this.width * this.height; } set(x, y, width, height) { this.point.set(x, y); this.size.set(width, height); } copy(r) { if (isDefined(r)) { this.point.copy(r.point); this.size.copy(r.size); } } clone() { return new Rectangle(this.point.x, this.point.y, this.size.width, this.size.height); } overlap(r) { const left = Math.max(this.left, r.left), top = Math.max(this.top, r.top), right = Math.min(this.right, r.right), bottom = Math.min(this.bottom, r.bottom); if (right > left && bottom > top) { return new Rectangle(left, top, right - left, bottom - top); } else { return null; } } toString() { return `[${this.point.toString()} x ${this.size.toString()}]`; } } export function isPowerOf2(v) { return ((v != 0) && !(v & (v - 1))); } export function nextPowerOf2(v) { return Math.pow(2, Math.ceil(Math.log2(v))); } export function prevPowerOf2(v) { return Math.pow(2, Math.floor(Math.log2(v))); } export function closestPowerOf2(v) { return Math.pow(2, Math.round(Math.log2(v))); } export function truncate(v) { if (Math.abs(v) > 0.0001) { return v; } return 0; } export function warnOnNaN(val, msg) { let type = null; let isBad = false; if (isNumber(val)) { type = "Value is"; isBad = !isGoodNumber(val); } else if ("length" in val) { type = "Array contains"; for (let i = 0; i < val.length; ++i) { if (!isGoodNumber(val[i])) { isBad = true; break; } } } else { type = "Vector component"; if ("w" in val) { isBad = isBad || !isGoodNumber(val.w); } if ("z" in val) { isBad = isBad || !isGoodNumber(val.z); } isBad = isBad || !isGoodNumber(val.y); isBad = isBad || !isGoodNumber(val.x); } if (isBad) { if (msg) { msg = `[${msg}] `; } else { msg = ""; } console.warn(`${msg}${type} not-a-number`); } } //# sourceMappingURL=math.js.map
use super::{write, read}; use core::fmt::{self, Write}; struct Stdout; const STDOUT: usize = 1; const STDIN: usize = 0; impl Write for Stdout { fn write_str(&mut self, s: &str) -> fmt::Result { write(STDOUT, s.as_bytes()); Ok(()) } } pub fn print(args: fmt::Arguments) { Stdout.write_fmt(args).unwrap(); } #[macro_export] macro_rules! print { ($str: literal $(, $($tail:tt)+)?) => { $crate::console::print(format_args!($str $(, $($tail)+)?)); } } #[macro_export] macro_rules! println { ($str: literal $(, $($tail:tt)+)?) => { $crate::console::print(format_args!(concat!($str, "\n") $(, $($tail)+)?)); } } pub fn getchar() -> u8 { let mut c = [0u8; 1]; read(STDIN, &mut c); c[0] }
import {CityLocModel, CurrentWeather, WeatherForecastModel} from '../models'; import {client} from './client'; import {API_KEY} from '@env'; export const getForecast = async ( city: Omit<CityLocModel, 'name'>, units: 'Imperial' | 'Metric', cnt?: number, ): Promise<WeatherForecastModel> => { const result = await client.get<WeatherForecastModel>('/data/2.5/forecast', { params: { lat: city.lat, lon: city.lon, APPID: API_KEY, units, cnt, }, }); return result.data; }; export const getCurrentWeather = async ( location: Omit<CityLocModel, 'name' | 'state'>, units: 'Imperial' | 'Metric', ): Promise<CurrentWeather> => { const result = await client.get<CurrentWeather>('/data/2.5/weather', { params: { lat: location.lat, lon: location.lon, APPID: API_KEY, units, }, }); return result.data; }; export const getCoordinatesByLocationName = async ( city: string, ): Promise<CityLocModel> => { const result = await client.get<Array<CityLocModel>>('/geo/1.0/direct', { params: { q: city, APPID: API_KEY, }, }); return result.data[0]; }; export const getLocationNameByCoordinates = async (coordinates: { lon: number; lat: number; }): Promise<CityLocModel> => { const result = await client.get<Array<CityLocModel>>('/geo/1.0/reverse', { params: { APPID: API_KEY, lat: coordinates?.lat, lon: coordinates?.lon, }, }); return result.data[0]; };
define(['./internal/arrayMap', './isArray', './internal/stringToPath'], function(arrayMap, isArray, stringToPath) { /** * Converts `value` to a property path array. * * @static * @memberOf _ * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] * * var path = ['a', 'b', 'c'], * newPath = _.toPath(path); * * console.log(newPath); * // => ['a', 'b', 'c'] * * console.log(path === newPath); * // => false */ function toPath(value) { return isArray(value) ? arrayMap(value, String) : stringToPath(value); } return toPath; });
import { createSlice, PayloadAction } from '@reduxjs/toolkit' export type TableData = { tableData: RowData[]; isLoading: boolean; error?: Error | null; isFullTable: boolean; genreList: string[]; } export type RowData = { ID: number, movieTitle: string, director: string, year: string, genre: string, } export const initialState: TableData = { tableData: [], isLoading: false, error: null, isFullTable: false, genreList: [], }; export type GetTableDataSuccessPayload = { tableData: []; } export type TableDataErrorPayload = { error: Error; } export type AddTableDataRequestPayload = { id: number; rowData: RowData; } export type RemoveTableDataPayload = { movieID: number; genre: string; } export type GetGenreTableDataRequestPayload = { tableData: []; } const tableData = createSlice({ name: 'tableData', initialState, reducers: { getTableDataRequest( state ) { state.isLoading = true; }, getTableDataSuccess( state, action: PayloadAction<GetTableDataSuccessPayload> ) { state.tableData = action.payload.tableData; state.isLoading = false; state.error = null; state.isFullTable = true; state.genreList = []; state.tableData.forEach((movie) => { if (!state.genreList.includes(movie.genre)) { state.genreList.push(movie.genre); } }) }, getTableDataError( state, action: PayloadAction<TableDataErrorPayload> ) { state.error = action.payload.error; state.isLoading = false; }, addTableDataRequest( state, action: PayloadAction<RowData> ) { state.isLoading = true; }, addTableDataSuccess( state, action: PayloadAction<AddTableDataRequestPayload> ) { if (!state.isFullTable && state.tableData.length === 25) { state.tableData.pop(); state.tableData.unshift({ ID: action.payload.id, ...action.payload.rowData }); } else { state.tableData = [{ ID: action.payload.id, ...action.payload.rowData }, ...state.tableData]; } state.isLoading = false; state.error = null; if (!state.genreList.includes(action.payload.rowData.genre)) { state.genreList.push(action.payload.rowData.genre); } }, addTableDataError( state, action: PayloadAction<TableDataErrorPayload> ) { state.error = action.payload.error; state.isLoading = false; }, get25TableDataRequest( state ) { state.isLoading = true; }, get25TableDataSuccess( state, action: PayloadAction<GetTableDataSuccessPayload> ) { state.tableData = action.payload.tableData; state.isLoading = false; state.error = null; state.isFullTable = false; }, get25TableDataError( state, action: PayloadAction<TableDataErrorPayload> ) { state.error = action.payload.error; state.isLoading = false; }, removeTableDataRequest( state, action: PayloadAction<RemoveTableDataPayload> ) { state.isLoading = true; }, removeTableDataSuccess( state, action: PayloadAction<RemoveTableDataPayload> ) { const filteredTableData = state.tableData.filter((movie) => movie.ID !== action.payload.movieID); state.tableData = filteredTableData; state.isLoading = false; state.error = null; const filteredGenreList = state.genreList.filter((genre) => genre !== action.payload.genre) state.genreList = filteredGenreList; state.tableData.forEach((movie) => { if (!state.genreList.includes(movie.genre)) { state.genreList.push(movie.genre); } }) }, removeTableDataError( state, action: PayloadAction<TableDataErrorPayload> ) { state.error = action.payload.error; state.isLoading = false; }, getGenreTableDataRequest( state, action: PayloadAction<GetGenreTableDataRequestPayload>, ) { state.isLoading = true; }, getGenreTableDataSuccess( state, action: PayloadAction<GetTableDataSuccessPayload> ) { state.tableData = action.payload.tableData; state.isLoading = false; state.error = null; state.isFullTable = true; }, getGenreTableDataError( state, action: PayloadAction<TableDataErrorPayload> ) { state.error = action.payload.error; state.isLoading = false; }, } }); const { actions, reducer } = tableData; export const tableDataActions = actions; export const tableDataReducer = reducer; const topSelect: (state) => TableData = (state) => state.tableData; export const tableDataSelectors = { selectTableData: (state) => topSelect(state).tableData, selectGenreList: (state) => topSelect(state).genreList, };
import React, { Component } from "react"; class PersonalCard extends Component { constructor(props) { super(props); this.state = { age: props.age }; } sumarEdad = () => { this.setState({ age: this.state.age + 1 }) } render() { const { firstName, lastName, hairColor } = this.props; return ( <div className="contenedor"> <h1>{lastName}, {firstName}</h1> <p>Age: {this.state.age}</p> <p>Hair Color: {hairColor}</p> <button onClick={this.sumarEdad}>Birthday button for {firstName} {lastName}</button> </div> ); } } export default PersonalCard;
import React, { useState } from "react"; export const NuevoCampo = ({ setCreation }) => { let [nombre, setNombre] = useState(""); let [provincia, setProvincia] = useState(""); let [municipio, setMunicipio] = useState(""); let [agregado, setAgregado] = useState(""); let [zona, setZona] = useState(""); let [poligono, setPoligono] = useState(""); let [parcela, setParcela] = useState(""); let [recinto, setRecinto] = useState(""); async function createCampo(){ const id=localStorage.getItem('user'); const body = { nombre: nombre, provincia: provincia, municipio: municipio, agregado: agregado, zona: zona, poligono: poligono, parcela: parcela, recinto: recinto, id_usuario:id }; try { await fetch( "https://campo.talkandeat.es/api/añadirCampo" , { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body), }).then(response=>{response.json()}).then(data=>{ alert(`Trabajador "${nombre}" creado correctamente.`); emptyForm(); }); } catch (error) { console.log(error.message); } } function emptyForm() { setNombre(""); setProvincia(""); setMunicipio(""); setAgregado(""); setZona(""); setPoligono(""); setParcela(""); setRecinto(""); } return ( <div className="form_campo container mt-5 mb-5"> <div> <button onClick={() => setCreation()}>&#5176;</button> <h2>Nuevo Campo</h2> </div> <p className="subtext"> Completa todos los campos para crear un trabajador. </p> <form onSubmit={(e) => { e.preventDefault(); createCampo(); setCreation() }} > <label className="form-label" htmlFor="nombre"> Nombre Recinto: </label> <input required className="form-control" type="text" name="nombre" id="nombre" value={nombre} onChange={(event) => setNombre(event.target.value)} /> <label className="form-label" htmlFor="provincia"> Provincia: </label> <input required className="form-control" type="text" name="provincia" id="provincia" value={provincia} onChange={(event) => setProvincia(event.target.value)} /> <label className="form-label" htmlFor="municipio"> Municipio: </label> <input required className="form-control" type="text" name="municipio" id="municipio" value={municipio} onChange={(event) => setMunicipio(event.target.value)} /> <label className="form-label" htmlFor="agregado"> Agregado: </label> <input required className="form-control" type="number" name="agregado" id="agregado" value={agregado} onChange={(event) => setAgregado(event.target.value)} /> <label className="form-label" htmlFor="zona"> Zona: </label> <input required className="form-control" type="number" name="zona" id="zona" value={zona} onChange={(event) => setZona(event.target.value)} /> <label className="form-label" htmlFor="poligono"> Polígono: </label> <input required className="form-control" type="number" name="poligono" id="poligono" value={poligono} onChange={(event) => setPoligono(event.target.value)} /> <label className="form-label" htmlFor="parcela"> Parcela: </label> <input required className="form-control" type="number" name="parcela" id="parcela" value={parcela} onChange={(event) => setParcela(event.target.value)} /> <label className="form-label" htmlFor="recinto"> Recinto: </label> <input required className="form-control" type="number" name="recinto" id="recinto" value={recinto} onChange={(event) => setRecinto(event.target.value)} /> <div> <p>*Rellena todo para habilitar*</p> <button type="submit">Crear</button> </div> </form> </div> ); };
import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; import {AdminComponent} from '../admin/admin/admin.component'; import {FarmersRegistrationReportComponent} from './farmers-registration-report/farmers-registration-report.component'; import {AdminGuard} from '../../core/guards/admin.guard'; import {FarmersApprovalProgressComponent} from './farmers-approval-progress/farmers-approval-progress.component'; import {ParchmentReportComponent} from './parchment-report/parchment-report.component'; const routes: Routes = [ { path: 'admin', component: AdminComponent, canActivateChild: [AdminGuard], children: [ { path: 'report/farmers', component: FarmersRegistrationReportComponent }, { path: 'farmers/approval/progress', component: FarmersApprovalProgressComponent }, { path: 'cherries/parchments/report', component: ParchmentReportComponent } ], } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class ReportRoutingModule { }
import React, { useState } from "react"; import styled, { css } from "styled-components"; import { Break } from "../Responsive"; import { Devices } from "../Responsive"; import BackgroundImage from "gatsby-background-image"; import { Link } from "gatsby"; import { Location } from "@reach/router"; import { getImage } from "gatsby-plugin-image"; const getBgImageType = (imageData) => imageData.layout === "fixed" ? "fixed" : "fluid"; const getAspectRatio = (imageData) => imageData.width / imageData.height; const getPlaceholder = (imageData) => { if (imageData.placeholder) { return imageData.placeholder.fallback.includes(`base64`) ? { base64: imageData.placeholder.fallback } : { tracedSvg: imageData.placeholder.fallback }; } return {}; }; const convertToBgImage = (imageData) => { if (imageData && imageData.layout) { const returnBgObject = {}; const bgType = getBgImageType(imageData); const aspectRatio = getAspectRatio(imageData); const placeholder = getPlaceholder(imageData); returnBgObject[bgType] = { ...imageData.images.fallback, ...placeholder, aspectRatio, }; return returnBgObject; } return {}; }; export const Colors = { blue: "#0084FF", lightBlue: "#BBEAFC", lightBlue2: "rgba(199, 243, 253, 0.5)", blue2: "#0097CD", veryLightBlue: "#C7F3FD", veryLightBlue2: "#E3F9FE", grayBrown: "#333333", gray2: "#A4A4A466", gray: "#898a8b", gray3: "#828282", verylightGray: "#F5F5F5", verylightGray2: "#FBFBFB", verylightGray3: "#F9F9F9", lightGray: "#ebebeb", lightGreen: "#c4f7b7", green: "#20630d", darkGray: "#3A3A3A", darkGray2: "#606060", borderGray: "#ececec", yellow: "#FFC718", lightYellow: "rgba(255, 183, 24, 0.1)", lightYellow2: "rgba(255, 183, 24, 0.2)", darkYellow: "#FFECBF", black: "#000000", white: "#FFFFFF", red: "red", lightRed: "#ffcdc9", whitePink: "#FFF1D1", shadow: "0px 0px 16px rgba(0, 0, 0, 0.15)", }; export const Select = styled.select` background: ${(props) => props.background}; color: ${(props) => props.color}; appearance: none; width: ${(props) => props.width}; text-align-last: center; border: ${(props) => props.border}; font-family: lato, sans-serif; padding: 5px; `; export const Option = styled.option` background: green; color: black; `; export const Tooltip = styled.div` position: absolute; left: 30px; bottom: 0; transform: translateY(50%); height: auto; z-index: 1; width: 300px; opacity: 1; border-radius: 0.25rem; margin-bottom: 1em; padding: 1em; background-color: rgba(137, 138, 139, 1); color: white; font-size: 1em; line-height: 1.2; text-align: center; -webkit-transition: all 0.15s ease-in-out; transition: all 0.15s ease-in-out; `; export const RoundImage = styled.div` display: ${(props) => props.display || "block"}; position: ${(props) => props.pos}; background-image: url(${(props) => props.url}); margin-bottom: ${(props) => props.mb}; background-repeat: no-repeat; background-size: ${(props) => props.bsize}; border-radius: ${(props) => props.border}; margin: ${(props) => props.margin}; background-position: ${(props) => props.position}; background-color: ${(props) => props.backgroundColor}; width: ${(props) => props.width}; height: ${(props) => props.height}; min-height: ${(props) => props.minHeight}; :hover { opacity: ${(props) => props.opacity}; } ${(props) => props.move && css` transform: translateY(-${(props) => props.up}); `} @media ${Break.lg} { width: ${(props) => props.w_lg}; height: ${(props) => props.h_lg}; border-radius: ${(props) => props.br_lg}; } @media ${Break.md} { height: ${(props) => props.h_md}; width: ${(props) => props.w_md}; border-radius: ${(props) => props.br_md}; } @media ${Break.sm} { height: ${(props) => props.h_sm}; width: ${(props) => props.w_sm}; border-radius: ${(props) => props.br_sm}; } @media ${Break.xs} { height: ${(props) => props.h_xs}; width: ${(props) => props.w_xs}; border-radius: ${(props) => props.br_xs}; } @media ${Devices.tablet} { width: ${(props) => props.width_tablet}; height: ${(props) => props.height_tablet}; } @media ${Devices.md} { width: ${(props) => props.width_md}; } @media ${Devices.lg} { width: ${(props) => props.width_lg}; } `; export const Span = styled.div` color: ${(props) => props.color}; margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; box-sizing: border-box; ${Tooltip}:hover { opacity: ${(props) => props.opacity}; } `; const StyledImage = styled.div` display: ${(props) => props.display}; position: ${(props) => props.position}; background-image: url(${(props) => props.src}); background-repeat: no-repeat; background-size: ${(props) => props.backgroundSize || "cover"}; border-radius: ${(props) => props.borderRadius}; background-position: ${(props) => props.position || "center center"}; background-color: ${(props) => props.backgroundColor}; width: ${(props) => props.width}; border: ${(props) => props.border}; height: ${(props) => props.height}; min-height: ${(props) => props.minHeight}; max-height: ${(props) => props.maxHeight || "none"}; min-width: ${(props) => props.minWidth}; margin: ${(props) => props.margin}; box-shadow: ${(props) => props.boxShadow}; padding: ${(props) => props.padding}; z-index: ${(props) => props.zIndex}; @media ${Break.sm} { height: ${(props) => props.h_sm}; min-height: ${(props) => props.minHeight_sm}; width: ${(props) => props.w_sm}; } @media ${Devices.xxs} { padding: ${(props) => props.padding_xxs}; display: ${(props) => props.display_xxs}; height: ${(props) => props.height_xxs}; right: ${(props) => props.right_xxs}; bottom: ${(props) => props.bottom_xxs}; left: ${(props) => props.left_xxs}; } @media ${Devices.xs} { display: ${(props) => props.display_xs}; height: ${(props) => props.height_xs}; left: ${(props) => props.left_xs}; right: ${(props) => props.right_xs}; top: ${(props) => props.top_xs}; bottom: ${(props) => props.bottom_xs}; } @media ${Devices.sm} { width: ${(props) => props.width_sm}; height: ${(props) => props.height_sm}; } @media ${Devices.tablet} { padding: ${(props) => props.padding_tablet}; display: ${(props) => props.display_tablet}; height: ${(props) => props.height_tablet}; width: ${(props) => props.width_tablet}; min-height: ${(props) => props.minHeight_tablet}; left: ${(props) => props.left_tablet}; right: ${(props) => props.right_tablet}; top: ${(props) => props.top_tablet}; bottom: ${(props) => props.bottom_tablet}; } @media ${Devices.md} { display: ${(props) => props.display_md}; left: ${(props) => props.left_md}; right: ${(props) => props.right_md}; top: ${(props) => props.top_md}; bottom: ${(props) => props.bottom_md}; height: ${(props) => props.height_md}; width: ${(props) => props.width_md}; } @media ${Devices.lg} { display: ${(props) => props.display_lg}; left: ${(props) => props.left_lg}; right: ${(props) => props.right_lg}; top: ${(props) => props.top_lg}; bottom: ${(props) => props.bottom_lg}; height: ${(props) => props.height_md}; } `; export const Img = React.memo(StyledImage); const StyledImageV2 = styled.div` background-image: url(${(props) => props.src}); background-repeat: no-repeat; background-size: ${(props) => props.backgroundSize || "cover"}; border-radius: ${(props) => props.borderRadius}; background-position: ${(props) => props.position || "center center"}; background-color: ${(props) => props.backgroundColor}; width: ${(props) => props.width}; height: ${(props) => props.height}; min-height: ${(props) => props.minHeight}; max-height: ${(props) => (props.maxHeight ? props.maxHeight : "none")}; min-width: ${(props) => props.minWidth}; margin: ${(props) => props.margin}; position: ${(props) => props.position}; top: ${(props) => props.top}; left: ${(props) => props.left}; rotate: ${(props) => props.rotate}; @media ${Break.xs} { height: ${(props) => props.height_xs}; min-height: ${(props) => props.minHeight_xs}; width: ${(props) => props.with_xs}; top: ${(props) => props.top_xs}; left: ${(props) => props.left_xs}; } @media ${Devices.tablet} { height: ${(props) => props.height_tablet}; min-height: ${(props) => props.minHeight_tablet}; width: ${(props) => props.width_tablet}; top: ${(props) => props.top_tablet}; left: ${(props) => props.left_tablet}; rotate: ${(props) => props.rotate_tablet}; } @media ${Devices.md} { height: ${(props) => props.height_md}; min-height: ${(props) => props.minHeight_md}; width: ${(props) => props.width_md}; top: ${(props) => props.top_md}; left: ${(props) => props.left_md}; } `; export const ImgV2 = React.memo(StyledImageV2); export const BackgroundSection = ({ id, children, alt, className, image, height, width, bgSize, borderRadius, margin, withOverlay, style, }) => { const thisImage = getImage(image); // Use like this: const bgImage = convertToBgImage(thisImage); return ( <BackgroundImage id={id} alt={alt} Tag="section" loading="eager" // fadeIn={false} className={className} borderRadius={borderRadius} {...bgImage} preserveStackingContext style={style} > {children} </BackgroundImage> ); }; export const StyledBackgroundSection = styled(BackgroundSection)` width: ${(props) => props.width || "100%"}; padding: ${(props) => props.padding}; text-align: ${(props) => props.align}; border-radius: ${(props) => props.borderRadius}; box-shadow: ${(props) => props.boxShadow}; position: ${(props) => props.position}; background-repeat: no-repeat; margin: ${(props) => props.margin || "auto"}; z-index: ${(props) => props.zIndex || 1}; opacity: 1; background-size: ${(props) => props.bgSize || "cover"}; height: ${(props) => props.height}; max-width: ${(props) => props.maxWidth}; min-height: ${(props) => props.minHeight}; flex-shrink: ${(props) => props.flexShrink}; display: ${(props) => props.display}; &:before { background-size: ${(props) => props.bgSize}; } &:after { min-height: ${(props) => props.minHeight}; border-radius: ${(props) => props.borderRadius}; filter: ${(props) => props.filter}; height: ${(props) => props.h_sm}; width: ${(props) => props.width}; max-width: ${(props) => props.maxWidth}; background-color: ${(props) => props.backgroundColor}; background-position: ${(props) => props.backgroundPosition} !important; } @media ${Devices.xxs} { height: ${(props) => props.height_xxs}; width: ${(props) => props.width_xxs}; margin: ${(props) => props.margin_xxs}; &:before, &:after { filter: ${(props) => props.filter_xxs}; } } @media ${Devices.xs} { height: ${(props) => props.height_xs}; margin: ${(props) => props.margin_xs}; width: ${(props) => props.width_xs || "100%"}; } @media ${Devices.sm} { height: ${(props) => props.height_sm}; width: ${(props) => props.width_sm}; } @media ${Devices.tablet} { border-radius: ${(props) => props.borderRadius_tablet}; height: ${(props) => props.height_tablet}; width: ${(props) => props.width_tablet || "100%"}; display: ${(props) => props.display_tablet}; margin: ${(props) => props.margin_tablet}; &:before, &:after { border-radius: ${(props) => props.borderRadius_tablet}; } } @media ${Devices.md} { width: ${(props) => props.width_md}; height: ${(props) => props.height_md}; } @media ${Devices.lg} { height: ${(props) => props.height_lg}; } @media ${Devices.xl} { } @media ${Devices.xxl} { } `; // @media ${Break.lg}{ // &:before, &:after { // background-position: ${props => props.bp_lg} !important; // } // } // @media ${Break.md}{ // &:before, &:after { // background-position: ${props => props.bp_md} !important; // } // } // @media ${Break.sm}{ // height: ${props => props.h_sm}; // width: ${props => props.w_sm}; // &:before, &:after { // border-radius: ${props => props.borderRadius_sm}; // background-position: ${props => props.bp_sm} !important; // } // } // @media ${Break.xs}{ // width: ${props => props.w_xs}; // &:before, &:after { // background-position: ${props => props.bp_xs} !important; // } // } export const Small = styled.small` display: ${(props) => props.display}; `; const getVariant = (props) => ({ outline: { border: `1px solid ${props.color}`, background: props.background || "initial", color: props.color, }, full: { border: "none", background: props.color, color: props.textColor || "white", }, empty: { border: "none", background: "none", color: "#0097CD", textTransform: "capitalize", }, }); const SmartButton = ({ children, onClick, type, icon, ...rest }) => { const styles = getVariant(rest)[rest.variant]; return ( <button type={type || "button"} onClick={(e) => onClick && onClick(e)} className={rest.className} style={{ ...rest.style, ...styles }} {...rest} > {icon} {children} </button> ); }; export const Button = styled(SmartButton)` font-size: ${(props) => props.fontSize}; font-family: "Lato", sans-serif; text-transform: ${(props) => props.textTransform || "uppercase"}; text-decoration: ${(props) => props.textDecoration || "none"}; text-decoration-line: ${(props) => props.textDecorationLine || "none"}; font-weight: ${(props) => props.fontWeight || "700"}; margin: ${(props) => props.margin}; border-radius: ${(props) => props.borderRadius}; position: ${(props) => props.position}; z-index: ${(props) => props.zIndex}; top: ${(props) => props.top}; bottom: ${(props) => props.bottom}; left: ${(props) => props.left}; right: ${(props) => props.right}; display: ${(props) => props.display}; padding: ${(props) => props.padding || "12px 24px"}; transform: ${(props) => props.transform}; color: ${(props) => props.color}; background: ${(props) => props.background}; border: ${(props) => props.border}; border-left: ${(props) => props.borderLeft}; border-top: ${(props) => props.borderTop}; border-bottom: ${(props) => props.borderBottom}; border-right: ${(props) => props.borderRight}; height: ${(props) => props.height || "40px"}; cursor: ${(props) => props.cursor || "pointer"}; text-align: ${(props) => props.textAlign || "center"}; letter-spacing: ${(props) => props.letterSpacing || "0px"}; line-height: ${(props) => props.lineHeight}; vertical-align: middle; width: ${(props) => props.width}; max-width: ${(props) => props.maxWidth}; min-width: ${(props) => props.minWidth}; align-items: ${(props) => props.alignItems}; align-self: ${(props) => props.alignSelf}; justify-self: ${(props) => props.justifySelf}; justify-content: ${(props) => props.justifyContent}; box-shadow: ${(props) => props.boxShadow}; &:hover { background-color: ${(props) => props.colorHover}; color: ${(props) => props.colorHoverText}; } @media ${Devices.xxs} { padding: ${(props) => props.padding_xxs}; } @media ${Devices.xs} { width: ${(props) => props.width_xs}; height: ${(props) => props.height_xs || "40px"}; text-align: ${(props) => props.textAlign_xs || "center"}; padding: ${(props) => props.padding_xs || "12px 24px"}; max-width: ${(props) => props.maxWidth_xs}; top: ${(props) => props.top_xs}; bottom: ${(props) => props.bottom_xs}; left: ${(props) => props.left_xs}; right: ${(props) => props.right_xs}; } @media ${Devices.sm} { width: ${(props) => props.width_sm}; height: ${(props) => props.height_sm || "40px"}; max-width: ${(props) => props.maxWidth_sm}; margin: ${(props) => props.margin_sm}; font-size: ${(props) => props.fontSize_sm}; top: ${(props) => props.top_sm}; bottom: ${(props) => props.bottom_sm}; left: ${(props) => props.left_sm}; right: ${(props) => props.right_sm}; } @media ${Devices.tablet} { width: ${(props) => props.width_tablet}; height: ${(props) => props.height_tablet || "40px"}; margin: ${(props) => props.margin_tablet}; padding: ${(props) => props.padding_tablet || "12px 24px"}; max-width: ${(props) => props.maxWidth_tablet}; display: ${(props) => props.display_tablet}; top: ${(props) => props.top_tablet}; bottom: ${(props) => props.bottom_tablet}; left: ${(props) => props.left_tablet}; right: ${(props) => props.right_tablet}; position: ${(props) => props.position_tablet}; } @media ${Devices.md} { width: ${(props) => props.width_md}; font-size: ${(props) => props.fontSize_md}; margin: ${(props) => props.margin_md}; top: ${(props) => props.top_md}; bottom: ${(props) => props.bottom_md}; left: ${(props) => props.left_md}; right: ${(props) => props.right_md}; } @media ${Devices.lg} { font-size: ${(props) => props.fontSize_lg}; width: ${(props) => props.width_lg}; left: ${(props) => props.left_lg}; right: ${(props) => props.right_lg}; } @media ${Devices.xl} { } @media ${Devices.xxl} { } `; Button.defaultProps = { fontSize: "12px", width: "fit-content", type: "button", colorHover: null, borderRadius: "0px", outline: false, onClick: null, display: "flex", alignItems: "center", }; export const Toggle = styled.div` width: ${(props) => props.width}; height: ${(props) => props.height}; background: ${(props) => props.bg}; color: ${(props) => props.color}; border-radius: ${(props) => props.b_radius}; cursor: pointer; vertical-align: middle; display: inline-block; font-family: lato, sans-serif; `; RoundImage.defaultProps = { width: "100%", }; Select.defaultProps = { background: Colors.white, color: Colors.black, border: "none", }; const SmartLink = ({ children, state, ...rest }) => ( <Location> {({ location }) => ( //make sure user's state is not overwritten <Link {...rest} state={{ prevUrl: location.href, ...state }}> {children} </Link> )} </Location> ); export { SmartLink as Link }; const linkRegex = new RegExp("(tel:|http)"); const StyledLink = ({ children, ...rest }) => { let Comp = Link; let props = {}; if (linkRegex.test(rest.to)) { props.href = rest.to; props.target = "_blank"; props.rel = "noopener noreferrer nofollow"; Comp = "a"; } else if (!rest.to || rest.to.charAt(0) === "#" || rest.to === "") { Comp = "label"; } return <Comp {...Object.assign(props, rest)}>{children}</Comp>; }; export const Anchor = styled(StyledLink)` display: ${(props) => props.display || "block"}; font-family: Lato, sans-serif; text-align: ${(props) => props.textAlign}; font-size: ${(props) => props.fontSize}; font-weight: ${(props) => props.fontWeight}; letter-spacing: 0.05em; text-transform: ${(props) => props.textTransform}; max-width: ${(props) => props.maxWidth}; cursor: ${(props) => props.cursor}; margin: ${(props) => props.margin}; max-width: ${(props) => props.maxWidth}; padding: ${(props) => props.padding}; padding-right: ${(props) => props.paddingRight || "innitial"}; text-shadow: ${(props) => props.textShadow}; line-height: ${(props) => props.lineHeight}; color: ${(props) => props.color}; &:hover { text-decoration: underline; } @media ${Devices.xxs} { } @media ${Devices.xs} { } @media ${Devices.sm} { } @media ${Devices.tablet} { } @media ${Devices.md} { } @media ${Devices.lg} { } @media ${Devices.xl} { } @media ${Devices.xxl} { } `; // @media ${Break.lg}{ // text-align: ${props => props.align_lg}; // font-size: ${props => props.fs_lg}; // } // @media ${Break.md}{ // text-align: ${props => props.align}; // font-size: ${props => props.fs_md}; // } // @media ${Break.sm}{ // display: ${props => props.display_sm}; // font-size: ${props => props.fs_sm}; // text-align: ${props => props.align_sm || 'center'}; // } // @media ${Break.xs}{ // font-size: ${props => props.fs_xs}; // text-align: ${props => props.align_xs}; // } export const Spinner = styled.div` border: ${(props) => `16px solid ${props.color || Colors.blue}`}; border-radius: 50%; border-top-color: #3498db; width: 120px; height: 120px; animation: spin 1s linear infinite; @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } `;
import { StyleSheet, Switch, Text, View, TextInput, Button, FlatList } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs'; import React, { useState, useEffect } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { MaterialCommunityIcons } from '@expo/vector-icons'; const Tab = createMaterialTopTabNavigator(); export default function TabsJunaid() { const [username, setUsername] = useState(''); const [email, setEmail] = useState(''); const [phoneNumber, setPhoneNumber] = useState(''); useEffect(() => { retrieveUserProfile(); }, []); const storeUserProfile = async () => { try { const profile = { username, email, phoneNumber, profilePicture }; await AsyncStorage.setItem('userProfile', JSON.stringify(profile)); } catch (error) { console.log('Error storing user profile:', error); } }; const retrieveUserProfile = async () => { try { const profileString = await AsyncStorage.getItem('userProfile'); if (profileString !== null) { const profile = JSON.parse(profileString); setUsername(profile.username); setEmail(profile.email); setPhoneNumber(profile.phoneNumber); } } catch (error) { console.log('Error retrieving user profile:', error); } }; return ( <NavigationContainer style={styles.container}> <Tab.Navigator screenOptions={{ headerStyle: { backgroundColor: 'skyblue' }, headerTintColor: 'black', headerTitleStyle: { fontSize: 50 } }} initialRouteName="My Favourites"> <Tab.Screen name="Profile" options={{ tabBarIcon: ({ color }) => ( <MaterialCommunityIcons name="account" size={24} color={color} /> ), }}> {(props) => ( <ProfileJunaid {...props} setUsername={setUsername} setEmail={setEmail} setPhoneNumber={setPhoneNumber} username={username} email={email} phoneNumber={phoneNumber} storeUserProfile={storeUserProfile} /> )} </Tab.Screen> <Tab.Screen name="My Favourites" component={MyFavJunaid} options={{ tabBarIcon: ({ color }) => ( <MaterialCommunityIcons name="heart" size={24} color={color} /> ), }} /> <Tab.Screen name="My Todos" component={MyTodosJunaid} options={{ tabBarIcon: ({ color }) => ( <MaterialCommunityIcons name="check" size={24} color={color} /> ), }} /> <Tab.Screen name="Settings" component={SettingsJunaid} options={{ tabBarIcon: ({ color }) => ( <MaterialCommunityIcons name="account-settings" size={24} color={color} /> ), }} /> </Tab.Navigator> </NavigationContainer> ); } function ProfileJunaid({ setUsername, setEmail, setPhoneNumber, username, email, phoneNumber, storeUserProfile, }) { const [inputUsername, setInputUsername] = useState(username); const [inputEmail, setInputEmail] = useState(email); const [inputPhoneNumber, setInputPhoneNumber] = useState(phoneNumber); const handleSave = async () => { setUsername(inputUsername); setEmail(inputEmail); setPhoneNumber(inputPhoneNumber); await storeUserProfile(); }; const retrieveUserProfile = async () => { try { const profileString = await AsyncStorage.getItem('userProfile'); if (profileString !== null) { const profile = JSON.parse(profileString); setInputUsername(profile.username); setInputEmail(profile.email); setInputPhoneNumber(profile.phoneNumber); } } catch (error) { console.log('Error retrieving user profile:', error); } }; useEffect(() => { retrieveUserProfile(); }, []); return ( <View style={styles.textview}> <TextInput style={styles.input} onChangeText={(text) => setInputUsername(text)} value={inputUsername} placeholder="Enter username" /> <TextInput style={styles.input} onChangeText={(text) => setInputEmail(text)} value={inputEmail} placeholder="Enter email" /> <TextInput style={styles.input} onChangeText={(text) => setInputPhoneNumber(text)} value={inputPhoneNumber} placeholder="Enter phone number" /> <Button onPress={handleSave} title="Save" /> <View style={styles.container}> <Text style={styles.title}>Saved Data:</Text> <Text>Username: {username}</Text> <Text>Email: {email}</Text> <Text>Phone Number: {phoneNumber}</Text> </View> </View> ); } function MyFavJunaid() { const registrationNumber = '8'; const [favoritePosts, setFavoritePosts] = useState([]); useEffect(() => { fetchPosts(); }, []); const fetchPosts = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = await response.json(); const filteredPosts = data.filter((post) => post.userId.toString() === getUserIdFromRegNum(registrationNumber)); setFavoritePosts(filteredPosts); } catch (error) { console.log('Error fetching posts:', error); } }; const getUserIdFromRegNum = (regNum) => { const regNumParts = regNum.split('-'); return regNumParts[regNumParts.length - 1]; }; return ( <View style={styles.container}> <Text style={styles.heading}>My Favorite Posts</Text> {favoritePosts.length > 0 ? ( favoritePosts.map((post) => ( <View key={post.id} style={styles.postContainer}> <Text style={styles.title}>{post.title}</Text> <Text style={styles.body}>{post.body}</Text> </View> )) ) : ( <Text style={styles.noPostsText}>No favorite posts found.</Text> )} </View> ); } function MyTodosJunaid() { const registrationNumber = '8'; const [todos, setTodos] = useState([]); useEffect(() => { fetchTodos(); }, []); const fetchTodos = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos'); const data = await response.json(); const filteredTodos = data .filter((todo) => todo.userId.toString() === getUserIdFromRegNum(registrationNumber)) .slice(0, 5); setTodos(filteredTodos); } catch (error) { console.log('Error fetching todos:', error); } }; const getUserIdFromRegNum = (regNum) => { const regNumParts = regNum.split('-'); return regNumParts[regNumParts.length - 1]; }; const renderItem = ({ item }) => { const itemStyle = item.completed ? styles.completedTodo : styles.incompleteTodo; return ( <View style={[styles.todoContainer, itemStyle]}> <View style={styles.todoItem}> <View style={styles.todoStatus} /> <View style={styles.todoContent}> <View style={styles.todoHeader}> <Text style={styles.todoTitle}>{item.title}</Text> <Text style={styles.todoStatusText}>{item.completed ? 'Completed' : 'Incomplete'}</Text> </View> <Text style={styles.todoUserId}>User ID: {item.userId}</Text> </View> </View> </View> ); }; return ( <View style={styles.container}> <FlatList data={todos} renderItem={renderItem} keyExtractor={(item) => item.id.toString()} contentContainerStyle={styles.listContainer} /> </View> ); } function SettingsJunaid() { const [isDarkMode, setIsDarkMode] = useState(false); useEffect(() => { retrieveTheme(); }, []); const toggleTheme = (value) => { setIsDarkMode(value); storeTheme(value); }; const storeTheme = async (value) => { try { await AsyncStorage.setItem('theme', value.toString()); } catch (error) { console.log('Error storing theme:', error); } }; const retrieveTheme = async () => { try { const value = await AsyncStorage.getItem('theme'); if (value !== null) { setIsDarkMode(value === 'true'); } } catch (error) { console.log('Error retrieving theme:', error); } }; return ( <View style={[styles.container, isDarkMode ? styles.darkBackground : styles.lightBackground]}> <View style={styles.settingItem}> <Switch trackColor={{ false: '#767577', true: '#81b0ff' }} thumbColor={isDarkMode ? '#f5dd4b' : '#f4f3f4'} ios_backgroundColor="#3e3e3e" onValueChange={toggleTheme} value={isDarkMode} /> </View> </View> ); } const styles = StyleSheet.create({ textview: { marginTop: 50, textAlign: 'center', justifyContent: 'center', fontSize: 20, fontWeight: 'bold', fontStyle: 'italic', backgroundColor: '#fff', }, container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, profileContainer: { alignItems: 'center', justifyContent: 'center', marginBottom: 20, }, profilePicture: { width: 150, height: 150, borderRadius: 75, }, noProfilePictureText: { fontSize: 18, marginBottom: 10, }, input: { height: 40, width: '60%', borderColor: 'gray', borderWidth: 1, marginBottom: 10, paddingHorizontal: 10, marginTop: 10, marginLeft: 270 }, heading: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, }, postContainer: { borderWidth: 1, borderColor: '#ccc', borderRadius: 5, padding: 10, marginBottom: 10, }, title: { fontSize: 18, fontWeight: 'bold', marginBottom: 5, }, body: { fontSize: 16, }, noPostsText: { fontSize: 18, }, listContainer: { width: '100%', paddingHorizontal: 20, }, todoContainer: { marginBottom: 10, borderRadius: 5, padding: 10, }, completedTodo: { backgroundColor: 'green', }, incompleteTodo: { backgroundColor: 'red', }, todoItem: { flexDirection: 'row', alignItems: 'center', }, todoStatus: { width: 10, height: 10, borderRadius: 5, marginRight: 10, }, todoContent: { flex: 1, }, todoHeader: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 5, }, todoTitle: { fontWeight: 'bold', }, todoStatusText: { fontWeight: 'bold', }, todoUserId: { fontStyle: 'italic', }, settingItem: { flexDirection: 'row', alignItems: 'center', }, lightBackground: { backgroundColor: '#fff', }, darkBackground: { backgroundColor: '#000', }, });
const data = { global: { speed: 30 // ilośc klatek na sekundę }, left: { // lewa strona obrazu background: { color: [ [0, '#cbdeba'], // [procent położenia koloru, kolor] [100, '#fba976'], ] }, wave: { // fla czerwieni w górnej części enable: true, // widoczność direction: 'left', // kerunek ruchu frames: 3700, // ilość klatek na cały cykl - czym więcej tym wolniejszy ruch color: '#e2562d', shape: { length: 3.5, // ile razy dłuższa jest fala od szerokości okna, w któreym jest wyświetlana points: [ [0, 50], // [oś x 0-100, wysokość fali od -100 do 100] [20, 110], // wystaje poza zakres [40, 0], [60, 30], [80, -50], ], } }, dots: { // niebieskie kropki enable: true, frames: 1900, quantity: 80, // ilość kropek w poziomie color: '#658fa8', field: [100, 65, 85], // przesunięcie w bok, zakres 0-100 fold: { x: { // wysunięcie ku górze frames: 1700, field: [100, 75, 90] // zakres 0-100 }, y: { // szerokość fali frames: 2300, field: [100, 180, 280, 120, 170, 200] // zakres 0-10000 }, } } }, right: { // prawa stona ekranu background: { color: [ [0, '#ff8469'], // [procent położenia koloru, kolor] [50, '#ebb5a0'], [100, '#bfa881'], ] }, text: { // napis gilotyna enable: true, // widoczność }, wave: { // fala niebieska w dolnej części enable: true, direction: 'right', frames: 4300, color: '#4974af', shape: { length: 5.0, points: [ [0, 40], [20, 110], [37, 0], [50, 30], [64, -20], [85, 80], ], } } }, box: { // prostokąt przyciemniający enable: true, margin: { left: 9.83, // odstęp od lewej w procentach względem szerokości całego obrazu top: 8.6, // odstęp od góry w procentach względem wysokości całego obrazu right: 13.08, // odstęp od prawej w procentach względem szerokości całego obrazu bottom: 8.2, // odstęp od dołu w procentach względem wysokości całego obrazu }, colors: [ [0, '#4974af33'], // [procent położenia koloru, kolor] [20, '#fba97644'], [55, '#fba97666'], [80, '#ff846944'], [100, '#4974af1a'], ], }, startText: { // tekst start do ekranu startowego distance: 5, // przestrzeń między literami numItems: 3, frames: 100, } }
import Link from "next/link"; import React from "react"; import { Navigation } from "../components/nav"; import { Card } from "../components/card"; import { Article } from "./article"; async function getData() { const url = "https://api.notion.com/v1/databases/fef61c124cbb40c39b4755c10f401101/query"; const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "Notion-Version": "2022-02-22", Authorization: "Bearer " + process.env.NEXT_PUBLIC_NOTION_TOKEN, }, body: JSON.stringify({ filter: { property: "Status", status: { equals: "Published", }, }, sorts: [ { property: "Date", direction: "ascending", }, ], }), }); const data = await res.json(); return data; } export const revalidate = 60; export default async function ProjectsPage() { const data = await getData(); const allProjects = data.results; const featured = allProjects.find( (project) => project.properties.Rank.select && project.properties.Rank.select.name === "Featured" ); const top2 = allProjects.find( (project) => project.properties.Rank.select && project.properties.Rank.select.name === "First" ); const top3 = allProjects.find( (project) => project.properties.Rank.select && project.properties.Rank.select.name === "Second" ); const sorted = allProjects .filter((p) => p.properties.Status.status.name === "Published") .filter( (project) => project.properties.Slug.rich_text[0].plain_text !== featured.properties.Slug.rich_text[0].plain_text && project.properties.Slug.rich_text[0].plain_text !== top2.properties.Slug.rich_text[0].plain_text && project.properties.Slug.rich_text[0].plain_text !== top3.properties.Slug.rich_text[0].plain_text ) .sort( (a, b) => new Date(b.date ?? Number.POSITIVE_INFINITY).getTime() - new Date(a.date ?? Number.POSITIVE_INFINITY).getTime() ); return ( <div className="relative pb-16"> <Navigation /> <div className="px-6 pt-24 mx-auto space-y-8 max-w-7xl lg:px-8 md:space-y-16 lg:pt-32"> <div className="max-w-2xl mx-auto lg:mx-0"> <h2 className="text-3xl font-bold font-display tracking-tight text-zinc-800 sm:text-4xl"> Projects </h2> <p className="mt-4 text-zinc-700"> Some of the projects are from work and some are on my own time. </p> </div> <div className="w-full h-px bg-zinc-800" /> <div className="grid grid-cols-1 gap-8 mx-auto lg:grid-cols-2 "> <Card> <Link href={`/projects/${featured.properties.Slug.rich_text[0].plain_text}`} className="articleCard" > <article className="relative w-full h-full p-4 md:p-8"> <div className="flex items-center justify-between gap-2"> <div className="text-xs text-zinc-800"> {featured.properties.Date.date.start ? ( <time dateTime={new Date( featured.properties.Date.date.start ).toISOString()} > {Intl.DateTimeFormat( undefined, { dateStyle: "medium", } ).format( new Date( featured.properties.Date.date.start ) )} </time> ) : ( <span>SOON</span> )} </div> </div> <span id="featured-post" className="mt-4 text-3xl font-bold text-zinc-800 group-hover:text-black sm:text-4xl font-display link-underline" > { featured.properties.Title.title[0] .plain_text } </span> <p className="mt-4 leading-8 duration-150 text-zinc-700 group-hover:text-zinc-800"> {featured.properties.Description .rich_text[0] ? featured.properties.Description .rich_text[0].plain_text : ""} </p> <div className="absolute bottom-4 md:bottom-8"> <p className="hidden text-zinc-700 hover:text-zinc-800 lg:block"> Read more{" "} <span aria-hidden="true">&rarr;</span> </p> </div> </article> </Link> </Card> <div className="flex flex-col w-full gap-8 mx-auto border-t border-gray-900/10 lg:mx-0 lg:border-t-0 "> {[top2, top3].map((project) => ( <Card key={project.id}> <Article project={project} /> </Card> ))} </div> </div> <div className="hidden w-full h-px md:block bg-zinc-800" /> <div className="grid grid-cols-1 gap-4 mx-auto lg:mx-0 md:grid-cols-3"> <div className="grid grid-cols-1 gap-4"> {sorted .filter((_, i) => i % 3 === 0) .map((project) => ( <Card key={project.id}> <Article project={project} /> </Card> ))} </div> <div className="grid grid-cols-1 gap-4"> {sorted .filter((_, i) => i % 3 === 1) .map((project) => ( <Card key={project.id}> <Article project={project} /> </Card> ))} </div> <div className="grid grid-cols-1 gap-4"> {sorted .filter((_, i) => i % 3 === 2) .map((project) => ( <Card key={project.id}> <Article project={project} /> </Card> ))} </div> </div> </div> </div> ); }
@extends('layouts.main') @section('container') <div class="contiainer m-5"> <div class="row justify-content-center" style="margin-top: 150px;"> @if (session()->has('success')) <div class="alert alert-success" role="alert"> {{ session('success') }} <svg viewBox="0 0 24 24" width="32" height="32" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"> <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path> <polyline points="22 4 12 14.01 9 11.01"></polyline> </svg> <button type="button" class="btn-close float-end" aria-label="Close"></button> </div> @endif <div class="col-md-7 mb-3"> <h2 class="title-style"><strong>{{ $work->title }}</strong></h2> <p class="text-justify">Andro Mind adalah perusahaan manufaktur pembuat alat-alat uji Tanah, Beton, Aspal, Hidrologi dan Klimatologi terbaik di Indonesia, yang memiliki pengalaman lebih dari 0 tahun dan memiliki ribuan pelanggan di Indonesia.</p> <p class="text-justify">Dengan slogan "Good Product Good Service" kami berusaha untuk memberikan produk yang berkualitas dan pelayanan purna jual yang terbaik. Kami mengundang Anda untuk tumbuh bersama mencapai visi kami menjadi perusahaan manufaktur alat uji bertaraf multinasional. Saat ini kami membuka peluang karir sebagai {{ $work->title }}.</p> <h2 class="title-style">Job Description</h2> <p>{!! $work->jobdesk !!} </p> <h2 class="title-style">Ringkasan</h2> <div> <ul class="list-unstyled"> <li> <div class="icon-text"> <i class="bi bi-building bg-circle"></i> <div class="item-info"> <p><strong>Tingkat Pendidikan</strong></p> <p>{{ $work->education }}</p> </div> </div> </li> <li> <div class="icon-text"> <i class="bi bi-gender-ambiguous bg-circle"></i> <div class="item-info"> <p><strong>Gender</strong></p> <p>{{ $work->gender }}</p> </div> </div> </li> <li> <div class="icon-text"> <i class="bi bi-briefcase-fill bg-circle"></i> <div class="item-info"> <p><strong>Status Kerja</strong></p> <p>{{ $work->status }}</p> </div> </div> </li> <li> <div class="icon-text"> <i class="bi bi-calendar-check bg-circle"></i> <div class="item-info"> <p><strong>Batas Lamaran</strong></p> <p>{{ \Carbon\Carbon::parse($work->deadline)->formatLocalized('%d %B %Y') }}</p> </div> </div> </li> </ul> </div> <h2 class="title-style">Kriteria</h2> <p>{!! $work->kriteria !!}</p> <h2 class="title-style">Benefit</h2> <p>{{ $work->benefit }}</p> <p class="text-justify">Jika Anda merasa bahwa posisi {{ $work->title }} di Andro Mind tepat untuk Anda, maka jangan ragu untuk mengirimkan CV terbaru Anda ke <a href="mailto:[email protected]?subject={{ urlencode($work->title) }}">[email protected]</a> atau gunakan formulir pendaftaran di halaman ini.</p> </div> <div class="col-md-4"> <div class="card p-4 shadow"> <h4 class="mb-3">Sumbit Your Application</h4> <form action="/applywork" method="POST" enctype="multipart/form-data"> @csrf <input class="form-control @error('title') is-invalid @enderror" type="hidden" name="title" value="{{ $work->title }}"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 form-group mb-3"> <input class="form-control @error('name') is-invalid @enderror" type="text" name="name" placeholder="Nama Lengkap" required=""> @error('name') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group mb-3"> <input class="form-control @error('email') is-invalid @enderror" type="email" name="email" placeholder="Email" value="{{ old('email') }}"> @error('email') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group mb-3"> <input class="form-control @error('phone') is-invalid @enderror" type="text" name="phone" placeholder="No Handphone" value="{{ old('phone') }}"> @error('phone') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group mb-3"> <input class="form-control @error('education') is-invalid @enderror" type="text" name="education" placeholder="Pendidikan Terakhir" value="{{ old('education') }}"> @error('education') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group mb-3"> <input class="form-control @error('school') is-invalid @enderror" type="text" name="school" placeholder="Asal Sekolah / Universitas" value="{{ old('school') }}"> @error('school') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group mb-3"> <input class="form-control @error('major') is-invalid @enderror" type="text" name="major" placeholder="Jurusan" value="{{ old('major') }}"> @error('major') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group mb-3"> <label for="dokumen">CV dan Dokumen Lainnya</label> <input class="form-control" type="file" id="dokumen" name="cv" placeholder="CV dan Dokumen Lainnya"> </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group"> <button class="btn btn-primary" type="submit" name="submit"><span class="btn-title">Submit Now</span></button> </div> </div> </form> </div> </div> </div> </div> @endsection
<?php /** * Wishlist create popup * * @author YITH <[email protected]> * @package YITH\Wishlist\Templates\Wishlist * @version 3.0.0 */ /** * Template variables: * * @var $heading_icon string Heading icon HTML tag */ if ( ! defined( 'YITH_WCWL' ) ) { exit; } // Exit if accessed directly ?> <div id="create_new_wishlist"> <form method="post" action="<?php echo esc_url( YITH_WCWL()->get_wishlist_url( 'create' ) ); ?>"> <?php /** * DO_ACTION: yith_wcwl_before_wishlist_create * * Allows to render some content or fire some action before the wishlist creation options. */ do_action( 'yith_wcwl_before_wishlist_create' ); ?> <div class="yith-wcwl-popup-content"> <?php /** * APPLY_FILTERS: yith_wcwl_show_popup_heading_icon_instead_of_title * * Filter whether to show the icon in the 'Create wishlist' popup. * * @param bool $show_icon Whether to show icon or not * @param string $heading_icon Heading icon * * @return bool */ if ( apply_filters( 'yith_wcwl_show_popup_heading_icon_instead_of_title', ! empty( $heading_icon ), $heading_icon ) ) : ?> <p class="heading-icon"> <?php /** * APPLY_FILTERS: yith_wcwl_popup_heading_icon_class * * Filter the heading icon in the 'Create wishlist' popup. * * @param string $heading_icon Heading icon * * @return string */ echo yith_wcwl_kses_icon( apply_filters( 'yith_wcwl_popup_heading_icon_class', $heading_icon ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> </p> <?php else : ?> <h3><?php esc_html_e( 'Create a new wishlist', 'yith-woocommerce-wishlist' ); ?></h3> <?php endif; ?> <p class="popup-description"> <?php /** * APPLY_FILTERS: yith_wcwl_create_wishlist_label * * Filter the label to create a wishlist. * * @param string $label Label * * @return string */ echo esc_html( apply_filters( 'yith_wcwl_create_wishlist_label', __( 'Create a wishlist', 'yith-woocommerce-wishlist' ) ) ); ?> </p> <?php yith_wcwl_get_template_part( 'create' ); ?> </div> <?php /** * DO_ACTION: yith_wcwl_after_wishlist_create * * Allows to render some content or fire some action after the wishlist creation options. */ do_action( 'yith_wcwl_after_wishlist_create' ); ?> </form> </div>
import { Controller, Get, Post, Body, Param, Put, Delete, } from '@nestjs/common'; import { ProductService } from './product.service'; import { Product } from './product.model'; @Controller('product') export class ProductController { constructor(private readonly productService: ProductService) {} @Post() async create(@Body() createProductDto: Product): Promise<Product> { return this.productService.create(createProductDto); } @Get() async findAll(): Promise<Product[]> { return this.productService.findAll(); } @Get(':id') async findOne(@Param('id') id: string): Promise<Product> { return this.productService.findOne(id); } @Put(':id') async update( @Param('id') id: string, @Body() createProductDto: Product, ): Promise<Product> { return this.productService.update(id, createProductDto); } @Delete(':id') async remove(@Param('id') id: string): Promise<any> { return this.productService.delete(id); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="post.PostDAO"%> <%@ page import="post.PostDTO"%> <%@ page import="category.CategoryDAO"%> <%@ page import="category.CategoryDTO"%> <%@ page import="java.util.List"%> <!DOCTYPE html> <html> <%@ include file="layout/header.jsp"%> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote-lite.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote-lite.min.js"></script> <style> .category span { font-family: "Hanna"; font-size: 20px; } </style> <body> <% if (session.getAttribute("messageType") != null) { String Error = "오류 메세지"; String messageType = (String) session.getAttribute("messageType"); String msg = (String) session.getAttribute("messageContent"); if (messageType.equals(Error)) { %> <script>showErrorMessage('<%=msg%>');</script> <% } else { %> <script>showSuccessMessage('<%=msg%> '); </script> <% } } int category = 1; if (request.getParameter("category") != null) { category = Integer.parseInt(request.getParameter("category")); } %> <%@ include file="layout/navigation.jsp"%> <% if (session.getAttribute("messageType") != null) { session.removeAttribute("messageType"); session.removeAttribute("messageContent"); } ; %> <div class="container"> <div class="btn-group btn-group-justified" role="group" style="margin-bottom: 40px"> <% CategoryDAO categoryDAO = new CategoryDAO(); List<CategoryDTO> clist = categoryDAO.getList(); for (int i = 0; i < clist.size(); i++) { %> <% String cname = clist.get(i).getCname(); %> <div class="btn-group" role="group"> <% if(category == i + 1) { %> <button type="button" class="btn btn-default category active" onclick="location.href='postpage.jsp?category=<%=i + 1%>'"> <img src="image/<%=cname%>.png " alt="<%=i + 1%>" class="img-responsive"><span><%=cname%></span> </button> <%} else { %> <button type="button" class="btn btn-default category" onclick="location.href='postpage.jsp?category=<%=i + 1%>'"> <img src="image/<%=cname%>.png " alt="<%=i + 1%>" class="img-responsive"><span><%=cname%></span> </button> <%} %> </div> <% } %> </div> <div class="row"> <form method="post" action="writePostAction.jsp?category=<%=category%>"> <table class="table table-striped" style="text-align: center; border: 1px solid #dddddd"> <thead> <tr> <th style="background-color: #eeeeee; text-align: center; color: #000000;">글쓰기</th> </tr> </thead> <tbody> <tr> <td><input type="text" class="form-control" placeholder="글 제목" name="title"></td> </tr> <tr style="text-align: left"> <td> <textarea id="summernote" name="contents" style="all: none;" ></textarea> </td> </tr> </tbody> </table> <input type="submit" class="btn btn-primary pull-right" value="게시물 등록"> </form> </div> </div> </body> <script> $('#postpageActiveId').addClass("active"); $('#summernote').summernote({ placeholder: '글 내용', tabsize: 2, height: 500, minHeight: 500, lang: "ko_KR", maximumImageFileSize: 1024*1024, // 1MB callbacks:{ onImageUploadError: function(msg){ alert(msg + ' (1 MB)'); } } }); </script> </html>
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ package com.sun.tools.visualvm.modules.coherence.tablemodel.model; import com.sun.tools.visualvm.modules.coherence.VisualVMModel; import com.sun.tools.visualvm.modules.coherence.helper.HttpRequestSender; import com.sun.tools.visualvm.modules.coherence.helper.RequestSender; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.management.AttributeList; import javax.management.ObjectName; import static com.sun.tools.visualvm.modules.coherence.helper.JMXUtils.getAttributeValue; import static com.sun.tools.visualvm.modules.coherence.helper.JMXUtils.getAttributeValueAsString; /** * A class to hold basic cache size data. * * @author tam 2013.11.14 * @since 12.1.3 */ public class CacheData extends AbstractData { // ----- constructors --------------------------------------------------- /** * Create CacheData passing in the number of columns. * */ public CacheData() { super(UNIT_CALCULATOR + 1); } // ----- DataRetriever methods ------------------------------------------ /** * {@inheritDoc} */ public List<Map.Entry<Object, Data>> getJMXData(RequestSender sender, VisualVMModel model) { SortedMap<Object, Data> mapData = new TreeMap<Object, Data>(); Data data; try { // get the list of caches Set<ObjectName> cacheNamesSet = sender.getAllCacheMembers(); for (Iterator<ObjectName> cacheNameIter = cacheNamesSet.iterator(); cacheNameIter.hasNext(); ) { ObjectName cacheNameObjName = cacheNameIter.next(); String sCacheName = cacheNameObjName.getKeyProperty("name"); String sServiceName = cacheNameObjName.getKeyProperty("service"); String sDomainPartition = cacheNameObjName.getKeyProperty("domainPartition"); if (sDomainPartition != null) { sServiceName = getFullServiceName(sDomainPartition, sServiceName); } Pair<String, String> key = new Pair<String, String>(sServiceName, sCacheName); data = new CacheData(); data.setColumn(CacheData.SIZE, Integer.valueOf(0)); data.setColumn(CacheData.MEMORY_USAGE_BYTES, Long.valueOf(0)); data.setColumn(CacheData.MEMORY_USAGE_MB, Integer.valueOf(0)); data.setColumn(CacheData.CACHE_NAME, key); mapData.put(key, data); } // loop through each cache and find all the different node entries for the caches // and aggregate the information. for (Iterator cacheNameIter = mapData.keySet().iterator(); cacheNameIter.hasNext(); ) { Pair<String, String> key = (Pair<String, String>) cacheNameIter.next(); String sCacheName = key.getY(); String sRawServiceName = key.getX(); Set<String> setDistributedCache = model.getDistributedCaches(); if (setDistributedCache == null) { throw new RuntimeException("setDistributedCache must not be null. Make sure SERVICE is before CACHE in enum."); } boolean fIsDistributedCache = setDistributedCache.contains(sRawServiceName); String[] asServiceDetails = getDomainAndService(sRawServiceName); String sDomainPartition = asServiceDetails[0]; String sServiceName = asServiceDetails[1]; Set resultSet = sender.getCacheMembers(sServiceName, sCacheName, sDomainPartition); boolean fisSizeCounted = false; // indicates if non dist cache size has been counted for (Iterator iter = resultSet.iterator(); iter.hasNext(); ) { ObjectName objectName = (ObjectName) iter.next(); if (objectName.getKeyProperty("tier").equals("back")) { data = (CacheData) mapData.get(key); if (fIsDistributedCache || (!fIsDistributedCache && !fisSizeCounted)) { data.setColumn(CacheData.SIZE, (Integer) data.getColumn(CacheData.SIZE) + Integer.parseInt(sender.getAttribute(objectName, "Size"))); if (!fisSizeCounted) { fisSizeCounted = true; } } AttributeList listAttr = sender.getAttributes(objectName, new String[]{ CacheDetailData.ATTR_UNITS, CacheDetailData.ATTR_UNIT_FACTOR, MEMORY_UNITS}); data.setColumn(CacheData.MEMORY_USAGE_BYTES, (Long) data.getColumn(CacheData.MEMORY_USAGE_BYTES) + (Integer.parseInt(getAttributeValueAsString(listAttr, CacheDetailData.ATTR_UNITS)) * 1L * Integer.parseInt(getAttributeValueAsString(listAttr, CacheDetailData.ATTR_UNIT_FACTOR)))); // set unit calculator if its not already set if (data.getColumn(UNIT_CALCULATOR) == null) { boolean fMemoryUnits = Boolean.valueOf(getAttributeValue(listAttr, MEMORY_UNITS).toString()); data.setColumn(CacheData.UNIT_CALCULATOR, fMemoryUnits ? "BINARY" : "FIXED"); } mapData.put(key, data); } } // update the cache entry averages data = (CacheData) mapData.get(key); // for FIXED unit calculator make the memory bytes and MB and avg object size null if (data.getColumn(CacheData.UNIT_CALCULATOR).equals("FIXED")) { data.setColumn(CacheData.AVG_OBJECT_SIZE, Integer.valueOf(0)); data.setColumn(CacheData.MEMORY_USAGE_BYTES, Integer.valueOf(0)); data.setColumn(CacheData.MEMORY_USAGE_MB, Integer.valueOf(0)); } else { if ((Integer) data.getColumn(CacheData.SIZE) != 0) { data.setColumn(CacheData.AVG_OBJECT_SIZE, (Long) data.getColumn(CacheData.MEMORY_USAGE_BYTES) / (Integer) data.getColumn(CacheData.SIZE)); } Long nMemoryUsageMB = ((Long) data.getColumn(CacheData.MEMORY_USAGE_BYTES)) / 1024 / 1024; data.setColumn(CacheData.MEMORY_USAGE_MB, Integer.valueOf(nMemoryUsageMB.intValue())); } mapData.put(key, data); } return new ArrayList<>(mapData.entrySet()); } catch (Exception e) { LOGGER.log(Level.WARNING, "Error getting cache statistics", e); return null; } } /** * {@inheritDoc} */ public String getReporterReport() { return null; // until the following JIRA is fixed we cannot implement this // COH-10175: Reporter does not Correctly Display Size of Replicated Or Optimistic Cache // return REPORT_CACHE_SIZE; } /** * {@inheritDoc} */ public Data processReporterData(Object[] aoColumns, VisualVMModel model) { Data data = new CacheData(); // the identifier for this row is the service name and cache name Pair<String, String> key = new Pair<String, String>(aoColumns[2].toString(), aoColumns[3].toString()); data.setColumn(CacheData.CACHE_NAME, key); data.setColumn(CacheData.SIZE, new Integer(getNumberValue(aoColumns[4].toString()))); data.setColumn(CacheData.MEMORY_USAGE_BYTES, new Long(getNumberValue(aoColumns[5].toString()))); data.setColumn(CacheData.MEMORY_USAGE_MB, new Integer(getNumberValue(aoColumns[5].toString())) / 1024 / 1024); if (aoColumns[7] != null) { data.setColumn(CacheData.AVG_OBJECT_SIZE, new Integer(getNumberValue(aoColumns[7].toString()))); } else { data.setColumn(CacheData.AVG_OBJECT_SIZE, Integer.valueOf(0)); } return data; } @Override public SortedMap<Object, Data> getAggregatedDataFromHttpQuerying(VisualVMModel model, HttpRequestSender requestSender) throws Exception { // no reports being used, hence using default functionality provided in getJMXData return null; } /** * {@inheritDoc} */ @Override protected SortedMap<Object, Data> postProcessReporterData(SortedMap<Object, Data> mapData, VisualVMModel model) { Set<String> setDistributedCache = model.getDistributedCaches(); if (setDistributedCache == null) { throw new RuntimeException("setDistributedCache must not be null. Make sure SERVICE is before CACHE in enum."); } // we need to check to see if this cache is not a distributed cache and adjust the // size accordingly - The problem is that currently we have no way of identifying the number of storage // enabled members - so this is currently going to report incorrect sizes for Replicated or Optomistic // caches return mapData; } // ----- constants ------------------------------------------------------ private static final long serialVersionUID = 6427775621469258645L; /** * Array index for cache name. */ public static final int CACHE_NAME = 0; /** * Array index for cache size. */ public static final int SIZE = 1; /** * Array index for memory usage in bytes. */ public static final int MEMORY_USAGE_BYTES = 2; /** * Array index for memory usage in MB. */ public static final int MEMORY_USAGE_MB = 3; /** * Array index for average object size. */ public static final int AVG_OBJECT_SIZE = 4; /** * Array index for unit calculator. */ public static final int UNIT_CALCULATOR = 5; /** * The logger object to use. */ private static final Logger LOGGER = Logger.getLogger(CacheData.class.getName()); /** * Attribute for "MemoryUnits". */ private static final String MEMORY_UNITS = "MemoryUnits"; }
using HotelBooking.Domain.Models.Hotel; namespace HotelBooking.Infrastructure.Tables { /// <inheritdoc cref="HotelDTO"/> internal class HotelTable : DbEntity { /// <inheritdoc cref="HotelDTO.Name"/> public string Name { get; set; } /// <inheritdoc cref="HotelDTO.BriefDescription"/> public string BriefDescription { get; set; } /// <inheritdoc cref="HotelDTO.FullDescription"/> public string FullDescription { get; set; } /// <inheritdoc cref="HotelDTO.StarRating"/> public float StarRating { get; set; } /// <inheritdoc cref="HotelDTO.OwnerName"/> public string OwnerName { get; set; } /// <inheritdoc cref="HotelDTO.Geolocation"/> public string Geolocation { get; set; } /// <inheritdoc cref="HotelDTO.CreationDate"/> public DateTime CreationDate { get; set; } /// <inheritdoc cref="HotelDTO.ModificationDate"/> public DateTime ModificationDate { get; set; } /// <inheritdoc cref="HotelDTO.CityId"/> public Guid CityId { get; set; } public CityTable City { get; set; } public List<HotelReviewTable> Reviews { get; } = new(); public List<RoomTable> Rooms { get; } = new(); public List<DiscountTable> Discounts { get; } = new(); public List<HotelVisitTable> Visits { get; } = new(); } }
package github.makeitvsolo.fstored.user.access.application.usecase.access; import github.makeitvsolo.fstored.user.access.application.FstoredUserAccessApplicationUnitTest; import github.makeitvsolo.fstored.user.access.application.encoding.Encode; import github.makeitvsolo.fstored.user.access.application.persistence.UserRepository; import github.makeitvsolo.fstored.user.access.application.session.CreateSessionToken; import github.makeitvsolo.fstored.user.access.application.session.SessionRepository; import github.makeitvsolo.fstored.user.access.application.session.TestSessionToken; import github.makeitvsolo.fstored.user.access.application.usecase.access.dto.AccessTokenDto; import github.makeitvsolo.fstored.user.access.application.usecase.access.dto.UserCredentialsDto; import github.makeitvsolo.fstored.user.access.application.usecase.access.dto.UserDto; import github.makeitvsolo.fstored.user.access.application.usecase.access.exception.InvalidUserPasswordException; import github.makeitvsolo.fstored.user.access.application.usecase.access.exception.UserDoesNotExistsException; import github.makeitvsolo.fstored.user.access.domain.User; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; public class SignInUserUsecaseTests extends FstoredUserAccessApplicationUnitTest { @Mock private UserRepository userRepository; @Mock private SessionRepository<TestSessionToken> sessionRepository; @Mock private CreateSessionToken<TestSessionToken> userSession; @Mock private Encode security; @InjectMocks private SignInUserUsecase<TestSessionToken> usecase; @Mock private TestSessionToken session; @Test public void invoke_SavesSession() { var existingUser = new User("user id", "name", "passwd"); var payload = new UserCredentialsDto("name", "passwd"); var expected = new AccessTokenDto( session.token(), session.expiresAt(), new UserDto(existingUser.id(), existingUser.name()) ); when(userRepository.findByName(payload.name())) .thenReturn(Optional.of(existingUser)); when(security.matches(payload.password(), existingUser.password())) .thenReturn(true); when(userSession.createFor(existingUser)) .thenReturn(session); var actual = usecase.invoke(payload); verify(sessionRepository).save(session); assertEquals(expected, actual); } @Test public void invoke_Throws_WhenUserDoesNotExists() { var payload = new UserCredentialsDto("name", "passwd"); when(userRepository.findByName(payload.name())) .thenReturn(Optional.empty()); assertThrows(UserDoesNotExistsException.class, () -> usecase.invoke(payload)); } @Test public void invoke_Throws_WhenPasswordIsInvalid() { var existingUser = new User("user id", "name", "passwd"); var payload = new UserCredentialsDto("name", "passwd"); when(userRepository.findByName(payload.name())) .thenReturn(Optional.of(existingUser)); when(security.matches(payload.password(), existingUser.password())) .thenReturn(false); assertThrows(InvalidUserPasswordException.class, () -> usecase.invoke(payload)); } }
const express = require("express"); const userRouter = express.Router(); const { Account, User } = require("../db"); const { signIn, signUp, update } = require("../types"); const jwt = require("jsonwebtoken"); const { JWT_SECRET } = require("../config"); const { authMiddleware } = require("../middleware"); userRouter.post("/signup", async (req, res) => { const userData = req.body; const { success } = signUp.safeParse(userData); console.log(success); if(!success) { return res.status(411).json({ message: "Email already taken / Incorrect inputs" }); } const existingUser = await User.findOne({ username: userData.username }) if(existingUser) { return res.status(411).json({ message: "Email already taken / Incorrect inputs" }) } const user = await User.create({ username: req.body.username, password: req.body.password, firstName: req.body.firstName, lastName: req.body.lastName }) const userId = user._id; await Account.create({ userId, balance: 1 + Math.random() * 10000 }); const token = jwt.sign({ userId }, JWT_SECRET); res.status(200).json({ message: "User created successfully", token: token }) }); userRouter.post("/signin", async (req, res) => { const body = req.body; const { success } = signIn.safeParse(body); if(!success) { return res.status(411).json({ message: "Incorrect Inputs" }) } const isUserExist = await User.findOne({ username: body.username, password: body.password }) console.log(isUserExist); if(!isUserExist) { return res.status(411).json({ message: "Error while logging in" }) } const userId = isUserExist._id; const token = jwt.sign({userId}, JWT_SECRET); return res.status(200).json({ token: token }) }); userRouter.put("/", authMiddleware, async (req, res) => { const { success } = update.safeParse(req.body) if (!success) { res.status(411).json({ message: "Error while updating information" }) } await User.updateOne({ _id: req.userId }, req.body); res.json({ message: "Updated successfully" }) }) userRouter.get("/bulk", async (req, res) => { const filter = req.query.filter || ""; const users = await User.find({ $or: [{ firstName: { "$regex": filter }, }, { lastName: { "$regex": filter } }] }) res.status(200).json({ user: users.map((user) => ({ username: user.username, firstName: user.firstName, lastName: user.lastName, _id: user._id })) }) }) module.exports = userRouter;
import { useReducer } from 'react'; import { createSlice } from '@/utils/react/create-slice'; type GlobalStateType = { value: number; additionIsCorrect: boolean; methodIsCorrect: boolean; }; const initialState: GlobalStateType = { value: 0, additionIsCorrect: false, methodIsCorrect: false, }; const { reducer } = createSlice({ initialState, reducers: { RESET: () => initialState, SET_VALUE: (state, payload: number) => { state.value = payload; }, SET_METHOD_IS_CORRECT: (state, payload: boolean) => { state.methodIsCorrect = payload; }, SET_ADDITION_IS_CORRECT: (state, payload: boolean) => { state.additionIsCorrect = payload; }, }, }); export const useEvaluationDetailPageState = () => { const [state, dispatch] = useReducer(reducer, initialState); return { state, dispatch }; };
// Wayfinder import SwiftUI import os struct BestOfReportView: View { @ObservedObject var store: Store @State public var selectedBestWorst: BestWorst = .best @State public var selectedCategory: Category = .activity @State public var selectedCategoryValue: String = "" @State public var selectedMetric: Metric = .combined public var wasUpdated: Binding<Bool>? @State private var result: [Reflection] = [] @State private var errorMessage: ErrorMessage? @State private var isPresented: Bool = false @State private var isDetailPresented: Bool = false @State private var reflectionToEdit: Reflection? private func updateBestOf() { func processResult(results: Result<[Reflection], Error>) { switch results { case .failure(let error): Logger().error("\(error.localizedDescription)") case .success(let result): self.result = result } } let inclusionComparator = selectedCategory.makeInclusionComparator(selectedCategoryValue) store.makeBestOfReport(inclusionComparator, by: selectedMetric, direction: selectedBestWorst, completion: processResult) } func updateAction(reflection: Reflection) -> Void { store.update(reflection: reflection) { error in if let error = error { errorMessage = ErrorMessage(title: "Update Error", message: "\(error)") } updateBestOf() wasUpdated?.wrappedValue = true } } var body: some View { VStack { VStack { HStack { Menu(content: { Picker(selection: $selectedBestWorst, label: Text(selectedBestWorst.rawValue.capitalized)) { ForEach(BestWorst.allCases) { bestWorst in Text(bestWorst.rawValue.capitalized).tag(bestWorst) } } }, label: { Text(selectedBestWorst.rawValue.capitalized) }) .onChange(of: selectedBestWorst, perform: {_ in updateBestOf()}) Text("of a \(store.activeAxis)") Menu(content: { Picker(selection: $selectedCategory, label: Text(selectedCategory.rawValue.capitalized)) { ForEach(Category.allCases) { category in Text(category.rawValue.capitalized).tag(category) } } }, label: { Text(selectedCategory.rawValue.capitalized) }) .onChange(of: selectedCategory, perform: {_ in updateBestOf()}) Spacer() } .font(.title) .padding([.top, .bottom]) HStack { Button(action: { isPresented = true }) { NamePickerField(name: selectedCategoryValue, prompt: selectedCategory.choicePrompt, font: .title2) .onChange(of: selectedCategoryValue, perform: {_ in updateBestOf()}) .padding([.leading, .trailing]) .background(RoundedRectangle(cornerRadius: 8).foregroundColor(Color.secondary.opacity(0.15))) } Spacer() } Picker("Metric", selection: $selectedMetric) { ForEach(Metric.allCases) { metric in Text(metric.rawValue.capitalized).tag(metric) } } .onChange(of: selectedMetric, perform: {_ in updateBestOf()}) .pickerStyle(SegmentedPickerStyle()) // TODO add date range toggle. Off = any. On = can choose. Or another picker? } .padding() List { if !result.isEmpty { // https://stackoverflow.com/questions/59295206/how-do-you-use-enumerated-with-foreach-in-swiftui ForEach(Array(zip(result.indices, result)), id: \.0) { index, r in Button(action: { reflectionToEdit = r isDetailPresented = true }) { HStack { Text("\(index + 1)") .font(.caption) CardView(reflection: r) let date = r.data.date let components = Calendar.current.dateComponents([.month, .day, .year], from: date) VStack { Text("\(MonthShortNames[components.month!] ?? "") \(components.day!)") Text(String(components.year!)) } .font(.caption) } } } } else { Text("No reflections found") } } .edgesIgnoringSafeArea([.leading, .trailing]) // Very silly. // Seems to be bug with nullable state variables. // Value won't stay set without this // https://developer.apple.com/forums/thread/652080 let _ = "\(reflectionToEdit ?? Reflection.exampleData[0])" Spacer() } .onAppear(perform: updateBestOf) .sheet(isPresented: $isPresented, onDismiss: updateBestOf) { switch selectedCategory { case .activity: NamePicker($selectedCategoryValue, nameOptions: store.activityNames, prompt: "Choose Activity", canCreate: false, parentIsPresenting: $isPresented) case .tag: NamePicker($selectedCategoryValue, nameOptions: store.tagNames, prompt: "Choose Tag", canCreate: false, parentIsPresenting: $isPresented) } } .sheet(isPresented: $isDetailPresented) { if let r = reflectionToEdit { DetailView( store: store, reflection: r, saveAction: updateAction, parentIsPresenting: $isDetailPresented ) } else { EmptyView() } } .alert(item: $errorMessage) { msg in msg.toAlert() } } } struct BestOfReportView_Previews: PreviewProvider { static var previews: some View { BestOfReportView(store: Store.createExample()) } }
# # @lc app=leetcode id=823 lang=python3 # # [823] Binary Trees With Factors # # @lc code=start # * DP Solution | O(n^2) Time | O(n) Space # * n -> Length of arr array class Solution: def numFactoredBinaryTrees(self, arr: List[int]) -> int: MOD = 10 ** 9 + 7 arr.sort() dp = [1] * len(arr) index_mappings = {num: i for i, num in enumerate(arr)} for i in range(len(arr)): for j in range(i): if arr[i] % arr[j] == 0 and arr[i] // arr[j] in index_mappings: dp[i] += dp[j] * dp[index_mappings[arr[i] // arr[j]]] dp[i] %= MOD return sum(dp) % MOD # @lc code=end
import { useEffect, useState } from 'react'; import { IBest250FilmsResponse, IFilm } from '../services/film/film.interface'; import { FilmService } from '../services/film/film.services'; export const useFilms = (page: number = 1) => { const [response, setResponse] = useState<IBest250FilmsResponse>({ docs: [], limit: 0, page: 0, pages: 0, total: 0, }); const [isLoading, setIsLoading] = useState(true); useEffect(() => { const fetchFilms = async () => { try { const response = await FilmService.getFilms(page); setResponse(response); setIsLoading(false); } catch (error) { setIsLoading(false); console.error('Failed to fetch films:', error); } }; fetchFilms(); }, [page]); return { response, isLoading }; };
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:gallery_poc/models/image.dart'; import 'package:gallery_poc/services/logger.dart'; import 'package:http/http.dart' as http; class GalleryController extends ChangeNotifier { static const String apiUrl = "pixabay.com"; final List<HitImage> _images = []; String _searchQuery = ""; bool _isLoading = false; GalleryController() { logger.i('Gallery Controller initiated'); browseImages(); } set setSearchQuery(String value) { logger.i('Changing search query...'); _searchQuery = value; notifyListeners(); } String get searchQuery => _searchQuery; bool get isLoading => _isLoading; List<HitImage> get images => _images; Future<void> browseImages() async { logger.i("Browsing..."); _images.clear(); _isLoading = true; notifyListeners(); final response = await http.get(Uri.https(apiUrl, '/api/', {"key": dotenv.env['PIXABAY_APIKEY'], "q": _searchQuery})); final hits = json.decode(response.body)['hits'] as List<dynamic>; populateImages(hits); } void populateImages(List<dynamic> hits) { logger.i("Populating..."); for (final hit in hits) { _images.add(HitImage.fromJson(hit)); } _isLoading = false; logger.i("Populated"); notifyListeners(); } }
<?php if ( ! defined( 'ABSPATH' ) ) { exit; } // Exit if accessed directly /** * Plugin Name: Ollie Pro * Plugin URI: https://github.com/OllieWP/ollie-pro * Description: The Ollie Pro plugin extends the Ollie theme with additional features. * Version: 1.0 * Author: buildwithollie * Author URI: https://olliewp.com * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt * Text Domain: ollie-pro * Domain Path: /languages * */ define( 'OLPO_PATH', untrailingslashit( plugin_dir_path( __FILE__ ) ) ); define( 'OLPO_URL', untrailingslashit( plugin_dir_url( __FILE__ ) ) ); define( 'OLPO_VERSION', '1.0' ); // localize. add_action( 'init', function () { $textdomain_dir = plugin_basename( dirname( __FILE__ ) ) . '/languages'; load_plugin_textdomain( 'ollie-pro', false, $textdomain_dir ); } ); // GitHub Updater. require OLPO_PATH . '/inc/plugin-update-checker/plugin-update-checker.php'; use YahnisElsts\PluginUpdateChecker\v5\PucFactory; $update_checker = PucFactory::buildUpdateChecker( 'https://github.com/OllieWP/ollie-pro/', __FILE__, 'ollie-pro' ); $update_checker->setBranch('main'); // run plugin. if ( ! function_exists( 'olpo_run_plugin' ) ) { add_action( 'plugins_loaded', 'olpo_run_plugin' ); /** * Run plugin * * @return void */ function olpo_run_plugin() { // Get the current theme. $theme = wp_get_theme(); if ( 'ollie' === $theme->template ) { require_once( OLPO_PATH . '/inc/class-olpo-settings.php' ); require_once( OLPO_PATH . '/inc/class-olpo-helper.php' ); olpo\Settings::get_instance(); olpo\Helper::get_instance(); } else { // Add admin notice. add_action( 'admin_notices', function () { $message = sprintf( __( 'The Ollie Pro plugin needs the free Ollie theme to work. View the theme and install it %s.', 'ollie-pro' ), '<a href=' . esc_url( admin_url( 'theme-install.php?search=ollie' ) ) . '>by clicking here</a>' ); echo wp_kses_post( '<div class="notice notice-error"><p>' . $message . '</p></div>' ); } ); } } add_action( 'init', 'olpo_register_pattern_block' ); function olpo_register_pattern_block() { // Register scripts. $olpo_asset_file = include( plugin_dir_path( __FILE__ ) . 'build/pattern-block/index.asset.php' ); wp_register_script( 'ollie-pattern-block', plugins_url( 'build/pattern-block/index.js', __FILE__ ), $olpo_asset_file['dependencies'], $olpo_asset_file['version'] ); // Register block. register_block_type( __DIR__ . '/build/pattern-block' ); // Enqueue scripts. wp_enqueue_media(); wp_enqueue_script( 'ollie-pattern-block', plugins_url( 'build/pattern-block/index.js', __FILE__ ), $olpo_asset_file['dependencies'], $olpo_asset_file['version'] ); wp_enqueue_style( 'ollie-pattern-block-style', plugins_url( 'build/pattern-block/index.css', __FILE__ ) ); require_once( OLPO_PATH . '/inc/class-olpo-helper.php' ); $args = array( 'version' => OLPO_VERSION, 'downloaded_patterns' => olpo\Helper::get_downloaded_patterns() ); wp_localize_script( 'ollie-pattern-block', 'ollie_pattern_options', $args ); // Make the blocks translatable. if ( function_exists( 'wp_set_script_translations' ) ) { wp_set_script_translations( 'ollie-pattern-block', 'ollie-pro', OLPO_PATH . '/languages' ); } } }
/* 采用channel作为模块之间的通信方式。虽然channel可以传递任何数据类型,甚至包括另外一个channel, 但为了让架构更容易拆分,这里严格限制了只能用于传递JSON格式的字符串类型数据。这样如果之后想将这 样的单进程示例修改为多进程的分布式架构,也不需要全部重写,只需替换通信层即可 */ package ipc import ( "encoding/json" "fmt" ) type Request struct { Method string "method" Params string "params" } type Response struct { Code string "code" Body string "body" } type Server interface { Name() string Handle(method, params string) *Response } type IpcServer struct { Server } func NewIpcServer(server Server) *IpcServer { return &IpcServer{server} } func (server *IpcServer) Connect() chan string { session := make(chan string, 0) go func(c chan string) { for { request := <-c if request == "CLOSE" { // 关闭该连接 break } var req Request err := json.Unmarshal([]byte(request), &req) if err != nil { fmt.Println("Invalid request format:", request) } resp := server.Handle(req.Method, req.Params) b, err := json.Marshal(resp) c <- string(b) // 返回结果 } fmt.Println("Session closed.") }(session) fmt.Println("A new session has been created successfully.") return session }
using UnityEngine; using System.Collections; using System.Collections.Generic; using VokeySharedEntities; using System.ComponentModel; using System.Threading; public class LoadStreet : MonoBehaviour { public GameObject HousePrefab; public UIAtlas Atlas; private static bool IsDone = false; private Town town = null; private string result = ""; // Use this for initialization void Start() { Debug.Log("LoadStreet::Start"); Street.Streets.Clear(); Vector3 roadPosition = Street.RoadCoordinates; Vector3 streetPosition = Street.StartingCoordinates; // Get town object town = GetVokeyObject<Town>("town"); if (town != null) { foreach (VokeySharedEntities.Street s in town.streets) { Debug.Log("Street: " + s.name + ", ID: " + s.id + ", Houses: " + s.houses.Count); VokeySharedEntities.Street street = GetVokeyObject<VokeySharedEntities.Street>("town/" + town.id + "/street/" + s.id); Street.Streets.Add(street); } // foreach street contained in town object for (int i = 0; i < Street.Streets.Count; i++) { // Create road GameObject road = GameObject.CreatePrimitive(PrimitiveType.Plane); road.transform.position = roadPosition; road.transform.localScale = new Vector3(5, 1, 200); road.name = "Road"; MeshRenderer mr = road.GetComponent<MeshRenderer>(); mr.material = Resources.Load("Materials/Concrete_Block_8x8_Gray_") as Material; // Create the streets CreateSingleStreet(streetPosition, Street.Streets[i].houses); streetPosition.x -= Street.StreetIncrement; roadPosition.x -= Street.StreetIncrement; } } // Request current users assignments AssignmentList assignments = GetVokeyObject<AssignmentList>("assignment"); // Scale and position Sprite as background UISprite backgroundSprite = ((GameObject)GameObject.Find("AssignmentListBackground")).GetComponent<UISprite>(); backgroundSprite.transform.localScale = new Vector3(300, assignments.TodoAssignments.Count * 45 + 45); // Create and position labels (assignments) for (int i = 0; i < assignments.TodoAssignments.Count; i++) { GameObject Anchor = (GameObject)GameObject.Find("AssignmentAnchor"); // Create the button GameObject assignment = new GameObject("assignment"); assignment.AddComponent<BoxCollider>(); assignment.AddComponent<UIButton>(); assignment.AddComponent<UIButtonScale>(); assignment.AddComponent<UIButtonOffset>(); assignment.AddComponent<UIButtonSound>(); AssignmentClicked clicked = assignment.AddComponent<AssignmentClicked>(); clicked.assignment = assignments.TodoAssignments[i]; assignment.transform.parent = Anchor.transform; assignment.layer = Anchor.layer; assignment.transform.localScale = new Vector3(1, 1, 1); assignment.transform.position = new Vector3(42, -60 - (i * 45), 1); // -15 assignment.transform.localPosition = assignment.transform.position; // Create the label GameObject lbl = new GameObject("assignment-label"); lbl.layer = Anchor.layer; lbl.AddComponent<UILabel>(); UILabel label = lbl.GetComponent<UILabel>(); label.transform.parent = assignment.transform; label.pivot = UIWidget.Pivot.TopLeft; label.transform.position = new Vector3(0, 0, 1); label.transform.localPosition = label.transform.position; label.transform.localScale = new Vector3(28, 28, 1); label.depth = 1; label.text = assignments.TodoAssignments[i].name; label.font = ((GameObject)Resources.Load("Atlases/Fantasy/Fantasy Font - Normal")).GetComponent<UIFont>(); /* // Create the sprite GameObject sprt = new GameObject("assignment-sprite"); sprt.AddComponent<UISprite>(); UISprite sprite = sprt.GetComponent<UISprite>(); sprite.transform.parent = assignment.transform; sprite.pivot = UIWidget.Pivot.TopLeft; sprite.transform.position = new Vector3(42, -15 - (i * 45), 1); sprite.transform.localPosition = sprite.transform.position; sprite.transform.localScale = new Vector3(label.transform. */ // Set up the box collider BoxCollider box = assignment.GetComponent<BoxCollider>(); box.center = new Vector3(140, -15, 0); // -15 box.size = new Vector3(280, 28, 0); } } // Update is called once per frame void Update() { } public T GetVokeyObject<T>(string r) { T vokeyObject = default(T); GetObject(r); while (!IsDone) { } if (result != null && result != string.Empty) { vokeyObject = MySerializerOfItems.FromXml<T>(result); result = null; } else { // Error Debug.Log("Result is empty / null"); } return vokeyObject; } public void GetObject(string request) { byte[] b = { 0x10, 0x20 }; Hashtable hash = new Hashtable(); hash.Add("Session", GlobalSettings.SessionID); hash.Add("Content-Type", "text/html"); WWW response = new WWW(GlobalSettings.serverURL + request, b, hash); while (!response.isDone) { if (!string.IsNullOrEmpty(response.error)) { //Messenger.Broadcast(VokeyMessage.REQUEST_FAIL, response.error); return; } } result = response.text; IsDone = response.isDone; } void CreateSingleStreet(Vector3 StartingCoordinates, List<House> Houses) { Quaternion rot = Quaternion.Euler(new Vector3(-90, -90, 0)); for (int i = 0; i < Houses.Count; i++) { GameObject house = (GameObject)Instantiate(HousePrefab, StartingCoordinates + new Vector3(0, 0, i * Street.HouseIncrement), rot); house.name = Houses[i].name; // Assign a student name to the house house.AddComponent<MeshCollider>(); house.AddComponent<StreetHouse>(); house.GetComponent<StreetHouse>().Atlas = Atlas; house.GetComponent<StreetHouse>().House = Houses[i]; } } /// <summary> /// Changes the color of a house part. /// </summary> /// <param name='house'> /// The house to change the color of. /// </param> /// <param name='newColor'> /// The new color of the house part. /// The RGB values have to be between 1.0f and 255.0f and/or normalized between 0,0f and 1,0f /// </param> /// <param name='housePart'> /// The part of the house to recolor. Part names are : 'Wall', 'Door', 'Roof', 'Windows', 'Venster' /// </param> void ChangeHousePartColor(GameObject house, string housePart, Color newColor) { Color normalizedColor = NormalizeColor(newColor); if (housePart.ToLower().Equals("windows")) { // we want to have the windows always the same alfa value normalizedColor.a = 100.0f / 255.0f; } // iterate through the materials until the right material has been found for (int iMat = 0; iMat < house.renderer.materials.Length; iMat++) { if (house.renderer.materials[iMat].name.ToLower().StartsWith(housePart.ToLower())) { house.renderer.materials[iMat].SetColor("_Color", normalizedColor); } } } /// <summary> /// Normalizes the color. ( a value between 0.0f and 1.0f ) /// </summary> /// <returns> /// The Normalized color. /// </returns> /// <param name='color'> /// A color. /// </param> private Color NormalizeColor(Color color) { Color newColor = new Color(color.r, color.g, color.b, color.a); while (newColor.r > 1.0f || newColor.g > 1.0f || newColor.b > 1.0f) { if (newColor.r > 1.0f) { newColor.r = newColor.r / 255.0f; } if (newColor.g > 1.0f) { newColor.g = newColor.g / 255.0f; } if (newColor.b > 1.0f) { newColor.b = newColor.b / 255.0f; } } Debug.Log("Normalized RGB: " + newColor.r + "," + newColor.g + "," + newColor.b); return newColor; } }
package com.example.demo.config; import com.example.demo.discount.DiscountPolicy; import com.example.demo.discount.FixDiscountPolicy; import com.example.demo.member.MemberRepository; import com.example.demo.member.MemberService; import com.example.demo.member.MemberServiceImpl; import com.example.demo.member.MemoryMemberRepository; import com.example.demo.order.OrderService; import com.example.demo.order.OrderServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class SpringAppConfig { @Bean public MemberService memberService() { return new MemberServiceImpl(memberRepository()); } @Bean public MemberRepository memberRepository() { return new MemoryMemberRepository(); } @Bean public OrderService orderService() { return new OrderServiceImpl(memberRepository(), discountPolicy()); } @Bean public DiscountPolicy discountPolicy() { return new FixDiscountPolicy(); } }
import React, { useEffect, useState } from 'react'; import axios from 'axios'; import DensityMediumIcon from '@mui/icons-material/DensityMedium'; import HomeOutlinedIcon from '@mui/icons-material/HomeOutlined'; import SubscriptionsOutlinedIcon from '@mui/icons-material/SubscriptionsOutlined'; import LiveTvOutlinedIcon from '@mui/icons-material/LiveTvOutlined'; import FavoriteBorderOutlinedIcon from '@mui/icons-material/FavoriteBorderOutlined'; import FooterPage from './footer'; import LoginPage from '../auth/login'; import '../../index.css'; const userString = localStorage.getItem('user'); const user = userString ? JSON.parse(userString) : null; // Trả về giá trị đăng nhập const login = localStorage.getItem('login'); const MenuPage = ({ closeModal }) => { const handleBackdropClick = (event) => { if (event.target === event.currentTarget) { closeModal(); // Gọi hàm closeModal khi nhấp vào nền } }; const [categories, setCategories] = useState([]); useEffect(() => { axios .get('http://localhost:5000/api/admin/categories') .then((response) => { // console.log(response.data); const categoriesData = response.data; setCategories(categoriesData); }) .catch((error) => { console.error(error); }); }, []); const [isLoginModal, setIsLoginModal] = useState(false); const openLoginModal = () => { if (login === "true") { setIsLoginModal(false); } else { setIsLoginModal(true); } }; const closeLoginModal = () => { setIsLoginModal(false); }; const handleHomeClick = () => { window.location.href = '/'; }; const handleCategoryClick = (categoryId, categoryName) => { window.location.href = '/category/id:' + categoryName + categoryId; }; const handleMyChannelClick = (userId) => { window.location.href = '/myChannel/id:' + userId; }; const handleFavoriteClick = (userId) => { window.location.href = '/favorite/id:' + userId; }; const handleChannelFollowedClick = (userId) => { window.location.href = '/channel/followed/id:' + userId; }; return ( <div className="w-screen h-screen bg-black bg-opacity-50 flex py fixed inset-0 z-50 " onClick={handleBackdropClick}> <div className="w-[250px] h-screen bg-gray-50 relative slide-in"> <div className="ml-5 mt-3 mr-4"> <div className="mb-5"> <button className="flex justify-center items-center w-10 h-10 hover:bg-gray-100 rounded-full" onClick={handleBackdropClick} > <DensityMediumIcon onClick={handleBackdropClick} /> </button> {/* logo website */} </div> <div> <div> {login === "true" ? ( <ul className="mb-2 font-bold"> <li className="hover:bg-gray-200 hover:text-blue-800 py-2 px-2 rounded-xl cursor-pointer" onClick={handleHomeClick} > <HomeOutlinedIcon className="mr-4" /> Trang Chủ </li> <li className="hover:bg-gray-200 hover:text-blue-800 py-2 px-2 rounded-xl cursor-pointer" onClick={() => handleMyChannelClick(user.id)} > <LiveTvOutlinedIcon className="mr-4" /> Kênh Của Tôi </li> <li className="hover:bg-gray-200 hover:text-blue-800 py-2 px-2 rounded-xl cursor-pointer" onClick={() => handleChannelFollowedClick(user.id)} > <SubscriptionsOutlinedIcon className="mr-4" /> Kênh Đăng Ký </li> <li className="hover:bg-gray-200 hover:text-blue-800 py-2 px-2 rounded-xl cursor-pointer" onClick={() => handleFavoriteClick(user.id)} > <FavoriteBorderOutlinedIcon className="mr-4" /> Video yêu thích </li> </ul> ) : ( <ul className="mb-2 font-bold"> <li className="hover:bg-gray-200 hover:text-blue-800 py-2 px-2 rounded-xl cursor-pointer mb-2" onClick={handleHomeClick} > <HomeOutlinedIcon className="mr-4" /> Trang Chủ </li> <li className="hover:bg-gray-200 hover:text-blue-800 text-white bg-blue-600 py-2 px-2 rounded-xl cursor-pointer text-center mb-5" onClick={openLoginModal} > Đăng nhập tài khoản </li> </ul> )} </div> <hr /> {/* <span className="flex justify-center items-center mt-2 text-blue-500 font-bold">Danh mục</span> */} {categories.map((category) => ( <div key={category.id}> <ul className="mt-2"> <li className="hover:bg-gray-200 hover:text-blue-500 py-2 px-2 rounded-xl cursor-pointer text-blue-900 font-bold" onClick={() => handleCategoryClick(category.id, category.name)} > <SubscriptionsOutlinedIcon className="mr-4" /> {category.name} </li> </ul> </div> ))} <div className="absolute bottom-0"> <FooterPage /> </div> </div> </div> </div> {isLoginModal && <LoginPage closeModal={closeLoginModal} />} </div> ); }; export default MenuPage;
import * as assert from 'assert'; import { config } from"../../wdio.conf.js"; import { ChainablePromiseElement } from 'webdriverio'; class MainPage { expectedTitle: string = 'АЛЛО - національний маркетплейс із найширшим асортиментом'; async open(): Promise<void>{ browser.url(config.baseUrl); await browser.pause(2000); } async verifyTitle(): Promise<void>{ const title = await browser.getTitle(); assert.strictEqual(title, this.expectedTitle) } get itemCategoryPhones (): ChainablePromiseElement<WebdriverIO.Element>{ return $("a[title=\"Смартфони та телефони\"]"); } get dropdownSort (): ChainablePromiseElement<WebdriverIO.Element>{ return $('span.sort-by__current'); } get dropdownSortPrice (): ChainablePromiseElement<WebdriverIO.Element>{ return $('[title=\'від дорогих до дешевих\']'); } get returnToMainPage(): ChainablePromiseElement<WebdriverIO.Element>{ return $('[title=\'Перейти на головну сторінку\']') } get chooseCategoryFishBtn(): ChainablePromiseElement<WebdriverIO.Element>{ return $("//p[contains(text(),'Туризм та риболовля')] "); } get filterLights (): ChainablePromiseElement<WebdriverIO.Element>{ return $("=Ліхтарі"); } get searchInput(): ChainablePromiseElement<WebdriverIO.Element>{ return $('#search-form__input'); } get showAllResultsBtn(): ChainablePromiseElement<WebdriverIO.Element>{ return $('button.search-result__nav-link') } async searchItem (itemName): Promise<void> { await this.searchInput.waitForClickable() await this.searchInput.click() await this.searchInput.setValue(itemName); await this.showAllResultsBtn.waitForClickable() await this.showAllResultsBtn.click(); } } export default new MainPage();
--- permalink: audit/audit-message-format.html sidebar: sidebar keywords: storagegrid, audit, message formats, message format summary: 'Les messages d"audit échangés dans le système StorageGRID incluent des informations standard communes à tous les messages et du contenu spécifique décrivant l"événement ou l"activité signalé.' --- = Format du message d'audit : présentation :allow-uri-read: :icons: font :imagesdir: ../media/ [role="lead"] Les messages d'audit échangés dans le système StorageGRID incluent des informations standard communes à tous les messages et du contenu spécifique décrivant l'événement ou l'activité signalé. Si le résumé fourni par le link:using-audit-explain-tool.html["audit - expliquer"] et link:using-audit-sum-tool.html["somme-audit"] les outils sont insuffisants, reportez-vous à cette section pour comprendre le format général de tous les messages de vérification. Voici un exemple de message d'audit tel qu'il peut apparaître dans le fichier journal d'audit : [listing] ---- 2014-07-17T03:50:47.484627 [AUDT:[RSLT(FC32):VRGN][AVER(UI32):10][ATIM(UI64):1405569047484627][ATYP(FC32):SYSU][ANID(UI32):11627225][AMID(FC32):ARNI][ATID(UI64):9445736326500603516]] ---- Chaque message d'audit contient une chaîne d'éléments d'attribut. L'ensemble de la chaîne est entre crochets (`[ ]`), et chaque élément d'attribut de la chaîne possède les caractéristiques suivantes : * Entre crochets `[ ]` * Introduit par la chaîne `AUDT`, qui indique un message d'audit * Sans délimiteurs (pas de virgules ni d'espaces) avant ou après * Terminé par un caractère de flux de ligne `\n` Chaque élément inclut un code d'attribut, un type de données et une valeur qui sont rapportées dans ce format : [listing] ---- [ATTR(type):value][ATTR(type):value]... [ATTR(type):value]\n ---- Le nombre d'éléments d'attribut dans le message dépend du type d'événement du message. Les éléments d'attribut ne sont pas répertoriés dans un ordre particulier. La liste suivante décrit les éléments d'attribut : * `ATTR` est un code à quatre caractères pour l'attribut en cours de signalement. Certains attributs sont communs à tous les messages d'audit et à d'autres, qui sont spécifiques à un événement. * `type` Est un identificateur à quatre caractères du type de données de programmation de la valeur, comme UI64, FC32, etc. Le type est entre parenthèses `( )`. * `value` est le contenu de l'attribut, généralement une valeur numérique ou de texte. Les valeurs suivent toujours deux-points (`:`). Les valeurs du type de données CSTR sont entourées de guillemets doubles `" "`.
mod tests { use core::traits::Into; use core::result::ResultTrait; use constructor::constructor::ExampleConstructor; use constructor::constructor::ExampleConstructor::{names}; use debug::PrintTrait; use starknet::{deploy_syscall, ContractAddress, contract_address_const}; use starknet::testing::{set_contract_address}; use starknet::class_hash::Felt252TryIntoClassHash; #[test] #[available_gas(2000000000)] fn should_deploy_and_init() { let name: felt252 = 'bob'; let address: ContractAddress = contract_address_const::<'caller'>(); let mut calldata: Array::<felt252> = array![]; calldata.append(name); calldata.append(address.into()); let (address_0, _) = deploy_syscall( ExampleConstructor::TEST_CLASS_HASH.try_into().unwrap(), 0, calldata.span(), false ) .unwrap(); let mut state = ExampleConstructor::unsafe_new_contract_state(); set_contract_address(address_0); let name: felt252 = names::InternalContractMemberStateTrait::read(@state.names, address); assert(name == 'bob', 'name should be bob'); } }
<template> <v-row justify="center"> <v-dialog v-model="dialog" persistent max-width="600px" > <v-card> <v-card-title> <span class="text-h5">User Profile</span> </v-card-title> <v-card-text> <v-container> <v-row> <v-col cols="12" class="d-flex flex-column align-center" > <v-row> <v-avatar size="70" class="picture" color="primary" @click="pictureChange" > <v-img :src="file" v-if="file" /> <span class="white--text text-h4" v-if="!file" > {{nameInitials}} </span> <input type="file" class="inputPicture" @change="onFileInputChange" /> </v-avatar> </v-row> <v-row> <v-btn x-small icon class="mt-1 delete-button" @click="deleteAvatar" > <v-icon> mdi-image-off-outline </v-icon> Delete avatar </v-btn> </v-row> </v-col > <v-col cols="12" sm="6" > <v-text-field label="Name" v-model="name" ></v-text-field> </v-col> <v-col cols="12" sm="6" > <v-text-field label="Username" v-model="username" ></v-text-field> </v-col> </v-row> </v-container> </v-card-text> <v-card-actions> <v-spacer></v-spacer> <v-btn color="blue darken-1" text @click="$store.commit('toggleUserSettings')" > Close </v-btn> <v-btn color="blue darken-1" text @click="saveSettings" > Save </v-btn> </v-card-actions> </v-card> </v-dialog> </v-row> </template> <script> export default { data(){ return { dialog: true, name: null, username: null, file: null, } }, methods:{ pictureChange(){ let inputPicture = document.querySelector('.inputPicture') inputPicture.click() }, onFileInputChange(e){ if(!e.target.files || !e.target.files[0]) return let file = e.target.files[0] const reader = new FileReader() reader.readAsDataURL(file) reader.onload = (e)=>{ this.file = e.target.result } }, saveSettings(){ let settings = {name: this.name, username: this.username, file: this.file} this.$store.dispatch('saveSettings', settings) this.$store.commit('toggleUserSettings') }, deleteAvatar(){ this.file = null } }, mounted(){ this.name = this.$store.state.userSettings.name this.username = this.$store.state.userSettings.username this.file = this.$store.state.userSettings.file }, computed:{ nameInitials(){ if(this.name){ let names = this.name.split(' ', 2) if(names.length < 2){ return `${names[0].slice(0,1)}` } else{ let initials = names.map((element)=>element.slice(0,1)) return `${initials[0]}${initials[1]}` } } else{ return 'NU' } }, } } </script> <style lang="scss"> .picture{ cursor: pointer; .inputPicture{ display: none; } } .delete-button{ &:hover{ color: red !important; } } </style>>
// 해시 - 베스트앨범 function solution(genres, plays) { const answer = []; // 노래를 구분하기 위한 배열을 만들어 준다. let songs = genres.map((genre, idx) => { return { no: idx, genre: genre, play: plays[idx], }; }); // 장르별 재생횟수를 위한 새로운 배열을 만들어 준다. let genrePlayCnt = []; songs.forEach((song) => { let thisGenre = genrePlayCnt.find((a) => a.genre === song.genre); if (thisGenre) { thisGenre.play += song.play; } else { genrePlayCnt.push({ genre: song.genre, play: song.play, }); } }); // 재생횟수가 많은 순으로 노래를 정렬한다. songs.sort((a, b) => b.play - a.play); // 재생횟수가 많은 순으로 장르를 정렬한다. genrePlayCnt.sort((a, b) => b.play - a.play); // 장르를 기준으로 배열을 돌면서 노래를 두 개 씩 넣는다. genrePlayCnt.forEach((a) => { let len = 0; songs.forEach((song) => { if (a.genre === song.genre && len < 2) { len++; answer.push(song.no); } }); }); return answer; }
import userModel from "../../../../DB/models/user.model.js"; import { asyncHandler } from "../../../utils/asyncHandler.js"; import bcryptjs from "bcryptjs"; import crypto from "crypto"; import jwt from "jsonwebtoken"; import { sendEmail } from "../../../utils/sendEmails.js"; import { resetPassword, signupTemp } from "../../../utils/generateHtml.js"; import tokenModel from "../../../../DB/models/token.model.js"; import randomstring from "randomstring"; import cartModel from "../../../../DB/models/cart.model.js"; export const register = asyncHandler(async (req, res, next) => { const { userName, email, password ,role} = req.body; const isUser = await userModel.findOne({ email }); if (isUser) { return next(new Error("email already registered !", { cause: 409 })); } const hashPassword = bcryptjs.hashSync( password, Number(process.env.SALT_ROUND) ); const activationCode = crypto.randomBytes(64).toString("hex"); const user = await userModel.create({ userName, email, password: hashPassword, role, activationCode, }); const link = `https://backend-kappa-beige.vercel.app/auth/confirmEmail/${activationCode}`; const isSent = await sendEmail({ to: email, subject: "Activate Account", html: signupTemp(link), }); return isSent ? res .status(200) .json({ success: true, message: "Please review Your email!" }) : next(new Error("something went wrong!", { cause: 400 })); }); export const activationAccount = asyncHandler(async (req, res, next) => { const user = await userModel.findOneAndUpdate( { activationCode: req.params.activationCode }, { isConfirmed: true, $unset: { activationCode: 1 } } ); if (!user) { return next(new Error("User Not Found!", { cause: 404 })); } if (user.role == "user") { await cartModel.create({ user: user._id }); } return res .status(200) .send("Congratulation, Your Account is now activated, try to login"); }); export const login = asyncHandler(async (req, res, next) => { const { email, password } = req.body; const user = await userModel.findOne({ email }); if (!user) { return next(new Error("Invalid-Email", { cause: 400 })); } if (!user.isConfirmed) { return next(new Error("Un activated Account", { cause: 400 })); } const match = bcryptjs.compareSync(password, user.password); if (!match) { return next(new Error("Invalid-Password", { cause: 400 })); } const token = jwt.sign( { id: user._id, email: user.email }, process.env.TOKEN_KEY, { expiresIn: "2d" } ); await tokenModel.create({ token, user: user._id, agent: req.headers["user-agent"], }); user.status = "online"; await user.save(); return res.status(200).json({ success: true, result: token }); }); //send forget Code export const sendForgetCode = asyncHandler(async (req, res, next) => { const user = await userModel.findOne({ email: req.body.email }); if (!user) { return next(new Error("Invalid email!", { cause: 400 })); } const code = randomstring.generate({ length: 5, charset: "numeric", }); user.forgetCode = code; await user.save(); return (await sendEmail({ to: user.email, subject: "Reset Password", html: resetPassword(code), })) ? res.status(200).json({ success: true, message: "check you email!" }) : next(new Error("Something went wrong!", { cause: 400 })); }); export const resetPasswordByCode = asyncHandler(async (req, res, next) => { const newPassword = bcryptjs.hashSync( req.body.password, +process.env.SALT_ROUND ); const checkUser = await userModel.findOne({ email: req.body.email }); if (!checkUser) { return next(new Error("Invalid email!", { cause: 400 })); } if (checkUser.forgetCode !== req.body.forgetCode) { return next(new Error("Invalid code!", { status: 400 })); } const user = await userModel.findOneAndUpdate( { email: req.body.email }, { password: newPassword, $unset: { forgetCode: 1 } } ); //invalidate tokens const tokens = await tokenModel.find({ user: user._id }); tokens.forEach(async (token) => { token.isValid = false; await token.save(); }); return res.status(200).json({ success: true, message: "Try to login!" }); });
import java.awt.Color; import java.awt.Graphics; import java.awt.BasicStroke; import java.awt.Graphics2D; public class Ball { // 1. Declaration of Variables private double x; //x-coordinate of the center of the ball private double y; //y-coordinate of the center of the ball private double diameter; //diameter of the ball private double radius; //radius of the ball private Color color; //color of the ball private double xSpeed; //x-speed = change in x-position private double ySpeed; //y-speed = change in y-position // 2. Create a default constructor /** * Default Constructor * Creates a red ball at (0, 0) with a diameter of 25. * The default speed is 0. */ public Ball() { this.x=0; this.y=0; this.diameter=25; this.radius=12.5; this.color=Color.RED; this.xSpeed=0; this.ySpeed=0; } // 3. Write a constructor that allows the user to input the parameters (x, y, diameter, Color) // and sets the x and y-speed = 0. public Ball(double x, double y, double diameter, Color color) { this.x=x; this.y=y; this.diameter=diameter; this.radius=diameter/2; this.color=color; this.xSpeed=0; this.ySpeed=0; } // 4. Create getters and setters for all private variables public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getDiameter() { return diameter; } public void setDiameter(double diameter) { this.diameter = diameter; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public double getxSpeed() { return xSpeed; } public void setxSpeed(double xSpeed) { this.xSpeed = xSpeed; } public double getySpeed() { return ySpeed; } public void setySpeed(double ySpeed) { this.ySpeed = ySpeed; } // 5. Finish the following methods // 6. Test using BouncingBallTester.java public void draw(Graphics g) { Graphics2D g2d = (Graphics2D) g; int outlineWidth = 8; g2d.setStroke(new BasicStroke(outlineWidth)); g.setColor(Color.BLACK); g.drawOval((int)(x-radius), (int)(y-radius), (int)diameter, (int)diameter); g.setColor(color); g.fillOval((int)(x-radius), (int)(y-radius), (int)diameter, (int)diameter); //setLocation(double x, double y) //Takes in new x/y coordinates as parameters. Sets the Ball’s x and y fields to the new provided values. //This “teleports” the ball to a new location. } // 7. Sets the center location of the ball // This "teleports" the ball to the given x/y location public void setLocation(double xLoc, double yLoc) { this.x=xLoc; this.y=yLoc; } // 8. Sets the xSpeed and ySpeed to a value between // negative maxSpeed and positive maxSpeed public void setRandomSpeed(double maxSpeed) { this.xSpeed=Math.random()*maxSpeed +4; this.ySpeed=Math.random()*maxSpeed +4; } // 9. Write the move method to make the ball move around the screen // and bounce of the edges. public void move(int rightEdge, int bottomEdge) { this.x+=xSpeed; this.y+=ySpeed; if (x+radius>=rightEdge) { x=rightEdge-radius; xSpeed=-xSpeed; } if (x-radius<=0) { x=radius; xSpeed=-xSpeed; } if (y+radius>=bottomEdge) { y=bottomEdge-radius; ySpeed=-ySpeed; } if (y-radius<=0) { y=radius; ySpeed=-ySpeed; } } }
import React, { useEffect, useState } from 'react'; import { w3cwebsocket as W3CWebSocket } from 'websocket'; function getRandomTickets(aviableTickets, num) { const shuffledTickets = aviableTickets.slice(); let selectedTickets = []; while (selectedTickets.length < num && shuffledTickets.length > 0) { const randomIndex = Math.floor(Math.random() * shuffledTickets.length); selectedTickets.push(shuffledTickets[randomIndex]); shuffledTickets.splice(randomIndex, 1); } return selectedTickets; } const TicketsGiveawayModal = ({ closeModal, giveawayId }) => { const [aviableTickets, setAviableTickets] = useState([]); const [generateNewNumbers, setGenerateNewNumbers] = useState(true); const handleGenerateNewNumbers = () => { setGenerateNewNumbers(true); }; useEffect(() => { const websocketURL = `ws://${process.env.NEXT_PUBLIC_APP_URL}/ws/tickets_giveaway/${giveawayId}/`; const client = new W3CWebSocket(websocketURL); client.onopen = (message) => { console.log('Conexión WebSocket abierta'); }; client.onmessage = (message) => { const data = JSON.parse(message.data); if (generateNewNumbers) { const randomTickets = getRandomTickets(data.iTickets, 5); setAviableTickets(randomTickets); setGenerateNewNumbers(false); } }; client.onclose = () => { console.log('Conexión WebSocket cerrada'); }; client.onerror = (error) => { console.error('Error de conexión WebSocket:', error); }; return () => { if (client.readyState === client.OPEN) { client.close(); } }; }, [generateNewNumbers, giveawayId]); useEffect(() => { handleGenerateNewNumbers(); }, []); return ( <div> {aviableTickets ? ( <div className='flex flex-row overflow-scroll gap-x-2'> {aviableTickets.map((aviableTicket, i) => ( <p key={i} className='text-white text-xl uppercase font-semibold'>{aviableTicket}</p> ))} </div> ) : ( <p>No hay información que mostrar {giveawayId} aviableTickets {aviableTickets}</p> )} <button onClick={handleGenerateNewNumbers}>Generar Nuevos Números</button> </div> ); }; export default TicketsGiveawayModal;
/** Tutorial Starting Point: This project serves as a starting point to follow the EagleSDK tutorial guide. Getting Started: 1. Set board target (Tools -> Board -> teensyduino -> Teensy 3.2/3.1) 2. Set sketchbook location to the EagleSDK_2.0 folder (File -> Preferences -> Sketchbook Location: C:\Users\RMcWilliam\Desktop\Repository\EagleSDK_2.0) While in preference line numbers can be turned on by checking the display line number box 3. Press the check mark in the top left to compile the code (there will be a green progress bar in the bottom right) 4. The build will automatically load to the teensy.exe app. Ensure the green auto button is pressed 5. When the Eagle is plugged in via micro usb (or while powered and connected with isolated usb) press the physical button on the bootloader board(small board connected to the Eagle). A programing progress bar will begin in the teensy app. 6. Now that this firmware has been flashed to the board, open the IrisControls software (EagleSDK_2.0/IrisControls4/IrisControls4.exe) 7. There will be a drop down menu that you can use to select the com port of the Eagle. 8. Once connected there will be a message in the console box saying that an Eagle has been connected. @author Rebecca McWilliam <[email protected]> @version 2.2.0 @copyright Copyright 2022 Iris Dynamics Ltd 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. For questions or feedback on this file, please email <[email protected]>. */ /* * Include addional Eagle SDK libraries and files within this project */ #include <iriscontrols4.h> // Iris controls 4 library (GUI Handling) #include <modbus_lib.h> // Modbus client library (UART communications with motors) #include "client/device_applications/actuator.h" // Actuator objects (abstracts communication to motor) #include "Main_GUI.h" // Custom IrisControls GUI interface //Motor connected on port 1 of the Eagle board Actuator motor(1, "Motor 1", CYCLES_PER_MICRO); // Initialize the actuator object to be a motor plugged into port 1 of the Eagle // The port number specifies the UART channel being used (communications with motor) // Changing the port will require changing the interrupt handler at the bottom of this file //Pass reference of the motor object to the GUI GUI gui(motor); // Pass by reference the motor object to the gui object so that gui elements have access to the motor IrisControls4 *IC4_virtual = &gui; // Pointer to the gui that will be used by that will be used to check version compatibility and occasional writing ot the console with errors /* * @brief Setup function is called once at the first when the Eagle resets (bootloader button pressed or power cycled) */ void setup() { motor.init(); // Intialize the UART port on the Eagle to allow communications with a motor (enabling interrupts and setting a default baud rate) motor.enable(); // Start pinging the port for a connected motor (will automatically handshake when detected) } /* * @brief Main loop that gets called continuously * Motor frames communication are done here, depending on the mode either Sleep, Force or Position will be commanded * Return frame contains information about motor position, force, temperature, power, errors. * Additional commands can be injected into the stream. */ void loop() { motor.run_in(); // Parse incoming motor frames (Motor -> Eagle) motor.run_out(); // Send out motor frames (Eagle -> Motor) gui.run(); // Run IrisControls connectivity, GUI element interaction, serial parsing found in Main_GUI.h } /* Interrupts handling for uart 1 The uart status interrupt is fired when a message byte is either sent or received The motor's isr function handles the sending and receiving of bytes */ void uart1_status_isr() { // If port 2 is used instead of or in addition to port 1 when initializing the motor object uart2_status_isr() should be used motor.isr(); }
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Router } from '@angular/router'; import { BehaviorSubject, map, Observable, startWith } from 'rxjs'; import { ProductModel } from 'src/app/shop-phone/models/product.model'; import { UserModel } from 'src/app/shop-phone/models/user.model'; import { CartService } from 'src/app/shop-phone/services/cart/cart.service'; import { ProductService } from 'src/app/shop-phone/services/product/product.service'; import { StorageService } from 'src/app/shop-phone/services/storage/storage.service'; import { UserService } from 'src/app/shop-phone/services/user/user.service'; @Component({ selector: 'app-topbar', templateUrl: './topbar.component.html', styleUrls: ['./topbar.component.css'] }) export class TopbarComponent implements OnInit { price = 0; quantityCart: number = 0; isLogin!: boolean; user!: UserModel; myControl = new FormControl(''); options: ProductModel[] = []; filteredOptions!: Observable<ProductModel[]>; constructor(private storageService: StorageService, private router: Router, private cartService: CartService, private userService: UserService, private productService: ProductService) { } ngOnInit(): void { if(this.storageService.getToken()){ this.isLogin = true; } this.loadUser(); this.cartService.getCart().subscribe(); this.listenState(); this.loadProduct(); this.filteredOptions = this.myControl.valueChanges.pipe( startWith(''), map(value => { const name = typeof value === 'string' ? value : value?.name; return name ? this._filter(name as string) : this.options.slice(); }), ); } displayFn(product: ProductModel): string { return product && product.name ? product.name : ''; } private _filter(name: string): ProductModel[] { const filterValue = name.toLowerCase(); return this.options.filter(option => option.name.toLowerCase().includes(filterValue)); } logout(){ this.storageService.deleteAll(); window.location.href = '/'; } loadUser(): void { this.userService.getUser().subscribe( res => { this.user = res; }, error => { console.log(error); } ) } listenState(): void{ this.cartService.cart$.subscribe(res => this.cartChange()); } cartChange(): void{ const cart = this.cartService.getCartUser(); if (cart){ this.quantityCart = cart.count; } } loadProduct() { this.productService.getProducts().subscribe( res => { this.options = res; },error => { console.log(error); } ) } searchProduct() { const array = this.options.filter(item => item.name.includes(this.myControl.value)); this.router.navigate( ['/products/shop'], { queryParams: { id: array[0].id, brandId: array[0].brand.id, type: array[0].type } } ); } }
import { Lox } from "./lox"; import { LiteralValue, Token, TokenType } from "./Token"; export class Scanner { start = 0; current = 0; line = 1; source: string; result: Token[]; keywords: Record<string, TokenType> = { and: TokenType.AND, class: TokenType.CLASS, else: TokenType.ELSE, false: TokenType.FALSE, for: TokenType.FOR, fun: TokenType.FUN, if: TokenType.IF, nil: TokenType.NIL, or: TokenType.OR, print: TokenType.PRINT, return: TokenType.RETURN, super: TokenType.SUPER, this: TokenType.THIS, true: TokenType.TRUE, var: TokenType.VAR, while: TokenType.WHILE, }; constructor(source: string) { this.source = source; this.result = []; } scanTokens(): Token[] { while (!this.isAtEnd()) { this.start = this.current; this.scanToken(); } this.result.push(new Token(TokenType.EOF, "", null, this.line)); return this.result; } private scanToken() { const c = this.advance(); switch (c) { case "(": this.addToken(TokenType.LEFT_PAREN); break; case ")": this.addToken(TokenType.RIGHT_PAREN); break; case "{": this.addToken(TokenType.LEFT_BRACE); break; case "}": this.addToken(TokenType.RIGHT_BRACE); break; case ",": this.addToken(TokenType.COMMA); break; case ".": this.addToken(TokenType.DOT); break; case "-": this.addToken(TokenType.MINUS); break; case "+": this.addToken(TokenType.PLUS); break; case ";": this.addToken(TokenType.SEMICOLON); break; case "*": this.addToken(TokenType.STAR); break; case "!": this.addToken(this.match("=") ? TokenType.BANG_EQUAL : TokenType.BANG); break; case "=": this.addToken( this.match("=") ? TokenType.EQUAL_EQUAL : TokenType.EQUAL ); break; case "<": this.addToken(this.match("=") ? TokenType.LESS_EQUAL : TokenType.LESS); break; case ">": this.addToken( this.match("=") ? TokenType.GREATER_EQUAL : TokenType.GREATER ); break; case "/": { if (this.match("/")) { while (this.peek() !== "\n" && !this.isAtEnd()) this.advance(); } else { this.addToken(TokenType.SLASH); } break; } case " ": case "\r": case "\t": // Ignore whitespace. break; case "\n": this.line++; break; case `"`: this.string(); break; default: { if (this.isDigit(c)) { this.number(); } else if (this.isAlpha(c)) { this.identifier(); } else { Lox.error(this.line, "Unexpected character."); } break; } } } private identifier() { while (this.isAlphaNumeric(this.peek())) this.advance(); let type: TokenType = TokenType.IDENTIFIER; const text = this.source.substring(this.start, this.current); const possibleKeyword = this.keywords[text]; if (possibleKeyword) { type = possibleKeyword; } this.addToken(type); } private isAlphaNumeric(c: string) { return this.isAlpha(c) || this.isDigit(c); } private isAlpha(c: string) { return (c >= "a" && c <= "z") || (c >= "A" && c <= "Z") || c === "_"; } private number() { while (this.isDigit(this.peek())) this.advance(); if (this.peek() === "." && this.isDigit(this.peekNext())) { this.advance(); while (this.isDigit(this.peek())) this.advance(); } this.addTokenWithLiteral( TokenType.NUMBER, Number(this.source.substring(this.start, this.current)) ); } private string() { while (this.peek() !== `"` && !this.isAtEnd()) { if (this.peek() === "\n") this.line++; this.advance(); } if (this.isAtEnd()) { Lox.error(this.line, "Unterminated string."); return; } this.advance(); const value = this.source.substring(this.start + 1, this.current - 1); this.addTokenWithLiteral(TokenType.STRING, value); } private isDigit(str: string) { return str >= "0" && str <= "9"; } private peekNext() { if (this.current + 1 >= this.source.length) return "\0"; return this.source.charAt(this.current + 1); } private peek() { if (this.isAtEnd()) return "\0"; return this.source.charAt(this.current); } private match(expected: string) { if (this.isAtEnd()) return false; if (this.source.charAt(this.current) !== expected) return false; this.current++; return true; } private addToken(type: TokenType) { this.addTokenWithLiteral(type, null); } private addTokenWithLiteral(type: TokenType, literal: LiteralValue) { const text = this.source.substring(this.start, this.current); this.result.push(new Token(type, text, literal, this.line)); } private advance() { this.current++; return this.source.charAt(this.current - 1); } private isAtEnd() { return this.current >= this.source.length; } }
package com.payapl.csdmp.sp.core.input.bigquery import com.payapl.csdmp.sp.core.Reader import com.paypal.csdmp.sp.consts.Constant.DATASOURCE_FORMAT_BIGQUERY import com.paypal.csdmp.sp.utils.parseContextInQuery import org.apache.spark.sql.{DataFrame, SparkSession} import scala.util.Random case class BigQueryReader(name: String, outputDataFrame: Option[String], projectName: String = "pypl-edw", datasetName: Option[String], tableName: Option[String], column: Option[String], filter: Option[String], sqlText: Option[String], materializationDataset: String = "pp_scratch", options: Option[Map[String, String]] ) extends Reader { override def read()(implicit sparkSession: SparkSession): DataFrame = { sparkSession.conf.set("viewEnabled", "true") sparkSession.conf.set("materializationDataset", materializationDataset) sparkSession.conf.set("materializationProject", projectName) sqlText match { case Some(sql) => val query: String = parseContextInQuery(sql, sparkSession) val randomQuery: String = addRandomClauseIntoSQL(sql) logInfo("the Query with random query is " + randomQuery) try { sparkSession.read.format(DATASOURCE_FORMAT_BIGQUERY).load(randomQuery) } catch { case e: Exception => sparkSession.read.format(DATASOURCE_FORMAT_BIGQUERY).load(query) } case None => val table: String = projectName + "." + datasetName.get + "." + tableName.get logInfo("Table is " + table) val tableDataFrame: DataFrame = sparkSession.read.format(DATASOURCE_FORMAT_BIGQUERY).load(table) column match { case Some(column) => val columnArray: Array[String] = column.split(",") filter match { case Some(filter) => logInfo("Has Column AND Filter") tableDataFrame.where(filter).select(columnArray.head, columnArray.tail: _*) case None => logInfo("Has Column BUT None Filter") tableDataFrame.select(columnArray.head, columnArray.tail: _*) } case None => filter match { case Some(filter) => logInfo("Has None Column BUT Have Filter") tableDataFrame.where(filter) case None => logInfo("Has None Column AND None Filter") tableDataFrame } } } } def addRandomClauseIntoSQL(sql: String): String = { val alias: Char = Random.alphanumeric.filter(_.isLetter).head "select " + alias + ".* from ( " + sql + " ) " + alias } }
import AMapLoader from '@amap/amap-jsapi-loader' import { Button, Card, Input, Switch } from 'antd' import React, { FC, useEffect, useState } from 'react' import { AMAP_APPLICATION_KEY } from '../../../../common/utils' const BasicMapPropertyRange: FC = () => { const [map, setMap] = useState<any>() const [AMap, setAMap] = useState<any>() const [NELng, setNELng] = useState(0) const [NELat, setNELat] = useState(0) const [SWLng, setSWLng] = useState(0) const [SWLat, setSWLat] = useState(0) const [shouldLimit, setShouldLimit] = useState(false) const [boundInfo, setBoundInfo] = useState<any>() useEffect(() => { AMapLoader.load({ key: AMAP_APPLICATION_KEY, // 申请好的Web端开发者Key,首次调用 load 时必填 version: '2.0.5', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15 plugins: [], // 需要使用的的插件列表,如比例尺'AMap.Scale'等 }) .then((AMap: any) => { const map = new AMap.Map('container', {}) setAMap(AMap) setMap(map) }) .catch((e: any) => { console.log(e) }) }, []) useEffect(() => { if (!map) { return } map.on('moveend', getBounds) map.on('zoomend', getBounds) }, [map]) useEffect(() => { if (!map) { return } if (shouldLimit) { map.setLimitBounds(boundInfo) } else { map.clearLimitBounds() } }, [shouldLimit]) const getBounds = () => { const bounds = map.getBounds() setBoundInfo(bounds) } const handleSetLngLat = () => { if ( NELng > -180 && NELng < 180 && NELat > -90 && NELat < 90 && SWLng > -180 && SWLng < 180 && SWLat > -90 && SWLat < 90 ) { const bounds = new AMap.Bounds([NELng, NELat], [SWLng, SWLat]) map.setBounds(bounds) } } return ( <div className='outer-container'> <div id='container' className='map-container' /> <Card className='info-card info-card-tr' style={{ width: '300px' }}> <div>当前地图展示范围</div> <div> 东北坐标: {boundInfo ? `${boundInfo.northEast.lng}, ${boundInfo.northEast.lat}` : ''} </div> <div> 西南坐标: {boundInfo ? `${boundInfo.southWest.lng}, ${boundInfo.southWest.lat}` : ''} </div> </Card> <Card className='info-card info-card-br'> <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}> <div style={{ display: 'flex', alignItems: 'center' }}> 东北坐标: <Input style={{ width: '150px' }} placeholder='经度,-180~180' onChange={(e: any) => setNELng(+e.target.value)} /> <Input style={{ width: '150px' }} placeholder='纬度,-90~90' onChange={(e: any) => setNELat(+e.target.value)} /> </div> <div style={{ display: 'flex', alignItems: 'center' }}> 西南坐标: <Input style={{ width: '150px' }} placeholder='经度,-180~180' onChange={(e: any) => setSWLng(+e.target.value)} /> <Input style={{ width: '150px' }} placeholder='纬度,-90~90' onChange={(e: any) => setSWLat(+e.target.value)} /> </div> <div style={{ display: 'flex', gap: '8px' }}> <Switch onChange={(value: boolean) => setShouldLimit(value)} /> {shouldLimit ? '取消限制范围' : '限制显示范围'} </div> <Button type='primary' onClick={handleSetLngLat}> 显示所选区域 </Button> </div> </Card> </div> ) } export default BasicMapPropertyRange