text
stringlengths
184
4.48M
<?php namespace App\Http\Controllers; use App\Models\Reminder; use Illuminate\Http\Request; class ReminderController extends Controller { /** * Display a listing of the resource. */ public function index() { $reminders = auth()->user()->reminders; // $user = User::find(auth()->user()->id); // $reminders = $user->reminders(); return view('reminders.reminders-list', compact('reminders')); } /** * Show the form for creating a new resource. */ public function create() { return view('reminders.create'); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $validated = $request->validate([ 'title' => 'required|max:255', 'description' => 'required', 'date' => 'required|numeric|between:1,30', 'time' => 'required|date_format:H:i:s', ]); $reminder = new Reminder(); $reminder->title = $request->title; $reminder->description = $request->description; $reminder->date = $request->date; $reminder->time = date('H:i:s', strtotime($request->time)); $reminder->is_active = isset($request->is_active) ? 1 : 0; $reminder->user_id = auth()->user()->id; $reminder->save(); return to_route('reminders.list')->with('success', 'Reminder created successfully!'); } /** * Display the specified resource. */ public function show(Reminder $reminder) { // } /** * Show the form for editing the specified resource. */ public function edit(Reminder $reminder) { if($reminder->user_id != auth()->user()->id){ abort(403, 'You are not allowed to view this!'); } return view('reminders.edit', compact('reminder')); } /** * Update the specified resource in storage. */ public function update(Request $request, Reminder $reminder) { $validated = $request->validate([ 'title' => 'required|max:255', 'description' => 'required', 'date' => 'required|numeric|between:1,30', 'time' => 'required|date_format:H:i:s', ]); $reminder->title = $request->title; $reminder->description = $request->description; $reminder->date = $request->date; $reminder->time = date('H:i:s', strtotime($request->time)); $reminder->is_active = isset($request->is_active) ? 1 : 0; $reminder->save(); return to_route('reminders.list')->with('success', 'Reminder updated successfully!'); } /** * Remove the specified resource from storage. */ public function destroy(Reminder $reminder) { $reminder->delete(); return to_route('reminders.list')->with('success', 'Reminder deleted successfully!'); } }
package lsp type InitializeRequest struct { Params InitializeRequestParams `json:"params"` Request } type InitializeRequestParams struct { ClientInfo *ClientInfo `json:"clientInfo"` // .. there's tons more that goes here } type ClientInfo struct { Name string `json:"name"` Version string `json:"version"` } type InitializeResponse struct { Response Result InitializeResult `json:"result"` } type InitializeResult struct { ServerInfo ServerInfo `json:"serverInfo"` Capabilities ServerCapabilities `json:"capabilities"` } type ServerCapabilities struct { TextDocumentSync int `json:"textDocumentSync"` HoverProvider bool `json:"hoverProvider"` } type ServerInfo struct { Name string `json:"name"` Version string `json:"version"` } func NewInitializeResponse(id int) InitializeResponse { return InitializeResponse{ Response: Response{ RPC: "2.0", ID: &id, }, Result: InitializeResult{ Capabilities: ServerCapabilities{ TextDocumentSync: 1, HoverProvider: true, }, ServerInfo: ServerInfo{ Name: "kaandesu/LSP", Version: "0.0.1", }, }, } }
import Link from 'next/link' import styles from './Navbar.module.css' import { ActiveLink } from './ActiveLink' const menuItems = [ { text: 'Home', href: '/' }, { text: 'About', href: '/about' }, { text: 'Contact', href: '/contact' }, { text: 'Pricing', href: '/pricing' }, ]; export const Navbar = () => { return ( <nav className={ styles['menu-container'] }> { menuItems.map(({text, href}) => { return <ActiveLink key={href} text={text} href={href} /> })} </nav> ) }
package com.cqmike.sip.common.convert; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; import org.jetbrains.annotations.Contract; import java.util.*; import java.util.function.Supplier; /** * 对象拷贝工具类 * * @author cqmike **/ public final class BeanConvertUtil { /** * <p>转换单个实体并处理</p> * * <pre> * Demo demo = new Demo(); * DemoVO vo = BeanConvertUtil.convert(demo, DemoVO::new, (source, target) -> { * target.setName("prefix" + source.getName()); * }); * </pre> * * @param source 源对象 * @param supplierTarget 目标对象获取器 * @param callBack 转换回调函数, 在copyProperties之后生效 * @return * @author cqmike * @since 1.0.0 */ @Contract("!null, !null, _, _ -> !null") public static <S, T> T convert(S source, Supplier<T> supplierTarget, ConvertCallBack<S, T> callBack, String ...ignoreProperties) { if (Objects.isNull(supplierTarget) || Objects.isNull(source)) { return null; } T target = supplierTarget.get(); BeanUtil.copyProperties(source, target, ignoreProperties); if (Objects.isNull(callBack)) { return target; } callBack.convert(source, target); return target; } /** * <p>深拷贝</p> * * <pre> * Demo demo = new Demo(); * DemoVO vo = BeanConvertUtil.deepConvert(demo, DemoVO.class, (source, target) -> { * target.setName("prefix" + source.getName()); * }); * </pre> * * @param source 源对象 * @param tClass 目标类型 * @param callBack 转换回调函数, 在拷贝之后生效 * @return * @author cqmike * @since 1.0.0 */ @Contract("!null, !null, _, _ -> !null") public static <S, T> T deepConvert(S source, Class<T> tClass, ConvertCallBack<S, T> callBack, String ...ignoreProperties) { if (Objects.isNull(tClass) || Objects.isNull(source)) { return null; } SimplePropertyPreFilter filter = new SimplePropertyPreFilter(ignoreProperties); T target = JSON.parseObject(JSON.toJSONString(source, filter), tClass); if (Objects.isNull(callBack)) { return target; } callBack.convert(source, target); return target; } /** * 转换单个实体 * <pre> * Demo demo = new Demo(); * DemoVO vo = BeanConvertUtil.convert(demo, DemoVO::new); * </pre> * * @param source 源对象 * @param supplierTarget 目标对象获取器 * @return * @author cqmike * @since 1.0.0 */ @Contract("!null, !null, _ -> !null") public static <S, T> T convert(S source, Supplier<T> supplierTarget, String ...ignoreProperties) { return convert(source, supplierTarget, null, ignoreProperties); } /** * 转换单个实体 * <pre> * Demo demo = new Demo(); * DemoVO vo = BeanConvertUtil.deepConvert(demo, DemoVO.class); * </pre> * * @param source 源对象 * @param tClass 目标类型 * @return * @author cqmike * @since 1.0.0 */ @Contract("!null, !null, _ -> !null") public static <S, T> T deepConvert(S source, Class<T> tClass, String ...ignoreProperties) { return deepConvert(source, tClass, null, ignoreProperties); } /** * <p>转换数组</p> * <pre> * Demo demo = new Demo(); * List<DemoVO> voList = BeanConvertUtil.convertList(new ArrayList(demo), DemoVO::new); * </pre> * * @param sources 源数据 * @param supplierTarget 对象目前获取器 * @return * @author cqmike * @since 1.0.0 */ public static <S, T> List<T> convertList(Collection<S> sources, Supplier<T> supplierTarget, String ...ignoreProperties) { return convertList(sources, supplierTarget, null, ignoreProperties); } /** * <p>转换数组</p> * <pre> * Demo demo = new Demo(); * List<DemoVO> voList = BeanConvertUtil.convertList(new ArrayList(demo), DemoVO::new, (source, target) -> { * target.setName("prefix" + source.getName()); * }); * </pre> * * @param sources 源数据 * @param supplierTarget 对象目标获取器 * @param callBack 处理函数 * @return * @author cqmike * @since 1.0.0 */ public static <S, T> List<T> convertList(Collection<S> sources, Supplier<T> supplierTarget, ConvertCallBack<S, T> callBack, String ...ignoreProperties) { if (Objects.isNull(supplierTarget) || CollUtil.isEmpty(sources)) { return Collections.emptyList(); } List<T> list = new ArrayList<>(sources.size()); for (S source : sources) { if (Objects.isNull(source)) { continue; } T target = supplierTarget.get(); BeanUtil.copyProperties(source, target, ignoreProperties); if (Objects.nonNull(callBack)) { callBack.convert(source, target); } list.add(target); } return list; } /** * <p>深拷贝数组</p> * <pre> * Demo demo = new Demo(); * List<DemoVO> voList = BeanConvertUtil.deepConvertList(new ArrayList(demo), DemoVO.class); * </pre> * * @param sources 源数据 * @param tClass 对象类型 * @return * @author cqmike * @since 1.0.0 */ public static <S, T> List<T> deepConvertList(Collection<S> sources, Class<T> tClass, String ...ignoreProperties) { return deepConvertList(sources, tClass, null, ignoreProperties); } /** * <p>深拷贝数组</p> * <pre> * Demo demo = new Demo(); * List<DemoVO> voList = BeanConvertUtil.deepConvertList(new ArrayList(demo), DemoVO.class, (source, target) -> { * target.setName("prefix" + source.getName()); * }); * </pre> * * @param sources 源数据 * @param tClass 对象类型 * @param callBack 处理函数 * @return * @author cqmike * @since 1.0.0 */ public static <S, T> List<T> deepConvertList(Collection<S> sources, Class<T> tClass, ConvertCallBack<S, T> callBack, String ...ignoreProperties) { if (Objects.isNull(tClass) || CollUtil.isEmpty(sources)) { return Collections.emptyList(); } SimplePropertyPreFilter filter = new SimplePropertyPreFilter(ignoreProperties); if (Objects.isNull(callBack)) { return JSON.parseArray(JSON.toJSONString(sources, filter), tClass); } List<T> list = new ArrayList<>(sources.size()); for (S source : sources) { if (Objects.isNull(source)) { continue; } T target = JSON.parseObject(JSON.toJSONString(source, filter), tClass); callBack.convert(source, target); list.add(target); } return list; } /** * 转换函数定义 * * @author cqmike * @return * @since 1.0.0 */ @FunctionalInterface public interface ConvertCallBack<S, T> { /** * 转换 * * @param source 源对象 * @param target 目标对象 * @return * @author cqmike * @since 1.0.0 */ void convert(S source, T target); } }
#pragma once #include <glew.h> #include <string> #include <fstream> #include <sstream> #include <vector> #include "Camera.h" #include "Model.h" #include "Terrain.h" #include "Texture.h" #include "SkyDome.h" #include "Light.h" #include "BillboardRenderer.h" namespace GE { class ModelRenderer { public: ModelRenderer() :ScaleX(0.5f), ScaleY(0.5f), ScaleZ(0.5f) { Init(); } virtual ~ModelRenderer() {} //does nothing void Init(); //create shaders and vertex buffer void Update(); void ManipulateVerticies(glm::mat4& tranformationMat, Model* model); void DrawWithIndecies(GLuint vertex, GLuint index, GLuint indexNumber); void Fog(float density); //update the state of the object e.g Anims void Draw(Camera* cam, Model* model, Light* light); //Rendering method void Draw(Model* model, Light* light); //Rendering method void Draw(Camera* cam, Terrain* terrain, Light* light); void Draw(Camera* cam, SkyDome* sky, Light* light); void Destroy(); //Releases object from the buffer //getters glm::vec3 getPos() const {return pos;} float getRotX() const {return RotX;} float getRotY() const {return RotY;} float getRotZ() const {return RotZ;} float getScaleX() const {return ScaleX;} float getScaleY() const {return ScaleY;} float getScaleZ() const {return ScaleZ;} const GLuint* getPID() {return &programID;} //Setters void setPos(float x, float y, float z) { pos.x = x; pos.y = y; pos.z = z; } void setRotation(float x, float y, float z) { RotX = x; RotY = y; RotZ = z; } void setScale(float x, float y, float z) { ScaleX = x; ScaleY = y; ScaleZ = z; } private: GLuint programID = 0; // program object that contains the shaders GLint vertexPos3DLocation = 0; //3D attributes for the pipeline GLint vertexUVLocation = 0; //recieves a UV coordiante GLint vertexNormal = 0; //normals of the verticeis //Light uniforms GLint lightColour; GLint ambient; GLint lightPos; //position, rotation and scale variables default glm::vec3 pos; //Rotation float RotX = 0.0f, RotY = 0.0f, RotZ = 0.0f; //Scale float ScaleX = 0.0f, ScaleY = 0.0f, ScaleZ = 0.0f; //IDs GLuint transformUniformID = 0, viewUniformID = 0, projectionUniformID = 0, samplerID = 0, viewPosID = 0; GLuint fogColourID = 0, fogDensityID = 0; std::string mr_vShader; std::string mr_fShader; std::unique_ptr<BillboardRenderer> billboardRend = nullptr; }; }
import { PiivIssuer } from "../../typechain-types"; import { ethers } from "hardhat"; interface DeployPiivIssuerOptions { piivGovernorAddress: string; deployerAddress: string; } interface TransferOwnershipOptions { piivGovernorAddress: string; piivIssuer: PiivIssuer; deployerAddress: string; } export const deployPiivIssuer = async ({ piivGovernorAddress, deployerAddress, }: DeployPiivIssuerOptions) => { console.log("🚀 Deploying Issuer....."); const piivIssuer = await ethers.deployContract("PiivIssuer"); await piivIssuer.waitForDeployment(); const piivIssuerAddress = await piivIssuer.getAddress(); console.log("✅ Deployed Issuer at:", piivIssuerAddress); await transferOwnership({ piivGovernorAddress, piivIssuer, deployerAddress, }); return { piivIssuer, piivIssuerAddress, }; }; const transferOwnership = async ({ piivGovernorAddress, piivIssuer, deployerAddress, }: TransferOwnershipOptions) => { console.log("🌀 Transferring ownership....."); await piivIssuer.transferOwnership(piivGovernorAddress, { from: deployerAddress, }); console.log("✅ Transferred ownership to Governor"); };
import matplotlib.pyplot as plt import numpy as np import math from matplotlib.pyplot import figure as fig # Variable List Description Units alpha = 1 # Dimensionless interaction strength [unitless] Rplanet = 8.61*(10**8) # The planetary radius [centimeters] Rstar =2.6568*(10**10) # The stellar radius [centimeters] v = 1.69*(10**7) # Velocity of the planet through the stellar magnetosphere [cm/s] theta = 90 # Angle between planetary mag. field and the rel. velocity vector [degrees] roh = 7.3*(10**-20) # The plasma density between the star and the planet [g/(cm**3)] eta = 0.01 # The efficiency value for the conversion of energy into radio waves [unitless] omega = 0.16 # The solid angle [steradians] d = 6.79*(10**19) # The distance between the star system and Earth [cm] delta_nu = 3*(10**9) # The observation bandwidth [Hz] a = 1.799*(10**11) # Semi-major axis of the planet [cm] x = np.arange(1, 1001, 1) y = np.arange(0.01, 10.01, 0.01) X, Y = np.meshgrid(x, y) def S_mag(Bdstar, Bdplanet): # Flux density for a magnetosphere S1 = (eta*(Rplanet**2)*Rstar*(v**2)*((4*math.pi*roh)**(1/2)))/(2*omega*(d**2)*delta_nu*a) #Flux density when Bdstar = Bdplanet = 1 Gauss, in erg/s*hz*cm^2 #print(S1) #6.76x10^-29 return (S1*((Bdstar*(Bdplanet**2))**(1/3)))*(10**29) #10^29 is the conversion to microJanskies. def S_ion(Bdstar): # Flux density for an ionosphere S1 = ((eta*(Rplanet**2)*(v**2)*((4*math.pi*roh)**(1/2))*(Rstar**3))/(2*(a**3)*omega*(d**2)*delta_nu)) #Flux density when Bdstar = 1 Gauss, in erg/s*hz*cm^2 print(S1) #1.47x10^-29 return (S1*Bdstar)*(10**29) #10^29 is the conversion to microJanskies. print((eta*(Rplanet**2)*(v**2)*((4*math.pi*roh)**(1/2))*(Rstar**3))/(2*(a**3)*omega*(d**2)*delta_nu)) magline = 0.0032*x maglineplot = plt.plot(x, magline) # print(len(magline)) # print(len(y)) # print(any(y>magline)) Z = (Y>magline) * (S_mag(X, Y)) + (Y<=magline) * (S_ion(X)) heatmap = plt.contourf(x, y, Z, 64, cmap='plasma') thresholdline = plt.contour(x, y, Z, levels=[91.4], colors='white') #plt.clabel(heatmap, inline=False, fmt='%1.1f', fontsize=10) # This makes the colorbar colorbar = plt.colorbar(heatmap) # This makes the color correspond with our chosen cmap value. colorbar.set_label('Theoretical Flux Density (\u03BCJy)', fontsize=28) # Makes the label for the colorbar plt.title('LTT3780 Theoretical Flux Density - Saur Closed Field', fontsize=30) plt.ylabel('Planetary Magnetic Dipole Field Strength (G)', fontsize=26) plt.xlabel('Stellar Magnetic Dipole Field Strength (G)', fontsize=28) plt.ylim(0, 10.01) plt.xticks(fontsize=26) plt.yticks(fontsize=26) plt.savefig("LTT3780HeatmapSaurCF", dpi = 300, bbox_inches='tight',pad_inches = 0) colorbar.ax.tick_params(labelsize=26) plt.show()
import Searchbar, { SelectedStock } from '@/components/searchbar'; import { Card, CardTitle } from '@/components/ui/card'; import StockInfo from '@/components/stock-info'; import Details from '@/components/details'; import Recent from '@/components/recent'; import { useState } from 'react'; import dynamic from 'next/dynamic'; const StockChart = dynamic(() => import ('../components/stock-chart'), { ssr: false }); /*** * Main component that displays all the stock information * @constructor */ const StockSearcher = ()=>{ // keep track of recent searches here const [recentSearches, setRecentSearches] = useState<SelectedStock[]>([]); const [currentStock, setCurrentStock] = useState<SelectedStock>({ id: 0, name: 'AAPL', title: 'Apple Inc.' }); const onNewSearch = (stock: SelectedStock) => { setCurrentStock(stock); setRecentSearches((prevState) => { return [...prevState].filter(curr => curr.name != stock.name).concat([stock]); }); }; return( <div className="container flex flex-col min-w-[500px] items-center md:flex md:flex-col max-w-4xl lg:flex lg:flex-row lg:justify-center lg:items-start lg:max-w-7xl gap-5 mb-10 "> <div className="flex flex-col gap-5 w-2/3"> <Searchbar onNewSearch={onNewSearch}></Searchbar> <Card className="bg-primary-grey h-[200px] "> <StockInfo ticker={currentStock.name}></StockInfo> </Card> <Card className="bg-primary-grey h-[450px] overflow-hidden"> <div className="h-5/6"> <StockChart ticker={currentStock.name}/> </div> </Card> <Card className="bg-primary-grey h-[400px] md:h-[200px] lg:h-[125px]"> <Details ticker={currentStock.name}></Details> </Card> </div> <Card className="bg-primary-grey w-2/3 max-h-[200px] min-h-[400px] lg:max-h-[880px] min-w-[250px] lg:w-[250px] overflow-y-scroll"> <div className='flex flex-row items-center justify-center'> <CardTitle className="text-[#71716F] italic text text-opacity-40 font-medium tracking-wide m-2">History</CardTitle> </div> <Recent recentList={recentSearches} onRecentSelected={onNewSearch}></Recent> </Card> </div> ) } export default StockSearcher;
--- import Header from "../components/Layout/Header/Header.astro"; import Footer from "../components/Layout/Footer.astro"; import { ViewTransitions } from "astro:transitions"; interface Props { title: string; } const { title } = Astro.props; --- <!doctype html> <html lang="es"> <head> <meta charset="UTF-8" /> <meta name="description" content="portfolio personal de diego aldao" /> <meta name="viewport" content="width=device-width" /> <meta name="generator" content={Astro.generator} /> <link rel="shortcut icon" href="/icono.ico" type="image/x-icon" /> <title>{title}</title> <ViewTransitions /> </head> <body> <Header /> <slot /> <Footer /> </body> </html> <style is:global> :root { --main-black: #101010; --main-white: #f2f2f2; --secondary-white: #afafaf; } * { -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; scroll-behavior: smooth; } body { background-color: var(--main-black); } img { width: 100%; height: 100%; object-fit: cover; } .custom-transition { transition: 0.2s cubic-bezier(0.165, 0.84, 0.44, 1); } .custom-transition--slow { transition: 0.4s cubic-bezier(0.165, 0.84, 0.44, 1); } .main-button { backdrop-filter: blur(15px); background-color: rgba(242, 242, 242, 0.05); border: 1px solid rgba(242, 242, 242, 0.1); } p, span, h1, h2, h3, button, a, li, th, td { color: var(--main-white); font-family: "Sharp Sans", sans-serif; } @font-face { font-family: "Sharp Sans"; src: url("/fonts/SharpSans-regular.otf") format("opentype"); font-weight: 400; font-style: normal; } @font-face { font-family: "Sharp Sans"; src: url("/fonts/SharpSans-medium.otf") format("opentype"); font-weight: 500; font-style: normal; } @font-face { font-family: "Sharp Sans"; src: url("/fonts/SharpSans-semibold.otf") format("opentype"); font-weight: 600; font-style: normal; } </style>
import type ApplicationInstance from '@ember/application/instance'; import Service from '@ember/service'; import { getContext } from '@ember/test-helpers'; import type { AssignedVariants, ExperimentName, } from 'my-app/utils/services/experiments'; import { TrackedObject } from 'tracked-built-ins'; function getTestContextOwner() { try { const { owner } = getContext() as { owner: ApplicationInstance }; return owner; } catch { throw new Error( 'To use the test helper, make sure to call `setupTest`, `setupRenderingTest`, or `setupApplicationTest`.', ); } } /** * For each experiment, assign the user to a specific variant. * * @param assignedVariants * * A mapping from the experiment name to the experiment variant * * @example * * Assign the user to a variant for an application test(s). * * ```ts * import { setupExperiments } from 'my-app/tests/helpers'; * * module('Acceptance | products', function (hooks) { * setupApplicationTest(hooks); * * test('A user can do something', async function (assert) { * // ... * }); * * module('nest-product-details, v1', function (nestedHooks) { * setupExperiments(nestedHooks, { * 'nest-product-details': 'v1', * }); * * test('A user can do something else', async function (assert) { * // ... * }); * }); * }); * ``` */ export function setupExperiments<E extends ExperimentName>( hooks: NestedHooks, assignedVariants: Partial<AssignedVariants> = {}, ) { hooks.beforeEach(function () { const owner = getTestContextOwner(); owner.register( 'service:experiments', class ExperimentsService extends Service { assignedVariants = new TrackedObject(assignedVariants); decideVariant() { // Do nothing } getVariant(experimentName: E): AssignedVariants[E] { return this.assignedVariants[experimentName] as AssignedVariants[E]; } }, ); }); }
const express = require('express'); const path = require('path'); const utils = require('./lib/hashUtils'); const partials = require('express-partials'); const bodyParser = require('body-parser'); // const Auth = require('./middleware/auth'); const createSession = require('../server/middleware/auth.js').createSession; const cookieParser = require('./middleware/cookieParser'); const models = require('./models'); const app = express(); app.set('views', `${__dirname}/views`); app.set('view engine', 'ejs'); app.use(partials()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser); app.use(createSession); app.use(express.static(path.join(__dirname, '../public'))); app.get('/', (req, res) => { if (req.session.userId === null) { return res.redirect('/login'); } else { res.render('index'); } }); app.get('/create', (req, res) => { if (req.session.userId === null) { return res.redirect('/login'); } else { res.render('index'); } }); app.get('/links', (req, res, next) => { models.Links.getAll() .then(links => { if (req.session.userId === null) { return res.redirect('/login'); } else { res.status(200).send(links); } }) .error(error => { res.status(500).send(error); }); }); app.post('/links', (req, res, next) => { var url = req.body.url; if (!models.Links.isValidUrl(url)) { // send back a 404 if link is not valid return res.sendStatus(404); } return models.Links.get({ url }) .then(link => { if (link) { throw link; } return models.Links.getUrlTitle(url); }) .then(title => { return models.Links.create({ url: url, title: title, baseUrl: req.headers.origin }); }) .then(results => { return models.Links.get({ id: results.insertId }); }) .then(link => { throw link; }) .error(error => { res.status(500).send(error); }) .catch(link => { // console.log(link) res.status(200).send(link); }); }); /************************************************************/ // Write your authentication routes here /************************************************************/ app.get('/login', (req, res) => { res.render('login'); }); app.post('/login', (req, res) => { var username = req.body.username; var password = req.body.password; return models.Users.get({username: username}) .then((results) => { if (models.Users.compare(password, results.password, results.salt)) { models.Sessions.update({hash: req.session.hash}, {userId: results.id}) return res.redirect('/'); } else { return res.redirect('/login'); } }) .catch(() => { return res.redirect('/login'); }) }); app.get('/signup', (req, res) => { res.render('signup'); }); app.post('/signup', (req, res) => { var username = req.body.username; var password = req.body.password; return models.Users.create({username, password}) .then((result) => { return models.Sessions.update({hash: req.session.hash}, {userId: result.insertId}) }) .then(() => { return res.redirect('/'); }) .catch(error => { if (error.code === 'ER_DUP_ENTRY') { return res.redirect('/signup'); } else { console.log('Sign up Oops') }; }) }); app.get('/logout', (req, res) => { req.cookies = {}; models.Sessions.delete({hash: req.session.hash}) .then(() => { req.session = {}; res.redirect('/login'); }) .catch(() => { console.log('cannot delete'); }) }); /************************************************************/ // Handle the code parameter route last - if all other routes fail // assume the route is a short code and try and handle it here. // If the short-code doesn't exist, send the user to '/' /************************************************************/ app.get('/:code', (req, res, next) => { return models.Links.get({ code: req.params.code }) .tap(link => { if (!link) { throw new Error('Link does not exist'); } return models.Clicks.create({ linkId: link.id }); }) .tap(link => { return models.Links.update(link, { visits: link.visits + 1 }); }) .then(({ url }) => { res.redirect(url); }) .error(error => { res.status(500).send(error); }) .catch(() => { res.redirect('/'); }); }); module.exports = app;
--- layout: post --- ## Introduction/Background Wikipedia is a common source of information that can be accessed around the world, so it’s crucial that accuracy and reliability is maintained. Currently, the Wikipedia community relies on editors to manually classify the quality of articles, however, one study proposes automatically assessing quality using gradient boosted trees. The method incorporates a features set to demonstrate the effectiveness in classifying the reliability of Wikipedia content and simplifying the moderation process [^3]. Another study tests an end-to-end learning method that doesn’t rely on manual feature engineering and utilizes Recurrent Neural Networks, which revealed higher performance in evaluating articles across multiple languages [^2]. These approaches highlight that ML techniques offer more efficient and accurate solutions to determining the reliability of Wikipedia content. To expand on current advancements, our project aims to classify articles based on citations and deliberate misinformation. The dataset used in this project consists of three different template files used by Wikipedia editors to flag for possibly unreliable content: hoax, more citations needed, unreliable sources. For each template, feature has_template will be used as the ground truth [^1]. [View our dataset!][dataset] {: .alert .alert--success} ## Problem Definition The reliability of Wikipedia articles are hindered by deliberate spreading of misinformation and ignorance of the requirements that go into making a quality article such as appropriate citations and valid sources. These problematic articles are moderated by editors who use templates to mark areas in which articles need to be improved including no citations, biased sources, or contradictory information. Reading millions of articles to determine which, if any, problematic templates an article falls into takes substantial time. A ML algorithm that automatically classifies articles as negative or positive for its appropriate templates would save the time of editors and make Wikipedia a more reliable source. ## Methods ### Data Preprocessing For data preprocessing, we implemented tf-idf on three different Wikipedia editor templates (hoax, more_citations_needed, and unreliable_sources. Before tf-idf, each csv was lemmatized. See tfidf_vectorizer.py, data_preprocessor.py and groundtruth.py for tfidf implementation and general data clean up. ### ML Algorithms/Models A Multinomial Naive Bayes was implemented as our first model. We used the vectorized version of all the Wikipedia articles tagged for each template in order to predict whether it was marked as reliable or not. Therefore, Naive Bayes was run three times on an 80/20 data split for each group of articles. See nb.py for Naive Bayes implementation and test/training data split. Naive Bayes was selected because it establishes a good baseline as to how learnable the task is. It is also quite simple and inexpensive, making it a good first algorithm to run. ## Results and Discussion ### Visualizations Unreliable Sources: ![unreliable sources ROC]({{ "/assets/unreliablesources_roc_curve.png" | relative_url }}) ![unreliable sources Precision/Recall]({{ "/assets/unreliablesources_precision_recall_curve.png" | relative_url }}) ![unreliable sources Confusion Matrix]({{ "/assets/unreliablesources_confusion_matrix.png" | relative_url }}) More Citations Needed: ![more citations ROC]({{ "/assets/morecitations_roc_curve.png" | relative_url }}) ![more citations Precision/Recall]({{ "/assets/morecitations_precision_recall_curve.png" | relative_url }}) ![more citations Confusion Matrix]({{ "/assets/morecitations_confusion_matrix.png" | relative_url }}) Hoax: ![hoax ROC]({{ "/assets/hoax_roc_curve.png" | relative_url }}) ![hoax Precision/Recall]({{ "/assets/hoax_precision_recall_curve.png" | relative_url }}) ![hoax Confusion Matrix]({{ "/assets/hoax_confusion_matrix.png" | relative_url }}) ### Quantitative Metrics Hoax Metrics: * F1 Score = 0.4391 * Balanced Accuracy = 0.3746 * Area Under ROC Curve = 0.3280 * All three metrics are much lower than our goal of around 0.7. The model has low precision and recall as shown by the low F1 score, low classification accuracy as the low balanced accuracy indicates, and the low AUC score meaning the model performs similarly to a random classifier. ### Analysis of Naive Bayes The accuracy of the Naive Bayes model was 37.38%. One possible reason that the model performed poorly could be the lack of sufficient training data. The smallest data set, hoax, only contained about 2700 tokens after running TF-IDF which may not be enough for Naive Bayes to correctly find correlations in the data for accurate classification. Another reason may be that our chosen preprocessing method, TF-IDF, does not include any semantic relationships in the text which could improve the classification accuracy. ### Next Steps In regards to improving our classification of the three templates, hoax, more citations needed, unreliable sources, we want to fine tune our Naive Bayes algorithm such as changing parameters or experimenting with different variations of the method. The goal is to raise the accuracy score and ROC AUC so it will be around 0.7 for both. However, it seems there is not enough training data to find patterns based on the tf-idf method, which generated around 27000 tokens for the hoax and more citations needed templates and only 14000 for the unreliable sources template, so we will need to consider other ways to achieve more diverse training data. In addition to enhancing our current method, our next step is implementing a Random Forest algorithm as well as a Gradient Boosted Trees. These may be more fitting for the classification due to handling more complex relationships in the data compared to Naive Bayes. In addition, we might want to explore CNN as it may yield better results for this type of task, but it will require a larger dataset for training in order to capture hierarchical relationships. [^1]: K. Wong, M. Redi, and D. Saez-Trumper, “Wiki-Reliability: A large scale dataset for content reliability on Wikipedia,” Proceedings of the 44th International ACM SIGIR Conference on Research and Development in Information Retrieval, Jul. 2021. doi:10.1145/3404835.3463253 [^2]: Q.-V. Dang and C.-L. Ignat, “An end-to-end learning solution for assessing the quality of Wikipedia articles,” Proceedings of the 13th International Symposium on Open Collaboration, Aug. 2017. doi:10.1145/3125433.3125448 [^3]: M. Schmidt and E. Zangerle, “Article Quality Classification on Wikipedia,” Proceedings of the 15th International Symposium on Open Collaboration, Aug. 2019. doi:10.1145/3306446.3340831 ## Gantt Chart ![gantt]({{ "/assets/gantt.png" | relative_url }}) ## Contribution Table | Name | Contribution | | ------------------------ | ------ | | [Ana Silva Carvalho](#) | ML Algorithms/Model, GitHub Site | | [Remy Bondurant](#) | Data Preprocessing | | [Or Yoked](#) | Visualizations, Next Steps, Gantt Chart | | [James White](#) | Data Preprocessing | | [Swarna Shah](#) | Quantitative Methods, Analysis of ML Algorithms/Models | ## References <!-- {% highlight ruby %} def print_hi(name) puts "Hi, #{name}" end print_hi('Tom') #=> prints 'Hi, Tom' to STDOUT. {% endhighlight %} --> [dataset]: https://figshare.com/articles/dataset/Wiki-Reliability_A_Large_Scale_Dataset_for_Content_Reliability_on_Wikipedia/14113799?file=26648861
### 回溯+排序去重 解题思路 此题与[题47 全排列 II](https://leetcode.cn/problems/permutations-ii/solution/by-alexhilton-m337/)其实是完全一样的,只不过是由数字换成了字符,但本质都一样,可以用题47的方法直接套过来。 唯一的区别就是,先把字符串转成字符数组,然后排列结果直接用字符串拼接,可以省去回溯操作,因为拼接是生成一个新的字符串对象,对原字符 串没有影响。 * java ```java class Solution { private List<String> result; private boolean[] visited; public String[] permutation(String s) { result = new ArrayList<>(); visited = new boolean[s.length()]; char[] payloads = s.toCharArray(); Arrays.sort(payloads); permuate(payloads, ""); return result.stream().toArray(String[]::new); } private void permuate(char[] s, String p) { if (p.length() == s.length) { result.add(p); return; } for (int i = 0; i < s.length; i++) { if (visited[i] || (i > 0 && s[i] == s[i - 1] && !visited[i - 1])) { continue; } visited[i] = true; permuate(s, p + s[i]); visited[i] = false; } } } ``` 时间复杂度$O(n!)$,空间复杂度$O(n)$。 ### 回溯之原地修改数组 与题47一样,也可以直接修改字符数组来实现排列。 * java ```java class Solution { private List<String> result; public String[] permutation(String s) { result = new ArrayList<>(); char[] payloads = s.toCharArray(); permuate(payloads, 0); return result.stream().toArray(String[]::new); } private void permuate(char[] s, int index) { if (index == s.length) { result.add(new String(s)); return; } Set<Character> set = new HashSet<>(); for (int i = index; i < s.length; i++) { if (set.contains(s[i])) { continue; } set.add(s[i]); swap(s, i, index); permuate(s, index + 1); swap(s, i, index); } } private void swap(char[] s, int i, int j) { if (i != j) { char t = s[i]; s[i] = s[j]; s[j] = t; } } } ``` 时间复杂度$O(n!)$,空间复杂度$O(n)$。
{% extends "base.html" %} {% load courses_tags %} {% block content %} {% load_my_courses user as enrollments %} <br> <div class="pure-g-r content-ribbon "> <div class="pure-u-1"> <h4> {% block breadcrumb %} <a class="titles" href="{% url 'accounts:dashboard' %}"> Meu Painel </a> {% endblock %} </h4> </div> <div class="pure-u-1-3"> <div class="pure-menu pure-menu-open new_class"> <ul> <li class="pure-menu-heading"> Bem-Vindo, {{ user }} </li> {% block menu_options %} <li class="pure-menu-heading">Cursos</li> {% for enrollment in enrollments %} <li> <a href="{% url 'courses:announcements' enrollment.course.slug %}"> <i class="fa fa-book"></i> {{ enrollment.course }} </a> </li> {% empty%} <li>Nenhum curso matriculado</li> {% endfor %} <li class="pure-menu-heading"> Configuração Conta</li> <li> <a href="{% url 'accounts:edit' %}"> <i class="fa fa-cog"></i> Editar Informações </a> </li> <li> <a href="{% url 'accounts:edit_password' %}"> <i class="fa fa-lock"></i> Editar Senha </a> </li> {% endblock %} </ul> </div> </div> <div class="pure-u-2-3"> <div class="inner"> {% block dashboard_content %} <h2 class="my_cursos_menu_dashboard">Meus Cursos</h2> {% for enrollment in enrollments %} <div class="well "> <h3 class="titles">{{ enrollment.course }} ({{ enrollment.course.start_date|date:'d/m/Y'|default:'Sem data' }}) </h3> <div class="titles"> {{ enrollment.course.description|linebreaks }} </div> <div class="pure-controls"> <a href="{% url 'courses:announcements' enrollment.course.slug %}" class="button-secondary pure-button">Acessar</a> <a href="{% url 'courses:undo_enrollment' enrollment.course.slug %}" class="button-error pure-button">Cancelar</a> </div> </div> {% empty %} <aside class="pure-u-1"> <p>Nenhum curso inscrito</p> </aside> {% endfor %} {% endblock %} </div> </div> </div> <br> {% endblock %}
#include "lists.h" /** * delete_dnodeint_at_index - Delete node at index of a `dlistint_t` LL * @head: double pointer to head of LL * @index: index position to remove from LL * Return: 1 if succeeded, -1 if failed */ int delete_dnodeint_at_index(dlistint_t **head, unsigned int index) { dlistint_t *deleted_node; deleted_node = get_dnodeint_at_index(*head, index); if (!*head || !deleted_node) return (-1); if (*head == deleted_node) *head = deleted_node->next; if (deleted_node->next) deleted_node->next->prev = deleted_node->prev; if (deleted_node->prev) deleted_node->prev->next = deleted_node->next; free(deleted_node); return (1); } /** * get_dnodeint_at_index - Function that returns * the nth node of a dlistint_t linked list * @head: Head of the doubly linked list * @index: Index of the node to be returned * * Return: A pointer to the the node at given index */ dlistint_t *get_dnodeint_at_index(dlistint_t *head, unsigned int index) { dlistint_t *node; if (!head) return (NULL); node = head; for (; index > 0 && node; index--) node = node->next; return (node); }
package com.dinoraw.chromelogs.presentation.service import android.accessibilityservice.AccessibilityService import android.accessibilityservice.GestureDescription import android.content.Intent import android.graphics.Path import android.view.WindowManager import android.view.accessibility.AccessibilityEvent import com.dinoraw.chromelogs.domain.model.GestureServiceResult import com.dinoraw.chromelogs.presentation.model.GestureServiceState import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update class GestureService : AccessibilityService() { private var _serviceState: MutableStateFlow<GestureServiceState> = MutableStateFlow(GestureServiceState(openedApplication = "", isActive = false)) val serviceState: StateFlow<GestureServiceState> get() = _serviceState.asStateFlow() private lateinit var windowManager: WindowManager companion object { var instance: GestureService? = null } override fun onCreate() { super.onCreate() instance = this windowManager = getSystemService(WINDOW_SERVICE) as WindowManager } override fun onAccessibilityEvent(event: AccessibilityEvent) { _serviceState.update { it.copy(openedApplication = "${event.packageName}") } } override fun onInterrupt() { } override fun onServiceConnected() { _serviceState.update { it.copy(isActive = true) } super.onServiceConnected() } override fun onUnbind(intent: Intent?): Boolean { _serviceState.update { it.copy(isActive = false) } return super.onUnbind(intent) } override fun onDestroy() { super.onDestroy() instance = null } // start and end coordinates in [0.1..0.9] fun onSwipe( heightPixels: Int = windowManager.currentWindowMetrics.bounds.height(), widthPixels: Int = windowManager.currentWindowMetrics.bounds.width(), startX: Float = 0.5f, endX: Float = 0.5f, startY: Float = 0.5f, endY: Float = 0.5f, ): GestureServiceResult { val startOfVerticalSwipe = heightPixels * startY val endOfVerticalSwipe = heightPixels * endY val startOfHorizontalSwipe = widthPixels * startX val endOfHorizontalSwipe = widthPixels * endX val gestureStartTime = 0L val gestureDuration = 500L val swipePath = Path().apply { moveTo(startOfHorizontalSwipe, startOfVerticalSwipe) lineTo(endOfHorizontalSwipe, endOfVerticalSwipe) } val gestureDescription = GestureDescription.Builder() .addStroke( GestureDescription.StrokeDescription( swipePath, gestureStartTime, gestureDuration, false ) ).build() dispatchGesture(gestureDescription, null, null) return GestureServiceResult( startOfHorizontalSwipe = startOfHorizontalSwipe.toInt(), endOfHorizontalSwipe = endOfHorizontalSwipe.toInt(), startOfVerticalSwipe = startOfVerticalSwipe.toInt(), endOfVerticalSwipe = endOfVerticalSwipe.toInt(), maxHeight = heightPixels, maxWidth = widthPixels, ) } }
package com.swamy.dao.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.swamy.dao.IEmployeeDao; import com.swamy.map.row.EmployeeRowMapper; import com.swamy.model.Employee; @Repository public class EmployeeDaoImpl implements IEmployeeDao { private static final String SAVE_EMPLOYEE_SQL = "INSERT INTO EMPLOYEE(ENAME,ESAL) VALUES(?,?)"; private static final String UPDATE_EMPLOYEE_SQL = "UPDATE EMPLOYEE SET ENAME=?,ESAL=? WHERE EID=?"; private static final String DELETE_EMPLOYEE_BY_ID_SQL = "DELETE FROM EMPLOYEE WHERE EID=?"; private static final String GET_ONE_EMPLOYEE_BY_ID_SQL = "SELECT * FROM EMPLOYEE WHERE EID=?"; private static final String GET_ALL_EMPLOYEES_SQL = "SELECT * FROM EMPLOYEE "; @Autowired private JdbcTemplate jt; @Override public void saveEmployee(Employee employee) { jt.update(SAVE_EMPLOYEE_SQL, employee.getEmpName(),employee.getEmpSal()); } @Override public void updateEmployee(Employee employee) { jt.update(UPDATE_EMPLOYEE_SQL, employee.getEmpName(),employee.getEmpSal(),employee.getId()); } @Override public void deleteEmployee(Integer id) { jt.update(DELETE_EMPLOYEE_BY_ID_SQL, id); } @Override public Employee getOneEmployee(Integer id) { return jt.queryForObject(GET_ONE_EMPLOYEE_BY_ID_SQL, new Object[] {id}, new EmployeeRowMapper()); } @Override public List<Employee> getAllEmployees() { List<Employee>list = null; // RowMapper<Employee>rowMapper = new EmployeeRowMapper(); // list = jt.query(GET_ALL_EMPLOYEES_SQL, rowMapper); list = jt.query(GET_ALL_EMPLOYEES_SQL, new EmployeeRowMapper()); return list; } }
import ListItem from "./ListItem"; interface List{ list: ListItem[]; load(): void, save(): void, clearList(): void, addItem(itemObj: ListItem): void, removeItem(id:string): void, } export default class FullList implements List{ static instance: FullList = new FullList(); private constructor(private _list: ListItem[] = []){} get list(): ListItem[]{ return this._list } load(): void { const storedList : string | null = localStorage.getItem('myList'); if (typeof storedList !== 'string') return const parsedList: {_id:string,_item: string, _checked:boolean} [] = JSON.parse(storedList) parsedList.forEach(itemObj => { const newListItem : new ListItem(itemObj._id, itemObj._item, itemObj._checked) }) } save(): void{ localStorage.setItem('myList', JSON.stringify(this._list)); } clearList(): void { this._list = []; this.save(); } addItem(itemObj: ListItem): void { this._list.push(itemObj) this.save(); } removeItem(id: string): void { this._list = this._list.filter(item => item.id !== id) this.save(); } }
import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:multiple_result/multiple_result.dart'; import 'package:shopping_app/features/auth/domain/entities/user_data.dart'; import 'package:shopping_app/features/auth/domain/repositories/user_repository.dart'; import 'package:shopping_app/features/auth/domain/usecases/get_user.dart'; class MockUserRepository extends Mock implements UserRepository {} void main() { late final MockUserRepository mockRepo; late final GetUser usecase; const user = UserData( uid: "1", email: "email", password: "password", firstName: "firstName", lastName: "lastName", phone: "phone", address: "address", ); setUp(() { mockRepo = MockUserRepository(); usecase = GetUser(mockRepo); registerFallbackValue(user); }); test( 'should return remote user of given uid', () async { // arrange when(() => mockRepo.getUser(any())) .thenAnswer((_) async => const Success(user)); // act final result = await usecase(user.uid); // assert expect(result, const Success(user)); verify(() => mockRepo.getUser(user.uid)).called(1); verifyNoMoreInteractions(mockRepo); }, ); }
import sys from os import path curDirname = path.dirname(__file__) while path.basename(path.normpath(curDirname)) != 'ideserve_online': curDirname = path.dirname(curDirname) sys.path.insert(0, curDirname) from BinaryTree.BinaryTreeNode import BinaryTreeNode from unittest import main, TestCase def morrisInorder(root): cur = root t = [] while cur: if not cur.left: if cur.data: t.append(cur.data) cur = cur.right else: pre = cur.left while pre.right and pre.right != cur: pre = pre.right if pre.right: if cur.data: t.append(cur.data) pre.right = None cur = cur.right else: pre.right = cur cur = cur.left return t class CodeTest(TestCase): def testEmpty(self): self.assertListEqual(morrisInorder(BinaryTreeNode(None)), []) def testLeftSkewed(self): root = BinaryTreeNode(1, BinaryTreeNode( 2, BinaryTreeNode(3, BinaryTreeNode(4, BinaryTreeNode(5))))) self.assertListEqual(morrisInorder(root), [5, 4, 3, 2, 1]) def testRightSkewed(self): root = BinaryTreeNode(1, right=BinaryTreeNode( 2, right=BinaryTreeNode(3, right=BinaryTreeNode(4, right=BinaryTreeNode(5))))) self.assertListEqual(morrisInorder(root), [1, 2, 3, 4, 5]) def testNormalTree(self): root = BinaryTreeNode(1) root.left = BinaryTreeNode(2) root.right = BinaryTreeNode(3) root.left.left = BinaryTreeNode(4) root.left.right = BinaryTreeNode(5) root.right.left = BinaryTreeNode(6) root.right.right = BinaryTreeNode(7) root.left.left.left = BinaryTreeNode(8) root.right.left.right = BinaryTreeNode(9) self.assertListEqual(morrisInorder(root), [8, 4, 2, 5, 1, 6, 9, 3, 7]) main()
# [[[ HEADER ]]] use RPerl; # hide from PAUSE indexing; comment must not be on 'package' line below due to Perl::Tidy format mismatch package MyClass_Good; use strict; use warnings; our $VERSION = 0.001_000; # [[[ OO INHERITANCE ]]] use parent qw(RPerl::CompileUnit::Module::Class); use RPerl::CompileUnit::Module::Class; # [[[ CRITICS ]]] ## no critic qw(ProhibitUselessNoCritic ProhibitMagicNumbers RequireCheckedSyscalls) # USER DEFAULT 1: allow numeric values & print operator ## no critic qw(RequireInterpolationOfMetachars) # USER DEFAULT 2: allow single-quoted control characters & sigils ## no critic qw(ProhibitUnusedPrivateSubroutines) # DEVELOPER DEFAULT 3: allow uncalled subroutines # [[[ OO PROPERTIES ]]] our hashref $properties = { foo_property => my string $TYPED_foo_property = 'quite a prize' }; # [[[ SUBROUTINES & OO METHODS ]]] sub foo_subroutine { { my integer $RETURN_TYPE }; ( my integer $foo_argument ) = @ARG; print 'in MyClass_Good::foo_subroutine(), received $foo_argument = ', $foo_argument, "\n"; my string $foo_variable = 'the prodigal son'; print 'in MyClass_Good::foo_subroutine(), have $foo_variable = ', $foo_variable, "\n"; # DEV NOTE: return() w/out space, test grammar token OP01_NAMED_VOID_LPAREN return($foo_argument * 2); } sub foo_method { { my integer::method $RETURN_TYPE }; ( my MyClass_Good $self, my integer $foo_argument ) = @ARG; print 'in MyClass_Good::foo_method(), received $foo_argument = ', $foo_argument, "\n"; print 'in MyClass_Good::foo_method(), have $self->{foo_property} = ', q{'}, $self->{foo_property}, q{'}, "\n"; # DEV NOTE: return () w/ space, test grammar token OP01_NAMED_VOID_LPAREN # DEV NOTE: DO NOT RUN PERLTIDY ON THIS FILE! the line below should read 'return (...);' not 'return(...);' return ($foo_argument * -2); } 1; # end of class
<h1 align=center>Práctica de fundamentos de Backend con Node.js</h1> ### Guía de inicio rápido Para ejecutar la aplicación habrá que tener instalado [Node JS](https://nodejs.org/) e instalar las dependencias usando el siguiente comando: ``` npm install ``` `.env` es el archivo que se utiliza para almacenar las variables de entorno, que son las que se utilizan para configurar el comportamiento de la aplicación. Como se suelen utilizar para almacenar información confidencial, como contraseñas de bbdd o claves de API, este fichero se encuentra includo en el `.gitignore` y puedes utilizar el tuyo propio. Para arrancar la base de datos con los anuncios iniciales, simplemente utiliza el comando ``` node init-db.js ``` Y se responderá a la pregunta de si se desea eliminar la base de datos existente. Para inicializar el proyecto se debe utilizar el comando ``` npm run start:dev ``` Finalmente, para recibir una lista de anuncios filtrada, la llamada debe realizarse de la siguiente manera: ``` http://localhost:3000/ads/search?[...] ``` Algunos ejemplos: - Para filtrar productos cuyo género sea "fantasy" `http://localhost:3000/ads/search?tags=fantasy` (2), o cuyo género sea "ensayo" `http://localhost:3000/ads/search?tags=essay` (2), o sean una trilogía `http://localhost:3000/ads/search?tags=trilogy` (1). - Para buscar los productos que están en venta `http://localhost:3000/ads/search?sale=true` (3) o se buscan `http://localhost:3000/ads/search?sale=false` (2). - Para filtrar productos que incluyan la palabra "la" en su nombre `http://localhost:3000/ads/search?name=la` (3) o "house" `http://localhost:3000/ads/search?name=house` (1). - Para buscar productos cuyo precio sea inferior a 100 `http://localhost:3000/ads/search?price=-100` (4) o exactamente 35 `http://localhost:3000/ads/search?price=35` (1). - O combinarlos juntos, por ejemplo para encontrar un producto de fantasía con el artículo "la" en su nombre, que se busque en un rango de precio inferior a 100 `http://localhost:3000/ads/search?tags=fantasy&sale=false&name=la&price=-100&start=0&limit=2&sort=price`. <div align=center> <img src="public\images\combined-filters.PNG" width="775px" alt="filtered-search-example"> </div> ## Enunciado <p align=justify>Imaginemos que un cliente nos pasa el siguiente <i>briefing</i> para que le hagamos este trabajo:</p> <p align=justify>Desarrollar el API que se ejecutará en el servidor de un servicio de venta de artículos de segunda mano llamado <b>Nodepop</b>. Hazte a la idea que esta API que vas a construir sería utilizado por otros desarrolladores de iOS o Android.</p> <p align=justify>El servicio mantiene anuncios de compra o venta de artículos y permite buscar como poner filtros por varios criterios, por tanto la API a desarrollar deberá proveer los métodos necesarios para esto.</p> <p align=justify>Cada anuncio tiene los siguientes datos:</p> - Nombre del artículo. Un anuncio siempre tendrá un solo artículo. - Si el artículo se _vende_ o _se busca_. - Precio. Será el precio del artículo en caso de ser una oferta de venta. En caso de que sea un anuncio de _se busca_ será el precio que el solicitante estaría dispuesto a pagar. - Foto del artículo. Cada anuncio tendrá solo una foto. - _Tags_ del anuncio. Podrá contener uno o varios de estos cuatro: _work_, _lifestyle_, _motor_ y _mobile_. ### Operaciones que debe realizar el API a crear: - Lista de anuncios con posibilidad de paginación. Con filtros por _tag_, tipo de anuncio (venta o búsqueda), rango de precio (precio min. y precio max.) y nombre de artículo (que empiece por el dato buscado). - Lista de tags existentes. - Creación de anuncios (este requisito es **opcional**). <p align=justify>Los sistemas donde se desplegará el API utilizan bases de datos <a href="https://www.mongodb.com/">MongoDB</a>.</p> <p align=justify>Se solicita que el entregable venga acompañado de una mínima documentación y el código del API esté bien formateado para facilitar su mantenimiento. En esta fase, ya que se desea probar si el modelo de negocio va a funcionar, no serán necesarios ni tests unitarios ni de integración.</p> <p align=right><sub><sup>Gracias a <a href="https://github.com/RodrigoCalvo">Rodrigo</a> por la paciencia, la ayuda y la base de datos.</sup></sub></p>
<?php namespace App\Filament\Resources; use App\Filament\Resources\ProductResource\Pages; use App\Models\Category; use App\Models\CriterionRating; use App\Models\DesignOption; use App\Models\FacilityOption; use App\Models\LocationOption; use App\Models\Product; use App\Models\PublicFacilityOption; use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\MarkdownEditor; use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; use Filament\Forms\Form; use Filament\Resources\Resource; use Filament\Tables; use Filament\Tables\Actions\DeleteAction; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; class ProductResource extends Resource { protected static ?string $model = Product::class; protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack'; protected static ?string $navigationGroup = 'Products'; public static function form(Form $form): Form { $facility = collect(CriterionRating::query()->where('criteria', 'facility')->first('rating')->rating)->mapWithKeys(fn($record) => [$record['value'] => "{$record['label']}: {$record['range']}"]); $publicFacility = collect(CriterionRating::query()->where('criteria', 'public_facility')->first('rating')->rating)->mapWithKeys(fn($record) => [$record['value'] => "{$record['label']}: {$record['range']}"]); // dd(collect(CriterionRating::query()->where('criteria', 'public_facility')->first('rating')->rating)->mapWithKeys(fn($record) => [$record['value'] => "{$record['label']}: {$record['range']}"])); $design = collect(CriterionRating::query()->where('criteria', 'design')->first('rating')->rating)->mapWithKeys(fn($record) => [$record['value'] => "{$record['label']}: {$record['range']}"]); $location = collect(CriterionRating::query()->where('criteria', 'location')->first('rating')->rating)->mapWithKeys(fn($record) => [$record['value'] => "{$record['label']}: {$record['range']}"]); return $form ->schema([ TextInput::make('name')->string()->required(), Select::make('category')->label('cluster')->options(Category::all()->pluck('name', 'id'))->relationship('category', 'name'), MarkdownEditor::make('description')->columnSpanFull(), TextInput::make("occupied")->label('Jumlah Terisi')->integer(), TextInput::make("capacity")->label('Kapasitas')->integer(), TextInput::make("price")->label('Price (Rp)')->integer(), TextInput::make("bedrooms")->integer(), TextInput::make("bathrooms")->integer(), TextInput::make("land_size")->label('Land Size (m2)')->integer(), Select::make("facility_option_id")->label('Facility')->options($facility), Select::make("public_facility_option_id")->label('Public Facility')->options($publicFacility), Select::make("design_option_id")->label('Design')->options($design), Select::make("location_option_id")->label('Location')->options($location), TextInput::make("floors")->integer(), TextInput::make("building_size")->label('Land Size (m2)')->integer(), FileUpload::make('images')->image()->required(), ]); } public static function table(Table $table): Table { return $table ->columns([ TextColumn::make('category.name'), TextColumn::make('name'), ]) ->filters([ Tables\Filters\TrashedFilter::make(), ]) ->actions([ Tables\Actions\EditAction::make(), DeleteAction::make(), ]) ->bulkActions([ Tables\Actions\BulkActionGroup::make([ Tables\Actions\DeleteBulkAction::make(), ]), ]); } public static function getRelations(): array { return [ // ]; } public static function getPages(): array { return [ 'index' => Pages\ListProducts::route('/'), 'create' => Pages\CreateProduct::route('/create'), 'edit' => Pages\EditProduct::route('/{record}/edit'), ]; } }
package com.aranaira.magichem.entities.constructs.ai; import com.aranaira.magichem.block.entity.ext.AbstractBlockEntityWithEfficiency; import com.aranaira.magichem.capabilities.grime.GrimeProvider; import com.aranaira.magichem.registry.ConstructTasksRegistry; import com.mna.api.ManaAndArtificeMod; import com.mna.api.entities.construct.IConstruct; import com.mna.api.entities.construct.ai.ConstructAITask; import com.mna.api.entities.construct.ai.parameter.ConstructAITaskParameter; import com.mna.api.entities.construct.ai.parameter.ConstructTaskIntegerParameter; import com.mna.api.entities.construct.ai.parameter.ConstructTaskPointParameter; import com.mna.entities.constructs.ai.conditionals.ConstructConditional; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.entity.BlockEntity; import java.util.List; public class ConstructHasGrimeLevel extends ConstructConditional<ConstructHasGrimeLevel> { private BlockPos targetApparatus = null; private float targetPercentage = 1; public ConstructHasGrimeLevel(IConstruct<?> construct, ResourceLocation guiIcon) { super(construct, guiIcon); } @Override protected boolean evaluate() { if(targetApparatus == null) return false; BlockEntity be = construct.asEntity().level().getBlockEntity(targetApparatus); if(be instanceof AbstractBlockEntityWithEfficiency bewe) { return ((float)GrimeProvider.getCapability(bewe).getGrime() / (float)bewe.getMaximumGrime()) >= targetPercentage; } return false; } @Override public ResourceLocation getType() { return ManaAndArtificeMod.getConstructTaskRegistry().getKey(ConstructTasksRegistry.QUERY_HAS_GRIME_LEVEL); } @Override protected List<ConstructAITaskParameter> instantiateParameters() { List<ConstructAITaskParameter> parameters = super.instantiateParameters(); parameters.add(new ConstructTaskPointParameter("query_has_grime_level.point")); parameters.add(new ConstructTaskIntegerParameter("query_has_grime_level.int", 1, 100)); return parameters; } @Override public void inflateParameters() { this.getParameter("query_has_grime_level.point").ifPresent((param) -> { if (param instanceof ConstructTaskPointParameter pointParam) { BlockPos targetPos = pointParam.getPosition(); if(targetPos != null) { targetApparatus = targetPos; } } }); this.getParameter("query_has_grime_level.int").ifPresent((param) -> { if (param instanceof ConstructTaskIntegerParameter integerParam) { targetPercentage = (float)integerParam.getValue() / 100.0f; } }); } @Override public boolean isFullyConfigured() { return targetApparatus != null; } @Override public ConstructHasGrimeLevel copyFrom(ConstructAITask<?> other) { if(other instanceof ConstructHasGrimeLevel task) { this.targetApparatus = task.targetApparatus; this.targetPercentage = task.targetPercentage; } return this; } @Override public ConstructHasGrimeLevel duplicate() { return new ConstructHasGrimeLevel(this.construct, this.guiIcon).copyFrom(this); } }
<!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> <script> let tmp = '我是{{name}},年龄{{age}},性别{{sex}}' let person = { name: '张三', age: 18, sex: '男' } console.log(render(tmp, person)) function render(tmp, person) { //{}在reg中是特定字符,在这里我们是想匹配{}本身, 所有要转义 // \d 代表数字 \w 代表字母 \w+代表一个或多个字母 (\w+)表示分组 const reg = /\{\{(\w+)\}\}/ if (reg.test(tmp)) {//return boolean值 console.log('有的', reg.exec(tmp)); const name = reg.exec(tmp)[1] console.log(name); tmp = tmp.replace(reg, person[name]) console.log(tmp) return render(tmp, person) } return tmp // console.log(Object.prototype.toString.call(reg)) //[object RegExp] } </script> </body> </html>
import React from "react" import { Line } from "react-chartjs-2" import "chartjs-adapter-moment" import { LinearScale, CategoryScale, PointElement, LineElement, Chart, TimeScale, Tooltip, plugins, } from "chart.js" Chart.register( LinearScale, CategoryScale, PointElement, LineElement, TimeScale, plugins, Tooltip ) const WeightChart = ({ data }) => { const chartData = { labels: data.map((entry) => entry.DATEON), datasets: [ { label: "Weight (kg)", data: data.map((entry) => entry.WEIGHT), fill: false, borderColor: "rgb(75, 192, 192)", tension: 0.1, }, ], } const options = { scales: { x: { type: "time", time: { unit: "day", displayFormats: { day: "DD MMM YY", }, }, display: false, title: { display: true, text: "Date", }, }, y: { beginAtZero: true, title: { display: true, text: "Weight (kg)", }, }, }, plugins: { legend: { display: true, position: "top", }, title: { display: true, text: "Weight Chart", }, tooltip: { enabled: true, mode: "index", }, }, } return ( <div> <h2>Weight Chart</h2> <Line data={chartData} options={options} /> </div> ) } export default WeightChart
import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { Link } from "react-router-dom"; import { FaTimes } from "react-icons/fa"; const DashedHeader = () => { const [color, setColor] = useState(false); const [home, setHome] = useState(true); const [showSmallNav, setShowSmallNav] = useState(false); useEffect(() => { setShowSmallNav((prev) => !prev); if (window.location.pathname !== "/") { setHome(false); } else { setHome(true); } }, [window.location.pathname]); let listener = null; useEffect(() => { listener = document.addEventListener("scroll", (e) => { var scrolled = document.scrollingElement.scrollTop; if (scrolled > 50) { setColor(true); } else { setColor(false); } }); }, [color]); const navigate = useNavigate(); return ( // <main> <section className={ home ? color ? "fixed top-0 left-0 right-0 flex justify-between z-40 py-5 px-4 bg-white text-black ease-out duration-1000" : "fixed top-0 left-0 right-0 flex justify-between z-30 py-5 px-4 text-white ease-in duration-300 " : "fixed top-0 left-0 right-0 flex justify-between z-30 py-5 px-4 text-black ease-in duration-300 bg-white " } > <div className=""> <h1 className="text-2xl font-thin cursor-pointer sm:text-2xl" onClick={() => navigate("/")} > RICKEY STARCHAN </h1> </div> <div className="hidden md:block"> <ul className="flex text-lg"> <Link to={"/modeling"}> <li className="pl-10 font-thin">MODELING</li> </Link> <Link to={"/nature"}> <li className="pl-10 font-thin">PHOTOGRAPHY</li> </Link> <Link to={"/clothes"}> <li className="pl-10 font-thin">CLOTHING</li> </Link> <Link to="/poetry"> <li className="pl-10 font-thin">POETRY</li> </Link> {/* <Link to="/userupload"> <li className="pl-10 font-thin">UPLOAD</li> </Link> */} </ul> </div> <div className=""> <button className="text-2xl md:hidden" onClick={() => setShowSmallNav((prev) => !prev)} > &#9776; </button> </div> {showSmallNav && ( <div className=" bg-transparent backdrop-blur-xl absolute top-0 left-0 h-screen w-full md:hidden"> <button className="absolute top-5 right-5 text-2xl" onClick={() => setShowSmallNav((prev) => !prev)} > <FaTimes /> </button>{" "} <ul className="grid justify-center mt-64 text-2xl"> <Link to={"/modeling"}> <li className=" font-thin hover:bg-black hover:text-white w-fit p-1 rounded-lg "> MODELING </li> </Link> <Link to={"/nature"}> <li className=" font-thin mt-5 hover:bg-black hover:text-white w-fit p-1 rounded-lg"> PHOTOGRAPHY </li> </Link> <Link to={"/clothes"}> <li className=" font-thin mt-5 hover:bg-black hover:text-white w-fit p-1 rounded-lg "> CLOTHING </li> </Link> <Link to="/poetry"> <li className=" font-thin mt-5 hover:bg-black hover:text-white w-fit p-1 rounded-lg "> POETRY </li> </Link> {/* <Link to="/userupload"> <li className="pl-10 font-thin">UPLOAD</li> </Link> */} </ul> </div> )} </section> // </main> ); }; export default DashedHeader;
import 'package:abe/models/user.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:provider/provider.dart'; import 'package:abe/components/chat_item.dart'; import 'package:abe/models/message.dart'; import 'package:abe/utils/firebase.dart'; import 'package:abe/view_models/user/user_view_model.dart'; import 'package:abe/widgets/indicators.dart'; import '../container/drawer_container.dart'; import '../screens/discover/discoverScreen.dart'; import '../screens/homePage/homePageScreen.dart'; import '../screens/page/pageScreen.dart'; import '../screens/profile/profileScreen.dart'; import '../screens/search/searchScreen.dart'; class Chats extends StatelessWidget { @override Widget build(BuildContext context) { return ChangeNotifierProvider<UserViewModel>( create: (_)=> UserViewModel(), child: ChatPage(), // So Provider.of<FormProvider>(context) can be read here ); } } class ChatPage extends StatefulWidget { const ChatPage({Key? key}) : super(key: key); @override _ChatPageState createState() => _ChatPageState(); } class _ChatPageState extends State<ChatPage> { @override void didChangeDependencies() { super.didChangeDependencies(); } currentUserId() { return firebaseAuth.currentUser?.uid; } @override void initState() { initialize(); setState(() { }); } UserModel? users=UserModel(id:'',education: '',email: '',from: '',number: '',owner: '',photoUrl: '',type: '',username: '',website: '',work: '',about: '',); void initialize()async{ DocumentSnapshot doc = await usersRef!.doc(currentUserId_()).get(); users = UserModel.fromJson((doc?.data()??{}) as Map<String, dynamic>); setState(() { }); } currentUserId_() { return firebaseAuth.currentUser!.uid; } final scaffoldKey = GlobalKey<ScaffoldState>(); Future<void> _onItemTapped(int index) async { _selectedIndex = index; if (index < 5) if(index == 4) { scaffoldKey.currentState!.openEndDrawer(); // CHANGE THIS LINE } else{ Navigator.pushReplacement(context,PageRouteBuilder( pageBuilder: (context, animation1, animation2) => _children[_selectedIndex], )); } if (firstsyncRequired == false && index != 2) setState(() { _selectedIndex = index; }); } int _selectedIndex = 0; bool firstsyncRequired = false; final List<Widget> _children = [ discover(), Chats(), Home(), search(), ]; @override Widget build(BuildContext context) { final height = MediaQuery .of(context) .size .height; final width = MediaQuery .of(context) .size .height; var viewModel = Provider.of<UserViewModel>(context); viewModel.setUser(); return Scaffold( backgroundColor: Colors.white, appBar: PreferredSize( preferredSize: Size.fromHeight(160.0), // here the desired height child: Container( margin: EdgeInsets.all(20), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( flex: 1, child:Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: 25, width: 25, //padding: EdgeInsets.only(left: 10), //margin: EdgeInsets.only(left: 10,top: 20), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.9), blurRadius: 2, offset: const Offset(0,0.2), ), ], ), child: GestureDetector( child:SvgPicture.asset("assets/back.svg",), onTap: () => Navigator.of(context).pop(), ), ) ], ), ), Expanded( flex: 1, child:Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( //margin: EdgeInsets.only(top: 20), child: Text("${users!.username} ",textAlign: TextAlign.center,style: TextStyle(fontFamily: 'Gilroy'),), ), Container( height: 25, width: 25, //padding: EdgeInsets.only(left: 10), // margin: EdgeInsets.only(right: 10,top: 20), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.9), blurRadius: 2, offset: const Offset(0,0.2), ), ], ), child:InkWell( onTap: (){ // Navigator.pushNamed(context, '/profileScreen',arguments: // ScreenArguments(firebaseAuth.currentUser!.uid) // ); if(users?.type=='Personal'){ Navigator.of(context).push(MaterialPageRoute(builder: (context) => profile(profileId: firebaseAuth.currentUser!.uid,))); } else if(users?.type=='Business'){ Navigator.of(context).push(MaterialPageRoute(builder: (context) => pagee(profileId: firebaseAuth.currentUser!.uid,))); } }, child:users?.photoUrl==''? CircleAvatar( backgroundImage: AssetImage("assets/avatar.jpg"), radius: 40.0, ): CircleAvatar( backgroundImage: NetworkImage(users!.photoUrl.toString()), radius: 40.0, ) ), ), ], ), ), ], ), SizedBox(height: 15,), Text("Inbox",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 25,fontFamily: 'Gilroy'),), SizedBox(height: 15,), Container( height: 30, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.1), blurRadius: 3, offset: const Offset(0,0.2), ), ], ), child: Row( children: [ Container( width: 50, height: 30, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.1), blurRadius: 3, offset: const Offset(0,0.2), ), ], ), child: SvgPicture.asset("assets/search.svg",fit: BoxFit.none,), ), SizedBox(width: 5,), Flexible( child: Container( margin: EdgeInsets.all(9), child: TextField( //inputFormatters: [FilteringTextInputFormatter.allow(RegExp('[a-zA-Z0-9]')),], // controller: appPass, onChanged: (appPass){ setState(() { appPass=appPass; }); }, obscureText: true, decoration: InputDecoration( hintText:"Type here..", border: InputBorder.none, hintStyle: TextStyle( fontSize: 12, fontFamily: 'Gilroy' ), ) ), ), ), ], ), ), // StoryScreenUI(), ], ), ) ), body: StreamBuilder<QuerySnapshot>( stream: userChatsStream('${viewModel.user!.uid ?? ""}'), builder: (context, snapshot) { if (snapshot.hasData) { List chatList = snapshot.data!.docs; if (chatList.isNotEmpty) { return ListView.separated( itemCount: chatList.length, itemBuilder: (BuildContext context, int index) { DocumentSnapshot chatListSnapshot = chatList[index]; return StreamBuilder<QuerySnapshot>( stream: messageListStream(chatListSnapshot.id), builder: (context, snapshot) { if (snapshot.hasData) { List messages = snapshot.data!.docs; Message message = Message.fromJson( messages.first.data(), ); List users = chatListSnapshot.get('users'); // remove the current user's id from the Users // list so we can get the second user's id users.remove('${viewModel.user!.uid ?? ""}'); String recipient = users[0]; return ChatItem( userId: recipient, messageCount: messages.length, msg: message.content!, time: message.time!, chatId: chatListSnapshot.id, type: message.type!, currentUserId: "abc", ); } else { return SizedBox(); } }, ); }, separatorBuilder: (BuildContext context, int index) { return Align( alignment: Alignment.centerRight, child: Container( height: 0.5, width: MediaQuery.of(context).size.width / 1.3, child: Divider(), ), ); }, ); } else { return Container(); } } else { return Center(child: circularProgress(context)); } }, ), bottomNavigationBar: Container( decoration: BoxDecoration( boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.1), blurRadius: 0, offset: const Offset(0,0.1), ), ], borderRadius: BorderRadius.all(Radius.circular(50)), ), margin: EdgeInsets.all(5), child: ClipRRect( borderRadius: BorderRadius.all(Radius.circular(50)), child: BottomNavigationBar( backgroundColor: Colors.white, items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Container( //padding: const EdgeInsets.all(7), child:SvgPicture.asset("assets/compass.svg",fit: BoxFit.none,) ), label: '', ), BottomNavigationBarItem( icon: Container( //padding: const EdgeInsets.all(7), child:SvgPicture.asset("assets/mail.svg",fit: BoxFit.none,) ), label: '', ), BottomNavigationBarItem( icon: Container( //padding: const EdgeInsets.all(7), child:SvgPicture.asset("assets/home.svg",fit: BoxFit.none,) ), label: '', ), BottomNavigationBarItem( icon: Container( //padding: const EdgeInsets.all(7), child:SvgPicture.asset("assets/search.svg",fit: BoxFit.none,) ), label: '', ), BottomNavigationBarItem( icon: Container( //padding: const EdgeInsets.all(7), child:SvgPicture.asset("assets/three.svg",fit: BoxFit.none,) ), label: '', ), ], currentIndex: _selectedIndex, selectedItemColor: Colors.black.withOpacity(0.5), unselectedItemColor: Colors.black45, showSelectedLabels: false, showUnselectedLabels: false, onTap: _onItemTapped, selectedFontSize: 12, unselectedFontSize: 12, type: BottomNavigationBarType.fixed, ), ), ), endDrawer: Drawer( shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(20), bottomLeft: Radius.circular(20)), ), width: (width)/3, child: MainDrawer(), ), ); } Stream<QuerySnapshot> userChatsStream(String uid) { return chatRef .where('users', arrayContains: '${uid}') .snapshots(); } Stream<QuerySnapshot> messageListStream(String documentId) { return chatRef .doc(documentId) .collection('messages') .orderBy('time', descending: true) .snapshots(); } }
FactoryBot.define do factory :answer do body { "MyAnswer" } user question trait :invalid do body { nil } end trait :random do body { Faker::Lorem.sentence } end end end
import '/auth/firebase_auth/auth_util.dart'; import '/backend/api_requests/api_calls.dart'; import '/backend/backend.dart'; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import '/flutter_flow/flutter_flow_widgets.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:provider/provider.dart'; import 'remove_video_model.dart'; export 'remove_video_model.dart'; class RemoveVideoWidget extends StatefulWidget { const RemoveVideoWidget({ super.key, this.videoDoc, this.videoId, }); final VideosRecord? videoDoc; final String? videoId; @override State<RemoveVideoWidget> createState() => _RemoveVideoWidgetState(); } class _RemoveVideoWidgetState extends State<RemoveVideoWidget> { late RemoveVideoModel _model; @override void setState(VoidCallback callback) { super.setState(callback); _model.onUpdate(); } @override void initState() { super.initState(); _model = createModel(context, () => RemoveVideoModel()); WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {})); } @override void dispose() { _model.maybeDispose(); super.dispose(); } @override Widget build(BuildContext context) { context.watch<FFAppState>(); return Container( decoration: BoxDecoration( color: FlutterFlowTheme.of(context).secondaryBackground, borderRadius: BorderRadius.circular(8.0), ), child: Padding( padding: EdgeInsets.all(16.0), child: Column( mainAxisSize: MainAxisSize.min, children: [ Align( alignment: AlignmentDirectional(1.0, 0.0), child: InkWell( splashColor: Colors.transparent, focusColor: Colors.transparent, hoverColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () async { Navigator.pop(context); }, child: Icon( Icons.close, color: FlutterFlowTheme.of(context).primaryText, size: 20.0, ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 16.0, 0.0, 0.0), child: Text( FFLocalizations.of(context).getText( 'shr2du0a' /* Do you really want to remove t... */, ), textAlign: TextAlign.center, style: FlutterFlowTheme.of(context).bodyMedium, ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 24.0, 0.0, 16.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ FFButtonWidget( onPressed: () async { var _shouldSetState = false; if (widget.videoId != null && widget.videoId != '') { _model.apiResultyhp123 = await DeleteUploadVideoCall.call( videoId: widget.videoId, ); _shouldSetState = true; Navigator.pop(context); context.pushNamed( 'Video_management', extra: <String, dynamic>{ kTransitionInfoKey: TransitionInfo( hasTransition: true, transitionType: PageTransitionType.fade, duration: Duration(milliseconds: 0), ), }, ); if (_shouldSetState) setState(() {}); return; } else { _model.apiResultyhp = await DeleteUploadVideoCall.call( videoId: widget.videoDoc?.videoId, ); _shouldSetState = true; _model.productListrslt1 = await queryLessonsRecordOnce( queryBuilder: (lessonsRecord) => lessonsRecord.where( 'videoRef', isEqualTo: widget.videoDoc?.reference, ), ); _shouldSetState = true; if (_model.productListrslt1!.length > 0) { _model.lessonCount = _model.productListrslt1?.length; while (_model.lessonCount! > 0) { await _model .productListrslt1![(_model.lessonCount!) - 1] .reference .update({ ...mapToFirestore( { 'videoRef': FieldValue.delete(), }, ), }); _model.lessonCount = (_model.lessonCount!) - 1; } } _model.productRslt1 = await queryCourseRecordOnce( queryBuilder: (courseRecord) => courseRecord.where( 'videoRef', isEqualTo: widget.videoDoc?.reference, ), ); _shouldSetState = true; if (_model.productRslt1!.length > 0) { _model.lessonCount = _model.productRslt1?.length; while (_model.lessonCount! > 0) { await _model .productRslt1![(_model.lessonCount!) - 1] .reference .update({ ...mapToFirestore( { 'videoRef': FieldValue.delete(), }, ), }); _model.lessonCount = (_model.lessonCount!) - 1; } } await widget.videoDoc!.reference.delete(); } Navigator.pop(context); context.pushNamed( 'Video_management', extra: <String, dynamic>{ kTransitionInfoKey: TransitionInfo( hasTransition: true, transitionType: PageTransitionType.fade, duration: Duration(milliseconds: 0), ), }, ); if (_shouldSetState) setState(() {}); }, text: FFLocalizations.of(context).getText( 'z7czwh0y' /* Yes */, ), icon: Icon( Icons.thumb_up_off_alt, size: 18.0, ), options: FFButtonOptions( height: 40.0, padding: EdgeInsetsDirectional.fromSTEB(24.0, 0.0, 24.0, 0.0), iconPadding: EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 0.0), color: FlutterFlowTheme.of(context).primary, textStyle: FlutterFlowTheme.of(context) .titleSmall .override( fontFamily: FlutterFlowTheme.of(context).titleSmallFamily, color: FlutterFlowTheme.of(context).primaryText, fontSize: 14.0, useGoogleFonts: GoogleFonts.asMap().containsKey( FlutterFlowTheme.of(context).titleSmallFamily), ), borderSide: BorderSide( color: Colors.transparent, width: 1.0, ), borderRadius: BorderRadius.circular(8.0), ), ), FFButtonWidget( onPressed: () async { Navigator.pop(context); }, text: FFLocalizations.of(context).getText( 'wen62p5f' /* No */, ), icon: Icon( Icons.thumb_down_off_alt, size: 18.0, ), options: FFButtonOptions( height: 40.0, padding: EdgeInsetsDirectional.fromSTEB(24.0, 0.0, 24.0, 0.0), iconPadding: EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 0.0), color: FlutterFlowTheme.of(context).primary, textStyle: FlutterFlowTheme.of(context) .titleSmall .override( fontFamily: FlutterFlowTheme.of(context).titleSmallFamily, color: FlutterFlowTheme.of(context).primaryText, fontSize: 14.0, useGoogleFonts: GoogleFonts.asMap().containsKey( FlutterFlowTheme.of(context).titleSmallFamily), ), borderSide: BorderSide( color: Colors.transparent, width: 1.0, ), borderRadius: BorderRadius.circular(8.0), ), ), ], ), ), ], ), ), ); } }
<template> <nav class="navbar has-background-black is-fixed-top" role="navigation" aria-label="main navigation"> <div class="container"> <!-- Marca --> <div class="navbar-brand"> <router-link to="/" class="navbar-item"><strong class="blanco">{{ brand }}</strong> <i class="hoja mdi mdi-leaf"></i></router-link> <a role="button" class="navbar-burger burger" aria-label="menu" aria-expanded="false" data-target="navbarMenu" :class="{'is-active': displayMenu}" @click="displayMenu = !displayMenu"> <span aria-hidden="true"></span> <span aria-hidden="true"></span> <span aria-hidden="true"></span> </a> </div> <!-- MEnú activado--> <div id="navbarMenu" class="navbar-menu" :class="{'is-active': displayMenu}"> <div class="navbar-end"> <!-- CARRITO DE COMPRAS--> <a class="navbar-item" data-testId='cart' @click="showCart"> <span class="icon blanco"> <i class="mdi mdi-32px mdi-cart"></i> <!--si, el getters es mayor a 0, muestra el valor--> <span class=" blanco tag is-success" v-if="$store.getters.shoppingCart.list.length > 0"> {{ $store.getters.shoppingCart.list.length }} </span> </span> </a> <!-- Login --> <router-link v-if="!isLoggedIn" to="/login" class="navbar-item"> Ingresa </router-link> <div v-else class="navbar-item has-dropdown is-hoverable"> <a class="navbar-link blanco"> <span class="icon blanco"> <i class="blanco mdi mdi-32px mdi-account"></i> </span> {{ getCurrentUser ? getCurrentUser.email : ''}} </a> <div class="navbar-dropdown"> <a class="navbar-item" @click="showCart"> Ver Carrito </a> <hr class="navbar-divider"> <router-link class="navbar-item" to="/create"> <span @click="displayMenu = !displayMenu">Añadir productos</span> </router-link> <hr class="navbar-divider"> <a class="navbar-item" @click="logout"> Cerrar Sesión </a> </div> </div> </div> </div> <!-- --> </div> <!-- container --> </nav> </template> <script> import Firebase from 'firebase'; export default { name: 'Navbar', components: {}, props: { brand: { type: String, default: '', }, }, data() { return { displayMenu: false, } }, methods: { showCart(event) { event.preventDefault(); this.$store.dispatch('updateShowCart', true) }, logout() { Firebase.auth().signOut().then( () => { this.$router.push('login') this.$store.dispatch('updateUser', false) this.displayMenu = false }) } }, computed: { isLoggedIn() { return this.$store.getters.isLoggedIn }, getCurrentUser(){ return Firebase.auth().currentUser ? Firebase.auth().currentUser : '' } }, watch: {}, created() {}, mounted() {} } </script> <style lang="scss" scoped> nav { height: 3.25rem; } .navbar-end{ padding: 4px } .blanco{ color:white!important; } .hoja { color:white; padding-left: 10px; } </style>
import { FC } from 'react'; import { NextSeo } from 'next-seo'; import useTranslation from 'next-translate/useTranslation'; import { Header } from '@/components/Header'; import { PageTitleBlog } from '@/components/PageTitleBlog'; import { Blog } from '@/components/Blog'; import { ContactSection } from '@/components/ContactSection'; import { PageSmoothScroll } from '@/components/PageSmoothScroll'; import { PageTransitionMask } from '@/components/PageTransitionMask'; import { useStopCssAnimationsOnResize } from '@/hooks/useStopCssAnimationsOnResize'; import { IBlogPost } from '@/types'; interface IProps { blogPosts: IBlogPost[]; blogPostsCount: number; } const BlogLayout: FC<IProps> = ({ blogPosts, blogPostsCount }: IProps) => { const { t } = useTranslation(); useStopCssAnimationsOnResize(); const tSeoTitle = t('seo:blog.title'); const tSeoDescription = t('seo:blog.description'); return ( <> <NextSeo title={tSeoTitle} description={tSeoDescription} /> <Header /> <PageSmoothScroll> <PageTitleBlog hideAllPosts={blogPostsCount <= blogPosts.length} /> <Blog type="main" blogPosts={blogPosts} /> <ContactSection /> </PageSmoothScroll> <PageTransitionMask /> </> ); }; export default BlogLayout;
import * as React from "react"; interface Props { name: string; label: string; placeholder?: string; value: any; onChange: (fieldName: string, value: string) => void; error?: string; } export const Input: React.FunctionComponent<Props> = (props) => { console.log("props", props); console.log("props.value", props.value); return ( <div className={formatWrapperClass(props)}> <label htmlFor={props.name}>{props.label}</label> <div className="field"> <input type={ props.name === "dateOperation" ? "date" : props.name === "amount" ? "number" : "text" } name={props.name} className="form-control" placeholder={props.placeholder} value={ props.value ? props.name === "dateOperation" ? new Date(props.value) : props.value : "" } onChange={onChangeInput(props)} /> </div> <div className="help-block">{props.error}</div> </div> ); }; const formatWrapperClass = (props: Props) => { const wrapperClass = "form-group"; return props.error ? `${wrapperClass} has-error` : wrapperClass; }; const onChangeInput = (props: Props) => (e: React.ChangeEvent<HTMLInputElement>) => { props.onChange(e.target.name, e.target.value); };
--- sidebar: sidebar permalink: express/express-c-series-c190-deploy_deploy_cisco_ucs_c-series_rack_server.html keywords: deploy, cisco, ucs, c, series, rack, server, cimc, boot, disable, iscsi, vnics summary: ここでは、手順 Express 構成で使用する Cisco UCS C シリーズスタンドアロンラックサーバを設定するための詳細な FlexPod について説明します。 --- = Cisco UCS C シリーズラックサーバを導入する :hardbreaks: :allow-uri-read: :nofooter: :icons: font :linkattrs: :imagesdir: ./../media/ [role="lead"] ここでは、手順 Express 構成で使用する Cisco UCS C シリーズスタンドアロンラックサーバを設定するための詳細な FlexPod について説明します。 == CIMC の Cisco UCS C シリーズスタンドアロンサーバの初期セットアップを実行します Cisco UCS C シリーズスタンドアロンサーバの CIMC インターフェイスの初期セットアップを行うには、次の手順を実行します。 次の表に、 Cisco UCS C シリーズスタンドアロンサーバごとに CIMC を設定するために必要な情報を示します。 |=== | 詳細( Detail ) | 詳細値 | CIMC IP アドレス | \<CIMC_IP>> | CIMC サブネットマスク | \<CIMC_netmask に追加されました | CIMC デフォルトゲートウェイ | \<CIMC_Gateway>> のようになります |=== NOTE: この検証で使用されている CIMC のバージョンは CIMC 4.4.0(4) です。 === すべてのサーバ . Cisco KVM (キーボード、ビデオ、およびマウス)ドングル(サーバに付属)を、サーバ前面の KVM ポートに取り付けます。VGA モニタと USB キーボードを、 KVM ドングルの対応するポートに接続します。 + サーバの電源を入れ、 CIMC 設定を開始するかどうか確認するプロンプトが表示されたら F8 キーを押します。 + image:express-c-series-c190-deploy_image5.png["エラー:グラフィックイメージがありません"] . CIMC 設定ユーティリティで、次のオプションを設定します。 + .. ネットワークインターフェイスカード( NIC )モード: + 専用の「 [X] 」 .. IP (ベーシック): + IPv4 :「 [X] 」 + DHCP が有効になっています + CIMC IP:`\<CIMC_IP>` + プレフィックス / サブネット: `\<CIMC_netmask>` + ゲートウェイ : `\<CIMC_gateway>` .. VLAN ( Advanced ): VLAN タギングを無効にする場合は、オフのままにします。 + NIC の冗長性 + なし :[X]` + image:express-c-series-c190-deploy_image6.png["エラー:グラフィックイメージがありません"] . F1 キーを押して、その他の設定を表示します。 + .. 共通プロパティ: + ホスト名 : `\<ESXi_host_name>` + ダイナミック DNS:`[] + 工場出荷時のデフォルト:オフのままにします。 .. デフォルトユーザ( basic ): + デフォルトのパスワード: `\<admin_password>` + パスワード「 \<admin_password>>` 」を再入力します + ポートのプロパティ:デフォルト値を使用します。 + ポートプロファイル:クリアしたままにします。 . F10 キーを押し、 CIMC インターフェイス設定を保存します。 . 設定を保存したら、 Esc キーを押して終了します。 == Cisco UCS C シリーズサーバの iSCSI ブートを設定します この FlexPod Express 構成では、 iSCSI ブートに VIC1457 が使用されます。 次の表に、 iSCSI ブートの設定に必要な情報を示します。 NOTE: 斜体のフォントは、 ESXi ホストごとに一意の変数を示します。 |=== | 詳細( Detail ) | 詳細値 | ESXi ホストイニシエータの名前 | \<<var_UCS_initiator_name_a>> を参照してください | ESXi ホスト iSCSI-A IP | \<<var_esxi_host_iscsia_ip>> | ESXi ホスト iSCSI - ネットワークマスク | \<<var_esxi_host_iscsia_mask>> を指定します | ESXi ホスト iSCSI A のデフォルトゲートウェイ | \<<var_esxi_host_iscsia_gateway>> を指定します | ESXi ホストイニシエータ B の名前 | \<<var_UCS_initiator_name_b>> を参照してください | ESXi ホスト iSCSI-B IP | \<<var_esxi_host_iSCSIb_ip>> | ESXi ホストの iSCSI-B ネットワークマスク | \<<var_esxi_host_iSCSIb_mask>> を指定します | ESXi ホスト iSCSI-B ゲートウェイ | \<<var_esxi_host_iSCSIb_gateway>> を指定します | IP アドレス iSCSI_lif01a | \<<var_iscsi_dlif01a>> | IP アドレス iSCSI_lif02a | \<<var_iscsi_dlif02a>> | IP アドレス iSCSI_lif01b | \<<var_iscsi_dlif01b>> を参照してください | IP アドレス iSCSI_lif02b | \<<var_iscsi_dlif02b>> | インフラ SVM IQN | \<<var_svm_iqn>> をクリックします |=== === 起動順序の設定 ブート順の設定を行うには、次の手順を実行します。 . CIMC インターフェイスのブラウザウィンドウで、 [Compute] タブをクリックし、 BIOS を選択します。 . Configure Boot Order (起動順序の設定)をクリックし、 OK をクリックします。 + image:express-c-series-c190-deploy_image7.png["エラー:グラフィックイメージがありません"] . Add Boot Device の下のデバイスをクリックし、 Advanced タブに移動して、次のデバイスを設定します。 + .. 仮想メディアの追加: + 名前: KVM-CD-DVD + サブタイプ: KVM マップ DVD + 状態:有効 + 順序: 1. .. iSCSI ブートの追加: + 名前: iSCSI-A + 状態:有効 + ご注文: 2. + スロット: mLOM + ポート: 1. .. Add iSCSI Boot をクリックします。 + 名前: iSCSI-B + 状態:有効 + 順序: 3. + スロット: mLOM + ポート: 3. . Add Device をクリックします。 . [ 変更の保存 ] をクリックし、 [ 閉じる ] をクリックします。 + image:express-c-series-c190-deploy_image8.png["エラー:グラフィックイメージがありません"] . サーバをリブートして、新しいブート順序でブートします。 === RAID コントローラを無効にする(存在する場合) C シリーズサーバに RAID コントローラが搭載されている場合は、次の手順を実行します。SAN 構成からのブートでは RAID コントローラは必要ありません。必要に応じて、サーバから RAID コントローラを物理的に取り外すこともできます。 . Compute タブで、 CIMC の左側のナビゲーションペインで BIOS をクリックします。 . [Configure BIOS] を選択します。 . 下にスクロールして [PCIe Slot:HBA Option ROM] を表示します。 . 値が無効になっていない場合は、 disabled に設定します。 + image:express-c-series-c190-deploy_image9.png["エラー:グラフィックイメージがありません"] == iSCSI ブート用に Cisco VIC1457 を設定します 次の設定手順は、 Cisco VIC 1457 で iSCSI ブートを使用する場合の手順です。 NOTE: ポート 0 、 1 、 2 、および 3 間のデフォルトのポートチャネリングをオフにしてから、 4 つの個別ポートを設定する必要があります。ポートチャネリングがオフになっていない場合、 VIC 1457 には 2 つのポートのみが表示されます。CIMC でポートチャネルを有効にするには、次の手順を実行します。 . [ ネットワーク ] タブで、 [Adapter Card mLOM] をクリックします。 . General タブで、ポートチャネルのチェックを外します。 . 変更を保存し、 CIMC をリブートします。 + image:express-c-series-c190-deploy_image10.png["エラー:グラフィックイメージがありません"] === iSCSI vNIC を作成します iSCSI vNIC を作成するには、次の手順を実行します。 . [ ネットワーク ] タブで、 [Adapter Card mLOM] をクリックします。 . [Add vNIC] をクリックして vNIC を作成します。 . [Add vNIC] セクションで、次の設定を入力します。 + ** 名前: eth1 ** CDN 名: iscsi-vNIC-A ** MTU : 9000 ** デフォルト VLAN : `\<<var_iscsi_vlan_a>` ** VLAN モード:トランク ** Enable PXE boot: チェック . [Add vNIC] をクリックし、 [OK] をクリックします。 . このプロセスを繰り返して、 2 番目の vNIC を追加します。 + ** vNIC eth3 に名前を付けます。 ** CDN 名: iscsi-vNIC-B ** VLAN として「 \<<var_iscsi_vlan_b>> 」と入力します。 ** アップリンクポートを 3 に設定します。 + image:express-c-series-c190-deploy_image11.png["エラー:グラフィックイメージがありません"] . 左側の vNIC eth1 を選択します。 + image:express-c-series-c190-deploy_image12.png["エラー:グラフィックイメージがありません"] . iSCSI Boot Properties ( iSCSI 起動プロパティ)で、イニシエータの詳細を入力します。 + ** 名前 : `\<<var_ucsa_initiator_name_a>` ** IP アドレス :`\<<var_esxi_hosta_iscsia_ip>> ** サブネットマスク : `\<<var_esxi_hosta_iscsia_mask>> ** ゲートウェイ :`\<<var_esxi_hosta_iscsia_gateway>> + image:express-c-series-c190-deploy_image13.png["エラー:グラフィックイメージがありません"] . プライマリターゲットの詳細を入力します。 + ** name :インフラ SVM の IQN 番号 ** IP アドレス: iscsi_dlif01a の IP アドレス ** ブート LUN : 0 . セカンダリターゲットの詳細を入力します。 + ** name :インフラ SVM の IQN 番号 ** IP アドレス: iSCSI_lif02a の IP アドレス ** ブート LUN : 0 + NOTE: ストレージ IQN 番号を取得するには 'vserver iscsi show コマンドを実行します + NOTE: 各 vNIC の IQN 名を必ず記録してください。これらのファイルはあとで必要になります。さらに、イニシエータの IQN 名は、各サーバおよび iSCSI vNIC で一意である必要があります。 . [Save Changes] をクリックします。 . vNIC eth3 を選択し、 Host Ethernet Interfaces セクションの上部にある iSCSI Boot ボタンをクリックします。 . 手順を繰り返して eth3 を設定します。 . イニシエータの詳細を入力します。 + ** 名前 : `\<<var_ucsa_initiator_name_b>` ** IP アドレス : `\<<var_esxi_HostB_iSCSIb_ip>` ** サブネットマスク: `\<<var_esxi_HostB_iSCSIb_mask>> ** ゲートウェイ : `\<<var_esxi_HostB_iSCSIb_gateway>> + image:express-c-series-c190-deploy_image14.png["エラー:グラフィックイメージがありません"] . プライマリターゲットの詳細を入力します。 + ** name :インフラ SVM の IQN 番号 ** IP アドレス: iscsi_dlif01b の IP アドレス ** ブート LUN : 0 . セカンダリターゲットの詳細を入力します。 + ** name :インフラ SVM の IQN 番号 ** IP アドレス: iscsi_dlif02b の IP アドレス ** ブート LUN : 0 + NOTE: ストレージ IQN 番号は、「 vserver iscsi show 」コマンドを使用して取得できます。 + NOTE: 各 vNIC の IQN 名を必ず記録してください。これらのファイルはあとで必要になります。 . [Save Changes] をクリックします。 . このプロセスを繰り返して、 Cisco UCS サーバ B の iSCSI ブートを設定します === ESXi の vNIC を設定します ESXi の vNIC を設定するには、次の手順を実行します。 . CIMC インターフェイスブラウザウィンドウで、 [Inventory] をクリックし、右側のペインで [Cisco VIC adapters] をクリックします。 . [Networking] > [Adapter Card mLOM] で [vNICs] タブを選択し、その下の vNIC を選択します。 . eth0 を選択し、 Properties をクリックします。 . MTU を 9000 に設定します。[Save Changes] をクリックします。 . VLAN をネイティブ VLAN 2 に設定します。 + image:express-c-series-c190-deploy_image15.png["エラー:グラフィックイメージがありません"] . eth1 に手順 3 と 4 を繰り返し、アップリンクポートが eth1 に 1 に設定されていることを確認します。 + image:express-c-series-c190-deploy_image16.png["エラー:グラフィックイメージがありません"] + NOTE: この手順は、最初の Cisco UCS サーバノードごと、および環境に追加する Cisco UCS サーバノードごとに繰り返す必要があります。 link:express-c-series-c190-deploy_netapp_aff_storage_deployment_procedure_@part_2@.html["次の記事:NetApp AFF ストレージ導入手順 (パート2)"]
import type { PSEnv, PSMap, PSModule, PSValue } from "./types.ts"; import type { Operation } from "./deps.ts"; import { expect, useAbortSignal } from "./deps.ts"; import { exclude, lookup } from "./psmap.ts"; import { createYSEnv, parse } from "./evaluate.ts"; import { recognize } from "./recognize.ts"; import * as data from "./data.ts"; export interface LoadOptions { location: string | URL; base?: string; env?: PSEnv; canon?: PSMap; } export function* load(options: LoadOptions): Operation<PSModule> { let { location, base, env, canon } = options; let url = typeof location === "string" ? new URL(location, base) : location; let content = yield* read(url); let source = parse(content); return yield* moduleEval({ source, location: url, env, canon }); } export interface ModuleEvalOptions { location: string | URL; source: PSValue; env?: PSEnv; canon?: PSMap; } export function* moduleEval(options: ModuleEvalOptions): Operation<PSModule> { let { location, source, env = createYSEnv() } = options; let url = typeof location === "string" ? new URL(location) : location; let mod: PSModule = { location: location.toString(), source, value: source, imports: [], }; if (source.type !== "map") { return mod; } let scope = data.map({}); let canon = options.canon ?? data.map({}); let imports = lookup("$import", source); let rest = exclude(["$import"], source); if (imports.type === "just") { if (imports.value.type !== "map") { throw new Error( `imports must be specified as a mapping of names: URL but was ${imports.value.type}`, ); } for (let [names, loc] of imports.value.value.entries()) { if (names.type !== "string") { throw new Error( `imported symbols should be a string, but was ${names.type}`, ); } if (loc.type !== "string") { throw new Error( `import location should be a url string, but was ${loc.type}`, ); } let bindings = matchBindings(names.value); let dep = loc.value === "--canon--" ? ({ location: loc.value, source: canon, value: canon, imports: [], }) : yield* load({ location: loc.value, base: url.toString(), env, }); mod.imports.push({ module: dep, bindings, }); for (let binding of bindings) { let name = binding.alias ?? binding.name; let value; if (binding.all) { value = dep.value; } else if (dep.value.type !== "map") { throw new Error( `tried to import a name from ${dep.location}, but it is not a 'map'. It is a ${dep.value.type}`, ); } else { let result = lookup(binding.name, dep.value); if (result.type === "nothing") { throw new Error( `module ${dep.location} does not have a member named '${binding.name}'`, ); } else { value = result.value; } } scope.value.set(data.string(name), value); } } } mod.value = data.map({}); let expanded = recognize(rest); if (expanded.type !== "map") { mod.value = yield* env.eval(expanded, scope); } else { for (let [key, value] of expanded.value.entries()) { let evaluated = yield* env.eval(value, scope); scope.value.set(key, evaluated); mod.value.value.set(key, yield* env.eval(value, scope)); } } return mod; } function* read(url: URL): Operation<string> { if (url.protocol === "file:") { return yield* expect(Deno.readTextFile(url)); } else if (url.protocol.startsWith("http")) { let signal = yield* useAbortSignal(); let response = yield* expect(fetch(url, { signal })); if (!response.ok) { throw new Error(`${url}: ${response.status} ${response.statusText}`); } return yield* expect(response.text()); } else { throw new Error( `cannot load module from ${url}: unsupported protocol '${url.protocol}'`, ); } } function matchBindings(spec: string): PSModule["imports"][number]["bindings"] { return spec.trim().split(/\s*,\s*/).map((spec) => { let splatMatch = spec.match(/(.+)<<$/); if (splatMatch) { return { name: splatMatch[1], all: true, }; } else { return { name: spec, all: false, }; } }); }
import { keyframes } from "@stitches/react"; import { styled } from "twin.macro"; const bounce = keyframes({ "0%": { transform: "scaleY(0)" }, "80%": { transform: "scaleY(1.03)" }, "100%": { transform: "scaleY(1)" }, }); const Svg = styled.svg({ animation: `${bounce} linear 600ms`, transformOrigin: "50% 100%", margin: "auto", }); interface BarProps { width: string; height: string; data: string; color: string; percentage: string; value: string; name: string; } function SingleBar({ width, height, data, color, percentage, value, name, }: BarProps) { return ( <div tw="flex flex-col items-center"> <Svg style={{ marginLeft: 5 }} width={width} height={height}> <path d={data} fill={color} tw="rounded-md" /> </Svg> <div tw="flex flex-col items-center justify-center space-y-1"> <div tw="mt-2"> <p tw="text-xs"> {value} <span tw="text-xs text-gray-500">{percentage}</span> </p> </div> <p tw="text-xs capitalize">{name}</p> </div> </div> ); } interface ListItem { percentage: number; value: number; name: string; color: string; } const max = 300; export function Chart({ list }: { list: ListItem[] }) { return ( <div tw="flex text-center flex-col items-center"> <div tw="flex space-x-6"> {list.map((e) => { const y = max - (max * e.percentage) / 100; return ( <SingleBar key={e.name} width="80px" height="300px" color={e.color || "#ea1"} percentage={`(${Number(e.percentage).toFixed(1)} %)`} value={`${e.value}`} data={`M 0 ${max} L 0 ${y + 5} C 0 ${y + 5} 0 ${y} 5 ${y} L 75 ${y} C 80 ${y} 80 ${y + 5} 80 ${y + 5} L 80 ${max} Z`} name={e.name} /> ); })} </div> </div> ); }
import allure import random import re import string from faker import Faker from selenium.webdriver.common.by import By from lib.page_objects.BasePage import BasePage from lib.utils.constants import Constants from lib.web_elements.signup_detail_elements import SignUpDetailElements regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' class SignupDetailObject(BasePage): def __init__(self, driver): self.driver = driver @allure.step("Click Age Month Dropdown") def click_select_age_month_field(self): self.click(SignUpDetailElements.AGE_MONTH_FIELD, "Age Month Dropdown") @allure.step("Select month_number {1}") def select_age_month(self, month_number): if str(month_number) == "": element = self.get_element_text(SignUpDetailElements.AGE_MONTH_FIELD_ERROR_FIELD, "") # print(element + "<br>") else: month_option = (By.XPATH, "//select[@id='edit-field-birthday-und-0-value-month']//option[@value='" + str( month_number) + "']") self.click(month_option, "Month Number: " + str(month_number)) @allure.step("Click Agree Terms checkbox") def click_agree_checkbox(self): self.click(SignUpDetailElements.AGREE_CHECKBOX, "Agree Terms checkbox") @allure.step("Click Teen Continue Button") def click_continue_button(self): self.click(SignUpDetailElements.CONTINUE_BUTTON, "Teen Continue Button") @allure.step("Click Age Year Dropdown") def click_select_age_year_field(self): self.click(SignUpDetailElements.AGE_YEAR_FIELD, "Age Year Dropdown") @allure.step("Click User Account") def click_select_user_account(self): self.click(SignUpDetailElements.USERACCOUNTBUTTON, "User Account ") @allure.step("Click Sign Out Button") def click_select_signout_button(self): self.click(SignUpDetailElements.SIGNOUTBUTTON, "Sign Out Button") @allure.step("Select year {1}") def select_age_year(self, year): year_option = ( By.XPATH, "//select[@id='edit-field-birthday-und-0-value-year']//option[@value='" + str(year) + "']") self.click(year_option, "Month Year: " + str(year)) @allure.step("Click Not US checkbox") def click_not_us_checkbox(self): self.click(SignUpDetailElements.NOT_US_CHECKBOX, "Not US checkbox") @allure.step("Click Country Dropdown") def click_country_field(self): self.click(SignUpDetailElements.COUNTRY_FIELD, "Country Dropdown") @allure.step("Select country_name {1}") def select_country(self, country_name): if country_name == "" or country_name == "Select": # print(country_name) self.click_country_field() self.wait(5) self.wait(5) element = self.get_element_text(SignUpDetailElements.COUNTRY_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") else: country_option = ( By.XPATH, "//select[@id='edit-field-user-location-und-0-country']//option[text()='" + str(country_name) + "']") self.click(country_option, "Country: " + str(country_name)) @allure.step("Enter Teen Email {1}") def enter_teen_email(self, email): if re.search(regex, email): self.enter_text(SignUpDetailElements.TEEN_EMAIL_FIELD, email, "Teen Email") else: self.enter_text(SignUpDetailElements.TEEN_EMAIL_FIELD, email) self.wait(5) element = self.get_element_text(SignUpDetailElements.ADULT_EMAIL_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") @allure.step("Enter UserName {1}") def enter_username(self, username): if username != "": self.enter_text(SignUpDetailElements.USERNAME_FIELD, username, "Teen Username") else: self.enter_text(SignUpDetailElements.USERNAME_FIELD, username) self.wait(5) element = self.get_element_text(SignUpDetailElements.USERNAME_FIELD_ERROR_MESSAGE, "") print(element + "<br>") @allure.step("Enter Password {1}") def enter_password(self, password): if password != "": self.enter_text(SignUpDetailElements.PASSWORD_FIELD, password, "Teen Password") else: self.enter_text(SignUpDetailElements.PASSWORD_FIELD, password) self.wait(5) element = self.get_element_text(SignUpDetailElements.PASSWORD_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") @allure.step("Click Next Button") def click_next_button(self): self.click(SignUpDetailElements.NEXT_BUTTON, "Next Button") def generate_random_password(self, length=8): password_characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(password_characters) for i in range(length)) return password def generate_test_data(self, category='adult'): faker = Faker() test_data = faker.simple_profile() splitted_name = test_data['name'].split(" ", 1) if category == 'adult': return { 'first_name': splitted_name[0], 'last_name': splitted_name[1], 'email': test_data['mail'], 'username': test_data['username'], 'password': Constants.SIGNUP_DETAIL_TEST_PASSWORD, } elif category == 'kid': parent_test_data = faker.simple_profile() return { 'username': test_data['username'], 'password': Constants.SIGNUP_DETAIL_TEST_PASSWORD, 'parent_email': parent_test_data['mail'] } elif category == 'teen': test_data = faker.simple_profile() return { 'email': test_data['mail'], 'username': test_data['username'], 'password': Constants.SIGNUP_DETAIL_TEST_PASSWORD, 'parent_email': test_data['mail'] } # Adult Signup Page Actions @allure.step("Enter First Name{1} ") def enter_adult_first_name(self, first_name): if first_name != "": self.enter_text(SignUpDetailElements.ADULT_FIRST_NAME_FIELD, first_name, "Adult First Name") else: self.enter_text(SignUpDetailElements.ADULT_FIRST_NAME_FIELD, first_name) self.wait(5) element = self.get_element_text(SignUpDetailElements.ADULT_FIRST_NAME_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") @allure.step("Enter LastName {1} ") def enter_adult_last_name(self, last_name): if last_name != "": self.enter_text(SignUpDetailElements.ADULT_LAST_NAME_FIELD, last_name, "Adult Last Name") else: self.enter_text(SignUpDetailElements.ADULT_LAST_NAME_FIELD, last_name) self.wait(5) element = self.get_element_text(SignUpDetailElements.ADULT_LAST_NAME_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") @allure.step("Enter Email {1} ") def enter_adult_email(self, email): if re.search(regex, email): self.enter_text(SignUpDetailElements.ADULT_EMAIL_FIELD, email, "Adult Email") else: self.enter_text(SignUpDetailElements.ADULT_EMAIL_FIELD, email) self.wait(5) element = self.get_element_text(SignUpDetailElements.ADULT_EMAIL_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") @allure.step("Enter UserName {1}") def enter_adult_username(self, username): if username != "": self.enter_text(SignUpDetailElements.ADULT_USERNAME_FIELD, username, "Adult Username") else: self.enter_text(SignUpDetailElements.ADULT_USERNAME_FIELD, username) self.wait(5) element = self.get_element_text(SignUpDetailElements.ADULT_USERNAME_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") @allure.step("Enter Password {1}") def enter_adult_password(self, password): if password != "": self.enter_text(SignUpDetailElements.ADULT_PASSWORD_FIELD, password, "Adult Password") else: self.enter_text(SignUpDetailElements.ADULT_PASSWORD_FIELD, password) self.wait(5) element = self.get_element_text(SignUpDetailElements.ADULT_PASSWORD_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") @allure.step("Click Not US checbox") def click_adult_not_us_checkbox(self): self.click(SignUpDetailElements.ADULT_NOT_US_CHECKBOX, "Not US checbox") @allure.step("Click Country Dropdown") def click_adult_country_field(self): self.click(SignUpDetailElements.ADULT_COUNTRY_FIELD, "Country Dropdown") @allure.step("Select country_name {1}") def select_adult_country(self, country_name): if country_name == "" or country_name == "Select": # print(country_name) self.click_adult_country_field() self.wait(5) self.click(SignUpDetailElements.ADULT_SUBMIT_BUTTON, "Adult Submit Button") self.wait(5) element = self.get_element_text(SignUpDetailElements.ADULT_COUNTRY_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") else: country_option = ( By.XPATH, "//select[@id='edit-field-user-location-und-0-country']//option[text()='" + str(country_name) + "']") self.click(country_option, "Country: " + str(country_name)) @allure.step("Click Email Updates option") def click_adult_no_email_updates(self): self.click(SignUpDetailElements.ADULT_NO_EMAIL_UPDATES, "Email Updates option") @allure.step("Click Agree Terms checkbox") def click_adult_agree_checkbox(self): self.click(SignUpDetailElements.ADULT_AGREE_CHECKBOX, "Agree Terms checkbox") @allure.step("Click Adult Submit Button") def click_adult_submit_button(self): self.click(SignUpDetailElements.ADULT_SUBMIT_BUTTON, "Adult Submit Button") @allure.step("Enter User Name {1}") # Kid Signup Page Actions def enter_kid_username(self, username): if (username != ""): self.enter_text(SignUpDetailElements.KID_USERNAME_FIELD, username, "Kid Username") elif (username == ""): self.enter_text(SignUpDetailElements.KID_USERNAME_FIELD, username) self.wait(5) element = self.get_element_text(SignUpDetailElements.KID_USERNAME_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") @allure.step("Enter Password {1}") def enter_kid_password(self, password): if (password != ""): self.enter_text(SignUpDetailElements.KID_PASSWORD_FIELD, password, "Kid Password") elif (password == ""): self.enter_text(SignUpDetailElements.KID_PASSWORD_FIELD, password) self.wait(5) element = self.get_element_text(SignUpDetailElements.KID_PASSWORD_FIELD_ERROR_MESSAGE, "") # print(element + "<br>") @allure.step("Click Age Month Dropdown") def click_kid_select_age_month_field(self): self.click(SignUpDetailElements.AGE_MONTH_FIELD, "Age Month Dropdown") @allure.step("Select month_number {1}") def select_kid_age_month(self, month_number): if str(month_number) == "": element = self.get_element_text(SignUpDetailElements.KID_AGE_MONTH_FIELD_ERROR_FIELD, "") # print(element + "<br>") else: month_option = (By.XPATH, "//select[@id='edit-field-birthday-und-0-value-month']//option[@value='" + str( month_number) + "']") self.click(month_option, "Month Number: " + str(month_number)) @allure.step("Click Age Year Dropdown") def click_kid_select_age_year_field(self): self.click(SignUpDetailElements.AGE_YEAR_FIELD, "Age Year Dropdown") @allure.step("Select year {1}") def select_kid_age_year(self, year): if str(year) == "": element = self.get_element_text(SignUpDetailElements.KID_AGE_MONTH_FIELD_ERROR_FIELD, "") # print(element + "<br>") else: year_option = ( By.XPATH, "//select[@id='edit-field-birthday-und-0-value-year']//option[@value='" + str(year) + "']") self.click(year_option, "Month Year: " + str(year)) @allure.step("Click Next Button") def click_kid_next_button(self): self.click(SignUpDetailElements.KID_NEXT_BUTTON, "Next Button") @allure.step("Enter Kid Parent Email {1}") def enter_kid_parent_email(self, parent_email): if re.search(regex, parent_email): self.enter_text(SignUpDetailElements.KID_PARENT_EMAIL_FIELD, parent_email, "Kid Parent Email") else: self.enter_text(SignUpDetailElements.KID_PARENT_EMAIL_FIELD, parent_email, "Kid Parent Invalid Email") self.click(SignUpDetailElements.KID_SUBMIT_BUTTON, "") element = self.get_element_text(SignUpDetailElements.KID_PARENT_EMAIL_FIELD_ERROR_FIELD, "") # print(element + "<br>") @allure.step("Click Agree Terms checkbox") def click_kid_agree_checkbox(self): self.click(SignUpDetailElements.KID_AGREE_CHECKBOX, "Agree Terms checkbox") @allure.step("Click Kid Submit Button") def click_kid_submit_button(self): self.click(SignUpDetailElements.KID_SUBMIT_BUTTON, "Kid Submit Button")
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines methods for CoFiXRouter interface ICoFiXRouter { /// @dev Register trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @param pool Pool for the trade pair function registerPair(address token0, address token1, address pool) external; /// @dev Get pool address for trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @return pool Pool for the trade pair function pairFor(address token0, address token1) external view returns (address pool); /// @dev Register routing path /// @param src Src token address /// @param dest Dest token address /// @param path Routing path function registerRouterPath(address src, address dest, address[] calldata path) external; /// @dev Get routing path from src token address to dest token address /// @param src Src token address /// @param dest Dest token address /// @return path If success, return the routing path, /// each address in the array represents the token address experienced during the trading function getRouterPath(address src, address dest) external view returns (address[] memory path); /// @dev Maker add liquidity to pool, get pool token (mint XToken to maker) /// (notice: msg.value = amountETH + oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The deadline of this request /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function addLiquidity( address pool, address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (address xtoken, uint liquidity); // /// @dev Maker add liquidity to pool, get pool token (mint XToken) and stake automatically // /// (notice: msg.value = amountETH + oracle fee) // /// @param pool The address of pool // /// @param token The address of ERC20 Token // /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) // /// @param amountToken The amount of Token added to pool // /// @param liquidityMin The minimum liquidity maker wanted // /// @param to The target address receiving the liquidity pool (XToken) // /// @param deadline The deadline of this request // /// @return xtoken The liquidity share token address obtained // /// @return liquidity The real liquidity or XToken minted from pool // function addLiquidityAndStake( // address pool, // address token, // uint amountETH, // uint amountToken, // uint liquidityMin, // address to, // uint deadline // ) external payable returns (address xtoken, uint liquidity); /// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) /// (notice: msg.value = oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param amountETHMin The minimum amount of ETH wanted to get from pool /// @param to The target address receiving the Token /// @param deadline The deadline of this request /// @return amountETH The real amount of ETH transferred from the pool /// @return amountToken The real amount of Token transferred from the pool function removeLiquidityGetTokenAndETH( address pool, address token, uint liquidity, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountETH, uint amountToken); /// @dev Swap exact tokens for tokens /// @param path Routing path. If you need to exchange through multi-level routes, you need to write down all /// token addresses (ETH address is represented by 0) of the exchange path /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param amountOutMin The minimum amount of ETH a trader want to swap out of pool /// @param to The target address receiving the ETH /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The deadline of this request /// @return amountOut The real amount of Token transferred out of pool function swapExactTokensForTokens( address[] calldata path, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint amountOut); // /// @dev Acquire the transaction mining share of the target XToken // /// @param xtoken The destination XToken address // /// @return Target XToken's transaction mining share // function getTradeReward(address xtoken) external view returns (uint); }
import { useEffect, useState } from 'react' import { IMAGE_CAT_URL } from '../constants' function useCatImage ({ fact, width = 320, height = 480, fontSize = 20, color = 'orange' }) { const [image, setImage] = useState() useEffect(() => { if (!fact) return const threeFirstWord = fact.split(' ', 3).join(' ') fetch(`${IMAGE_CAT_URL}/cat/says/${threeFirstWord}?fontColor=${color}&fontSize=${fontSize}&width=${width}&height=${height}`) .then(res => res.blob()) .then(data => { const url = URL.createObjectURL(data) setImage(url) }) }, [fact]) return { image } } export default useCatImage
import { NextRequest, NextResponse } from "next/server"; import clientPromise from "@/app/lib/mongodb"; import jwt, { JwtPayload } from "jsonwebtoken"; // delete page export async function DELETE( req: NextRequest, { params }: { params: { id: string; date: string; pageKey: string } } ) { try { const cookie = req.cookies.get("token"); if (!cookie) { return NextResponse.json({ success: false, message: "Token not found in cookies", }); } const token = cookie.value; const decodedToken = jwt.decode(token) as JwtPayload; const userId = params.id; if (userId !== decodedToken!.id) { return NextResponse.json({ success: false, message: "Unauthorized", }); } const { date, pageKey } = params; console.log(date, pageKey); const client = await clientPromise; const db = client.db("Deary"); const diariesCollection = db.collection("Diary"); const diary = await diariesCollection.findOne({ user_id: userId }); if (!diary) { return NextResponse.json({ success: false, message: "You have no diary", }); } const diaryEntry = diary.diary[date]; if (!diaryEntry) { return NextResponse.json({ success: false, message: "Diary not found", }); } const pages = diaryEntry.page; if (!pages || !pages[pageKey]) { return NextResponse.json({ success: false, message: "Page not found", }); } // Remove the specific page await diariesCollection.updateOne( { user_id: userId }, { $unset: { [`diary.${date}.page.${pageKey}`]: "" } } ); return NextResponse.json({ success: true, message: "Page deleted", }); } catch (error: any) { console.error("Error handling DELETE request:", error); return NextResponse.json({ error: error.message }); } }
import React, { useState } from 'react'; import { FaUserAlt } from 'react-icons/fa'; import { Stack, Flex, HStack, VStack, Text, Link, Box } from '@chakra-ui/react'; import { AnimatePresence, motion } from 'framer-motion'; const variants = { open: { opacity: 1, zIndex: 9999, y: 0 }, close: { opacity: 0, zIndex: -1, y: '-100%' }, }; export const UserProfile = () => { const MotionStack = motion(Flex); const [isActive, setIsActive] = useState(false); const changeOnMouseEnter = (event: React.MouseEvent) => { setIsActive(true); }; const changeOnMouseLeave = (event: React.MouseEvent) => { setIsActive(false); }; return ( <Flex pos="relative"> <HStack pl={2} pr={2} spacing={2} bg={isActive ? '#2c3338' : '#1d2327'} onMouseEnter={changeOnMouseEnter} onMouseLeave={changeOnMouseLeave} > <Text fontSize="xs" color={isActive ? '#63B3ED' : 'white'}> Привіт, user </Text> <FaUserAlt color={isActive ? '#63B3ED' : 'white'} /> </HStack> <AnimatePresence> {isActive && ( <MotionStack pos="absolute" top="35px" right="0" pl={2} pr={2} py={2} fontSize="xs" bg="#2c3338" onMouseEnter={changeOnMouseEnter} onMouseLeave={changeOnMouseLeave} variants={variants} initial="close" animate="open" exit="close" > <HStack spacing={2}> <Box w="100px" h="100px" display="flex" justifyContent="center" alignItems="center" > <FaUserAlt fontSize="50px" width="50px" height="50px" color="white" /> </Box> <VStack w="150px" justifyContent="flex-start" alignItems="flex-start" > <Link href="/" variant="header-menu"> user </Link> <Link href="/" variant="header-menu"> Редагувати профіль </Link> <Link href="/" variant="header-menu"> Вийти </Link> </VStack> </HStack> </MotionStack> )} </AnimatePresence> </Flex> ); };
@extends('admin.layouts.base') @section('title', 'Movies'); @section('content') <div class="row"> <div class="col-md-12"> {{-- Alert Here --}} <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Create Movie</h3> </div> <form enctype="multipart/form-data" method="POST" action="{{ route('admin.movies.store') }}"> @csrf <div class="card-body"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" name="title" value="{{ old('title') }}" placeholder="e.g Guardian of The Galaxy"> <p class="text-danger">{{ $errors->first('title') }}</p> <div class="form-group"> <label for="trailer">Trailer</label> <input type="text" class="form-control" id="trailer" name="trailer" value="{{ old('trailer') }}" placeholder="Video url"> <p class="text-danger">{{ $errors->first('trailer') }}</p> </div> <div class="form-group"> <label for="movie">Movie</label> <input type="text" class="form-control" id="movie" name="movie" value="{{ old('movie') }}" placeholder="Movie url"> <p class="text-danger">{{ $errors->first('movie') }}</p> </div> <div class="form-group"> <label for="duration">Duration</label> <input type="text" class="form-control" id="duration" name="duration" value="{{ old('duration') }}" placeholder="1h 39m"> <p class="text-danger">{{ $errors->first('duration') }}</p> </div> <div class="form-group"> <label>Date:</label> <div class="input-group date" id="release-date" data-target-input="nearest"> <input type="text" name="release_date" class="form-control datetimepicker-input" value="{{ old('release_date') }}" data-target="#release-date"/> <div class="input-group-append" data-target="#release-date" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <p class="text-danger">{{ $errors->first('release_date') }}</p> </div> <div class="form-group"> <label for="short-about">Casts</label> <input type="text" class="form-control" id="short-about" name="casts" value="{{ old('casts') }}" placeholder="Jackie Chan"> <p class="text-danger">{{ $errors->first('casts') }}</p> </div> <div class="form-group"> <label for="short-about">Categories</label> <input type="text" class="form-control" id="short-about" name="categories" value="{{ old('categories') }}" placeholder="Action, Fantasy"> <p class="text-danger">{{ $errors->first('categories') }}</p> </div> <div class="form-group"> <label for="small-thumbnail">Small Thumbnail</label> <input type="file" class="form-control" name="small_thumbnail"> <p class="text-danger">{{ $errors->first('small_thumbnail') }}</p> </div> <div class="form-group"> <label for="large-thumbnail">Large Thumbnail</label> <input type="file" class="form-control" name="large_thumbnail"> <p class="text-danger">{{ $errors->first('large_thumbnail') }}</p> </div> <div class="form-group"> <label for="short-about">Short About</label> <input type="text" class="form-control" id="short-about" name="short_about" value="{{ old('short_about') }}" placeholder="Awesome Movie"> <p class="text-danger">{{ $errors->first('short_about') }}</p> </div> <div class="form-group"> <label for="short-about">About</label> <input type="text" class="form-control" id="about" name="about" value="{{ old('about') }}" placeholder="Awesome Movie"> <p class="text-danger">{{ $errors->first('about') }}</p> </div> <div class="form-group"> <label>Featured</label> <select class="custom-select" name="featured"> <option value="0" {{ old('featured') == 0 ? 'selected' : '' }}>No</option> <option value="1" {{ old('featured') == 1 ? 'selected' : '' }}>Yes</option> </select> <p class="text-danger">{{ $errors->first('featured') }}</p> </div> </div> <div class="card-footer"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> </div> </div> @endsection @section('js') <script> $(function () { $('#release-date').datetimepicker({ format: 'YYYY-MM-DD' }); }); </script> @endsection
<script lang="ts"> import { SearchStr, schpanel } from "@/lib/stores"; import SearchChilds from "./search_childs.svelte"; import NavTaxonomyChilds from "./nav_taxonomy_childs.svelte"; export let indent = 0; interface ValueType { display?: string; } export let value: string | ValueType = ""; interface ObjType { concept?: any[]; // Adjust the type according to what `concept` actually contains [key: string]: any; // This allows other dynamic keys if necessary } export let obj: ObjType = {}; let json: ObjType = {}; let concept: any[] = []; let arrowDown = false; $: obj; function eventObject() { if (Object.keys(json).length == 0) { let Arg = $SearchStr.split(/[\s|,|、| ]/); try { const keys = Object.keys(obj); if (keys.includes("concept")) { const conceptAry = obj["concept"] as any[]; for (let i in conceptAry) { let tmp = conceptAry[i]; let schStr = JSON.stringify(conceptAry[i]); for (let n in Arg) { const regex = new RegExp(Arg[n], "gi"); const comparison = regex.test(schStr); if (comparison) { concept.push(tmp); break; //1つでも見つかったら登録して抜ける } } } } else { //conceptを含まない場合は、検索文字があるか比較 let schStr = JSON.stringify(obj); let comparison = false; for (let n in Arg) { const regex = new RegExp(Arg[n], "gi"); comparison = regex.test(schStr); if (comparison) { json = obj; break; //1つでも見つかったら登録して抜ける } } } } catch (e) { console.error(e); } json = obj; arrowDown = true; } else { json = {}; //「隠す」も考慮する concept = []; arrowDown = false; } //await tick(); //console.log(json, Object.keys(json).length); } eventObject(); function display(text: string) { if (text) { let Arg = $SearchStr.split(/[\s|,|、| ]/); for (let n in Arg) { const regex = new RegExp(Arg[n], "gi"); let result = text.match(regex); if (result) { text = text.replaceAll(regex, "<b>" + Arg[n] + "</b>"); //console.log("regex:", regex); } } return text; } else { return ""; } } function SelectObject() { $schpanel = "invisible"; OpenElement(obj.code); } let OpenElement = (code: any) => {}; let mvScroll = () => {}; </script> <div class="hidden"> <!--NavTaxonomyChilds#OpenElement呼出しの為表示しない--> {#if ($schpanel = "visible")} <NavTaxonomyChilds bind:OpenElement bind:mvScroll /> {/if} </div> <!--div>{!value ? ["選択してください"] : value}</div--> <button on:click={SelectObject} class="ml-{indent} text-left"> <div class="text-[1.1em] border-b"> <span class="arrow col-{indent}" class:arrowDown>&#x25b7</span> {obj["count"] ? `${obj["count"]}:` : ""} {#if typeof value === "object" && value.display} {@html display(value.display)} {:else} {@html display(JSON.stringify(value))} {/if} </div> </button> {#if json} <ul class="ml-4"> {#each Object.keys(json) as key} {#if typeof json[key] == "object"} {#if key !== "concept"} <ul class="ml-{indent + 1}"> <SearchChilds obj={json[key]} value={key} indent={indent + 1} /> </ul> {/if} {:else if key !== "count"} <li class="ml-{indent + 2}"> {@html display(key)}:{@html display(json[key])} </li> {/if} {/each} {#if concept} {#each concept as item} <SearchChilds obj={item} value={item} indent={indent + 1} /> {/each} {/if} </ul> {/if} <style> .arrow { cursor: pointer; display: inline-block; /* transition: transform 200ms; */ } .arrowDown { transform: rotate(90deg); } .col-1 { color: #2364aa; } .col-2 { color: #fec601; } .col-3 { color: #73bfb8; } .col-4 { color: #ea7317; } .col-5 { color: #3da5d9; } </style>
class Book attr_reader :author, :title def initialize(author, title) @author = author @title = title end def to_s %("#{title}", by #{author}) end end book = Book.new("Neil Stephenson", "Snow Crash") puts %(The author of "#{book.title}" is #{book.author}.) puts %(book = #{book}.) # The author of "Snow Crash" is Neil Stephenson. # book = "Snow Crash", by Neil Stephenson. # attr_reader is shorthand for getter methods. # attr_writer is shorthand for setter methods. # attr_accessor adds both getter and setter methods. # Therefore, attr_reader or attr_accessor would have worked.
import React, {useState, useEffect} from 'react'; import Avatar from '@mui/material/Avatar'; import Button from '@mui/material/Button'; import CssBaseline from '@mui/material/CssBaseline'; import TextField from '@mui/material/TextField'; import FormControlLabel from '@mui/material/FormControlLabel'; import Checkbox from '@mui/material/Checkbox'; import Paper from '@mui/material/Paper'; import Box from '@mui/material/Box'; import Grid from '@mui/material/Grid'; import AssignmentIcon from '@mui/icons-material/Assignment'; import Typography from '@mui/material/Typography'; import { createTheme, ThemeProvider } from '@mui/material/styles'; import axios from 'axios'; import { useNavigate, Link as RouterLink } from 'react-router-dom'; const theme = createTheme(); export default function SignInSide() { const history = useNavigate(); const [error, setError] = useState(false); const [errorMessage, setErrorMessage] = useState(""); useEffect(() => { if(window.localStorage.getItem('token')){ history('/me'); } }) const handleSubmit = async(event) => { event.preventDefault(); let data = new FormData(event.currentTarget); // eslint-disable-next-line no-console // console.log({ // email: data.get('email'), // password: data.get('password'), // }); let email = data.get('email'); let password = data.get('password'); const user = await axios.post("api/users/login", {email, password}) .then((user) => { window.localStorage.setItem('token', user.data.token); history('/me'); }).catch((e) => { console.log(e); setError(true) setErrorMessage("Invalid Credentials!") setTimeout(() => { setError(false) setErrorMessage("") }, 3000) }) }; return ( <ThemeProvider theme={theme}> <Grid container component="main" sx={{ height: '100vh' }}> <CssBaseline /> <Grid item xs={false} sm={4} md={7} sx={{ backgroundImage: 'url(https://source.unsplash.com/random)', backgroundRepeat: 'no-repeat', backgroundColor: (t) => t.palette.mode === 'light' ? t.palette.grey[50] : t.palette.grey[900], backgroundSize: 'cover', backgroundPosition: 'center', }} /> <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square> <Box sx={{ my: 8, mx: 4, display: 'flex', flexDirection: 'column', alignItems: 'center', }} > <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}> <AssignmentIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign in </Typography> <Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 1 }}> <TextField error={error} margin="normal" required fullWidth id="email" label="Email Address" name="email" autoComplete="email" autoFocus /> <TextField error={error} helperText={errorMessage} margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" /> <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> <Button type="submit" fullWidth variant="contained" sx={{ mt: 3, mb: 2 }} > Sign In </Button> <Grid container> <Grid item xs> </Grid> <Grid item> <RouterLink to="/signup" > {"Don't have an account? Sign Up"} </RouterLink> </Grid> </Grid> </Box> </Box> </Grid> </Grid> </ThemeProvider> ); }
package day_18_recap; public class EmailTask2 { public static void main(String[] args) { String email = "craig_federighi@apple.com"; int indexOf_ = email.indexOf("_"); int indexOfAt = email.indexOf("@"); String firstName = email.substring(0, indexOf_); //craig firstName = ("" +firstName.charAt(0) ).toUpperCase() + firstName.substring(1).toLowerCase(); // first character is in uppercase and remaining is in lower System.out.println("firstName = " + firstName); String lastName = email.substring(indexOf_ +1, indexOfAt); lastName = lastName.substring(0,1).toUpperCase() + lastName.substring(1).toLowerCase() ; System.out.println("lastName = " + lastName); String domain = email.substring(indexOfAt+1, email.indexOf(".")); System.out.println("domain = " + domain); /* EmailTask2: Assume that email address is constructed by person's first name and followed by an underscore and last name. Write a program that will print out information about user based on email. Print first name, last name, and domain. First and Last name should be printed with proper format - uppercase first letter and remaining lowercase. Ex: input: craig_federighi@apple.com Output: First name: Craig Last name: Federighi Domain: apple */ } }
@charset "UTF-8"; /* Con este reset vamos a resolver: 👉 Unificar el uso de Custom Properties 👉 Problemas de box-model más generales 👉 Problemas con imagenes, vídeos e iconos svg 👉 Problemas con tipografías y etiquetas input en formularios 👉 Unificar la tipografía de todas las etiquetas de una web */ /* Aquí definimos las Custom properties */ :root { --colorsecundario: #000000; --colorprincipal: #ffc300; --blanco: #fffafa; /* Tipografía */ --tipo-titular: 'Dosis', sans-serif; --tipo-principal: 'Montserrat', sans-serif; } /* Opcional */ /* Configuramos si un usuario ha activado el modo alto contraste. (WD) */ /* Opcional */ /* Desactivamos los animations en el caso de que el usuario haya configurado el modo sin animation */ @media (prefers-reduced-motion: reduce) { * { -webkit-animation: none !important; animation: none !important; -webkit-transition: none !important; transition: none !important; } } /* Reseteamos los margin y paddings de todas las etiquetas */ * { margin: 0; padding: 0; border: 0; -webkit-box-sizing: border-box; box-sizing: border-box; vertical-align: baseline; } /* Evitamos problemas con las imagenes */ img, picture, video, iframe, figure { max-width: 100%; width: 100%; display: block; /* opcional */ -o-object-fit: cover; object-fit: cover; /* opcional */ -o-object-position: center center; object-position: center center; } /* Reseteamos los enlaces para funcionar como cajas... */ a { display: block; text-decoration: none; color: inherit; font-size: inherit; cursor: none; } /* ... excepto los que se encuentran en párrafos */ p a { display: inline; } /* Quitamos los puntos de los <li> */ li { list-style-type: none; } /* Configuramos anclas suaves */ html { scroll-behavior: smooth; } /* Desactivamos estilos por defecto de las principales etiquetas de texto */ h1, h2, h3, h4, h5, h6, p, span, a, strong, blockquote, i, b, u, em { font-size: 1em; font-weight: inherit; font-style: inherit; text-decoration: none; color: inherit; } /* Evitamos problemas con los pseudoelementos de quotes */ blockquote:before, blockquote:after, q:before, q:after { content: ""; content: none; } /* Configuramos el texto que seleccionamos */ ::-moz-selection { background-color: var(--negro); color: var(--blanco); } ::selection { background-color: var(--negro); color: var(--blanco); } /* Nivelamos problemas de tipografías y colocación de formularios */ form, input, textarea, select, button, label { font-family: inherit; font-size: inherit; -webkit-hyphens: auto; -ms-hyphens: auto; hyphens: auto; background-color: transparent; color: inherit; display: block; /* opcional */ -webkit-appearance: none; -moz-appearance: none; appearance: none; } /* Reseteamos las tablas */ table, tr, td { border-collapse: collapse; border-spacing: 0; } /* Evitamos problemas con los SVG */ svg { width: 100%; display: block; fill: currentColor; } /* (Probándolo, no usar en producción) En el caso de añadir una */ /* p svg{ display: inline; width: initial; } */ /* Configuramos la tipografía para toda la web */ body { min-height: 100vh; font-size: 100%; font-family: var(--tipo-principal); color: var(--colorsecundario); background: var(--colorprincipal); /* opcional */ line-height: 1.4em; /* opcional */ -webkit-hyphens: auto; -ms-hyphens: auto; hyphens: auto; /* opcional */ font-smooth: always; /* opcional */ -webkit-font-smoothing: antialiased; /* opcional */ -moz-osx-font-smoothing: grayscale; cursor: none; max-width: 100%; } .header{ width: 100%; min-width: 5em; padding: 1em 2em; display: flex; flex-flow: row nowrap; justify-content: space-between; align-items: center; } .header__logotipo { display: flex; flex-flow: row nowrap; justify-content: space-between; align-items: center; gap: 1em; } .header__logo{ width: 3em; height: 3em; fill: var(--colorsecundario); } .header__h1{ font-size: 1.3em; font-family: var(--tipo-titular); font-weight: 600; text-transform: uppercase; } .nav__ul{ display: flex; flex-flow: row nowrap; justify-content: space-between; align-items: center; } .nav__li{ margin: 0 1em; font-weight: 500; } .logomenu{ display: none; } .main{ margin: 1em 0; text-align: center; } .seccion{ width: 100%; min-height: 90vh; margin: 1em 0; padding: 2em; display: flex; flex-flow: column wrap; justify-content: center; align-items: center; } .header__logo, .seccion--intro p:first-of-type, .seccion__h2{ animation: aparecer 2s ease 1 both; } .seccion__p--intro, .seccion__h3, .seccion__ul{ animation: aparecer 2s ease 1 both; animation-delay: 1s; } .seccion__logo{ width: 15em; animation-name: efecto3d; animation-duration: 15.5s; animation-iteration-count: infinite; transform-origin: 50% 50%; display: inline-block; } @keyframes efecto3d { 0% { transform: perspective(400px) rotateY(0deg); } 100% { transform: perspective(400px) rotateY(360deg); } } .seccion__p{ width: 90%; font-size: 2em; line-height: 1.3em; } .seccion__ul{ display: flex; flex-flow: row wrap; justify-content: center; align-items: center; } .seccion__li{ margin: 1.5em 1em; } .seccion__a--intro{ border-top: 1px dotted rgba(0, 0, 0, 0); padding: .5em 0; font-weight: 600; transition: all .9s ease; } .seccion__a--intro:hover{ border-top: 1px dotted rgba(0, 0, 0, 1); } .seccion__h2{ font-family: var(--tipo-titular); font-size: 6em; line-height: 1em; text-transform: uppercase; font-weight: 600; } .seccion__h3{ margin: 0 0 .2em 0; font-family: var(--tipo-titular); font-size: 4em; line-height: 1em; } .cita { width: 90%; margin: 4em 0 15em; } .cita__frase{ font-size: 1.4em; font-style: italic; } .cita__quote { width: 9em; height: 9em; display: inline; margin: 0 -5em 0 0; opacity: .3; } .seccion--proyectos{ color: var(--colorprincipal); background-color: var(--colorsecundario); box-shadow: 0 0 3em 3em var(--colorsecundario); } .seccion__h2--proyectos { font-size: 4em; margin: 0 0 .5em; } .seccion__grid{ width: 100%; margin: 1em 0; display: flex; flex-flow: row wrap; justify-content: center; align-content: center; } .seccion__article{ width: 50%; padding: 3em 0 6em 0; margin: 0 ; border: solid 3px var(--colorprincipal); overflow: hidden; position: relative; } .seccion__a--proyectos{ width: 100%; min-height: inherit; display: flex; flex-flow: column nowrap; justify-content: center; align-items: center; } .seccion__picture{ width: 90%; transition: transform 0.8s; } .seccion__picture:hover{ transform: scale(1.3) rotate(0.01deg); } .seccion__h4{ font-family:var(--tipo-titular); padding: .5em .5em .2em 0; font-size: 2rem; font-weight: 600; text-transform: uppercase; position: absolute; bottom: .8em; right: 0; } .seccion__a--proyectos:hover .seccion__h4{ opacity: .5; color: transparent; -webkit-text-stroke: 1px var(--colorprincipal); transition: transform 1s cubic-bezier(.19,1,.22,1); transform: scale(1.1); } .seccion__h2--about{ font-size: 4em; margin: 1em 0 .9em; } .seccion__p--about{ max-width: 70%; margin: 0 0 1em; font-size: 1.2rem; text-align: left; line-height: 1.5em; text-align: justify; } .seccion__a--tum{ display: inline; text-decoration: underline dotted ; } .seccion__redes{ width: 90%; margin: 4em 0 0; display: flex; flex-flow: row wrap; justify-content: space-between; align-items: center; } .seccion__redes__li{ width: 28%; transform: translate(0); } .seccion__redes__a{ padding: .8em 0; display: flex; flex-flow: row nowrap; justify-content: space-between; align-items: center; border-top: 1px solid var(--colorsecundario); transition: .6s cubic-bezier(0,.89,.41,1); position: relative; overflow: hidden; } .seccion__redes__a:hover{ padding: .8em 1em; border-top: 1px solid transparent; } .seccion__redes__a:hover:after{ transform: translate(0); } .seccion__redes__a::after{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; transform: translateY(-101%); content: ""; background-color: #19FFD1; transition: .2s; z-index: -1; } .seccion__redes__a p:first-child{ font-size: 1.2em; text-align: left; } .seccion__redes__a p:last-child{ font-size: .8em; text-align: left; opacity: .8; } .seccion__svg{ width: 2em; height: 2em; margin-bottom: 1.2em; } .seccion__svg--last{ margin-top: -.5em; } .footer{ padding: 2em 0; text-align: center; } .footer__dixit{ width: 10%; margin: auto; } @keyframes aparecer{ from{ opacity: 0; transform: translateY(50%); } to{ opacity: 1; transform: translateY(0%); } } #cursor{ width: 3em; height: 3em; background-color: var(--blanco); position: fixed; top: 0; left: 0; z-index: 30; pointer-events: none; border-radius: 50%; mix-blend-mode: difference; } #foto{ width: 20em; position: fixed; right: 0; top: 0; opacity: 0; z-index: -2; transform: rotate(-8deg); } #foto.mostrar{ opacity: 1; z-index: 2 } @media (pointer:coarse) { #cursor{ display: none; } #foto.mostrar{ opacity: 0; } } #cursor.mini{ mix-blend-mode: overlay; } @media screen and (max-width: 840px){ .seccion__redes{ width: 90%; margin: 4em 0 0; padding: 0; display: flex; flex-flow: column wrap; justify-content: space-between; align-items: center; } .seccion__redes__li{ width: 90%; transform: translate(0); } } @media screen and (max-width: 560px) { .seccion__grid{ width: 100%; margin: 1em 0; display: flex; flex-flow: column wrap; justify-content: center; align-content: center; } .seccion__article{ width: 100%; } .seccion__h4{ padding: .5em .5em .2em 0; font-size: 2rem; font-weight: 600; text-transform: uppercase; position: absolute; bottom: .8em; right: 0; } .logomenu{ width: 3em; height: 3em; display: inline-block; } .logomenu__icon{ width: 3em; height: 3em; position: relative; } .logomenu__first-bar, .logomenu__second-bar, .logomenu__third-bar{ position: absolute; width: 30px; height: 3px; background-color: var(--colorsecundario); border-radius: 5px; transition: transform .2s; } .logomenu__first-bar{ top: 10px; } .logomenu__second-bar{ top: 20px; } .logomenu__third-bar{ top: 30px; } .logomenu__icon.show .logomenu__first-bar{ transform: rotate(-45deg); top: 1.5rem; } .logomenu__icon.show .logomenu__second-bar{ width: 0; } .logomenu__icon.show .logomenu__third-bar{ transform: rotate(45deg); top: 1.5rem; } .header { width: 100vw; position: fixed; padding: 0 0; top: 0; left: 0; height: 10%; display: flex; flex-flow: column nowrap; justify-content: space-between; align-items: center; z-index: 5; } .header__logotipomenu { width: 100%; padding: .5em 0 0; background-color: var(--colorprincipal); display: flex; flex-flow: row nowrap; justify-content: space-between; align-items: center; z-index: 10; border-bottom: 1px solid var(--colorsecundario); } .nav{ width: 100vh; height: 100vh; transform: translateY(-100%); z-index: 1; transition: transform .3s; } .nav.show{ transform: translateY(0); } .nav__ul{ border-top: 1px solid gray; background-color: var(--colorsecundario); color: var(--colorprincipal); display: flex; flex-flow: column nowrap; justify-content: center; align-items: center; } .nav__li{ width: 100%; text-align: center; font-size: 2em; font-weight: 500; text-transform: uppercase; line-height: 2.5; border-bottom: 1px solid var(--colorprincipal); } .main{ margin: 4em 0 0; } } @media screen and (max-width: 410px) { .seccion__h2{ font-size: 5em; } } /* PROYECTOS */ .section-info{ padding: 5%; display: flex; flex-flow: row wrap; justify-content: space-between; align-content: center; } .section-info__principal{ width: 48%; height: 100%; margin: 0 0 12em; position: sticky; top: 5em; } .section__h1{ transition: none; font-family: var(--tipo-titular); font-size: 4em; font-weight: 800; text-transform: uppercase; margin: 0 0 1em; } .section__p{ text-align: justify; } .section__bloque{ display: flex; flex-flow: row nowrap; justify-content: space-between; align-items: flex-end; margin: 2em 0 0; } .section__wrap{ display: flex; flex-flow: row nowrap; justify-content: space-between; align-items: center; gap: 3em; } .section__item{ display: flex; flex-flow: column nowrap; justify-content: center; align-items: start; } .section__item--title{ font-style: italic; } .section__link--a{ text-decoration: underline dotted; } .section__images{ width: 48%; } .section__imageArea{ display: flex; flex-flow: column nowrap; justify-content: center; align-items: center; gap: 5em; } /* .section__imageArea .img{ width: 100%; } */ .section-galeria{ padding: 5%; } .section__atribucion{ text-align: right; font-size: .9em; } .footer-flecha{ padding: 0 5%; margin: 0 0 6em; display: flex; flex-flow: row nowrap; justify-content: space-around; align-items: center; } .footer__ico{ width: 12em; height: 12em; opacity: .7; } .footer__ico:hover{ opacity: 1; } @media screen and (max-width: 960px) { .section-info{ display: flex; flex-flow: column wrap; justify-content: center; align-items: center; } .section-info__principal{ width: 95%; margin: 4em 0; position: static; } .section__images{ width: 100%; } .section__imageArea{ display: flex; flex-flow: column nowrap; justify-content: center; align-items: center; gap: 4em; } .section-galeria{ padding: 5%; } .section__video:first-child{ margin: 0 0 4em; } .footer__ico{ width: 6em; height: 6em; opacity: .7; } } @media screen and (max-width: 490px) { .section__h1{ font-size: 4em; line-height: 1em; } } /*ESTILOS LIGHTBOX*/ .section-galerialightbox { margin: 0 8% 4%; padding: 3% 0; border-radius: 3em; background-color: var(--colorsecundario); min-width: 20em; } .section-galerialightbox__h2{ color: var(--colorprincipal); font-size: 2em; padding: 0 0 2% 6%; } .section-galerialightbox__ul-li{ width: 80%; padding: 1em; margin: auto; display: grid; grid-template-columns: repeat(auto-fit, minmax(15em, 1fr)); gap: 2em; } .section-galerialightbox__img{ transition: all .5s ease; transform: scale(1); } .section-galerialightbox__li:hover .galerialigthbox__img{ transform: scale(1.1); } .section-galerialightbox__lightbox{ position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, .8); z-index:2; display: flex; flex-flow: column nowrap; justify-content: center; align-items: center; opacity: 0; transform: scale(1.1); transition: all .5s ease; pointer-events: none; } .section-galerialightbox__lightbox.activo{ opacity: 1; transform: scale(1); pointer-events: auto; cursor: none; } .section-galerialightbox__iconocerrar, .section-galerialightbox__cerrar{ width: 2em; height: 2em; margin: 0 0 1em; cursor: none; } .section-galerialightbox__grande{ width: auto; max-height: 90vh; } /* CARRUSEL */ .section-carrousel { width: 90%; max-width: 120em; padding: 0 5%; margin: 0 auto 4em; overflow-x: hidden; } .section-carrousel__h2{ color: var(--colorsecundario); font-size: 2em; padding: 2% 0 2% 6%; } .section-carrousel__big{ width: 1000%; display: flex; flex-flow: row nowrap; justify-content: space-around; align-items: center; transition: all .5s ease; transform: translateX(0%); } .section-carrousel__img{ width: calc( 100% / 10 - 3% ); } .section-carrousel__puntos{ width: 100%; margin: 1em 0 0; padding: .4em; display: flex; flex-flow: row wrap; justify-content: center; align-items: center; } .section-carrousel__punto{ width: 2em; height: 2em; margin: 1em 1em 0; border: 1px solid var(--colorsecundario); border-radius: 1em; } .section-carrousel__punto.activo{ background-color: var(--colorsecundario); } /* Las adaptamos al modo oscuro */ @media (prefers-color-scheme: dark) { :root { --colorsecundario: #ffc300; --colorprincipal: #000000; --blanco: #000000; } #cursor{ background-color: snow; mix-blend-mode: difference; } #cursor.mini{ background-color: var(--colorsecundario); mix-blend-mode: exclusion; } .header__logo{ fill: var(--colorsecundario); } .seccion__redes__a::after{ background-color: #454e4c; } }
from django.shortcuts import render,redirect from online_course.forms import UserForm from django.contrib.auth import authenticate,login,logout from django.http import Http404 from django.shortcuts import get_object_or_404 from django.core.mail import send_mail from online_course.settings import EMAIL_HOST_USER from accounts.models import Account , Profile import random from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from base.models import Student,Teacher from django.contrib.auth.views import PasswordResetView , PasswordResetConfirmView # from .forms import CustomPasswordResetForm from django.urls import reverse_lazy from django.contrib import messages import uuid from django.contrib.auth import get_user_model from online_course.tasks import send_mail_celery # user registration --> @csrf_exempt def Otpverify(request): if request.method == 'POST': userotp = request.POST.get('otp') name = request.POST.get('name') email = request.POST.get('email') username = request.POST.get('username') role = request.POST.get('role') password1 = request.POST.get('password1') password2 = request.POST.get('password2') print("OTP:",userotp) if password1 == password2: form = Account.objects.create_user( name = name, email = email, username = username, role = role, password = password1 ) if role == 'teacher': teacher = Teacher.objects.create( teacher_id=form, name = name ) teacher.save() elif role == 'student': student = Student.objects.create( student_id=form, name = name ) student.save() form.save() return JsonResponse({'otp' : 'otp'}, status=200 ) def Signup(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST) name = request.POST.get('name') email = request.POST.get('email') username = request.POST.get('username') role = request.POST.get('role') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if form.is_valid(): otp = random.randint(1000,9999) print("form is saved successfully") # send_mail("TWO FACTOR AUTHENTICATION: ",f"VERIFY YOUR MAIL USING THIS OTP: {otp}",EMAIL_HOST_USER,[email],fail_silently=True) send_mail_celery.delay("TWO FACTOR AUTHENTICATION: ",f"VERIFY YOUR MAIL USING THIS OTP: {otp}",EMAIL_HOST_USER,[email],fail_silently=True) print("email sended successfully") context = { 'name' : name, 'email' : email, 'username' : username, 'role': role, 'password1' : password1, 'password2' : password2, 'otp' : otp } return render(request, 'template/OTPverify.html' ,context) else: print("some error has occured") context= { 'form': form } return render(request, 'signup.html', context) # user login --> @csrf_exempt def LoginOtpVerify(request): if request.method == 'POST': userotp = request.POST.get('otp') email = request.POST.get('email') password = request.POST.get('password') role = request.POST.get('role') user = authenticate(request,email=email, password=password) print("OTP:",userotp) print(user) if user is not None: login(request,user) print("login done") return redirect("base:welcome") else: print("login failed") return JsonResponse({'otp' : 'otp'}, status=200 ) def Login(request): if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') try: user = Account.objects.get(email=email) email = user.email role = user.role print(f'{password} {email} {role}') except Account.DoesNotExist: print("user does not exist") user = authenticate(request,email=email, password=password) print(user) if user is not None: otp = random.randint(1000,9999) print("form is saved successfully") # send_mail("TWO FACTOR AUTHENTICATION: ",f"LOGIN USING THIS OTP: {otp}",EMAIL_HOST_USER,[email],fail_silently=True) send_mail_celery.delay("TWO FACTOR AUTHENTICATION: ",f"LOGIN USING THIS OTP: {otp}",EMAIL_HOST_USER,[email]) print("email sended successfully") context = { 'otp' : otp, 'email' : email, 'password' : password, 'role': role } return render(request,'template/LoginOtpVerify.html' ,context) else: print("Invalid Entry") return render(request, 'login.html') def Logout(request): logout(request) print("logout done") return redirect('/login') def ChangePassword(request, token): context = {} try: # Attempt to retrieve the profile associated with the token profile_obj = get_object_or_404(Profile, forget_password_token=token) if request.method == "POST": new_password = request.POST.get("new_password") confirm_password = request.POST.get("confirm_password") user_id = request.POST.get("user_id") if user_id is None: messages.error(request, "No user id found") return redirect(f'/change-password/{token}/') if new_password != confirm_password: messages.error(request, "Both passwords do not match") return redirect(f'/change-password/{token}/') user_obj = profile_obj.user user_obj.set_password(new_password) user_obj.save() return redirect('/login/') context = { 'user_id': profile_obj.user.id } except Http404: messages.error(request, "Profile not found. Please request a new password reset.") return redirect('/forget-password/') # Redirect to the password reset page except Exception as e: print(e) messages.error(request, "An error occurred while processing your request. Please try again.") return render(request, 'change-password.html', context) def send_forget_password_mail(email, token): subject = 'Your forget password link' message = f'Click on the link to reset your password: http://127.0.0.1:8000/change-password/{token}/' email_from = EMAIL_HOST_USER recipient_list = [email] try: send_mail_celery.delay(subject, message, email_from, recipient_list) return True except Exception as e: print(e) return False def ForgetPassword(request): if request.method == "POST": try: email = request.POST.get('email') print(email) user_obj = Account.objects.filter(email=email).first() if not user_obj: messages.error(request, 'No user found with this email address') return redirect('/forget-password/') # Generate a new token for each password reset request token = str(uuid.uuid4()) try: # Check if the user already has a profile profile_obj = user_obj.profile profile_obj.forget_password_token = token # Update the existing profile with the new token except Profile.DoesNotExist: # If the user doesn't have a profile, create a new one profile_obj = Profile(user=user_obj, forget_password_token=token) profile_obj.save() # Print the token for debugging purposes print(f"Token generated for {user_obj.username}: {token}") if send_forget_password_mail(email, token): messages.success(request, 'An email has been sent with a link to reset your password') print('Email has been sent') else: messages.error(request, 'Failed to send the email. Please try again later.') print('Failed to send the email') return redirect('/forget-password/') except Exception as e: print(e) return render(request, 'forget-password.html')
import { Edit, SimpleForm, TextInput, required, useGetList, SelectArrayInputProps, Labeled, ReferenceManyField, Datagrid, TextField, NumberField, EditButton, BooleanInput, useRecordContext } from 'react-admin'; import React, {useEffect, useState} from "react"; import {Category, Promotion} from "../../types"; import ThumbnailField from "../product/ThumbnailField"; const CategoryTitle = () => { const record = useRecordContext<Category>(); return record ? <span>{record.name}</span> : null; }; export const CategoryEdit = (props: SelectArrayInputProps) => { const [categories, setCategories] = useState<Category[]>([]); const {data}: any = useGetList<Category>('category', { pagination: {page: 1, perPage: 100}, sort: {field: 'name', order: 'ASC'}, }); useEffect(() => { if (data) { setCategories(data); } }, [data]); return ( <Edit title={<CategoryTitle/>}> <SimpleForm> <TextInput source="name" validate={required()}/> <BooleanInput source="status" label="Trạng thái" defaultValue={false}/> <Labeled label="Sản phẩm thuộc danh mục" fullWidth> <ReferenceManyField reference="product" target="category" perPage={20} > <Datagrid sx={{ '& .column-thumbnail': { width: 25, padding: 0, }, }} > <ThumbnailField source="thumbnail" label="" /> <TextField source="name" /> <NumberField source="price" options={{ style: "currency", currency: "VND", }} label="Giá" /> <NumberField source="quantity" /> <NumberField source="sold" /> <EditButton /> </Datagrid> </ReferenceManyField> </Labeled> </SimpleForm> </Edit> ) };
import React from 'react'; import { Label, Wrapper, TextInput } from './styles'; export interface FilterCharacter { name: string; } export interface FilterEpisode { name: string; } type filterDataKeys = keyof FilterCharacter | keyof FilterEpisode; interface FilterProps { label: string; dataToChange: filterDataKeys; filterData: FilterCharacter | FilterEpisode; setData: React.Dispatch< React.SetStateAction<FilterCharacter | FilterEpisode> >; } const Filter: React.FC<FilterProps> = ({ label, dataToChange, filterData, setData, }: FilterProps) => { function handleTextInputOnChange(event: React.ChangeEvent<HTMLInputElement>) { const { value } = event.target; setData({ ...filterData, [dataToChange]: value }); } return ( <Wrapper> <Label htmlFor={dataToChange}>{label}</Label> <TextInput id={dataToChange} type="text" onChange={handleTextInputOnChange} value={filterData[dataToChange]} /> </Wrapper> ); }; export default Filter;
import React, { useEffect } from 'react'; // @ts-ignore import { Document, Page } from 'react-pdf'; import styled from 'styled-components'; import { Icon } from 'components/Icon/Icon'; import DownloadSvg from './download.svg'; import { media } from 'global/RWD'; import { useParams } from 'react-router-dom'; import { FirebaseProvider } from 'global/Firebase/Firebase'; import { useFirebase } from 'global/Firebase/FirebaseContext'; const OfferWrapper = styled.div` display: flex; justify-content: center; align-items: center; flex-direction: column; `; const DownloadWrapper = styled.div` width: 100%; background-color: #bdbdbd; display: flex; justify-content: center; align-items: center; border-bottom: 1px solid grey; ${media.xs` position: fixed; bottom: 0; left: 0; z-index: 2; margin-bottom: 0; `} ${media.lg` position: static; margin-bottom: 24px; `} `; const StyledLink = styled.a` display: flex; justify-content: center; align-items: center; cursor: pointer; p { font-weight: 600; color: #361d32; margin: 0; } `; const removeWhenVisible = (selector: string) => { const checkExist = setInterval(function() { if (document.querySelector(selector)) { // @ts-ignore document.querySelector(selector).setAttribute('style', 'display: none!important'); clearInterval(checkExist); } }, 100); }; const StyledDocument = styled(Document)` ${media.xs` max-height: calc(100vh - 57px); max-width: 100vw; overflow: scroll; margin-bottom: 57px; `} ${media.lg` overflow: auto; max-height: unset; max-width: unset; `} `; const DOCUMENT_WIDTH = 1366; const withFirebaseProvider = (Component: React.ElementType) => () => ( <FirebaseProvider> <Component /> </FirebaseProvider> ); export const Offer = withFirebaseProvider(() => { const { offerId } = useParams(); const { db } = useFirebase(); useEffect(() => { removeWhenVisible('#hubspot-messages-iframe-container'); removeWhenVisible('#footer-shape'); removeWhenVisible('.Footer'); removeWhenVisible('.Header'); db.collection('offer-visits').add({ offerId: offerId, }); }); const SCALE = DOCUMENT_WIDTH > window.innerWidth ? window.innerWidth / DOCUMENT_WIDTH : 1; return ( <OfferWrapper> <DownloadWrapper> <StyledLink href="/offer.pdf" download> <Icon alt="Download Icon" svgLink={DownloadSvg} /> <p>Download pdf</p> </StyledLink> </DownloadWrapper> <div> <StyledDocument file="/offer.pdf" loading="Please wait, rendering pdf..." renderMode="svg"> <Page pageNumber={1} scale={SCALE} /> </StyledDocument> </div> </OfferWrapper> ); });
<template> <q-select :class="classes" outlined dense :disable="disable" :hide-bottom-space="hideBottomSpace" :options-dense="optionsDense" popup-content-class="s-select--item" v-model="selectedValue" :options="options" > <template #default> <slot></slot> </template> <template v-for="(_, name) in $slots" #[name]="slotData"> <slot :name="name" v-bind="slotData" /> </template> </q-select> </template> <script lang="ts"> import { defineComponent, ref } from 'vue'; export default defineComponent({ name: 'SSelect', props: { disable: { type: Boolean, default: false, required: false, }, required: { type: Boolean, default: false, required: false, }, hideBottomSpace: { type: Boolean, default: true, }, optionsDense: { type: Boolean, default: true, }, options: { type: Array, // Передаем массив опций default: () => [], required: false, }, value: [String, Number] // Добавляем привязку значения через v-model }, setup(props, { slots, emit }) { const classesArray = ref([ 's-select', props.disable ? 's-select--disable' : '', props.required ? 'required' : '', ] as Array<string>); const classes = ref(classesArray.value.join(' ') as string); return { classes, slots, selectedValue: props.value, emit, } }, }) </script>
import 'package:flutter/material.dart'; import '../../../constant/konstant.dart'; class DynamicInputWidget extends StatelessWidget { const DynamicInputWidget({ super.key, required this.isNonPasswordField, required this.controller, this.toggleObscureText, required this.obscureText, required this.focusNode, this.validator, this.prefIcon, required this.labelText, required this.textInputAction, this.onChanged, this.onEditingComplete, this.onFieldSubmitted, }); // bool to check if the text field is for password or not final bool isNonPasswordField; // Controller for the text field final TextEditingController controller; // Function to toggle Text obscuration on the password text field final VoidCallback? toggleObscureText; // to obscure text or not bool final bool obscureText; // FocusNode for input final FocusNode focusNode; // Validator function final String? Function(String?)? validator; // Prefix icon for input form final Icon? prefIcon; // label for input form final String labelText; // The keyword action to display final TextInputAction textInputAction; final void Function(String)? onChanged; final void Function()? onEditingComplete; final void Function(String)? onFieldSubmitted; @override Widget build(BuildContext context) { return TextFormField( style: const TextStyle(color: Konstant.white), onEditingComplete: onEditingComplete, onFieldSubmitted: onFieldSubmitted, onChanged: onChanged, controller: controller, decoration: InputDecoration( enabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: Konstant.formColor), ), focusedBorder: const OutlineInputBorder( borderSide: BorderSide(color: Color(0xff4964AC))), border: const OutlineInputBorder( // Make border edge circular borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(color: Color(0xff4964AC))), fillColor: const Color(0xff050A31), filled: true, label: Text(labelText), labelStyle: const TextStyle(color: Konstant.formColor), prefixIcon: prefIcon, suffixIcon: IconButton( onPressed: toggleObscureText, icon: isNonPasswordField ? const Icon(null) : obscureText ? const Icon( Icons.visibility, color: Colors.white, ) : const Icon( Icons.visibility_off, color: Colors.white, ), ), ), focusNode: focusNode, textInputAction: textInputAction, obscureText: obscureText, validator: validator, // onSaved: passwordValidator, ); } } class AuthValidators { static const String emailErrMsg = "Invalid Email Address, Please provide a valid email."; static const String passwordErrMsg = "Password must have at least 6 characters."; static const String confirmPasswordErrMsg = "Two passwords don't match."; static const usernameErrMsg = "Username cannot character used"; static const String defaultMsg = "Field cannot be empty"; String? defaultValidator(String? val) { String value = val as String; if (value.isEmpty) return defaultMsg; return null; } String? emailValidator(String? val) { final String email = val as String; // RegExp emailReg = RegExp(email); bool containsSpecialCharacters(String str) { final pattern = RegExp(r'[!^&%#()$*]'); return pattern.hasMatch(str); } //Check if the length of the email is less than or equal to 3 if (email.length <= 3) return emailErrMsg; if (containsSpecialCharacters(email)) return emailErrMsg; // Check if it has @ // # 4 final hasAtSymbol = email.contains('@'); // find the position of @ // # 5 final indexOfAt = email.indexOf('@'); // Check numbers of @ // # 6 final numbersOfAt = "@".allMatches(email).length; // Valid if has @ if (!hasAtSymbol) return emailErrMsg; // and if the number of @ is only 1 if (numbersOfAt != 1) return emailErrMsg; //and if '@' is not the first or last character if (indexOfAt == 0 || indexOfAt == email.length - 1) return emailErrMsg; //if it contains value such as #$%!^@&_- // Else its valid return null; } // Password validator String? passwordWordValidator(String? val) { final String password = val as String; if (password.isEmpty || password.length <= 5) return passwordErrMsg; // else return null; } // confirm password String? confirmPasswordValidator(String? val1, String? val2) { final String password1 = val1 as String; final String password2 = val2 as String; if (password1.isEmpty || password2.isEmpty || password1.length != password2.length) return confirmPasswordErrMsg; // If two passwords do not match then send an error message if (password1 != password2) return confirmPasswordErrMsg; return null; } String? usernameValidator(String? val) { final String username = val as String; bool containsSpecialCharacters(String str) { final pattern = RegExp(r'[!^&%#()$*]'); return pattern.hasMatch(str); } if (containsSpecialCharacters(username)) return usernameErrMsg; // else return null; } }
package com.oscarhanke.recipeapp.bootstrap; import com.oscarhanke.recipeapp.domain.Category; import com.oscarhanke.recipeapp.domain.Difficulty; import com.oscarhanke.recipeapp.domain.Ingredient; import com.oscarhanke.recipeapp.domain.Notes; import com.oscarhanke.recipeapp.domain.Recipe; import com.oscarhanke.recipeapp.domain.UnitOfMeasure; import com.oscarhanke.recipeapp.repositories.CategoryRepository; import com.oscarhanke.recipeapp.repositories.RecipeRepository; import com.oscarhanke.recipeapp.repositories.UnitOfMeasureRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Slf4j @Component public class RecipeBootstrap implements ApplicationListener<ContextRefreshedEvent> { private final CategoryRepository categoryRepository; private final UnitOfMeasureRepository unitOfMeasureRepository; private final RecipeRepository recipeRepository; public RecipeBootstrap(CategoryRepository categoryRepository, UnitOfMeasureRepository unitOfMeasureRepository, RecipeRepository recipeRepository) { this.categoryRepository = categoryRepository; this.unitOfMeasureRepository = unitOfMeasureRepository; this.recipeRepository = recipeRepository; } @Override @Transactional public void onApplicationEvent(ContextRefreshedEvent event) { recipeRepository.saveAll(getRecipes()); log.debug("Loading bootstrap data"); } private List<Recipe> getRecipes(){ List<Recipe> recipes = new ArrayList<>(2); //get UOMs Optional<UnitOfMeasure> eachUomOptional = unitOfMeasureRepository.findByDescription("Each"); if (!eachUomOptional.isPresent()){ throw new RuntimeException("Expected UOM not found"); } Optional<UnitOfMeasure> tableSpoonUOMOptional = unitOfMeasureRepository.findByDescription("Tablespoon"); if (!tableSpoonUOMOptional.isPresent()){ throw new RuntimeException("Expected UOM not found"); } Optional<UnitOfMeasure> teaSpoonUOMOptional = unitOfMeasureRepository.findByDescription("Teaspoon"); if (!teaSpoonUOMOptional.isPresent()){ throw new RuntimeException("Expected UOM not found"); } Optional<UnitOfMeasure> dashUOMOptional = unitOfMeasureRepository.findByDescription("Dash"); if (!dashUOMOptional.isPresent()){ throw new RuntimeException("Expected UOM not found"); } Optional<UnitOfMeasure> pintUOMOptional = unitOfMeasureRepository.findByDescription("Pint"); if (!pintUOMOptional.isPresent()){ throw new RuntimeException("Expected UOM not found"); } Optional<UnitOfMeasure> cupUOMOptional = unitOfMeasureRepository.findByDescription("Cup"); if (!cupUOMOptional.isPresent()){ throw new RuntimeException("Expected UOM not found"); } //get optionals UnitOfMeasure eachUom = eachUomOptional.get(); UnitOfMeasure tableSpoonUom = tableSpoonUOMOptional.get(); UnitOfMeasure teaSpoonUom = teaSpoonUOMOptional.get(); UnitOfMeasure dashUom = dashUOMOptional.get(); UnitOfMeasure pintUom = pintUOMOptional.get(); UnitOfMeasure cupUom = cupUOMOptional.get(); //get categories Optional<Category> americanCategoryOptional = categoryRepository.findByDescription("American"); if (!americanCategoryOptional.isPresent()){ throw new RuntimeException("Expected Category Not Found"); } Optional<Category> mexicanCategoryOptional = categoryRepository.findByDescription("Mexican"); if (!mexicanCategoryOptional.isPresent()){ throw new RuntimeException("Expected Category Not Found"); } //get optionals Category americanCategory = americanCategoryOptional.get(); Category mexicanCategory = mexicanCategoryOptional.get(); //guacamole recipe Recipe guacamoleRecipe = new Recipe(); guacamoleRecipe.setDescription("Perfect Guacamole"); guacamoleRecipe.setPrepTime(10); guacamoleRecipe.setCookTime(0); guacamoleRecipe.setDifficulty(Difficulty.EASY); guacamoleRecipe.setDirections("1. Cut the avocados in half. Remove the pit. Score the inside of the avocado with a blunt knife and scoop out the flesh with a spoon. Place in a bowl." + "\n" + "2. Using a fork, roughly mash the avocado. (Don't overdo it! The guacamole should be a little chunky.)" + "\n" + "3. Sprinkle with salt and lime (or lemon) juice. The acid in the lime juice will provide some balance to the richness of the avocado and will help delay the avocados from turning brown.\n" + "Add the chopped onion, cilantro, black pepper, and chilis. Chili peppers vary individually in their spiciness. So, start with a half of one chili pepper and add more to the guacamole to your desired degree of heat.\n" + "Remember that much of this is done to taste because of the variability in the fresh ingredients. Start with this recipe and adjust to your taste." + "\n" + "4. If making a few hours ahead, place plastic wrap on the surface of the guacamole and press down to cover it to prevent air reaching it. (The oxygen in the air causes oxidation which will turn the guacamole brown.)\n" + "Garnish with slices of red radish or jigama strips. Serve with your choice of store-bought tortilla chips or make your own homemade tortilla chips.\n" + "Refrigerate leftover guacamole up to 3 days.\n" + "Note: Chilling tomatoes hurts their flavor. So, if you want to add chopped tomato to your guacamole, add it just before serving."); Notes guacamoleNotes = new Notes(); guacamoleNotes.setRecipeNotes("Look for ancho chile powder with the Mexican ingredients at your grocery store, on buy it online. (If you can't find ancho chili powder, you replace the ancho chili, the oregano, and the cumin with 2 1/2 tablespoons regular chili powder, though the flavor won't be quite the same.)"); guacamoleNotes.setRecipe(guacamoleRecipe); guacamoleRecipe.setNotes(guacamoleNotes); guacamoleRecipe.addIngredient(new Ingredient("ripe avocados", new BigDecimal(2), eachUom)); guacamoleRecipe.addIngredient(new Ingredient("Kosher salt", new BigDecimal(".5"), teaSpoonUom)); guacamoleRecipe.addIngredient(new Ingredient("fresh lime juice or lemon juice", new BigDecimal(2), tableSpoonUom)); guacamoleRecipe.addIngredient(new Ingredient("minced red onion or thinly sliced green onion", new BigDecimal(2), tableSpoonUom)); guacamoleRecipe.addIngredient(new Ingredient("serrano chiles, stems and seeds removed, minced", new BigDecimal(2), eachUom)); guacamoleRecipe.addIngredient(new Ingredient("Cilantro", new BigDecimal(2), tableSpoonUom)); guacamoleRecipe.addIngredient(new Ingredient("freshly grated black pepper", new BigDecimal(2), dashUom)); guacamoleRecipe.addIngredient(new Ingredient("ripe tomato, seeds and pulp removed, chopped", new BigDecimal(".5"), eachUom)); guacamoleRecipe.getCategories().add(americanCategory); guacamoleRecipe.getCategories().add(mexicanCategory); guacamoleRecipe.setUrl("https://www.simplyrecipes.com/recipes/perfect_guacamole/"); guacamoleRecipe.setServings(4); guacamoleRecipe.setSource("Simply Recipe"); //add to return list recipes.add(guacamoleRecipe); //tacos Recipe tacosRecipe = new Recipe(); tacosRecipe.setDescription("Spicy Grilled Chicken Taco"); tacosRecipe.setCookTime(9); tacosRecipe.setPrepTime(20); tacosRecipe.setDifficulty(Difficulty.MODERATE); tacosRecipe.setDirections("1 Prepare a gas or charcoal grill for medium-high, direct heat.\n" + "2 Make the marinade and coat the chicken: In a large bowl, stir together the chili powder, oregano, cumin, sugar, salt, garlic and orange zest. Stir in the orange juice and olive oil to make a loose paste. Add the chicken to the bowl and toss to coat all over.\n" + "Set aside to marinate while the grill heats and you prepare the rest of the toppings.\n" + "\n" + "\n" + "3 Grill the chicken: Grill the chicken for 3 to 4 minutes per side, or until a thermometer inserted into the thickest part of the meat registers 165F. Transfer to a plate and rest for 5 minutes.\n" + "4 Warm the tortillas: Place each tortilla on the grill or on a hot, dry skillet over medium-high heat. As soon as you see pockets of the air start to puff up in the tortilla, turn it with tongs and heat for a few seconds on the other side.\n" + "Wrap warmed tortillas in a tea towel to keep them warm until serving.\n" + "5 Assemble the tacos: Slice the chicken into strips. On each tortilla, place a small handful of arugula. Top with chicken slices, sliced avocado, radishes, tomatoes, and onion slices. Drizzle with the thinned sour cream. Serve with lime wedges.\n" + "\n" + "\n" + "Read more: http://www.simplyrecipes.com/recipes/spicy_grilled_chicken_tacos/#ixzz4jvtrAnNm"); Notes tacoNotes = new Notes(); tacoNotes.setRecipeNotes("We have a family motto and it is this: Everything goes better in a tortilla.\n" + "Any and every kind of leftover can go inside a warm tortilla, usually with a healthy dose of pickled jalapenos. I can always sniff out a late-night snacker when the aroma of tortillas heating in a hot pan on the stove comes wafting through the house.\n" + "Today’s tacos are more purposeful – a deliberate meal instead of a secretive midnight snack!\n" + "First, I marinate the chicken briefly in a spicy paste of ancho chile powder, oregano, cumin, and sweet orange juice while the grill is heating. You can also use this time to prepare the taco toppings.\n" + "Grill the chicken, then let it rest while you warm the tortillas. Now you are ready to assemble the tacos and dig in. The whole meal comes together in about 30 minutes!\n" + "\n" + "\n" + "Read more: http://www.simplyrecipes.com/recipes/spicy_grilled_chicken_tacos/#ixzz4jvu7Q0MJ"); tacoNotes.setRecipe(tacosRecipe); tacosRecipe.setNotes(tacoNotes); tacosRecipe.getIngredients().add(new Ingredient("Ancho Chili Powder", new BigDecimal(2), tableSpoonUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("Dried Oregano", new BigDecimal(1), teaSpoonUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("Dried Cumin", new BigDecimal(1), teaSpoonUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("Sugar", new BigDecimal(1), teaSpoonUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("Salt", new BigDecimal(".5"), teaSpoonUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("Clove of Garlic, Choppedr", new BigDecimal(1), eachUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("finely grated orange zestr", new BigDecimal(1), tableSpoonUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("fresh-squeezed orange juice", new BigDecimal(3), tableSpoonUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("Olive Oil", new BigDecimal(2), tableSpoonUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("boneless chicken thighs", new BigDecimal(4), tableSpoonUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("small corn tortillasr", new BigDecimal(8), eachUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("packed baby arugula", new BigDecimal(3), cupUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("medium ripe avocados, slic", new BigDecimal(2), eachUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("radishes, thinly sliced", new BigDecimal(4), eachUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("cherry tomatoes, halved", new BigDecimal(".5"), pintUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("red onion, thinly sliced", new BigDecimal(".25"), eachUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("Roughly chopped cilantro", new BigDecimal(4), eachUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("cup sour cream thinned with 1/4 cup milk", new BigDecimal(4), cupUom, tacosRecipe)); tacosRecipe.getIngredients().add(new Ingredient("lime, cut into wedges", new BigDecimal(4), eachUom, tacosRecipe)); tacosRecipe.getCategories().add(americanCategory); tacosRecipe.getCategories().add(mexicanCategory); //add to return list recipes.add(tacosRecipe); return recipes; } }
<?php namespace App\Http\Requests\User; use Illuminate\Validation\Rule; class UpdateUserRequest extends StoreUserRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, mixed> */ public function rules() { $rules = parent::rules(); $rules['email'] = [ 'required', 'string', 'email', 'max:255', Rule::unique('users')->ignore($this->user)->whereNull('deleted_at') ]; //$rules['password'] = 'required'; return $rules; } public function messages(){ $messages = parent::messages(); $messages['password.required'] = "La contraseña es requerida."; return $messages; } }
/* ***************************************************************************** * Name: * Date: * Description: **************************************************************************** */ import java.util.Iterator; import java.util.NoSuchElementException; public class Deque<Item> implements Iterable<Item> { private int size; private Node head; private Node tail; private class Node { Item item; Node prev; Node next; Node(Item item) { this.item = item; } } private class ItemIterator implements Iterator<Item> { Node currentNode; ItemIterator() { currentNode = new Node(null); currentNode.next = head; } public boolean hasNext() { return currentNode.next != null; } public Item next() { if (!hasNext()) throw new NoSuchElementException(); currentNode = currentNode.next; return currentNode.item; } public void remove() { throw new UnsupportedOperationException(); } } // construct an empty deque public Deque() { size = 0; } // is the deque empty? public boolean isEmpty() { return size == 0; } // return the number of items on the deque public int size() { return size; } // add the item to the front public void addFirst(Item item) { if (item == null) throw new IllegalArgumentException(); Node newNode = new Node(item); if (head == null) { head = newNode; tail = newNode; } else { newNode.next = head; head.prev = newNode; head = newNode; } size++; } // add the item to the back public void addLast(Item item) { if (item == null) throw new IllegalArgumentException(); Node newNode = new Node(item); if (tail == null) { head = newNode; tail = newNode; } else { tail.next = newNode; newNode.prev = tail; tail = newNode; } size++; } // remove and return the item from the front public Item removeFirst() { if (size == 0) throw new NoSuchElementException(); Node oldItem = head; if (head == tail) { head = null; tail = null; } else { head = head.next; head.prev = null; } size--; return oldItem.item; } // remove and return the item from the back public Item removeLast() { if (size == 0) throw new NoSuchElementException(); Node oldItem = tail; if (tail == head) { tail = null; head = null; } else { tail = tail.prev; tail.next = null; } size--; return oldItem.item; } // return an iterator over items in order from front to back public Iterator<Item> iterator() { return new ItemIterator(); } // unit testing (required) public static void main(String[] args) { Deque<Integer> d = new Deque<>(); d.addFirst(null); for (int i = 0; i < 10; i++) d.addFirst(i); for (int i = 10; i < 20; i++) d.addLast(i); d.removeLast(); d.removeFirst(); d.removeLast(); d.removeFirst(); d.removeLast(); d.removeFirst(); d.removeLast(); d.removeFirst(); d.removeLast(); d.removeFirst(); d.removeLast(); d.removeFirst(); d.removeLast(); d.removeFirst(); d.removeLast(); d.removeFirst(); d.removeLast(); d.size(); d.isEmpty(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> <style> rogier-quote p { color: blue; } </style> </head> <body> <rogier-quote data-nr="1"></rogier-quote> <rogier-quote data-nr="3"></rogier-quote> <rogier-quote data-nr="2"></rogier-quote> <script> 'use strict' // define new element based on HTMLQuoteElement class RogierQuoteElement extends HTMLQuoteElement { // call parent constructor constructor() { super(); } // create content createdCallback(){ var quotes = [ 'beter één vogel in de hand dan 10 in andermans hand', 'men moet een gegeven paard niet op de bek slaan', 'hoe meer zielen, hoe zieliger' ]; var nr = this.hasAttribute('data-nr') ? +this.getAttribute('data-nr') % 3 : Math.floor(Math.random() * 3); this.innerHTML = '<p>' + quotes[nr] + '</p>'; } } // register new element with tagname 'rogier-quote' document.registerElement('rogier-quote', RogierQuoteElement); </script> </body> </html>
<template> <base-card-page header="Change password"> <el-form ref="formRef" class="form" label-position="top" :model="form" :rules="requestPasswordResetRules"> <p> Enter the email address you used for this site and we will send pam an email with instructions on how to reset your password. </p> <el-form-item label="Email" prop="email"> <el-input v-model="form.email" v-on:keyup.enter="submitForm()" :disabled="disabled" maxlength="254" show-word-limit clearable style="max-width: 132ch" ></el-input> </el-form-item> <el-form-item> <div style="margin-left: auto; margin-right: 0; margin-top: 1rem"> <el-link type="primary" :underline="false" style="margin-right: 1rem" @click="$router.push({ name: 'Login' })" > Go back </el-link> <el-button type="primary" :loading="disabled" @click="submitForm()"> Send Email </el-button> </div> </el-form-item> </el-form> </base-card-page> </template> <script setup lang="ts"> import { BaseCardPage } from '@/components/pages'; import { requestPasswordResetRules } from '@/components/tags/form/rules'; import { useRequestPasswordReset } from '@/composables'; import type { FormInstance } from 'element-plus'; import { ElButton, ElForm, ElFormItem, ElInput, ElLink } from 'element-plus'; import { ref } from 'vue'; import { useRouter } from 'vue-router'; const router = useRouter(); const formRef = ref<FormInstance>(); const disabled = ref(false); const form = ref({ email: '', }); async function fetch() { const url = new URL( router.resolve({ name: 'ResetPasswordRequest', }).href, window.location.origin, ).href; const data = await useRequestPasswordReset(form.value.email, url); if (data === null) { disabled.value = false; } else { router.push({ name: 'ResetPasswordConfirm' }); } } function submitForm() { formRef.value?.validate(isValid => { if (isValid) { disabled.value = true; fetch(); return true; } return false; }); } </script>
import React from "react" import { Redirect } from "react-router-dom" import { Button } from "react-bootstrap" import DataSource from "../data/datasource" import FormInput from "../components/FormInput" import BasePage from "./BasePage" import AlertMessage from "../components/AlertMessage" export default class SignUpPage extends React.Component { constructor() { super() this.state = { username: "", password: "", confirmPassword: "", isLoading: false, validationsError: [], } this.handleSignUp = this.handleSignUp.bind(this) this.handleInputChanged = this.handleInputChanged.bind(this) } render() { if (DataSource.shared.isLoggedIn) { return <Redirect to='/'/> } const { errorMessage, username, password, confirmPassword, isLoading, validationsError } = this.state return ( <BasePage isLoading={isLoading}> <AlertMessage errorMessage={errorMessage}/> <form> <FormInput id="username" type="username" label="username" help={validationsError.username} value={username} validationstate={validationsError.username ? "error" : null} onChange={this.handleInputChanged} /> <FormInput id="password" type="password" label="Password" help={validationsError.password} value={password} validationstate={validationsError.password ? "error" : null} onChange={this.handleInputChanged} /> {/* <FormInput id="confirmPassword" type="password" label="confirmPassword" help={validationsError.confirmPassword} value={confirmPassword} validationstate={validationsError.confirmPassword ? "error" : null} onChange={this.handleInputChanged} /> */} <Button type="submit" onClick={this.handleSignUp} disabled={isLoading}>SignUp</Button> </form> </BasePage> ) } handleInputChanged(event) { const { value, id } = event.target switch (id) { case "username": this.setState({ username: value, }) break case "password": this.setState({ password: value, }) break case "confirmPassword": this.setState({ confirmPassword: value, }) break } } async handleSignUp(e) { e.preventDefault() const { username, password, confirmPassword } = this.state this.setState({ isLoading: true, }, async () => { try { await DataSource.shared.signup(username, password, confirmPassword) await DataSource.shared.login(username, password) this.setState({ isLoading: false, }) window.location.replace("/") } catch (err) { if (err.type === "validation_failed") { this.parseValidationError(err.validationErrors) } else { this.setState({ errorMessage: err.type || err.message, isLoading: false, }) } } }) } parseValidationError(validationErrors) { const { validationsError } = this.state validationErrors.forEach((validationError) => { switch (validationError.field) { case "username" : validationsError.username = validationError.type break case "password" : validationsError.password = validationError.type break } }) } }
https://www.geeksforgeeks.org/path-length-maximum-number-bends/ 1. Start with left and right subtree of root with dir 'l' and 'r', everytime if u chnage direction increment bend 2. When u reach leaf node compare max bend Time:O(N), SPace:O(H) #include <iostream> using namespace std; struct Node { int key; struct Node* left; struct Node* right; }; // Utility function to create a new node struct Node* newNode(int key) { struct Node* node = new Node(); node->left = NULL; node->right = NULL; node->key = key; return node; } void solve(Node* root, int bend, char dir, int currLength, int& len, int& maxBend) { if(!root) { return; } if(!root->left && !root->right) { if(maxBend<bend) { maxBend=bend; len=currLength; } } else { if(dir=='l') { //u can continue to move to left or right solve(root->left,bend,'l',currLength+1,len,maxBend); solve(root->right,bend+1,'r',currLength+1,len,maxBend); } else { //u can continue to move to right or left solve(root->right,bend,'r',currLength+1,len,maxBend); solve(root->left,bend+1,'l',currLength+1,len,maxBend); } } } int findMaxBends(Node* root) { //find total num of nodes in that path and return -1 as we want the length if(!root) { return 0; } if(!root->left && !root->right) { return 0; } int len=0,maxBend=0; //try for both left and right subtree solve(root->left,0,'l',1,len,maxBend); solve(root->right,0,'r',1,len,maxBend); len++; //add root; return len; } int main() { Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(2); root->right->left->right = newNode(1); root->right->left->right->left = newNode(9); cout << findMaxBends(root) -1 ; //as we need to find edge length return 0; }
from flask import Flask, render_template, jsonify,request import requests,re import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart app = Flask(__name__) # Replace 'YOUR_API_KEY' with your actual API key api_key = '69194etjlfv7x06u7do6k' # DoodAPI endpoint URL url = f'https://doodapi.com/api/file/list?key={api_key}' @app.route('/') def movie_list(): params = { 'per_page': 25, 'fid':'yes' } # Make the API request response = requests.get(url, params=params) # Check if the request was successful if response.status_code == 200: # Parse the JSON response movie_data = response.json() movies = movie_data.get('result', {}).get('files', []) return render_template('movies.html', movies=movies) # Pass movies data to the template else: error_message = f"Error: Unable to retrieve movie data. Status code: {response.status_code}" return jsonify(error=error_message), 500 @app.route('/bollywood') def movie_list_bollywood(): params = { 'per_page': 25, 'fid':'yes' } # Make the API request response = requests.get(url, params=params) # Check if the request was successful if response.status_code == 200: # Parse the JSON response movie_data = response.json() movies = movie_data.get('result', {}).get('files', []) return render_template('bollywood.html', movies=movies) # Pass movies data to the template else: error_message = f"Error: Unable to retrieve movie data. Status code: {response.status_code}" return jsonify(error=error_message), 500 @app.route('/hollywood') def movie_list_hollywood(): params = { 'per_page': 25, 'fid':'yes' } # Make the API request response = requests.get(url, params=params) # Check if the request was successful if response.status_code == 200: # Parse the JSON response movie_data = response.json() movies = movie_data.get('result', {}).get('files', []) return render_template('hollywood.html', movies=movies) # Pass movies data to the template else: error_message = f"Error: Unable to retrieve movie data. Status code: {response.status_code}" return jsonify(error=error_message), 500 @app.route('/web-series') def movie_list_web_series(): params = { 'per_page': 25, 'fid':'yes' } # Make the API request response = requests.get(url, params=params) # Check if the request was successful if response.status_code == 200: # Parse the JSON response movie_data = response.json() movies = movie_data.get('result', {}).get('files', []) return render_template('web-series.html', movies=movies) # Pass movies data to the template else: error_message = f"Error: Unable to retrieve movie data. Status code: {response.status_code}" return jsonify(error=error_message), 500 @app.route('/punjabi') def movie_list_punjabi(): params = { 'per_page': 25, 'fid':'yes' } # Make the API request response = requests.get(url, params=params) # Check if the request was successful if response.status_code == 200: # Parse the JSON response movie_data = response.json() movies = movie_data.get('result', {}).get('files', []) return render_template('punjabi.html', movies=movies) # Pass movies data to the template else: error_message = f"Error: Unable to retrieve movie data. Status code: {response.status_code}" return jsonify(error=error_message), 500 @app.route('/bollywood/<file_code>') @app.route('/hollywood/<file_code>') @app.route('/punjabi/<file_code>') @app.route('/web-series/<file_code>') @app.route('/netflix/<file_code>') @app.route('/<file_code>') def movie_detail(file_code): params = { 'search_term': file_code, } # Make the API request response = requests.get(f'https://doodapi.com/api/search/videos?key={api_key}', params=params) # print(response.text) # Check if the request was successful if response.status_code == 200: # Parse the JSON response movie_data = response.json() movie = movie_data.get('result', {})[0] movie_title=movie['title'] movie_img=movie['splash_img'] movie_id=movie['file_code'] print(movie_title) description = get_movie_description(movie_title) movie_data={ 'title':movie_title, 'splash_img':movie_img, 'file_code':movie_id, 'description':description } print(movie_data) return render_template('moviedetail.html', movie=movie_data) else: error_message = f"Error: Movie not found for title: {file_code}" return jsonify(error=error_message), 404 def get_movie_description(movie_title): # Define the OMDb API endpoint and your API key (get a free API key from http://www.omdbapi.com/apikey.aspx) api_key = "626c98f7" # Replace with your API key url = f"http://www.omdbapi.com/?t={movie_title}&apikey={api_key}" # Send an HTTP GET request to the OMDb API response = requests.get(url) if response.status_code == 200: movie_data = response.json() print(movie_data) if "Plot" in movie_data: return movie_data # Description is in the "Plot" field else: return "Description not found" else: return "Unable to retrieve data from OMDb API" # Define routes for movie search and movie request @app.route('/search', methods=['POST']) def search_movies(): search_query = request.form.get('search_query') print(search_query) params = { 'search_term': search_query, } # Make the API request response = requests.get(f'https://doodapi.com/api/search/videos?key={api_key}', params=params) # print(response.text) # Check if the request was successful if response.status_code == 200: # Parse the JSON response movie_data = response.json() movie = movie_data.get('result', {})[0] movie_title=movie['title'] movie_img=movie['splash_img'] movie_id=movie['file_code'] print(movie_title) description = get_movie_description(movie_title) movie_data={ 'title':movie_title, 'splash_img':movie_img, 'file_code':movie_id, 'description':description } print(movie_data) return render_template('moviedetail.html', movie=movie_data) else: error_message = f"Error: Movie not found for title: {search_query}" return jsonify(error=error_message), 404 @app.route('/request', methods=['POST']) def request_movie(): requested_movie = request.form.get('comment') print(requested_movie) smtp_server = 'smtp.gmail.com' smtp_port = 587 # 587 is the default for TLS, use 465 for SSL smtp_username = 'sarbtech123@@gmail.com' smtp_password = 'fpaibhjdkuifdifs' sender_email = 'sarbtech123@gmail.com' recipient_email = 'sarbtech123@gmail.com' subject = 'Movie requested' msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = recipient_email msg['Subject'] = subject msg.attach(MIMEText(requested_movie, 'plain')) try: # Connect to the SMTP server and send the email with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(smtp_username, smtp_password) server.sendmail(sender_email, recipient_email, msg.as_string()) response = 'Request sent successfully' print(response) return jsonify({"message": response}) except Exception as e: response = 'Error sending Request: ' + str(e) return response if __name__ == '__main__': app.run(debug=True)
<template> <v-card> <v-card-title>Tags</v-card-title> <v-card-text> <v-form ref="tagform" @submit.prevent="addTagToRecipe" @keydown.tab="addTagToRecipe" > <v-row no-gutters> <v-col cols="12" md="5"> <v-text-field variant="outlined" v-model="recipe.recipeName" label="Rezept Name" /> </v-col> <v-col cols="12" md="5" ><v-autocomplete variant="outlined" id="searchField" multiple chips closable-chips :items="tagItems" v-model="recipe.tags" v-model:search="searchValue" hide-selected label="Tags" @click="getTagItems" ></v-autocomplete ></v-col> <v-col cols="2"><v-btn block variant="outlined" height="70%" rounded="0" type="submit">speichern</v-btn></v-col> </v-row> </v-form> </v-card-text> <v-card-text> <ul> <li>searchValue: {{ searchValue }}</li> <li>model: {{ model }}</li> <li>rezept: {{ recipe }}</li> </ul> log: {{ message() }} </v-card-text> </v-card> </template> <script setup lang="ts"> import { computed, ref } from "vue"; import { db, getCollection } from "@/plugins/firebase"; const props = defineProps(["modelValue"]); const emitValue = defineEmits(["update:modelValue"]); const tagItems = ref<string[]>(["erster Tag"]); const searchValue = ref(); const model = ref(); const recipe = computed({ get() { return props.modelValue; }, set(value) { emitValue("update:modelValue", value); }, }); function message(value: string): string { setTimeout(() => { value = "asdfa" }, 1000) return "laksjdöflkjasdf"; } function getTagItems(): void { console.log("getTagItems"); getCollection("tags").then((res) => { tagItems.value = []; res.forEach((tag) => { const tags = tag.data(); tagItems.value = tags.tags; }); }); } function addTagToRecipe(): void { console.log("add ", searchValue.value); if (!searchValue.value) { message("leerer String"); console.info("leerer String"); } else { recipe.value.tags.push(searchValue.value); } searchValue.value = null; } </script> <style scoped></style>
import React from 'react'; import { render, fireEvent } from '@testing-library/react'; import BmiCalculation from './bmiCalculation'; import '@testing-library/jest-dom'; describe('BMI Calculation', () => { it('calculates BMI correctly', () => { const { getByLabelText, getByText } = render(<BmiCalculation />); const weightInput = getByLabelText('Weight (kg):'); const heightInput = getByLabelText('Height (m):'); const calculateButton = getByText('Calculate BMI'); // Test with valid inputs fireEvent.change(weightInput, { target: { value: '70' } }); fireEvent.change(heightInput, { target: { value: '1.75' } }); fireEvent.click(calculateButton); expect(getByText('Your BMI is: 22.9')).toBeInTheDocument(); // Test with invalid weight fireEvent.change(weightInput, { target: { value: '0' } }); fireEvent.click(calculateButton); expect(getByText('Weight should be between 1.0 and 300.0 kg')).toBeInTheDocument(); // Test with invalid height fireEvent.change(weightInput, { target: { value: '70' } }); fireEvent.change(heightInput, { target: { value: '0' } }); fireEvent.click(calculateButton); expect(getByText('Height should be between 0.1 and 3.0 meters')).toBeInTheDocument(); // Test with empty inputs fireEvent.change(weightInput, { target: { value: '' } }); fireEvent.change(heightInput, { target: { value: '' } }); fireEvent.click(calculateButton); expect(getByText('Weight is required')).toBeInTheDocument(); expect(getByText('Height is required')).toBeInTheDocument(); }); it('resets BMI calculation', () => { const { getByLabelText, getByText, queryByText } = render(<BmiCalculation />); const weightInput = getByLabelText('Weight (kg):'); const heightInput = getByLabelText('Height (m):'); const calculateButton = getByText('Calculate BMI'); const resetButton = getByText('Reset'); fireEvent.change(weightInput, { target: { value: '70' } }); fireEvent.change(heightInput, { target: { value: '1.75' } }); fireEvent.click(calculateButton); expect(getByText('Your BMI is: 22.9')).toBeInTheDocument(); fireEvent.click(resetButton); expect(weightInput.value).toBe(''); expect(heightInput.value).toBe(''); expect(queryByText('Your BMI is: 22.9')).not.toBeInTheDocument(); }); });
let multi = 2 let n = 0 console.log('WHILE') while (n < 10) { console.log(multi +' X '+ n +' = '+ multi * n) n++ } n = 0 console.log('') console.log('DO WHILE') do { // "do while" garante que mesmo a expressão seja falsa, o bloco seja executado ao menos uma vez if (n > 5 ) { break // pula o bloco } console.log(multi +' X '+ n +' = '+ multi * n) n++ } while (n < 10); console.log('') console.log('FOR') for (let i = 0; i < 10; i++) { if (i == 6) { continue // pula a execução } console.log(multi +' X '+ i +' = '+ multi * i) }
package com.app.note_lass.module.home.material import android.content.Intent import android.util.Log import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.app.note_lass.R import com.app.note_lass.common.File import com.app.note_lass.module.home.HomeViewModel import com.app.note_lass.module.note.NoteActivity import com.app.note_lass.ui.theme.NoteLassTheme import com.app.note_lass.ui.theme.PrimaryGray import java.io.FileOutputStream import java.io.IOException @Composable fun MaterialInHome( title : String, file : File, date: String, viewModel : HomeViewModel = hiltViewModel() ){ val context = LocalContext.current val fileState = viewModel.getMaterialFileState if(fileState.value.isSuccess&&file.id == fileState.value.result!!.fileId){ val fileMaterial = java.io.File(context.filesDir, "myFile") try { FileOutputStream(fileMaterial).use { outputStream -> val buffer = ByteArray(1024) var length: Int while (fileState.value.result!!.stream.read(buffer).also { length = it } != -1) { outputStream.write(buffer, 0, length) } } val intent = Intent(context, NoteActivity::class.java) if(file.originalFileName.contains("pdf")) { intent.putExtra("filePath", fileMaterial.absolutePath) intent.putExtra("pdfTitle", title) } else{ intent.putExtra("photoPath", fileMaterial.absolutePath) intent.putExtra("pdfTitle",title) } context.startActivity(intent) Log.e("filePath",fileMaterial.absolutePath) } catch (e: IOException) { e.printStackTrace() } // 파일 경로를 Intent에 넣어서 전달 // 파일 경로를 Intent에 넣어서 전달 // val intent = Intent(context, NoteActivity::class.java).apply { // val url = "https://notelass.site/api/file/" + file.id // putExtra("pdfString", url) // putExtra("pdfTitle", title) // } // context.startActivity(intent) } Box( modifier = Modifier .fillMaxSize() .padding(horizontal = 10.dp) .clickable { viewModel.getFile(file.id) } ){ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Icon(painter = painterResource(id = R.drawable.note_lecture_small),contentDescription = null,tint = Color.Unspecified) Spacer(modifier = Modifier.height(16.dp)) Text(text = title, style = NoteLassTheme.Typography.fourteen_600_pretendard) Spacer(modifier = Modifier.height(4.dp)) Text(text = date, style = NoteLassTheme.Typography.twelve_600_pretendard, color = PrimaryGray ) } } }
"use client"; import { Card, CardContent, CardDescription, CardTitle, CardFooter, CardHeader, } from "@/components/ui/card"; import { Avatar, AvatarImage } from "@/components/ui/avatar"; import { Button } from "@/components/ui/button"; import Image from "next/image"; import person_icon from "@/public/person_icon.svg"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { useRouter, useParams } from "next/navigation"; import { event1 } from "./volunteer-dummyData"; import { UUID } from "crypto"; import useVolunteeridQuery from "@/hooks/use-volunteerid-query"; import left_arrow_icon from "@/public/left_arrow_icon.svg"; import useRegisteredEventsOnAdminQuery from "@/hooks/use-registered-events-on-admin"; import moment from "moment"; import Link from "next/link"; export default function Volunteers() { const router = useRouter(); const { volunteer_id } = useParams(); const { data: volunteer, status } = useVolunteeridQuery(volunteer_id as UUID); const { data: registeredEvents, status: eventStatus } = useRegisteredEventsOnAdminQuery(volunteer_id as UUID); if (status === "pending") return <p>Loading...</p>; if (status === "error") return <ErrorResponse />; const accountDetails = [ { name: "Name", value: volunteer.name, }, { name: "Sex", value: volunteer.sex }, { name: "Date of Birth", value: volunteer.birth_date }, { name: "Email Address", value: volunteer.email }, { name: "Age", value: volunteer.age }, ]; const addressDetails = [ { name: "Address", value: volunteer.address, }, { name: "City", value: volunteer.city }, { name: "Province", value: volunteer.province }, { name: "Postal Code", value: volunteer.postal_code }, ]; const contactDetails = [ { name: "Phone Number", value: volunteer.phone_number, }, { name: "Emergency Contact", value: volunteer.emergency_contact }, { name: "Facebook Link", value: volunteer.email }, //to be changed ]; const schoolDetails = [ { name: "School", value: "placeholder", }, { name: "Major", value: "placeholder" }, { name: "Year", value: "placeholder" }, ]; const hoursRendered = [ { name: "Hours Rendered", value: volunteer.hours_rendered, }, ]; return ( <> <Button className="border-primary w-full max-w-fit" onClick={() => router.back()} > <Image src={left_arrow_icon} alt="left arrow icon" /> Back </Button> {/* Profile */} <div className="grid gap-4 md:grid-cols-3 lg:grid-cols-5 text-xsm"> {/* Account Details */} <div className="col-span-1"> <Card className=""> <CardHeader className="p-0 py-7 text-xsm"> <Avatar className="w-44 h-44 mx-auto"> <AvatarImage src={volunteer.picture!} /> </Avatar> <CardTitle className="text-md mx-auto pt-5 pb-1"> {volunteer.nickname} </CardTitle> <CardDescription className="mx-auto text-white"> <Button className="rounded-3xl font-semibold text-xsm"> Registration Form </Button> </CardDescription> </CardHeader> <CardContent className="font-semibold text-center text-lg pt-4 grid gap-y-2 bg-slate-300 rounded-b-md"> <p>{volunteer.occupation}</p> </CardContent> </Card> </div> {/* 2nd Grid */} <div className="col-span-2 space-y-3"> <Card> <CardHeader className="p-1 ps-3"> <CardTitle className="text-sm">Account Details</CardTitle> </CardHeader> <CardContent> {accountDetails.map((value, index) => ( <div key={index} className="flex justify-between"> <p className="py-1">{value.name}</p> <p>{value.value}</p> </div> ))} </CardContent> </Card> <Card> <CardHeader className="p-1 ps-3"> <CardTitle className="text-sm">Address Details</CardTitle> </CardHeader> <CardContent> {addressDetails.map((value, index) => ( <div key={index} className="flex justify-between"> <p className="py-1">{value.name}</p> <p>{value.value}</p> </div> ))} </CardContent> </Card> </div> {/* 3rd Grid */} <div className="col-span-2 space-y-3"> <Card> <CardHeader className="p-1 ps-3"> <CardTitle className="text-sm">Contact Details</CardTitle> </CardHeader> <CardContent> {contactDetails.map((value, index) => ( <div key={index} className="flex justify-between"> <p className="py-1">{value.name}</p> <p>{value.value}</p> </div> ))} </CardContent> </Card> <Card> <CardHeader className="p-1 ps-3"> <CardTitle className="text-sm">School Details</CardTitle> </CardHeader> <CardContent> {schoolDetails.map((value, index) => ( <div key={index} className="flex justify-between"> <p className="py-1">{value.name}</p> <p>{value.value}</p> </div> ))} </CardContent> </Card> </div> </div> <div className="md:flex"> <div className=""> <p className="pt-12 text-lg font-bold">Participated Events</p> {/* Participated Events */} <div className="text-xs grid md:grid-cols-3 gap-5 col-span-4 mr-10"> {registeredEvents?.events!.map( ({ event_id, name, event_start, volunteer_cap }) => ( <Card key={event_id}> <CardHeader className="p-3 pt-4"> <CardTitle className="text-md leading-8">{name}</CardTitle> <CardDescription className="text-sm"> {moment(event_start).format(" MMMM DD YYYY")} </CardDescription> {registeredEvents?.eventVolunteer.map( ({ event_id: singleEventID, status }) => singleEventID == event_id ? ( <CardDescription key={event_id} className={ status === "accepted" ? "text-center text-primary-foreground font-semibold py-3 px-5 mt-3 bg-green-400 rounded-lg" : "text-center text-primary-foreground font-semibold py-3 px-5 mt-3 bg-red-500 rounded-lg" } > {status} </CardDescription> ) : ( "" ), )} </CardHeader> <CardContent></CardContent> <CardFooter className="p-3 flex justify-between text-white"> <div> <Image className="inline-block" src={person_icon} alt="person icon" /> <span className="ps-2 align-middle text-black font-semibold"> {volunteer_cap} </span> </div> <Link href={{ pathname: `/dashboard/events/${event_id}` }}> <Button className="text-xsm ">View Event</Button> </Link> </CardFooter> </Card> ), )} </div> </div> <div className="flex-1"> <div className=" p-6 md:p-8"> <div className="flex items-center justify-center mb-6"> <h1 className="text-lg font-bold text-center">Total Hours</h1> </div> <div className="flex flex-col items-center justify-center gap-8"> <div className="flex flex-col items-center justify-center"> <CardContent> {hoursRendered.map((value, index) => ( <div key={index} className="flex justify-between text-5xl font-bold" > {value.value} </div> ))} </CardContent> {/* <div className="text-4xl font-bold">160</div> */} <p className="text-gray-500 dark:text-gray-400">Hours</p> </div> </div> </div> </div> </div> </> ); } function ErrorResponse() { return ( <Alert variant="destructive"> <AlertTitle>An error has occurred!</AlertTitle> <AlertDescription> There was an error in fetching Volunteers data. </AlertDescription> </Alert> ); }
const baseURL = 'https://www.apitutor.org/spotify/simple/v1/search'; // Note: AudioPlayer is defined in audio-player.js const audioFile = 'https://p.scdn.co/mp3-preview/bfead324ff26bdd67bb793114f7ad3a7b328a48e?cid=9697a3a271d24deea38f8b7fbfa0e13c'; const audioPlayer = AudioPlayer('.player', audioFile); const search = (ev) => { const term = document.querySelector('#search').value; console.log('search for:', term); // issue three Spotify queries at once... getTracks(term); getAlbums(term); getArtist(term); if (ev) { ev.preventDefault(); } } const getTracks = (term) => { console.log(` get tracks from spotify based on the search term "${term}" and load them into the #tracks section of the DOM...`); const element = document.querySelector("#tracks") element.innerHTML = "" fetch(baseURL + "?type=track&q=" + term) .then(response=>response.json()) .then((data)=>{ if (data.length == 0) { document.querySelector("#tracks").innerHTML += "No tracks found that match your search criteria." } if(data.length > 0){ for(track of data.slice(0,5)){ element.innerHTML +=`<button class="track-item preview" data-preview-track="${track.preview_url}" onclick="handleTrackClick(event);"> <img src="${track.album.image_url}"> <i class="fas play-track fa-play" aria-hidden="true"></i> <div class="label"> <h2>${track.name}</h2> <p> ${track.artist.name} </p> </div> </button>` } } }) }; const getAlbums = (term) => { console.log(` get albums from spotify based on the search term "${term}" and load them into the #albums section of the DOM...`); const element = document.querySelector("#albums") element.innerHTML = "" fetch(baseURL + "?type=album&q=" + term) .then(response=>response.json()) .then((data)=>{ if (data.length == 0) { document.querySelector("#albums").innerHTML += "No albums found that match your search criteria." } if(data.length > 0){ for(album of data){ element.innerHTML +=`<section class="album-card" id="${album.id}"> <div> <img src="${album.image_url}"> <h2>${album.name}</h2> <div class="footer"> <a href="${album.spotify_url}" target="_blank"> view on spotify </a> </div> </div> </section>` } } }) }; const getArtist = (term) => { console.log(` get artists from spotify based on the search term "${term}" and load the first artist into the #artist section of the DOM...`); const element = document.querySelector("#artist") element.innerHTML = "" fetch(baseURL + "?type=artist&q=" + term) .then(response=>response.json()) .then((data)=>{ if (data.length == 0) { document.querySelector("#artist").innerHTML += "No artists found that match your search criteria." } if(data.length > 0){ const firstArtist = data[0] element.innerHTML += `<section class="artist-card" id="${firstArtist.id}"> <div> <img src="${firstArtist.image_url}"> <h2>${firstArtist.name}</h2> <div class="footer"> <a href="${firstArtist.spotify_url}" target="_blank"> view on spotify </a> </div> </div> </section>` } }) }; const handleTrackClick = (ev) => { const previewUrl = ev.currentTarget.getAttribute('data-preview-track'); console.log(previewUrl); audioPlayer.setAudioFile(previewUrl) audioPlayer.play() document.querySelector("#current-track").innerHTML = ev.currentTarget.innerHTML } document.querySelector('#search').onkeyup = (ev) => { // Number 13 is the "Enter" key on the keyboard console.log(ev.keyCode); if (ev.keyCode === 13) { ev.preventDefault(); search(); } };
#[doc(inline)] use std::path::PathBuf; use color_eyre::{ eyre::{ensure, eyre}, Result, }; use ndarray::{Array2, ShapeBuilder}; use rayon::prelude::*; use rust_htslib::bcf::header::HeaderView; use rust_htslib::bcf::record::GenotypeAllele; use rust_htslib::bcf::IndexedReader; use rust_htslib::bcf::Read; use rust_htslib::bcf::Record; use crate::structs::{Coord, PhasedMatrix}; use crate::utils::filter_samples; use crate::{ args::Selection, error::HatkError::{NormalizeError, PloidyError, SamplesNotFoundError}, }; use crate::{args::StandardArgs, core::get_htslib_contig_len}; use crate::{io::read_sample_ids, structs::Ploidy}; pub fn get_reader( path: &PathBuf, contig: &str, range: Option<(u64, u64)>, ) -> Result<IndexedReader> { let mut reader = IndexedReader::from_path(path)?; let rid = reader.header().name2rid(contig.as_bytes())?; match range { // RUST-HTSLIB is 0-based so subtract 1 Some((start, end)) => { reader.fetch(rid, start.saturating_sub(1), Some(end.saturating_sub(1)))? } None => reader.fetch(rid, 0, None)?, }; Ok(reader) } pub fn get_samples(header: &HeaderView) -> Result<Vec<String>> { header .samples() .into_iter() .map(|sample| Ok(String::from_utf8_lossy(sample).to_string())) .collect() } pub fn get_sample_names( args: &StandardArgs, contig: &str, wanted_samples: Option<Vec<String>>, ) -> Result<(Vec<usize>, Vec<String>)> { let reader = get_reader(&args.file, contig, None)?; let samples = reader .header() .samples() .into_iter() .map(|sample| Ok(String::from_utf8_lossy(sample).to_string())) .collect::<Result<Vec<String>>>()?; let wanted = match wanted_samples.clone() { Some(wanted) => Some(wanted), None => read_sample_ids(&args.samples)?, }; let sample_indexes = filter_samples(&samples, wanted); ensure!(!sample_indexes.is_empty(), SamplesNotFoundError); let samples: Vec<String> = sample_indexes .iter() .map(|s| &samples[*s]) .cloned() .collect(); Ok((sample_indexes, samples)) } pub fn read_vcf_to_matrix( args: &StandardArgs, contig: &str, variant_pos: u64, range: Option<(u64, u64)>, wanted_samples: Option<Vec<String>>, ) -> Result<PhasedMatrix> { let (indexes, samples) = get_sample_names(args, contig, wanted_samples)?; tracing::info!("Input VCF: {:?}", args.file); tracing::info!("Reading phased genotypes from {contig} with target position at {variant_pos}."); tracing::info!("Using {} samples from the VCF.", indexes.len()); // If contig length not reported, read single thread if get_htslib_contig_len(&args.file, contig).is_err() { tracing::info!( "Contig {} length missing from the VCF. Reading genotypes single-threaded.", contig ); let (markers, coords) = read_vcf_to_matrix_single_batch(args, contig, range, &indexes)?; tracing::info!("Finished reading all genotypes."); construct_phased_matrix( samples, markers, coords, &args.selection, variant_pos, contig, ) } else { read_parallel(args, contig, variant_pos, range, samples, &indexes) } } fn read_vcf_to_matrix_single_batch( args: &StandardArgs, contig: &str, range: Option<(u64, u64)>, sample_indexes: &[usize], ) -> Result<(Vec<u8>, Vec<Coord>)> { let mut reader = get_reader(&args.file, contig, range)?; let (mut markers, mut coords) = (vec![], vec![]); let mut gt_buffer = rust_htslib::bcf::record::Buffer::new(); for record in reader.records() { let record = record?; // HTSlib is 0-based so add 1 let pos = (record.pos() + 1) as u64; tracing::trace!("Reading record at position {pos}"); // NOTE: this info_limit filter has not been tested // if _check_info_limit(args, &record, contig, pos)? { ensure!(record.alleles().len() == 2, NormalizeError(pos)); let gts = record.genotypes_shared_buffer(&mut gt_buffer)?; let markers_len_before = markers.len(); for i in sample_indexes { markers.extend(gts.get(*i).iter().filter_map(genotype_to_u8)); } let diff = markers.len() - markers_len_before; let gts_per_sample = diff / sample_indexes.len(); let gts_mod = diff % sample_indexes.len(); ensure!( check_ploidy(gts_per_sample, gts_mod, args), PloidyError((pos, gts_per_sample)) ); coords.push(construct_coord(&record, contig, pos)); // } } Ok((markers, coords)) } fn read_parallel( args: &StandardArgs, contig: &str, variant_pos: u64, range: Option<(u64, u64)>, samples: Vec<String>, sample_indexes: &[usize], ) -> Result<PhasedMatrix> { let (first_pos, last_pos) = match range { Some((start, end)) => (start, end), None => (0, get_htslib_contig_len(&args.file, contig)?), }; let mut batches = vec![]; let nthreads = rayon::current_num_threads(); let batch_size = (last_pos - first_pos) / (nthreads * 5) as u64; let mut start = first_pos; loop { // plus one to evade rounding down let end = start + batch_size + 1; if end <= last_pos { batches.push((start, end)); start = end + 1; } else { batches.push((start, last_pos)); break; } } tracing::info!("Reading the VCF genotypes in {} batches.", batches.len()); let matrices = batches .par_iter() .map(|range| read_vcf_to_matrix_single_batch(args, contig, Some(*range), sample_indexes)) .collect::<Result<Vec<(Vec<u8>, Vec<Coord>)>>>()?; tracing::info!("Finished parallelized construction of genotype matrices."); let (markers, coords) = matrices.into_iter().fold((vec![], vec![]), |mut acc, cur| { acc.0.extend(cur.0); acc.1.extend(cur.1); acc }); construct_phased_matrix( samples, markers, coords, &args.selection, variant_pos, contig, ) } fn construct_phased_matrix( samples: Vec<String>, markers: Vec<u8>, coords: Vec<Coord>, selection: &Selection, variant_pos: u64, contig: &str, ) -> Result<PhasedMatrix> { let ploidy: Ploidy = selection.as_ref().into(); let matrix = Array2::from_shape_vec((samples.len() * ploidy as usize, coords.len()).f(), markers)?; let mut vcf = PhasedMatrix::new(0, matrix, samples, coords, &selection); // vcf.variant_idx = vcf.get_first_idx_on_right_by_pos(variant_pos); vcf.variant_idx = vcf.get_nearest_idx_by_pos(variant_pos); if selection == &Selection::OnlyAlts || selection == &Selection::OnlyRefs { vcf.idx_by_pos(variant_pos).ok_or_else(|| { eyre!("Cannot select using a variant. Not found at position {contig}:{variant_pos}") })?; } tracing::info!( "Constructed a genotype matrix from {} records. Starting variant position: {}.", vcf.ncoords(), vcf.variant_idx_pos(), ); Ok(vcf) } fn check_ploidy(length: usize, gts_mod: usize, args: &StandardArgs) -> bool { if gts_mod != 0 { return false; } match args.selection { Selection::Haploid => length == 1 || length == 2, _ => length == 2, } } fn genotype_to_u8(g: &GenotypeAllele) -> Option<u8> { match g { GenotypeAllele::Unphased(v) => Some(*v as u8), GenotypeAllele::Phased(v) => Some(*v as u8), GenotypeAllele::UnphasedMissing => None, GenotypeAllele::PhasedMissing => None, } } fn construct_coord(record: &rust_htslib::bcf::Record, contig: &str, pos: u64) -> Coord { let alleles = record.alleles(); let reference = String::from_utf8_lossy(alleles.get(0).unwrap()).to_string(); let alt = String::from_utf8_lossy(alleles.get(1).unwrap()).to_string(); Coord { contig: contig.to_string(), reference, alt, pos, } } fn _check_info_limit(args: &StandardArgs, record: &Record, contig: &str, pos: u64) -> Result<bool> { if let Some(info_limit) = args.info_limit { match record.info(b"INFO").float()? { Some(buffer) => Ok(buffer[0] >= info_limit), None => return Err(eyre!("No INFO score on a variant at: {contig}:{pos}")), } } else { Ok(true) } }
from flask_wtf import FlaskForm from .models import User from wtforms import StringField, SubmitField, PasswordField, BooleanField, TextAreaField, EmailField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError, Regexp class LoginForm(FlaskForm): email = StringField("Пошта:", validators=[DataRequired("Це поле є обов'язковим"), Email("Будь-ласка введіть ваш пароль")]) password = PasswordField("Пароль:", validators=[DataRequired("Це поле є обов'язковим"), Length(min=6, max=10)]) rememberMe = BooleanField("Запам'ятати мене") submit = SubmitField("Вхід") class RegistrationForm(FlaskForm): username = StringField("Ім'я користувача", validators=[ DataRequired("Це поле обов'язкове"), Length(min=4, max=10), Regexp('^[A-Za-z][a-zA-Z0-9._]+$', 0, "Ім'я користувача повинно містити лише літери, цифри, крапки чи підкреслення")]) email = EmailField("Електронна пошта", validators=[DataRequired("Це поле обов'язкове"), Email("Будь ласка, введіть свою електронну адресу")]) password = PasswordField("Пароль", validators=[DataRequired("Це поле обов'язкове"), Length(min=6)]) confirmPassword = PasswordField("Підтвердити пароль", validators=[ DataRequired("Це поле обов'язкове"), EqualTo("password", "Паролі не збігаються")]) submit = SubmitField("Зареєструватися") def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Електронна пошта вже зареєстрована') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError("Ім'я користувача вже використовується") class ChangePasswordForm(FlaskForm): password = PasswordField("Введіть новий пароль", validators=[DataRequired("Це поле є обов'язковим"), Length(min=4, max=10)]) repassword = PasswordField("Введіть новий пароль ще раз", validators=[DataRequired("Це поле є обов'язковим"), Length(min=4, max=10)]) submit = SubmitField("Змінити") class AddTodoItemForm(FlaskForm): title = StringField("Введіть завдання тут", validators=[DataRequired("Це поле є обов'язковим")]) description = StringField("Введіть опис тут", validators=[DataRequired("Це поле є обов'язковим")]) submit = SubmitField("Зберегти") class RegistrationForm(FlaskForm): username = StringField("Ім'я користувача", validators=[DataRequired("Це поле обов'язкове"), Length(min=4, max=10)]) email = EmailField("Електронна пошта", validators=[DataRequired("Це поле обов'язкове"), Email("Будь ласка, введіть свою електронну адресу")]) password = PasswordField("Пароль", validators=[DataRequired("Це поле обов'язкове"), Length(min=6)]) confirmPassword = PasswordField("Підтвердити пароль", validators=[DataRequired("Це поле обов'язкове"), EqualTo("password", "Паролі не збігаються")]) submit = SubmitField("Зареєструватися")
import { ICar, IWinner } from '../interfaces/Models'; const flagStat = require('../../media/flag16.gif'); const flagAnim = require('../../media/flag18.gif'); const SmokeBack = require('../../media/smoke10.gif'); const SmokeAbove = require('../../media/smoke6.gif'); const BoomAbove = require('../../media/boom2.gif'); const CarSVG = require('../../media/car.svg'); type AttrList = { [k: string]: string }; type ClassList = string[]; export default class HtmlBuilder { messageCounter = 1; private timerId = setTimeout(() => 1, 0); public timerResult = ''; public init(): void { this.buildPage('root'); } public createElement(tag: string, classes: ClassList = [], attrs: AttrList = {}, ctx = ''): HTMLElement { const elem = document.createElement(tag); if (classes.length > 0) { for (let i = 0; i < classes.length; i += 1) { elem.classList.add(classes[i]); } } if (Object.keys(attrs).length > 0) { for (let i = 0; i < Object.keys(attrs).length; i += 1) { elem.setAttribute(Object.keys(attrs)[i], attrs[Object.keys(attrs)[i]]); } } if (ctx !== '') elem.innerHTML = ctx; return elem; } public buildPage(id: string): void | never { const rootBody: HTMLElement | null = document.getElementById(id); if (!rootBody) throw new Error(`Something wrong with #${id}`); const nav = this.createElement('nav'); const garageBtn = this.createElement('button', ['active'], { id: 'garage-btn' }, 'Garage'); const winBtn2 = this.createElement('button', [], { id: 'winners-btn' }, 'Winners'); nav.append(garageBtn, winBtn2); rootBody.append(nav); const garage = this.createElement('article', ['garage'], { id: 'garage' }); const winners = this.createElement('article', ['winners', 'hidden'], { id: 'winners' }); const messages = this.createElement('article', ['messages'], { id: 'messages' }); const middleMsg = this.createElement('article', ['middle-msg', 'hidden'], { id: 'middle-msg' }); const p = this.createElement('p', [], { id: 'middle-msg-txt' }); middleMsg.append(p); const middleMsg2 = this.createElement('article', ['middle-msg2', 'hidden'], { id: 'middle-msg2' }); const p2 = this.createElement('p', [], { id: 'middle-msg-txt2' }); middleMsg2.append(p2); rootBody.append(garage, winners, messages, middleMsg, middleMsg2); this.buildGarage('garage'); this.buildWinners('winners'); } public buildGarage(id: string): void | never { const garage: HTMLElement | null = document.getElementById(id); if (!garage) throw new Error(`Something wrong with #${id}`); const garageTopic = this.createElement('h2', [], {}, 'Garage: <span id="garage-total">0</span> cars'); const pages = this.createElement('div', ['garage__pages']); const prevBtn = this.createElement('button', [], { id: 'garage-page-prev-btn' }, '&lt;'); const pageNum = this.createElement('p', [], {}, 'Page: <span id="garage-page-cur">1</span> of <span id="garage-page-total">1</span>'); const nextBtn = this.createElement('button', [], { id: 'garage-page-next-btn' }, '&gt;'); pages.append(prevBtn, pageNum, nextBtn); const create = this.createElement('div', ['garage__create-control']); const createcontainer = this.createElement('div'); const createTxt = this.createElement('input', [], { type: 'text', id: 'garage-create-txt', placeholder: 'Car name...' }); const createColor = this.createElement('input', [], { type: 'color', id: 'garage-create-color', value: '#ffffff' }); const createBtn = this.createElement('button', [], { id: 'garage-create-btn', disabled: 'true' }, 'Create'); createcontainer.append(createTxt, createColor, createBtn); create.append(createcontainer); const update = this.createElement('div', ['garage__update-control']); const updateContainer = this.createElement('div'); const updateTxt = this.createElement('input', [], { type: 'text', id: 'garage-update-txt', placeholder: 'Car for update...' }); const updateColor = this.createElement('input', [], { type: 'color', id: 'garage-update-color', value: '#ffffff' }); const updateId = this.createElement('input', [], { type: 'hidden', id: 'garage-update-id' }); const updateBtn = this.createElement('button', [], { id: 'garage-update-btn', disabled: 'true' }, 'Update'); updateContainer.append(updateTxt, updateColor, updateId, updateBtn); update.append(updateContainer); const race = this.createElement('div', ['garage__race-control']); const raceStart = this.createElement('button', [], { id: 'garage-start-btn' }, 'RACE'); const raceStop = this.createElement('button', [], { id: 'garage-stop-btn' }, 'RESET'); const raceGen = this.createElement('button', [], { id: 'garage-generate-btn' }, '+100 Cars'); race.append(raceStart, raceStop, raceGen); const timer = this.createElement('div', ['garage__race-timer']); const digits = this.createElement('h2', ['garage__timer', 'x-sign'], { id: 'timer-msec' }, '0.000'); timer.append(digits); const list = this.createElement('div', [], { id: 'garage-list' }); garage.append(garageTopic, pages, create, update, race, timer, list); } public buildWinners(id: string): void | never { const winners: HTMLElement | null = document.getElementById(id); if (!winners) throw new Error(`Something wrong with #${id}`); const winTopic = this.createElement('h2', [], {}, 'Winners: <span id="winners-total">0</span> crews'); const winPages = this.createElement('div', ['winners__pages']); const prevBtn = this.createElement('button', [], { id: 'winners-page-prev-btn' }, '&lt;'); const pageNum = this.createElement('p', [], {}, 'Page: <span id="winners-page-cur">1</span> of <span id="winners-page-total">1</span>'); const nextBtn = this.createElement('button', [], { id: 'winners-page-next-btn' }, '&gt;'); winPages.append(prevBtn, pageNum, nextBtn); const table = this.createElement('table', ['winners__table']); const tableHead = this.createElement('thead', ['winners__table-head']); const tableHeadTr = this.createElement('tr'); const tableHeadThId = this.createElement('th'); tableHeadThId.append(this.createElement('button', [], { id: 'sort-num' }, '№')); const tableHeadThCar = this.createElement('th'); tableHeadThCar.append(this.createElement('button', [], { id: 'sort-car', disabled: 'true' }, 'Car')); const tableHeadThName = this.createElement('th'); tableHeadThName.append(this.createElement('button', [], { id: 'sort-name', disabled: 'true' }, 'Name')); const tableHeadThWin = this.createElement('th'); tableHeadThWin.append(this.createElement('button', [], { id: 'sort-win' }, 'Wins')); const tableHeadThTime = this.createElement('th'); tableHeadThTime.append(this.createElement('button', [], { id: 'sort-time' }, 'Best time')); tableHeadTr.append( tableHeadThId, tableHeadThCar, tableHeadThName, tableHeadThWin, tableHeadThTime, ); tableHead.append(tableHeadTr); const tableBody = this.createElement('tbody', ['winners__table-body'], { id: 'winner-list' }); table.append(tableHead, tableBody); winners.append(winTopic, winPages, table); } public buildCarList(d: ICar[] |Response): void | never { const garageList: HTMLElement | null = document.getElementById('garage-list'); if (!garageList) throw new Error('Something wrong with #garage-list'); garageList.innerHTML = ''; const data = d as ICar[]; for (let i = 0; i < data.length; i += 1) { const carBlock = this.createElement('div', ['garage__car-block'], { 'data-id': String(data[i].id) }); const control = this.createElement('div', ['garage__car-block-control']); const name = this.createElement('p', ['garage__car-name'], { 'data-id': String(data[i].id) }, data[i].name); const carControl = this.createElement('div', ['garage__car-control']); const select = this.createElement('button', ['garage__select-car-btn'], { 'data-id': String(data[i].id) }, 'Select'); const remove = this.createElement('button', ['garage__remove-car-btn'], { 'data-id': String(data[i].id) }, 'Remove'); carControl.append(select, remove); const driveControl = this.createElement('div', ['garage__car-drive-control']); const start = this.createElement('button', ['garage__start-car-btn'], { 'data-id': String(data[i].id) }, 'Go'); const stop = this.createElement('button', ['garage__stop-car-btn'], { 'data-id': String(data[i].id), disabled: 'true' }, 'X'); driveControl.append(start, stop); control.append(name, carControl, driveControl); const drive = this.createElement('div', ['garage__car-drive']); const road = this.createElement('div', ['garage__road']); const carContainer = this.createElement('div', ['garage__car-container']); const num = this.createElement('p', ['garage__car-number'], {}, String(data[i].id)); const car = this.buildCar(data[i].color); const phrase = this.createElement('div', ['garage__car-phrase']); const smokeB = this.createElement('img', ['garage__smoke_back'], { alt: 'exhaust', src: SmokeBack }); const smokeA = this.createElement('img', ['garage__smoke_above'], { alt: 'smoke', src: SmokeAbove }); const boom = this.createElement('img', ['garage__boom_above'], { alt: 'boom', src: BoomAbove }); if (car) carContainer.append(car); carContainer.append(num, smokeB, smokeA, boom, phrase); const surf = this.createElement('div', ['garage__surface']); const flag = this.createElement('img', ['garage__flag'], { alt: 'flag', src: flagStat }); road.append(carContainer, surf, flag); drive.append(road); carBlock.append(control, drive); garageList.append(carBlock); } } public buildCar(color: string): SVGSVGElement | null { const car = document.createElement('div'); car.innerHTML = CarSVG; const svg = car.querySelector('svg'); if (svg) { svg.setAttribute('width', '95'); svg.setAttribute('height', '45'); } const g = car.querySelector('svg g'); if (g) { g.setAttribute('fill', color); } const wheel1 = car.querySelector('path:nth-child(2)'); const wheel2 = car.querySelector('path:nth-child(3)'); if (wheel1 && wheel2) { wheel1.setAttribute('fill', 'grey'); wheel2.setAttribute('fill', 'grey'); } const carEl = car.querySelector('svg'); return carEl; } public buildWinnerList(dataW: Response | IWinner[], dataC: Response | ICar[]): void | never { const dataWinners = dataW as IWinner[]; const dataCars = dataC as ICar[]; const tableBody: HTMLElement | null = document.getElementById('winner-list'); if (!tableBody) throw new Error('Something wrong with #winner-list'); tableBody.innerHTML = ''; let carModel: ICar = { id: 0, name: '', color: '' }; for (let i = 0; i < dataWinners.length; i += 1) { for (let z = 0; z < dataCars.length; z += 1) { if (dataCars[z].id === dataWinners[i].id) { carModel = dataCars[z]; break; } } if (carModel.id) { const tr = this.createElement('tr'); const tdId = this.createElement('td', [], {}, String(dataWinners[i].id)); const tdCar = this.createElement('td'); const carCont = this.createElement('div', ['winners__car-container']); const carEl = this.buildCar(carModel.color); if (carEl) carCont.append(carEl); tdCar.append(carCont); const tdName = this.createElement('td', [], {}, carModel.name); const tdWin = this.createElement('td', [], {}, String(dataWinners[i].wins)); const tdTime = this.createElement('td', [], {}, String(dataWinners[i].time.toFixed(3))); tr.append(tdId, tdCar, tdName, tdWin, tdTime); tableBody.append(tr); carModel.id = 0; } } } public addMessage(text: string, type: 'warning' | 'error' | 'info'): void { const messageList: HTMLElement | null = document.getElementById('messages'); if (!messageList) throw new Error('Something wrong with #messages'); const container = this.createElement('div', [type], { 'data-id': String(this.messageCounter) }); const p = this.createElement('p', [], {}, text); container.append(p); messageList.append(container); this.deleteMessage(this.messageCounter); this.messageCounter += 1; } public changeFlag(id: number, act: 'stat' | 'anim'): void { const flagEl: HTMLElement | null = document.querySelector(`.garage__car-block[data-id="${id}"] .garage__flag`); if (flagEl) { if (act === 'stat') flagEl.setAttribute('src', flagStat); if (act === 'anim') flagEl.setAttribute('src', flagAnim); } } public deleteMessage(index: number): void { const message: HTMLElement | null = document.querySelector(`.messages div[data-id="${index}"]`); setTimeout(() => { if (message) { message.style.opacity = '0'; } }, 4500); setTimeout(() => { if (message) { message.style.height = '0px'; } }, 4700); setTimeout(() => { if (message) { message.remove(); } }, 5000); } public carPhrase(id: number, txt: string, delay = 3000): void { const car: HTMLElement | null = document.querySelector(`.garage__car-block[data-id="${id}"] .garage__car-phrase`); if (car) { const p = this.createElement('p', [], {}, txt); p.style.transition = `all ${delay}ms`; car.append(p); setTimeout(() => { p.style.margin = '0 30px 15px 0'; p.style.transform = 'rotate(-3deg)'; }, 100); setTimeout(() => { car.firstChild?.remove(); }, delay); } } public carSmokeBack(id: number, act: 'start' | 'stop'): void { const carEl: HTMLElement | null = document.querySelector(`.garage__car-block[data-id="${id}"] .garage__smoke_back`); if (carEl) { if (act === 'start') carEl.style.opacity = '0.2'; if (act === 'stop') carEl.style.opacity = '0'; } } public carSmokeAbove(id: number, act: 'start' | 'stop'): void { const carEl: HTMLElement | null = document.querySelector(`.garage__car-block[data-id="${id}"] .garage__smoke_above`); if (carEl) { if (act === 'start') carEl.style.opacity = '.5'; if (act === 'stop') carEl.style.opacity = '0'; } } public boomAbove(id: number): void { const carEl: HTMLElement | null = document.querySelector(`.garage__car-block[data-id="${id}"] .garage__boom_above`); if (carEl) { carEl.style.opacity = '1'; carEl.setAttribute('src', carEl.getAttribute('src') ?? ''); setTimeout(() => { carEl.style.opacity = '0'; }, 1000); } } public middleMsg(txt: string, num = 1): void { let msg: HTMLElement | null = document.getElementById('middle-msg'); let msgEl: HTMLElement | null = document.getElementById('middle-msg-txt'); if (num === 2) { msg = document.getElementById('middle-msg2'); msgEl = document.getElementById('middle-msg-txt2'); } setTimeout(() => { if (msgEl && msg) { msgEl.innerHTML = txt; msg.classList.remove('hidden'); msgEl.style.opacity = '1'; if (num === 3) msgEl.style.fontSize = '22px'; } }, 0); setTimeout(() => { if (msgEl && msg) { msgEl.style.opacity = '0'; if (num === 1) { msgEl.style.transform = 'rotate(25deg)'; msgEl.style.fontSize = '150px'; } else if (num === 2) { msgEl.style.transform = 'rotate(-25deg)'; msgEl.style.fontSize = '300px'; } else { msgEl.style.transform = 'rotate(-10deg)'; msgEl.style.fontSize = '100px'; } } }, (num === 3) ? 5500 : 1500); setTimeout(() => { if (msgEl && msg) { msgEl.style.transform = ''; msg.classList.add('hidden'); msgEl.style.fontSize = ''; if (num === 3) msgEl.style.fontSize = ''; } }, (num === 3) ? 6000 : 2000); } public disableCarControlBtn(id: number, arr: string[] = []): void { const car: HTMLElement | null = document.querySelector(`.garage__car-block[data-id="${id}"]`); if (car) { const removeBtn = car.querySelector('.garage__remove-car-btn') as HTMLButtonElement | null; const selectBtn = car.querySelector('.garage__select-car-btn') as HTMLButtonElement | null; const startBtn = car.querySelector('.garage__start-car-btn') as HTMLButtonElement | null; const stopBtn = car.querySelector('.garage__stop-car-btn') as HTMLButtonElement | null; if (arr.includes('start') && startBtn) startBtn.disabled = true; if (arr.includes('stop') && stopBtn) stopBtn.disabled = true; if (arr.includes('select') && selectBtn) selectBtn.disabled = true; if (arr.includes('remove') && removeBtn) removeBtn.disabled = true; if (arr.length === 0 && removeBtn && selectBtn && startBtn && stopBtn) { startBtn.disabled = false; stopBtn.disabled = false; selectBtn.disabled = false; removeBtn.disabled = false; } } } public disableRaceControlBtn(arr: string[] = []): void { const startBtn = document.getElementById('garage-start-btn') as HTMLButtonElement | null; const stopBtn = document.getElementById('garage-stop-btn') as HTMLButtonElement | null; const genBtn = document.getElementById('garage-generate-btn') as HTMLButtonElement | null; if (arr.length === 0 && startBtn && stopBtn && genBtn) { startBtn.disabled = false; stopBtn.disabled = false; genBtn.disabled = false; } if (startBtn && arr.includes('start')) startBtn.disabled = true; if (stopBtn && arr.includes('stop')) stopBtn.disabled = true; if (genBtn && arr.includes('generate')) genBtn.disabled = true; } public timerStart(): void { if (this.timerId) clearTimeout(this.timerId); const startTime = Date.now(); const msec = document.getElementById('timer-msec'); if (!msec) return; this.timerId = setInterval(() => { const elapsedTime = Date.now() - startTime; msec.innerHTML = (elapsedTime / 1000).toFixed(3); this.timerResult = String((elapsedTime / 1000).toFixed(3)); }, 37); } public timerReset(): void { const msec = document.getElementById('timer-msec'); if (msec) msec.innerHTML = '0.000'; this.timerResult = '0.000'; } public timerStop(): void { if (this.timerId) clearTimeout(this.timerId); } }
import ProductModal from './ProductModal.vue'; export default { props: { id: { type: String }, param: Object, fnConfirm: { type: Function }, }, mounted() { //this.Options = []; //this.orderList = []; //주문 번호 관련 //this.orderNumber = ""; //선택했을 때 해당 주문번호 받아오기 //his.chkGoodsList = []; //선택할 상품들 리스트 if(this.$route.name === 'inquiry' || this.$route.name === 'cs-main' || this.$route.name === 'cs-cs-find-result'){ this.$util.debug(this.$route.name + " 진입......."); this.InquiryCommon(); if(!this.$util.isEmpty(this.param)){ this.orderNumber = this.param.orderno; this.chkGoodsList = this.param.goodslist; } } if(this.$route.name === 'detail-inquiry'){ this.$util.debug(this.$route.name + " 진입......."); this.InquiryCommon(); this.text = "1:1문의 수정"; this.idx = this.$route.params.idx; var iqParams = { idx: this.idx, } this.onInquiry(iqParams); } if(this.$route.name === 'detail-qna'){ this.$util.debug(this.$route.name + " 진입......."); this.qnaCommon(); this.text = "상품 Q&A 수정"; this.idx = this.$route.params.idx; var qnaParams = { idx: this.idx, } this.onQna(qnaParams); } }, data() { return { idx: 0, //수정 진입 시 전달할 idx text: "1:1문의 등록", //문의 유형이 수정 or 등록 placeHolder: "유형을 선택해주세요.", SelectType: "", Options: [], content: "", files:[], deletefilelist: [], orderList: [], //주문 번호 관련 orderNumber: "", //선택했을 때 해당 주문번호 받아오기 chkGoodsList: [], //선택할 상품들 리스트 qnalist: [], qnaPopThumbnailData: {}, skey:0, modalInfo: { comp: null, param: null, fnConfirm: () => {}, fnCancel: () => {}, }, }; }, methods: { /********************************* * 1:1 문의유형 로드 *********************************/ InquiryCommon() { //공통코드 목록 불러오기 let cmclassArr = ['INQUIRYTYPE']; //* this.$http.post('/common/code/map/list', {cmclass : cmclassArr, isloading: false}).then(result =>{ for(var i=0; i<result.data.inquirytype.length; i++){ var temp = {}; temp.label = result.data.inquirytype[i].codename; temp.value = result.data.inquirytype[i].cmcode; //문의유형 화면쪽 this.Options.push(temp); } }) }, /********************************* * Q&A 문의유형 로드 *********************************/ qnaCommon() { //공통코드 목록 불러오기 let cmclassArr = ['QNATYPE']; //* this.$http.post('/common/code/map/list', {cmclass : cmclassArr, isloading: false}).then(result =>{ for(var i=0; i<result.data.qnatype.length; i++){ var temp = {}; temp.label = result.data.qnatype[i].codename; temp.value = result.data.qnatype[i].cmcode; //문의유형 화면쪽 this.Options.push(temp); } }) }, /********************************* * 1:1 문의 상세 진입 *********************************/ onInquiry(param) { this.$http.post('/cscenter/inquirydtl',param).then(result => { if(result.statusCode == 200){ this.orderList = result.data.list.goodslist; this.files = result.data.list.files; this.placeHolder = result.data.list.inquirytypename; this.SelectType = result.data.list.inquirytype; //this.content = result.data.list.content; this.content = result.data.list.content.replace(/(<br>|<br\/>|<br \/>)/g, '\r\n'); this.$refs.imageupload.bindFile(this.files); if(!this.$util.isEmpty(result.data.list.goodslist)){ this.chkGoodsList = result.data.list.goodslist; this.orderNumber = result.data.list.goodslist[0].ordno; } if(!this.$util.isEmpty(this.param)){ this.$util.debug(this.param); this.orderNumber = this.param.ordernumber; this.chkGoodsList = this.param.orderlist; } this.$nextTick(()=>{ this.$util.debug(this.$refs); this.$refs.imageupload.bindFile(this.files); }) } }) }, /********************************* * 상품 Q&A 상세 진입 *********************************/ onQna(param) { this.$http.post('/cscenter/qnadetail',param).then(result => { if(result.statusCode == 200){ this.qnalist = result.data.list; this.files = result.data.list.files; this.placeHolder = result.data.list.qnatypename; this.SelectType = result.data.list.qnatype; this.content = result.data.list.content; this.content = this.content.replaceAll("<br/>","\n"); this.qnaPopThumbnailData.fullpath = result.data.list.fullpath; } }) }, OptionCheck(val) { this.SelectType = val; }, /************************** * 부모에서 전달받은 파일목록 매핑 ****************************/ bindFile(files){ this.$util.debug("bindFile...."); this.$util.debug(files); //저장된 파일리스트에 id값 부여 for (let index = 0; index < files.length; index++) { files[index].id = 'files'+index; files[index].url = files[index].fullpath; } this.filelist = files; }, /********************************* * 첨부파일 변경시 처리 *********************************/ changeFiles(files, deletelist) { this.files = files; this.deletefilelist = deletelist; }, handleSelect() { }, //모달 openProductModal() { this.$util.debug("openProductModal ....."); //선택된 체크박스 let param ={ chkordno: this.orderNumber, chkgoodslist: this.chkGoodsList, }; this.modalInfo.comp = ProductModal; this.modalInfo.id = 'ProductModal'; this.modalInfo.param = param; this.modalInfo.fnConfirm=(result)=>{ this.$util.debug("ProductModal Close ...."); this.$util.debug("ProductModal Close result data >>>>>>>>>>>>>>>>"); this.$util.debug(result); this.orderNumber = result.orderno; this.chkGoodsList = result.goodslist; } this.$nextTick(function () { this.$bvModal.show("ProductModal"); }); // this.$eventBus.$emit('showModal', ProductModal, 'ProductModal', param,(param)=>{ // }); }, closeModal() { this.$util.debug("모달닫기"); this.$bvModal.hide("WriteModal"); }, /************************** * 1:1 문의 등록 / 수정 ****************************/ registerInquiry() { this.$util.debug("registerInquiry...."); if(this.$util.isNull(this.SelectType)){ this.$eventBus.$emit('alert', '알림', "문의유형을 선택해주세요."); return; } if(this.$util.isNull(this.content)){ this.$eventBus.$emit('alert', '알림', "내용을 입력해주세요."); return; } if(this.content.length > 500){ this.$eventBus.$emit('alert', '알림', "내용은 최대 500자까지 입력가능합니다."); return; } this.$refs.imageupload.emitFileList(); var regParams = { idx: this.idx, files: this.files, deletefilelist: this.deletefilelist, content: this.content, type: this.SelectType, //주문상품선택한 param ordno: this.orderNumber, goodslist: this.chkGoodsList, } this.$util.debug("registerInquiry file list >>>>>>>>>>>>>>>>>>>>>>>>>>>"); this.$util.debug(JSON.stringify(this.file)); if(this.idx == 0){ //등록 this.inquiryRegister(regParams); }else{ //수정 this.inquiryRevise(regParams); } }, /************************** * 1:1 문의 저장 ****************************/ inquiryRegister(param) { this.$http.post('/cscenter/registerinq', param).then(result => { if (result.statusCode == 200) { this.$eventBus.$emit('alert', '알림', "등록이 완료되었습니다."); this.$router.push({name: 'inquiry'}); this.fnConfirm(param); this.closeModal(); } }) }, /************************** * 1:1 문의 수정 ****************************/ inquiryRevise(param) { this.$http.post('/cscenter/reviseinq', param).then(result => { if (result.statusCode == 200) { this.$eventBus.$emit('alert', '알림', "수정이 완료되었습니다."); this.$router.push({name: 'detail-inquiry'}); this.fnConfirm(param); this.closeModal(); } }) }, /************************** * 상품 문의 수정 ****************************/ reviseQna(){ this.$util.debug("reviseQna...."); if(this.$util.isNull(this.SelectType)){ this.$eventBus.$emit('alert', '알림', "문의유형을 선택해주세요."); return; } if(this.$util.isNull(this.content)){ this.$eventBus.$emit('alert', '알림', "내용을 입력해주세요."); return; } if(this.content.length > 500){ this.$eventBus.$emit('alert', '알림', "내용은 최대 500자까지 입력가능합니다."); return; } var param = { idx: this.idx, content: this.content, type: this.SelectType, } this.$http.post('/cscenter/reviseqna', param).then(result => { if (result.statusCode == 200) { this.$eventBus.$emit('alert', '알림', "수정이 완료되었습니다."); this.$router.replace({name: 'qna'}); this.closeModal(); } }) }, }, watch: { } };
vim.o.number = true vim.o.signcolumn = 'yes' vim.o.tabstop = 4 vim.o.shiftwidth = 4 vim.o.updatetime = 300 vim.o.termguicolors = true vim.g.loaded_netrw = 1 vim.g.loaded_netrwPlugin = 1 vim.opt.termguicolors = true vim.cmd [[colorscheme tokyonight]] -- key mappings -- vim.keymap.set('n', 'vw', 'viw', { noremap = true }) -- key mappings -- -- short plugin configs -- require('nvim-autopairs').setup({ disable_filetype = { "TelescopePrompt" , "vim" }, }) local cmp_autopairs = require('nvim-autopairs.completion.cmp') local cmp = require('cmp') cmp.event:on( 'confirm_done', cmp_autopairs.on_confirm_done() ) require'alpha'.setup(require'alpha.themes.startify'.config) require("nvim-surround").setup() require("conform").setup({ formatters_by_ft = { python = { "ruff_organize_imports", "ruff_format", "ruff_fix" }, javascript = { { "prettierd", "prettier" } }, css = { { "prettierd", "prettier" } }, html = { { "prettierd", "prettier" } }, astro = { { "prettierd", "prettier" } }, nix = {"alejandra "}, cpp = {"clang-format"} , ["*"] = { "codespell" }, }, format_on_save = { lsp_fallback = true, timeout_ms = 500, }, }) require("nvim-tree").setup({ sort = { sorter = "case_sensitive", }, view = { width = 30, }, renderer = { group_empty = true, }, filters = { dotfiles = true, }, }) local api = require "nvim-tree.api" vim.keymap.set('n', 'tr', api.tree.open, {}) vim.keymap.set('n', 'ty', api.tree.close, {}) local on_attach = function(_, bufnr) local bufmap = function(keys, func) vim.keymap.set('n', keys, func, { buffer = bufnr }) end bufmap('<leader>r', vim.lsp.buf.rename) bufmap('<leader>a', vim.lsp.buf.code_action) bufmap('gd', vim.lsp.buf.definition) bufmap('gD', vim.lsp.buf.declaration) bufmap('gI', vim.lsp.buf.implementation) bufmap('<leader>D', vim.lsp.buf.type_definition) bufmap('gr', require('telescope.builtin').lsp_references) bufmap('<leader>s', require('telescope.builtin').lsp_document_symbols) bufmap('<leader>S', require('telescope.builtin').lsp_dynamic_workspace_symbols) bufmap('K', vim.lsp.buf.hover) vim.api.nvim_buf_create_user_command(bufnr, 'Format', function(_) vim.lsp.buf.format() end, {}) end local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').default_capabilities(capabilities) require('neodev').setup() require('lspconfig').nil_ls.setup { on_attach = on_attach, capabilities = capabilities, } --- Make sure to install the lsp's via a flake for dev env --- require('lspconfig').pyright.setup{ on_attach = on_attach, capabilities = capabilities, } require('lspconfig').svelte.setup{ on_attach = on_attach, capabilities = capabilities, } require('lspconfig').html.setup { on_attach = on_attach, capabilities = capabilities, } require('lspconfig').tsserver.setup { on_attach = on_attach, capabilities = capabilities, single_file_support = true, } require'lspconfig'.clangd.setup{ on_attach = on_attach, capabilities = capabilities, } require'lspconfig'.astro.setup{ on_attach = on_attach, capabilities = capabilities, } local cmp = require('cmp') local luasnip = require('luasnip') require('luasnip.loaders.from_vscode').lazy_load() luasnip.config.setup {} cmp.setup { snippet = { expand = function(args) luasnip.lsp_expand(args.body) end, }, mapping = cmp.mapping.preset.insert { ['<C-n>'] = cmp.mapping.select_next_item(), ['<C-p>'] = cmp.mapping.select_prev_item(), ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete {}, ['<CR>'] = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Replace, select = true, }, ['<Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expand_or_locally_jumpable() then luasnip.expand_or_jump() else fallback() end end, { 'i', 's' }), ['<S-Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.locally_jumpable(-1) then luasnip.jump(-1) else fallback() end end, { 'i', 's' }), }, sources = { { name = 'nvim_lsp' }, { name = 'luasnip' }, { name = 'path' }, { name = 'git' }, { name = 'cmdline' }, }, } local builtin = require('telescope.builtin') vim.keymap.set('n', 'ff', builtin.find_files, {}) vim.keymap.set('n', 'fg', builtin.live_grep, {}) require('nvim-treesitter.configs').setup { ensure_installed = {}, auto_install = false, highlight = { enable = true }, indent = { enable = true }, }
// File : EPSSetCmykColor.java // Purpose : class representing setcmykcolor operator // Creation Date : 1st June 2008 // Author : Nicola L.C. Talbot // http://www.dickimaw-books.com/ /* Copyright (C) 2006 Nicola L.C. Talbot This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package com.dickimawbooks.jdr.io.eps.operators; import java.io.*; import java.awt.geom.*; import com.dickimawbooks.jdr.*; import com.dickimawbooks.jdr.io.eps.*; import com.dickimawbooks.jdr.io.EPS; import com.dickimawbooks.jdr.exceptions.*; /** * Object representing setcmykcolor operator. * @author Nicola L C Talbot */ public class EPSSetCmykColor extends EPSOperator { public EPSSetCmykColor() { super("setcmykcolor"); } public void execute(EPSStack stack, EPS eps) throws InvalidFormatException, NoninvertibleTransformException, IOException { double black = stack.popDouble(); double yellow = stack.popDouble(); double magenta = stack.popDouble(); double cyan = stack.popDouble(); if (black > 1) { black = 1; } else if (black < 0) { black = 0; } if (yellow > 1) { yellow = 1; } else if (yellow < 0) { yellow = 0; } if (magenta > 1) { magenta = 1; } else if (magenta < 0) { magenta = 0; } if (cyan > 1) { cyan = 1; } else if (cyan < 0) { cyan = 0; } eps.getCurrentGraphicsState().setPaint( new JDRColorCMYK(eps.getCanvasGraphics(), cyan, magenta, yellow, black)); } }
import SwiftUI struct ComposeView: View{ @EnvironmentObject var store: MemoStore var memo:Memo?=nil @Environment(\.dismiss) var dismiss @State private var content: String = "" var body: some View{ NavigationView{ VStack{ TextEditor(text: $content) .padding() .onAppear{ if let memo = memo { content = memo.content } } } .navigationTitle(memo != nil ? "메모편집" : "새 메모") .navigationBarTitleDisplayMode(.inline) .toolbar{ ToolbarItemGroup(placement:.navigationBarLeading) { Button{ dismiss() }label:{ Text("취소") } } ToolbarItemGroup(placement:.navigationBarTrailing){ Button{ if let memo = memo{ store.update(memo: memo, content: content) }else{ store.insert(memo: content) } dismiss() }label:{ Text("저장") } } } } } } struct ComposeView_Previews:PreviewProvider{ static var previews:some View{ ComposeView() .environmentObject(MemoStore()) } }
import React from "react"; import { useEffect } from "react"; import axios from "axios"; import { COLLECTION_LINK } from "../Data"; import ProductCard from "./ProductCard"; const ProductDetails = (props) => { useEffect(() => { axios .get(`${COLLECTION_LINK}products`) .then((resonse) => { props.setProducts(resonse.data); }) .catch((err) => { console.log(err); }); }); const updateBalance = (id, price) => { axios .put(`${COLLECTION_LINK}updatebalance`, { id: id, balance: props.money - price, }) .then((resonse) => { props.setMoney((money) => money - price); }) .catch((err) => console.log(err)); }; const addBuyedItem = (product) => { axios .post(`${COLLECTION_LINK}addbuyedproduct`, { name: product.name, description: product.description, price: product.price, userId: props.id, }) .then((resonse) => { updateBalance(props.id, product.price); props.setBuyedItems((buyedItems) => [ { name: product.name, description: product.description, price: product.price, userId: props.id, }, ...buyedItems, ]); deleteProduct(product.id); }) .catch((err) => console.log(err)); }; const deleteProduct = (id) => { axios .delete(`${COLLECTION_LINK}deleteproduct/${id}`) .then((resonse) => { props.setProducts( props.products.filter((product) => { return product.id !== id; }) ); }) .catch((err) => console.log(err)); }; const showMsg = () => { props.setBg("from-red-400 to-red-600 shadow-xl shadow-red-500 "); props.setHasShown(true) setTimeout(() => { props.setBg("bg-green-400"); props.setHasShown(false); }, 2000); } const doTrasaction = (product) => { product.price <= props.money ? addBuyedItem(product) : showMsg(); } return ( <div className="p-3 flex flex-col gap-4 w-3/5 bg-indigo-300 rounded-md"> <div className="text-xl text-slate-200 font-semibold text-center bg-indigo-700 p-3 rounded-md"> Buy Items </div> {props.products.length !== 0 ? ( props.products.map((product, key) => { return <ProductCard key={key} text={"Buy now"} doTrasaction={doTrasaction} product={product} /> }) ) : ( <div className="text-slate-200 text-xl first-letter:text-red-600"> No Data </div> )} </div> ); }; export default ProductDetails;
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[allowOnlyAlphaSpace]', }) export class AtlpAllowOnlyAlphaSpaceDirective { // prettier-ignore regexStr = "^[a-zA-Z \b]+$"; @Input() isAlphaNumeric: boolean; constructor(private el: ElementRef) {} @HostListener('keypress', ['$event']) onKeyPress(event) { return new RegExp(this.regexStr).test(event.key); } @HostListener('paste', ['$event']) blockPaste(event: ClipboardEvent) { this.validateFields(event); } validateFields(event: ClipboardEvent) { event.preventDefault(); const pasteData = event.clipboardData .getData('text/plain') .replace(/[^a-zA-Z ]/g, ''); document.execCommand('insertHTML', false, pasteData); } }
# The frequency of the letters of the alphabet in English # https://www3.nd.edu/~busiforc/handouts/cryptography/letterfrequencies.html # Letter frequency # https://en.wikipedia.org/wiki/Letter_frequency from english_dictionary.scripts.read_pickle import get_dict english_dict = get_dict() # english_dict["xylophone"] # english_dict is a Python dictionary of English import random letters = "" centerLetter = "" score = 0 # define alphabet consonantsMoreFrequent = ["r", "n", "t", "l", "c", "d", "g", "p", "m", "h", "b"] consonantsLessFrequent = ["y", "g", "v", "k", "w", "z", "x", "j", "q"] vowels = ["a", "e", "i", "o", "u"] # set letters def setLetters(): selectedConsonantsMF = random.sample(consonantsMoreFrequent, 4) selectedConsonantsLF = random.sample(consonantsLessFrequent, 1) selectedVowels = random.sample(vowels, 2) letters = selectedConsonantsMF + selectedConsonantsLF + selectedVowels print("letters: ", letters) centerLetter = random.sample(letters, 1) print("center letter: ", centerLetter) # letters = ["g", "i", "n", "z", "l", "d", "a"] # centerLetter = "a" # create guess list guessList = [] def showLetters(): theLetters = ', '.join(letters) print("letters: ", theLetters) print("centerLetter: ", centerLetter) def usesAllLetters(guess): global score counter = 0 for letter in letters: if letter in guess: counter += 1 if counter == 7: score += 15 return "pangram!" else: score += len(guess) return len(guess) # get and check input def makeGuess(): global score guess = input("Enter word guess here: ") if len(guess) < 4: print("Too short!") makeGuess() elif centerLetter not in guess: print("Missing center letter!") makeGuess() elif guess in guessList: print("Already found!") makeGuess() else: if lookupWord(guess) == True: guessList.append(guess) print(guessList) print(usesAllLetters(guess)) print("points!") print(f"Score: {score}") else: print("word not found. no points!") makeGuess() # look up guess in dictionary def lookupWord(word): try: meaning = english_dict[word] print(meaning) if meaning: return True else: return False except Exception as e: # print(f"Error: {e}") return False # run functions setLetters() # showLetters() makeGuess() # try this instead of PyDictionary # install first: pip install nltk # import nltk # from nltk.corpus import words # nltk.download('words') # def word_exists(word): # word = word.lower() # return word in words.words() # word_to_check = "hello" # if word_exists(word_to_check): # print(f"'{word_to_check}' exists in the English language.") # else: # print(f"'{word_to_check}' does not exist in the English language.")
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/dms/model/ReleaseStatusValues.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace DatabaseMigrationService { namespace Model { namespace ReleaseStatusValuesMapper { static const int beta_HASH = HashingUtils::HashString("beta"); ReleaseStatusValues GetReleaseStatusValuesForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == beta_HASH) { return ReleaseStatusValues::beta; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ReleaseStatusValues>(hashCode); } return ReleaseStatusValues::NOT_SET; } Aws::String GetNameForReleaseStatusValues(ReleaseStatusValues enumValue) { switch(enumValue) { case ReleaseStatusValues::beta: return "beta"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace ReleaseStatusValuesMapper } // namespace Model } // namespace DatabaseMigrationService } // namespace Aws
from abc import ABC, abstractmethod # Implementor interface class DrawingAPI(ABC): @abstractmethod def draw_circle(self, x, y, radius): pass # Concrete Implementor 1 class DrawingAPI1(DrawingAPI): def draw_circle(self, x, y, radius): print(f"API1.circle at {x}:{y} radius {radius}") # Concrete Implementor 2 class DrawingAPI2(DrawingAPI): def draw_circle(self, x, y, radius): print(f"API2.circle at {x}:{y} radius {radius}") # Abstraction class Shape(ABC): def __init__(self, drawing_api): self.drawing_api = drawing_api @abstractmethod def draw(self): pass # Refined Abstraction class CircleShape(Shape): def __init__(self, x, y, radius, drawing_api): super().__init__(drawing_api) self.x = x self.y = y self.radius = radius def draw(self): self.drawing_api.draw_circle(self.x, self.y, self.radius) # Client code if __name__ == "__main__": shapes = [ CircleShape(1, 2, 3, DrawingAPI1()), CircleShape(5, 7, 11, DrawingAPI2()) ] for shape in shapes: shape.draw()
import { ChangeEvent, FC, ReactNode, SyntheticEvent, useEffect, useState } from 'react'; import type { ControllerRenderProps } from 'react-hook-form'; import { Checkbox, Select, SelectProps } from 'antd'; import type { CheckboxChangeEvent } from 'antd/lib/checkbox'; import cx from 'classnames'; import { ALL_OPTIONS } from 'constant'; import IconDropdown from 'resources/svg/IconDropdown'; const { Option } = Select; type OptionType = { value: any; name: any; }; type ISelectInput = { field?: ControllerRenderProps<any, string>; options: OptionType[]; prefix?: ReactNode; className?: string; onChange?: (e: ChangeEvent<HTMLInputElement>) => void; optionsType?: 'checkbox'; enableAllOption?: boolean; optionsRenderProps?: (item: OptionType) => any; suffixIcon?: ReactNode; allOptionsText?: string; }; const SelectInput: FC<SelectProps<any, OptionType> & ISelectInput> = ({ field, options, prefix, className, onChange, optionsType, enableAllOption, optionsRenderProps, suffixIcon = <IconDropdown />, allOptionsText = 'common.all', ...props }) => { const [indeterminate, setIndeterminate] = useState(true); const [checkAll, setCheckAll] = useState(false); const { value } = field || {}; const optionsValue = enableAllOption && optionsType !== 'checkbox' && options.length > 1 ? [ { value: ALL_OPTIONS, name: allOptionsText, }, ].concat(options) : options; useEffect(() => { setIndeterminate(!!value && value.length > 0 && value.length < optionsValue.length); setCheckAll(!!value && value.length > 0 && value.length === optionsValue.length); }, [value]); const onCheckAllOptions = (event: CheckboxChangeEvent) => { const { checked } = event.target; let values = []; if (checked) { values = optionsValue.map((option) => option.value); } else { values = []; } setIndeterminate(false); setCheckAll(checked); onChangeSelect(values); }; const optionsSelectAllRender = () => { switch (optionsType) { case 'checkbox': { return ( <div className='search-form__all-options'> <Checkbox onChange={onCheckAllOptions} id={ALL_OPTIONS} indeterminate={indeterminate} checked={checkAll}> {allOptionsText} </Checkbox> </div> ); } default: { return null; } } }; const optionsRender = (item: OptionType) => { switch (optionsType) { case 'checkbox': { return ( <Checkbox id={item.value} checked={value && value.indexOf(item.value) >= 0}> <div onClick={onPreventMouseDown}> {optionsRenderProps && item?.value !== ALL_OPTIONS ? optionsRenderProps(item) : item.name} </div> </Checkbox> ); } default: { return optionsRenderProps && item?.value !== ALL_OPTIONS ? optionsRenderProps(item) : item.name; } } }; const onPreventMouseDown = (event: SyntheticEvent<HTMLDivElement>) => { event.stopPropagation(); }; const onChangeSelect = (val: any) => { field?.onChange(val); if (onChange) onChange(val); }; return ( <div className={cx('ant-select-wrapper', className)}> {prefix} <Select {...field} onChange={onChangeSelect} getPopupContainer={(trigger) => trigger.parentElement} notFoundContent={null} suffixIcon={suffixIcon} dropdownRender={(menu) => ( <> {enableAllOption && optionsValue.length > 1 && optionsSelectAllRender()} {menu} </> )} {...props} > {optionsValue.map((item) => ( <Option value={item.value} key={item.value} label={item.name}> {optionsRender(item)} </Option> ))} </Select> </div> ); }; export default SelectInput;
Some Recent Developments in Inference for Geostatistical Functional Data. Algunos desarrollos recientes en inferencia para datos funcionales geoestadsticos Colorado State University, Fort Collins, USA. Penn State University, State College, USA Abstract We review recent developments related to inference for functions defined at spatial locations. We also consider time series of functions defined at irregularly distributed spatial points or on a grid. We focus on kriging, estimation of the functional mean and principal components, and significance testing, giving special attention to testing spatio–temporal separability in the context of functional data. We also highlight some ideas related to extreme value theory for spatially indexed functional time series. Key words: Functional data; Spatial statistics. Resumen Revisamos desarrollos recientes relacionados con la inferencia de funciones definidas en locaciones espaciales. Tambin consideramos series de tiempo funcionales definidas en puntos espaciales irregularmente distribuidos en una cuadrcula. Nos centramos en el kriging, la estimacin de la media funcional y de los componentes principales, y en la prueba de significancia, dando especial atencin a pruebas de separabilidad de espacio-tiempo en el contexto de datos funcionales. Tambin destacamos algunas ideas relaciones con la teora de valores extremos para series de tiempo funcionales indexadas en el espacio. Palabras clave: datos funcionales; estadstica espacial. 1. Introduction The objective of this paper is to review some recent developments in inference for geostatistical functional data. We thus consider data which are a collection of curves at spatial locations {sk }. Each t 7→ X(sk ; t) is a curve. For example, the {sk } can be locations of meteorological stations, and X(sk , t) can be some measurement, for example temperature or wind speed at time t. A sample of geostatistical spatial data has the form {X(sk , t), sk ∈ S, t ∈ T , k = 1, 2, . . . , N } . The spatial domain S is typically a subset of the two–dimensional plane or sphere. The points sk at which observations are available are generally scattered over S in some irregular manner. In some applications, e.g. satellite pictures, these points form a grid, but the methodology we discuss in this paper has been motivated by and generally applies to irregularly spaced locations sk . Some more general data structures consisting of time series of functions observed at spatial locations will also be considered. Just as in the case of scalar geostatistical data, the model for functional geosta- tistical data is the random field {X(s), s ∈ S}, with the difference that now each X(s) is a random function. We assume that each X(s) is an element of the Hilbert space L2 = L2 (T ), with the interval T = [0, 1] chosen merely for convenience. We assume that each X(s) is square integrable, i.e. ∫ 2 E ∥X(s)∥ = EX 2 (s; t)dt < ∞. If we assume that S is the whole Euclidean space, we can define strict stationarity by the condition d {X(s1 + h), X(s2 + h), . . . , X(sm + h)} = {X(s1 ), X(s2 ), . . . , X(sm )} . (1) 2 If this is the case, then E ∥X(s)∥ does not depend on s. Square integrability and strict stationarity imply that the mean function µ(t) = EX(s; t) and the covariances C(h; t, u) = Cov(X(s; t), X(s + h; u)) exist and do not depend on s. When working with functional geostatistical data, it is important to keep in mind that the function h 7→ C(h; t, u) is nonnegative definite only if t = u. In that case, C(·; t) := C(·; t, t) is the spatial covariance function of the scalar field {X(s; t)}. It is often assumed that the covariances are isotropic, i.e. C(h; t, u) = C(h; t, u) depends only on h = ∥h∥. Unless stated otherwise, in the remainder of this paper, we assume that the field {X(s)} is square integrable, strictly stationary, and isotropic. Revista Colombiana de Estadstica 42 (2019) 101–122 Some Recent Developments in Inference for Geostatistical Functional Data 103 We also consider a more complex data structure; at spatial locations we observe time series of functions. The data have the form Xn (s; t), where n is year, s is a spatial location, and t is time within a year. For example Xn (s; t) can be the curve of daily temperatures, the unit of t is day, in year n, and at location s. Other examples are: total daily precipitation, wind strength, wind direction, solar radiation. Many of these daily time series are either maxima, minima or averages of data obtained in higher temporal resolutions. Historical records can be treated as geostatistical data, as meteorological stations are not uniformly distributed. However, computer weather prediction models produce complete records at dense grids that extend many decades into the future. The paper is organized as follows. In Section 2, we review the subject of kriging in the context of functional data. Kriging is a fundamental tool in the field of spatial statistics, and so is a suitable starting point. We then turn, in Section 3, to the subject of estimation of the the mean function and the functional principal components from a sample of spatially distributed curves. Most methods of Sections 2 and 3 are implemented in the R package geofd. Examples of code are given in Chapter 9 of Kokoszka & Reimherr (2017). Section 4 is devoted to several significance tests in the context of spatial functional data. Testing of separability is presented in a separate section, Section 5, due to its importance in many inferential procedures for spatio–temporal data. We conclude with fairly recent research on extreme events defined in terms of spatially indexed functional time series. This work, whose many aspects are still under development, is outlined in Section 6. It is not our objective to present a complete review of the subject, but rather to explain those recent developments which have attracted our interest. We strive not to merely provide references, but to explain the central points in detail that will allow the reader to gain sufficient understanding to decide if a specific development is relevant to her work or not. We assume that the reader is familiar with the fundamental concepts of spatial statistics, explained, e.g., in initial chapters of Wackernagel (2003), Schabenberger & Gotway (2005) or Sherman (2011). Chapter 3 of Gelfand, Diggle, Fuentes & Guttorp (2010) also provides a sufficient introduction. Some familiarity with the fundamental concepts of functional data analysis would also be helpful; Chapters 1 and 3 of Kokoszka & Reimherr (2017) provide enough background. 2. Kriging We observe functions X(sk ) at spatial locations s1 , s2 , . . . , sN . Suppose s is a different location, and we want to predict the function X(s) using the func- tions X(s1 ), X(s2 ), . . . , X(sN ). In the functional setting, the available data can be represented as a matrix of scalars [X(sk ; tj ), k = 1, 2, . . . , N, j = 1, 2, . . . , J] , assuming all functions are observed at the same points tj . In some situations, the points tj may depend on the location sk , so the scalar data points are X(sk , tkj ). Revista Colombiana de Estadstica 42 (2019) 101–122 104 Piotr Kokoszka & Matthew Reimherr b There are many approaches to computing a predictor X(s) of the unobserved curve X(s). We start with a method which is the most direct extension of the approach used for scalar data. Taking a functional point of view, we treat each curve X(sk ) as an indivisible data object. We want to determine the weights wk for the predictor of the form ∑ N b X(s) =µ+ wk (X(sk ) − µ). (2) k=1 Since the X(sk ) are now functions, we calculate the weights by minimizing the expected L2 distance between X(s) b and X(s). We thus want to find weights w1 , w2 , . . . , wN which minimize 2 ∫ ( )2 b E X(s) − X(s) = E b t) − X(s; t) dt. X(s; Observe that 2 2 ∑ N b X(s) − X(s) = µ+ wk (X(sk ) − µ) − X(s) k=1 ⟨N ⟩ ∑ ∑ N = wk (X(sk ) − µ) − (X(s) − µ), wℓ (X(sℓ ) − µ) − (X(s) − µ) k=1 ℓ=1 ∑ N = wk wℓ ⟨X(sk ) − µ, X(sℓ ) − µ⟩ k,ℓ=1 ∑ N −2 wk ⟨X(sk ) − µ, X(s) − µ⟩ + ⟨X(s) − µ, X(s) − µ⟩ . k=1 Define the functional spatial covariances as C(s, s′ ) = E [⟨X(s) − µ, X(s′ ) − µ⟩] . (3) Notice that for any two spatial points, C(s, s′ ) is a real number, as opposed to an operator. Using this notation, we see that 2 ∑ N ∑ N b E X(s) − X(s) = wk wℓ C(sk , sℓ ) − 2 wk C(sk , s) + C(s, s). k,ℓ=1 k=1 Finding the kriging weights is thus based on the same equations as for scalar data, but using the functional covariances (3). Therefore, the weights wk are found by solving the system of equations ∑ N C(sk , sℓ )wℓ = C(sk , s), k = 1, 2, . . . N. (4) ℓ=1 Revista Colombiana de Estadstica 42 (2019) 101–122 Some Recent Developments in Inference for Geostatistical Functional Data 105 To implement this approach in practice, we must estimate the covariances C(sk , sℓ ) and C(sk , s). We now explain how this can be done. Using the assump- tions of stationarity and isotropy, we see that ∫ C(s, s′ ) = E (X(s; t) − µ(t)) (X(s′ ; t) − µ(t)) dt ∫ = C(∥s − s′ ∥ ; t)dt, where C(h; t) = Cov(X(s + h; t), X(s; t)), h = ∥h∥ , is the spatial covariance function of the scalar field {X(·; t)} obtained by fixing t. For each t, the covariance function h 7→ C(h; t) can be estimated by any method that is applicable to covariance estimation for scalar spatial data; this is typically done by estimating the semivariogram. The kriging predictor is often expressed∑ in a slightly different way. We want to N find a predictor X ⋆ (s) of the form X ⋆ (s) = k=1 λk X(sk ), subject to the condition ∑N ∑N k=1 λk = 1. By contrast, equations (4) do not imply that k=1 wk = 1. In many applications, the weights wj are very close to the weights λj , and the predicted b function X(s) and X ⋆ (s) are also very close. In addition to these simple methods, (Delicado, Giraldo, Comas & Mateu 2010) give references to several other methods of kriging functional data. Another rela- tively simple kriging method they discuss, which gives predictions as good as more complex methods can be summarized as follows. The predictor has the form ∑ N b t) = X(s; wk (t)X(sk ; t), k=1 ∑N where the unknown functions wk (·) satisfy k=1 wk (t) = 1, for each t. The observed functions X(sk ) and the unknown weight functions wk (·) are expanded using some basis system: ∑ M ∑ M X(sk ; t) = ckm Bm (t), wk (t) = bkm Bm (t). m=1 m=1 In particular, one can use the estimated FPC’s v̂m as the Bm . The coefficient matrix B = [bkm , 1 ≤ k ≤ N, 1 ≤ m ≤ M ] is also found by minimizing E∥X(s)b − 2 X(s)∥ . This approach is similar to the method of co–kriging used for multivariate data, e.g. Wackernagel (2003). We have assumed so far that EX(s; t) = µ(t) does not depend on the location s. Caballero, Giraldo & Mateu (2013) and Menafoglio, Secchi & Rosa (2013) show how to perform kriging under a more flexible assumption that EX(s; t) = ∑L ℓ=1 βℓ (t)fℓ (s). Revista Colombiana de Estadstica 42 (2019) 101–122 106 Piotr Kokoszka & Matthew Reimherr 3. Estimation of the mean function and of the FPC’s To estimate the mean function, we use the weighted average ∑ N µ̂(t) = wk X(sk ; t), (5) k=1 and the problem becomes how to compute the optimal weights wk . As in Section 2, in (5) we treat the curves X(sk ) as indivisible statistical objects, and so we apply one weight to the whole curve. One could consider weights wk (t), defined as functions, but the simple approach we describe in this section is easy to implement, and produces estimates which significantly improve on the simple average. Figure 1 illustrates the difference between the simple average (wk = 1/N ) and the weighted average we are about to derive, using annual temperature curves in Canada. There are plenty of locations in the southern part of Canada, especially in the densely populated South–East of the country, and very few in the North. If we postulate the model X(sk ; t) = µ(t) + ε(sk ; t), then µ should represent the typical annual temperature profile for the whole country. The simple average will mostly reflect temperature curves in the region where there are many stations, i.e. mostly in the South. To obtain a more informative kriged mean function, stations far in the North must receive larger weights. Some stations in the south will receive even slightly negative weights. 20 10 0 −10 −20 −30 0 100 200 300 Day Figure 1: Gray lines: annual temperature curves at 35 locations in Canada (averaged over several decades). Dashed line: simple average of these curves. Continu- ous black line: mean function estimated by functional kriging. We define the optimal weights as those that minimize ∑ N 2 ∫ {∑ N }2 E wk X(sk ) − µ = wk X(sk ; t) − µ(t) dt, (6) k=1 k=1 Revista Colombiana de Estadstica 42 (2019) 101–122 Some Recent Developments in Inference for Geostatistical Functional Data 107 ∑n subject to the condition k=1 wk = 1 which ensures that E µ̂ = µ. The method of Lagrange multipliers leads to the following system of N + 1 linear equations: ∑ N ∑ N wk = 1, wk C(sk , sn ) − r = 0, n = 1, 2, . . . N, (7) k=1 k=1 in which w1 , w2 , . . . , wN , r are N +1 unknowns. The functional covariances C(sk , sn ) can be estimated as explained in Section 2. A fundamental tool of functional data analysis is the Karhunen–Loéve ∑∞ ex- pansion. Every function X in L2 can be represented as X(t) = j=1 ξ j v j (t), where the vj are orthonormal functions known as the functional principal compo- (p) ∑p (FPC’s). The main feature of this expansion is that the function X (t) = nents j=1 ξj vj (t) is a very good approximation of the function X(·) even for small p; in many applications p = 3 is sufficient. A small number of scores ξ1 , ξ2 , . . . , ξp thus encodes an infinitely dimensional function. Details are explained in Chapter 11 of Kokoszka & Reimherr (2017). The functions vj are the eigenfunctions of the covariance function c(t, s) = Cov(X(t), X(s)). Therefore, if the spatially indexed functions X(s) have the same distribution, then each of them admits the expansion ∞ ∑ X(s; t) = µ(t) + ξi (s)vi (t). (8) i=1 We now explain how to estimate the vj in (8) under the assumptions of station- arity and isotropy stated in Section 1. We also assume that µ(t) = 0; in practice we would subtract the estimated mean function. We describe one of the two methods proposed by Gromenko, Kokoszka, Zhu & Sojka (2012). Both methods have very similar finite sample performance, and have significantly smaller MSE’s compared to the standard method which does not take spatial dependence into account. It is assumed that the vj admit the expansion ∑ K vj (t) = x(j) α Bα (t), (9) α=1 where the Bα are elements of an orthonormal basis, for example Fourier basis (splines will not work because they are not orthogonal). The expansion (9) is already an estimation step. We would take K so large that∑each observed function K X(sk ) is well approximated by the sum X (K) (sk ; t) = α=1 bα (sk )Bα (t). The exact expansion is ∞ ∑ X(s; t) = bα (s)Bα (t), bα (s) = ⟨X(s), Bα ⟩ . α=1 The bα (sk ) form an observable field. The vj are determined (up to a sign) by the conditions C(vj ) = λj vj and ∥vj ∥ = 1, where C(·) = E[⟨X(s), ·⟩ X(s)] is the covariance operator. Using the orthonormality of the Bj , we obtain Revista Colombiana de Estadstica 42 (2019) 101–122 108 Piotr Kokoszka & Matthew Reimherr [⟨ ∞ ⟩ ∞ ] ∑ ∑ C(Bj ) = E bα (s)Bα , Bj bi (s)Bi (10) α=1 i=1 [ ∞ ] ∑ = E bj (s) bi (s)Bi i=1 ∞ ∑ = E[bi (s)bj (s)]Bi . i=1 Thus, to estimate C, we must estimate the means E[bi (s)bj (s)]. Fix i and j, and define the scalar field z by z(s) = bi (s)bj (s). We can postulate a parametric model for the covariance structure of the field z(·), and use an empirical variogram to estimate µz = Ez(s) as a weighted average of the z(sk ). Denote the resulting estimate by r̂ij . The empirical version of (10) is then ∑ K b j) = C(B r̂ij Bi . (11) i=1 Relation (11) defines the estimator Cb which acts on the span of Bj , 1 ≤ j ≤ K. ∑ Its eigenfunctions are of the form x = 1≤α≤K xα Bα . Observe that ( ) ∑ ∑ ∑ ∑ b C(x) = xα r̂iα Bi = r̂iα xα Bi . α i i α ∑ other hand, λx = i λxi Bi . Since the Bi form an orthonormal basis, we On the∑ obtain α r̂iα xα = λxi . Setting x = [x1 , x2 , . . . , xK ]T , b = [r̂ij , 1 ≤ i, j ≤ K], R we can write the above as a matrix equation b = λx. Rx (12) Denote the solutions to (12) by (j) (j) (j) x̂(j) = [x̂1 , x̂2 , . . . , x̂k ]T , λ̂j , 1 ≤ j ≤ K. (13) ∑K (j) (i) The x̂(j) satisfy α=1 x̂α x̂α = δij . Therefore the v̂j defined by ∑ K v̂j = x̂(j) α Bα (14) α=1 are also orthonormal (because the Bj are orthonormal). The v̂j given by (14) are the estimators of the FPC’s, and the λ̂j in (13) of the corresponding eigenvalues. A natural question to ask is what happens if one applies standard software to the observed curves X(sk ), 1 ≤ k ≤ K, in order to estimate the FPC’s, vj , Revista Colombiana de Estadstica 42 (2019) 101–122 Some Recent Developments in Inference for Geostatistical Functional Data 109 in (8). The usual method, implemented in the function pca of the fda package (and in many other packages) is to use the the eigenfunctions of the sample co- variance operator. It is suitable for a sample of iid curves or for curves forming a regularly spaced functional time series, but not for geostatistical functional data. We illustrate with an example. A comprehensive theory and more examples were developed by Hörmann & Kokoszka (2013). This material is also presented in Chapter 18 of Horváth & Kokoszka (2012). For mean zero functions, the sample covariance operator C b is defined by ∑ N bN (x) = N −1 C ⟨Xk , x⟩ Xk . k=1 The usual estimated FPC’s are defined by C bN (v̂j ) = λ̂j v̂j . Consider a functional random field ∞ ∑ X(s; t) = ξj (s)ej (t), s ∈ Rd , t ∈ [0, 1], (15) j=1 where {ej , j ≥ 1} is a complete orthonormal system and the ξj (s) are ∑∞mean zero random variables with E[ξj (s)ξj (s + h)] = λj ρj (h), h = ∥h∥, where j=1 λj < ∞ and each ρj (·) is a positive correlation function. ∑∞ Recall that C(·) = E[⟨X(s), ·⟩ X(s)]. Direct verification shows that C(x) = j=1 λj ⟨ej , x⟩ ej , so the λj are the eigenval- ues of C, and the ej the corresponding eigenfunctions, i.e. vj = ej . Now consider a sequence sn → 0. Because of the positive dependence, X(sn ) is close to X(0), so CbN , as an arithmetic average, is close to the random operator X ⋆ = ⟨X(0), ·⟩ X(0). Observe that X ⋆ (X(0)) = ∥X(0)∥2 X(0). Thus X(0) is an eigenfunction of X ⋆ . Since it is random, it cannot be close to any of the vj , even asymptotically. The above is only an intuitive illustration of the point that if the spatial loca- tions at which functions are observed have dense clusters, or if the the dependence is strong, then the eigenfunctions of C bN do not consistently estimate the FPC’s vj in (8). 4. Independence, Trend and Change Point Tests In this section, we discuss several significance tests for geostatistical functional data. These tests are analogs of simpler tests for iid curves. The spacial depen- dence between the curves requires more complex forms of the test statistics. In addition, these statistics typically require complex numerical procedures to com- pute them. We therefore merely describe what has been done, and provide suitable references. We begin with a test of independence of two functional random fields. It was proposed by Gromenko et al. (2012), and is described in detail in Chapter 17 of Horváth & Kokoszka (2012). The data are observed at N spatial locations: s1 , s2 , . . . , sN . At location sk , we observe two curves: X(sk ) and Y (sk ). We assume that the sample {X(sk )} is a realization of a random field {X(s), s ∈ S}, Revista Colombiana de Estadstica 42 (2019) 101–122 110 Piotr Kokoszka & Matthew Reimherr and the sample {Y (sk )} is a realization of a random field {Y (s), s ∈ S}. We want to test the null hypothesis: H0 : for each s ∈ S, the random functions X(s) and Y (s) are independent against the alternative that H0 does not hold. The test statistic detects departures from H0 that manifest themselves in the lack of the correlation between the projec- tions ⟨x, X(s)⟩ and ⟨y, Y (s)⟩, for any x, y ∈ L2 . In practice, the lack of correlation can be tested only for x and y from sufficiently large finite dimensional subspaces, those spanned by the first p FPC’s of X(s), and the first q FPC’s of Y (s). The idea of the test, thus requires that the pairs (X(s), Y (s)) have the same distribution for every s ∈ S. The construction of the test assumes that both fields, {X(s), s ∈ S} and {Y (s), s ∈ S} are stationary. The test statistic SbN is constructed from the inner products ⟨X(sk ), v̂j ⟩ , 1 ≤ j ≤ p and ⟨Y (sk ), ûj ⟩ , 1 ≤ j ≤ q, where the v̂j are estimated FPC’s of the X–sample and the ûj of the Y –sample. The v̂j and the ûj be computed as described in Section 3. Under H0 , the test statistic SbN converges, as N → ∞, to a chi–square distribution with pq degrees of freedom. Once the v̂j and the ûj are computed, the tests statistic can be computed without difficulty using package fda. Since the critical values are those of the chi-square distribution, the test is easy to apply. The problem of testing the equality of two mean functions, each defined for functions observed over a different spatial region, is considered in Gromenko & Kokoszka (2012). Our next test is motivated by an interesting and extensively studied problem of space physics. The account presented here is based on Gromenko & Kokoszka (2013) and Gromenko, Kokoszka & Sojka (2017). We first describe the space physics problem, and then explain the idea of the test. 16 300 14 250 SRF, W/ m2 /Hz 12 200 foF2, MHz 10 150 8 100 6 50 4 0 1960 1970 1980 1990 2000 2010 Figure 2: Gray lines represent ionosonde measurements obtained at observatories lo- cated in mid-latitude northern hemisphere, with the scale on the left-hand side. The black line represents the observed solar radio flux with the scale on the right-hand side. Revista Colombiana de Estadstica 42 (2019) 101–122 Some Recent Developments in Inference for Geostatistical Functional Data 111 Increased concentration of greenhouse gases in the upper atmosphere is as- sociated with global warming in the lower troposphere (the atmosphere roughly below 10 km). Roble & Dickinson (1989) suggested that the increasing amounts of these radiatively active gases, mostly CO2 and CH4 , would lead to a global cooling in the ionosphere (atmosphere roughly 300 km above the Earth’s surface). Rishbeth (1990) pointed out that this would result in a thermal contraction of the ionosphere. The height of the ionosphere can be approximately computed using data from a radar–type instrument called the ionosonde. Relevant measurements have been made for many decades by globally distributed ionosondes. In principle, these observations could be used to quantitatively test the hypothesis of Roble & Dickinson (1989). The difficulty in testing the contraction hypothesis comes from several sources. The height of the ionosphere depends on magnetic coordinates, the season, long term changes in the strength and direction of the internal mag- netic field, and, most importantly, on the solar cycle; more solar radiation leads to greater ionization. This is illustrated in Figure 2. Another difficulty stems from the fact that ionosonde records are not complete. Most observation stations do not operate continuously for many decades. They start and end operation at dif- ferent times, some of them are out of service for many years, or even decades. In the mid-latitude northern hemisphere, there are 81 ionosonde stations, but at any given time, data from no more than 40 are available, as shown in Figure 3. This means that the estimation methods described in Section 3 cannot be used, as they require complete records to compute various integrals. More complex methods that work for incomplete records are needed. 40 30 Number of stations 20 10 0 1960 1970 1980 1990 2000 2010 Figure 3: Number of available stations in the mid–latitude northern hemisphere. Let Y (sk ; τi ) be the original record at location sk , measured from 1958 to 2015, possibly with long gaps. The set of all locations is {sk , 1 ≤ k ≤ K}, and the set of time points at which measurements may be available is {τi , 1 ≤ i ≤ T }; in Gromenko, Kokoszka & Sojka (2017) these are months from January 1958 to December 2015. The following spatio–temporal model is postulated: Revista Colombiana de Estadstica 42 (2019) 101–122 112 Piotr Kokoszka & Matthew Reimherr Y (s; τ ) = µ(s; τ ) + ε(s; τ ) + θ(s; τ ), (16) where s is a generic location in a region of interest, and τ is continuous time. A simple form of the mean function relevant to the space physics problem is µ(s; τ ) = β1 + β2 τ + β3 SRF(τ ) + β4 M (s; τ ), where SRF(τ ) is the solar radio flux, cf. Fig. 2, and M (s; τ ) is a suitable function computed from the coordinates of the internal magnetic field. The interest lies in the estimation of the mean function, and testing if it contains a linear trend, i.e. testing H0 : β2 = 0. The function µ(·, ·) is treated as an unknown determinis- tic functional parameter. The second term, ε(s; τ ), describes the spatio–temporal variability away from the mean function. Stochastic modeling of this term is needed to develop inferential procedures. The term θ(s; τ ) represents a random error, which can be associated with measurement error. The details of the esti- mation and testing procedures are too complex to describe here. The conclusion is that β2 is significantly negative, confirming the hypothesis of global ionospheric contraction. The software to perform the test is available and can be used to test for the presence of global trends in other data of this type, for example in near-surface temperatures. We conclude this section with a discussion of change-point detection for the mean function. The presentation is based on Gromenko, Kokoszka & Reimherr (2017). General theory for change points for scalar data is presented in Csörgő & Horváth (1997), several extensions to functional data are presented in Horváth & Kokoszka (2012). In the spatio–temporal setting we consider here, the data are assumed to follow the model Xn (s, t) = µn (s; t) + εn (s; t). In most applications, n denotes year, s, as before, spatial location, and t time within a year. For a fixed s, {Xn (s), n = 1, 2, . . .} is a time series of functions, one function per year. While we assume that the curves are observed densely in time, they are only observed at a finite number of spatial locations {sk : k = 1, . . . , K}. The goal is to determine if the mean functions, µn , are the same across n or if there is a change in the mean. In other words, we aim to evaluate the null hypothesis H0 : µ1 = µ2 = · · · = µN against HA : µ1 = . . . µn∗ ̸= µn∗ +1 = · · · = µN . The alternative of a sudden change at a single year n∗ is to be viewed as a math- ematical approximation. As with all testing problems, the null hypothesis of no change is tested, and the alternative specifies the violations of the null hypothesis which will be detected with the highest power. The tests described below, will also detect different violations of H0 , including gradual changes taking place over a few years. To carry out the tests, we assume that the covariance structure of the εn is separable, a test of which will be discussed in section 5. In particular, we assume that Cov(εn (s; t), εn (s′ ; t′ )) = v(t, t′ )u(s, s′ ). Revista Colombiana de Estadstica 42 (2019) 101–122 Some Recent Developments in Inference for Geostatistical Functional Data 113 ∫ decomposition above is unique only up to a constant, we thus Notice that the assume that v(t, t) dt = 1. Gromenko, Kokoszka & Reimherr (2017) consider three different test statistics based on CUSUM’s (cumulative sums), each of which uses the expansion (8) applied to the annual curves in different ways. They do not require a specific procedure for estimating v(t, t′ ) and U = {u(sk , sk′ )}, instead formulating their tests assuming they have consistent estimates. Examples of how to estimate these quantities are given in their appendix, as well as in Aston, Pigoli & Tavakoli (2016) and Constantinou, Kokoszka & Reimherr (2017). The first test involves using a temporal FPCA, normalizing by the corresponding eigenvalues, and then pooling across space. The tests statistics is ⟨ r ⟩2 1 ∑ ∑ ∑ ∑ r ∑ K p N N Λ̂1 = 2 ŵk λ̂−1 i Xn (sk ) − Xn (sk ), v̂i . N i=1 r=1 n=1 N n=1 k=1 The pooling weights, ŵk , can be chosen however the user prefers, but in practice, using weights as described in Section 3 works well. It has now become well rec- ognized in the FDA community that dividing by estimated eigenvalues can cause stability problems with certain data. Thus a second test statistic was also proposed which omits normalizing by the λ̂i : ⟨ r ⟩2 1 ∑ ∑p ∑ ∑ r ∑ K N N Λ̂2 = 2 ŵk Xn (sk ) − Xn (sk ), v̂i . N i=1 r=1 n=1 N n=1 k=1 For p large, Λ̂2 is essentially an approximation of the third and final test statistic 2 1 ∑ ∑ ∑ ∑ r ∑ K p N r N −1 Λ̂∞ 2 = ŵk λ̂ i Xn (sk ) − Xn (sk ) . N2 i=1 r=1 n=1 N n=1 k=1 Each statistic has a slightly different limiting distribution. In particular, under H0 ∑ K d ∫ ∑ d Λ̂1 → w(k) 2 Bik (t) dt k=1 i=1 ∑ K ∑ d ∫ d Λ̂2 → w(k) λi 2 Bik (t) dt k=1 i=1 ∑ K ∞ ∑ ∫ ∞ d Λ̂2 → w(k) 2 λi Bik (t) dt, k=1 i=1 where Bik (t) are Brownian bridges which satisfy Cov(Bik (t), Bi′ k′ (t′ )) = 1i=i′ min{t, t′ }(1 − min{t, t′ })σ(sk , sk′ ). These asymptotics can be used for choosing rejection regions with proper Type 1 error. To do so, one can use Monte Carlo, though (Gromenko, Kokoszka & Revista Colombiana de Estadstica 42 (2019) 101–122 114 Piotr Kokoszka & Matthew Reimherr Reimherr 2017) also provide a normal approximation which works well when considering a relatively large number of spatial points. These tests can be im- plemented using the scpt package in R, which is available from http://www. personal.psu.edu/~mlr36/codes.html and includes an example code for imple- menting the methodology. 48 10 46 9 4 44 8 42 7 2 40 3 6 38 1 5 −105 −100 −95 −90 −85 −80 2 Figure 4: The spatial field showing the L distance between the mean log–precipitation before and after 1966. There is an increase in precipitation throughout the year in the area around location 4, decrease in the first half of the year in the area around location 1. Locations close to 2 and 3 do not show a large change nor a consistent pattern. If a change point is detected, its location can be identified as the year when a test statistics attains maximum. Gromenko, Kokoszka & Reimherr (2017) applied the above test procedures (with suitable finite sample calibration) to test if the precipitation pattern over the midwest US states has changed. All tests led to the same conclusion: one change point in second half of the sixties. The pattern of the change is shown in Fig. 4. The biggest changes are in the area around Michigan Lake and south–west of the lake. To visualize the spatial distribution of change, the authors used the spatial field ϕ̂(s) = ∥µˆ1 (s) − µ̂2 (s)∥, where ∑ r̂ −1 ∑ N µ̂1 (s; t) = r̂−1 Xn (s; t), µ̂2 (s; t) = (N − r̂) Xn (s; t). n=1 n=r̂+1 They performed kriging with the exponential covariance model to obtain the heat map shown in Fig. 4. The application of the significance tests confirms that the Revista Colombiana de Estadstica 42 (2019) 101–122 Some Recent Developments in Inference for Geostatistical Functional Data 115 heat map shows a statistically significant change over a region, not a variation in the magnitude of change which may be due to chance. 5. Separability Tests The second order structure of a random field of functions is described by the covariance function σ(s, s′ ; t, t′ ) = Cov(X(s, t), X(s′ , t′ )). Theoretical and com- putational aspects of most procedures can be significantly simplified if one can assume that σ(s, s′ ; t, t′ ) = u(s, s′ )v(t, t′ ), (17) that is, if the spatio–temporal covariance function factors into the product of a purely spatial and purely temporal covariance functions. The above condition is, for example, required to develop the change point methodology described in Section 4. If (17) holds, we say that the functional random field is separable. In particular, the spatial dependence structure is the same for any time t. Tests whose null hypothesis is (17) have been proposed by (Liu, Ray & Hooker 2017), (Aston et al. 2016) and (Constantinou et al. 2017). We discuss the latter two approaches here. We begin by discussing two different procedures for estimating v(t, t′ ) and U = {u(sk , sk′ )}. Aston et al. (2016) used partial trace operators to estimate these quantities, while (Constantinou et al. 2017) combined bases expansions with a “flip-flop” approach, which basically iterates between estimating v and U. Partial trace operators are used to eliminate either the temporal or spatial component of the covariance, in particular, define the estimated covariance function as 1 ∑ N σ̂(sk , s′k , t, t′ ) = Xn (sk , t)Xn (sk′ , t′ ). N n=1 (In the above formula, and in the remainder of this section, we assume that the mean function is zero.) Then the spatial covariance is estimated using ∫ Ûkk = σ̂(sk , s′k , t, t) dt, ′ and the temporal covariance is estimated using ∑K ′ σ̂(sk , sk , t, t′ ) ∫ v̂(t, t ) = ∑ k=1 . k σ̂(sk , sk , t, t) dt The normalization above ensures that the trace of v(t, t′ ) is normalized to be 1, though other normalizations are possible. One thing to note is that the full covariance σ̂ does not actually need to be estimated, as one can move to estimating the Û and v̂ directly. The second approach to estimating v and U comes form (Constantinou et al. 2017) and begins with basis expansions. In particular, one approximates each temporal curve using J basis functions: Revista Colombiana de Estadstica 42 (2019) 101–122 116 Piotr Kokoszka & Matthew Reimherr ∑ J Xn (sk , t) ≈ ξjn (sk )ej (t). j=1 The basis ej (t) can either be deterministic or data driven, such as FPCA. Testing separability of Xn is then translated into testing separability of ξjn (sk ), so that the null becomes H0 : Cov(ξjn (sk ), ξj ′ n (sk′ ) = Vjj ′ Ukk′ . However, this is now a multivariate problem and we can utilize multivariate meth- ods for estimating V and U, in particular, the maximum likelihood estimators, assuming the data are Gaussian, satisfy 1 ∑ 1 ∑ ⊤ −1 N N V̂ = Ξn Û−1 Ξ⊤ n Û = Ξ V̂ Ξn , N n=1 N n=1 n where Ξn = {ξjn (sk )} is a J ×K matrix. To compute these estimators, one chooses an initial value, for example Û0 = I, and then iterates between the two estimates, hence the name “flip-flop method". With these estimators in hand, one can now carry out a number of different tests. To construct these tests first define Σ := E vec(Ξn ) vec(Ξn )⊤ , where vec is the vectorization operator, which stacks the columns of a matrix into a vector. Under H0 one can show that Σ = V ⊗ U, where ⊗ is the Kronecker product. Constantinou et al. (2017) consider three different approaches c + (V̂ ⊗ Û − Σ), b ⊤W TW = N (V̂ ⊗ Û − Σ) b TL = N (J log det(Û) + K log det(V̂) − log det(Σ̂)), b 2. TF = N ∥V̂ ⊗ Û − Σ∥ F The first test uses the Moore–Penrose generalized inverse of the estimated covari- ance matrix of V̂ ⊗ Û − Σ b ,Wc + , to normalize the difference and create a Wald c is complex, but can be found in Constantinou type test statistic. The form for W et al. (2017). The generalized inverse is necessary since the symmetry of the ma- trices and the non-uniqueness of U and V create a number of linear constraints. This turns out to be a fairly unstable test statistic in terms of Type 1 error, and works well only for very small J and K. The second test is derived from the likelihood ratio and had previously been explored in the multivariate literature in ?. This test is also quite unstable, but only when using a chi-squared distribution as an asymptotic approximation. Mitchell, Genton & Gumpertz (2006) provided a Monte-Carlo method which provides a much more stable (in terms of type 1 Revista Colombiana de Estadstica 42 (2019) 101–122 Some Recent Developments in Inference for Geostatistical Functional Data 117 error) test. The last test forgoes normalizing the test statistic and instead uses an asymptotic distribution given by a weighted sum of chi-squares. This test is very stable and, in the settings considered by Constantinou et al. (2017) exhib- ited excellent power. Lastly, we note that Aston et al. (2016) provided a testing procedure that focussed on testing the separability in the directions dictated by the eigenfunctions. They utilized a bootstrap approach instead of asymptotic dis- tributions, and their individual tests can be pooled to construct a global test for evaluating separability overall. 6. Spatio-Temporal Extremes In this section, we summarize the work of (French, Kokoszka, Stoev & Hall 2019) which deals with the computation of probabilities of heat waves. The raw data are spatially–indexed time series of daily temperature measurements, X(sk , j), denoting the temperature at a spatial location sk , k = 1, . . . , K, on day j. As argued above, due to the natural annual climate cycle, for each site, we partition {X(si , j)} into years, and view the resulting 365-dimensional vectors as samples from a functional time series: Xn (sk ; ·) = {Xn (sk ; ti ), i ∈ {1, 2, . . . 365}} . (18) Here, t 7→ Xn (sk ; t) is the temperature curve at site sk for year n, viewed as a function of time t in days. In contrast to the setting of previous sections, the data used by French et al. (2019) are not historical records, but data generated by a computer climate model. These artificial data are of much higher quality than historical records; there are no gaps, and the daily records are available at 16,100 locations forming a grid covering much of North America. It is, at this point, not clear how to extend the methodology of (French et al. 2019) to historical records. The advantage of using computer model data is that they are predicted future temperatures (French et al. 2019 work with the period 2041-2070), which are more relevant to the prediction of future heat waves. On the other hand, these data do depend on a model, and the poor quality, geostatistical historical records are the real data. French et al. (2019) propose many functionals that can quantify a heat wave, but here we focus on one specific approach that explains the general idea. A heat wave is characterized by its spatial and temporal extents and by its intensity. The intensity is typically quantified by a threshold. Public health concerns call for a fixed threshold, like 1050 F. However, in climate studies of large spatial regions, with many climatic zones, such a fixed threshold is not appropriate. Also the vari- ability of temperatures depends greatly on the geographical location, with coastal locations exhibiting much smaller variability than locations far away from large bodies of water. It is therefore reasonable to work with standardized temperatures Xn (sk , ti ) − X(sk , ti ) Zn (sk , ti ) = , (19) SD(sk , ti ) Revista Colombiana de Estadstica 42 (2019) 101–122 118 Piotr Kokoszka & Matthew Reimherr where 1 ∑ 1 ∑ N N X(sk , ti ) = Xn (sk , ti ) and SD2 (sk , ti ) = (Xn (sk , ti )−X(sk , ti ))2 . N n=1 N − 1 n=1 (20) If the Zn (sk , ti ) exceed a fixed threshold z, e.g. z = 2, for a number of neighboring locations and over a period of time, then we have observed a heat wave (the Zn (sk , ti ) are practically normal). The severity of a heat wave increases with the size of the region, the duration and the threshold z that is exceeded. Suppose the Xn (sk , ti ) are maximum daily temperatures, and set 1 ∑ Zn⋆ (sk , tj ) = Zn (sk , ti ). ℓ tj −ℓ<ti ≤tj This is the average maximum temperature over the ℓ days preceding day tj . Next, define Zn⋆ (tj ) = min Zn⋆ (sk , tj ). 1≤k≤K If Zn⋆ (tj ) > z, then the average maximum temperature over ℓ days over K (neigh- boring) locations exceeds, z; this corresponds to a heat wave defined by this specific functional. We are interested in the probability of a heat wave in any given year. We assume that this probability does not depend on year n. We thus want to compute, for some relevant z > 0, ( ) p(z) = P (∃ j : Zn (tj ) > z) = P max Zn⋆ (tj ) > z = P (MJ > z), 1≤j≤J where J = 365, and d MJ = MJ,n := max Zn⋆ (tj ). 1≤j≤J ⋆ The concatenated sequence Z (tj ) is stationary and weakly dependent, so (see e.g. Beirlant, Goegebeur, Segers & Teugels 2006, Chapter 10), there are sequences aJ and bJ such that ( ) MJ − bJ lim P ≤ z → H(z), J→∞ aJ where H is a univariate Generalized Extreme Value distribution function. The function H depends on three parameters, which can be estimated, together with the constants aJ and bJ , using now standard R implementations. Figure 5 shows examples of regions corresponding to 50, 150 and 450 neighbor- ing locations. Figure 6 shows a map of the probability of a heat wave for d = 50 for three durations ℓ, with (a) corresponding to ℓ = 3, (b) to ℓ = 10, and (c) to ℓ = 30. When ℓ = 3, there is a surprisingly high probability of localized heat waves over the Labrador Peninsula. Such short heat spells may occur with prob- ability approaching 50%, that is on average every second year. While our EVT approximation may break down for such high probabilities, it is nevertheless obvi- ous that that part of Canada will see heat spells much more frequently than in the past. Generally, we see that the area around the Hudson Bay will experience an Revista Colombiana de Estadstica 42 (2019) 101–122 Some Recent Developments in Inference for Geostatistical Functional Data 119 increased frequency of hot spells lasting a few days. There is a noticeable drop in the probability of such a heat wave around the Rocky Mountain range. The prob- ability is also very low along the Eastern seaboard of the United States. Increasing the duration to ℓ = 10 days, dramatically reduces the probability of a heat wave of the corresponding magnitude. The reader will note the different probability scale. Many parts of Canada once again show an increased probability of a heat wave of this magnitude, as well as parts of Iowa and Illinois, certain regions in Texas, and, most visibly, the Pacific Ocean off the Southern California coast. Increas- ing the duration to approximately 1 month (ℓ = 30), causes the probability of a heat wave to drop even further; generally, throughout North America, heat waves of this magnitude will occur with probability of less than 1%, i.e. once per one hundred years, on average. Over the Canadian plains and the Canadian Rockies, this probability increases only slightly to about 1.5%. There are two patches, in Arizona and Southern Texas, with probabilities elevated to 2-3%. Figure 5: A map of the neighborhood structures for different locations using 50, 150, and 450 nearest neighbors. Each × marks a neighborhood centroid and the sequences of grey shading mark the extents of the increasing neighborhood sizes. Revista Colombiana de Estadstica 42 (2019) 101–122 120 Piotr Kokoszka & Matthew Reimherr Figure 6: Probability of a heat wave with amplitude more than 2 standard deviations above the mean for spatial extent d = 50 and durations of (a) ℓ = 3, (b) ℓ = 10, and (c) ℓ = 30. 7. Conclusions This article has focused on aspects of the statistical analysis of functions and time series of functions distributed over space that have attracted our interest. No claim is made that this survey is complete. There have been developments in the analysis of functional data arising in brain and other medical studies that have important spacial aspects, but do not readily fit into the more traditional and well understood paradigms of spatial statistics. One can expect that as new data sets consisting of functions that exhibit some form of spatial dependence arise, new tools may need to be developed to extract useful information. Revista Colombiana de Estadstica 42 (2019) 101–122 Some Recent Developments in Inference for Geostatistical Functional Data 121 Acknowledgements The research presented in this paper has been partially supported by the United States National Science Foundation grants DMS-0931948 Spatio-temporal Statis- tical Framework for the Evaluation of Global Change in the Ionosphere and DMS– 1462067 FRG: Collaborative Research:Extreme Value Theory for Spatially Indexed Functional Data. [ ] Received: January 2017 — Accepted: November 2018 References Aston J, Pigoli D, Tavakoli S. Tests for separability in nonparametric covariance operators of random surfaces.(2016). The Annals of Statistics. Beirlant J, Goegebeur Y, Segers J, Teugels J. Statistics of Extremes: Theory and Applications.(2006). John Wiley and Sons. Caballero W, Giraldo R, Mateu J. A universal kriging approach for spatial functional data.(2013). Stochastic Environmental Research and Risk Assessment. Constantinou P, Kokoszka P, Reimherr M. Testing separability of space-time functional processes.(2017). Biometrika. Csörgő M, Horváth L. Limit Theorems in Change-Point Analysis.(1997). Wiley. Delicado P, Giraldo R, Comas C, Mateu J. Statistics for spatial functional data: some recent contributions.(2010). Environmetrics. French J, Kokoszk P, Stoev S, Hall L. Quantifying the risk of heat waves using extreme value theory and spatio-temporal functional data.(2019). Computational Statistics and Data Analysis. Gelfand A E, Diggle P J, Fuentes M, Guttor P. Handbook of Spatial Statistics.(2019). CRC Press. Gromenko O, Kokoszka P. Testing the equality of mean functions of spatially distributed curves.(2012). Journal of the Royal Statistical Society. Gromenko O, Kokoszka P. Nonparametric inference in small data sets of spatially indexed curves with application to ionospheric trend determination.(2013). Computational Statistics and Data Analysis. Gromenko O, Kokoszka P, Reimherr M. Detection of change in the spatiotemporal mean function.(2017). Journal of the Royal Statistical Society . Gromenko O, Kokoszka P, Sojka J. Evaluation of the global cooling trend in the ionosphere using functional regression models with incomplete curves.(2017). The Annals of Applied Statistics. Gromenko O, Kokoszka P, Zhu L, Sojka J. Estimation and testing for spatially indexed curves with application to ionospheric and magnetic field trends.(2012). The Annals of Applied Statistics. Hörmann S, Kokoszka P. Consistency of the mean and the principal components of spatially distributed functional data.(2013). Bernoulli. Horváth L, Kokoszka P. Inference for Functional Data with Applications.(2012). Springer. Kokoszka P, Reimherr M. Introduction to Functional Data Analysis.(2017). CRC Press. Liu C, Ray S, Hooker G. Functional principal components analysis of spatially correlated data.(2017). Statistics and Computing. Lu N, Zimmerman D. The likelihood ratio test for a separable covariance matrix.(2005). Statistics and Probability Letters. Menafoglio A, Secchi P, Rosa M D. A universal kriging predictor for spatially dependent functional data of a hilbert space.(2013). Electronic Journal of Statistics. Mitchell M W, Genton M G, Gumpertz M L. A likelihood ratio test for separability of covariances.(2006). Journal of Multivariate Analysis. Rishbeth H. A greenhouse effect in the ionosphere?.(1990). Planetary and Space Science. Roble R G, Dickinson R E. How will changes in carbon dioxide and methane modify the mean structure of the mesosphere and thermosphere?.(1989).. Schabenberger O, Gotway C A. Statistical Methods for Spatial Data Analysis.(2005). Chapman and Hall/CRC. Sherman M. Spatial Statistics and Spatio–Temporal Data: Covariance Functions and Directional Properties.(2011). Wiley. Wackernagel H. Multivariate Geostatistics.(2003). Springer.
import { Navbar as MantineNavbar, Stack, useMantineTheme } from "@mantine/core"; import React from "react"; import { NavMenu } from "."; import { headerHeight } from "lib/const"; export const Navbar = (props: { opened: boolean }) => { const theme = useMantineTheme(); return ( <MantineNavbar p="md" hiddenBreakpoint="sm" hidden={!props.opened} width={{ sm: 200, lg: 300 }} height={`calc(100vh - ${headerHeight}px)`} px={24} sx={{ backgroundColor: theme.colors.pink[6], border: "none", position: "fixed", }} > <Stack> <NavMenu href="/about">About</NavMenu> <NavMenu href="/blog">Blog</NavMenu> <NavMenu href="/portfolio">Portfolio</NavMenu> <NavMenu href="/contact">Contact</NavMenu> </Stack> </MantineNavbar> ); };
import { api } from "../utils/api"; import { createContext } from "react"; import { INovoUsuarioContext, IChildren, INovoUsuario } from '../utils/interfaces'; import { useNavigate } from "react-router-dom"; import { toast } from "react-toastify"; import nProgress from "nprogress"; import { toastConfig } from '../utils/toast'; export const UserContext = createContext({} as any); export const UserProvider = ({ children }: IChildren) => { const navigate = useNavigate(); const novoUsuario = async (usuario: INovoUsuarioContext) => { try { nProgress.start(); await api.post("/dados-pessoais", usuario); toast.success("Usuário cadastrado com sucesso!",toastConfig); navigate("/"); } catch (error) { toast.error("Houve algum erro, tente novamente!",toastConfig); } finally { nProgress.done(); } } const editarUsuario = async (usuario: INovoUsuarioContext) => { try { nProgress.start(); console.log(usuario); await api.put(`/dados-pessoais/${usuario.cpf}`, usuario); toast.success("Usuário editado com sucesso!",toastConfig); navigate("/"); } catch (error) { console.log(error); toast.error("Houve algum erro, tente novamente!",toastConfig); } finally { nProgress.done(); } } const deletarUsuario = async (cpf:string) => { try { nProgress.start(); await api.delete(`/dados-pessoais/${cpf}`); toast.success("Usuário excluído com sucesso!",toastConfig); navigate("/"); } catch (error) { toast.error("Houve algum erro, tente novamente!",toastConfig); } finally { nProgress.done(); } } const listarUsuarios = async (): Promise<Array<INovoUsuario> | undefined> => { try { nProgress.start(); const response = await api.get(`/dados-pessoais`); nProgress.done(); return response.data; } catch (error) { toast.error("Houve algum erro, tente novamente!",toastConfig); } finally { nProgress.done(); } } const pesquisarUsuario = async (cpf: string) : Promise<INovoUsuario | undefined> => { try { nProgress.start(); const response = await api.get(`/dados-pessoais/${cpf}`); nProgress.done(); return response.data; } catch (error) { } finally { nProgress.done(); } return; } return ( <UserContext.Provider value={{ novoUsuario, editarUsuario, listarUsuarios, deletarUsuario, pesquisarUsuario }}> {children} </UserContext.Provider> ) }
import { ArgumentValue, Command, } from "https://deno.land/x/cliffy@v1.0.0-rc.3/command/mod.ts"; import jsonld from "npm:jsonld"; import { toText } from "https://deno.land/std@0.208.0/streams/mod.ts"; import { defaultTheme, highlight } from "https://deno.land/x/stx@0.1.1/mod.ts"; function jsonType({ label, name, value }: ArgumentValue): unknown { try { return JSON.parse(value); } catch (e) { if (e instanceof SyntaxError) { throw new Error(`${label} ${name} must be a valid JSON; ${e.message}`); } throw e; } } function mediaTypeType({ label, name, value }: ArgumentValue): string { if (!value.match(/^[a-z]+\/[a-z0-9.+-]+$/i)) { throw new Error(`${label} ${name} must be a valid media type`); } return value; } const command = new Command() .name("jld") .description("JSON-LD CLI tools") .version("0.1.2") .type("json", jsonType) .type("media_type", mediaTypeType) .arguments("[source:file]") .option( "-c, --compact <context:json>", "compact a document according to a specified context", { conflicts: ["expand", "flatten", "normalize", "to-rdf"] }, ) .option("-e, --expand", "expand a document and remove its context", { conflicts: ["compact", "flatten", "normalize", "to-rdf"], }) .option( "-f, --flatten", "flatten a document so that " + "all deep-level trees are flattened to the top-level", { conflicts: ["compact", "expand", "normalize", "to-rdf"] }, ) .option( "-n, --normalize, -C, --canonize, --canonicalize", "normalize (canonize) a document using RDFC-1.0 (formerly URDNA2015) " + "so that it can be used for hashing, comparison, and so on", { conflicts: ["compact", "expand", "flatten", "to-rdf"] }, ) .option("-r, --to-rdf", "serialize a document to N-Quads (RDF)", { conflicts: ["compact", "expand", "flatten", "normalize"], }) .option( "-a, --accept <media_type:media_type>", "specify the media type to send Accept header with " + "(used only when source is a URL)", { default: "application/ld+json", }, ); function prettyPrintJson(json: unknown) { const formatted = JSON.stringify(json, null, 2); if (Deno.isatty(Deno.stdout.rid)) { console.log(highlight(defaultTheme, "javascript", formatted)); } else { console.log(formatted); } } async function run( { args, options }: Awaited<ReturnType<typeof command.parse>>, ) { let json: string; if (args[0] == null) { json = await toText(Deno.stdin.readable); } else if ( args[0].startsWith("https://") || args[0].startsWith("http://") || args[0].startsWith("file://") ) { const response = await fetch(args[0], { headers: { Accept: options.accept }, }); json = await response.text(); } else { json = await Deno.readTextFile(args[0]); } const doc = JSON.parse(json); if (options.compact != null) { const compacted = await jsonld.compact(doc, options.compact); prettyPrintJson(compacted); } else if (options.expand) { const expanded = await jsonld.expand(doc); prettyPrintJson(expanded); } else if (options.flatten) { const flattened = await jsonld.flatten(doc); prettyPrintJson(flattened); } else if (options.normalize) { const normalized = await jsonld.normalize(doc); console.log(normalized); } else if (options.toRdf) { const rdf = await jsonld.toRDF(doc); prettyPrintJson(rdf); } else { await jsonld.expand(doc); // for validation prettyPrintJson(doc); } } async function main() { const result = await command.parse(Deno.args); try { await run(result); } catch (e) { result.cmd.throw(e); } } if (import.meta.main) await main();
<?php namespace App\Http\Requests\Scheduling; use Illuminate\Foundation\Http\FormRequest; class CustomerTypeRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required|string|max:250', ]; } /** * Get the error messages for the defined validation rules. * * @return array */ public function messages() { return [ 'name.required' => 'El tipo de cliente es requerido.', 'name.string' => 'El tipo de cliente debe ser un nombre valido.', 'name.max' => 'El tipo de cliente debe ser de máximo 50 caracteres.' ]; } }
<?php namespace App\Controller; use App\Entity\Animal; use App\Form\AnimalType; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Routing\Annotation\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\VarDumper\VarDumper; class AnimaisController extends AbstractController { /** * @Route("/animais", name="listar_animais") * @Template("animais/index.html.twig") */ public function index() { $em = $this->getDoctrine()->getManager(); $animais = $em->getRepository(Animal::class)->findAll(); return ['animais' => $animais]; } /** * @Route("/animal/visualizar/{id}", name="visualizar_animal") * @Template("animais/view.html.twig") * * @param Animal $animal * @return array */ public function view(Animal $animal) { return ['animal' => $animal]; } /** * @Route("animal/cadastrar", name="cadastrar_animal") * @Template("animais/create.html.twig") */ public function create(Request $request) { $animal = new Animal(); $form = $this->createForm(AnimalType::class, $animal); $form->handleRequest($request); if($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($animal); $em->flush(); $this->addFlash('success', "Animal foi salvo com sucesso!"); return $this->redirectToRoute('visualizar_animal', [ 'id' => $animal->getId() ]); } return [ 'form' => $form->createView() ]; } }
import React, { useState } from 'react' import { Link, useNavigate } from 'react-router-dom'; import Navbar from 'react-bootstrap/Navbar'; import { Container, Nav } from 'react-bootstrap'; import Avatar from '@mui/material/Avatar'; import Button from '@mui/material/Button'; import TextField from '@mui/material/TextField'; import Grid from '@mui/material/Grid'; import Box from '@mui/material/Box'; import LockOutlinedIcon from '@mui/icons-material/LockOutlined'; import Typography from '@mui/material/Typography'; import InputLabel from '@mui/material/InputLabel'; import MenuItem from '@mui/material/MenuItem'; import Select from '@mui/material/Select'; import axios from 'axios'; import { message } from 'antd'; const Register = () => { const navigate = useNavigate() const [data, setData] = useState({ name: "", email: "", password: "", type: "", phone: "" }) const handleChange = (e) => { const { name, value } = e.target; setData({ ...data, [name]: value }); }; const handleSubmit = (e) => { e.preventDefault() if (!data?.name || !data?.email || !data?.password || !data?.type || !data?.phone) return alert("Please fill all fields"); else { axios.post('http://localhost:8001/api/user/register', data) .then((response) => { if (response.data.success) { message.success(response.data.message); navigate('/login') } else { message.error(response.data.message) } }) .catch((error) => { console.log("Error", error); }); } }; return ( <> <Navbar expand="lg" className="bg-body-tertiary"> <Container fluid> <Navbar.Brand><h2>Rentify</h2></Navbar.Brand> <Navbar.Toggle aria-controls="navbarScroll" /> <Navbar.Collapse id="navbarScroll"> <Nav className="me-auto my-2 my-lg-0" style={{ maxHeight: '100px' }} navbarScroll > </Nav> <Nav> <Link to={'/'}>Home</Link> <Link to={'/login'}>Login</Link> <Link to={'/register'}>Register</Link> </Nav> </Navbar.Collapse> </Container> </Navbar> <Container component="main" > <Box sx={{ marginTop: 8, marginBottom: 4, display: 'flex', flexDirection: 'column', alignItems: 'center', }} > <Avatar sx={{ bgcolor: 'secondary.main' }}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign up </Typography> <Box component="form" onSubmit={handleSubmit} noValidate> <TextField margin="normal" fullWidth id="name" label="Renter Full Name/Owner Name" name="name" value={data.name} onChange={handleChange} autoComplete="name" autoFocus /> <TextField margin="normal" fullWidth id="email" label="Email Address" name="email" value={data.email} onChange={handleChange} autoComplete="email" autoFocus /> <TextField margin="normal" fullWidth name="password" value={data.password} onChange={handleChange} label="Password" type="password" id="password" autoComplete="current-password" /> <TextField margin="normal" fullWidth name="phone" value={data.phone} onChange={handleChange} label="Phone no." type="text" id="phone" autoComplete="current-phone" /> <InputLabel id="demo-simple-select-label">User Type</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" name='type' value={data.type} label="type" defaultValue="Select User" onChange={handleChange} style={{ width: '200px' }} > <MenuItem value={'Select User'} disabled>Select User</MenuItem> <MenuItem value={'Renter'}>Renter</MenuItem> <MenuItem value={"Owner"}>Owner</MenuItem> </Select> <Box mt={2}> <Button type="submit" variant="contained" style={{ width: '200px' }} > Sign Up </Button> </Box> <Grid container> <Grid item>Have an account? <Link style={{ color: "blue" }} to={'/login'} variant="body2"> {" Sign In"} </Link> </Grid> </Grid> </Box> </Box> </Container> </> ) } export default Register
import React, { useState } from 'react'; import Firebase from '../../firebaseConfig'; import './CreatePoll.css'; import {Link, useNavigate} from "react-router-dom"; import "../../styles/components.css" import Button from "../../Components/Button"; import HomeButton from "../../Components/HomeButton"; const firebaseInstance = new Firebase(); function CreatePoll() { const [pollName, setPollName] = useState('') const [pollQuestionText, setPollQuestionText] = useState(''); const [pollAccessMode, setPollAccessMode] = useState('public'); const navigate = useNavigate(); const handleSubmit = async (e) => { e.preventDefault(); // Get user's ID token const idToken = await firebaseInstance.auth.currentUser.getIdToken(true); // Create the question object const questionObject = { question: pollQuestionText, // Use the question text input yesVotes: 0, noVotes: 0, totalVotes: 0 }; const pollObject = { name: pollName, active: true, accessMode: pollAccessMode, question: questionObject } // Send POST request to Spring Boot backend with poll details try { const response = await fetch('http://localhost:8080/api/polls', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${idToken}` // Passing ID token in header }, body: JSON.stringify(pollObject) }); const responseData = await response.json(); console.log("creating poll data: ", responseData); if (response.ok) { navigate('/home') } else { alert('Error creating poll: ' + responseData.message); } } catch (error) { console.error("There was an error creating the poll", error); } fetch('http://localhost:8080/api/sendToDweet', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(pollObject), }) .then(response => response.json()) .then(data => { console.log('Data sent to Dweet via proxy:', data); }) .catch(error => { console.error('Error sending data to Dweet via proxy:', error); }); }; return ( <div className="welcome-background min-h-[80vh] flex items-center justify-center bg-gray-200"> <div className="beigeBox md:w-1/2 lg:w-1/3 xl:w-1/4 p-4 md:p-6 lg:p-8 rounded-xl shadow-lg flex flex-col justify-center items-center"> <HomeButton /> <h2 className="title">Create A New Poll</h2> <form className="form" onSubmit={handleSubmit}> <div className="input-group"> <label className="label">Poll Name:</label> <input className="input" value={pollName} onChange={(e) => setPollName(e.target.value)} required /> </div> <div className="input-group"> <label className="label">Poll Question:</label> <input className="input" value={pollQuestionText} onChange={(e) => setPollQuestionText(e.target.value)} required /> </div> <div className="input-group"> <label className="label">Access Mode:</label> <div className="radio-group"> <label className="radio-label"> <input type="radio" value="public" checked={pollAccessMode === 'public'} onChange={() => setPollAccessMode('public')} /> Public </label> <label className="radio-label"> <input type="radio" value="private" checked={pollAccessMode === 'private'} onChange={() => setPollAccessMode('private')} /> Private </label> </div> </div> <div className="flex items-center justify-center space-x-4 mt-4"> <Button type="submit" text="Create" /> </div> </form> </div> </div> ); } export default CreatePoll;
<template> <s-row justify-content="flex-start" :gap="20"> <s-input v-model="val"> <template #prefixSlot>https://</template> </s-input> <s-input v-model="val"> <template #suffixSlot>.com</template> </s-input> </s-row> <s-row justify-content="flex-start" :gap="20"> <s-input v-model="val"> <template #prefixSlot> <s-icon target="edit"></s-icon> </template> </s-input> <s-input v-model="val" class="with-button"> <template #suffixSlot> <s-dropdown> <template #reference> <s-button type="cyan">click me</s-button> </template> <s-dropdown-item v-for="item in data" :value="item" @select="foo" >{{item}}</s-dropdown-item> </s-dropdown> </template> </s-input> </s-row> </template> <script setup lang="ts"> import {ref} from "vue"; const val = ref(undefined); const data = ref(['item 1', 'item 2', 'item 3', 'item 4', 'item 5']); const foo = (v:string) => { val.value = v; } </script> <style lang="less"> .with-button .s-input__slot--suffix { padding: 0; & > * { border: none; border-radius: unset; } } </style>
#include "lists.h" /** * add_node - adds a new node at the beginning of a list * @head: the head of the list * @str: the string of the node to add *Return: the head of the new list */ list_t *add_node(list_t **head, const char *str) { list_t *node; size_t len = 0; node = malloc(sizeof(list_t)); if (node == NULL) return (NULL); node->str = strdup(str); while (str[len]) { len++; } node->len = len; node->next = *head; *head = node; return (*head); }
# -*- coding: utf-8 -*- # @Time : 2020/05/29 20:19 # @Author : Xu HongBin # @Email : 2775751197@qq.com or 17770026885@163.com # @github : https://github.com/ToughStoneX # @blog : https://blog.csdn.net/hongbin_xu # @File : unsup_loss # @Software: PyCharm import torch import torch.nn as nn import torch.nn.functional as F from losses.modules import * from losses.homography import * class UnSupLoss(nn.Module): def __init__(self): super(UnSupLoss, self).__init__() self.ssim = SSIM() def forward(self, imgs, cams, depth): # print('imgs: {}'.format(imgs.shape)) # print('cams: {}'.format(cams.shape)) # print('depth: {}'.format(depth.shape)) ''' 当张量被解绑时,它的指定维度会被拆分成多个张量,这些张量将以一个 Python 列表的形式返回。 拆分的张量将具有与原始张量相同的大小,除了指定的维度被移除。 例如, 如果有一个形状为 [3, 4, 5] 的张量 x,并且调用 torch.unbind(x, dim=0),那么将返回一个包含 3 个形状为 [4, 5] 的张量的列表。 ''' # imgs 和 cams 使用 torch.unbind 函数进行解绑,得到一个图片列表和一个相机参数列表。 imgs = torch.unbind(imgs, 1) # img:[B ref+src 3 H W] cams = torch.unbind(cams, 1) # cams:[B ref+src ... 类似 # 检查图片和相机参数的数量是否一致。 assert len(imgs) == len(cams), "Different number of images and projection matrices" #len返回列表的长度 # 获取图像的高度和宽度,并记录图像数量。 img_height, img_width = imgs[0].shape[2], imgs[0].shape[3] num_views = len(imgs) # 选择参考图像和相机参数 ref_img = imgs[0] # ref_img = F.interpolate(ref_img, scale_factor=0.25, mode='bilinear') # ref_img = F.interpolate(ref_img, size=[depth.shape[1], depth.shape[2]]) ref_img = ref_img.permute(0, 2, 3, 1) # [B, C, H, W] --> [B, H, W, C] ref_cam = cams[0] # print('ref_cam: {}'.format(ref_cam.shape)) # 初始化一些损失变量。 # reconstr_loss 是重建损失(reconstruction loss)。 # ssim_loss 是结构相似性损失(structural similarity loss)。 # smooth_loss 是平滑损失(smoothness loss)。 self.reconstr_loss = 0 self.ssim_loss = 0 self.smooth_loss = 0 # 对每个视角进行迭代计算。 warped_img_list = [] mask_list = [] reprojection_losses = [] for view in range(1, num_views): # 从第二个视角开始(索引为 1)。 view_img = imgs[view] view_cam = cams[view] # print('view_cam: {}'.format(view_cam.shape)) # view_img = F.interpolate(view_img, scale_factor=0.25, mode='bilinear') # view_img = F.interpolate(view_img, size=[depth.shape[1], depth.shape[2]]) view_img = view_img.permute(0, 2, 3, 1) # [B, C, H, W] --> [B, H, W, C] # warp view_img to the ref_img using the dmap of the ref_img # 使用参考图片的深度图(depth)将当前视角的图片进行逆向变换(inverse warping) warped_img, mask = inverse_warping(view_img, ref_cam, view_cam, depth) warped_img_list.append(warped_img) mask_list.append(mask) # 计算重建损失(reconstr_loss)和有效掩模(valid_mask)。 reconstr_loss = compute_reconstr_loss(warped_img, ref_img, mask, simple=True) valid_mask = 1 - mask # replace all 0 values with INF reprojection_losses.append(reconstr_loss + 1e4 * valid_mask) # SSIM loss## # 对前三个视角计算结构相似性损失(ssim_loss)。 if view < 3: self.ssim_loss += torch.mean(self.ssim(ref_img, warped_img, mask)) #print(reconstr_loss) ##smooth loss## # 计算平滑损失(smooth_loss)。 self.smooth_loss += depth_smoothness(depth.unsqueeze(dim=-1), ref_img, 1.0) # top-k operates along the last dimension, so swap the axes accordingly # 构建重投影损失体积(reprojection volume)并选择前三个最小值。 reprojection_volume = torch.stack(reprojection_losses).permute(1,2,3,4,0) # 将重建损失存储为一个损失体积(reprojection volume)。 # by default, it'll return top-k largest entries, hence sorted=False to get smallest entries top_vals, top_inds = torch.topk(torch.neg(reprojection_volume), k=3, sorted=False) # 使用 torch.topk 函数选择体积中最小的前三个值和对应的索引。 top_vals = torch.neg(top_vals) # 创建一个与 top_vals 相同大小的掩模(top_mask),将小于 1e4 的值设为 1,其他值设为 0。 top_mask = top_vals < (1e4 * torch.ones_like(top_vals, device=device)) top_mask = top_mask.float() # 将 top_vals 乘以 top_mask,将大于 1e4 的值设为 0。 top_vals = torch.mul(top_vals, top_mask) # 计算 top_vals 沿最后一个维度的和,并取平均值,得到 reconstr_loss self.reconstr_loss = torch.mean(torch.sum(top_vals, dim=-1)) #self.unsup_loss = 12 * self.reconstr_loss + 6 * self.ssim_loss + 0.18 * self.smooth_loss self.unsup_loss = 12 * self.reconstr_loss + 6 * self.ssim_loss + 0.05 * self.smooth_loss # 按照un_mvsnet和M3VSNet的设置 #print(reconstr_loss) #self.unsup_loss = (0.8 * self.reconstr_loss + 0.2 * self.ssim_loss + 0.067 * self.smooth_loss) * 15 return self.unsup_loss def non_zero_mean_absolute_diff(y_true, y_pred, interval): """ non zero mean absolute loss for one batch """ batch_size = y_pred.shape[0] interval = interval.reshape(batch_size) mask_true = torch.ne(y_true, 0.0).float() denom = torch.sum(mask_true, dim=[1,2]) + 1e-7 masked_abs_error = torch.abs(mask_true * (y_true - y_pred)) masked_mae = torch.sum(masked_abs_error, dim=[1,2]) masked_mae = torch.sum((masked_mae.float() / interval.float()) / denom.float()) return masked_mae def less_one_percentage(y_true, y_pred, interval): """ less one accuracy for one batch """ batch_size = y_pred.shape[0] height = y_pred.shape[1] width = y_pred.shape[2] interval = interval.reshape(batch_size) mask_true = torch.ne(y_true, 0.0).float() denom = torch.sum(mask_true) + 1e-7 interval_image = interval.reshape(batch_size, 1, 1).repeat(1, height, width) # print('y_true: {}'.format(y_true.shape)) # print('y_pred: {}'.format(y_pred.shape)) abs_diff_image = torch.abs(y_true.float() - y_pred.float()) / interval_image.float() less_three_image = mask_true * torch.le(abs_diff_image, 1.0).float() return torch.sum(less_three_image) / denom def less_three_percentage(y_true, y_pred, interval): """ less three accuracy for one batch """ batch_size = y_pred.shape[0] height = y_pred.shape[1] width = y_pred.shape[2] interval = interval.reshape(batch_size) mask_true = torch.ne(y_true, 0.0).float() denom = torch.sum(mask_true) + 1e-7 interval_image = interval.reshape(batch_size, 1, 1).repeat(1, height, width) abs_diff_image = torch.abs(y_true.float() - y_pred.float()) / interval_image.float() less_three_image = mask_true * torch.le(abs_diff_image, 3.0).float() return torch.sum(less_three_image) / denom
#include "include/flutter_dev_tools/flutter_dev_tools_plugin.h" #include <flutter_linux/flutter_linux.h> #include <gtk/gtk.h> #include <sys/utsname.h> #include <cstring> #include "flutter_dev_tools_plugin_private.h" #define FLUTTER_DEV_TOOLS_PLUGIN(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj), flutter_dev_tools_plugin_get_type(), \ FlutterDevToolsPlugin)) struct _FlutterDevToolsPlugin { GObject parent_instance; }; G_DEFINE_TYPE(FlutterDevToolsPlugin, flutter_dev_tools_plugin, g_object_get_type()) // Called when a method call is received from Flutter. static void flutter_dev_tools_plugin_handle_method_call( FlutterDevToolsPlugin* self, FlMethodCall* method_call) { g_autoptr(FlMethodResponse) response = nullptr; const gchar* method = fl_method_call_get_name(method_call); if (strcmp(method, "getPlatformVersion") == 0) { response = get_platform_version(); } else { response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); } fl_method_call_respond(method_call, response, nullptr); } FlMethodResponse* get_platform_version() { struct utsname uname_data = {}; uname(&uname_data); g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version); g_autoptr(FlValue) result = fl_value_new_string(version); return FL_METHOD_RESPONSE(fl_method_success_response_new(result)); } static void flutter_dev_tools_plugin_dispose(GObject* object) { G_OBJECT_CLASS(flutter_dev_tools_plugin_parent_class)->dispose(object); } static void flutter_dev_tools_plugin_class_init(FlutterDevToolsPluginClass* klass) { G_OBJECT_CLASS(klass)->dispose = flutter_dev_tools_plugin_dispose; } static void flutter_dev_tools_plugin_init(FlutterDevToolsPlugin* self) {} static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { FlutterDevToolsPlugin* plugin = FLUTTER_DEV_TOOLS_PLUGIN(user_data); flutter_dev_tools_plugin_handle_method_call(plugin, method_call); } void flutter_dev_tools_plugin_register_with_registrar(FlPluginRegistrar* registrar) { FlutterDevToolsPlugin* plugin = FLUTTER_DEV_TOOLS_PLUGIN( g_object_new(flutter_dev_tools_plugin_get_type(), nullptr)); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), "flutter_dev_tools", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel, method_call_cb, g_object_ref(plugin), g_object_unref); g_object_unref(plugin); }
<script> import { onMount } from "svelte"; import Board from "./components/Board.svelte"; import { Kanban } from "./stores/Kanban.js"; import { keyHandler } from "./stores/keyHandler.js"; import * as App from "../wailsjs/go/main/App.js"; let styles = { backgroundcolor: "blue", textcolor: "white", unselectTabColor: "lightgray", unselectTabTextColor: "black", selectTabColor: "lightblue", selectTabTextColor: "black", mainboardcolor: "lightblue", listcontainercolor: "lightblue", listbgcolor: "#9AC2FA", listtextcolor: "white", itembgcolor: "white", itemtextcolor: "black", font: '"Fira Code"', fontsize: 16, dialogBGColor: "lightblue", dialogTextColor: "black", kanbanInfo: "black", cursorColor: "blue", cursorWidth: "10px", }; onMount(async () => { // // Load the board information from the harddrive. // let kanbanStr = await App.ReadKanbanString(); $Kanban = JSON.parse(kanbanStr); if ($Kanban.boards === null) $Kanban.boards = []; let styleStr = await App.ReadThemeString(); styles = JSON.parse(styleStr); // // For debug purposes. NOTE: Remove when done testing. // window.Kanban = $Kanban; }); async function addBoard() { var newID = 0; if ($Kanban.boards.length > 0) { $Kanban.boards.forEach((item) => { if (item.id >= newID) newID = item.id + 1; }); } $Kanban.boards.push({ id: newID, name: "New Board", lists: [], }); await SaveKanbanBoards($Kanban); } async function addList(e) { var newID = 0; var ind = 0; $Kanban.boards.map((board, index) => { if (board.id === e.detail.board) { board.lists.map((list) => { if (list.id >= newID) { newID = list.id + 1; } }); ind = index; } }); $Kanban.boards[ind].lists.push({ id: newID, name: "New List", items: [], }); await SaveKanbanBoards($Kanban); } async function addItem(e) { var newID = 0; var Boardind = 0; var Listind = 0; $Kanban.boards.map((board, bindex) => { if (board.id === e.detail.board) { Boardind = bindex; board.lists.map((list, lindex) => { if (list.id === e.detail.list) { Listind = lindex; list.items.map((item) => { if (item.id >= newID) { newID = item.id + 1; } }); } }); } }); $Kanban.boards[Boardind].lists[Listind].items.push({ id: newID, name: "New Item", description: "This should describe the card's function.", color: "", notes: [], apps: [], }); await SaveKanbanBoards($Kanban); } async function deleteList(e) { $Kanban.boards.map((board) => { if (board.id === e.detail.board) { board.lists = board.lists.filter((list) => e.detail.list !== list.id); } }); await SaveKanbanBoards($Kanban); } async function deleteItem(e) { $Kanban.boards.map((board) => { if (board.id === e.detail.board) { board.lists.map((list) => { if (list.id === e.detail.list) { list.items = list.items.filter((item) => e.detail.item !== item.id); } }); } }); await SaveKanbanBoards($Kanban); } async function newItemMsg(e) { let Bdindex = 0; let Ltindex = 0; let Itindex = 0; let newid = 0; $Kanban.boards.map((board, bindex) => { if (board.id === e.detail.board) { Bdindex = bindex; board.lists.map((list, lindex) => { if (list.id === e.detail.list) { Ltindex = lindex; list.items.map((item, iindex) => { if (item.id === e.detail.item) { Itindex = iindex; if (item.notes.length > 0) { item.notes.map((note) => { if (note.id >= newid) newid = note.id + 1; }); } } }); } }); } }); let notes = $Kanban.boards[Bdindex].lists[Ltindex].items[Itindex].notes; $Kanban.boards[Bdindex].lists[Ltindex].items[Itindex].notes = [ e.detail.msg, ...notes, ]; await SaveKanbanBoards($Kanban); } async function newItemApp(e) { let Bdindex = 0; let Ltindex = 0; let Itindex = 0; $Kanban.boards.map((board, bindex) => { if (board.id === e.detail.board) { Bdindex = bindex; board.lists.map((list, lindex) => { if (list.id === e.detail.list) { Ltindex = lindex; list.items.map((item, iindex) => { if (item.id === e.detail.item) { Itindex = iindex; } }); } }); } }); $Kanban.boards[Bdindex].lists[Ltindex].items[Itindex].apps.push( e.detail.app ); await SaveKanbanBoards($Kanban); } async function appUpdate(e) { let Bdindex = 0; let Ltindex = 0; let Itindex = 0; let Apindex = 0; $Kanban.boards.map((board, bindex) => { if (board.id === e.detail.board) { Bdindex = bindex; board.lists.map((list, lindex) => { if (list.id === e.detail.list) { Ltindex = lindex; list.items.map((item, iindex) => { if (item.id === e.detail.item) { Itindex = iindex; item.apps.map((app, aindex) => { if (app.id === e.detail.app.id) { Apindex = aindex; } }); } }); } }); } }); $Kanban.boards[Bdindex].lists[Ltindex].items[Itindex].apps[Apindex] = e.detail.app; await SaveKanbanBoards($Kanban); } async function listUpdate(e) { let Bdindex = 0; let Ltindex = 0; $Kanban.boards.map((board, bindex) => { if (board.id === e.detail.board) { Bdindex = bindex; board.lists.map((list, lindex) => { if (list.id === e.detail.list.id) { Ltindex = lindex; } }); } }); $Kanban.boards[Bdindex].lists[Ltindex] = e.detail.list; await SaveKanbanBoards($Kanban); } async function SaveKanbanBoards(boards) { await App.SaveKanbanBoards(JSON.stringify(boards)); $Kanban = boards; } </script> <svelte:window on:keydown={(e) => { if ($keyHandler !== null) $keyHandler(e); }} /> <div id="main" style="background-color: {styles.backgroundcolor}; color: {styles.textcolor}; font-family: {styles.font}; font-size: {styles.fontsize}px;" > <Board {styles} on:saveBoad={async () => { await SaveKanbanBoards($Kanban); }} on:addboard={() => { addBoard(); }} on:addlist={(e) => { addList(e); }} on:additem={(e) => { addItem(e); }} on:deleteList={(e) => { deleteList(e); }} on:deleteItem={deleteItem} on:newItemMsg={newItemMsg} on:newItemApp={newItemApp} on:appUpdate={appUpdate} on:listUpdate={listUpdate} /> </div> <style> #main { position: absolute; top: 0px; left: 0px; display: flex; flex-direction: column; flex: 1fr; text-align: left; padding: 0px; margin: 0px; user-select: none; width: 100%; max-width: 100%; height: 100%; max-height: 100%; } :global(h1) { font-size: 18px !important; text-align: center; } </style>
import { Profile, FollowersRequest, useFollowers as useFollowersHook, } from '@lens-protocol/api-bindings'; import { useLensApolloClient } from '../helpers/arguments'; import { PaginatedArgs, PaginatedReadResult, usePaginatedReadResult } from '../helpers/reads'; import { useFragmentVariables } from '../helpers/variables'; /** * {@link useProfileFollowers} hook arguments */ export type UseProfileFollowersArgs = PaginatedArgs<FollowersRequest>; /** * `useProfileFollowers` is a paginated hook that lets you fetch profiles that follow a requested profile. * * @category Profiles * @group Hooks * * @example * ```tsx * const { data, loading, error } = useProfileFollowers({ * of: '0x123', * }); * ``` */ export function useProfileFollowers(args: UseProfileFollowersArgs): PaginatedReadResult<Profile[]> { return usePaginatedReadResult( useFollowersHook( useLensApolloClient({ variables: useFragmentVariables(args), }), ), ); }
import { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn, } from "typeorm"; import { Pessoa } from "./Pessoa"; @Index("capitalsocial_pkey", ["idcapitalsocial"], { unique: true }) @Index("fki_fk_pessoacapital", ["idpessoa"], {}) @Entity("capitalsocial", { schema: "cup" }) export class Capitalsocial { @Column("integer", { name: "idpessoa" }) idpessoa: number; @Column("double precision", { name: "autorizado", nullable: true, precision: 53, }) autorizado: number | null; @Column("double precision", { name: "subscrito", nullable: true, precision: 53, }) subscrito: number | null; @Column("double precision", { name: "integralizado", nullable: true, precision: 53, }) integralizado: number | null; @Column("double precision", { name: "valorcota", nullable: true, precision: 53, }) valorcota: number | null; @Column("character", { name: "status", nullable: true, length: 1, default: () => "'A'", }) status: string | null; @Column("date", { name: "dataatualizacao", nullable: true, default: () => "now()", }) dataatualizacao: string | null; @Column("character varying", { name: "idusuario", nullable: true, length: 20, }) idusuario: string | null; @Column("character varying", { name: "idestacao", nullable: true, length: 50, }) idestacao: string | null; @PrimaryGeneratedColumn({ type: "integer", name: "idcapitalsocial" }) idcapitalsocial: number; @ManyToOne(() => Pessoa, (pessoa) => pessoa.capitalsocials) @JoinColumn([{ name: "idpessoa", referencedColumnName: "idpessoa" }]) idpessoa2: Pessoa; }
" An IVPointTest is a test class for testing the behavior of IVPoint " Class { #name : #IVPointTest, #superclass : #TestCase, #category : #'IsomericView-Tests' } { #category : #private } IVPointTest >> newPoint [ ^ IVPoint new ] { #category : #test } IVPointTest >> testAbs [ | a r | a := IVPoint x: 1 y: 2 z: 3. r := a abs. self assert: r x equals: 1. self assert: r y equals: 2. self assert: r z equals: 3. a := IVPoint x: -1 y: -2 z: -3. r := a abs. self assert: r x equals: 1. self assert: r y equals: 2. self assert: r z equals: 3 ] { #category : #test } IVPointTest >> testAsIVPoint [ | p r | p := self newPoint. r := p asIVPoint. self assert: p identicalTo: r ] { #category : #test } IVPointTest >> testIsZero [ | obj | obj := IVPoint x: 0 y: 0 z: 0. self assert: obj isZero. obj := IVPoint x: 1 y: 0 z: 0. self deny: obj isZero. obj := IVPoint x: 0 y: 1 z: 0. self deny: obj isZero. obj := IVPoint x: 0 y: 0 z: 1. self deny: obj isZero ] { #category : #test } IVPointTest >> testMax [ | a b r | a := IVPoint x: 10 y: 20 z: 30. b := IVPoint x: 15 y: 6 z: 7. r := a max: b. self assert: r x equals: 15. self assert: r y equals: 20. self assert: r z equals: 30. a := IVPoint x: 10 y: 20 z: 30. b := IVPoint x: 5 y: 26 z: 7. r := a max: b. self assert: r x equals: 10. self assert: r y equals: 26. self assert: r z equals: 30. a := IVPoint x: 10 y: 20 z: 30. b := IVPoint x: 5 y: 6 z: 37. r := a max: b. self assert: r x equals: 10. self assert: r y equals: 20. self assert: r z equals: 37 ] { #category : #test } IVPointTest >> testMin [ | a b r | a := IVPoint x: 10 y: 20 z: 30. b := IVPoint x: 5 y: 26 z: 37. r := a min: b. self assert: r x equals: 5. self assert: r y equals: 20. self assert: r z equals: 30. a := IVPoint x: 10 y: 20 z: 30. b := IVPoint x: 15 y: 6 z: 37. r := a min: b. self assert: r x equals: 10. self assert: r y equals: 6. self assert: r z equals: 30. a := IVPoint x: 10 y: 20 z: 30. b := IVPoint x: 15 y: 26 z: 7. r := a min: b. self assert: r x equals: 10. self assert: r y equals: 20. self assert: r z equals: 7 ] { #category : #test } IVPointTest >> testMinus [ | a b r | a := IVPoint x: 10 y: 20 z: 30. b := IVPoint x: 1 y: 2 z: 3. r := a - b. self assert: r x equals: 9. self assert: r y equals: 18. self assert: r z equals: 27. r := b - a. self assert: r x equals: -9. self assert: r y equals: -18. self assert: r z equals: -27 ] { #category : #test } IVPointTest >> testPlus [ | a b r | a := IVPoint x: 10 y: 20 z: 30. b := IVPoint x: 1 y: 2 z: 3. r := a + b. self assert: r x equals: 11. self assert: r y equals: 22. self assert: r z equals: 33. r := b + a. self assert: r x equals: 11. self assert: r y equals: 22. self assert: r z equals: 33 ] { #category : #test } IVPointTest >> testPrintOn [ | p s | p := self newPoint. s := WriteStream on: String new. p printOn: s. self assert: s contents equals: '(IVPoint x: nil y: nil z: nil)'. p := self newPoint. p setX: 1 setY: 2 setZ: 3. s := WriteStream on: String new. p printOn: s. self assert: s contents equals: '(IVPoint x: 1 y: 2 z: 3)' ] { #category : #test } IVPointTest >> testPrintTripletOn [ | p s | p := self newPoint. s := WriteStream on: String new. p printTripletOn: s. self assert: s contents equals: 'nil,nil,nil'. p := self newPoint. p setX: 1 setY: 2 setZ: 3. s := WriteStream on: String new. p printTripletOn: s. self assert: s contents equals: '1,2,3' ] { #category : #test } IVPointTest >> testSetXSetYSetZ [ | p | p := self newPoint. self assert: p x isNil. p setX: 123 setY: 456 setZ: 789. self assert: p x equals: 123. self assert: p y equals: 456. self assert: p z equals: 789. p setX: 9 setY: 8 setZ: 7. self assert: p x equals: 9. self assert: p y equals: 8. self assert: p z equals: 7 ] { #category : #test } IVPointTest >> testX [ | p | p := self newPoint. self assert: p x isNil. p setX: 123 setY: nil setZ: nil. self assert: p x equals: 123. p setX: 456 setY: nil setZ: nil. self assert: p x equals: 456. self assert: p y isNil. self assert: p z isNil ] { #category : #test } IVPointTest >> testY [ | p | p := self newPoint. self assert: p y isNil. p setX: nil setY: 123 setZ: nil. self assert: p y equals: 123. p setX: nil setY: 456 setZ: nil. self assert: p y equals: 456. self assert: p x isNil. self assert: p z isNil ] { #category : #test } IVPointTest >> testZ [ | p | p := self newPoint. self assert: p z isNil. p setX: nil setY: nil setZ: 123. self assert: p z equals: 123. p setX: nil setY: nil setZ: 456. self assert: p z equals: 456. self assert: p x isNil. self assert: p y isNil ]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Built-in form validation</title> <style> input:invalid { border: 2px dashed red; } input:invalid:required { background-image: linear-gradient(to right, pink, lightgreen); } input:valid { border: 2px solid black; } form { font: 1em sans-serif; max-width: 320px; } p > label { display: block; } input[type="text"], input[type="email"], input[type="number"], textarea, fieldset { width: 100%; border: 1px solid #333; box-sizing: border-box; } input:invalid { box-shadow: 0 0 5px 1px red; } input:focus:invalid { box-shadow: none; } </style> </head> <body> <form> <label for="choose">Wiykd you prefer a banana or cherry?</label> <input id="choose" name="i-like" required pattern="[Bb]anana|[Cc]herry" /> <button>Submit</button> <div> <label for="choose">Would you prefer a banana or a cherry?</label> <input type="text" id="choose" name="i-like" required minlength="6" maxlength="6" /> </div> <div> <label for="number">How many would you like?</label> <input type="number" id="number" name="amount" value="1" min="1" max="10" /> </div> <div> <button>Submit</button> </div> <p> <fieldset> <legend>Do you have a driver's license?<span aria-label="required">*</span> </legend> <input type="radio" required name="driver" id="r1" value="yes"><label for="r1">Yes</label> <input type="radio" required name="driver" id="r2" value="no"><label for="r2">No</label> </fieldset> </p> <p> <label for="n1">How old are you?</label> <input type="number" min="12" max="120" step="1" id="n1" name="age" pattern="\d+"> </p> <p> <label for="t1">What's your favorite fruit?<span aria-label="required">*</span></label> <input type="text" id="t1" name="fruit" list="li" required pattern="[Bb]anana|[Cc]herry|[Aa]pple|[Ss]trawberry|[Ll]emon|[Oo]range"> <datalist id="l1"> <option>Banana</option> <option>Cherry</option> <option>Apple</option> <option>Strawberry</option> <option>Lemon</option> <option>Orange</option> </datalist> </p> <p> <label for="t2">What's your email address?</label> <input type="email" id="t2" name="email"> </p> <p> <label for="t3">Leave a short message</label> <textarea id="t3" name="msg" maxlength="140" rows="5"></textarea> </p> <p> <button>Submit</button> </p> </form> </body> </html>
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Map; //ActionListener implementation for handling the "Add to shopping cart" button public class AddToCartBtnHandler implements ActionListener{ private JTable productsTable; private ArrayList<Product> productList; private TableModelCart cartTableModel; private ShoppingCartGUI shoppingCartGUI; private boolean firstPurchase; //Constructor for AddToCartBtnHandler public AddToCartBtnHandler(JTable productsTable,ArrayList<Product> productList, TableModelCart cartTableModel,ShoppingCartGUI shoppingCartGUI,boolean firstPurchase){ this.productsTable = productsTable; this.productList = productList; this.cartTableModel = cartTableModel; this.shoppingCartGUI = shoppingCartGUI; this.firstPurchase = firstPurchase; } //Handles the button click event by adding the selected product to the shopping cart @Override public void actionPerformed(ActionEvent event) { //Get the selected row in the products table int selectedRow = productsTable.getSelectedRow(); //Check if a row is selected if(selectedRow != -1) { //Get the product ID of the selected product String selectedProductId = productsTable.getValueAt(selectedRow, 0).toString(); Map<Product, Integer> quantityOnCart = cartTableModel.getShoppingCart().getCartQuantity(); //Iterate through the available products to find the selected product for (Product checker : productList) { //Check if the product ID matches and there are available items if (checker.getProductID().equals(selectedProductId) && checker.getNumberOfAvailableItems()>0) { int availableItems; //Calculate the available items considering items already in the cart if(quantityOnCart.containsKey(checker)){ availableItems = checker.getNumberOfAvailableItems() - quantityOnCart.get(checker); } else availableItems = checker.getNumberOfAvailableItems(); //If there are available items, add the product to the cart and update the GUI if (availableItems > 0) { cartTableModel.getShoppingCart().addProductToCart(checker); shoppingCartGUI.updatePrices(cartTableModel.getShoppingCart().calculateTotalCost(),cartTableModel.getShoppingCart(),firstPurchase); cartTableModel.fireTableDataChanged(); } //break out of the loop after processing the selected product break; } } } } }
import chaiSubset from "chai-subset"; import "cypress-plugin-tab"; import "cypress-real-events"; import "cypress-wait-if-happens"; import "cypress-wait-until"; import { StringMatcher } from "cypress/types/net-stubbing"; export * from "cypress-pipe"; /** * Sinon matcher for stubs/spy comparison * @example * // partial match of spy function params called with * ```ts * it("should partially match spy params", () => { * const obj = { * func: (param: Object) => {} * }; * given.spyOnObject(obj, "func"); * obj.func({ shelly: "go", inner: { attr: "value" } }); * expect( * get * .spyFromFunction(obj.func) * .should( * "have.been.calledWithMatch", * match({ inner: { attr: "value" } }) * ) * ); * }); * ``` * For more information see [Sinon.match documentation](https://sinonjs.org/releases/latest/matchers/) */ export const match = Cypress.sinon.match; export class CypressHelperOptions { /** * default data attribute for elements selection */ defaultDataAttribute?: string = "data-cy"; /** * slot data selector suffix (only relevant when handleSlotShadowDOM is set to true) */ shadowSlotSuffix?: string = "slot"; /** * when set to true, cypress helper will automatically find the assigned dom element of elements with data selector * with `defaultShadowSlotSuffix` suffix */ handleSlotShadowDOM?: boolean = true; /** * when set to true, waits until elements are loaded before returning them */ waitForElementsToLoad?: boolean = true; } /** * @class CypressHelper was designed to help you develop cypress tests faster. * @classdes CypressHelper exposes the following public properties: * @property given - The given property will hold methods which will allow us to set pre-conditions before something takes place. * This is a classic place to have methods which will set the inputs which are going to be passed down to our component. * @property when - The when property will hold methods of “events” which will take place like render, click, hover, etc. * @property get - The get property will hold methods which will give our tests access to the “output” of the component in a “black box” fashion */ export class CypressHelper { /** * * @param [options = { * defaultDataAttribute : "data-cy" , * shadowSlotSuffix : "slot", * handleSlotShadowDOM : true}] */ constructor(private readonly options: CypressHelperOptions = {}) { this.options.defaultDataAttribute = this.options.defaultDataAttribute || "data-cy"; this.options.shadowSlotSuffix = this.options.shadowSlotSuffix || "slot"; this.options.handleSlotShadowDOM = this.options.handleSlotShadowDOM || true; } private isGetter = <T>(obj: T, prop: keyof T) => !!Object.getOwnPropertyDescriptor(obj, prop)!["get"]; private isSetter = <T>(obj: T, prop: keyof T) => !!Object.getOwnPropertyDescriptor(obj, prop)!["set"]; private waitUntilLoadBeforeInvocation = <T>( checkFunction: () => Cypress.Chainable<T>, options?: WaitUntilOptions ): Cypress.Chainable<T> => { if (this.options.waitForElementsToLoad) { this.when.waitUntil(checkFunction, options); } return checkFunction(); }; beforeAndAfter = () => { before(() => { chai.use(chaiSubset); }); beforeEach(() => { cy.on("uncaught:exception", (err, runnable) => { console.log(err); return false; }); }); }; /** * @property given - The given property will hold methods which will allow us to set pre-conditions before something takes place. * This is a classic place to have methods which will set the inputs which are going to be passed down to our component. */ public given = { /** * Use interceptAndMockResponse to stub and intercept HTTP requests and responses. * @example * // adds token to response header * ```ts * helper.given.interceptAndMockResponse({ * url: '** /sysmgmt/2015/bmc/session', * response: { * headers:{ * 'XSRF-Token': 'token', * }, * }, * alias: 'login' * }) * ``` * @example * // mocks response to login request * ```ts * helper.given.interceptAndMockResponse({ * method: "POST", * url: "** /login", * alias: "login", * response : { * token: 'token' * } * }) * ``` * * @example * // mocks network error * ```ts * helper.given.interceptAndMockResponse({ * method: "POST", * url: "** /avamars", * alias: "avamar", * response : { * forceNetworkError: true * } * }) * ``` * @example * // mocks missing image * ```ts * helper.given.interceptAndMockResponse({ * method: "POST", * url: "** /image.png", * alias: "image", * response: { headers: 404 } * }) * ``` * @example * // using a fixture * ```ts * helper.given.interceptAndMockResponse({ * url: "** /shellygo/whatever**", * response: { fixture: "user.json" }, * alias: "whatever" * }); * ``` */ interceptAndMockResponse: (options: { url: StringMatcher; response: Object; alias?: string; method?: string; }) => { const { url, response, alias, method } = options; cy.intercept({ url, method: method || "GET" }, response).as( alias || "call" ); }, /** * Load a fixture * @param filename * @param alias * @example * ```ts * helper.given.fixture("user.json", "user"); * expect( * helper.get.fixture("user").should("deep.nested.include", { * name: "Jane Doe", * id: "1234", * nested: { * attr1: "something", * attr2: "the other thing" * } * }) * ); * ``` */ fixture: (filename: string, alias: string) => cy.fixture(filename).as(alias), /** * Replace a function, record its usage and control its behavior. * @returns {Cypress.Agent<sinon.SinonStub<any[], any>>} */ stub: (): Cypress.Agent<sinon.SinonStub<any[], any>> => cy.stub(), /** * Stub an object's method and create an alias for the stub * @param obj object containing function to stub * @param method function to stub * @returns {Cypress.Agent<sinon.SinonSpy<any[], any>>} * @example * ```ts * //stubbing a service method * helper.given.stubObjectMethod(serviceMock, "functionName").returns(3); * * //stubbing setters and getters * helper.given.stubObjectMethod(serviceMock, "count").get(() => 3).set(() => {}); * ``` */ stubObjectMethod: <T>( obj: T, method: keyof T ): Cypress.Agent<sinon.SinonStub<any[], any>> => cy.stub(obj, method).as(`${String(method)}`), /** * Returns a new spy function, and creates an alias for the newly created spy * @param name - spy name * @returns {Cypress.Agent<sinon.SinonSpy<any[], any>>} */ spy: (name: string): Cypress.Agent<sinon.SinonSpy<any[], any>> => cy.spy().as(`${name}Spy`), /** * Spy on a method and create an alias for the spy * @param obj object containing function to spy on * @param method function to spy on * @returns {Cypress.Agent<sinon.SinonSpy<any[], any>>} */ spyOnObject: <T>( obj: T, method: keyof T ): Cypress.Agent<sinon.SinonSpy<any[], any>> => cy.spy(obj, method).as(`${String(method)}Spy`) }; /** * @property when - The when property will hold methods of “events” which will take place like render, click, hover, etc. */ public when = { /** * Visit a given url */ visit: (url: string) => { cy.visit(url); }, /** * Wait for a number of milliseconds. */ wait: (ms: number) => cy.wait(ms), /** * Wait for a specific request to complete. * @param alias */ waitForResponse: (alias: string) => cy.wait(`@${alias}`), /** * Wait for multiples requests to complete. * @param alias */ waitForResponses: (alias: string, responses: number) => cy.wait(Array(responses).fill(`@${alias}`)), /** * Wait for a last request to complete. */ waitForLastCall: (alias: string, timeout: number = 1000) => cy.waitIfHappens({ alias: `@${alias}`, timeout, lastCall: true }), /** * Wait for something to happen in the DOM. * Note! you should not have any asserts in the callback function. From cypress-wait-until documentation: * you cannot put assertions inside checkFunction. There is no way to avoid a test failure if an assertion throws an error. * You must manually check what the assertions would check for you. * The most common case is checking that an element exists or not * @example * ```ts * helper.when.waitUntil(() => * helper.get.elementByTestId(selector, index) * ); * ``` */ waitUntil: <ReturnType = any>( checkFunction: () => | ReturnType | Cypress.Chainable | PromiseLike<ReturnType>, options?: WaitUntilOptions ) => cy.waitUntil(checkFunction, options), /** * Fires native system click event. * * @example * ```ts * <button data-cy="move-right">Move</button> * helper.when.realClick('move-right') * ``` */ realClick: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).realClick(), /** * Click a DOM element. * * @example * ```ts * <button data-cy="move-right">Move</button> * helper.when.click('move-right') * ``` */ click: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).click({ force: true }), /** * * Double-click a DOM element. */ dblclick: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).dblclick(), /** * Right click a DOM element. * @param selector * @param index */ rightclick: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).rightclick(), /** * overrides native global functions related to time * allowing them to be controlled synchronously via helper.when.tick() * This includes controlling: * setTimeout * clearTimeout * setInterval * clearInterval * Date Objects * The clock starts at the unix epoch (timestamp of 0). * This means that when you instantiate new Date in your application, it will have a time of January 1st, 1970. */ clock: () => cy.clock(), /** * Fires native hover event. Yes, it can test :hover preprocessor. * @example * ```ts * helper.when.hover('consent-terms-agree') * ``` */ hover: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).realHover(), /** * Move time after overriding a native time function with helper.when.clock(). * helper.when.clock() must be called before helper.when.tick() * @example * ```ts * helper.when.clock(); * helper.when.click('login-button'); * helper.when.tick(2000); * ``` */ tick: (ms: number) => cy.tick(ms), /** * Focus on a DOM element. */ focus: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).focus(), /** * Blur a focused element. * This element must currently be in focus. * If you want to ensure an element is focused before blurring, * try using helper.when.focus() before helper.when.blur(). */ blur: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).blur(), /** * Clear the value of an input or textarea */ clear: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).clear(), /** * Type into a DOM element. */ type: (selector: string, keys: string, index: number = 0) => this.get.elementByTestId(selector, index).focus().type(keys), /** * Type tab (move to element with next tab-index) */ tab: (selector: string, index: number = 0) => this.get.element(selector, index).tab(), /** * Runs a sequence of native press event (via cy.press) Type event is global. Make sure that it is not attached to any field. */ realType: (selector: string, keys: string, index: number = 0) => this.get.elementByTestId(selector, index).realType(keys), /** * Scroll to the bottom. */ scrollToBottom: () => cy.scrollTo("bottom", { ensureScrollable: false }), /** * Check checkbox(es) or radio(s). * This element must be an html input element with type checkbox or radio. */ check: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).check({ force: true }), /** * Uncheck checkbox(es). */ uncheck: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).uncheck({ force: true }), /** * * Toggle radio(s) by selector * This element must be an html input element with type radio. */ toggleRadioBySelector: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index).check({ force: true }), /** * * Check radio(s). * This element must be an html input element with type radio. */ toggle: (index: number) => this.get.nthBySelector("radio", index, "type").check({ force: true }), /** * Select an option with specific text, value, or index within a select html element. */ selectOption: (selector: string, label: string, index: number = 0) => this.get.nthBySelector(selector, index).select(label), /** * Drag an element and drop it in target element * @example * ```ts * helper.when.dragAndDrop( * helper.get.elementByTestId('selected-item', 2), * helper.get.elementByTestId('available-items') * ) * ``` * @param element element to be dragged * @param targetElement target of drag operation */ dragAndDrop: ( element: Cypress.Chainable<JQuery<HTMLElement>>, targetElement: Cypress.Chainable<JQuery<HTMLElement>> ) => { element .realMouseDown({ button: "left", position: "center" }) .realMouseMove(0, 10, { position: "center" }); targetElement.realMouseMove(0, 0, { position: "center" }).realMouseUp(); }, /** * Scopes all subsequent cy commands to within this element * @example * helper.when.within(() => expect(get.emcLogo()).to.exist, 'company-logo') */ within: (fn: () => void, selector: string, index: number = 0) => this.get.elementByTestId(selector, index).within(fn) }; /** * @property get - The get property will hold methods which will give our tests access to the “output” of the component in a “black box” fashion */ public get = { /** * Get one or more DOM elements by selector. * @example * Get an element with shape="filter-grid" * ```ts * <clr-icon shape="filter-grid"></clr-icon> * helper.get.bySelector("filter-grid", "shape") * ``` * @param selector * @param [attribute = defaultDataAttribute (default is "data-cy")] */ bySelector: ( selector: string, attribute: string = this.options.defaultDataAttribute! ) => cy.get(`[${attribute}="${selector}"]`), /** * Get A DOM element at a specific index from elements. * @example * // Get the 3rd checkbox * ```ts * helper.get.nthBySelector("checkbox", 3, "type") * ``` * @param selector * @param [index=0] * @param [attribute= defaultDataAttribute (default is "data-cy")] */ nthBySelector: ( selector: string, index: number, attribute: string = this.options.defaultDataAttribute! ) => this.get.bySelector(selector, attribute).eq(index), /** * Returns specific environment variable or undefined * @example * // Keeping password in cypress.config file * ```ts * e2e: { * env: { * password: "Changeme@1", * } * } * ``` * // using password during test * ```ts * helper.get.env("password"); * ``` */ env: (key: string) => Cypress.env(key), /** * Get the current URL of the page that is currently active. * @returns {Cypress.Chainable<string>} */ currentLocation: (): Cypress.Chainable<string> => cy.url(), /** * Returns element's style attribute * * @param selector * @param attributeName * @param [index = 0] * @returns {Cypress.Chainable<string>} */ elementsStyleAttribute: ( selector: string, attributeName: string, index: number = 0 ) => this.waitUntilLoadBeforeInvocation(() => this.get.elementByTestId(selector, index).invoke("css", attributeName) ), /** * * @param selector * @param propertyName * @param [index = 0] * @returns */ elementsProperty: ( selector: string, propertyName: keyof JQuery<HTMLElement>, index: number = 0 ) => this.waitUntilLoadBeforeInvocation(() => this.get.elementByTestId(selector, index).invoke(propertyName) ), /** * Returns element's computed style, including pseudo elements * * @param selector * @param [index = 0] * @param [pseudoElement] * @returns {Cypress.Chainable<CSSStyleDeclaration>} */ elementsComputedStyle: ( selector: string, index: number = 0, pseudoElement?: string ): Cypress.Chainable<CSSStyleDeclaration> => this.get .elementByTestId(selector, index) .then($element => window.getComputedStyle($element.get(0), pseudoElement) ), /** * @example * ```ts * expect(helper.get.elementsText("parent-job-name", 3).should("include", "Job 3 Name")) * ``` * @param selector * @param [index = 0] * @returns {Cypress.Chainable<string>} */ elementsText: ( selector: string, index: number = 0 ): Cypress.Chainable<string> => this.waitUntilLoadBeforeInvocation(() => this.get.elementByTestId(selector, index).invoke("text") ), /** * Get value of input element * @example * ```ts * expect(helper.get.inputValue('credentials-password').should("eq","initial password")); * ``` * @param selector * @param [index = 0] * @returns { Cypress.Chainable<string | number | string[]> } */ inputValue: ( selector: string, index: number = 0 ): Cypress.Chainable<string | number | string[]> => this.waitUntilLoadBeforeInvocation(() => this.get.elementByTestId(selector, index).invoke("val") ), /** * Get A DOM element at a specific index from elements. * @example * ```ts * helper.when.dragAndDrop( * helper.get.elementByTestId('selected-item', 2), * helper.get.elementByTestId('available-items') * ``` * @param selector * @param [index = 0] */ elementByTestId: (selector: string, index: number = 0) => this.options.handleSlotShadowDOM && selector.endsWith(`-${this.options.shadowSlotSuffix}`) ? this.get.nthBySelector(selector, index).then(slot => cy.wrap( Cypress.$(slot as JQuery<HTMLSlotElement>) .get(0) .assignedNodes()[0].parentElement! ) ) : this.get.nthBySelector(selector, index), /** * Get the element currently focused in the document. * @returns {Cypress.Chainable<JQuery<HTMLElement>>} */ focusedElement: () => cy.focused(), /** * Get A DOM element at a specific index from elements. * Same as get.elementByTestId * @example * ```ts * helper.when.dragAndDrop( * helper.get.element('selected-item', 2), * helper.get.element('available-items') * ``` * @param selector * @param [index = 0] */ element: (selector: string, index: number = 0) => this.get.elementByTestId(selector, index), /** * Get the DOM element containing the text. * DOM elements can contain more than the desired text and still match. * Additionally, Cypress prefers some DOM elements over the deepest element found. * @example * ```ts * expect(helper.get.elementByText("Avamar")).to.exist; * ``` * @param content * @param [index = 0] */ elementByText: (content: string | RegExp, index: number = 0) => cy.contains(content).eq(index), /** * Get number of elements with a specific selector * @example * ```ts * expect(helper.get.numberOfElements("migrated-vcenter").should("eq",2)); * ``` * @param selector * @returns {Cypress.Chainable<number>} */ numberOfElements: (selector: string): Cypress.Chainable<number> => this.get.bySelector(selector).its("length"), /** * @example * ```ts * expect(helper.get.elementsAttribute('avatar-picture', 'style').should("include", 'background-image: url("assets/avatar/def-user-male.png")')) * ``` * @param selector * @param attributeName * @param [index = 0] * @returns {Cypress.Chainable<string | undefined>} */ elementsAttribute: ( selector: string, attributeName: string, index = 0 ): Cypress.Chainable<string | undefined> => this.waitUntilLoadBeforeInvocation(() => this.get.elementByTestId(selector, index).invoke("attr", attributeName) ), /** * Get fixture * @param alias * @example * ```ts * given.fixture("user.json", "user"); * expect( * get.fixture("user").should("deep.nested.include", { * name: "Jane Doe", * id: "1234", * nested: { * attr1: "something", * attr2: "the other thing" * } * }) * ); * ``` */ fixture: (alias: string) => cy.get(`@${alias}`), /** * Get intercepted response's header * @param alias * @returns { Cypress.Chainable<{ [key: string]: string | string[]}>} */ responseHeader: ( alias: string ): Cypress.Chainable<{ [key: string]: string | string[]; }> => this.when.waitForResponse(alias).then(xhr => xhr.response!.headers), /** * Get intercepted response's body * If a JSON Content-Type was used and the body was valid JSON, this will be an object. * If the body was binary content, this will be a buffer. * @param alias * @returns {Cypress.Chainable<any>} */ responseBody: (alias: string): Cypress.Chainable<any> => this.when.waitForResponse(alias).then(xhr => xhr.response!.body), /** * Get intercepted request's body * If a JSON Content-Type was used and the body was valid JSON, this will be an object. * If the body was binary content, this will be a buffer. * @param alias * @returns {Cypress.Chainable<any>} */ requestBody: (alias: string): Cypress.Chainable<any> => this.when.waitForResponse(alias).then(xhr => xhr.request.body), /** * Get intercepted request's url * @param alias * @returns {Cypress.Chainable<string>} */ requestUrl: (alias: string): Cypress.Chainable<string> => this.when.waitForResponse(alias).then(xhr => xhr.request.url), /** * Get intercepted request's header * @param alias * @returns { Cypress.Chainable<{ [key: string]: string | string[]}>} */ requestHeader: ( alias: string ): Cypress.Chainable<{ [key: string]: string | string[] }> => this.when.waitForResponse(alias).then(xhr => xhr.request.headers), /** * Get intercepted request's query param * @param alias * @param queryParam * @returns { Cypress.Chainable<{[k: string]: string;}>} */ requestQueryParams: ( alias: string ): Cypress.Chainable<{ [k: string]: string }> => this.when .waitForResponse(alias) .then(xhr => Object.fromEntries( new URLSearchParams(new URL(xhr.request.url).search) ) ), /** * Get spy by alias * @param name * @returns */ spy: (name: string) => cy.get(`@${name}Spy`), /** * Get spy by function name alias * @param func * @returns */ spyFromFunction: (func: Function) => cy.get(`@${func.name}`), /** * Get stub by alias * @param name * @returns */ stub: (name: string) => cy.get(`@${name}`) }; }
import functools import inspect import warnings from argparse import ArgumentParser try: from pyrootutils import setup_root except ImportError: setup_root = None def with_argparse(func): return _with_argparse(func, ignore_mapping=set()) def with_opt_argparse(*, ignore_mapping: set[str] = None, setup_cwd: bool = False): def decorator(func): return _with_argparse(func, ignore_mapping=ignore_mapping or set(), setup_cwd=setup_cwd) return decorator def _with_argparse(func, *, ignore_mapping: set[str], setup_cwd=False): @functools.wraps(func) def inner(*inner_args, **inner_kwargs): if setup_cwd: if setup_root is not None: setup_root(search_from=__file__, cwd=True, pythonpath=True) else: warnings.warn("Could not import setup_root from pyrootutils. Using 'setup_cwd=True' requires installing" "pyrootutils") info = inspect.getfullargspec(func) args = ArgumentParser() mappings = {} def add_argument(x, typ, default, required): nonlocal mappings if typ in {list[str], list[int]} and x.endswith("s") and x not in ignore_mapping: mappings[x[:-1]] = x x = x[:-1] if typ == bool: default = default if default is not None else False if default: mappings["no_" + x] = x args.add_argument(f"--no_" + x, action="store_false", default=default) else: args.add_argument(f"--" + x, action="store_true", default=default) elif typ == list[str]: args.add_argument("--" + x, type=str, default=default, required=required, nargs="+") elif typ == list[int]: args.add_argument("--" + x, type=int, default=default, required=required, nargs="+") else: args.add_argument("--" + x, type=typ, default=default, required=required) defaults = tuple(None for _ in range(len(info.args) - len(info.defaults or []))) if info.defaults: defaults = defaults + info.defaults else: defaults = defaults + tuple(None for _ in range(len(info.args))) for i, arg in enumerate(info.args or []): if i < len(inner_args): continue assert arg in info.annotations arg_type = info.annotations[arg] arg_default = defaults[i] arg_required = info.defaults is None or len(info.defaults) <= (len(info.args) - (i + 1)) add_argument(arg, arg_type, arg_default, arg_required) for i, arg in enumerate(info.kwonlyargs or []): if arg in inner_kwargs: continue assert arg in info.annotations arg_type = info.annotations[arg] arg_default = info.kwonlydefaults.get(arg, None) if info.kwonlydefaults is not None else None arg_required = info.kwonlydefaults is None or arg not in info.kwonlydefaults add_argument(arg, arg_type, arg_default, arg_required) args = args.parse_args() args_dict = dict() for k, v in args.__dict__.items(): if k in mappings: args_dict[mappings[k]] = v else: args_dict[k] = v return func(*inner_args, **args_dict, **inner_kwargs) return inner