text
stringlengths
184
4.48M
// // Created by Michał on 2018-06-04. // #ifndef JIMP_EXERCISES_SEQUENTIALGENERATOR_H #define JIMP_EXERCISES_SEQUENTIALGENERATOR_H #include <iostream> template<class T, class U> class SequentialIdGenerator { U id; bool first; public: SequentialIdGenerator() { id = 0; first = true; }; ~SequentialIdGenerator() {}; SequentialIdGenerator(U id) : id{id}, first{true} {}; operator int() { return int(id); } int NextValue() { if (first) { first = false; return int(id); } else { ++id; return int(id); } } }; #endif //JIMP_EXERCISES_SEQUENTIALGENERATOR_H
import json import pandas as pd def json_to_table(path_to_json): # Загружаем JSON данные из файла with open(path_to_json, 'r') as file: data = json.load(file) # Извлекаем список бенчмарков benchmarks = data["benchmarks"] # Создаем DataFrame из списка бенчмарков df = pd.DataFrame(benchmarks, columns=["name", "real_time", "cpu_time"]) df[['algorithm_dataset', 'sample', 'iterations']] = df['name'].str.split('/', expand=True) df = df.drop(['name', 'iterations'], axis=1) df['sample'] = df['sample'].str.split('-', expand=True)[1] df[['algorithm', 'dataset']] = df['algorithm_dataset'].str.rsplit('_', expand=True, n=1) df = df.drop(['algorithm_dataset'], axis=1) df['algorithm'] = df['algorithm'] .str.split('_', expand=True)[1] df['real_time'] = df['real_time'].apply(lambda x : round(x, 2)) df['cpu_time'] = df['cpu_time'].apply(lambda x : round(x, 2)) column_order = ['algorithm', 'dataset', 'sample', 'real_time', 'cpu_time'] df = df[column_order] return df df = json_to_table("BM_iterative_google_web.json") for alg, table in df.groupby(by='algorithm'): table.sort_values(by='sample', ascending=True) if alg == "Hits": table.to_excel(f"./hits/my_cpp_hits_results_web.xlsx", index=False) elif alg == "Pagerank": table.to_excel(f"./pagerank/my_cpp_pagerank_results_web.xlsx", index=False) df = json_to_table("BM_iterative_movielens.json") for alg, table in df.groupby(by='algorithm'): table.sort_values(by='sample', ascending=True) if alg == "Hits": table.to_excel(f"./hits/my_cpp_hits_results_movielens.xlsx", index=False) elif alg == "Pagerank": table.to_excel(f"./pagerank/my_cpp_pagerank_results_movielens.xlsx", index=False)
import React from 'react'; // Définition des propriétés (props) que le composant Chip attend export interface ChipProps { type: 'checkbox' | 'radio'; // Soit une checkbox, soit un bouton radio label: string; // Étiquette à afficher à côté de l'input id: string; // Identifiant de l'input name: string; // Nom de l'input (utile pour les groupes de boutons radio) disabled?: boolean; // Optionnel: pour désactiver l'input } // Définition des propriétés (props) pour le composant RadioGroup export interface RadioGroupProps { children: React.ReactNode; // Contenu à afficher à l'intérieur du groupe (typiquement, plusieurs composants Chip) } // Définition du contexte pour les radios export interface RadioContextProps { selectedId: string | null; // ID du bouton radio sélectionné ou null si aucun n'est sélectionné setSelectedId: (id: string | null) => void; // Fonction pour mettre à jour l'ID du bouton radio sélectionné } // Typage pour le contexte export const RadioContext: React.Context<RadioContextProps | undefined>; // Composant RadioGroup export const RadioGroup: React.FC<RadioGroupProps>; // Composant Chip declare const Chip: React.FC<ChipProps>; export default Chip;
import React, { useEffect } from 'react'; import { useForm } from 'react-hook-form'; import { Link, useNavigate } from "react-router-dom"; import MainLayout from "../../components/MainLayout"; import { useMutation } from "@tanstack/react-query"; import toast from 'react-hot-toast'; import { useDispatch, useSelector } from 'react-redux'; import { userActions } from "../../store/reducers/userReducers"; import { signup } from "../../services/index/users"; const RegisterPage = () => { const navigate = useNavigate(); const dispatch = useDispatch(); const userState = useSelector(state => state.user); useEffect(() => { if (userState.userInfo) { navigate("/"); } }, [navigate, userState.userInfo]); const { register, handleSubmit, formState: { errors, isValid }, watch } = useForm({ defaultValues: { name: "", email: "", password: "", confirmPassword: "", }, mode: "onChange", }); const mutation = useMutation({ mutationFn: ({ name, email, password }) => signup({ name, email, password }), onSuccess: (data) => { dispatch(userActions.setUserInfo(data)); localStorage.setItem('account', JSON.stringify(data)); }, onError: (error) => { toast.error(error.message); console.log(error); }, }); const submitHandler = (data) => { mutation.mutate(data); }; const password = watch('password'); return ( <MainLayout> <section className='container mx-auto px-5 py-10'> <div className='w-full max-w-sm mx-auto'> <h1 className='font-roboto text-2xl font-bold text-center text-dark-hard mb-8'>Sign Up</h1> <form onSubmit={handleSubmit(submitHandler)}> <div className="flex flex-col mb-6 w-full"> <label htmlFor="name" className="text-[#5a7164] font-semibold block"> Name </label> <input type="text" id="name" {...register("name", { minLength: { value: 1, message: "Name length must be at least 1 character", }, required: { value: true, message: "Name is required", }, })} placeholder="Enter name" className={`placeholder:text-[#959ead] text-dark-hard mt-3 rounded-lg px-5 py-4 font-semibold block outline-none border border-[#c3cad9] ${errors.name ? "border-red-500" : "border-[#c3cad9]"}`} /> {errors.name?.message && (<p className='text-red-500 text-xs mt-1'>{errors.name?.message}</p>)} </div> <div className='flex flex-col mb-6 w-full'> <label htmlFor="email" className='text-[#5a7164] font-semibold block'>Email</label> <input type="email" id='email' {...register("email", { pattern: { value: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: "Enter a valid email", }, required: { value: true, message: "Email is required", } })} placeholder='Enter email' className={`placeholder:text-[#959ead] text-dark-hard mt-3 rounded-lg px-5 py-4 font-semibold block outline-none border ${errors.email ? "border-red-500" : "border-[#c3cad9]"}`} /> {errors.email && <p className='text-red-500 text-xs mt-1'>{errors.email.message}</p>} </div> <div className='flex flex-col mb-6 w-full'> <label htmlFor="password" className='text-[#5a7164] font-semibold block'>Password</label> <input type="password" id='password' {...register("password", { required: { value: true, message: "Password is required", }, minLength: { value: 6, message: "Password length must be at least 6 characters", }, })} placeholder='Enter password' className={`placeholder:text-[#959ead] text-dark-hard mt-3 rounded-lg px-5 py-4 font-semibold block outline-none border ${errors.email ? "border-red-500" : "border-[#c3cad9]"}`} /> {errors.password && <p className='text-red-500 text-xs mt-1'>{errors.password.message}</p>} </div> <div className='flex flex-col mb-6 w-full'> <label htmlFor="confirmPassword" className='text-[#5a7164] font-semibold block'>Confirm Password</label> <input type="password" id='confirmPassword' {...register("confirmPassword", { required: { value: true, message: "Confirm password is requierd" }, validate: (value) => { if (value !== password) { return "Password do not match"; } }, })} placeholder='Enter Confirmation Password' className={`placeholder:text-[#959ead] text-dark-hard mt-3 rounded-lg px-5 py-4 font-semibold block outline-none border ${errors.email ? "border-red-500" : "border-[#c3cad9]"}`} /> {errors.confirmPassword && <p className='text-red-500 text-xs mt-1'>{errors.confirmPassword.message}</p>} </div> <button type="submit" disabled={!isValid} className="bg-primary text-white font-bold text-lg py-4 px-8 w-full rounded-lg mb-6 disabled:opacity-70 disabled:cursor-not-allowed" Z>Register</button> <p className='text-sm font-semibold text-[#5a7184]'>You have an account? <Link to="/login" className='text-primary'> Login now</Link> </p> </form> </div> </section> </MainLayout> ) } export default RegisterPage;
package io.springbatch.job; import io.springbatch.step.tasklet.CustomTasklet; import lombok.RequiredArgsConstructor; import org.springframework.batch.core.*; import org.springframework.batch.core.job.builder.FlowBuilder; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.job.flow.Flow; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.core.step.job.DefaultJobParametersExtractor; import org.springframework.batch.item.*; import org.springframework.batch.item.support.ListItemReader; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.PlatformTransactionManager; import java.util.Arrays; @Configuration @RequiredArgsConstructor public class StepExampleJobConfiguration { @Bean public Job stepJob(JobRepository jobRepository, @Qualifier("taskletStep") Step taskletStep, @Qualifier("customTaskletStep") Step customTaskletStep, @Qualifier("chunkStep") Step chunkStep, @Qualifier("jobStep") Step jobStep, @Qualifier("paritionerStep") Step paritionerStep) { return new JobBuilder("stepJob", jobRepository) .incrementer(new RunIdIncrementer()) .start(taskletStep) .next(customTaskletStep) .next(chunkStep) .next(jobStep) //.next(paritionerStep) .build(); } @Bean(name="taskletStep") public Step taskletStep(JobRepository jobRepository, PlatformTransactionManager tx) { return new StepBuilder("taskletStep", jobRepository) .tasklet((contribution, chunkContext) -> { // 익명 클래스로 생성하는 방법. System.out.println("tasklet Step has executed!"); return RepeatStatus.FINISHED; }, tx).build(); } @Bean(name="customTaskletStep") public Step customTaskletStep(JobRepository jobRepository, PlatformTransactionManager tx) { return new StepBuilder("customTaskletStep", jobRepository) .tasklet(new CustomTasklet(), tx) .startLimit(3) // 최대 실행 가능 횟수 초과 시 StartLimitExceededExecption 발생 .allowStartIfComplete(true) // Step 이 성공했어도 다시 실행 하도록 설정하는 값. .listener(new StepExecutionListener() { @Override public void beforeStep(StepExecution stepExecution) { StepExecutionListener.super.beforeStep(stepExecution); System.out.println("before CustomTaskletStep."); } @Override public ExitStatus afterStep(StepExecution stepExecution) { System.out.println("After CustomTaskletStep."); return StepExecutionListener.super.afterStep(stepExecution); } }) .build(); } @Bean(name="chunkStep") public Step chunkStep(JobRepository jobRepository, PlatformTransactionManager tx) { return new StepBuilder("chunkStep", jobRepository) .<String, String>chunk(2, tx) .reader(new ListItemReader<>(Arrays.asList("item1", "item2", "item3", "item4", "item5"))) .processor(new ItemProcessor<String, String>() { @Override public String process(String item) throws Exception { return item.toUpperCase(); } }) .writer(new ItemWriter<String>() { @Override public void write(Chunk<? extends String> chunk) throws Exception { chunk.forEach(item -> System.out.println(item)); } }) .build(); } @Bean(name="paritionerStep") public Step partitionerStep(JobRepository jobRepository, PlatformTransactionManager tx) { return new StepBuilder("partitionerStep", jobRepository) .partitioner(taskletStep(jobRepository, tx)) .gridSize(2) .build(); } @Bean(name="jobStep") public Step jobStep(JobRepository jobRepository, PlatformTransactionManager tx, JobLauncher jobLauncher) { return new StepBuilder("jobStep", jobRepository) .job(childJob(jobRepository, tx)) .launcher(jobLauncher) .parametersExtractor(jobParametersExtractor()) .listener(new StepExecutionListener() { @Override public void beforeStep(StepExecution stepExecution) { StepExecutionListener.super.beforeStep(stepExecution); stepExecution.getExecutionContext().putString("name", "user1"); } }) .build(); } @Bean(name="flowStep") public Step flowStep(JobRepository jobRepository, PlatformTransactionManager tx) { return new StepBuilder("flowStep", jobRepository) .flow(flowStepExampleFlow(jobRepository, tx)) .build(); } private Job childJob(JobRepository jobRepository, PlatformTransactionManager tx) { return new JobBuilder("childJob", jobRepository) .incrementer(new RunIdIncrementer()) .start(taskletStep(jobRepository, tx)) .build(); } private DefaultJobParametersExtractor jobParametersExtractor() { // StepExecution context 내의 값을 Child Job의 JobExecution context 의 값으로 변경시킴. // setKeys의 경우 stepExecution Context 내에 설정한 Key 값이 있으면 넣겠다는 의미(여기서는 name) DefaultJobParametersExtractor extractor = new DefaultJobParametersExtractor(); extractor.setKeys(new String[]{"name"}); return extractor; } private Flow flowStepExampleFlow(JobRepository jobRepository, PlatformTransactionManager tx) { FlowBuilder<Flow> flowBuilder = new FlowBuilder<>("flowStepExampleFlow"); flowBuilder.start(chunkStep(jobRepository, tx)).end(); return flowBuilder.build(); } }
import React, { useEffect, useState } from "react"; function Quiz({ data, setStop, setQuestion_number, question_number }){ //question update on UI by using some logic const[questions, setQuestions]=useState(null); //answers check by using usestste const[selectedAns, setSelectedAns]=useState(null); //className updated value const[className, setClassName]=useState("answer"); //fetching of questions by useEffect useEffect(()=>{ setQuestions(data[question_number-1]); }, [data, question_number]); const delay=(duration, callback)=>{ setTimeout(()=>{ callback(); }, duration); }; const handleClick=(a)=>{ setSelectedAns(a); setClassName("answer active"); delay(3000, ()=>setClassName(a.correct? "answer correct" : "answer wrong") ); //code for update the questions on the UI screen....................................................... delay(6000, ()=>{ if(a.correct){ setQuestion_number((prev)=>prev+1); setSelectedAns(null); } else{ setStop(true); } }); }; return( <div className="quiz"> <div className="questions">{questions?.questions}</div> <div className="answers"> {questions?.answers.map((a)=>( <div className={selectedAns===a? className: "answer"} onClick={()=>handleClick(a)}>{a.text}</div> ))} </div> </div> ) } export default Quiz;
💻 [AWS] EC2 AMI ![](https://images.velog.io/images/dustjs159/post/c7223c11-14b1-4ee6-8f75-af02079aaa05/%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202022-01-09%20%E1%84%8B%E1%85%A9%E1%84%92%E1%85%AE%2011.02.18.png) * AMI(Amazon Machine Image) : 인스턴스를 생성하기 위해 필요한 운영체제와 그 외 필요한 소프트웨어들(웹 서버 Nginx 등)이 설치된 이미지 * AWS에서 제공하는 AMI를 커스터마이징하여 동일한 구성의 여러 인스턴스를 찍어내듯 생성 가능(필요한 소프트웨어를 인스턴스 생성할 때마다 설치하지 않아도 됨) * EC2 생성 시 선택할 수 있는 AMI 종류 * Linux : Amazon Linux2, Red Hat Enterprise Linux, Ubuntu, SUSE Linux 등 * Windows : MS Windows Server * 이미 만들어져있는 AMI 외에 개인이 직접 제작하여 Marketplace에서 배포도 가능하며 이 경우에는 AMI가 안전하지 않을 수도 있기 때문에 배포자를 잘 확인하고 사용 * 계정 간 공유 가능 * 인스턴스에 필요한 소프트웨어 설치 및 보안 취약점을 조치한 골든 이미지를 통해 인스턴스 셋업 시간을 줄일 수 있음 * 골든 이미지 없이 작업하는 것은 상당히 괴롭다... ## AMI 생성하기 1. 인스턴스 생성 2. (선택)데이터 무결성을 위해 인스턴스 중지 3. AMI 생성 - Create Image 4. 인스턴스 생성 과정에서 AMI 선택 시, 3 에서 만들어둔 AMI 선택 ## 백업용으로 만들어둔 AMI로 인스턴스 복구할 때 루트 EBS 볼륨을 제외하고 추가 볼륨을 Attach 한 상태에서 (+ 인스턴스 내 `/etc/fstab`에 자동 마운트까지 등록된 상태) AMI를 만들었다고 가정하자. 정기적인 백업 정책을 통해 만들어둔 AMI로 인스턴스를 복구할 일이 생겨서 "Launch Instance From AMI"를 하면서 추가 볼륨은 필요 없었기에 Remove하고 인스턴스를 생성했다. 그리고 인스턴스에 접속해보니 .... 추가 볼륨이 Attach된 채로 인스턴스가 생성이 되었고 이를 제거하기 위해 마운트 해제 후 수동으로 볼륨을 detach했다. (비용을 조금이라도 줄이려고) 왜 그런지 찾아봤는데, AMI가 만들어지는 지점은 특정 시점의 스냅샷이기 때문에 원본 인스턴스의 특정 시점을 그대로 가져오는 것이였다. 따라서 콘솔에서 추가 볼륨을 Remove하는 것은 의미가 없었던 것..
#!/bin/python3 from pyspark.sql import SparkSession from pyspark.sql.types import * from pyspark.sql.functions import * import asyncio import socketio sio_client = socketio.AsyncClient() @sio_client.event async def connect(): print('I\'m connected sparkSqlStream.py') async def main(): spark = SparkSession \ .builder \ .appName("movie_python") \ .master("local[*]") \ .getOrCreate() spark.sparkContext.setLogLevel("ERROR") lines = spark\ .readStream\ .format("socket")\ .option("host", "localhost")\ .option("port", 9999)\ .load() words = lines.select( explode( split(lines.value, " ") ).alias("word") ) wordCounts = words.groupBy("word").count() query = wordCounts\ .writeStream\ .outputMode("complete")\ .format("console")\ .start() await sio_client.connect(url='http://localhost:8833', socketio_path='sockets') await sio_client.emit("chat", wordCounts) await sio_client.wait() query.awaitTermination() if __name__ == '__main__': asyncio.run(main())
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="scripts/angular.js"></script> </head> <body ng-app> <input type="checkbox" ng-model="showAds" /> Show Ads <dialog ng-open="showAds"> <img src="Images/1.jpg" width="400" height="200" /> </dialog> <form name="frmHome"> <table align="center" border="1" width="80%" height="300"> <tr align="center"> <td colspan="2">Online Tutorials</td> </tr> <tr height="300"> <td width="200"> <ul> <li><input type="checkbox" ng-model="js" /> JavaScript</li> <li><input type="checkbox" ng-model="ng" /> Angular JS</li> </ul> </td> <td> <details ng-open="js"> <summary>JavaScript</summary> <ol> <li>Variables</li> <li>Operators</li> <li>Functions</li> </ol> </details> <details ng-open="ng"> <summary>Angular JS</summary> <ol> <li>Directives</li> <li>Modules</li> <li>Controller</li> </ol> </details> </td> </tr> </table> </form> </body> </html>
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:iaudiometer/routes/route_name.dart'; import 'package:iaudiometer/utils/theme/light.dart'; import 'package:iaudiometer/views/clinic/clinician_detail/clinician_detail_ctrl.dart'; class ClinicianDetail extends StatefulWidget { const ClinicianDetail({super.key}); @override State<ClinicianDetail> createState() => _ClinicianDetailState(); } class _ClinicianDetailState extends State<ClinicianDetail> { @override Widget build(BuildContext context) { return GetBuilder<ClinicianDetailController>( init: ClinicianDetailController(), builder: (_) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( leading: InkWell( onTap: () => Get.back(), child: Icon( Icons.arrow_back_ios_new, color: lightColorScheme.onPrimary, ), ), elevation: 0, backgroundColor: Colors.white, centerTitle: true, title: const Text( "CLINICIAN DETAILS", style: TextStyle( color: Colors.black, ), ), ), body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Container( width: 65, height: 65, decoration: BoxDecoration( color: Colors.grey.shade300, borderRadius: BorderRadius.circular(6), ), ).marginOnly(right: 15), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _.args["title"] ?? '', overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 20, fontWeight: FontWeight.w500, ), ), ], ), ) ], ).marginOnly(top: 10), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Email ID", style: GoogleFonts.poppins( fontSize: 17, fontWeight: FontWeight.w600, ), ), Text( "catalystclinic@gmail.com", style: GoogleFonts.poppins(color: Colors.grey.shade600), ), ], ).marginOnly(bottom: 25, top: 30), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Certificate Name", style: GoogleFonts.poppins( fontSize: 17, fontWeight: FontWeight.w600, ), ), Text( "Name here", style: GoogleFonts.poppins(color: Colors.grey.shade600), ), ], ).marginOnly(bottom: 25), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Degree Name", style: GoogleFonts.poppins( fontSize: 17, fontWeight: FontWeight.w600, ), ), Text( "PhD - Research", style: GoogleFonts.poppins(color: Colors.grey.shade600), ), ], ).marginOnly(bottom: 25), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "PCP", style: GoogleFonts.poppins( fontSize: 17, fontWeight: FontWeight.w600, ), ), Text( "Option-1", style: GoogleFonts.poppins(color: Colors.grey.shade600), ), ], ).marginOnly(bottom: 25), Row( children: [ GestureDetector( onTap: () { Get.toNamed(AppRouteNames.addEditClinician, arguments: {"isEdit": true}); }, child: Container( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14), decoration: BoxDecoration( color: lightColorScheme.primary, borderRadius: BorderRadius.circular(30), ), child: const Text( "EDIT", style: TextStyle( fontSize: 16, fontWeight: FontWeight.w500, ), ), ).marginOnly(right: 20), ), Container( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14), decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(30), ), child: const Text( "DELETE CLINICIAN", style: TextStyle( fontSize: 16, color: Colors.white, fontWeight: FontWeight.w500, ), ), ) ], ) ], ), ], ).paddingSymmetric(horizontal: 20), ); }, ); } }
@extends('layouts.master') @section('content') <div class="row"> <div class="mx-auto offset-3"> <h1>Sign Up</h1> @if(count($errors) > 0) <div class="alert alert-danger"> @foreach($errors->all() as $error) <p>{{ $error }}</p> @endforeach </div> @endif <form name="my-form" onsubmit="return validform()" action="{{ route('user.signup') }}" method="post"> <div class="form-group row"> <label for="name" class="col-md-4 col-form-label text-md-right">Όνομα:</label> <div class="col-md-6"> <input type="text" id="name" class="form-control" name="name"> </div> @error('name') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group row"> <label for="surname" class="col-md-4 col-form-label text-md-right">Επώνυμο:</label> <div class="col-md-6"> <input type="text" id="surname" class="form-control" name="surname"> </div> @error('surname') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group row"> <label for="password" class="col-md-4 col-form-label text-md-right">Κωδικός:</label> <div class="col-md-6"> <input type="password" id="password" class="form-control" name="password"> <input type="checkbox" onclick="passwordfunction()">Εμφάνιση κωδικού <script>function passwordfunction() { var x = document.getElementById("password"); if (x.type === "password") { x.type = "text"; } else { x.type = "password"; } }</script> </div> <div class="container"><p class="text-muted" text-align="center">.<br></p></div> @error('password') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group row"> <label for="password_confirmation" class="col-md-4 col-form-label text-md-right">Επιβεβαίωση Κωδικού:</label> <div class="col-md-6"> <input type="text" id="password_confirmation" class="form-control" name="password_confirmation"> <input type="checkbox" onclick="confirmfunction()">Εμφάνιση κωδικού <script>function confirmfunction() { var x = document.getElementById("password_confirmation"); if (x.type === "password") { x.type = "text"; } else { x.type = "password"; } }</script> </div> @error('password_confirmation') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group row"> <label for="email" class="col-md-4 col-form-label text-md-right">E-Mail:</label> <div class="col-md-6"> <input type="text" id="email" class="form-control @error('email') is-invalid @enderror" name="email" required autocomplete="email"> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="email-confirm" class="col-md-4 col-form-label text-md-right">Επιβεβαίωση e-mail</label> <div class="col-md-6"> <input id="email-confirm" type="email" class="form-control" name="email_confirmation"> </div> </div> <div class="form-group row"> <label for="phone" class="col-md-4 col-form-label text-md-right">Τηλεφωνικός αριθμός:</label> <div class="col-md-6"> <input id="phone" type="telephone" class="form-control @error('phone') is-invalid @enderror" name="phone" > @error('phone') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <!-- <div class="form-group row"> <label for="stathero" class="col-md-4 col-form-label text-md-right">Σταθερό τηλέφωνο(προαιρετικό):</label> <div class="col-md-6"> <input type="tel" class="form-control @error('stathero') is-invalid @enderror" name="telephone"> @error('stathero') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> --> <div class="form-group row"> <label for="address" class="col-md-4 col-form-label text-md-right">Διεύθυνση:</label> <div class="col-md-6"> <input type="text" name="address" id="address" class="form-control"> </div> @error('address') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group row"> <label for="city" class="col-md-4 col-form-label text-md-right">Πόλη:</label> <div class="col-md-6"> <input type="city" name="city" id="city" class="form-control"> </div> @error('city') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group row"> <label for="zip" class="col-md-4 col-form-label text-md-right">Ταχυδρομικός Κώδικας:</label> <div class="col-md-6"> <input id="zip" name="zip" type="number" class="form-control"> </div> @error('zip') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <!-- <div class="form-group row"> <label for="vatnumber" class="col-md-4 col-form-label text-md-right">ΑΦΜ:</label> <div class="col-md-6"> <input type="text" id="number" name="number" class="form-control"> <div class="container"><p class="text-muted">Προαιρετικό</p></div> </div> @error('vatnumber') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> --> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary"> Εγγραφή </button> {{ csrf_field() }} </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> @endsection
<div> <h2> <span jhiFnmTranslate="sfdApp.serviceUser.home.title">Service Users</span> <button class="btn btn-primary float-right create-service-user" [routerLink]="['/entity','service-user', { outlets: { popup: ['service-user-new'] } }]"> <span class="fa fa-plus"></span> <span class="hidden-sm-down" jhiFnmTranslate="sfdApp.serviceUser.home.createLabel"> Create new Service User </span> </button> </h2> <jhi-alert></jhi-alert> <div class="row"> <div class="col-sm-12"> <form name="searchForm" class="form-inline"> <div class="input-group w-100 mt-3"> <input type="text" class="form-control" [(ngModel)]="currentSearch" id="currentSearch" name="currentSearch" placeholder="{{ 'sfdApp.serviceUser.home.search' | fnmtranslate : langue.lang | async }}"> <button class="btn-floating waves-effect waves-light" (click)="search(currentSearch)"> <span class="fa fa-search"></span> </button> <button class="btn-floating waves-effect waves-light" (click)="clear()" *ngIf="currentSearch"> <span class="fa fa-trash-o"></span> </button> </div> </form> </div> </div> <br/> <ng-template #elseBlock> <div class="ui active centered inline loader"> {{principal.loading}} </div> </ng-template> <div class="table-responsive" *ngIf="serviceUsers;else elseBlock"> <table class="bordered striped highlight"> <thead> <tr jhiSort [(predicate)]="predicate" [(ascending)]="reverse" [callback]="transition.bind(this)"> <!-- <th jhiSortBy="reference"><span jhiFnmTranslate="sfdApp.serviceUser.reference">Reference</span> <span class="fa fa-sort"></span></th> --> <th><span>Nom</span></th> <th><span>Prénoms</span></th> <th class="text-right">Actions</th> </tr> </thead> <tbody> <tr *ngFor="let serviceUser of serviceUsers | recherche:currentSearch"> <!-- <td>{{serviceUser.reference}}</td> --> <td>{{serviceUser.first_name}}</td> <td>{{serviceUser.last_name}}</td> <td class="text-right"> <div class="btn-group flex-btn-group-container"> <button type="submit" [routerLink]="['/entity','service-user', serviceUser.id ]" class="btn btn-info btn-sm"> <span class="fa fa-eye"></span> <span class="hidden-md-down" jhiFnmTranslate="entity.action.view">View</span> </button> <button type="submit" [routerLink]="['/entity','service-user', { outlets: { popup: 'service-user/'+ serviceUser.id + '/edit'} }]" replaceUrl="true" class="btn btn-primary btn-sm"> <span class="fa fa-pencil"></span> <span class="hidden-md-down" jhiFnmTranslate="entity.action.edit">Edit</span> </button> <button type="submit" [routerLink]="['/entity','service-user', { outlets: { popup: 'service-user/'+ serviceUser.id + '/delete'} }]" replaceUrl="true" class="btn btn-danger btn-sm"> <span class="fa fa-remove"></span> <span class="hidden-md-down" jhiFnmTranslate="entity.action.delete">Delete</span> </button> </div> </td> </tr> </tbody> </table> </div> <div *ngIf="serviceUsers && serviceUsers.length"> <div class="row justify-content-center"> <!-- <jhi-item-count [page]="page" [total]="queryCount" [itemsPerPage]="itemsPerPage"></jhi-item-count> --> </div> <div class="row justify-content-center"> <ngb-pagination [maxSize]="5" [rotate]="true" [ellipses]="false" [boundaryLinks]="true" [collectionSize]="totalItems" [(page)]="page" (pageChange)="loadPage(page)" [pageSize]="itemsPerPage"></ngb-pagination> </div> </div> </div>
# RGB_data_transfer CONTENTS OF THIS FILE --------------------- * Introduction * Requirements * Installation * Configuration * Troubleshooting * FAQ * Maintainers INTRODUCTION ------------ This project is about VLC (Visible Light Communication). We use arduino uno boards and Adafruit TCS34725 RGB color sensors. We use RGB leds, each represents one bit of information. Thus at single cycle we will send 3 bits of information. * To submit bug reports and feature suggestions, or to track changes: yigitsuoglu@sabanciuniv.edu EQUIPMENTS ------------ This module requires the following equipments: * Arduino Board x2 * Jumpers * RGB LEDs (power LEDs are highly recommended) x2 * RGB light sensor (TCS34725) x2 * Tape * Breadboard x2 REQUIREMENTS ------------ * Not very bright environment * Undisturbed line of sight between the LEDs and RGB sensor. INSTALLATION ------------ * All libraries in the repository should be added to Arduino IDE. * Connect the power LEDs to corresponding pins (default values are 2,3,4 for rgb respectively) on the Arduino Board. Also, the color sensor (TCS34725) should be connected as specified here (https://cdn-shop.adafruit.com/datasheets/TCS34725.pdf). You can disable the LEDs on the light sensor by grounding the LED pin. * Repeat same process to other board. * Connect the Arduino boards to the computers. * Upload master.ino using Arduino IDE to the board. * Open serial monitors and change Baud to 250000. * Start calibration sequence with reserved word (default is MODE_sync). * Do the same processes for the other board. * Then enjoy slow chatting by the RGB LEDs with Arduino. CONFIGURATION ------------- Modes and default keywords: * MODE_sync: Sends calibration sequence. * MODE_recal: Listens for calibration sequence. * MODE_ledC: Enters LED opening mode. Input decimal equivalent of binary number formed as RGB. Input "quit" for quitting. * MODE_party: Randomly turns on/off LEDs. Change period with integers from 0 to 9. Input "quit" for quitting. * MODE_credits: Prints the team members in alphabetical order. TROUBLESHOOTING --------------- * If any LEDs or sensor does not work check your connections. * If calibration fails at mid-process, reset the Arduino. * If calibration values are not suitable for current environment do recalibration process. * If the system locks in mid-transmission reset transmitting Arduino. * If nonsense characters show up in serial monitor, ensure that Baud speed is set to 250000 (on the right bottom of the serial monitor). FAQ --- Q: I want to disable the LED on the sensor. Is there way to do this? A: Yes, this is possible. Simply by connecting the "LED" pin to ground will short-circuit it. Q: What is the bit rate of the system? A: 40 bits/sec. Q: Is there any way enchance the bit rate? A: It is not possible with current hardware without a more complex algorithm. MAINTAINERS ----------- Current maintainers: * Yiğit Süoğlu - https://github.com/suoglu * Baran Dereli - https://github.com/BaranDer * Özgün Şensoy - https://github.com/osensoy * Musab Çevik - https://github.com/musabc * Onur Çalık - https://github.com/calikonur This project has been sponsored by: * AirTies Wireless Networks AirTies was established in 2004 by an executive and technical equip who has returned to Turkey from the Silicon Valley with the aim of being the market leaders in Wireless Network Technologies. With its expert R&D team the company designs the hardware and software of their own products. Their products provide wireless high-definition data and media transfer on multiple TVs, notebooks, PC and game consoles. Their product portfolio includes wideband internet devices, local area network products, accesories and set top boxes. In total, AirTies has over 8 million products worldwide. Visit http://www.airties.com.tr for more information.
import { User } from "@/database/user.model" import { connectToDatabase } from "./mongoose" const bcrypt = require("bcrypt") import GoogleProvider from "next-auth/providers/google" import CredentialsProvider from "next-auth/providers/credentials" import GitHubProvider from "next-auth/providers/github" export const authOptions = { providers: [ GitHubProvider({ clientId: process.env.GITHUB_ID ?? "", clientSecret: process.env.GITHUB_SECRET ?? "", }), GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID ?? "", clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? "", }), CredentialsProvider({ name: "Credentials", credentials: { email: { label: "Email", type: "email" }, password: { label: "Password", type: "password" }, }, async authorize(credentials) { try { if (!credentials) return null await connectToDatabase() const user = await User.findOne({ email: credentials.email, }) if (!user) return null if ( !(await bcrypt.compare( credentials?.password, user.password )) ) return null return user } catch (error) { console.log(error) throw new Error("Error while authorizing") } }, }), ], callbacks: { async signIn({ profile, account }: any) { if ( account?.provider === "google" || account?.provider === "github" ) { try { await connectToDatabase() const userExists = await User.findOne({ email: profile.email, }) if (!userExists) { await User.create({ name: profile.name, email: profile.email, }) } return true } catch (error) { console.error("signIn error: ", error) throw new Error("Error while signing in") } } return true }, async session({ session, token }: any) { try { await connectToDatabase() const user = await User.findOne({ email: token.email, }) if (user) { session.user = { id: user._id.toString(), email: user.email, name: user.name, image: user.image, onboardingCompleted: user.onboardingCompleted, } } } catch (error) { console.error("signIn error: ", error) throw new Error("Error while signing in") } return session }, }, pages: { signIn: "/login", signOut: "/register", }, }
package com.example.tokopaerbe.home.store import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.tokopaerbe.R import com.example.tokopaerbe.core.retrofit.response.Product import com.example.tokopaerbe.databinding.ItemProductBinding import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.analytics.ktx.logEvent import com.google.firebase.ktx.Firebase import java.text.NumberFormat import java.util.Locale class ProductAdapter(private val onProductClick: (Product) -> Unit) : PagingDataAdapter<Product, ProductAdapter.ListViewHolder>(DIFF_CALLBACK) { private lateinit var firebaseAnalytics: FirebaseAnalytics companion object { private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Product>() { override fun areItemsTheSame( oldItem: Product, newItem: Product ): Boolean { return oldItem == newItem } override fun areContentsTheSame( oldItem: Product, newItem: Product ): Boolean { return oldItem.productName == newItem.productName } } } override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ListViewHolder { val binding = ItemProductBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false) return ListViewHolder(binding) } override fun onBindViewHolder(holder: ListViewHolder, position: Int) { val productData = getItem(position) if (productData != null) { holder.bind(productData) holder.itemView.setOnClickListener { onProductClick(productData) firebaseAnalytics = Firebase.analytics firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) { param(FirebaseAnalytics.Param.ITEM_LIST_ID, productData.productId) param(FirebaseAnalytics.Param.ITEM_LIST_NAME, productData.productName) } } } } class ListViewHolder(var binding: ItemProductBinding) : RecyclerView.ViewHolder(binding.root) { @SuppressLint("SetTextI18n") fun bind(productData: Product) { binding.apply { Glide.with(itemView) .load(productData.image) .placeholder(R.drawable.image_loading) .into(binding.itemImage) binding.itemTitle.text = productData.productName val itemPrice = formatPrice(productData.productPrice.toDouble()) binding.itemPrice.text = "Rp$itemPrice" binding.store.text = productData.store binding.ratingTerjual.text = "${productData.productRating} | Terjual ${productData.sale}" } } private fun formatPrice(price: Double): String { val numberFormat = NumberFormat.getNumberInstance( Locale( "id", "ID" ) ) // Use the appropriate locale for your formatting return numberFormat.format(price) } } }
import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; import { RecipesComponent } from './recipes/recipes.component'; import { LoggedInGuard } from 'ngx-auth-firebaseui'; import { ProfilePageComponent } from './user/profile-page/profile-page.component'; import { LoginPageComponent } from './user/login-page/login-page.component'; import { ShoppingListComponent } from './shopping-list/shopping-list.component'; import { RecipeEditComponent } from './recipe-edit/recipe-edit.component'; import { IngredientEditComponent } from './ingredients/ingredient-edit/ingredient-edit.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; import { PrintLayoutComponent } from './print/print-layout/print-layout.component'; import { PrintRecipeComponent } from './print/print-recipe/print-recipe.component'; import { PrintListComponent } from './print/print-list/print-list.component'; import { HistoryComponent } from './history/history.component'; const appRoutes: Routes = [ {path: '', component: RecipesComponent, canActivate: [LoggedInGuard] }, {path: 'profile', component: ProfilePageComponent, canActivate: [LoggedInGuard]}, {path: 'log-in', component: LoginPageComponent }, {path: 'recipes', component: RecipesComponent, canActivate: [LoggedInGuard]}, {path: 'shopping-cart', component: ShoppingListComponent, canActivate: [LoggedInGuard]}, {path: 'recipe-edit', component: RecipeEditComponent, canActivate: [LoggedInGuard]}, {path: 'ingredient-edit', component: IngredientEditComponent, canActivate: [LoggedInGuard]}, {path: 'history', component: HistoryComponent, canActivate: [LoggedInGuard]}, {path: '**', component: PageNotFoundComponent}, { path: 'print', outlet: 'print', component: PrintLayoutComponent, children: [ {path: 'recipe-print/:recipeIds', component: PrintRecipeComponent}, {path: 'shopping-print/:shoppingIds', component: PrintListComponent} ] } ]; @NgModule({ declarations: [], imports: [RouterModule.forRoot(appRoutes, {preloadingStrategy: PreloadAllModules})], exports: [RouterModule] }) export class AppRoutingModule { }
(function() { 'use strict'; angular .module('itinterviewApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider .state('question-master-statics', { parent: 'entity', url: '/question-master-statics', data: { authorities: ['ROLE_USER'], pageTitle: 'QuestionMasterStatics' }, views: { 'content@': { templateUrl: 'app/entities/question-master-statics/question-master-statics.html', controller: 'QuestionMasterStaticsController', controllerAs: 'vm' } }, resolve: { } }) .state('question-master-statics-detail', { parent: 'entity', url: '/question-master-statics/{id}', data: { authorities: ['ROLE_USER'], pageTitle: 'QuestionMasterStatics' }, views: { 'content@': { templateUrl: 'app/entities/question-master-statics/question-master-statics-detail.html', controller: 'QuestionMasterStaticsDetailController', controllerAs: 'vm' } }, resolve: { entity: ['$stateParams', 'QuestionMasterStatics', function($stateParams, QuestionMasterStatics) { return QuestionMasterStatics.get({id : $stateParams.id}).$promise; }], previousState: ["$state", function ($state) { var currentStateData = { name: $state.current.name || 'question-master-statics', params: $state.params, url: $state.href($state.current.name, $state.params) }; return currentStateData; }] } }) .state('question-master-statics-detail.edit', { parent: 'question-master-statics-detail', url: '/detail/edit', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/question-master-statics/question-master-statics-dialog.html', controller: 'QuestionMasterStaticsDialogController', controllerAs: 'vm', backdrop: 'static', size: 'lg', resolve: { entity: ['QuestionMasterStatics', function(QuestionMasterStatics) { return QuestionMasterStatics.get({id : $stateParams.id}).$promise; }] } }).result.then(function() { $state.go('^', {}, { reload: false }); }, function() { $state.go('^'); }); }] }) .state('question-master-statics.new', { parent: 'question-master-statics', url: '/new', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/question-master-statics/question-master-statics-dialog.html', controller: 'QuestionMasterStaticsDialogController', controllerAs: 'vm', backdrop: 'static', size: 'lg', resolve: { entity: function () { return { rightCount: null, wrongCount: null, upVoteCount: null, downVoteCount: null, eloRating: null, id: null }; } } }).result.then(function() { $state.go('question-master-statics', null, { reload: 'question-master-statics' }); }, function() { $state.go('question-master-statics'); }); }] }) .state('question-master-statics.edit', { parent: 'question-master-statics', url: '/{id}/edit', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/question-master-statics/question-master-statics-dialog.html', controller: 'QuestionMasterStaticsDialogController', controllerAs: 'vm', backdrop: 'static', size: 'lg', resolve: { entity: ['QuestionMasterStatics', function(QuestionMasterStatics) { return QuestionMasterStatics.get({id : $stateParams.id}).$promise; }] } }).result.then(function() { $state.go('question-master-statics', null, { reload: 'question-master-statics' }); }, function() { $state.go('^'); }); }] }) .state('question-master-statics.delete', { parent: 'question-master-statics', url: '/{id}/delete', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/question-master-statics/question-master-statics-delete-dialog.html', controller: 'QuestionMasterStaticsDeleteController', controllerAs: 'vm', size: 'md', resolve: { entity: ['QuestionMasterStatics', function(QuestionMasterStatics) { return QuestionMasterStatics.get({id : $stateParams.id}).$promise; }] } }).result.then(function() { $state.go('question-master-statics', null, { reload: 'question-master-statics' }); }, function() { $state.go('^'); }); }] }); } })();
#include<iostream> using namespace std; class Arrayx { public: int *Arr; int iSize; Arrayx(int i) { cout<<"Allocating memory for Array..."<<"\n"; iSize = i; Arr = new int[iSize]; } ~Arrayx() { cout<<"Deallocating memory for resources..."<<"\n"; delete []Arr; } void Accept() { cout<<"Enter the element of array: "<<"\n"; for(int iCnt = 0; iCnt < iSize; iCnt++) { cin>>Arr[iCnt]; } } void Display() { cout<<"Element of array are :"<<"\n"; for(int iCnt = 0; iCnt < iSize; iCnt++) { cout<<Arr[iCnt]<<"\t"; } cout<<"\n"; } }; int main() { int iLength = 0; cout<<"Enter the Size :"<<"\n"; cin>>iLength; Arrayx obj(iLength); // static obj.Accept(); obj.Display(); return 0; }
/* * Copyright © 2019-2023 Forb Yuan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package win.doyto.tpchchallenge.q10; import lombok.Getter; import lombok.Setter; import win.doyto.query.annotation.CompositeView; import win.doyto.query.annotation.GroupBy; import win.doyto.tpchchallenge.domain.customer.CustomerEntity; import win.doyto.tpchchallenge.domain.lineitem.LineItemEntity; import win.doyto.tpchchallenge.domain.nation.NationEntity; import win.doyto.tpchchallenge.domain.orders.OrdersEntity; import javax.persistence.Column; import java.math.BigDecimal; /** * ReturnedItemReportingView * * @author f0rb on 2023/2/18 * @since 1.0.1 */ @Getter @Setter @CompositeView({CustomerEntity.class, OrdersEntity.class, LineItemEntity.class, NationEntity.class}) public class ReturnedItemReportingView { @GroupBy private Integer c_custkey; @GroupBy private String c_name; @Column(name = "SUM(l_extendedprice * (1 - l_discount))") private BigDecimal revenue; @GroupBy private BigDecimal c_acctbal; @GroupBy private String n_name; @GroupBy private String c_address; @GroupBy private String c_phone; @GroupBy private String c_comment; }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { graphql } from 'react-apollo'; import { Form, message } from 'antd'; import { flowRight } from 'meteor/idreesia-common/utilities/lodash'; import { InputTextAreaField, FormButtonsSaveCancel, } from '/imports/ui/modules/helpers/fields'; import { SecuritySubModulePaths as paths } from '/imports/ui/modules/security'; import { SECURITY_VISITOR_BY_ID, UPDATE_SECURITY_VISITOR_NOTES } from '../gql'; class Notes extends Component { static propTypes = { match: PropTypes.object, history: PropTypes.object, location: PropTypes.object, loading: PropTypes.bool, visitorId: PropTypes.string, securityVisitorById: PropTypes.object, updateSecurityVisitorNotes: PropTypes.func, }; state = { isFieldsTouched: false, }; handleCancel = () => { const { history } = this.props; history.push(`${paths.visitorRegistrationPath}`); }; handleFieldsChange = () => { this.setState({ isFieldsTouched: true }); } handleFinish = ({ criminalRecord, otherNotes }) => { const { history, securityVisitorById, updateSecurityVisitorNotes, } = this.props; updateSecurityVisitorNotes({ variables: { _id: securityVisitorById._id, criminalRecord, otherNotes, }, }) .then(() => { history.push(`${paths.visitorRegistrationPath}`); }) .catch(error => { message.error(error.message, 5); }); }; render() { const { loading, securityVisitorById } = this.props; const isFieldsTouched = this.state.isFieldsTouched; if (loading) return null; return ( <Form layout="horizontal" onFinish={this.handleFinish} onFieldsChange={this.handleFieldsChange}> <InputTextAreaField fieldName="criminalRecord" fieldLabel="Criminal Record" initialValue={securityVisitorById.criminalRecord} required={false} /> <InputTextAreaField fieldName="otherNotes" fieldLabel="Other Notes" initialValue={securityVisitorById.otherNotes} required={false} /> <FormButtonsSaveCancel handleCancel={this.handleCancel} isFieldsTouched={isFieldsTouched} /> </Form> ); } } export default flowRight( graphql(UPDATE_SECURITY_VISITOR_NOTES, { name: 'updateSecurityVisitorNotes', options: { refetchQueries: ['pagedSecurityVisitors'], }, }), graphql(SECURITY_VISITOR_BY_ID, { props: ({ data }) => ({ ...data }), options: ({ match }) => { const { visitorId } = match.params; return { variables: { _id: visitorId } }; }, }) )(Notes);
# You are given an m x n integer matrix matrix with the following two properties: # Each row is sorted in non-decreasing order. # The first integer of each row is greater than the last integer of the previous row. # Given an integer target, return true if target is in matrix or false otherwise. # You must write a solution in O(log(m * n)) time complexity. # Example 1: # Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 # Output: true # Example 2: # Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 # Output: false class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix or not matrix[0]: return False m, n = len(matrix), len(matrix[0]) left, right = 0, m * n - 1 while left <= right: mid = (left + right) // 2 row, col = divmod(mid, n) if matrix[row][col] == target: return True elif matrix[row][col] < target: left = mid + 1 else: right = mid - 1 return False
import React, { useState } from "react"; import { Review } from "./app"; function ReviewListItem({review}: {review: Review}){ const [likeCount, setLikeCount] = useState(review.like); return ( <li className="review__list__item"> <p className="review__list__item__name">{review.username} さんの感想・評価</p> <p className="review__list__item__comment">{review.comment}</p> <p className="review__list__item__like"> <a href="#" className="review__list__item__like__button" onClick={()=> setLikeCount(likeCount + 1)}> &#x2764;️ {likeCount}件 </a> </p> </li> ); }; function ReviewList({reviews}: {reviews: Review[]}) { return ( <ul className="review__list"> {reviews.map(review => <ReviewListItem key={review.id} review={review} />)} </ul> ); }; export {ReviewList}
library(shiny) library(httr) library(sass) library(markdown) library(waiter) library(shinyjs) library(shinyCopy2clipboard) library(flexdashboard) library(XML) library(rvest) library(dplyr) library(stringr) library(writexl) library(readxl) library(tidyr) library(knitr) library(kableExtra) # Define UI for application ui <- dashboardPage( dashboardHeader(title = "Cryptocurrency Research App"), dashboardSidebar( width = 220, sidebarMenu( menuItem("Bitcoin", tabName = "bitcoin", icon = icon("bitcoin")), menuItem("Dashboard", tabName = "dashboard", icon = icon("chart-bar")), menuItem("ChatGPT", tabName = "chatgpt", icon = icon("comments")) )), dashboardBody( tabItems( tabItem("bitcoin", fluidRow( column(width = 12, box(width = NULL, uiOutput('tz'), plotlyOutput('period_graph', height = 250) )), column(width = 12, box(width = NULL, DT::dataTableOutput('return_table'), style = "height:400px; overflow-y: scroll" )) ) ), tabItem("dashboard", fluidRow( column(width = 12, box(width = NULL, uiOutput('tz'), plotlyOutput('period_graph', height = 250) )), column(width = 12, box(width = NULL, DT::dataTableOutput('return_table'), style = "height:400px; overflow-y: scroll" )) ) ), tabItem("chatgpt", fluidRow( column(width = 12, height = 300, box( tags$div( id = "chat-container", tags$div( id = "chat-header", tags$h3("ChatGPT") ), tags$div( id = "chat-history", uiOutput("chatThread"), ), tags$div( id = "chat-input", tags$form( column(12,textAreaInput(inputId = "prompt", label="", placeholder = "Send a message.", width = "100%")), fluidRow( tags$div(style = "margin-left: 1.5em;", actionButton(inputId = "submit", label = "Send", icon = icon("paper-plane")), actionButton(inputId = "remove_chatThread", label = "Clear History", icon = icon("trash-can")), CopyButton("clipbtn", label = "Copy", icon = icon("clipboard"), text = "") )) )) ) )) ) ) ) ) )
""" Core jird code. Includes representation of music, evaluation of parsed text into music, and basic functions on music. """ import logging import math import operator from abc import ABC, abstractmethod from dataclasses import dataclass from fractions import Fraction from functools import partial, reduce from itertools import chain from typing import Any, Callable, Iterable, List, Optional, Set, Tuple, TypeVar, Union from jird import constants from jird.parser import Lark_StandAlone, Token, Transformer logger = logging.getLogger(__name__) PARSER = Lark_StandAlone() # type: ignore[no-untyped-call] # Lark can generate a standalone parser to avoid a dependency on lark. # This can be generated from the grammar in jird.g by running # # $ python3 -m lark.tools.standalone --maybe_placeholders jird.g > parser.py # # For development it can be convenient to use lark itself to avoid # regenerating the standalone parser after each change to the grammar. # # Use imports and definitions below if using lark itself rather than standalone parser # # from pathlib import Path # from lark import Lark, Token, Transformer # # GRAMMAR = (Path(__file__).parent / "jird.g").read_text() # PARSER = Lark(GRAMMAR, maybe_placeholders=True, parser="lalr") Number = Union[Fraction, float] class Unevaluated(ABC): """Base class for unevaluated quantities.""" @abstractmethod def evaluate(self) -> Number: """Calculate actual value from unevaluated representation.""" def __le__(self, other: Union["Unevaluated", Number]) -> bool: return self.evaluate() <= evaluate(other) def __lt__(self, other: Union["Unevaluated", Number]) -> bool: return self.evaluate() < evaluate(other) def __ge__(self, other: Union["Unevaluated", Number]) -> bool: return self.evaluate() >= evaluate(other) def __gt__(self, other: Union["Unevaluated", Number]) -> bool: return self.evaluate() > evaluate(other) class RatioProduct(Unevaluated): """Unevaluated product of ratios.""" def __init__( self, ratios: Union[Tuple[Fraction, ...], Fraction, "RatioProduct"] = () ) -> None: """ Create unevaluated product of ratios. Ratios making up the product are stored in a tuple. This allows seeing how a given ratio was composed. Parameters ---------- ratios : tuple of Fraction or RatioProduct or Fraction Ratios making up the product. """ if isinstance(ratios, tuple): self.ratios = ratios elif isinstance(ratios, Fraction): self.ratios = (ratios,) elif isinstance(ratios, RatioProduct): self.ratios = ratios.ratios else: raise ValueError(ratios) def __repr__(self) -> str: return "*".join( f"{x.numerator}" if x.denominator == 1 else f"{x.numerator}/{x.denominator}" for x in self.ratios ) def evaluate(self) -> Fraction: """Calculate product of ratios.""" product = prod(self.ratios, Fraction(1)) assert isinstance(product, Fraction) return product def __mul__( self, other: Union["RatioProduct", Fraction, Tuple[Fraction, ...]] ) -> "RatioProduct": return RatioProduct(self.ratios + RatioProduct(other).ratios) def __rmul__( self, other: Union["RatioProduct", Fraction, Tuple[Fraction, ...]] ) -> "RatioProduct": return RatioProduct(RatioProduct(other).ratios + self.ratios) def __eq__(self, other: object) -> bool: if not isinstance(other, (RatioProduct, tuple, Fraction)): return False return self.ratios == RatioProduct(other).ratios @dataclass class Power(Unevaluated): """ Unevaluated power. The power is of the form `b**(m/n)` where `b`, `m`, and `n` are integers. Used for example to make number of steps in equal temperaments more obvious, e.g. 2**8/12 rather than 2**2/3. """ base: int exponent_numerator: int exponent_denominator: int def __repr__(self) -> str: return f"{self.base}**{self.exponent_numerator}/{self.exponent_denominator}" def evaluate(self) -> float: """Calculate value of power.""" power: float = self.base ** ( self.exponent_numerator / self.exponent_denominator ) return power def __rmul__(self, other: Union[RatioProduct, Fraction]) -> "Power": msg = "Multiplication not implemented for Power" raise NotImplementedError(msg, (self, other)) @dataclass(frozen=True) class MidiNote: """ Midi representation of a musical note. Attributes ---------- pitch : int Midi pitch number. Between 0 and 127. bend : int, optional Midi pitch bend number. Between 0 and 16383. ticks : int Number of midi ticks that the note lasts. velocity : int Midi note velocity (often mapped to loudness by synths). Between 0 and 127. """ pitch: int bend: Optional[int] ticks: int velocity: int def __post_init__(self) -> None: assert 0 <= self.pitch <= 127 if self.bend is not None: assert 0 <= self.bend <= 2**14 - 1 assert 0 <= self.velocity <= 127 @dataclass class Note: """ Individual musical note. A note here is characterized by its frequency (giving its pitch), its duration (giving how long it is played for), and its volume (giving how loud it sounds). Frequency, duration, and volume are given as a fraction of basic units which are left unspecified. Attributes ---------- frequency : RatioProduct or Fraction or Power Frequency ratio, e.g. 5/4. Real frequency of note is this frequency ratio multiplied by the basic frequency :math:`f_0`. duration : RatioProduct or Fraction Duration of note as a fraction of a basic time unit :math:`t_0`. The basic time unit can be chosen freely, e.g. to be the length of one bar or one whole note. volume : RatioProduct or Fraction Volume of note as a fraction of a reference volume. The reference volume 1/1 is mapped to midi volume 64. Notes ----- A rest is represented by a note with zero frequency. """ frequency: Union[RatioProduct, Fraction, Power] duration: Union[RatioProduct, Fraction] volume: Union[RatioProduct, Fraction] = Fraction(1) # noqa: RUF009 @property def cents(self) -> float: """ Calculate number of cents in the interval from 1 to the note's frequency. Returns ------- float Number of cents in interval from 1 to `frequency` rounded to three decimal places. Returns nan if the note has zero frequency (corresponding to a rest). Examples -------- There are about 700 cents in a just perfect fifth. >>> note = parse("3/2:1")[0][0] >>> note.cents 701.955 """ frequency = evaluate(self.frequency) return ( float("nan") if frequency == constants.REST_FREQUENCY else round(1200 * math.log2(frequency), 3) ) def __repr__(self) -> str: return ( f"Note(frequency={self.frequency}, cents={self.cents}, duration={self.duration}" + (f", volume={self.volume})" if self.volume != 1 else ")") ) def to_midi(self, *, f0: float, pitch_bend_range: int) -> MidiNote: """ Midi representation of `note`. Parameters ---------- f0 : float Basic frequency for computing real frequency of `note`. pitch_bend_range : int Number of semitones to assume max pitch bend corresponds to. Returns ------- MidiNote Midi representation of `note`. """ duration = evaluate(self.duration) # Assume basic jird time unit t0 represents one quarter note # Actual value of time unit t0 not needed here; real tempo is set by `tempo_track`. ticks = duration * constants.DIVISION assert int(ticks) == ticks ticks = int(ticks) real_frequency = evaluate(self.frequency) * f0 if real_frequency == 0: # Rest return MidiNote( pitch=0, bend=constants.PITCH_BEND_CENTER, ticks=ticks, velocity=0 ) # Express frequency as integer number of semitones (from middle C) plus remainder exact_semitones = 12 * math.log2(real_frequency / constants.MIDDLE_C_FREQUENCY) integer_semitones = round(exact_semitones) remainder = exact_semitones - integer_semitones # Pitch 60 is middle C in midi pitch = 60 + integer_semitones bend = round( constants.PITCH_BEND_CENTER + remainder * (constants.PITCH_BEND_MAX - constants.PITCH_BEND_CENTER) / pitch_bend_range ) velocity = min(round(evaluate(self.volume) * 64), 127) return MidiNote(pitch=pitch, bend=bend, ticks=ticks, velocity=velocity) Chord = Tuple[Note, ...] Part = List[Union[Note, Chord]] Piece = Tuple[Part, ...] Music = Union[Note, Chord, Part, Piece] def apply_to_notes(music: Music, f: Callable[[Note], Any]) -> Any: # noqa: ANN401 """ Apply a function `f` to each note in a `Music` object. Parameters ---------- music : Music Music containing the notes to apply `f` to. f : function Function to apply to each note. Returns ------- Any The `music` object with `f` applied to each note. Examples -------- Extract the cents for each note in some music. >>> music = parse("5/4:1 <1 3/2>:1") >>> apply_to_notes(music, lambda x: x.cents) ([386.314, (0.0, 701.955)],) Double duration of each note. >>> music = parse("7/6:1 4/3:1")[0] >>> music [Note(frequency=7/6, cents=266.871, duration=1), Note(frequency=4/3, cents=498.045, duration=1)] >>> f = lambda x: Note(frequency=x.frequency, duration=evaluate(Fraction(2) * x.duration)) >>> apply_to_notes(music, f) [Note(frequency=7/6, cents=266.871, duration=2), Note(frequency=4/3, cents=498.045, duration=2)] """ if isinstance(music, Note): return f(music) if isinstance(music, tuple): return tuple(apply_to_notes(x, f) for x in music) if isinstance(music, list): return [apply_to_notes(x, f) for x in music] raise ValueError(music) class NoteTransformer(Transformer[Token, Piece]): """ Transformer to convert an abstract syntax tree (AST) into a `Music` object. Each method is called on the corresponding node in the AST, so methods have the same names as elements of the grammar. The transformer works up the tree from the bottom. For more information see the Lark docs `here <https://lark-parser.readthedocs.io/en/latest/visitors.html#transformer>`_. """ def integer(self, children: List[Token]) -> int: """ Convert token (subclass of string) for integer to actual integer. Parameters ---------- children : list of Token List of exactly one string representing an integer. Returns ------- int Integer corresponding to single element of `children`. """ assert len(children) == 1 return int(children[0]) def ratio(self, children: List[Optional[int]]) -> RatioProduct: """ Convert pair of integers representing a ratio into the actual ratio. The ratio is returned as a `RatioProduct` in order to leave any later multiplications in a factored form, e.g. 5/4*3/2 will remain 5/4*3/2 rather than 15/8. This is because the factorization often comes from 'factoring out the root note' and so is musically useful to know. Parameters ---------- children : list of (int or None) The numerator and denominator of the ratio. If the denominator is None the numerator is returned. This allows handling both "3/2" and "2" as ratios. Returns ------- RatioProduct Ratio corresponding to integers in `children`. """ x, y = children assert x is not None return RatioProduct(Fraction(x, y)) def ratio_product(self, children: List[RatioProduct]) -> RatioProduct: """ Form product of ratios. Parameters ---------- children : list of RatioProduct Ratios to multiply. Returns ------- RatioProduct Product of ratios in `children`. """ product = prod(children, RatioProduct()) assert isinstance(product, RatioProduct) return product def mult_expr(self, children: List[Union[RatioProduct, Music]]) -> Music: """ Multiply frequencies of notes in music by a ratio. Parameters ---------- children : list of RatioProduct or Music Last element is the Music containing the notes to multiply the frequencies of. Preceding elements are ratios to multiply frequencies in the music by. Returns ------- Music Music with its note frequencies multiplied by given ratios. """ ratios = children[:-1] music = children[-1] # Establish types ratio_products = [] for x in ratios: assert isinstance(x, RatioProduct) ratio_products.append(x) assert not isinstance(music, RatioProduct) multiplier = prod(ratio_products, RatioProduct()) new_music: Music = apply_to_notes( music, lambda x: Note( frequency=RatioProduct(multiplier) * x.frequency, duration=x.duration, volume=x.volume, ), ) return new_music def power(self, children: List[Union[Music, RatioProduct]]) -> Music: """ Multiply note volume by exponent. Parameters ---------- children : list of Music or RatioProduct Two element list of music and exponent. Returns ------- Music Music with its volume multiplied. """ music, volume_multiplier = children assert not isinstance(music, RatioProduct) assert isinstance(volume_multiplier, RatioProduct) new_music: Music = apply_to_notes( music, lambda x: Note( frequency=x.frequency, duration=x.duration, volume=volume_multiplier * x.volume, # type: ignore[operator] ), ) return new_music def note(self, children: List[Optional[RatioProduct]]) -> List[Note]: """ Convert frequency, duration, and volume into corresponding note. Parameters ---------- children : list of RatioProduct Three element list containing frequency, duration, and volume of a note. Volume can be None. Returns ------- list of Note List containing a single `Note` of given frequency, duration, and volume. Volume is defaulted to one. """ frequency, duration, volume = children assert frequency is not None assert duration is not None return [ Note( frequency=frequency, duration=duration, volume=volume if volume is not None else Fraction(1), ), ] def chord(self, children: List[Optional[RatioProduct]]) -> List[Tuple[Note, ...]]: """ Convert list of frequencies, duration, and volume into the corresponding chord. Parameters ---------- children : list of RatioProduct List containing the frequencies of the notes in the chord along with the duration of the chord as the second last element and the volume as the last element. Volume can be None. Returns ------- list of tuple of Note List containing a single tuple of notes making up the given chord. """ frequencies = children[:-2] duration = children[-2] volume = children[-1] assert duration is not None notes = [] for f in frequencies: assert f is not None notes.append( Note( frequency=f, duration=duration, volume=volume if volume is not None else Fraction(1), ) ) return [tuple(notes)] def part(self, children: List[List[Music]]) -> List[Music]: """ Combine musics sequentially by forming a single list from them. Parameters ---------- children : list of list of Music List of individual musics to combine sequentially. Returns ------- list of Music Single list of all musics joined together. """ return list(chain.from_iterable(children)) def music(self, children: List[Music]) -> Tuple[Music, ...]: """ Combine musics simultaneously by forming a tuple of them. Parameters ---------- children : list of Music List of musics to combine simultaneously. Returns ------- tuple of Music Tuple of individual musics to be played simultaneously. """ return tuple(children) def parse(input_string: str) -> Piece: """ Parse text into music. Parameters ---------- input_string: str String containing the musical notation as text. Returns ------- Piece Music corresponding to the text in `input_string` Examples -------- One note. >>> parse("7/5:1") ([Note(frequency=7/5, cents=582.512, duration=1)],) Two notes in succession. >>> print_music(parse("2:1/4 6/5:1/4")) ( [ Note(frequency=2, cents=1200.0, duration=1/4), Note(frequency=6/5, cents=315.641, duration=1/4), ], ), A chord. >>> print_music(parse("<1 7/6 16/9>:1/4")) ( [ ( Note(frequency=1, cents=0.0, duration=1/4), Note(frequency=7/6, cents=266.871, duration=1/4), Note(frequency=16/9, cents=996.09, duration=1/4), ), ], ), """ tree = PARSER.parse(input_string) music = NoteTransformer().transform(tree) logger.info("Parsed music of total duration %d", total_duration(music)) return music def temper_note(note: Note, *, edo: int) -> Note: """ Temper single note. Approximates frequency of `note` by one of the frequencies obtained by splitting the octave into `edo` parts. Parameters ---------- note : Note Note to temper. edo : int Number of Equal Divisions of the Octave to select the tempered frequency from. For example `edo = 12` is the common equal temperament. Other popular values are 19, 31, and 53, but anything is possible and perhaps interesting. Returns ------- Note Closest approximation to `note` in a system of `edo` equal divisions of the octave. Examples -------- Consider a minor third (frequency ratio 6/5): >>> note = parse("6/5:1")[0][0] >>> note Note(frequency=6/5, cents=315.641, duration=1) Tempering with twelve notes gives three ordinary semitones, exactly 300 cents. >>> temper_note(note, edo=12) Note(frequency=2**3/12, cents=300.0, duration=1) Tempering with nineteen notes gives a very close approximation to the just frequency. >>> temper_note(note, edo=19) Note(frequency=2**5/19, cents=315.789, duration=1) Notes ----- A ratio product has each term tempered separately (rather than first multiplying terms then tempering). This is to preserve the tempered intervals within a chord when its frequency is multiplied. For example <1 5/4 11/8>:1 is tempered in 12EDO to 0, 4, 6 steps, but 80/81*<1 5/4 11/8>:1 would be tempered to 0, 4, 5 steps. From listening to automatically tempered just intonation music (e.g. megamorsel in music dir in this repo), this shifting of chord quality can sound strange. Tempering each term in a product separately makes sure that the intervals within the chord remain unchanged by multiplication. """ frequency = evaluate(note.frequency) if frequency == 0: return note if isinstance(note.frequency, RatioProduct): n = sum(round(edo * math.log2(x)) for x in note.frequency.ratios) else: n = round(edo * math.log2(frequency)) new_frequency = Power(2, n, edo) return Note(frequency=new_frequency, duration=note.duration, volume=note.volume) def temper(music: Piece, *, edo: Optional[int]) -> Piece: """ Temper all notes in music. Parameters ---------- music : Piece Music to temper. edo : int, optional Number of Equal Divisions of the Octave to use for tempering. No tempering done if `edo` is None. Returns ------- Piece Tempered version of `music`. """ if edo is None: return music logger.info("Tempering to %d edo", edo) tempered_music: Piece = apply_to_notes(music, partial(temper_note, edo=edo)) return tempered_music def evaluate(quantity: Union[Unevaluated, Number]) -> Number: """ Evaluate a quantity. For quantities which are `Unevaluated` call their `evaluate` to force evaluation. Parameters ---------- quantity : Unevaluated or Number quantity to evaluate. Returns ------- Number Evaluated quantity Examples -------- >>> quantity = RatioProduct((Fraction(5, 4), Fraction(6, 5))) >>> quantity 5/4*6/5 >>> evaluate(quantity) Fraction(3, 2) >>> evaluate(Fraction(7, 6)) Fraction(7, 6) """ if isinstance(quantity, Unevaluated): return quantity.evaluate() return quantity def total_duration(music: Music) -> Number: """ Find total duration of music. Takes largest duration if `music` contains simultaneous pieces of different duration. Parameters ---------- music : Music Music to find duration of. Returns ------- Number Total duration of music. Examples -------- >>> music = parse("7/6:1/4 4/3:1/4") >>> total_duration(music) Fraction(1, 2) >>> music = parse("2:1 3/2:1; 1/2:2") >>> total_duration(music) Fraction(2, 1) """ if isinstance(music, Note): return evaluate(music.duration) if isinstance(music, tuple): return max(total_duration(x) for x in music) if music else 0 if isinstance(music, list): return sum(total_duration(x) for x in music) if music else 0 raise ValueError(music) def frequencies_set(music: Music) -> Set[Number]: """ Find set of all frequencies used in `music`. Parameters ---------- music : Music Music to find frequencies in. Returns ------- set of {fraction or float} Set of all frequencies in `music` """ if isinstance(music, Note): frequency = evaluate(music.frequency) return {frequency} if frequency != 0 else set() return set(chain.from_iterable(frequencies_set(x) for x in music)) def all_frequencies(music: Music) -> List[Number]: """ Find all frequencies in `music`. Parameters ---------- music : Music Music to find frequencies in. Returns ------- list of [Fraction or float] List of all frequencies in `music` sorted from lowest to highest. Examples -------- Any products are evaluated so frequencies are given in their simplest form. >>> music = parse("1:1 5/4:1 4/3*5/4:1") >>> all_frequencies(music) [Fraction(1, 1), Fraction(5, 4), Fraction(5, 3)] This can be used to find a scale in which all notes in `music` can be found. >>> music = parse("10/9*<1 6/5 9/5>:1 3/2*<1 5/4>:1") >>> all_frequencies(music) [Fraction(10, 9), Fraction(4, 3), Fraction(3, 2), Fraction(15, 8), Fraction(2, 1)] """ return sorted(frequencies_set(music)) def height(music: Music) -> int: """ Measure of number of simultaneous notes in `music`. Used for example to assign enough midi channels to each part in :func:`jird.midi.music_to_midi_file`. Parameters ---------- music : Music Music to measure height of. Returns ------- int Measure of simultaneous height of `music`. Examples -------- >>> height(parse("<1 5/4 3/2 7/4>:1")) 4 >>> height(parse("<1 5/4 3/2 7/4>:1; 1/2:1")) 5 >>> height(parse("1:1/4 9/8:1/4 5/4:1/2; 1/2:1/2 3/4:1/2")) 2 """ if not music: return 0 if isinstance(music, Note): return 1 if isinstance(music, tuple): return sum(height(x) for x in music) if isinstance(music, list): return max(height(x) for x in music) raise ValueError(music) def lowest(music: Music) -> Number: """ Find lowest frequency in `music`. Parameters ---------- music : Music Music to containing frequencies to consider. Returns ------- Number Lowest frequency in `music`. """ if not music: return float("inf") if isinstance(music, Note): frequency = evaluate(music.frequency) # Rests have zero frequency so we should ignore them return frequency if frequency != 0 else float("inf") return min(lowest(x) for x in music) def print_music(music: Music, level: int = 0) -> None: """ Pretty print `music`. Parameters ---------- music : Music Music to be printed. level : int Indentation level. Defaults to 0. Used to indent nested pieces of music when `print_music` is called recursively. """ indent = " " if isinstance(music, Note): print(level * indent + f"{music},") elif isinstance(music, tuple): print(level * indent + "(") for x in music: print_music(x, level + 1) print(level * indent + "),") elif isinstance(music, list): print(level * indent + "[") for y in music: print_music(y, level + 1) print(level * indent + "],") else: raise ValueError(music) def interval_table(frequencies: Iterable[Number]) -> List[List[Number]]: """ Find interval between each pair of frequencies in `frequencies`. Parameters ---------- frequencies : iterable of Ratio Frequencies to find intervals between. Returns ------- list of list of Ratio All intervals between frequencies. Examples -------- >>> table = interval_table([Fraction(1), Fraction(5, 4), Fraction(3, 2)]) >>> for row in table: print(row) [Fraction(1, 1), Fraction(5, 4), Fraction(3, 2)] [Fraction(4, 5), Fraction(1, 1), Fraction(6, 5)] [Fraction(2, 3), Fraction(5, 6), Fraction(1, 1)] """ return [[evaluate(x / y) for x in frequencies] for y in frequencies] def print_interval_table(music: Music) -> None: """ Print interval table built from all frequencies in `music`. Parameters ---------- music : Music Music containing frequencies to build intervals from. Examples -------- >>> print_interval_table(parse("<1 7/6 4/3>:1")) <BLANKLINE> 1 7/6 4/3 --------------- 1 | 1 7/6 4/3 7/6 | 6/7 1 8/7 4/3 | 3/4 7/8 1 <BLANKLINE> """ frequencies = all_frequencies(music) if not frequencies: return table = interval_table(frequencies) table_width = max(len(str(x)) for x in chain.from_iterable(table)) music_width = max(len(str(x)) for x in frequencies) width = max(table_width, music_width) separator = " " border = " | " header = separator.join(f"{x!s:>{width}}" for x in frequencies) spaces = (width + len(border)) * " " overlap = 2 print() print(spaces + header) print(spaces[:-overlap] + (len(header) + overlap) * "-") for i, row in enumerate(table): print( f"{frequencies[i]!s:>{width}}" + border + separator.join(f"{x!s:>{width}}" for x in row) ) print() T = TypeVar("T", int, Fraction, RatioProduct) def prod(quantities: Iterable[T], initializer: T) -> T: """ Compute product. Used instead of math.prod to support Python 3.7. Parameters ---------- quantities : iterable of T Things to multiply. initializer : T First element to use in product. Returns ------- T Product of `quantities`. """ return reduce(operator.mul, quantities, initializer)
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class LoginRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ "email" => ["required"], "password"=> ["required", "min:4"], ]; } public function messages() { return [ 'email.required' => 'البريد الالكتروني مطلوب', 'password.required' => 'كلمة السر مطلوبة', 'password.min' => 'يجب الا تقل كلمة السر عن 4 خانات' ]; } }
import { MdThumbDownOffAlt } from "react-icons/md/"; import { BsPeople } from "react-icons/bs/"; import { AiOutlineStar, AiOutlineMessage, AiOutlineWallet, AiOutlineClockCircle, } from "react-icons/ai"; import NavBar from "../component/home/Navbar"; import { Button, TextField, Typography, Card } from "@mui/material"; import { useParams } from "react-router-dom"; import AboutCource from "../component/Cources/AboutCource"; import LatestSubject from "../component/services/LatestSubject"; import data from '../asset/data' import LatestAssignments from "../component/services/LatestAssignments"; export default function Cources() { const { name } = useParams(); return ( <> <div className="hero h-[600px]"> <div className="mask"> <NavBar /> <div className="hero_text "> <Typography variant="h3" component="h6" className="m-4"> Hire best tutors and researchers </Typography> <Typography variant="p" component="h4"> Request a call back and our managers will be in touch within 6 hours to understand the requirements. </Typography> <Button sx={{ bgcolor: "transparent", marginTop: "20px", borderRadius: "20px", borderColor: "white", border: "white", borderWidth: "2px", }} variant="contained" > Call Back </Button> </div> </div> </div> <div className="center md:translate-y-[-60%]" style={{ display: "flex", justifyContent: "center", }} > <Card variant="outlined" className="form_card" sx={{ width: "300px", backgroundColor: "white", display: "flex", padding: "5px", justifyContent: "center", }} > <form action="" style={{ display: "flex", justifyContent: "center", flexDirection: "column", }} className="py-5" > <Typography variant="h6" component="h6" sx={{ textAlign: "center", my: 2 }} > Quick Upload </Typography> <input type="text" placeholder="Enter Your Name" className="bg-transparent my-2 py-2 outline-none border-b-2 border-[#b7b7b7] " /> <input type="text" placeholder="Enter Your Email" className="bg-transparent my-2 py-2 outline-none border-b-2 border-[#b7b7b7] " /> <input type="text" placeholder="Enter Your Subject" className="bg-transparent my-2 py-2 outline-none border-b-2 border-[#b7b7b7] " /> <Button sx={{ bgcolor: "blue", marginTop: "20px", borderRadius: "20px", borderColor: "white", border: "white", borderWidth: "2px", }} variant="contained" > Upload Now </Button> </form> </Card> </div> <div className="px-[10%]"> <h1 className="md:text-[45px] text-[30px] text-[#00a6ae] font-[500] text-center"> Best Assignment Help Service in {name} </h1> <div className="flex shadow-2xl flex-wrap justify-around p-[2%]"> <AboutCource icon={<BsPeople size={50} color="#00a6ae" />} heading="FULL TIME EXPERTS" content="Lorem ipsum dolor sit amet consectetur adipisicing elit. Et maxime accusantium earum corrupti, ea debitis ab deleniti doloribus necessitatibus. Sequi consequatur perferendis maiores in voluptatum, nihil aperiam fugit amet architecto quod soluta suscipit totam!" /> <AboutCource icon={<AiOutlineStar size={50} color="#00a6ae" />} heading="FULL TIME EXPERTS" content="Lorem ipsum dolor sit amet consectetur adipisicing elit. Et maxime accusantium earum corrupti, ea debitis ab deleniti doloribus necessitatibus. Sequi consequatur perferendis maiores in voluptatum, nihil aperiam fugit amet architecto quod soluta suscipit totam!" /> <AboutCource icon={<AiOutlineMessage size={50} color="#00a6ae" />} heading="FULL TIME EXPERTS" content="Lorem ipsum dolor sit amet consectetur adipisicing elit. Et maxime accusantium earum corrupti, ea debitis ab deleniti doloribus necessitatibus. Sequi consequatur perferendis maiores in voluptatum, nihil aperiam fugit amet architecto quod soluta suscipit totam!" /> <AboutCource icon={<MdThumbDownOffAlt size={50} color="#00a6ae" />} heading="FULL TIME EXPERTS" content="Lorem ipsum dolor sit amet consectetur adipisicing elit. Et maxime accusantium earum corrupti, ea debitis ab deleniti doloribus necessitatibus. Sequi consequatur perferendis maiores in voluptatum, nihil aperiam fugit amet architecto quod soluta suscipit totam!" /> <AboutCource icon={<AiOutlineWallet size={50} color="#00a6ae" />} heading="FULL TIME EXPERTS" content="Lorem ipsum dolor sit amet consectetur adipisicing elit. Et maxime accusantium earum corrupti, ea debitis ab deleniti doloribus necessitatibus. Sequi consequatur perferendis maiores in voluptatum, nihil aperiam fugit amet architecto quod soluta suscipit totam!" /> <AboutCource icon={ <AiOutlineClockCircle size={50} color="#00a6ae" style={{ strokeWidth: "1px" }} /> } heading="FULL TIME EXPERTS" content="Lorem ipsum dolor sit amet consectetur adipisicing elit. Et maxime accusantium earum corrupti, ea debitis ab deleniti doloribus necessitatibus. Sequi consequatur perferendis maiores in voluptatum, nihil aperiam fugit amet architecto quod soluta suscipit totam!" /> </div> </div> <div className="shadow-xl p-[2%] my-8"> <h1 className="md:text-[45px] text-[30px] text-[#00a6ae] font-[500] text-center"> About {name} </h1> <hr className="text-black border-b-2" /> <div> <h1 className="md:text-[25px] text-[20px] text-left font-[500] "> About Cource </h1> <p> {data.map((data)=>{ if(data.name==name) return data.content })} </p> </div> </div> {/* <div className="flex justify-center translate-y-[-30%]"> <div className="w-[60%] flex flex-col items-center mx-4"> <Card/> <Card/> <Card/> <Card/> </div> <div> <LatestAssignments/> <LatestSubject/> </div> </div> */} <div className="flex justify-around px-[10%]"> <LatestAssignments name="Latest Subject" /> <LatestAssignments /> <LatestAssignments name="Latest Solutions" /> </div> </> ); }
<template> <div class="posts"> <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-5"> <div v-if="errors.length"> <div v-for="error in errors" :key="error.index" class="alert alert-danger mt-1" role="alert"> {{ error }} </div> </div> <div class="card"> <div class="card-header"> Detail Bayar Parkir </div> <div class="card-body"> <form> <div class="form-group"> <label>Nomor Registrasi</label>: {{post.no_registrasi}} </div> <div class="form-group"> <label>Arrival</label>: {{post.arrival}} </div> <div class="form-group"> <label>Lama Parkir</label>: {{post.lama}} </div> <div class="form-group"> <label>Biaya</label>: {{post.biaya}} </div> </form> <p></p> <router-link :to="{name:'/'}" class="btn btn-md btn-success mr-2">stay</router-link> <button @click.prevent="PostUpdate(post.id)" class="btn btn-md btn-danger">left</button> </div> </div> </div> </div> </div> </div> </template> <script> import axios from 'axios' export default { data() { return { post: {}, errors: [] } }, created() { axios.get(`http://localhost:3000/car_park/get/${this.$route.params.id}`).then(response => { this.post = response.data.data; }); },methods:{ PostUpdate(id) { axios.put(`http://localhost:3000/car_park/${id}`) .then(() => { this.$router.push('/') }).catch(error => { console.log(error.response); }); } } } </script>
@extends('base') @section('content') <div class="container"> <div class="row justify-content-center mt-5"> <div class="col-8"> <div class="d-flex justify-content-between mb-5"> <h2 class="h2 m-0 text-uppercase">Liste des articles </h2> <a href="{{ route('tasks.create') }}" class="btn btn-primary">Ajouter un article</a> </div> <table class="display" style="width:100%" id="myTable"> <thead> <tr> <th scope="col">#</th> <th scope="col">Titre</th> <th scope="col">Description</th> <th scope="col">Action</th> </tr> </thead> <tbody> @foreach ($tasks as $key => $task) <tr> <th scope="row">{{ $key + 1 }}</th> <td>{{ $task->title }}</td> <td>{{ $task->description }}</td> <td> <a href="{{ route('tasks.show', $task) }}" class="btn btn-secondary"><i class="bi bi-eye"></i></a> <a href="{{ route('tasks.edit', $task) }}" class="btn btn-primary"><i class="bi bi-pencil-square"></i></a> <a href="" onclick="event.preventDefault();supprime('{{$task->id}}')" class="btn btn-danger"><i class="bi bi-trash3"></i></a> <form action="{{ route('tasks.destroy', $task) }}" method="POST" class="d-none" id="submit{{$task->id}}"> @csrf @method('DELETE') </form> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> @endsection
@extends('layout.app') @section('content') @if(Session::has('success')) <p class="alert alert-info">{{ Session::get('success') }}</p> @endif <a href="{{route('student.create')}}" class="btn btn-primary">Add Student</a> <table> <tr> <th>Name</th> <th>Email</th> <th>Mobile</th> <th colspan="3" class="text-center">Action</th> </tr> <tr> @foreach($data as $datas) <td>{{$datas->name}}</td> <td>{{$datas->email}}</td> <td>{{$datas->mobile}}</td> <td><a href="{{route('student.show',$datas->id)}}" class="btn btn-success">Show</a></td> <td><a href="{{route('student.edit',$datas->id)}}" class="btn btn-warning">Edit</a></td> <td> <form action="{{route('student.destroy',$datas->id)}}" method="POST"> @csrf @method('DELETE') <input type="submit" name="delete" value="DELETE" class="btn btn-danger"> </form> </td> @endforeach </tr> </table> @endsection
@extends('Admin.Layout.starter') @section('title','Products') @section('page','Products') @section('content') <div class="content"> <div class="container-fluid"> <form action="{{ route('product.store') }}" method="post" enctype="multipart/form-data"> @csrf <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Name</label> <input type="text" class="form-control @error('name') is-invalid @enderror" name="name" placeholder="Name..." value="{{ old('name') }}"> @error('name') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="form-group col-md-6"> <label for="inputTitle4">Title</label> <input type="Title" class="form-control @error('title') is-invalid @enderror" id="inputTitle4" name="title" placeholder="Title" value="{{ old('title') }}"> @error('title') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> </div> <div class="form-group"> <label for="inputDescribtion">Describtion</label> <input type="text" name="describtion" class="form-control @error('describtion') is-invalid @enderror" id="inputDescribtion" placeholder="Text...." value="{{ old('describtion') }}"> @error('describtion') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <label>Photo</label> <div class="input-group mb-3"> <div class="custom-file col-4"> <input type="file" name="photo" class="custom-file-input @error('photo') is-invalid @enderror" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01" value="{{ old('photo') }}"> <label class="custom-file-label" for="inputGroupFile01">Choose file</label> </div> @error('photo') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputCity">Price</label> <input type="text" name="price" class="form-control @error('price') is-invalid @enderror" id="inputCity" value="{{ old('price') }}"> @error('price') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="form-group col-md-2"> <label for="inputZip">Price-After-Discount</label> <input type="text" name="discount" class="form-control @error('discount') is-invalid @enderror" id="inputZip" value="{{ old('discount') }}"> @error('discount') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="form-group col-md-4"> <label for="inputState">Category</label> <select id="inputState" name="category_id" class="form-control @error('category_id') is-invalid @enderror"> <option value="">Choose...</option> @foreach ($categories as $category) <option @selected(old('category_id')==$category->id) value="{{ $category->id }}">{{ $category->name }}</option> @endforeach </select> @error('category_id') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> </div> <div class="form-group"> {{-- <input type="text" name="counter" style="display: none" value="" id="input"> --}} <a class="btn btn-outline-warning" id="add"> Add-Option </a> </div> <div class="form-group" style="display: flex;flex-wrap:wrap;" id="divbtn"> @if(session('isOption')) <div> {{ session('isOption') }} </div> @endif @if(session('isOptionFull')) <div> {{session('isOptionFull')}} </div> @endif </div> <button type="submit" id="submit_form" class="btn btn-outline-primary">Add</button> </form> {{-- @selected('S' == old('option.color.${index}'))/ --}} </div> </div> @endsection @push('js') <script src="{{ asset('dist/js/AutoCreateOption.js') }}"></script> @endpush
import React from "react"; import { inject, observer } from "mobx-react"; import { withTranslation } from "react-i18next"; import Skeleton, { SkeletonTheme } from "react-loading-skeleton"; import * as variable from "Base/Variables"; import Layout from "Components/Layout/Layout"; import Panel from "Components/Panel/Panel"; import Loader from "Components/Loader/Loader"; import Pagination from "Components/Pagination/Pagination"; import "./AttackHistory.scss"; @inject("AuthStore", "AttackHistoryStore") @observer class AttackHistory extends React.Component { constructor(props) { super(); this.state = { historyData: [], page: 1, dataLoading: true, last_page: null, username: "", }; } componentDidMount() { this.getHistory(); let { AuthStore } = this.props; this.setState({ username: AuthStore.name, }); } getHistory = () => { const { AttackHistoryStore, AuthStore } = this.props; let { page } = this.state; AttackHistoryStore.getHistory(AuthStore.token, page).then((res) => { this.setState({ historyData: res.data.data, dataLoading: false, last_page: res.data.last_page, page: res.data.current_page, isLoading: false, }); }); }; onPageChange = (e) => { this.setState( { page: e.selected + 1, isLoading: true, }, () => { this.getHistory(); } ); }; render = () => { let { historyData, dataLoading, last_page, isLoading, page, username } = this.state; return ( <div className="attack_history"> <Layout title="Attack History"> {dataLoading ? ( <Loader /> ) : historyData && historyData.length !== 0 ? ( <div className="panel-wrapper"> <Panel theme="purple"> <div className="panel-inner"> <div className="table-row"> <div className="table-heading purple-text"> Attacker User Name </div> <div className="table-heading purple-text"> Defender User Name </div> <div className="table-heading purple-text"> Earn Capacity </div> <div className="table-heading purple-text">Win Type</div> </div> {historyData.map((obj, key) => { return ( <div key={key} className="full-width"> {isLoading ? ( <div className="skeleton-row"> <SkeletonTheme color={variable.Active} highlightColor={variable.CheckboxBorder} > <Skeleton count={1} style={{ margin: "20px" }} /> </SkeletonTheme> </div> ) : ( <div className="table-row"> <div className="table-col center-flex-div"> <span className="span-heading"> Attacker User Name :- </span> {` ${obj.display_attacker_username}`} </div> <div className="table-col center-flex-div"> <span className="span-heading"> Defender User Name :- </span> {` ${obj.display_defender_username}`} </div> <div className="table-col center-flex-div"> <span className="span-heading"> Earn Capacity :- </span> {username === obj.attacker_username ? ` ${obj.earn_capacity.toFixed(2)}` : ` -${obj.earn_capacity.toFixed(2)}`} </div> <div className="table-col center-flex-div"> <span className="span-heading">Win Type :-</span> {` ${ username === obj.attacker_username ? "Win" : "Lose" }`} </div> </div> )} </div> ); })} {last_page !== null && page <= last_page && ( <div className="set-margin"> <Pagination pageCount={last_page} onPageChange={(e) => this.onPageChange(e)} /> </div> )} </div> </Panel> </div> ) : ( <div className="greenpurple"> Sorry, Attack history is not available..... </div> )} </Layout> </div> ); }; } export default withTranslation()(AttackHistory);
import React, { useEffect, useState } from 'react'; import { useLocation, useParams } from 'react-router-dom'; import { getComment, getVideoDetail } from 'src/api/requests'; import { getRelationVideo, getChannelInfo } from './../../api/requests'; import './VideoDetail.scss'; import VideoInfo from 'src/components/VideoInfo/VideoInfo'; import ChannelInfo from 'src/components/ChannelInfo/ChannelInfo'; import VideoComments from './../../components/VideoComments/VideoComments'; import RelatedVideos from 'src/components/RelatedVideos/RelatedVideos'; export default function VideoDetail() { // 비디오 아이디, 채널 아이디 const { videoId } = useParams<string>(); const { state } = useLocation(); const channelId: string = state.channelId; const [videoLoading, setVideoLoading] = useState(true); const [channelLoading, setChannelLoading] = useState(true); const [commentLoading, setCommentLoading] = useState(true); const [relatedLoading, setRelatedLoading] = useState(true); const [relatedDetailLoading, setRelatedDetailLoading] = useState(true); // 일일할당량때문에 localStorage 에 없을 경우 저장 useEffect(() => { if (!JSON.parse(localStorage.getItem('VideoDetail'))) { getVideoDetail(videoId).then((data) => { localStorage.setItem('VideoDetail', JSON.stringify(data)); setVideoLoading(false); }); } else { setVideoLoading(false); } if (!JSON.parse(localStorage.getItem('ChannelInfo'))) { getChannelInfo(channelId).then((data) => { localStorage.setItem('ChannelInfo', JSON.stringify(data)); setChannelLoading(false); }); } else { setChannelLoading(false); } if (!JSON.parse(localStorage.getItem('Comment'))) { getComment(videoId).then((data) => { localStorage.setItem('Comment', JSON.stringify(data)); setCommentLoading(false); }); } else { setCommentLoading(false); } if (!JSON.parse(localStorage.getItem('RelationVideo'))) { getRelationVideo(videoId).then((data) => { localStorage.setItem('RelationVideo', JSON.stringify(data)); setRelatedLoading(false); }); } else { setRelatedLoading(false); } }, [channelId, videoId]); // 로컬에 있는 데이터로 쓰기 const videoData = JSON.parse(localStorage.getItem('VideoDetail')); const channelInfo = JSON.parse(localStorage.getItem('ChannelInfo')); const commentData = JSON.parse(localStorage.getItem('Comment')); const relationVideos = JSON.parse(localStorage.getItem('RelationVideo')); const commentCount = videoData && videoData.statistics.commentCount; const relatedId = relationVideos && relationVideos.map((video) => video.id.videoId); useEffect(() => { if (relatedId) { Promise.all( relatedId.map(async (id: string) => { if (!JSON.parse(localStorage.getItem(id))) { await getVideoDetail(id).then((data) => { const res = { duration: data.contentDetails.duration, viewcount: data.statistics.viewCount }; localStorage.setItem(id, JSON.stringify(res)); }); } }), ).then(() => { setRelatedDetailLoading(false); }); } }, [relatedId]); return ( <> {videoLoading || channelLoading || commentLoading || relatedLoading || relatedDetailLoading ? ( <h1>Loading...</h1> ) : ( <section className="videoDetail"> <div className="wrap"> <div className="videoDetailLeft"> {/* 비디오 */} <div id="videoWrap"> <iframe title="video" id="player" src={`//www.youtube.com/embed/${videoId}`} allowFullScreen></iframe> </div> {/* 비디오 정보 */} <VideoInfo videoData={videoData} /> {/* 채널 정보 */} <ChannelInfo channelInfo={channelInfo} /> {/* 댓글 */} <VideoComments commentData={commentData} commentCount={commentCount} /> </div> {/* 관련 동영상 */} <div className="videoDetailRight"> <RelatedVideos relationVideos={relationVideos} /> </div> </div> </section> )} </> ); }
# Map Template This app is built on React, with our Web Components used where applicable. ## Running the app To get the app up and running, clone this repo, install everything using [Lerna](https://lerna.js.org), and start the app: ```zsh $ git clone https://github.com/MapsPeople/web-ui.git $ cd web-ui && npm install && npx lerna run build $ cd packages/map-template && npm run start ``` Now open the app served on [http://localhost:3000/](http://localhost:3000/). The Map Template has a main `MapsIndoorsMap` React component. It wraps the whole app inside of it. It's used in a function in `App.jsx` which is imported into `index.jsx` where it's defined that an HTML element with `id="root"` will render the app. We show how that is done in `packages/map-template/index.html`. ### Adding Google Maps API Keys or Mapbox Access Tokens Rename `.env.example`, to `.env` and add either of the keys (or both) to that file, and the maps will load properly. ### React Components We follow [the React convention](https://reactjs.org/docs/faq-structure.html#avoid-too-much-nesting) with one level of depth in the Components' folder. We still import React components into each other (even in multiple levels), but the folder structure is flat. ### Web Components We use our own Web Components ([Custom Elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements)) from `packages/components` inside of the Map Template. To illustrate the relation between the React app, its React Components and our Web Components, here's a drawing of how this works in the Route Instructions part of the app: ``` // public/index.html - App.js - MapsIndoorsMap - BottomSheet - Directions - RouteInstructions - mi-route-instructions-step - mi-icon - mi-time - mi-distance ``` The `mi-route-instructions-step` Web Component uses `mi-route-instructions-maneuver` to render sub steps, `mi-icon` for icons, and `mi-time` and `mi-distance` to show estimated time and distance. We use `mi-route-instructions-step` in the React Component `RouteInstructions` to show, well, route instructions. This is used inside of an "umbrella" component for all directions (including searching for where to go) called `Directions`. Everything in the app is displayed in the `BottomSheet` (on mobile viewports), and the main app component is named `MapsIndoorsMap`. If you have a React app, you can use any of these React Components in your own app. If you want to not use a bottom sheet for instance, you could import the `Directions` component and work with that in your app. #### Working on Components used in Map Template To have any Stencil component changes be reflected in this project, you need to run `npx lerna run build` from the root folder. There are no watch scripts yet. ## Supported properties on the MapsIndoors Map component The MapsIndoors Map component supports a list of props (see the list below) that can be configured in the `App.jsx` file. When loading the MapsIndoors Map component for the first time, the map will respect the default values set for the `apiKey`, `venue`, `logo` and `primaryColor` props, which can be found in the `MapsIndoorsMap.jsx` file under the `defaultProps` object. |Property|Type|Description| |:--|:--|:--| |`apiKey`|`string`|The MapsIndoors Solution you want to load. Takes both API key as string and "App alias". | |`gmApiKey`|`string`|Your Google Maps API key. | |`mapboxAccessToken`|`string`|Your Mapbox Access Token. Setting it will load a Mapbox map. If you set both a Mapbox Access Token and Google Maps API key, the Mapbox Access Token takes precedence. | |`venue`|`string`|The Venue to load from your MapsIndoors Solution. | |`locationId`|`string`|Set a MapsIndoors Location ID to show it on the map and its details in the sheet. | |`primaryColor`|`string`|The primary color to use throughout the app. | |`logo`|`string`|The logo to show during initial load. | |`appUserRoles`|`array`|A list of App User Roles to apply when loading data. Used like so: `appUserRoles={["App User Role"]}`| |`directionsFrom`|`string`|Set a MapsIndoors Location ID or the string `USER_POSITION` to be used as origin to instantly show directions. | |`directionsTo`|`string`|Set a MapsIndoors Location ID or the string `USER_POSITION` to be used as destination to instantly show directions. | |`externalIDs`|`array`|Array of external IDs which filters the map and shows a list of locations. Because of the way browsers work, you can not use External IDs with the `,`, `&`, `#` and `+`, character in them, as they are interpreted by the browser in a particular way. | |`tileStyle`|`string`|Name of Tile Style to display on the map. | |`startZoomLevel`|`number`|The initial zoom level of the map. | |`supportsUrlParameters`|`bool`|Indicates if the Map Template supports URL parameters. | |`gmMapId`|`string`|The Google Maps Map ID associated with a specific map style or feature. | |`pitch`|`number`|The pitch (Mapbox) or tilt (Google) value of the map. The value of the pitch can be between 0-85 degrees on a Mapbox map. | |`bearing`|`number`|The bearing (Mapbox) or heading (Google) value of the map. It accepts any value, and will modify it to fit into the range [0, 360]. | ## Using Query Parameters The Map Template supports using query parameters for all the properties provided by the MapsIndoorsMap component if the `supportsUrlParameters` property is set to true. The supported query parameters are the following: 1. `apiKey` - Used like this `apiKey=yourApiKey`. If no apiKey is provided, the app will default to `3ddemo`. 2. `venue` - Used like this `venue=yourVenueName` - the Venue property is case sensitive. If no venue is provided, the app will select the first venue from the solution in alphabetical order. 3. `locationId` - Used like this `locationId=yourLocationId` 4. `primaryColor` - Used like this `primaryColor=000000`. **Note!** You need to provide a hex color value, without the `#`, due to the hashtag being a reserved symbol that has a predefined purpose in a query string. If no primary color is provided, the app will default to the MapsPeople brand color. 5. `logo` - Used like this `logo=https://images.g2crowd.com/uploads/product/image/social_landscape/social_landscape_7a75ff13f42605422950b411ab7e03b5/mapspeople.png`. Use an image address to provide a different logo on the loading screen. If no logo is provided, the app will default to the MapsPeople icon. 6. `appUserRoles` - Used like this `appUserRoles=visitor,staff,security` - the App User Roles are case sensitive. **Note!** You need to provide a list of comma separated values, without any spaces between the comma and the value. This will further be converted into an array of appUserRoles. 7. `directionsFrom` - Used like this `directionsFrom=yourOriginLocationId` when having a location ID, or like this `directionsFrom=USER_POSITION` when having the user location. Using the `directionsFrom` property in the URL followed by the selection of a destination location in the search view results in the wayfinding having both the origin and the destination prefilled. 8. `directionsTo` - Used like this `directionsTo=yourDestinationLocationId` when having a location ID, or like this `directionsTo=USER_POSITION` when having the user location. 9. `externalIDs` - Used like this `externalIDs=0.0.1,0.0.2,0.0.3`. **Note!** You need to provide a list of comma separated values, without any spaces between the comma and the value. This will further be converted into an array of external IDs. Because of the way browsers work, you **cannot** use External IDs with the `,`, `&`, `#` and `+`, character in them, as they are interpreted by the browser in a particular way. 10. `tileStyle` - Used like this `tileStyle=yourTileStyleName`. If no tile style is provided, the app will show the default tile style. 11. `mapboxAccessToken` - Used like this `mapboxAccessToken=yourMapboxAccessToken`. If both the `mapboxAccessToken` and the `gmApiKey` are present, the app will load a Mapbox map. 12. `gmApiKey` - Used like this `gmApiKey=yourGmApiKey`. If both the `mapboxAccessToken` and the `gmApiKey` are present, the app will load a Mapbox map. 13. `startZoomLevel` - Used like this `startZoomLevel=22`. 14. `gmMapId` - Used like this `gmMapId=yourGmMapId`. 15. `pitch` - Used like this `pitch=30`. Not compatible with MapsIndoors 2D models and MapsIndoors labels on Google Maps. The value of the pitch can be between 0-85 degrees on a Mapbox map. 16. `bearing` - Used like this `bearing=180`. Not compatible with MapsIndoors 2D models and MapsIndoors labels on Google Maps. It accepts any value, and will modify it to fit into the range [0, 360]. **Note!** All the query parameters need to be separated with the `&` symbol, without any spaces in between. **Note!** When using parameters such as `directionsTo`, `directionsFrom`, `locationId`, `externalIDs`, and `tileStyle` make sure you are using the correct `apiKey` parameter to which they belong. **Note!** When using the `gmMapId` property, you need to use it together with the `gmApiKey` that it is associated with. Example of URL: `https://domain.com/?apiKey=yourApiKey&venue=yourVenueName&locationId=yourLocationId&primaryColor=000000&logo=https://images.g2crowd.com/uploads/product/image/social_landscape/social_landscape_7a75ff13f42605422950b411ab7e03b5/mapspeople.png&appUserRoles=visitor,staff,security` **Important!** Not all the query parameters can be used together, as they serve their own purpose which in some cases overlaps with other query parameters. Example of cases that **DON’T** work together: `locationId` + `startZoomLevel` → the `startZoomLevel` has priority over the `locationId` `locationId` + `externalIDs` → the `locationId` has priority over the `externalIDs` `directionsTo` + `directionsFrom` + `locationId` → the `directionsTo` + `directionsFrom` have priority over the `locationId` `directionsTo` + `directionsFrom` + `externalIDs` → the `directionsTo` + `directionsFrom` have priority over the `externalIDs` ## Deploying Map Template to a cloud storage provider We often use Google Cloud Storage (GCS) for deploying small useful apps for demo purposes. This guide refers to GCS, but many of the steps are identical for AWS, Azure Blob, and the like. Running the regular build command (`npm run build`), it's assumed that all links refer to the root of a domain. When you deploy to a storage bucket, you need to build the app with the bucket name preprended to all links. Vite has a build option to take care of this: ```zsh $ npx vite build --base=/YOUR_BUCKET_NAME ``` At this point you can upload the files manually to your bucket, or use the helpful CLI [`gsutil`](https://cloud.google.com/storage/docs/gsutil) for the purpose. This command uploads the complete `build` folder, and prevents the files from being cached: ```zsh $ gsutil -m -h "Cache-Control:public, max-age=0, no-store, no-cache" cp -r build/* gs://YOUR_BUCKET_NAME ``` ### Using the `deploy-to-gcloud` npm script To make this even easier (mostly for ourselves), there's a `deploy-to-gcloud` script. It takes one argument which is the bucket name, and is used like this: ``` $ npm run deploy-to-gcloud -- BUCKET_NAME ``` This script will only work if you've already authenticated using the `gsutil` CLI on your machine, and have the proper access rights to deploy to the specified bucket.
package main import ( "context" "embed" "fmt" "log" "net/http" "strconv" "time" "wails-template/components" "github.com/a-h/templ" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/wailsapp/wails/v3/pkg/application" ) //go:embed all:frontend/dist components var assets embed.FS var version = "0.0.0" func main() { r := NewChiRouter() // r.Use(middleware.Logger) // r.Use(middleware.Recoverer) app := application.New(application.Options{ Name: "wails3-htmx-template", Description: "A demo of using raw HTML & CSS", Assets: application.AssetOptions{ FS: assets, Middleware: func(next http.Handler) http.Handler { r.NotFound(next.ServeHTTP) return r }, }, Mac: application.MacOptions{ ApplicationShouldTerminateAfterLastWindowClosed: true, }, KeyBindings: map[string]func(window *application.WebviewWindow){ "F12": func(window *application.WebviewWindow) { println("teste") window.Show() }, }, }) // Register for events app.Events.On("myevent", func(e *application.WailsEvent) { fmt.Println("event run") app.Logger.Info("[Go] WailsEvent received", "name", e.Name, "data", e.Data, "sender", e.Sender, "cancelled", e.Cancelled) }) // Create window app.NewWebviewWindowWithOptions(application.WebviewWindowOptions{ Title: "Main Window", CSS: `body { background-color: rgba(255, 255, 255, 0); } .main { color: white; margin: 20%; }`, Mac: application.MacWindow{ InvisibleTitleBarHeight: 50, Backdrop: application.MacBackdropTranslucent, TitleBar: application.MacTitleBarHiddenInset, }, KeyBindings: map[string]func(window *application.WebviewWindow){ "F12": func(window *application.WebviewWindow) { window.Show() }, }, URL: "/", }) // Systray Window systemTray := app.NewSystemTray() window := app.NewWebviewWindowWithOptions(application.WebviewWindowOptions{ Name: "systray", Width: 400, Height: 600, Frameless: true, AlwaysOnTop: true, Hidden: true, DisableResize: true, ShouldClose: func(window *application.WebviewWindow) bool { window.Hide() return false }, Windows: application.WindowsWindow{ HiddenOnTaskbar: true, }, KeyBindings: map[string]func(window *application.WebviewWindow){ "F12": func(window *application.WebviewWindow) { systemTray.OpenMenu() }, }, URL: "/", }) app.NewWebviewWindowWithOptions(application.WebviewWindowOptions{ Name: "view", Title: "View Window", // Width: 800, // Height: 800, Frameless: false, AlwaysOnTop: false, Hidden: true, DisableResize: true, ShouldClose: func(window *application.WebviewWindow) bool { window.Hide() return false }, Windows: application.WindowsWindow{ HiddenOnTaskbar: true, }, // KeyBindings: map[string]func(window *application.WebviewWindow){ // "F12": func(window *application.WebviewWindow) { // systemTray.OpenMenu() // }, // }, URL: "/", }) // Systray Menu myMenu := app.NewMenu() systemTray.SetMenu(myMenu) myMenu.Add("Quit").OnClick(func(ctx *application.Context) { app.Quit() }) // Attach extra windows systemTray.AttachWindow(window).WindowOffset(5) err := app.Run() if err != nil { log.Fatal(err) } } func NewChiRouter() *chi.Mux { r := chi.NewRouter() r.Use(middleware.Logger) r.Use(middleware.Recoverer) c := &Counter{} // r.Get("/initial", templ.Handler(components.Pages([]struct { // Path string // Label string // }{ // {"/greet", "Greet form"}, // {"/events", "Events page"}, // }, struct { // Version string // Text string // }{ // version, "No update available", // })).ServeHTTP) r.Get("/init", InitContent()) r.Get("/greet", templ.Handler(components.GreetForm("/greet")).ServeHTTP) r.Post("/greet", components.Greet) r.Get("/modal", templ.Handler(components.TestPage("#modal", "outerHTML")).ServeHTTP) r.Post("/modal", templ.Handler(components.Modal("Title for the modal", "Sample Data")).ServeHTTP) // r.Get("/systray", InitContent()) // r.Get("/sidebar", templ.Handler(components.SideBar()).ServeHTTP) r.Get("/counter", CounterHandler(c)) r.Get("/events", templ.Handler(components.Events()).ServeHTTP) // Custom Endpoints r.Get("/event", TestLoop) return r } type Counter struct { count int } func InitContent() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := context.Background() windowID := r.Header.Get("X-Wails-Window-Id") app := application.Get() app.Events.Emit(&application.WailsEvent{ Name: "myevent", Data: "now", }) if windowID == "1" { components.Index().Render(ctx, w) } if windowID == "2" { components.SideBar2().Render(ctx, w) } } } func CounterHandler(c *Counter) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { c.count++ w.Write([]byte("count is " + strconv.Itoa(c.count))) } } func TestLoop(w http.ResponseWriter, r *http.Request) { templ.Handler(components.Modal("title", "test ")).ServeHTTP(w, r) fmt.Println("test event") application.Get().Events.Emit(&application.WailsEvent{ Name: "myevent", Data: "hello", }) fmt.Println("test loop") for i := 0; i < 3; i++ { w.Write([]byte("test loop")) time.Sleep(time.Second * 2) } } // func TestLoop(w http.ResponseWriter, r *http.Request) { // // templ.Handler(components.Modal("title", "test ")).ServeHTTP(w, r) // w.Header().Set("Content-Type", "text/event-stream") // w.Header().Set("Cache-Control", "no-cache") // w.Header().Set("Connection", "keep-alive") // w.Header().Set("Access-Control-Allow-Origin", "*") // w.Header().Set("Access-Control-Allow-Headers", "Content-Type") // flusher, ok := w.(http.Flusher) // if !ok { // http.Error(w, "Streaming unsupported", http.StatusInternalServerError) // return // } // for i := 0; i < 3; i++ { // w.Write([]byte("test loop")) // flusher.Flush() // time.Sleep(time.Second * 2) // } // } /* TODO 1. Add systray 2. Add user settings 3. Add notifications 4. Add realtime updates 5. Add multiwindow 6. Add mouse bound window for context interaction/frameless/global keybindings 7. Add daisyui/other 8. Add DB + local storage (bbolt/pocketbase) 9. Add dialog 10. Add Auth 11. Embedded files + audio notification UX Idea: So while keeping the default wails template view, we can add a hover menu that opens an overlay grid with the options for different views, that then uses htmx + astro to render the different views. Systray usage: New idea 2: Use bottom nav menu in systray to default to notfications view but change to settings/updates. Use events and wml to navigate from notifications to main window. New idea: Change notifications to be purely for notifications, with settings and updates done in the main window via bottom/top/sidebar. Old: - User/System settings0 - Notifications - Realtime updates (time, background tasks) Systray could be used for notifcations/modals, a links or options for navigation, or just a demo for opening alternate windows settings/notifications/realtime updates for status information/widgets and action shortcuts, background tasks&activites ###Stuck### - stuck on how to manage route for different windows i.e systray for loading the relevant components/html/css for each window - fixed - Add support for htmx no js - done (except for the 1 small demo) add greet demo - chi - done? tailwind - done daisyui systray - added, but will be a view controller or something? multiwindow - what for? astro - done add embedded files demo/user config/embedded binary - store in webview storage streaming? sse/websockets/chunked/events? notifications? db 1. go to events page which loads the page 2. button to activate the call to events 3. return instant result then loop to send an event with updates. */
package com.esteban.marketfinalproyectpoo; import java.util.ArrayList; import java.util.Scanner; public class Stock { //atributos private Vendedor vendedor; ArrayList<Iproductos> productosStock = new ArrayList<>(); //constructor public Stock() { this.vendedor = null; this.productosStock = null; } //metodos public void adicionarAlStock(ArrayList<Iproductos> productos) { if (productos != null) { for (Iproductos producto : productos) { if (producto instanceof Libro) { this.productosStock.add(producto); } if (producto instanceof Resaltadores) { this.productosStock.add(producto); } } productos.clear(); } if (productos.isEmpty()) { System.out.println("No existen Productos ingresados..."); } } public void leerProducto() { System.out.println(); System.out.println("----------------------Lista de productos---------------------"); if (this.productosStock != null) { for (int i = 0; i < this.productosStock.size(); i++) { System.out.println(i + "." + this.productosStock.get(i)); } } System.out.println("-------------------------------------------------------------"); System.out.println(); } public void actualizarProducto() { Scanner leer = new Scanner(System.in); System.out.println("porfavor ingrese el numero del producto desea actualizar"); int value = leer.nextInt(); leer.nextLine(); if (this.productosStock.get(value) instanceof Libro) { System.out.println("Ingrese el titulo"); String titulo = leer.nextLine(); System.out.println("Ingrese el autor"); String autor = leer.nextLine(); Libro libro = new Libro(titulo, autor); this.productosStock.set(value, libro); } if (this.productosStock.get(value) instanceof Resaltadores) { System.out.println("Ingrese el Color"); String color = leer.nextLine(); System.out.println("Ingrese la marca"); String marca = leer.nextLine(); Resaltadores resaltadores = new Resaltadores(color, marca); this.productosStock.set(value, resaltadores); } } public void eliminarProducto(int value) { if (this.productosStock != null) { this.productosStock.remove(value); } } //getter and setter public Vendedor getVendedor() { return vendedor; } public void setVendedor(Vendedor vendedor) { this.vendedor = vendedor; } public ArrayList<Iproductos> getProductosStock() { return productosStock; } public void setProductosStock(ArrayList<Iproductos> productosStock) { this.productosStock = productosStock; } }
#include <cstdio> #include <iostream> #include <fstream> #include <vector> #include <utility> // for std::pair #include <algorithm> // for max function #include <tuple> bool debug = true; const int INF = 1e9; // Representing infinity // nodes are numbered from 1 to N and the graph is undirected // Using vector of vectors to represent an adjacency list, where each pair is (neighbor, cost) typedef std::vector<std::vector<std::pair<int, int>>> Graph; void sendMessage(std::ofstream& outputFile, int src, int dest, const std::vector<std::vector<int>>& dist, const std::vector<std::vector<int>>& nextHop, const std::string& message, const int INF) { if (dist[src][dest] == INF) { // Destination is not reachable outputFile << "from " << src << " to " << dest << " cost infinite hops unreachable message " << message << std::endl; } else { // Trace the path using the nextHop table std::vector<int> path; int currentNode = src; while (currentNode != dest) { path.push_back(currentNode); currentNode = nextHop[currentNode][dest]; if (currentNode == -1) { // Break loop if path is incomplete or broken break; } } // Output the message routing information outputFile << "from " << src << " to " << dest << " cost " << dist[src][dest] << " hops "; for (size_t i = 0; i < path.size(); ++i) { if (i > 0) outputFile << " "; outputFile << path[i]; } outputFile << " message " << message << std::endl; } } void handleMessageForwarding(const std::string& messageFilePath, const std::vector<std::vector<int>>& dist, const std::vector<std::vector<int>>& nextHop, std::ofstream& outputFile, const int INF) { std::ifstream messageFile(messageFilePath); if (!messageFile.is_open()) { std::cerr << "Could not open message file\n"; return; } int src, dest; std::string messageContent; while (messageFile >> src >> dest) { std::getline(messageFile, messageContent); // To correctly handle the message content after reading src and dest if (messageContent.size() > 0 && messageContent[0] == ' ') { // Remove leading space from message content messageContent.erase(0, 1); } sendMessage(outputFile, src, dest, dist, nextHop, messageContent, INF); } messageFile.close(); } void outputForwardingTables(const std::vector<std::vector<int>>& dist, const std::vector<std::vector<int>>& nextHop, std::ofstream& outputFile, int maxNodes, const int INF) { for (int node = 1; node <= maxNodes; ++node) { for (int dest = 1; dest <= maxNodes; ++dest) { if (node == dest) { // Output the node itself with a next hop of itself and a cost of 0, ensuring it's in order outputFile << dest << " " << dest << " " << 0 << std::endl; } else if (dist[node][dest] != INF) { int nexthop = nextHop[node][dest]; // Use the actual next hop for the destination outputFile << dest << " " << nexthop << " " << dist[node][dest] << std::endl; } } // outputFile << std::endl; // Separate tables for readability when debugging } } void applyChangeToGraph(Graph& graph, int node1, int node2, int newCost, int maxNodes) { bool edgeFound = false; // Update the cost if the edge exists for (auto& edge : graph[node1]) { if (edge.first == node2) { if (newCost == -999) edge.second = INF; // Or remove the edge entirely else edge.second = newCost; edgeFound = true; break; } } if (!edgeFound && newCost != INF) { // If the edge does not exist and we're not removing, add it graph[node1].push_back(std::make_pair(node2, newCost)); } // Since the graph is undirected, repeat for node2 to node1 edgeFound = false; for (auto& edge : graph[node2]) { if (edge.first == node1) { if (newCost == -999) edge.second = INF; // Or remove the edge entirely else edge.second = newCost; edgeFound = true; break; } } if (!edgeFound && newCost != INF) { graph[node2].push_back(std::make_pair(node1, newCost)); } } void recomputeDistanceVectors(const Graph& graph, std::vector<std::vector<int>>& dist, std::vector<std::vector<int>>& nextHop, int maxNodes) { // Reset the distance vectors for(int i = 1; i <= maxNodes; ++i) { std::fill(dist[i].begin(), dist[i].end(), INF); dist[i][i] = 0; // Distance to itself is 0 for(const auto& edge : graph[i]) { int neighbor = edge.first; int cost = edge.second; dist[i][neighbor] = cost; // Direct neighbor cost } } // Reset nextHop table for (int i = 1; i <= maxNodes; ++i) { for (int j = 1; j <= maxNodes; ++j) { if (i == j) nextHop[i][j] = i; // Next hop to itself is itself else if (dist[i][j] != INF) nextHop[i][j] = j; // Directly connected nodes else nextHop[i][j] = -1; // Undefined next hop } } // Apply the DV update logic bool updated; do { updated = false; for (int i = 1; i <= maxNodes; ++i) { for (const auto& edge : graph[i]) { int neighbor = edge.first; for (int j = 1; j <= maxNodes; ++j) { // Check for a better path or a tie with a preferable next hop if (dist[i][j] > dist[i][neighbor] + dist[neighbor][j] || (dist[i][j] == dist[i][neighbor] + dist[neighbor][j] && nextHop[i][j] > nextHop[i][neighbor])) { dist[i][j] = dist[i][neighbor] + dist[neighbor][j]; // Update next hop, considering direct connections and ensuring the next hop isn't set to -1 incorrectly nextHop[i][j] = (dist[i][neighbor] == INF) ? -1 : nextHop[i][neighbor]; updated = true; } } } } } while (updated); } void printDistanceTable(const std::vector<std::vector<int>>& dist, int maxNodes, const int INF) { std::cout << "Distance table:" << std::endl; for(int i = 1; i <= maxNodes; ++i) { for(int j = 1; j <= maxNodes; ++j) { if(dist[i][j] == INF) std::cout << "INF "; else std::cout << dist[i][j] << " "; } std::cout << std::endl; } } int main(int argc, char** argv) { if (argc != 4) { std::cout << "Usage: ./distvec topofile messagefile changesfile\n"; return -1; } std::ofstream outputFile("output.txt"); if (!outputFile.is_open()) { std::cerr << "Could not open output.txt for writing\n"; return -1; } std::ifstream topoFile(argv[1]); if (!topoFile.is_open()) { std::cerr << "Could not open topology file\n"; return -1; } int node1, node2, cost; int maxNodes = 0; // Temporary storage to hold edge information before resizing the graph std::vector<std::tuple<int, int, int>> edges; // determine the maximum node ID while (topoFile >> node1 >> node2 >> cost) { edges.push_back(std::make_tuple(node1, node2, cost)); maxNodes = std::max(maxNodes, std::max(node1, node2)); } // we know the maximum node ID, we can resize the graph and populate it Graph graph(maxNodes + 1); // +1 because nodes are 1-indexed instead of 0-indexed // construct the graph for (const auto& edge : edges) { node1 = std::get<0>(edge); node2 = std::get<1>(edge); cost = std::get<2>(edge); graph[node1].push_back(std::make_pair(node2, cost)); graph[node2].push_back(std::make_pair(node1, cost)); // because the graph is undirected } topoFile.close(); // debug the topology if (debug == true){ for (int i = 0; i < graph.size(); ++i) { if (!graph[i].empty()) { std::cout << "Node " << i << " -> "; for (const auto& neighbor : graph[i]) { std::cout << "(" << neighbor.first << ", " << neighbor.second << ") "; } std::cout << "\n"; } } } std::vector<std::vector<int>> dist(maxNodes+1, std::vector<int>(maxNodes+1, INF)); std::vector<std::vector<int>> nextHop(maxNodes+1, std::vector<int>(maxNodes+1, -1)); // do the Distance Vector computing for the first time, before any changes applied recomputeDistanceVectors(graph, dist, nextHop, maxNodes); // output the forwarding table after computing the distance table outputForwardingTables(dist, nextHop, outputFile, maxNodes, INF); // handle message forwarding handleMessageForwarding(argv[2], dist, nextHop, outputFile, INF); // debug the distance table after iteratively update distances until no changes if (debug) { printDistanceTable(dist, maxNodes, INF); } // handle the topology changes std::ifstream changesFile(argv[3]); if (!changesFile.is_open()) { std::cerr << "Could not open changes file\n"; return -1; } int newCost; while (changesFile >> node1 >> node2 >> newCost) { // Apply the change to the graph // Note: You'll need to adjust your graph structure to allow for easy updates std::cout << "Applying change: Node1=" << node1 << ", Node2=" << node2 << ", NewCost=" << newCost << std::endl; applyChangeToGraph(graph, node1, node2, newCost, maxNodes); std::cout << "Change applied. Recomputing distance vectors..." << std::endl; // Recompute the Distance Vectors recomputeDistanceVectors(graph, dist, nextHop, maxNodes); // output the forwarding table after computing the distance table outputForwardingTables(dist, nextHop, outputFile, maxNodes, INF); // handle message forwarding handleMessageForwarding(argv[2], dist, nextHop, outputFile, INF); std::cout << "Distance vectors recomputed." << std::endl; if (debug) { printDistanceTable(dist, maxNodes, INF); } } changesFile.close(); return 0; }
import { gql, useQuery } from "@apollo/client"; import { BlogData } from "../interfaces/blogs"; interface Props { slug?: string; } const BLOG_BY_SLUG = gql` query getBlogBySlug($slug: String!) { blogBySlug(slug: $slug) { _id Title Date urlES urlEN } } `; export const useGetBlog = ({ slug }: Props) => { const { loading: loading, error: error, data: data, } = useQuery<BlogData>(BLOG_BY_SLUG, { variables: { slug }, }); return { loading, data, error, }; };
import { Component } from '@angular/core'; import { OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ApplicationData } from './application-data'; import { ApplicationDataService } from './application-data.service'; @Component({ moduleId: module.id, selector: 'phone-numbers', templateUrl: 'phone-numbers.component.html', styleUrls: ['phone-numbers.component.css'] }) export class PhoneNumbersComponent implements OnInit { application_data: ApplicationData; constructor( private router: Router, private applicationDataService: ApplicationDataService ) { } ngOnInit(): void { this.applicationDataService.getApplicationData().then( application_data => this.application_data = application_data); } saveAndBack(): void { this.applicationDataService.updateApplicationData() .then(response => { if (response.success) { this.router.navigate(['/characteristics']); } else { console.log('Failed to update data to server. Not navigating away.'); } }); } }
package tech.valinaa.medishop.web.controller; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.RestController; import tech.valinaa.medishop.api.Result; import tech.valinaa.medishop.api.medicine.MedicineDetailApi; import tech.valinaa.medishop.api.medicine.request.MedicineDetailRequest; import tech.valinaa.medishop.api.medicine.response.MedicineDetailResponse; import tech.valinaa.medishop.core.converter.MedicineConverter; import tech.valinaa.medishop.core.model.MedicineDetailDO; import tech.valinaa.medishop.core.service.MedicineDetailService; import tech.valinaa.medishop.core.service.MedicineService; /** * @author Valinaa * @Date 2023/10/8 13:39 */ @RestController @RequiredArgsConstructor public class MedicineDetailController implements MedicineDetailApi { private final MedicineService medicineService; private final MedicineDetailService medicineDetailService; @Override public Result<MedicineDetailResponse> getDetailOne(Long id) { var medicine = medicineService.getById(id); var medicineDetail = medicineDetailService.getOne(medicineDetailService.lambdaQuery() .eq(MedicineDetailDO::getMedicineId, id)); return Result.convert( MedicineConverter.INSTANCE.mergeDao2DetailResponse(medicine, medicineDetail)); } @Override public Result<Boolean> addDetailOne(MedicineDetailRequest medicineDetailRequest) { return Result.convert( medicineDetailService.saveOrUpdate( MedicineConverter.INSTANCE.req2DetailDO(medicineDetailRequest))); } }
import React, { useState, useRef } from "react"; import CustomInput from "./CustomInput"; export default function App() { const [value, setValue] = useState("red"); const inputRef = useRef(); // console.log("accessing ref from child",inputRef.current.alertHi()); return ( <> <CustomInput ref={inputRef} value={value} onChange={(e) => setValue(e.target.value)} /> <br /> <button onClick={() => inputRef.current.alertHi()}>Click me</button> </> ); }
#!/usr/bin/env python3 levels = { 0x0000: 0, # Level 1 0x4775: 1, # Level 2 0x18b3: 2, # Level 3 0xF83B: 3, # Level 4 } pwd_alphabet_to_char = { 0x0: "A", 0x1: "B", 0x2: "C", 0x3: "F", 0x4: "H", 0x5: "I", 0x6: "J", 0x7: "L", 0x8: "M", 0x9: "O", 0xA: "P", 0xB: "S", 0xC: "T", 0xD: "V", 0xE: "X", 0xF: "Z", } pwd_alphabet_to_bin = { "A": 0x0, "B": 0x1, "C": 0x2, "F": 0x3, "H": 0x4, "I": 0x5, "J": 0x6, "L": 0x7, "M": 0x8, "O": 0x9, "P": 0xA, "S": 0xB, "T": 0xC, "V": 0xD, "X": 0xE, "Z": 0xF, } def decode_password_string(password: str) -> None: in_password = password[0:4] print(password, " -> ", in_password) password_int = 0 for i in range(0, len(password)): # byte_mask = (1 << (i * (4 + 1)) + 4) - 1 # print(f"Byte mask: {byte_mask:b}") print(f"i = {i}") password_int += (pwd_alphabet_to_bin[password[i]] << (i * 4)) print(f"Final password int: {password_int:04x}") message = f"Level {levels[password_int] + 1} unlocked!" if password_int in levels else "Unknown key!" print(message) def decode_password_string_with_score(password: str): in_password = password[0:4] score_string = password[4:8] password_int = 0 print(f"(w/ Score): score string: {score_string}") for i in range(0, len(in_password)): # byte_mask = (1 << (i * (4 + 1)) + 4) - 1 # print(f"Byte mask: {byte_mask:b}") print(f"i = {i}") password_int += (pwd_alphabet_to_bin[in_password[i]] << (i * 4)) print(f"(w/ Score): Final password int: {password_int:04x}") score_int = 0 for i in range(0, len(score_string)): # byte_mask = (1 << (i * (4 + 1)) + 4) - 1 # print(f"Byte mask: {byte_mask:b}") score_int += (pwd_alphabet_to_bin[score_string[i]] << (i * 4)) level_message = f"Level {levels[password_int] + 1} unlocked!" if password_int in levels else "Unknown key!" message = f"Score: {score_int * 100}" print(f"{level_message}. Starting {message}") def main(): decode_password_string("FSMB") decode_password_string("AAAA") decode_password_string("BBBB") decode_password_string_with_score("SFMZAHIA") if __name__ == "__main__": main()
import numpy as np import torch import time import tracemalloc import json import matplotlib.pyplot as plt from safetensors.torch import save_file, load_file # Define paths file_path_vectors = 'output/vectors.safetensors' file_path_docids = 'output/docids.safetensors' def measure_performance(file_path): """ Measures the time and memory used for loading data with SafeTensors. """ # Measure load performance start_time_load = time.time() tracemalloc.start() loaded_data = load_file(file_path) current_load, peak_load = tracemalloc.get_traced_memory() time_taken_load = time.time() - start_time_load tracemalloc.stop() print(f"Time taken to load: {time_taken_load} seconds") print(f"Memory used: {current_load / 10**6} MB; Peak: {peak_load / 10**6} MB") return time_taken_load, current_load, peak_load def verify_data_integrity(original_data, loaded_data, key): """ Verifies that data remains unchanged after saving and loading with SafeTensors. Parameters: - original_data: The original data before saving. - loaded_data: The data loaded from the SafeTensors file. - key: The key used to save and thus to load the data. """ original_tensor = torch.tensor(original_data, dtype=loaded_data[key].dtype) if not torch.equal(original_tensor, loaded_data[key]): print(f"Data integrity check failed for {key}!") print(f"Original data type: {original_tensor.dtype}, Loaded data type: {loaded_data[key].dtype}") print(f"Original shape: {original_tensor.shape}, Loaded shape: {loaded_data[key].shape}") if original_tensor.shape == loaded_data[key].shape: diff = original_tensor != loaded_data[key] print(f"Number of mismatched entries: {diff.sum()}") print(f"Mismatched original data: {original_tensor[diff]}") print(f"Mismatched loaded data: {loaded_data[key][diff]}") assert False, "Mismatch detected." else: print(f"Data integrity verified for {key}.") def check_data_type(data, key): """ Checks the data type of the loaded data. Parameters: - data: The loaded data. - key: The key used to save and thus to load the data. """ if not isinstance(data[key], torch.Tensor): print(f"Data type check failed for {key}!") print(f"Expected data type: torch.Tensor, Actual data type: {type(data[key])}") assert False, "Data type mismatch detected." else: print(f"Data type verified for {key}.") # Load the original data for integrity check # Replace 'load_original_data' with the actual function or method you have to load the original data. # If the original data is not available in the memory, you need to load it from where it was saved before conversion to SafeTensors. # Initialize lists to hold data input_file_path = './input/vectors.part00.jsonl' vectors = [] docids = [] # Process the JSONL file to extract vectors and docids with open(input_file_path, 'r') as file: for line in file: entry = json.loads(line) vectors.append(entry['vector']) docids.append(entry['docid']) # For vectors original_vectors = vectors # This function should be defined by you print(len(original_vectors)) print(len(original_vectors[2])) time_taken_load_vectors, current_load_vectors, peak_load_vectors = measure_performance(file_path_vectors) loaded_vectors = load_file(file_path_vectors) # For vectors verify_data_integrity(original_vectors, loaded_vectors, 'vectors') # For docids # Since docids are not numbers, we should convert them to their corresponding index values. original_docids = docids # This function should be defined by you loaded_docids = load_file(file_path_docids) # Load the docid_to_idx mapping from the JSON file docid_to_idx_path = 'output/docid_to_idx.json' # Update with your actual path with open(docid_to_idx_path, 'r') as f: docid_to_idx = json.load(f) # Now you can use this loaded mapping to convert original_docids to indices # and verify the data integrity using verify_data_integrity function original_docids_idx = [docid_to_idx[docid] for docid in original_docids] verify_data_integrity(original_docids_idx, loaded_docids, 'docids') check_data_type(loaded_vectors, 'vectors') check_data_type(loaded_docids, 'docids')
## Copyright (C) 2002 Etienne Grossmann <etienne@egdn.net> ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see <http://www.gnu.org/licenses/>. ## s = vrml_text(t,...) ## ## Makes vrml Shape node representing string t ## ## Options : ## ## "col" , col : default = [ 0.3 0.4 0.9 ] ## "size" , size : default = 1.0 ## "family", family : default = "SERIF". ## (could also be : "TYPEWRITER", "SANS") ## "style", style : default = "PLAIN". ## (could also be : "BOLD", "ITALIC", "BOLDITALIC") ## "justify", justify : default = "MIDDLE" ## (could also be "FIRST", "BEGIN", "END") function s = vrml_text(t,varargin) col = [0.3,0.4,0.9] ; size = 1.0 ; family = "SERIF" ; justify = "MIDDLE" ; style = "PLAIN" ; verbose = 0 ; filename = "vrml_text" ; if nargin > 1 op1 = " col size family justify style " ; op0 = " verbose " ; df = tars (col, size, family, justify, style, verbose); s = read_options (varargin, "op1",op1,"op0",op0, "default",df); col= s.col; size= s.size; family= s.family; justify= s.justify; style= s.style; verbose= s.verbose; end s = sprintf (["Shape {\n",\ " appearance Appearance {\n",\ " material Material {\n",\ " diffuseColor %8.3f %8.3f %8.3f\n",\ " emissiveColor %8.3f %8.3f %8.3f\n",\ " }\n",\ " }\n",\ " geometry Text {\n",\ " string \"%s\"\n"\ " fontStyle FontStyle {\n",\ " family \"%s\"\n",\ " justify \"%s\"\n",\ " style \"%s\"\n",\ " size %-8.3f\n",\ " }\n",\ " }\n",\ "}\n",\ ],\ col,\ col,\ t,\ family,\ justify,\ style,\ size\ ); endfunction
import { prisma } from "@/infra/prisma-client"; import type { FastifyInstance } from "fastify"; import type { ZodTypeProvider } from "fastify-type-provider-zod"; import z from "zod"; import { BadRequestError } from "../_errors"; import { hash } from "bcryptjs"; export async function resetPassword(app: FastifyInstance) { app.withTypeProvider<ZodTypeProvider>().patch( "/password/reset/:tokenId", { schema: { params: z.object({ tokenId: z.string(), }), body: z.object({ newPassword: z.string().min(8), }), response: { 204: z.null(), }, }, }, async (request, reply) => { const [{ newPassword }, { tokenId }] = [request.body, request.params]; const passwordRecoveryToken = await prisma.token.findUnique({ where: { id: tokenId }, }); if (!passwordRecoveryToken) { throw new BadRequestError("Token inválido"); } const passwordHash = await hash(newPassword, 6); await prisma.$transaction([ prisma.user.update({ where: { id: passwordRecoveryToken.userId }, data: { passwordHash }, }), prisma.token.delete({ where: { id: passwordRecoveryToken.id }, }), ]); return reply.status(204).send(); }, ); }
# 디자인 패턴 <aside> 💡 자바에서 디자인 패턴 사용예시 https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries/2707195#2707195 </aside> ## 싱글톤 패턴이란? <aside> 💡 싱글톤 패턴은 어떤 클래스의 인스턴스가 오직 하나만 생성 되는 것을 보장하며, 이 인스턴스에 접근할 수 있는 전역적인 접촉점을 제공하는 패턴. </aside> ### 싱글톤 패턴을 사용하는 이유 - 한번의 new를 통한 객체 생성으로 단 하나의 객체만이 있음을 보장 - 싱글톤으로 구현한 객체는 전역임으로 다른 클래스들이 데이터를 공유할 수 있다. ### 싱글톤 패턴이 사용되는 경우 > 스프링을 통해 웹 애플리케이션 구현시, 여러가지 요청이 오는경우를 싱글톤으로 해결 가능 요청이 올때마다 새로운 객체를 만들어서 처리한다면, 다량의 요청을 처리하기에 어렵다. 싱글톤을 통해 요청들을 하나의 서비스 객체를 통해 처리가 가능하다. > 이 외에도, 객체 생성에 많은 비용이 들어가는 데이터베이스 커넥션 풀, 쓰레드 풀들이 싱글톤 패턴으로 생성된다. 간단한 싱글톤 코드 ```java class Singleton { //static을 통해 class가 로드될때 객체를 생성 private static Singleton singleton = new Singleton(); private Singleton() {} //생성자에 접근 x public static Singleton getInstance() { return singleton; } } ``` ### 싱글톤 패턴과 유닛 테스트 싱글톤은 하나의 인스턴스만 만들고 해당 인스턴스를 여러 모듈이 공유하여 사용하기 때문에, 유닛 테스트 진행시 모듈간 의존성을 분리시키기가 어렵다는 단점이 있다. ### 의존성 주입 싱글톤 기반의 인스턴스가 구체 클래스를 의존한다면 모듈간 의존도가 매우 올라가가 된다. 그렇기에 인터페이스에 의존하여서 결합도를 낮추는것이 중요하다. --- ### 팩토리 패턴 팩토리 패턴은 간단하게, 객체를 생성하는 클래스를 따로 두는 것을 의미한다. 아래의 코드에서 SimplePhoneFactory에서 원하는 타입만 넣어주면 원하는 타입의 객체를 생성할 수 있는것다. ```java public class SimplePhoneFactory { public Phone orderPhone(String type) { Phone phone = createPhone(type); phone.complete(); return phone; } private Phone createPhone(String type) { return switch (type) { case "IPHONE" -> new IPhone(); case "ANDROID" -> new AndroidPhone(); default -> null; }; } } ``` 팩토리 패턴은 단순히 객체를 만드는 작업을 하나의 팩토리 클래스에 모아두는 것을 의미한다. ### 팩토리 메소드 패턴 / 추상 팩토리 패턴 ### 팩토리 메소드 패턴 팩토리 메소드 패턴의 정의는 다음과 같다. <aside> 💡 객체를 생성하기 위한 인터페이스를 정의하는 과정에서 어떤 클래스의 인스턴스를 만들지는`서브클래스`에서 결정 **클래스의 인스턴스를 만드는 일을 `서브클래스`에게 맡기는 것** </aside> 위의 예시에선 SimplePhoneFactory라는 곳에 직접 만들고자 하는 객체의 이름을 주어 해당 Factory에서 객체를 만들어 주었다면, 팩토리 메소드 패턴은 위의 팩토리 패턴에 추상화 단계가 올라간 형태이다. 팩토리 자체를 인터페이스로 만들어 객체를 생성하고 싶은 팩토리를 해당 인터페이스를 구현하고, 그 팩토리에서 객체를 생성하는 것이다. ```java public interface PhoneFactory { default Phone orderPhone() { Phone phone = createPhone(); phone.complete(); return phone; } Phone createPhone(); } public class IPhoneFactory implements PhoneFactory { @Override public Phone createPhone() { return new IPhone(); } } public class AndroidPhoneFactory implements PhoneFactory { @Override public Phone createPhone() { return new AndroidPhone(); } } ``` ### 추상 팩토리 패턴 추상 팩토리 패턴은 팩토리 메소드 패턴을 한번 더 추상화해, 하나의 Factory에서 여러개의 제품군(Product)조합을 생성할 수 있게 해주는 패턴이다. Factory라는 인터페이스를 정의하고, 아래의 코드와 같이 회사를 인자로 받으면 해당 회사에 해당되는 팩토리를 받환받을 수 있다. ```java public interface PhoneAbstractFactory { PhoneFactory requestPhone(String company); } public class DefaultPhoneFactoryOfFactory implements PhoneAbstractFactory { @Override public PhoneFactory requestPhone(String company) { switch (company) { case "IPHONE": return new IPhoneFactory(); case "ANDROID": return new AndroidPhoneFactory(); } throw new IllegalArgumentException(); } } ``` --- ### 전략 패턴(strategy pattern) 객체들이 할 수 있는 행위 각각에 대해 전략 클래스를 생성하고, 유사한 행위들을 캡슐화 하는 인터페이스를 정의하여, 행위를 유연하게 확장하는 방법을 말합니다. 쉽게 예를 들어 Car 클래스에 move라는 메소드를 만들었다고 생각해보자. 예전에는 Car라는 것이 move하는 동작은 정해져 있기에, Car 클래스에서 move라는 메소드를 가진 인터페이스를 구현하면 되었다. 하지만 시간이 지나, 자동차마다 움직임의 동작이 조금씩 달라 문제가 생기기 시작했다. 기존의 것을 바꾸지 않고, 여러 클래스에서 해당 메소드만 바꾸고 사용하려면 중복이 많아진다는 문제점이 있다. 그렇기에 행위 자체를 추상화하여 클래스 레벨이 아닌 메소드 레벨에도 유연한 동작이 가능하도록 설계하는 것이 전략패턴이다. ### 전략 패턴 구현 구현하는 방법은 기존의 클래스를 인터페이스로 만들어 행위를 정의한것처럼, 행위에 대한 Strategy inferace를 만들고, 그 행위에 대한 명세를 구체 클래스에서 작성한다. ```java public interface MovableStrategy { public void move(); } public class RailLoadStrategy implements MovableStrategy{ public void move(){ System.out.println("선로를 통해 이동"); } } public class LoadStrategy implements MovableStrategy{ public void move() { System.out.println("도로를 통해 이동"); } } ``` 아래의 코드와 같이 구체 클래스에선 행위에 대해 추상화를 높히고, 구현체를 직접 받는 방식으로 코드를 작성하면 아래와 같이 유연하게 다양한 행위를 사용할 수 있다. ```java train.setMovableStrategy(new RailLoadStrategy()); bus.setMovableStrategy(new LoadStrategy()); train.move(); bus.move(); bus.setMovableStrategy(new RailLoadStrategy()); bus.move(); ``` --- ### 옵저버 패턴 > **옵서버 패턴**(observer pattern)은 [객체](https://ko.wikipedia.org/wiki/%EA%B0%9D%EC%B2%B4_(%EC%BB%B4%ED%93%A8%ED%84%B0_%EA%B3%BC%ED%95%99))의 상태 변화를 관찰하는 관찰자들, 즉 옵저버들의 목록을 객체에 등록하여 상태 변화가 있을 때마다 [메서드](https://ko.wikipedia.org/wiki/%EB%A9%94%EC%84%9C%EB%93%9C) 등을 통해 객체가 직접 목록의 각 옵저버에게 통지하도록 하는 [디자인 패턴](https://ko.wikipedia.org/wiki/%EB%94%94%EC%9E%90%EC%9D%B8_%ED%8C%A8%ED%84%B4)이다. 주로 분산 이벤트 핸들링 시스템을 구현하는 데 사용된다. [발행/구독 모델](https://ko.wikipedia.org/wiki/%EB%B0%9C%ED%96%89/%EA%B5%AC%EB%8F%85_%EB%AA%A8%EB%8D%B8)로 알려져 있기도 하다. - 위키백과 > 간단하게 어떤 객체의 상태가 변할 때 그와 연관된 객체 들에게 알림을 보내는 디자인 패턴이다. ### Java에서의 Observer 와 Observable 멀티쓰레드 환경에서 옵저버 패턴이 잘 동작하도록 Java에서 제공하는 옵저버 패턴이있다. Observable은 발행자이고, Observer는 구독자이다. 발행자 클래스에서 Observable 클래스를 상속받아서 사용하면 된다. 해당 클래스를 보니 Vector로 Observer들을 가질 수 있고, Observer들에게 Observable클래스에있는 메소드들을 실행할 수 있을것으로 짐작할 수 있다. <img src = "https://velog.velcdn.com/images/wook2pp/post/817b15ae-febe-41b0-84cf-d7dab18d10d9/image.png" width="50%" height="50%"> <img src = "https://velog.velcdn.com/images/wook2pp/post/f923ce2f-2038-443a-9508-8d717bbe5975/image.png" width="50%" height="50%"> Observer들에게 notify하고 싶다면, notifyObservers 메서드를 통해 obj를 넘겨 update를 하는 것으로 보인다. Observer 인터페이스를 살펴보면, > This method is called whenever the observed object is changed. An application calls an Observable object's notifyObservers method to have all the object's observers notified of the change. > update메소드는 observed된 객체가 변화하면 항상 불려지고, Observable객체들에 notifyObservers 메소드가 실행되면 구독중인 Observer들이 변화를 받는것으로 보인다. --- ### 프록시 패턴 > 일반적으로 프록시는 다른 무언가와 이어지는 인터페이스의 역할을 하는 클래스이다. 프록시는 어떠한 것(이를테면 네트워크 연결, 메모리 안의 커다란 객체, 파일, 또 복제할 수 없거나 수요가 많은 리소스)과도 인터페이스의 역할을 수행할 수 있다. - 위키백과 > 프록시는 주로 대리자라고 불리는데, 기존 요청객체로 바로 요청을 보내는 것이 아니라 대리자에게 먼저 전달해 부가기능을 추가하거나, 분기를 처리하는 등 새로운 기능을 추가할 수 있다. 즉 프록시는 대상 객체를 composition하여 멤버변수로 가지고 있다. 자바에서는 프록시 클래스를 통해 프록시 객체를 생성할 수 있다. --- ### 이터레이터 패턴 > [위키백과] > > > **반복자 패턴**(iterator pattern)은 [객체 지향 프로그래밍](https://ko.wikipedia.org/wiki/%EA%B0%9D%EC%B2%B4_%EC%A7%80%ED%96%A5_%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D)에서 [반복자](https://ko.wikipedia.org/wiki/%EB%B0%98%EB%B3%B5%EC%9E%90)를 사용하여 [컨테이너](https://ko.wikipedia.org/wiki/%EC%BB%A8%ED%85%8C%EC%9D%B4%EB%84%88)를 가로지르며 컨테이너의 요소들에 접근하는 [디자인 패턴](https://ko.wikipedia.org/wiki/%EB%94%94%EC%9E%90%EC%9D%B8_%ED%8C%A8%ED%84%B4)이다. 반복자 패턴은 컨테이너로부터 [알고리즘](https://ko.wikipedia.org/wiki/%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98)을 분리시키며, 일부의 경우 알고리즘들은 필수적으로 컨테이너에 특화되어 있기 때문에 분리가 불가능하다. > 객체를 저장하는 방식은 보여주지 않으면서도 클라이언트가 객체들에게 일일이 접근할 수 있게 해주는 방법이다. 이 패턴의 구현 방법은 반복 작업을 Iterator 인터페이스를 이용하여 캡슐화 하는 것이다. 집합체의 내부 구조를 노출하지 않고 순회 할 수 있다는 장점이 있다. --- ### MVC 패턴 화면에 보여주는 로직과 실제 데이터가 처리 되는 로직을 분리하기 위해 만들어진 패턴 - Model : 모델에는 애플리케이션의 데이터 형식, - View : 모델을 기반으로 사용자에게 제공되어 보여지는 UI 부분 - Controller : 뷰로부터 변경사항을 받으면 Model에 변경사항을 전달해준다. ### MVP 패턴의 장점 - 애플리케이션의 구성 요소를 세 가지 역할로 구분하여 개발 프로세스에서 각각의 구성 요소에만 집중해서 개발 - 재사용성과 확장성이 용이 ### MVP 패턴의 단점 - 애플리케이션이 복잡해질수록 뷰와 모델간 의존성이 복잡해질 가능성이 있다. --- ### MVP 패턴 • MVP 패턴은 MVC 패턴으로부터 파생되었으며 MVC에서 C에 해당하는 컨트롤러가 프레젠터(presenter)로 교체된 패턴 - Presenter는 ***View와 Model의 인스턴스를 가짐 ⇒ 결합도가 크다*** - ***뷰와 프레젠터는 일대일 관계*** → MVC 패턴보다 더 강한 결합을 지님 결합도가 크기 때문에, 애플리케이션 복잡도가 증가하면 결합도 문제해결이 어렵다. --- ### MVVC 패턴 뷰모델은 뷰를 더 추상화한 계층이다. View를 나타내 주기 위한 Model이자 View를 나타내기 위한 데이터 처리 를 하는 부분 view와 view Model에서는 데이터 바인딩을 하고 변경에 대한 처리를 View Model에 넘기고, View Model에서 Model에 모델의 변화를 처리한 뒤, 다시 View Model로 위임하게 된다.
package com.github.elongeau.pocziohttp import zhttp.http._ import zhttp.service.server.ServerChannelFactory import zhttp.service.{EventLoopGroup, Server} import zio.json._ object Main extends App { val app: Http[Has[Greeting.Service], Throwable, Request, Response] = Http.collectZIO[Request] { case Method.GET -> !! / "text" => for { greetings <- Greeting.greet } yield Response.text(greetings.toJson) } private val server = Server.port(8090) ++ // Setup port Server.app(app) // Setup the Http app // Run it like any simple app override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] = { val value: ZIO[zio.ZEnv, Any, Nothing] = server .make .use(start => console.putStrLn(s"Server started on port ${start.port}") *> ZIO.never, ) .provideCustomLayer(ServerChannelFactory.auto ++ EventLoopGroup.auto(2) ++ Greeting.live) value.exitCode } }
"use client" import Button from "@/app/components/Button" import Input from "@/app/components/inputs/Input" import { useCallback, useEffect, useState } from "react" import { BsGithub, BsGoogle } from "react-icons/bs" import { FieldValues, useForm, SubmitHandler } from "react-hook-form" import AuthSocialButton from "./AuthSocialButton" import axios from "axios" import { toast } from "react-hot-toast" import { signIn, useSession } from "next-auth/react" import {useRouter} from "next/navigation" type Variant = "LOGIN" | "REGISTER" export default function AuthForm() { const [variant, setVariant] = useState<Variant>("LOGIN") const [isLoading, setIsLoading] = useState(false) const session = useSession() const router = useRouter() useEffect(()=>{ if(session?.status==='authenticated'){ router.push('/users') } },[router, session?.status]) const toggleVariant = useCallback(() => { if (variant === "LOGIN") { setVariant("REGISTER") } else { setVariant("LOGIN") } }, [variant]) const { register, handleSubmit, formState: { errors }, } = useForm<FieldValues>({ defaultValues: { name: "", email: "", password: "", }, }) const onSubmit: SubmitHandler<FieldValues> = (data) => { setIsLoading(true) if (variant === "REGISTER") { axios .post("/api/register", data) .then(()=>signIn('credentials', data)) .catch(() => toast.error("出错了!")) .finally(() => setIsLoading(false)) } if (variant === "LOGIN") { signIn('credentials',{ ...data, redirect: false }).then((callback)=>{ if(callback?.error){ toast.error('无效账户') } if(callback?.ok&&!callback?.error){ toast.success('登陆成功') router.push('/users') } }).finally(()=>setIsLoading(false)) } } const socialAction = (action: string) => { setIsLoading(true) signIn(action, {redirect: false}).then((callback)=>{ if(callback?.error){ toast.error('无效账户') } if(callback?.ok&&!callback?.error){ toast.success('登陆成功') router.push('/users') } }).finally(()=>setIsLoading(false)) } return ( <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md"> <div className="bg-white px-4 py-8 shadow sm:rounded-lg sm:px-10"> <form className="space-y-6" onSubmit={handleSubmit(onSubmit)}> {variant === "REGISTER" && ( <Input id="name" label="账号" register={register} errors={errors} disabled={isLoading} /> )} <Input id="email" label="邮件" type="email" register={register} errors={errors} disabled={isLoading} /> <Input id="password" label="密码" type="password" register={register} errors={errors} disabled={isLoading} /> <div> <Button disabled={isLoading} fullWidth type="submit"> {variant === "LOGIN" ? "登录" : "注册"} </Button> </div> </form> <div className="mt-6"> <div className="relative"> <div className=" absolute inset-0 flex items-center " > <div className="w-full border-t border-gray-300" /> </div> <div className="relative flex justify-center text-sm"> <span className="bg-white px-2 text-gray-500">其他登陆方式</span> </div> </div> <div className="mt-6 flex gap-2"> <AuthSocialButton icon={BsGithub} onClick={() => socialAction("github")} /> <AuthSocialButton icon={BsGoogle} onClick={() => socialAction("google")} /> </div> </div> <div className=" flex gap-2 justify-center text-sm mt-6 px-2 text-gray-500 " > <div>{variant === "LOGIN" ? "没有账户?" : "已有账户?"}</div> <div onClick={toggleVariant} className="underline cursor-pointer"> {variant === "LOGIN" ? "创建账户" : "登录"} </div> </div> </div> </div> ) }
const express = require('express'); const router = express.Router(); const { check, validationResult } = require('express-validator'); const jwt = require('jsonwebtoken'); const config = require('config'); const bcrypt = require('bcryptjs'); const User = require('../../models/User'); const isBlank = (str) => !str || /^\s*$/.test(str); router.post( '/', check('name', 'Name is required').not().isEmpty(), check('email', 'Please include a valid email').isEmail(), check( 'password', 'Please enter a password with minimum of 6 characters' ).isLength({ min: 6 }), async (req, res) => { const errors = validationResult(req); console.log(errors); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { name, email, githubusername, password } = req.body; try { let user = await User.findOne({ email }); if (user) { return res.status(400).json({ errors: [{ msg: 'User Exists!' }] }); } let avatar = !isBlank(githubusername) ? `https://avatars.githubusercontent.com/${githubusername}?s=200` : `https://ui-avatars.com/api/?name=${name .replace(/\s\s+/g, ' ') .split(' ') .join('+')}&size=200`; user = new User({ name, email, githubusername, avatar, password, }); const salt = await bcrypt.genSalt(); user.password = await bcrypt.hash(password, salt); await user.save(); const payload = { user: { id: user.id, }, }; jwt.sign( payload, config.get('jwtSecret'), { expiresIn: 360000 }, (err, token) => { if (err) throw err; res.json({ token }); } ); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } } ); module.exports = router;
<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>Sindupedia</title> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css"> <!-- Bootstrap Js --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> </head> <body class="d-flex justify-content-center"> <div> {% with alerts = get_flashed_messages(with_categories=true) %} {% if alerts %} {% for category,alt in alerts %} {% if category == "error" %} <div class="alert alert-danger text-center" role="alert"> <p>{{alt}}</p> </div> {% elif category == "info" %} <div class="alert alert-success text-center" role="alert"> <p>{{alt}}</p> </div> {% endif %} {% endfor %} {% endif %} {% endwith %} <div class="text-center text-uppercase mt-4"> <h1 class="font-weight-bold brand">Sindupedia</h1> </div> <div class="text-center selection-header"> <div class="row"> <div class="col"> <a href="/" style="text-decoration:none;"><h5 class="font-weight-light text-secondary">Login</h5></a> </div> <div class="col"> <a href="#" style="text-decoration:none;"><h5 class="font-weight-light text-dark">Sign In</h5></a> </div> </div> </div> <form action="#" method="post" class="mt-1"> <div class="form-group p-3"> <label for="fname" class="text-dark">First Name</label> <input required type="text" class="form-control custom-input" name="fname" aria-describedby="fname" placeholder="Enter first name" autocomplete="off"> </div> <div class="form-group p-3"> <label for="lname" class="text-dark">Last Name</label> <input required type="text" class="form-control custom-input" name="lname" aria-describedby="lname" placeholder="Enter last name" autocomplete="off"> </div> <div class="form-group p-3"> <label for="email" class="text-dark">Email</label> <input required type="email" class="form-control custom-input" name="email" aria-describedby="email" placeholder="Enter email" autocomplete="off"> </div> <div class="form-group p-3"> <label for="password" class="text-dark">Password</label> <input required type="password" class="form-control custom-input" name="password" id="password" placeholder="Enter password" autocomplete="off"> <span class="bi bi-eye-slash field-icon" id="passwordToggle"></span> <small class="form-text text-muted">We'll never share your password with anyone else.</small> </div> <div class="row d-flex justify-content-center pt-3"> <button type="submit" class="btn btn-dark w-50">Confirm</button> </div> </form> <div class="text-center pt-3"> <a href="/" class="link-secondary"><small >Already have an account? Log In</small></a> </div> </div> <script> let icon = document.getElementById('passwordToggle') let password = document.getElementById('password') icon.addEventListener('click', function(){ let type = password.getAttribute('type') === 'password' ? 'text':'password'; password.setAttribute('type',type); this.classList.toggle("bi-eye"); }); </script> </body> <style> body{ font-family: 'Inter', sans-serif; } .brand{ font-family: 'Poppins', sans-serif; } .selection-header{ margin-top: 75px; } .custom-labels{ padding-left: 12px; margin-bottom: 3px; } .custom-input{ border: none; border-bottom: 2px solid #e0e0eb; } .field-icon { float: right; padding-right: 10px; margin-left: -25px; margin-top: -25px; position: relative; z-index: 2; } </style> </html>
<?php namespace App\Modules\Media\Http\Controllers; use App\Modules\Media\Contracts\Requests\BulkCreateMediaRequestContract; use App\Modules\Media\Contracts\Requests\CreateMediaRequestContract; use App\Modules\Media\Contracts\Requests\DeleteMediaRequestContract; use App\Modules\Media\Contracts\Requests\SearchMediaRequestContract; use App\Modules\Media\Contracts\Resources\MediaCollectionContract; use App\Modules\Media\Contracts\Resources\MediaListResourceContract; use App\Modules\Media\Contracts\Resources\MediaResourceContract; use App\Modules\Media\Contracts\Services\MediaServiceContract; use App\Modules\Media\Http\Resources\MediaCollection; use App\Modules\Media\Http\Resources\MediaResource; use Illuminate\Routing\Controller; use Symfony\Component\HttpFoundation\Response; use function response; class MediaController extends Controller { public function create( CreateMediaRequestContract $request, MediaServiceContract $mediaService ): MediaResourceContract { $file = $request->file('file'); $data = $request->onlyValidated(); $content = file_get_contents($file->getPathname()); $media = $mediaService->create($content, $file->getClientOriginalName(), $data); return new MediaResource($media); } public function delete(DeleteMediaRequestContract $request, MediaServiceContract $mediaService, int $id): Response { $mediaService->delete($id); return response('', Response::HTTP_NO_CONTENT); } public function search( SearchMediaRequestContract $request, MediaServiceContract $mediaService ): MediaCollectionContract { $result = $mediaService->search($request->onlyValidated()); return MediaCollection::make($result); } public function bulkCreate( BulkCreateMediaRequestContract $request, MediaServiceContract $mediaService ): MediaListResourceContract { $result = $mediaService->bulkCreate($request->onlyValidated('media')); return MediaCollection::make($result); } }
import { Dialog, DialogActions, DialogContent } from '@mui/material'; import { Button, SaveButton, TextInput, useNotify, useRecordContext, RaRecord, required, maxLength, useListContext, Form, useDataProvider, } from 'react-admin'; import IconCancel from '@mui/icons-material/Cancel'; import IconContentAdd from '@mui/icons-material/Edit'; import { useToggler } from '../../../useToggler'; import { useMutation } from 'react-query'; import { FieldValue, FieldValues } from 'react-hook-form'; import { CustomDataProvider } from '../../../dataProvider'; export const EditStepDownloadButton = () => { const { value, setTrue, setFalse } = useToggler(); const record = useRecordContext(); const { mutate, isLoading } = useMutation( ['step-downloads', record.id], (values: FieldValues) => dataProvider.updateMultipart('step-downloads', { data: values, id: record.id, previousData: {}, }), { onSuccess: (data) => { setFalse(); notify('ra.notification.updated', { type: 'success', messageArgs: { smart_count: 1 }, }); refetch(); }, onError: (error) => { notify('ra.page.error', { type: 'error' }); }, } ); const notify = useNotify(); const { refetch } = useListContext(); const dataProvider = useDataProvider<CustomDataProvider>(); const onSave = (values: Partial<RaRecord>) => mutate(values); return ( <> <Button onClick={setTrue} label="Edit"> <IconContentAdd /> </Button> <Dialog maxWidth="sm" fullWidth open={value}> <Form defaultValues={record} onSubmit={onSave}> <> <DialogContent> <TextInput multiline fullWidth source="title" label="Title" placeholder="Type the download title, for example 'Download dataset'" helperText="The download title" validate={[required(), maxLength(150)]} /> </DialogContent> <DialogActions> <Button label="ra.action.cancel" onClick={setFalse} disabled={isLoading} > <IconCancel /> </Button> <SaveButton /> </DialogActions> </> </Form> </Dialog> </> ); };
<template> <div class="flex items-center"> <div class="relative"> <input type="text" placeholder="Search by Dota ID or Steam Name" class="px-5 py-3 w-80" v-model="searchField" @input="debounceSearch" @keyup.enter="onEnter"> <SearchResults v-show="showResults" :user-list="searchResults" /> </div> <button class="bg-black px-3 py-3" @click="onEnter"> <font-awesome-icon icon="fa-regular fa-magnifying-glass" size="xl" class="text-white" /> </button> </div> </template> <script setup> import { useStore } from '~/stores/store.js' import { useToast } from 'vue-toastification' const toast = useToast() const store = useStore() const { getSearchUser } = useStore() const searchField = ref('') const debounceTimeout = ref(null) const searchResults = computed(() => store?.searchedUserData) const showResults = ref(false) const searchUser = async () => { getSearchUser(searchField.value) showResults.value = true } const onEnter = () => { showResults.value = false navigateTo(`/search/${searchField.value}`) } const debounceSearch = () => { if (debounceTimeout.value) clearTimeout(debounceTimeout.value); debounceTimeout.value = setTimeout(() => { searchUser() }, 500) } </script>
using AgencyService.Enums; using AgencyService.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace AgencyService.Data.Configuration { public class AgencyConfiguration : IEntityTypeConfiguration<Agency> { public void Configure(EntityTypeBuilder<Agency> builder) { builder.HasKey(x => x.Id); builder.Property(x => x.Name).IsRequired(); builder.HasMany(x => x.PaymentServices).WithOne(x => x.Agency).HasForeignKey(x=> x.AgencyId); builder.HasMany(x=> x.Users).WithOne(x=> x.Agency).HasForeignKey(x=>x.AgencyId); builder.HasMany(x=> x.ServiceOfferItems).WithOne(x=> x.Agency).HasForeignKey(x=> x.AgencyId); builder.HasData(new Agency() { Id = 1, Name = "Agency" }); } } }
import { User } from "@entities/user.entity"; import { UserDecorator } from "@generics/User.decorator"; import { RecaptchaGuard } from "@guards/recaptcha.guard"; import { RefreshJwtAuthGuard } from "@guards/refresh-jwt.guard"; import { Body, Controller, Get, HttpCode, Post, Req, UnauthorizedException, UseGuards, } from "@nestjs/common"; import { ConfigService } from "@nestjs/config"; import { ApiTags } from "@nestjs/swagger"; import { CookieOptions, Request } from "express"; import { RefreshService } from "./use-cases/refresh/refresh.service"; import { SignInDto } from "./use-cases/sign-in/sign-in.dto"; import { SignInService } from "./use-cases/sign-in/sign-in.service"; import { SignOutService } from "./use-cases/sign-out/sign-out.service"; import { SignUpDto } from "./use-cases/sign-up/sign-up.dto"; import { SignUpService } from "./use-cases/sign-up/sign-up.service"; @ApiTags("authentication") @Controller("auth") export class AuthController { private readonly refreshPaths = ["refresh", "sign-out"]; private readonly configService: ConfigService; private readonly signUpService: SignUpService; private readonly signInService: SignInService; private readonly signOutService: SignOutService; private readonly refreshService: RefreshService; public constructor( configService: ConfigService, signUpService: SignUpService, signInService: SignInService, signOutService: SignOutService, refreshService: RefreshService, ) { this.configService = configService; this.signUpService = signUpService; this.signInService = signInService; this.signOutService = signOutService; this.refreshService = refreshService; } @Post("sign-up") @UseGuards(RecaptchaGuard) public async signUp(@Body() body: SignUpDto) { return await this.signUpService.execute(body); } @Post("sign-in") @UseGuards(RecaptchaGuard) public async signIn(@Req() request: Request, @Body() body: SignInDto) { const tokens = await this.signInService.execute(body); const { refreshToken, ...rest } = tokens; this.setResponseRefreshToken( request, refreshToken.refresh_token, refreshToken.expiresAt, ); return rest; } @Post("sign-out") @HttpCode(204) public async signOut(@Req() request: Request) { try { await this.signOutService.execute(request.cookies["refresh_token"]); } finally { this.clearResponseRefreshToken(request); } } @Get("refresh") @UseGuards(RefreshJwtAuthGuard) public async refresh(@Req() request: Request, @UserDecorator() user: User) { try { const tokens = await this.refreshService.execute(user); const { refreshToken, ...rest } = tokens; if (refreshToken != null) { this.setResponseRefreshToken( request, refreshToken.refresh_token, refreshToken.expiresAt, ); } return rest; } catch (err) { if (err instanceof UnauthorizedException) { this.clearResponseRefreshToken(request); } throw err; } } private setResponseRefreshToken( request: Request, refreshToken: string, expiresAt: Date, ) { const cookie: CookieOptions = { httpOnly: true, expires: expiresAt, secure: this.configService.get<string>("NODE_ENV") !== "development", sameSite: "none", }; for (const path of this.refreshPaths) { request.res.cookie("refresh_token", refreshToken, { ...cookie, path: `/${this.configService.get<string>("host.PREFIX")}/auth/${path}`, }); } } private clearResponseRefreshToken(request: Request) { for (const path of this.refreshPaths) { request.res.clearCookie("refresh_token", { path: `/${this.configService.get<string>("host.PREFIX")}/auth/${path}`, }); } } }
<!DOCTYPE html> <html lang="en-US"> <head> <title>Green Foundation</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <link rel="stylesheet" href="css/index.css"> </head> <body> <div id="pageLayoutGrid"> <!-- Navigation section of the grid --> <nav id="nav"> <ul id="navItems"> <li class="navItem"> <a href="#" class="navLink logo">Green Foundation</a> </li> <li class="navItem"> <a href="#" class="navLink">About</a> <div class="navDropdown"> <a href="#" class="navDropdownLink">Mission and Vision</a> <a href="#" class="navDropdownLink">History</a> </div> </li> <li class="navItem"> <a href="#" class="navLink">Projects</a> </li> <li class="navItem"> <a href="#" class="navLink">News</a> <div class="navDropdown"> <a href="#" class="navDropdownLink">Events Calendar</a> <a href="#" class="navDropdownLink">Image Gallery</a> </div> </li> <li class="navItem"> <a href="#" class="navLink">Get Involved</a> <div class="navDropdown"> <a href="#" class="navDropdownLink">Donate</a> <a href="#" class="navDropdownLink">Online Store</a> <a href="#" class="navDropdownLink">Volunteer</a> </div> </li> <li class="navItem"> <a href="#" class="navLink">Contact Us</a> </li> </ul> <!-- CTA is short for Call To Action --> <div id="navCtas"> <a href="#" class="navCta">DONATE</a> </div> </nav> <!-- Hero section of the grid --> <header id="header"> <div class="eyebrow">Planting the Seeds of the Future</div> <h1 class="heroHeading"> Poverty and environmental degradation are intrinsically linked. By healing the environment, we can heal lives as well. </h1> <form> <!-- TODO: Add in the form inputs for users to subscribe their email --> </form> </header> <!-- Banner section of the grid --> <div id="bannerItem1" class="bannerItem"> <h3>Get Started in Your Community</h3> <p> Curious about what you can do in your neighborhood? Download our free eBook to find out. </p> <div class="bannerActions"> <a class="downloadButton" href="#">DOWNLOAD</a> </div> </div> <div id="bannerItem2" class="bannerItem"> <h3>Take Part in our<br>Green Thumb Initiative</h3> <p> Community gardens are an excellent opportunity to provide for the needy in your neighborhood, while also providing a chance to educate young people about how food is grown. </p> <div class="bannerActions"> <a class="learnMoreButton" href="#">LEARN MORE</a> </div> </div> <div id="bannerItem3" class="bannerItem"> <h3>Follow Us on Our<br>Social Media Accounts</h3> <p> Engage with us online! We post at least once a day, and we'd love to hear from you about how the Green Foundation has helped in your community. </p> <div class="bannerActions"> <a class="socialMediaLink" href="#"> <!-- TODO: fix image src --> <img src="../../images/10wmt-superJumbo-v4.jpeg" alt="twitter" /> </a> <a class="socialMediaLink" href="#"> <!-- TODO: fix image src --> <img src="../../images/26-267842_facebook-round-logo-png-transparent-background-facebook-logo.png" alt="facebook" /> </a> <a class="socialMediaLink" href="#"> <!-- TODO: fix image src --> <img src="../../images/ew-instagram-logo-transparent-related-keywords-logo-instagram-vector-2017-115629178687gobkrzwak.webp" alt="instagram" /> </a> </div> </div> <!-- Storefront section of the grid --> <section id="storefront"> <h2>Add some GREEN into your life from our online store</h2> <div id="shopGrid"> <div class="shopItemCard"> <!-- TODO: fix image src --> <img style="width: 100px" class="shopItemImage" alt="tshirt1" src="../../images/man(clothing).jpeg" /> <div class="shopItemBadge">TSHIRT</div> <form class="shopItemSelection"> <select name="quantity"> <option value="">--Select a Quantity--</option> <option value="fruits">1</option> <option value="vegetables">2</option> <option value="meats">3</option> <option value="grains">4</option> <option value="dairy">5</option> </select> <!-- TODO: change button text to say "Buy" or "Purchase" --> <input type="submit" value="Purchase"> </form> </div> <div class="shopItemCard"> <!-- TODO: fix image src --> <img style="width: 90px" class="shopItemImage" alt="tshirt2" src="../../images/clothing(woman).jpg" /> <div class="shopItemBadge">TSHIRT</div> <form class="shopItemSelection"> <select name="quantity"> <option value="">--Select a Quantity--</option> <option value="fruits">1</option> <option value="vegetables">2</option> <option value="meats">3</option> <option value="grains">4</option> <option value="dairy">5</option> </select> <!-- TODO: change button text to say "Buy" or "Purchase" --> <input type="submit" value="Purchase"> </form> </div> <div class="shopItemCard"> <!-- TODO: fix image src --> <img style="width: 100px" class="shopItemImage" alt="tshirt3" src="../../images/clothing(3).jpeg" /> <div class="shopItemBadge">TSHIRT</div> <form class="shopItemSelection"> <select name="quantity"> <option value="">--Select a Quantity--</option> <option value="fruits">1</option> <option value="vegetables">2</option> <option value="meats">3</option> <option value="grains">4</option> <option value="dairy">5</option> </select> <!-- TODO: change button text to say "Buy" or "Purchase" --> <input type="submit" value="Purchase"> </form> </div> <div class="shopItemCard"> <!-- TODO: fix image src --> <img style="width: 100px" class="shopItemImage" alt="tshirt4" src="../../images/clothing(4).jpeg" /> <div class="shopItemBadge">TSHIRT</div> <form class="shopItemSelection"> <select name="quantity"> <option value="">--Select a Quantity--</option> <option value="fruits">1</option> <option value="vegetables">2</option> <option value="meats">3</option> <option value="grains">4</option> <option value="dairy">5</option> </select> <!-- TODO: change button text to say "Buy" or "Purchase" --> <input type="submit" value="Purchase"> </form> </div> <div class="shopItemCard"> <!-- TODO: fix image src --> <img style="width: 100px" class="shopItemImage" alt="mug1" src="../../images/mug2.jpeg" /> <div class="shopItemBadge">COFFEE MUG</div> <form class="shopItemSelection"> <select name="quantity"> <option value="">--Select a Quantity--</option> <option value="fruits">1</option> <option value="vegetables">2</option> <option value="meats">3</option> <option value="grains">4</option> <option value="dairy">5</option> </select> <!-- TODO: change button text to say "Buy" or "Purchase" --> <input type="submit" value="Purchase"> </form> </div> <div class="shopItemCard"> <!-- TODO: fix image src --> <img style="width: 100px" class="shopItemImage" alt="mug2" src="../../images/mug.jpeg" /> <div class="shopItemBadge">COFFEE MUG</div> <form class="shopItemSelection"> <select name="quantity"> <option value="">--Select a Quantity--</option> <option value="fruits">1</option> <option value="vegetables">2</option> <option value="meats">3</option> <option value="grains">4</option> <option value="dairy">5</option> </select> <!-- TODO: change button text to say "Buy" or "Purchase" --> <input type="submit" value="Purchase"> </form> </div> <div class="shopItemCard"> <!-- TODO: fix image src --> <img style="width: 100px" class="shopItemImage" alt="seeds1" src="../../images/seedImage.jpeg" /> <div class="shopItemBadge">SEEDS</div> <form class="shopItemSelection"> <select name="quantity"> <option value="">--Select a Quantity--</option> <option value="fruits">1</option> <option value="vegetables">2</option> <option value="meats">3</option> <option value="grains">4</option> <option value="dairy">5</option> </select> <!-- TODO: change button text to say "Buy" or "Purchase" --> <input type="submit" value="Purchase"> </form> </div> <div class="shopItemCard"> <!-- TODO: fix image src --> <img style="width: 100px" class="shopItemImage" alt="seeds2" src="../../images/seed-sowing.jpeg" /> <div class="shopItemBadge">SEEDS</div> <form class="shopItemSelection"> <select name="quantity"> <option value="">--Select a Quantity--</option> <option value="fruits">1</option> <option value="vegetables">2</option> <option value="meats">3</option> <option value="grains">4</option> <option value="dairy">5</option> </select> <!-- TODO: change button text to say "Buy" or "Purchase" --> <input type="submit" value="Purchase"> </form> </div> </div> </section> <!-- Blog section of grid --> <div id="blog"> <h2>Check out our latest blog posts</h2> <div class="blogPost"> <!-- TODO: fix image src --> <img src="../../images/colourful-herbaceous-flower-borders-in-the-summer-royalty-free-image-1585433134.webp" class="blogPostImage" alt="happy plants" /> <div class="blogPostPreview"> <h3 class="blogPostPreviewTitle"> Will talking to plants help them grow? </h3> <p> We've heard some pretty ridiculous urban (and rural) myths when it comes to growing your crops. But just because they sound silly doesn't mean they aren't true. So we decided to try them out ourselves to find out just how... </p> <a href="#">Keep reading</a> </div> </div> <div class="blogPost"> <div class="blogPostPreview"> <h3 class="blogPostPreviewTitle"> Arid field becomes radiant garden </h3> <p> An empty barren field on the outskirts of a rural village in the south had been a blight on the poor but otherwise lively town. Fast forward six months, and see what a difference a little irrigation made in the lives of these villagers... </p> <a href="#">Keep reading</a> </div> <!-- TODO: fix image src --> <img src="../../images/Happy.jpeg" class="blogPostImage" alt="happy people" /> </div> </div> <!-- Footer section of grid --> <div id="footer"> <div id="footerItems"> <div class="footerItem"> <a href="#" class="footerLink">Green Foundation</a> </div> <div class="footerItem"> <a href="#" class="footerLink">About</a> <a href="#" class="footerLink">Mission and Vision</a> <a href="#" class="footerLink">History</a> </div> <div class="footerItem"> <a href="#" class="footerLink">Projects</a> </div> <div class="footerItem"> <a href="#" class="footerLink">News</a> <a href="#" class="footerLink">Events Calendar</a> <a href="#" class="footerLink">Image Gallery</a> </div> <div class="footerItem"> <a href="#" class="footerLink">Get Involved</a> <a href="#" class="footerLink">Donate</a> <a href="#" class="footerLink">Online Store</a> <a href="#" class="footerLink">Volunteer</a> </div> <div class="footerItem"> <a href="#" class="footerLink">Contact Us</a> </div> </div> </div> <div id="footerSocialMedia"> <h3>Follow Us on Social Media</h3> <div> <a class="socialMediaLink" href="#"> <!-- TODO: fix image src --> <img src="../../images/10wmt-superJumbo-v4.jpeg" alt="twitter" /> </a> <a class="socialMediaLink" href="#"> <!-- TODO: fix image src --> <img src="../../images/26-267842_facebook-round-logo-png-transparent-background-facebook-logo.png" alt="facebook" /> </a> <a class="socialMediaLink" href="#"> <!-- TODO: fix image src --> <img src="../../images/ew-instagram-logo-transparent-related-keywords-logo-instagram-vector-2017-115629178687gobkrzwak.webp" alt="instagram" /> </a> </div> </div> <footer id="copyright"> <span>© 2022 The Green Foundation</span> Terms of Use | Privacy Statement | Charitable Solicitation Disclosures | Mobile Terms & Conditions | Title VI Notice of Nondiscrimination </footer> </div> <script type="text/javascript"> $('.navItem').hover( function() { $(this).addClass('navOpen'); // TODO: jQuery to add the 'navOpen' class to $(this) goes here }, function() { $(this).removeClass('navOpen'); // TODO: jQuery to remove the 'navOpen' class to $(this) goes here } ); </script> </body> </html>
<template> <div class="textfieldComponent"> <label>{{ label }}</label> <div class="textfield-custom"> <input :value="internalValue" :type="type" :placeholder="placeholder" :required="required" class="form-control" @input="updateModelValue($event.target.value)" /> </div> </div> </template> <script lang="ts" setup> const props = defineProps({ modelValue: { type: String || Number, default: "", }, placeholder: { type: String, default: "", }, type: { type: String, default: "text", }, label: { type: String, default: '' }, required: { type: Boolean, default: false, }, }); const emit = defineEmits(["update:modelValue"]); const internalValue = ref<string | number>(props.modelValue); function updateModelValue(value: string | number) { internalValue.value = value; emit("update:modelValue", value); } watch(internalValue, (): void => { internalValue.value = props.modelValue; }); </script> <style lang="scss" scoped> .textfieldComponent { text-align: left; label { font-weight: 600; font-size: 14px; line-height: 2.7; } .textfield-custom { border: 1px solid var(--white-1); border-radius: 0.25rem; padding: 0.375rem 0.75rem; .form-control { display: block; border: unset; width: 100%; height: 44px; font-size: 1rem; font-weight: var(--font-weight-regular); line-height: 1.5; color: var(--gray-2); background-color: var(--white); background-clip: padding-box; transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; &:focus-visible { outline: unset; } } input:focus { background-color: unset; } &:focus { border: 1px solid var(--primary-color); box-shadow: unset !important; } } } </style>
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./ISavageDroids.sol"; /** * @title Upgrade contract for Savage Droids * @dev This contract allows the upgrade of Savage Droids tokens. * * Users supply 2 Droids to be upgraded. * * SAVAGE DROIDS X BLOCK::BLOCK * * Smart contract work done by joshpeters.eth */ contract UpgradeModule is Ownable, ReentrancyGuard { using ECDSA for bytes32; using Address for address; ISavageDroids savageDroids; // Token ID uint256 private _currentTokenId; // Upgrade toggle bool private _isUpgradeActive; // Singer for upgrade address private signVerifier; // Module contract mapping(address => bool) private moduleContracts; event Mint( address indexed to, uint256 indexed tokenId, uint256 indexed serialId, uint256 factionId, bytes32 biosHash ); constructor(address savageDroidsAddress, uint256 currentTokenId) { savageDroids = ISavageDroids(savageDroidsAddress); _currentTokenId = currentTokenId; _isUpgradeActive = false; signVerifier = 0x251738372e272681FcD8e2E3D0D09A9Af047C562; } // @dev Returns the token id of the last token function getCurrentTokenId() external view returns (uint256) { return _currentTokenId; } // @dev Returns the enabled/disabled status for upgrade function getUpgradeState() external view returns (bool) { return _isUpgradeActive; } // @dev Allows to enable/disable minting of upgrade function flipUpgradeState() external onlyOwner { _isUpgradeActive = !_isUpgradeActive; } // @dev Sets a new signature verifier function setSignVerifier(address verifier) external onlyOwner { signVerifier = verifier; } // @dev Future proof the contract to allow for // functionality like fusion to increment token id counter. function toggleModuleContract(address module, bool state) external onlyOwner { moduleContracts[module] = state; } // @dev Future proof the contract to allow for // functionality like fusion to increment token id counter. function incrementCurrentTokenId() external returns (uint256) { require(moduleContracts[msg.sender]); _currentTokenId += 1; return _currentTokenId; } function getUpgradeSigningHash( address recipient, uint256 sourceTokenId, uint256 destinationTokenId, uint256 sourceSerialId, uint256 destinationSerialId, bytes32 sourceBiosHash, bytes32 destinationBiosHash ) public pure returns (bytes32) { return keccak256( abi.encodePacked( recipient, sourceTokenId, destinationTokenId, sourceSerialId, destinationSerialId, sourceBiosHash, destinationBiosHash ) ); } function upgradeDroid( uint256 sourceTokenId, uint256 destinationTokenId, uint256 sourceSerialId, uint256 destinationSerialId, bytes32 sourceBiosHash, bytes32 destinationBiosHash, bytes memory sig ) external nonReentrant { require(_isUpgradeActive, "Upgrade not active"); require(sourceTokenId != destinationTokenId, "Droids cannot be the same"); require( savageDroids.ownerOf(sourceTokenId) == msg.sender, "Must own source Droid" ); require( savageDroids.ownerOf(destinationTokenId) == msg.sender, "Must own destination Droid" ); // Verify signature bytes32 message = getUpgradeSigningHash( msg.sender, sourceTokenId, destinationTokenId, sourceSerialId, destinationSerialId, sourceBiosHash, destinationBiosHash ).toEthSignedMessageHash(); require( ECDSA.recover(message, sig) == signVerifier, "Permission to call upgrade function failed" ); // Mint new source droid _currentTokenId += 1; uint256 sourceFactionId = savageDroids.getFaction(sourceTokenId); emit Mint( msg.sender, _currentTokenId, sourceSerialId, sourceFactionId, sourceBiosHash ); savageDroids.mintToken(msg.sender, _currentTokenId, sourceFactionId); // Mint new destination droid _currentTokenId += 1; uint256 destinationFactionId = savageDroids.getFaction(destinationTokenId); emit Mint( msg.sender, _currentTokenId, destinationSerialId, destinationFactionId, destinationBiosHash ); savageDroids.mintToken(msg.sender, _currentTokenId, destinationFactionId); //Burn old source droid savageDroids.burnToken(sourceTokenId); //Burn old destination droid savageDroids.burnToken(destinationTokenId); } }
package network.resources; import jakarta.ws.rs.*; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import network.dao.ImageDao; import network.model.Image; import network.model.ServerError; import org.glassfish.jersey.server.ContainerRequest; import utils.Check; import utils.TokenList; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; @Path("/gallery") public class ImagesResource { @Context private ContainerRequest request; @Path("/images") @Check @GET @Produces(MediaType.APPLICATION_JSON) public Response images(){ try { List<Image> images = ImageDao.getImages(); return Response.status(200).entity(images).build(); } catch (SQLException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ServerError("SQL error")).build(); } } @Path("/image") @Check @POST @Consumes(MediaType.APPLICATION_JSON) public Response image(Image image){ Date date = Calendar.getInstance().getTime(); DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss"); String strDate = dateFormat.format(date); try{ System.out.println(image.getEncoding()); ImageDao.addImage(getUsername(), image.getEncoding(), strDate); return Response.status(200).build(); } catch (SQLException e) { e.printStackTrace(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ServerError("SQL error")).build(); } } private String getUsername(){ return TokenList.getUser(request.getRequestCookies().get("SESSION_ID").getValue()); } }
const prevElement = document.querySelector(".arrow-left"); const nextElement = document.querySelector(".arrow-right"); const pageOneElement = document.querySelector(".one"); const pageTwoElement = document.querySelector(".two"); const productsElement = document.querySelectorAll(".products"); let currentPage = 1; let productsPerPage = 9; let cart = []; function Product(id, image, title, price) { this.id = id; this.image = image; this.title = title; this.price = price; console.log(this); } function Cart(product, quantity) { this.product = product; this.quantity = quantity; } const products = [ new Product("1", "./images/beats.jpg", "Beats", "$995"), new Product("2", "./images/rocky.jpg", "Rocky Mountain", "$8,250"), new Product( "3", "./images/game console.jpg", "Game Console Controller Cable", "$8,250" ), new Product( "4", "./images/elitebook tablet.jpg", "White EliteBook Tablet 810", "$9,950" ), new Product("5", "./images/wear c7.jpg", "Gore Wear C7", "$449"), new Product( "6", "./images/wireless audio.jpg", "Wireless Audio System Multiroom 360", "$8,250" ), new Product("7", "./images/beats2.jpg", "Beats", "$9,950"), new Product( "8", ".//images/smartwatch.jpg", "Smartwatch 20 LTE Wifi", "$499" ), new Product("9", "./images/rocky.jpg", "Rocky Mountain", "$8,250"), new Product("10", "./images/wear c7.jpg", "Gore Wear C7", "$449"), new Product( "11", "./images/wireless audio.jpg", "Wireless Audio System Multiroom 360", "$8,250" ), new Product("12", "./images/beats2.jpg", "Beats", "$9,950"), new Product( "13", ".//images/smartwatch.jpg", "Smartwatch 20 LTE Wifi", "$499" ), new Product("14", "./images/rocky.jpg", "Rocky Mountain", "$8,250"), new Product("15", "./images/beats.jpg", "Beats", "$995"), new Product("16", "./images/rocky.jpg", "Rocky Mountain", "$8,250"), new Product( "17", "./images/game console.jpg", "Game Console Controller Cable", "$8,250" ), ]; const newProductContainer = document.querySelector(".best-products-images"); function displayProducts(productList) { newProductContainer.innerHTML = ""; productList.forEach((product) => { const newDiv = document.createElement("div"); newDiv.classList.add("products"); newDiv.setAttribute("data-productId", product.id); newDiv.innerHTML = ` <img src="${product.image}" alt="${product.title}" width="300" /> <div class="products-text">${product.title}</div> <div class="products-price"> <button class="cart" data-productId="${product.id}">Add to Cart</button> ${product.price} </div> </div>`; newProductContainer.appendChild(newDiv); }); } displayProducts(products); const addToCartButtons = document.querySelectorAll(".cart"); addToCartButtons.forEach((button) => { button.addEventListener("click", (event) => { console.log(event.target); addToCart(event.target.dataset.productid); }); }); function addToCart(productId) { console.log("productId", productId); const product = products.find((p) => p.id == productId); cart.push(new Cart(product, 1)); updateCart(); } function updateCart() { const cartCount = document.querySelector(".cart-number"); const cartList = document.querySelector(".cart-list-total"); // const existingCartItem = cart.find( // (cartItem) => cartItem.product.id === product.id // ); // if (existingCartItem) { // existingCartItem.quantity += 1; // } else { // cart.push({ product, quantity: 1 }); // } const totalItems = cart.reduce((acc, curr) => acc + curr.quantity, 0); cartCount.textContent = totalItems; cartList.innerHTML = ""; cart.forEach((cartItem) => { if (cartItem.product) { const productDiv = document.createElement("div"); productDiv.classList.add("cart-list"); productDiv.innerHTML = ` <img src="${cartItem.product.image}" alt="${cartItem.product.title}"> <div class="cart-list-details"> <div>${cartItem.product.title}</div> <div class="cart-list-price">${cartItem.quantity} * ${cartItem.product.price}</div> <i class="fa-solid fa-xmark cart-list-remove"></i> </div> </div> `; cartList.appendChild(productDiv); } }); const subtotalDiv = document.createElement("div"); subtotalDiv.classList.add("cart-list-subtotal"); subtotalDiv.innerHTML = ` <div>Sub Total</div> <div class="subtotal-amount">${calculateSubtotal()}</div> `; cartList.appendChild(subtotalDiv); } // function calculateSubtotal() { // const subtotal = cart.reduce((acc, cartItem) => { // if (cartItem.product && typeof cartItem.product.price === "number") { // return acc + cartItem.quantity * cartItem.product.price; // } else { // console.error("Invalid product or price:", cartItem); // return acc; // } // }, 0); // return subtotal; // } function calculateSubtotal() { const subtotal = cart.reduce((acc, cartItem) => { if (cartItem.product && cartItem.product.price === "number") { return acc + cartItem.quantity * cartItem.product.price; } }, 0); return subtotal; } const cartIcon = document.querySelector(".cart-icon"); cartIcon.addEventListener("click", () => { console.log(cart); const cartList = document.querySelector(".cart-list-total"); if (cartList.style.display === "none") { cartList.style.display = "block"; } else { cartList.style.display = "none"; } }); updateCart(); function searchProducts() { const search = document .querySelector(".search-container input") .value.toLowerCase(); const updatedProducts = products.filter((product) => product.title.toLowerCase().includes(search) ); displayProducts(updatedProducts); console.log("search"); } const searchInput = document.querySelector(".search-container input"); searchInput.addEventListener("input", searchProducts); searchInput.addEventListener("keydown", function (event) { if (event.key === "Enter") { searchProducts(); } }); function showProductCategories() { const toggleIcon = document.querySelector(".toggle-icon"); const categoryList = document.querySelector(".category-list"); toggleIcon.addEventListener("click", function () { if ( categoryList.style.display === "none" || categoryList.style.display === "" ) { categoryList.style.display = "block"; } else { categoryList.style.display = "none"; } }); } document.addEventListener("DOMContentLoaded", showProductCategories); function productsForCurrentPage() { const startIndex = (currentPage - 1) * productsPerPage; const endIndex = Math.min(startIndex + productsPerPage, products.length); let pageInfoParagraph = document.querySelector(".page-info"); pageInfoParagraph.innerHTML = `Showing ${startIndex + 1}-${endIndex} of ${ products.length } results `; return products.slice(startIndex, endIndex); } function nextPage() { if (currentPage * productsPerPage < products.length) { currentPage++; displayProducts(productsForCurrentPage()); } console.log("next"); } function prevPage() { if (currentPage > 1) { currentPage--; displayProducts(productsForCurrentPage()); } console.log("prev"); } function showSidebar() { const sidebar = document.querySelector(".info-sidebar"); sidebar.style.display = "flex"; } function hideSidebar() { const sidebar = document.querySelector(".info-sidebar"); sidebar.style.display = "none"; } pageOneElement.addEventListener("click", prevPage); pageTwoElement.addEventListener("click", nextPage); nextElement.addEventListener("click", nextPage); prevElement.addEventListener("click", prevPage);
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import {Task} from '../model/task'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class TaskService { private baseURI: String = "http://localhost:8888/api/v1/"; constructor(private http: HttpClient) { } getTasks(): any { console.log("Payload = " + this.http.get(this.baseURI + 'tasks',{ observe: 'response' }) .subscribe( response => console.log(response.body) )); return this.http.get<Task[]>(this.baseURI + 'tasks').pipe(map(x=>x)); } getAllParent(): any { return this.http.get(this.baseURI + 'parentTasks'); } getTaskById(taskId): any { console.log("getTask By Id = " + this.http.get(this.baseURI + 'task'+ taskId,{ observe: 'response' }) .subscribe( response => console.log(response.body) )); return this.http.get(this.baseURI + 'task'+'/' + taskId); } addTask(task): any { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token' }) }; console.log("Display Project ID:"+task.project.projectId); return this.http.post(this.baseURI + 'addTask', task, httpOptions); } addParentTask(task): any { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token' }) }; return this.http.post(this.baseURI + 'addParent', task, httpOptions); } endTask(taskId): any { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token' }) }; return this.http.put(this.baseURI + 'endTask/' + taskId, httpOptions); } updateTask(task:Task): any { console.log(" edit task service " +task.taskId); const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token' }) }; return this.http.put(this.baseURI + 'task'+'/'+task.taskId ,task, httpOptions); } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <title>Busway</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <header th:replace="include/navbar :: navbar"></header> <div class="container mt-5"> <h2>Les stations</h2> <div th:if="${success}" class="alert alert-success" role="alert"> <span th:text="${success}"></span> </div> <div th:if="${error}" class="alert alert-danger" role="alert"> <span th:text="${error}"></span> </div> <a th:href="@{/trip/new}" class="btn btn-sm btn-primary my-4 float-end">Ajouter un voyage</a> <table class="table table-striped table-bordered my-4"> <thead> <th>Matricule bus</th> <th>Ligne</th> <th>Station départ</th> <th>Heure départ</th> <th>Station arrivee</th> <th>Heure arrivee</th> <th>Actions</th> </thead> <tbody> <tr th:each="trip : ${trips}"> <td th:text="${trip.busMatriculation}"></td> <td th:text="${trip.busLine}"></td> <td th:text="${trip.departure.name}"></td> <td th:text="${trip.departureAt}"></td> <td th:text="${trip.arrival.name}"></td> <td th:text="${trip.arrivalAt}"></td> <td> <a th:href="@{/trip/edit/{id}(id=${trip.busMatriculation})}" class="btn btn-sm btn-warning">Modifier</a> <a th:href="@{/trip/delete/{id}(id=${trip.busMatriculation})}" class="btn btn-sm btn-danger">Supprimer</a> </td> </tr> </tbody> </table> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script> </body> </html>
package com.jojo.basicauth.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import static org.springframework.security.config.Customizer.withDefaults; @Configuration @EnableWebSecurity public class SecurityConfig { private final UserDetailsService userDetailsService; private final BCryptPasswordEncoder passwordEncoder; public SecurityConfig(UserDetailsService userDetailsService, BCryptPasswordEncoder passwordEncoder) { this.userDetailsService = userDetailsService; this.passwordEncoder = passwordEncoder; } @Bean public DaoAuthenticationProvider authProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(passwordEncoder); return authProvider; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .headers().frameOptions().disable().and() .csrf().disable() .cors().disable() .authorizeRequests(auth -> { auth.antMatchers("/api/admin").hasAuthority("ADMIN"); auth.antMatchers("/api/user").hasAnyAuthority("ADMIN", "USER"); auth.antMatchers("/api/public").permitAll(); auth.antMatchers("/api/create").permitAll(); auth.anyRequest().authenticated(); }) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .httpBasic(withDefaults()) .build(); } }
--- title: "Leetcode - Largest Unique Number(Premium)" date: 2024-04-19 categories: [Leetcode] tags: [Leetcode, Problem Solving, Golang, DSA, Data Structure, Programming, Algorithm, Hash Table] --- # [Leetcode - Largest Unique Number(Premium)](https://leetcode.com/problems/largest-unique-number/description/){:target="_blank"} [![Hits](https://hits.sh/mokhlesurr031.github.io/posts/leetcode-largest-unique-number.svg)](https://hits.sh/mokhlesurr031.github.io/posts/leetcode-largest-unique-number/) - Given an array of integers, identify the highest value that appears only once in the array. If no such number exists, return -1. Solution ```go type Solution struct{} func (sol Solution) largestUniqueNumber(A []int) int { freqMap := make(map[int]int) largestVal := -1 for _, val := range A{ freqMap[val]++ } for _, val := range A{ if freqMap[val]==1 && val>largestVal{ largestVal= val } } return largestVal } ```
// App.js import React from 'react'; import { Route, BrowserRouter as Router, Routes } from 'react-router-dom'; // Import Routes instead of Switch import BookDetailsPage from './components/BookDetailsPage'; import BooksPage from './components/BooksPage'; function App() { return ( <Router> <div className="App"> <Routes> <Route path="/" element={<BooksPage />} /> {/* Default route for the root URL */} <Route path="/books/:id" element={<BookDetailsPage />} /> <Route path="/books" element={<BooksPage />} /> </Routes> </div> </Router> ); } export default App;
<template> <n-spin :show="loadingRef"> <div class="TaskDetailPage" v-if="taskData"> <n-h2>任务详情</n-h2> <div class="info-card"> <div class="header-title"> <div class="dfc gap1"> <n-h4 class="title4">任务信息</n-h4> <n-tag :type="TaskStatusTag[taskData.status || 'unknown'].type" size="small" >{{ TaskStatusTag[taskData.status || 'unknown'].title }}</n-tag> <n-text depth="3">暂不支持修改</n-text> </div> <n-space> <n-button size="small" secondary @click="handleRefresh" v-if="taskData?.status === TaskStatus.ING" :loading="loadingRef" >更新</n-button> <n-button size="small" secondary @click="handlePreview" type="primary">预览</n-button> <n-popconfirm @positive-click="handleStopTask" v-if="taskData?.status === TaskStatus.ING" > <template #trigger> <n-button type="error" size="small" secondary>停止</n-button> </template> <span>确认要停止吗?</span> </n-popconfirm> </n-space> </div> <div class="info-content"> <div class="dfc gap3"> <n-text depth="3">任务ID: {{ taskData.id }}</n-text> <n-text depth="3">任务名称: {{ taskData.taskName }}</n-text> <n-text depth="3">托管平台: {{ taskData.platform?.platformConfig?.type }}</n-text> <n-text depth="3">项目模版: {{ taskData.template?.type }}</n-text> </div> <div class="dfc gap3"> <n-text depth="3">GIT账户: {{ taskData.owner }}</n-text> <n-text depth="3"> 仓库: <a :href="`https://github.com/${taskData.owner}/${taskData.repository}`" target="_blank" style="color: #03a9f4" >{{ taskData.repository }}</a> </n-text> <n-text depth="3">分支: {{ taskData.branch }}</n-text> <n-text depth="3" v-if="taskData.buildScript">编译命令: {{ taskData.buildScript }}</n-text> <n-text depth="3" v-if="taskData.runScript">运行命令: {{ taskData.runScript }}</n-text> <n-text depth="3" v-if="taskData.serverPort">项目端口: {{ taskData.serverPort }}</n-text> <n-text depth="3" v-if="taskData.buildPath">编译目录: {{ taskData.buildPath }}</n-text> <n-text depth="3" v-if="taskData.routerMode">路由模式: {{ taskData.routerMode }}</n-text> <n-text depth="3" v-if="taskData.domain">域名: {{ taskData.domain }}</n-text> <n-text depth="3" v-if="taskData.externalPort">外部端口: {{ taskData.externalPort }}</n-text> </div> </div> </div> <div class="info-card"> <div class="header-title"> <div class="dfc gap1"> <n-h4 class="title4">子任务信息</n-h4> </div> </div> <div class="info-content"> <div class="dfc gap3"> <n-text depth="3">子任务ID:{{ taskData.activeId || '等待触发' }}</n-text> <div class="dfc"> <n-text depth="3">子任务进度:</n-text> <n-tag size="small" depth="3" :type="childStatus.type">{{ childStatus.title }}</n-tag> </div> <n-text depth="3">花费时间:{{ takeTime }}</n-text> </div> </div> </div> <div class="info-card"> <div class="header-title"> <div class="dfc gap1"> <n-h4 class="title4">子任务进度</n-h4> </div> </div> <div class="info-content"> <div> <n-steps> <n-step :status="[ChildTaskStatus.INIT_ERROR, ChildTaskStatus.DOWNLOAD_ERROR].includes(taskData.child?.status || 0) ? 'error' : (taskData.child?.status || 0) >= 100 ? 'process' : 'wait'" title="触发中" description="增加初始化数据" @click="handleChangeLog(ChildTaskStatus.INIT)" /> <n-step :status="[ChildTaskStatus.BUILD_ERROR].includes(taskData.child?.status || 0) ? 'error' : (taskData.child?.status || 0) > 100 ? 'process' : 'wait'" title="构建中" v-if="taskData.template?.isStructure" description="正在构建镜像,请耐心等待" @click="handleChangeLog(ChildTaskStatus.BUILDING)" /> <n-step :status="[ChildTaskStatus.RUN_ERROR, ChildTaskStatus.STOP_ERROR].includes(taskData.child?.status || 0) ? 'error' : (taskData.child?.status || 0 )>= 110 ? 'process' : 'wait'" title="运行中" v-if="taskData.template?.isRun" description="准备运行,请耐心等待" @click="handleChangeLog(ChildTaskStatus.RUNING)" /> <n-step :status="[ChildTaskStatus.BIND_ERROR, ChildTaskStatus.COPY_ERROR].includes(taskData.child?.status || 0) ? 'error' : (taskData.child?.status || 0) > 110 ? 'process' : 'wait'" title="部署中" description="正在部署中,请耐心等待" @click="handleChangeLog(ChildTaskStatus.BINDING)" /> <n-step :status="[ChildTaskStatus.ERROR].includes(taskData.child?.status || 0) ? 'error' : (taskData.child?.status || 0) === 200 ? 'process' : 'wait'" title="已完成" description="当前子任务已完成,等待重新触发" @click="handleChangeLog(ChildTaskStatus.DENO)" /> </n-steps> </div> </div> </div> <div class="info-card"> <div class="header-title"> <div class="dfc gap1"> <n-h4 class="title4">子任务日志</n-h4> </div> <div class="dfc gap1"> <n-text depth="3">更新时间: {{ taskData.child?.updatedAt }}</n-text> </div> </div> <div class="info-content"> <div class="log-box"> <div class="log-header"> <div>任务日志</div> <div class="dfc gap1"> <n-button strong secondary size="small" :loading="loadingLogRef" @click="handleRefreshLog" circle text > <template #icon> <n-icon> <Refresh /> </n-icon> </template> </n-button> <n-button strong secondary size="small" :loading="loadingLogRef" @click="handleDownloadLog" circle text > <template #icon> <n-icon> <ArrowDownCircleOutline /> </n-icon> </template> </n-button> <span>3</span> </div> </div> <div class="log-content"> <n-log :rows="20" :log="logs[logType] || '暂无日志'" /> </div> </div> </div> </div> </div> </n-spin> </template> <script lang="tsx" setup> import { computed, reactive, watch } from 'vue'; import { ref } from 'vue'; import dayjs from 'dayjs'; import { ITaskDetail, taskChange, taskDetail, taskLog } from '../../../api/common'; import { ChildTaskStatus, TaskStatus, TaskStatusTag, TaskChildStatusTag } from '../../../constants/status'; import { useRoute } from 'vue-router'; import { useMessage } from 'naive-ui'; import { Refresh, ArrowDownCircleOutline } from '@vicons/ionicons5'; const route = useRoute() const message = useMessage() const loadingRef = ref(false); const loadingLogRef = ref(false); const taskData = ref<ITaskDetail>(); const currentStatus = ref<ChildTaskStatus>(taskData.value?.child?.status || ChildTaskStatus.INIT); const logs = reactive<Record<string, string>>({}); const logType = computed(() => { return { [ChildTaskStatus.DENO]: 'deploy', [ChildTaskStatus.BUILDING]: 'build', [ChildTaskStatus.COPYING]: 'deploy', [ChildTaskStatus.BINDING]: 'deploy', [ChildTaskStatus.DOWNLOADING]: 'init', [ChildTaskStatus.STOPING]: 'run', [ChildTaskStatus.RUNING]: 'run', [ChildTaskStatus.STOP]: 'init', [ChildTaskStatus.INIT]: 'init', [ChildTaskStatus.BUILD_ERROR]: 'build', [ChildTaskStatus.INIT_ERROR]: 'init', [ChildTaskStatus.DOWNLOAD_ERROR]: 'init', [ChildTaskStatus.RUN_ERROR]: 'run', [ChildTaskStatus.COPY_ERROR]: 'deploy', [ChildTaskStatus.STOP_ERROR]: 'run', [ChildTaskStatus.BIND_ERROR]: 'deploy', }[currentStatus.value as number] || 'init'; }); const handleChangeLog = (t: ChildTaskStatus) => { currentStatus.value = t; handleFetchLog(); } const handleFetchLog = async () => { if (taskData.value?.activeId && taskData.value?.child) { loadingLogRef.value = true; const log = await taskLog({ type: logType.value, id: taskData.value?.id as string }).finally(() => { loadingLogRef.value = false; }); logs[logType.value] = log?.log || '' } }; const childStatus = computed(() => { if (!taskData.value?.child?.status) { return { type: 'default', title: '等待触发', } } return TaskChildStatusTag[taskData.value?.child?.status] || { type: 'default', title: '未知状态' }; }) const takeTime = computed(() => { if (taskData.value) { if (!taskData.value?.child?.updatedAt) { return '-'; } return dayjs(new Date(1640966400000 + dayjs(new Date(taskData.value?.child?.updatedAt || '')).diff(taskData.value?.child?.createdAt, 'millisecond'))).format('HH:mm:ss'); } return '-' }); const handlePreview = () => { window.open(`http://${location.host}:${taskData.value?.externalPort}`) } const handleStopTask = async () => { await taskChange({ status: TaskStatus.STOP, id: route.params.id as string }); message.success('停止成功'); _fetch(); } const _fetch = async () => { loadingRef.value = true; const data = await taskDetail({ id: route.params.id as string }).finally(() => { loadingRef.value = false; }); taskData.value = data; currentStatus.value = data.child?.status as ChildTaskStatus; handleFetchLog(); } _fetch(); const handleRefresh = () => { _fetch(); } const handleRefreshLog = () => { handleFetchLog(); } const handleDownloadLog = () => { } </script> <style lang="scss"> .TaskDetailPage { min-width: 1024px; // max-width: 1024px; margin: 0 auto; .info-card { margin-bottom: 24px; } .header-title { display: flex; align-items: center; justify-content: space-between; margin-bottom: 18px; .title4 { margin-bottom: 0; } } .info-content { display: flex; flex-direction: column; gap: 12px; } .log-box { background-color: #fff; border-radius: 6px; overflow: hidden; border: 1px solid #f4f5f6; .log-header { background-color: #eee; // border-radius: 6px; display: flex; align-items: center; justify-content: space-between; padding: 12px 24px; } .log-content { padding: 12px 24px; } } .dfc { display: flex; align-items: center; } .gap1 { gap: 12px; } .gap2 { gap: 24px; } .gap3 { gap: 36px; } } </style>
/* * Copyright (C) 2002-2022 by the Widelands Development Team * * 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, see <https://www.gnu.org/licenses/>. * */ #ifndef WL_WUI_CONSTRUCTIONSITEWINDOW_H #define WL_WUI_CONSTRUCTIONSITEWINDOW_H #include <memory> #include "logic/map_objects/tribes/constructionsite.h" #include "ui_basic/box.h" #include "ui_basic/button.h" #include "ui_basic/checkbox.h" #include "ui_basic/progressbar.h" #include "ui_basic/radiobutton.h" #include "ui_basic/textarea.h" #include "wui/buildingwindow.h" #include "wui/inputqueuedisplay.h" #include "wui/waresdisplay.h" // Soldier capacity for training or military site struct ConstructionSoldierCapacityBox : public UI::Box { private: uint32_t current_, min_, max_; bool enabled_; UI::Button cs_soldier_capacity_decrease_; UI::Button cs_soldier_capacity_increase_; UI::Textarea cs_soldier_capacity_display_; public: ConstructionSoldierCapacityBox( Panel* parent, uint32_t current, uint32_t min, uint32_t max, bool enabled); void refresh(uint32_t current, uint32_t max, bool enabled); void set_current(uint32_t value); void change_current(int32_t delta); Notifications::Signal<> changed; uint32_t get_current() { return current_; } bool handle_key(bool down, SDL_Keysym code) override; bool handle_mousewheel(int32_t x, int32_t y, uint16_t modstate) override; private: void update(); }; /** * Status window for construction sites. */ struct ConstructionSiteWindow : public BuildingWindow { ConstructionSiteWindow(InteractiveBase& parent, UI::UniqueWindow::Registry& reg, Widelands::ConstructionSite&, bool avoid_fastclick, bool workarea_preview_wanted); void think() override; protected: void init(bool avoid_fastclick, bool workarea_preview_wanted) override; private: class FakeWaresDisplay : public WaresDisplay { public: FakeWaresDisplay(UI::Panel* parent, bool can_act, Widelands::ConstructionSite& cs, Widelands::WareWorker type); ~FakeWaresDisplay() override; protected: void draw_ware(RenderTarget& dst, Widelands::DescriptionIndex ware) override; private: Widelands::WarehouseSettings& settings_; const Widelands::TribeDescr& tribe_; std::unique_ptr<Widelands::WareList> warelist_; }; Widelands::OPtr<Widelands::ConstructionSite> construction_site_; UI::ProgressBar* progress_; // BuildingSettings-related UI elements UI::Checkbox* cs_launch_expedition_; std::unique_ptr<UI::Radiogroup> cs_prefer_heroes_rookies_; ConstructionSoldierCapacityBox* cs_soldier_capacity_; std::vector<InputQueueDisplay*> cs_ware_queues_; std::vector<InputQueueDisplay*> cs_worker_queues_; UI::Checkbox* cs_stopped_; FakeWaresDisplay* cs_warehouse_wares_; FakeWaresDisplay* cs_warehouse_workers_; void change_policy(Widelands::WareWorker, Widelands::StockPolicy); void add_wares_queues(Widelands::ConstructionSite* construction_site, UI::Box& box) const; void add_progress_bar(UI::Box& box); void build_wares_tab(Widelands::ConstructionSite* construction_site); void build_settings_tab(Widelands::ConstructionSite* construction_site); DISALLOW_COPY_AND_ASSIGN(ConstructionSiteWindow); }; #endif // end of include guard: WL_WUI_CONSTRUCTIONSITEWINDOW_H
package com.dev.was.security; import com.dev.was.controller.ExceptionCodeEnum; import com.dev.was.entity.UserEntity; import com.dev.was.scheduleTask.DataGoScheduleTask; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; @Component @RequiredArgsConstructor public class CustomAuthenticatorProvider implements AuthenticationProvider { private final PrincipalDetailsService principalDetailsService; private final PasswordEncoder passwordEncoder; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); // 사용자가 입력한 id String password = (String) authentication.getCredentials(); // 사용자가 입력한 password PrincipalDetails principalDetails = (PrincipalDetails) principalDetailsService.loadUserByUsername(username); if (principalDetails == null) { logger.info("[{}] is not valid", username); throw new CustomAuthenticationException(ExceptionCodeEnum.FOUNT_NOT_ID); } String dbPassword = principalDetails.getPassword(); if(! passwordEncoder.matches(password, dbPassword)) { logger.info("[{}] password not match", username); throw new CustomAuthenticationException(ExceptionCodeEnum.PW_INVALID); } return new UsernamePasswordAuthenticationToken(principalDetails, null, principalDetails.getAuthorities()); } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticatorProvider.class); }
var cacheName = 'pwa-v1-fenoul'; var appShellFiles = [ '/', '/css/reset.css', '/css/styles.css', '/icon/android-icon-192x192.png', '/icon/apple-icon-57x57.png', '/icon/apple-icon-60x60.png', '/icon/apple-icon-72x72.png', '/icon/apple-icon-76x76.png', '/icon/144.png', '/icon/apple-icon-114x114.png', '/icon/apple-icon-120x120.png', '/icon/apple-icon-152x152.png', '/icon/apple-icon-180x180.png', '/icon/favicon-16x16.png', '/icon/favicon-32x32.png', '/icon/favicon-96x96.png', '/icon/maskable-196x196.png', '/icon/splash-512x512.png', '/js/app.js', '/index.html' ]; self.addEventListener('install', (e) => { console.log('[Service Worker] Install'); e.waitUntil( caches.open(cacheName).then((cache) => { console.log('[Service Worker] Caching all: app shell and content'); return cache.addAll(appShellFiles); }) ); }); self.addEventListener('fetch', function(e) { if (!(e.request.url.indexOf('http') === 0)) return; e.respondWith( caches.match(e.request).then(function(r) { console.log('[Service Worker] Fetching resource: '+e.request.url); return r || fetch(e.request).then(function(response) { return caches.open(cacheName).then(function(cache) { console.log('[Service Worker] Caching new resource: ' + e.request.url); cache.put(e.request, response.clone()); return response; }); }); }) ); });
--- title: University multilateral federation decision tree description: Use this decision tree to help design a multilateral federation solution for universities. services: active-directory author: janicericketts manager: martinco ms.service: active-directory ms.workload: identity ms.subservice: fundamentals ms.topic: conceptual ms.date: 04/01/2023 ms.author: jricketts ms.custom: "it-pro" ms.collection: M365-identity-device-management --- # Decision tree Use this decision tree to determine the multilateral federation solution that's best suited for your environment. [![Diagram that shows a decision matrix with key criteria to help choose between three solutions.](media/multilateral-federation-decision-tree/tradeoff-decision-matrix.png)](media/multilateral-federation-decision-tree/tradeoff-decision-matrix.png#lightbox) ## Migration resources The following resources can help with your migration to the solutions covered in this content. | Migration resource | Description | Relevant for migrating to... | | - | - | - | | [Resources for migrating applications to Microsoft Entra ID](~/identity/enterprise-apps/migration-resources.md) | List of resources to help you migrate application access and authentication to Microsoft Entra ID | Solution 1, Solution 2, and Solution 3 | | [Microsoft Entra custom claims provider](~/identity-platform/custom-claims-provider-overview.md)| Overview of the Microsoft Entra custom claims provider | Solution 1 | | [Custom security attributes](~/fundamentals/custom-security-attributes-manage.md) | Steps for managing access to custom security attributes | Solution 1 | | [Microsoft Entra SSO integration with Cirrus Bridge](~/identity/saas-apps/cirrus-identity-bridge-for-azure-ad-tutorial.md) | Tutorial to integrate Cirrus Bridge with Microsoft Entra ID | Solution 1 | | [Cirrus Bridge overview](https://blog.cirrusidentity.com/documentation/azure-bridge-setup-rev-6.0) | Cirrus Identity documentation for configuring Cirrus Bridge with Microsoft Entra ID | Solution 1 | | [Configuring Shibboleth as a SAML proxy](https://shibboleth.atlassian.net/wiki/spaces/KB/pages/1467056889/Using+SAML+Proxying+in+the+Shibboleth+IdP+to+connect+with+Azure+AD) | Shibboleth article that describes how to use the SAML proxying feature to connect the Shibboleth identity provider (IdP) to Microsoft Entra ID | Solution 2 | | [Microsoft Entra multifactor authentication deployment considerations](~/identity/authentication/howto-mfa-getstarted.md) | Guidance for configuring Microsoft Entra multifactor authentication | Solution 1 and Solution 2 | ## Next steps See these related articles about multilateral federation: [Multilateral federation introduction](multilateral-federation-introduction.md) [Multilateral federation baseline design](multilateral-federation-baseline.md) [Multilateral federation Solution 1: Microsoft Entra ID with Cirrus Bridge](multilateral-federation-solution-one.md) [Multilateral federation Solution 2: Microsoft Entra ID with Shibboleth as a SAML proxy](multilateral-federation-solution-two.md) [Multilateral federation Solution 3: Microsoft Entra ID with AD FS and Shibboleth](multilateral-federation-solution-three.md)
import React from "react"; import { DevProject } from "../../../../../../types/DevProject"; import { Container, InfoBox, StoreButtonGroup } from "./styles"; import { ImageLoader } from "../../../../../../components"; import appStoreButton from "../../../../../../assets/images/appStoreButton.png"; import playStoreButton from "../../../../../../assets/images/playStoreButton.png"; import { useWindowDimensions } from "../../../../../../hooks"; import { TABLET_WIDTH } from "../../../../../../assets/styles/deviceSize"; interface ProjectItemProps { currentProject: DevProject; leftImage: boolean; } const ProjectItem = (props: ProjectItemProps) => { const { width } = useWindowDimensions(); if (width < TABLET_WIDTH) { return ( <Container leftAlign={props.leftImage}> <InfoBox leftAlign={props.leftImage}> <h1>{props.currentProject.title}</h1> <p>{props.currentProject.description}</p> <h2>Tecnologias utilizadas:</h2> {props.currentProject.tools && props.currentProject.tools.map((item, index) => (<span key={index}>- {item}</span>))} <div> {props.currentProject.images && <ImageLoader images={props.currentProject.images} />} </div> <StoreButtonGroup> {props.currentProject.playStoreLink && <img src={playStoreButton} alt={"play Store Button"} onClick={() => window.location.href = props.currentProject.playStoreLink ?? ""} />} {props.currentProject.appStoreLink && <img src={appStoreButton} alt={"App Store Button"} onClick={() => window.location.href = props.currentProject.appStoreLink ?? ""} />} </StoreButtonGroup> </InfoBox> </Container> ); } return ( <Container leftAlign={props.leftImage}> {props.currentProject.images && props.leftImage && <ImageLoader images={props.currentProject.images} />} <InfoBox leftAlign> <h1>{props.currentProject.title}</h1> <p>{props.currentProject.description}</p> <h2>Tecnologias utilizadas:</h2> {props.currentProject.tools && props.currentProject.tools.map((item, index) => (<span key={index}>- {item}</span>))} <StoreButtonGroup> {props.currentProject.playStoreLink && <img src={playStoreButton} alt={"play Store Button"} onClick={() => window.location.href = props.currentProject.playStoreLink ?? ""} />} {props.currentProject.appStoreLink && <img src={appStoreButton} alt={"App Store Button"} onClick={() => window.location.href = props.currentProject.appStoreLink ?? ""} />} </StoreButtonGroup> </InfoBox> {props.currentProject.images && !props.leftImage && <ImageLoader images={props.currentProject.images} />} </Container> ); }; export default ProjectItem;
//tik-tak-toe //positions are: 11 12 13 // 21 22 23 // 31 32 33 #include <iostream> using namespace std; int xWin = 0, oWin = 0; void resetMatrix(int matrix[4][4]) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { matrix[i][j] = 0; } } } void print(int matrix[4][4]) { for(int i = 1; i < 4; i++) { for(int j = 1; j < 4; j++) { if (matrix[i][j] == 1) { cout<<"X "; } else if (matrix[i][j] == 4) { cout<<"O "; } else cout << "_ "; } cout << endl; } } bool win(int matrix[4][4]) { int sum = 0; //horisontal for(int i = 1; i < 4; i++) { for(int j = 1; j < 4; j++) { sum+= matrix[i][j]; } if (sum == 3) { cout<<"CONGTATULATIONS!! X WON"; xWin++; return true; } else if (sum == 12) { cout<<"CONGTATULATIONS!! O WON"; oWin++; return true; } else sum = 0; } //vertical for(int i = 1; i < 4; i++) { for(int j = 1; j < 4; j++) { sum+= matrix[j][i]; } if (sum == 3) { cout<<"CONGTATULATIONS!! X WON"; xWin++; return true; } else if (sum == 12) { cout<<"CONGTATULATIONS!! O WON"; oWin++; return true; } else sum = 0; } //diagonal if ((matrix[1][1] + matrix[2][2] + matrix[3][3]) == 3) { cout<<"CONGTATULATIONS!! X WON"; xWin++; return true; } else if ((matrix[1][1] + matrix[2][2] + matrix[3][3]) == 12) { cout<<"CONGTATULATIONS!! O WON"; oWin++; return true; } else if ((matrix[1][3] + matrix[2][2] + matrix[3][1]) == 3) { cout<<"CONGTATULATIONS!! X WON"; xWin++; return true; } else if ((matrix[1][3] + matrix[2][2] + matrix[3][1]) == 12) { cout<<"CONGTATULATIONS!! O WON"; oWin++; return true; } return false; } int main() { int matrix[4][4] = {0}; int x, o, a, b; char c; do { resetMatrix(matrix); for (int i=0; i<5; i++) { //player x cout <<"player x: "; cin >> x; a = x / 10; b = x % 10; while(((matrix[a][b] == 1) || (matrix[a][b] == 4)) || ((x!=11) && (x!=12) && (x!=13) && (x!=21) && (x!=22) && (x!=23) && (x!=31) && (x!=32) && (x!=33))) { cout <<"Invalid input. Player x again: "; cin >> x; a = x / 10; b = x % 10; } matrix[a][b] = 1; print(matrix); if (win(matrix)) break; //DRAW if (i == 4) { cout << "Sorry, it's a draw." << endl; break;; } //player 0 cout <<"player O: "; cin >> o; a = o / 10; b = o % 10; while(((matrix[a][b] == 1) || (matrix[a][b] == 4)) || ((o!=11) && (o!=12) && (o!=13) && (o!=21) && (o!=22) && (o!=23) && (o!=31) && (o!=32) && (o!=33))) { cout <<"Invalid input. Player o again: "; cin >> o; a = o / 10; b = o % 10; } matrix[a][b] = 4; print(matrix); if (win(matrix)) break; } cout << endl << "The current result is: X:= " << xWin << " O:= " << oWin << endl; cout << "Do you want to play another game?: [Y]es/[N]o " << endl; cin >> c; while ((toupper(c)!='Y') && (toupper(c)!='N')) { cout << "Invalid input! Please choose [Y]es/[N]o" << endl; cin >> c; } }while (toupper(c) == 'Y'); return 0; }
# frozen_string_literal: true require "time" module RubyChallenge module SegmentParsers class ParsingSegmentError < StandardError; end class ParsingDateTimeError < StandardError; end class Base CONFIG = { origin: { position: 0, type: :string }, from_time: { position: 1, type: :time }, to_time: { position: 2, type: :time } }.freeze def initialize(words:) @words = words @config = CONFIG end def call segment = create_segment check_segment_errors(segment) segment end protected def create_segment parsed_klass = self.class.name.split("::").last Object.const_get("RubyChallenge::Segments::#{parsed_klass}").new( origin: field_value(:origin), from_time: field_value(:from_time, clock_time: "23:59"), to_time: field_value(:to_time, clock_time: "00:00") ) end def check_segment_errors(segment) raise ParsingSegmentError, "Errors parging segment #{segment.inspect}" unless segment.valid? end def field_value(field, extra_config = {}) field_config = @config[field] position = field_config[:position] case field_config[:type] when :string @words[position] else send("parse_#{field_config[:type]}", position, extra_config) end end def parse_time(position, extra_config) time_text = if position.is_a?(Array) position.map { @words[_1] }.join(" ") else "#{@words[position]} #{extra_config[:clock_time]}" end convert_text_to_time(time_text) end def convert_text_to_time(time_text) Time.strptime(time_text, "%Y-%m-%d %H:%M") rescue ArgumentError raise ParsingDateTimeError, "Invalid datetime from text '#{time_text}'" end end end end
import * as platform from '../helpers/platform.base'; import { TS } from '../helpers/platform.base'; import { DATA_GRID_VIEW_TABLE, DATA_LIST_VIEW_TABLE, E2eTestPO } from '../pages/e2eTestPO'; import { SEARCH_RESULTS_ITEM, SEARCH_RESULTS_LABEL } from '../pages/components/search.bar.co'; const test = platform.initialize(__filename); const e2eTestPO = platform.pages.getPage<E2eTestPO>(platform.PageNames.E2eTestPage); const tableCo = e2eTestPO.getComponent(e2eTestPO.componentNames.Table); const searchBarCo = e2eTestPO.getComponent(e2eTestPO.componentNames.SearchBar); test.testplan( 'Validate the top row - Generate Data Tests, Error & No Data', TS.meta().addRunTypeRegression().setTestStatusAutomated().setTestTypeUi().addComponent('appConfig'), () => { beforeAll(async () => { await platform.helper.goto(); await e2eTestPO.assertPageIsLoaded(); }); test.testcaseWithSteps('Verify with correct credentials results in valid login and then logout.', platform.TS.meta(), async () => { // await test.step('Click the protected button and wait for login', async () => { // await e2eTestPO.clickProtectedPageBtn(); // await platform.helper.waitForLoginLoad(); // }); // await test.step('Logging into platform app', async () => { // await platform.login.setCredentials( // platform.envir.e2eTester1Username().toUpperCase(), // platform.envir.defaultPassword(), // platform.envir.e2eTester1MFA() // ); // await platform.helper.waitForLoad(); // await test // .assert('Check that login was successful.') // .expect(await platform.platformCore.browser.getCurrentUrl()) // .not.toContain('login'); // }); }); test.testcaseWithSteps('Check that we click generate data and data is present', platform.TS.meta(), async () => { let initialGeneratedData, actualGeneratedData; await test.step('Validate the title text and get the initial data', async () => { test .assert('Validate the header title text') .expect((await e2eTestPO.getTitleHeader()).toUpperCase()) .toEqual(await e2eTestPO.getTitle()); initialGeneratedData = await e2eTestPO.getGeneratedDataLength(); }); await test.step('Click the Generate Data button, wait for the loading spinner, & validate that data is shown', async () => { await e2eTestPO.clickGenerateDataBtn(); await e2eTestPO.waitForGridSpinnerLoading(); actualGeneratedData = await e2eTestPO.getGeneratedDataLength(); test.assert('Validate that data is now shown').expect(actualGeneratedData).toBeGreaterThan(initialGeneratedData); }); await test.step('Scroll down to the last element, validate that the spinner is shown, and more data is generated', async () => { await tableCo.scrollToLastRowInTable(); await e2eTestPO.waitForGridSpinnerLoading(); test .assert('Validate that data generated is now larger') .expect(await e2eTestPO.getGeneratedDataLength()) .toBeGreaterThan(actualGeneratedData); }); await test.step('After clicking on the Generate Error button, verify the error text', async () => { await e2eTestPO.clickGenerateErrorBtn(); await e2eTestPO.waitForGridSpinnerLoading(); test.assert('Verify error message result').expect(tableCo.errorMessageResultText()).toEqual(platform.text.generatedErrorMessage); }); await test.step('No Data should show after clicking Generate No Data button', async () => { await e2eTestPO.clickGenerateNoDataBtn(); await e2eTestPO.waitForGridSpinnerLoading(); test .assert('Verify error message is showing no data') .expect(tableCo.errorMessageResultText()) .toEqual(platform.text.generatedNoDataMessage); }); }); test.testcaseWithSteps('Validate List View and Grid View', platform.TS.meta(), async () => { await test.step('Validate that the List View is preselected', async () => { await e2eTestPO.clickGenerateDataBtn(); await e2eTestPO.waitForGridSpinnerLoading(); test .assert('List View should already be preselected') .expect(await e2eTestPO.whichViewIsSelected()) .toBe('listView'); test .assert('List View table should be present') .expect(await (await platform.TS.web.$(DATA_LIST_VIEW_TABLE)).isPresent()) .toBe(true); }); await test.step('Validate the Grid View after selection', async () => { await e2eTestPO.clickGridView(); test .assert('Grid view should be selected') .expect(await e2eTestPO.whichViewIsSelected()) .toEqual('gridView'); test .assert('Grid View table should be present') .expect(await (await platform.TS.web.$(DATA_GRID_VIEW_TABLE)).isPresent()) .toBeTruthy(); }); }); test.testcaseWithSteps('The search libraries should show the selected values', platform.TS.meta(), async () => { const expectedResultsArray = ['@ce/config-lib', '@ce/auth-lib', '@ce/platform-lib', '@ce/danda-angular-lib']; await test.step('Validate each item we select and search label updates', async () => { await searchBarCo.clickSearchLibraries(); await expectedResultsArray.map(async (results, index) => { await searchBarCo.clickElementByText(SEARCH_RESULTS_ITEM, results); }); await searchBarCo.clickSearchLibrariesArrowDropdown(); test .assert(`Verify that 4 (for the tag) is still present`) .expect(await searchBarCo.getElementText(SEARCH_RESULTS_LABEL)) .toEqual('4'); }); await test.step('Check that generate data does not affect the search results label', async () => { await e2eTestPO.clickGenerateDataBtn(); await e2eTestPO.waitForGridSpinnerLoading(); await searchBarCo.clickSearchLibraries(); await searchBarCo.clickSearchLibrariesArrowDropdown(); test .assert(`Verify that 4 (for the tag) is still present`) .expect(await searchBarCo.getElementText(SEARCH_RESULTS_LABEL)) .toEqual('4'); }); await test.step('Click search libraries and unselected the results', async () => { await searchBarCo.clickSearchLibrariesArrowDropdown(); await expectedResultsArray.map(async (results) => { await searchBarCo.clickElementByText(SEARCH_RESULTS_ITEM, results); }); }); await test.step('Search for an unavailable result and verify no result shown', async () => { await searchBarCo.setInputSearch('@ce/config-lib'); await searchBarCo.getSearchResults(true); await searchBarCo.setInputSearch('fake lib'); await searchBarCo.getSearchResults(false); }); }); } );
const { mongoose } = require("./con_db") const userSchema = new mongoose.Schema({ first_name:{ type:String, required: [true,"First Name is required."] }, last_name:{ type:String, required: [true,"Last Name is required."] }, email:{ type:String, required: [true, "Email is Required"], unique: [true, "Email is already Taken"], match: [/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/, 'Please fill a valid email address'] }, password:{ type:String, required: [true,"Password is required."] }, isAdmin:{ type: Boolean, required: true }, isVerified:{ type: Boolean, required: true, default: false }, forgot_password_code: { type: String, required: false, }, forgot_password_code_created_at: { type: Date, required: false, } },{timestamps: true}) const User = mongoose.model('User',userSchema); module.exports = User
import { FC, useState, useReducer } from 'react'; import NewTodo from './components/newTodo'; import TodoList from './components/TodoList'; import './css/style.css'; import 'bootstrap/dist/css/bootstrap.css'; const initialState = { todos: [] }; // const initialState = { // todos: [{ id: 1, description: 'test task', state: 'NEW' }], // }; let todoC = []; const reducer = (state, action) => { switch (action.type) { case 'ADD': return { ...state, todos: [...state.todos, action.todo], }; case 'COMPLETE': // console.log('the reducer index is: ', action.todoIndex); // return { // state, // todos: state.todos.splice(action.todoIndex, 1), // }; const newItems = [...state.todos]; // create new array newItems.splice(action.todoIndex, 1); // remove element return { ...state, todos: newItems }; // spread state first so we don't lose our awesome title, override items with new items case 'COMPLETED': todoC.push(action.todo); todoC = [...new Set(todoC)]; console.log('todoC is: ', todoC); default: return state; } }; export const App: FC<{ name: string }> = ({ name }) => { const [state, dispatch] = useReducer(reducer, initialState); const { todos } = state; function addTodoHandlerReducer(todo) { dispatch({ type: 'ADD', todo: todo }); } function completeTodoHandlerReducer(index) { console.log('the index is: ', index); dispatch({ type: 'COMPLETE', todoIndex: index }); } function completeAddTodoHandlerReducer(todo) { console.log('the todo text is: ', todo); dispatch({ type: 'COMPLETED', todo: todo }); } return ( <> <h1>Todo Appication:</h1> <br /> <h1 style={{ color: 'grey', fontWeight: 'normal' }}>V1</h1> {/* <button type="button" className="btn btn-success" >Complete</button> */} <NewTodo addtodoHandlerReducer={addTodoHandlerReducer} /> <br /> <TodoList todos={todos} todoC={todoC} //completedTodos={completedTodos} completeTodoHandlerReducer={completeTodoHandlerReducer} completeAddTodoHandlerReducer={completeAddTodoHandlerReducer} /> </> ); };
import { Modal } from "flowbite-react"; import { useEffect, useState } from "react"; import Api from "app/api"; import { useFormik } from "formik"; import * as Yup from "yup"; import { useNavigate } from "react-router-dom"; import { useImageUpload } from "hooks/use-image-upload"; import { toast } from "react-toastify"; export default function AddPage({ fetchData }) { const [categories, setCategories] = useState([]); const [brands, setBrands] = useState([]); useEffect(() => { try { (async () => { const res = await Api.Get("/category"); if (!res.isSuccess) { toast.error("Đã có lỗi xảy ra"); return; } const newData = res.response.map((obj, index) => { return { id: obj.id, name: obj.name, } }) setCategories(newData); })(); (async () => { const res = await Api.Get("/brand"); if (!res.isSuccess) { toast.error("Đã có lỗi xảy ra"); return; } let newData = res.response.map((obj, index) => { return { id: obj.id, name: obj.name, } }) setBrands(newData); })(); } catch (err) { console.log(err); } }, []); const [openModal, setOpenModal] = useState(false); const [status, setStatus] = useState({ isError: false, errorMessage: "", isSubmit: false, }); const navigate = useNavigate(); const { image, previewUrl, handleImageChange } = useImageUpload(); const uploadImage = async (id) => { if (!image) { return false; } const formData = new FormData(); formData.append('image', image); const resData = await Api.Post(`/product/upload-image/${id}`, formData, { headers: { "Content-Type": "multipart/form-data" } }); if (!resData.isSuccess) { toast.error("Đã có lỗi xảy ra"); return false; } return true; } const formik = useFormik({ enableReinitialize: true, initialValues: { categoryId: categories[0] ? categories[0].id : 0, brandId: brands[0] ? brands[0].id : 0, name: "", price: 0, description: "", colors: [], sizes: [], }, validationSchema: Yup.object({ categoryId: Yup.string() .required("Đây là dữ liệu bắt buộc"), brandId: Yup.string() .required("Đây là dữ liệu bắt buộc"), name: Yup.string() .required("Đây là dữ liệu bắt buộc") .min(6, `Cần ít nhất 6 ký tự`) .max(255, `Không thể vượt quá 255 ký tự`), price: Yup.number() .required("Đây là dữ liệu bắt buộc") .typeError("Dữ liệu phải là một số"), description: Yup.string() .required("Đây là dữ liệu bắt buộc"), colors: Yup.array(), sizes: Yup.array(), }), onSubmit: async (values, { resetForm }) => { setStatus(prevState => ({ ...prevState, isSubmit: true })); const data = { categoryId: parseInt(values.categoryId), brandId: parseInt(values.brandId), name: values.name, price: parseInt(values.price), description: values.description, colors: values.colors, sizes: values.sizes, } console.log(data); const resData = await Api.Post("/product", data); if (!resData.isSuccess) { setStatus(prevState => ({ isError: true, errorMessage: resData.response.message, isSubmit: false, })); console.log(status); toast.error("Đã có lỗi xảy ra"); setOpenModal(false); return; } await uploadImage(resData.response.id); setStatus(prevState => ({ isError: false, errorMessage: resData.response.message, isSubmit: false, })); fetchData(); toast.success("Thêm thành công"); resetForm(); setOpenModal(false); }, }) return ( <div> {/* Modal toggle */} <div className="flex justify-center m-5"> <button onClick={() => setOpenModal(true)} className="w-full md:w-auto block text-white w-24 bg-primary-700 hover:bg-primary-800 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center" > Thêm </button> </div> <Modal show={openModal} onClose={() => setOpenModal(false)}> <Modal.Header className="pb-4">Thêm sản phẩm</Modal.Header> <Modal.Body className="pt-2"> <form onSubmit={formik.handleSubmit}> <div className="grid gap-4 mb-6 sm:grid-cols-2"> <div> <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Loại hàng</label> <select name="categoryId" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5" value={formik.values.categoryId || 0} onChange={formik.handleChange} > { categories.map((obj, index) => ( <option key={index} value={obj.id}> {obj.name} </option> )) } </select> {formik.errors.categoryId && formik.touched.categoryId && ( <p className="mt-1 ml-1 text-red-600 text-sm"> {formik.errors.categoryId} </p> )} </div> <div> <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Thương hiệu</label> <select name="brandId" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5" value={formik.values.brandId || 0} onChange={formik.handleChange} > { brands.map((obj, index) => ( <option key={index} value={obj.id}> {obj.name} </option> )) } </select> {formik.errors.brandId && formik.touched.brandId && ( <p className="mt-1 ml-1 text-red-600 text-sm"> {formik.errors.brandId} </p> )} </div> <div> <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Tên</label> <input type="text" name="name" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5" autoComplete="off" spellCheck="false" value={formik.values.name || ''} onChange={formik.handleChange} /> {formik.errors.name && formik.touched.name && ( <p className="mt-1 ml-1 text-red-600 text-sm"> {formik.errors.name} </p> )} </div> <div> <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Giá</label> <input type="text" name="price" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5" autoComplete="off" spellCheck="false" value={formik.values.price || ''} onChange={formik.handleChange} /> {formik.errors.price && formik.touched.price && ( <p className="mt-1 ml-1 text-red-600 text-sm"> {formik.errors.price} </p> )} </div> <div> <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Màu sắc</label> <select name="colors" multiple size="5" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5" onChange={formik.handleChange} > <option>Xanh</option> <option>Đỏ</option> <option>Tím</option> <option>Vàng</option> <option>Hồng</option> <option>Đen</option> <option>Trắng</option> </select> </div> <div> <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Kích cỡ</label> <select name="sizes" multiple size="5" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5" onChange={formik.handleChange} > <option>S</option> <option>M</option> <option>L</option> <option>XL</option> </select> </div> <div> <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Mô tả</label> <input type="text" name="description" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5" autoComplete="off" spellCheck="false" value={formik.values.description || ''} onChange={formik.handleChange} /> {formik.errors.description && formik.touched.description && ( <p className="mt-1 ml-1 text-red-600 text-sm"> {formik.errors.description} </p> )} </div> <div> <label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Hình ảnh</label> <input type="file" name="image" onChange={handleImageChange} /> </div> </div> <button disabled={status.isSubmit} type="submit" className="text-white inline-flex items-center bg-primary-700 hover:bg-primary-800 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center "> Xác nhận </button> </form> </Modal.Body> </Modal> </div> ) }
<template> <div> <el-form ref="form" label-width="80px"> <el-row ><el-col :span="12" ><el-form-item label="申请人"> <el-input v-model="form.applicant" readonly /> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="职位"> <el-input v-model="form.position" readonly /> </el-form-item> </el-col> <div v-if="openType !== 'add'"> <el-col :span="12"> <el-form-item label="开始时间"> <el-input v-model="form.start_time" readonly></el-input> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="结束时间"> <el-input v-model="form.end_time" readonly></el-input> </el-form-item> </el-col> </div> <div v-else> <el-col :span="12"> <el-form-item label="开始时间"> <date-time v-if="isreload" :startstauts="true" @settime="getStartTime" > </date-time> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="结束时间"> <date-time v-if="isreload" @settime="getEndTime"></date-time> </el-form-item> </el-col> </div> <el-col :span="12"> <el-form-item label="请假类型"> <el-select v-model="form.leave_category" placeholder="请选择" style="width:100%;" > <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" > </el-option> </el-select> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="共计天数"> <el-input :value="form.day_count != '' ? form.day_count : day_count" readonly /> </el-form-item> </el-col> <el-col :span="24"> <el-form-item label="请假事由"> <el-input v-model="form.reason" type="textarea" rows="3" minlength="300px" /> </el-form-item ></el-col> <el-col :span="24" v-if="openType == 'headle'"> <el-form-item label="意见"> <el-input type="textarea" :row="3" v-model="reasons"></el-input> </el-form-item> </el-col> <el-col :span="12" v-if="userTaskName != '结束' && openType != 'check'"> <el-form-item label="审核人"> <el-select v-model="userid" style="width:100%;" placeholder="没绑定审核人" > <el-option v-for="(item, index) in userList" :key="index" :value="item.userid" :label="item.username" ></el-option> </el-select> </el-form-item> </el-col> </el-row> <div v-if="openType == 'add'"> <el-row> </el-row> <el-form-item> <el-button type="success" @click="submitForm('form')">申请</el-button> <!-- <el-button type="danger" @click="resetForm('form')">重置</el-button> --> </el-form-item> </div> <div v-else-if="openType == 'headle'"> <el-form-item> <template v-for="(item, index) in buttonList"> <el-button v-if="item == 'submit'" :key="index" type="success" size="mini" @click="headleprocess(true)" >提交</el-button > <el-button v-if="item == 'Resubmit'" :key="index" type="success" size="mini" @click="headleprocess(true)" >重新提交</el-button > <el-button v-else-if="item == 'reject'" :key="index" type="warning" size="mini" @click="headleprocess(false)" >驳回</el-button > <el-button v-else-if="item == 'disagree'" :key="index" type="danger" size="mini" @click="headleprocess(false)" >不同意</el-button > </template> </el-form-item> </div> </el-form> <el-divider content-position="left">流程线</el-divider> <el-steps finish-status="success" :space="250" :active="current" style="margin-left:50px;" align-center > <el-step :title="item.name" v-for="(item, index) in activityList" :key="index" :description="item.username" ></el-step> </el-steps> <template v-if="openType != 'add'"> <el-divider content-position="left">审批流程</el-divider> <el-table :data="DataList" border> <el-table-column v-for="(item, index) in ApprovalHeaderList" :key="index" :label="item[0]" :prop="item[1]" :type="index == 0 ? 'index' : ''" :width="item[2]" align="center" ></el-table-column> </el-table> </template> </div> </template> <script> import DateTime from "@/components/Ca-date-time/Ca-date-time"; import { apisaveLeave, apipassLeave, apigetProcessList } from "@/request/api.js"; export default { name: "leavetable", data() { return { userTaskName: "", ApprovalHeaderList: [ ["序号", "index", 60], ["流程节点", "name_", 100], ["审核人", "username", 80], ["审核时间", "END_TIME_", 160], ["审核意见", "MESSAGE_"] ], reasons: "", options: [ { value: 0, label: "事假" }, { value: 1, label: "病假" }, { value: 2, label: "婚假" }, { value: 3, label: "产假" }, { value: 4, label: "丧假" }, { value: 5, label: "年假" }, { value: 6, label: "其它" } ], isreload: true, Approvaltable: [], buttonList: [], userid: 0, userList: [], activityList: [], current: 1 }; }, computed: { day_count() { let count = 0; let start = new Date(this.form.start_time); let end = new Date(this.form.end_time); let start_hour = start.getHours(); let leave_time = (end - start) / 3600000; if (start_hour >= 12) { if (leave_time <= 12) { count = 0.5; } else if (leave_time > 12 && leave_time <= 24) { count = 1; } else if (leave_time > 24) { count = Math.floor(leave_time / 24) + (leave_time % 24 <= 12 ? 0.5 : 1); } } else { if (leave_time <= 4) { count = 0.5; } else if (leave_time > 4 && leave_time <= 10) { count = 1; } else if (leave_time > 10) { count = Math.floor(leave_time / 24) + ((leave_time % 24) + start_hour <= 14 ? 0.5 : 1); } } return count; } }, components: { DateTime }, props: { DataList: Array, form: { type: Object, default: () => { return { leave_category: 1 }; } }, openType: String, active: Object }, created() { this.getprossList(); }, methods: { //获取下一审核人 getprossList() { let data = {}; if (this.active) { data = { taskid: this.active.ID_, //(必填)流程任务id processInstanceId: this.active.PROC_INST_ID_ ? this.active.PROC_INST_ID_ : this.active.taskid, //(必填)流程实例id key: "Leave_flow", //(必填)流程定义key position: this.active.role_name, //(必填)申请人角色 type: "" //(必填)新增new/运行中 }; } else { data = { taskid: "", //(必填)流程任务id processInstanceId: "", //(必填)流程实例id key: "Leave_flow", //(必填)流程定义key position: this.form.position, //(必填)申请人角色 type: "new" //(必填)新增new/运行中 }; } apigetProcessList(data).then(res => { console.log(res); //当前流程节点 if (this.DataList == "") { this.activityList = res.activityList; } else { let currentTask = this.DataList[this.DataList.length - 1]; //流程线 this.activityList = res.activityList.map((item, index) => { if (item.name == currentTask.name_) { this.current = currentTask.END_TIME_ == "" ? index : index + 1; } return item; }); } this.userTaskName = res.userlist.userTaskName; this.buttonList = res.startForm.split(","); this.userid = this.userTaskName == "结束" ? 0 : res.userlist.userList && res.userlist.userList != "" ? res.userlist.userList[0].userid : ""; this.userList = res.userlist.userList ? res.userlist.userList != "" ? res.userlist.userList : [] : []; }); }, //办理流程 headleprocess(type) { if (this.reasons == "") { this.$message.error("请填写审核意见"); return; } if (this.userid === "" && type) { this.$message.error("审核人为空不能提交!"); return; } this.$confirm( `确定${type === true ? "办理" : type === false ? "驳回" : "不同意"}吗?` ) .then(() => { let data = { taskid: this.active.ID_, userid: this.userid, reasons: this.reasons, sign: type }; apipassLeave(data).then(res => { console.log(res); this.$message.success(res.msg); this.$emit("close"); }); }) .catch(() => {}); }, //重置数据 reload() { this.isreload = false; this.$nextTick(() => { this.isreload = true; }); this.form = { applicant: sessionStorage.getItem("username"), position: sessionStorage.getItem("role_name"), start_time: "", end_time: "", leave_category: "", day_count: "", reason: "", userid: "" }; }, getApprover(e) { this.form.userid = e; }, // resetForm(formName) { // this.reload(); // this.$refs[formName].resetFields(); // }, //提交 submitForm() { if (this.form.start_time >= this.form.end_time) { this.$message.error("开始时间须早于结束时间"); return; } if (this.userid === "") { this.$message.warning("审核人为空不能提交"); return; } if (!this.form.reason || this.form.reason == "") { this.$message.warning("请补充请假事由"); return; } this.form.userid = this.userid; this.form.day_count = this.day_count; this.$confirm(`确定请假吗?`) .then(() => { apisaveLeave(this.form).then(res => { console.log(res); this.$message.success(res.msg); this.$emit("close"); }); }) .catch(() => {}); }, //从组件获取结束时间 getEndTime(time) { this.form.end_time = time; }, //从组件获取开始时间 getStartTime(time) { this.form.start_time = time; } } }; </script> <style lang="scss"> .el-table--striped .el-table__body tr.el-table__row--striped.current-row td, .el-table__body tr.current-row > td { background-color: rgb(252, 233, 199); } .el-table--striped .el-table__body tr.hover-row.el-table__row--striped > td, .el-table__body tr.hover-row > td { background-color: #d9ecff !important; } </style>
// // Copyright (c) 2022 - 2023. // Haixing Hu, Qubit Co. Ltd. // // All rights reserved. // import clone from '../src'; import Buyer from './model/Buyer'; import Credential from './model/Credential'; import CredentialType from './model/CredentialType'; import Gender from './model/Gender'; import Guardian from './model/Guardian'; import Insurant from './model/Insurant'; import Kinship from './model/Kinship'; import Person from './model/Person'; import expectAlike from './utils/expect-alike'; /** * Unit test the `clone()` function to clone objects of a customized class. * * @author Haixing Hu */ describe('clone objects of a customized class', () => { test('clone(Person)', () => { const obj = new Person(); obj.id = '0'; obj.name = 'name'; obj.credential = new Credential(CredentialType.IDENTITY_CARD.value, '123'); obj.gender = Gender.MALE.value; obj.birthday = '1990-01-01'; obj.mobile = '12039495'; obj.email = 'i@i.com'; const result = clone(obj); expect(result).toBeInstanceOf(Person); expectAlike(result, obj); }); test('clone(Buyer)', () => { const obj = new Buyer(); obj.id = '0'; obj.name = 'name'; obj.credential = new Credential(CredentialType.IDENTITY_CARD.value, '123'); obj.gender = Gender.MALE.value; obj.birthday = '1990-01-01'; obj.mobile = '12039495'; obj.email = 'i@i.com'; const result = clone(obj); expect(result).toBeInstanceOf(Buyer); expectAlike(result, obj); expectAlike(result.credential, obj.credential); }); test('clone(Guardian)', () => { const obj = new Guardian(); obj.id = '0'; obj.name = 'name'; obj.credential = new Credential(CredentialType.IDENTITY_CARD.value, '123'); obj.gender = Gender.MALE.value; obj.birthday = '1990-01-01'; obj.mobile = '12039495'; obj.email = 'i@i.com'; const result = clone(obj); expect(result).toBeInstanceOf(Guardian); expectAlike(result, obj); expectAlike(result.credential, obj.credential); }); test('clone(Insurant)', () => { const obj = new Insurant(); obj.id = '0'; obj.name = 'name'; obj.credential = new Credential(CredentialType.IDENTITY_CARD.value, '123'); obj.gender = Gender.MALE.value; obj.birthday = '1990-01-01'; obj.mobile = '12039495'; obj.email = 'i@i.com'; obj.kinship = Kinship.PARENT.value; obj.guardian = new Guardian(); obj.guardian.id = '1'; obj.guardian.name = 'guardian'; obj.guardian.credential = new Credential(CredentialType.IDENTITY_CARD.value, '456'); obj.guardian.gender = Gender.FEMALE.value; obj.guardian.birthday = '1970-02-03'; obj.guardian.mobile = '383789904'; obj.guardian.email = 'c@c.com'; const result = clone(obj); expect(result).toBeInstanceOf(Insurant); expectAlike(result, obj); expectAlike(result.credential, obj.credential); expectAlike(result.guardian, obj.guardian); expectAlike(result.guardian.credential, obj.guardian.credential); }); }); /** * Unit test the `clone()` function to clone objects of a customized class * with naming conversion. * * @author Haixing Hu */ describe('clone objects of a customized class with naming conversion', () => { test('clone(object, { convertNaming: true })', () => { const person = new Person(); person.id = '0'; person.name = 'name'; person.credential = new Credential(CredentialType.IDENTITY_CARD.value, '123'); person.gender = Gender.MALE.value; person.birthday = '1990-01-01'; person.mobile = '12039495'; person.email = 'i@i.com'; const obj = { first_field: 'first-field', second_field: { first_child_field: 'first-child-field', second_child_field: { the_person: person, }, }, }; const result = clone(obj, { convertNaming: true, sourceNamingStyle: 'LOWER_UNDERSCORE', targetNamingStyle: 'LOWER_CAMEL', }); expect(result).toBeInstanceOf(Object); expect(result.firstField).toBe(obj.first_field); expect(result.secondField).toBeInstanceOf(Object); expect(result.secondField.firstChildField).toBe(obj.second_field.first_child_field); expect(result.secondField.secondChildField).toBeInstanceOf(Object); expect(result.secondField.secondChildField.thePerson).toBeInstanceOf(Person); expectAlike(result.secondField.secondChildField.thePerson, person); }); test('clone(object, { convertNaming: true }), no targetNamingStyle', () => { const person = new Person(); person.id = '0'; person.name = 'name'; person.credential = new Credential(CredentialType.IDENTITY_CARD.value, '123'); person.gender = Gender.MALE.value; person.birthday = '1990-01-01'; person.mobile = '12039495'; person.email = 'i@i.com'; const obj = { first_field: 'first-field', second_field: { first_child_field: 'first-child-field', second_child_field: { the_person: person, }, }, }; const result = clone(obj, { convertNaming: true, sourceNamingStyle: 'LOWER_UNDERSCORE', }); expect(result).toBeInstanceOf(Object); expect(result.firstField).toBe(obj.first_field); expect(result.secondField).toBeInstanceOf(Object); expect(result.secondField.firstChildField).toBe(obj.second_field.first_child_field); expect(result.secondField.secondChildField).toBeInstanceOf(Object); expect(result.secondField.secondChildField.thePerson).toBeInstanceOf(Person); expectAlike(result.secondField.secondChildField.thePerson, person); }); test('clone(object, { convertNaming: true }), no sourceNamingStyle', () => { const person = new Person(); person.id = '0'; person.name = 'name'; person.credential = new Credential(CredentialType.IDENTITY_CARD.value, '123'); person.gender = Gender.MALE.value; person.birthday = '1990-01-01'; person.mobile = '12039495'; person.email = 'i@i.com'; const obj = { firstField: 'first-field', secondField: { firstChildField: 'first-child-field', secondChildField: { thePerson: person, }, }, }; const result = clone(obj, { convertNaming: true, targetNamingStyle: 'LOWER_UNDERSCORE', }); expect(result).toBeInstanceOf(Object); expect(result.first_field).toBe(obj.firstField); expect(result.second_field).toBeInstanceOf(Object); expect(result.second_field.first_child_field).toBe(obj.secondField.firstChildField); expect(result.second_field.second_child_field).toBeInstanceOf(Object); expect(result.second_field.second_child_field.the_person).toBeInstanceOf(Person); expectAlike(result.second_field.second_child_field.the_person, person); }); });
import {deNormalize, normalize,} from './tensor_helper.js'; let GLOBAL_MODEL; let GLOBAL_NORMALIZED_FEATURE; let GLOBAL_NORMALIZED_LABEL; let GLOBAL_POINT_ARRAY; export default class MyAI { static LEARNING_RATE = 0.1; static SAVE_KEY = 'Save_AI_DATA'; pointArray; model; trainingLabelTensor; testingLabelTensor; trainingFeatureTensor; testingFeatureTensor; normalizedFeatureTensor; normalizedLabelTensor; fields; fieldsValue; constructor() { } async removeErrors(obj) { return obj.x != null && obj.y != null; } async readData() { //./cars_multiple_linear.csv //./kc_house_data.csv // x: record.sqft_living, // x: record.engine_v, const loadingData = tf.data.csv('./kc_house_data.csv'); const pointsDataSet = loadingData.map(record => ({ x: record.sqft_living, y: record.price, })); const pointsArray = await pointsDataSet.toArray(); const temp = await loadingData.toArray(); this.fieldsValue = temp.slice(0, 10); this.fields = loadingData.fullColumnNames; if (pointsArray.length % 2 !== 0) { pointsArray.pop(); } this.pointArray = pointsArray; } async plot() { const surfacing = document.getElementById('plot1'); tfvis.render.scatterplot( surfacing , {values: [this.pointArray], series: ["original"]}, { xLabel: "foot", yLabel: "Price", } ); } getPointArray() { return this.pointArray; } initModel() { this.model = tf.sequential(); this.model.add(tf.layers.dense({ units: 1, useBias: true, activation: 'linear', inputDim: 1, })); const optimizer = tf.train.sgd(MyAI.LEARNING_RATE); this.model.compile({ loss: 'meanSquaredError', optimizer, }) } async run() { tf.util.shuffle(this.pointArray); await this.plot(); // extracting const featureValues = this.pointArray.map(p => p.x); const featureTensor = tf.tensor2d(featureValues, [featureValues.length, 1]); const labelValues = this.pointArray.map(p => p.y); const labelTensor = tf.tensor2d(labelValues, [labelValues.length, 1]); //normalization this.normalizedFeatureTensor = normalize(featureTensor); this.normalizedLabelTensor = normalize(labelTensor); [this.trainingFeatureTensor, this.testingFeatureTensor] = tf.split(this.normalizedFeatureTensor.tensor, 2); [this.trainingLabelTensor, this.testingLabelTensor] = tf.split(this.normalizedLabelTensor.tensor, 2); this.initModel(); this.summaryModel(); } summaryModel() { const surfacing1 = document.getElementById('plot2'); const surfacing2 = document.getElementById('plot3'); tfvis.show.modelSummary(surfacing1, this.model); const layer = this.model.getLayer(undefined, 0); tfvis.show.layer(surfacing2, layer); } async trainModel() { await this.plotPredictionLine(); const surfacing = document.getElementById('plot5'); const {onBatchEnd, onEpochEnd} = tfvis.show.fitCallbacks( surfacing , ['loss']); GLOBAL_MODEL = this.model; GLOBAL_NORMALIZED_FEATURE = this.normalizedFeatureTensor; GLOBAL_NORMALIZED_LABEL = this.normalizedLabelTensor; GLOBAL_POINT_ARRAY = this.pointArray; const result = await this.model.fit(this.trainingFeatureTensor, this.trainingLabelTensor, { batchSize: 32, epochs: 20, validationSplit: 0.2, callbacks: { onEpochEnd, onEpochBegin: async function () { const [xs, ys] = tf.tidy(() => { const normalisedXs = tf.linspace(0, 1, 100); const normalisedYs = GLOBAL_MODEL.predict(normalisedXs.reshape([100, 1])); const xs = deNormalize(normalisedXs, GLOBAL_NORMALIZED_FEATURE.min, GLOBAL_NORMALIZED_FEATURE.max); const ys = deNormalize(normalisedYs, GLOBAL_NORMALIZED_LABEL.min, GLOBAL_NORMALIZED_LABEL.max); return [xs.dataSync(), ys.dataSync()]; }); const predictedPoints = Array.from(xs).map((val, index) => { return {x: val, y: ys[index]}; }); const surfacing = document.getElementById('plot4'); tfvis.render.scatterplot( surfacing , {values: [GLOBAL_POINT_ARRAY, predictedPoints], series: ["original", "predicted"]}, { xLabel: name, yLabel: "Price", } ); const surfacing2 = document.getElementById('plot6'); const layer = GLOBAL_MODEL.getLayer(undefined, 0); tfvis.show.layer(surfacing2, layer); }, } }); const trainingLoss = result.history.loss.pop(); const validationLoss = result.history.val_loss.pop(); return {trainingLoss, validationLoss} } async plotPredictionLine() { const [xs, ys] = tf.tidy(() => { const normalisedXs = tf.linspace(0, 1, 100); const normalisedYs = this.model.predict(normalisedXs.reshape([100, 1])); const xs = deNormalize(normalisedXs, this.normalizedFeatureTensor.min, this.normalizedFeatureTensor.max); const ys = deNormalize(normalisedYs, this.normalizedLabelTensor.min, this.normalizedLabelTensor.max); return [xs.dataSync(), ys.dataSync()]; }); const predictedPoints = Array.from(xs).map((val, index) => { return {x: val, y: ys[index]}; }); const surfacing = document.getElementById('plot4'); tfvis.render.scatterplot( surfacing , {values: [this.pointArray, predictedPoints], series: ["original", "predicted"]}, { xLabel: name, yLabel: "Price", } ); } async loadModel() { const models = await tf.io.listModels(); const isModel = models[`localstorage://${MyAI.SAVE_KEY}`] if (isModel) { this.model = await tf.loadLayersModel(`localstorage://${MyAI.SAVE_KEY}`) this.summaryModel(); await this.plotPredictionLine(); return true; } else { return false; } } deleteModel() { } async saveModel() { this.model = await this.model.save(`localstorage://${MyAI.SAVE_KEY}`); } async testModel() { const lossTensor = this.model.evaluate(this.testingFeatureTensor, this.testingLabelTensor); return await lossTensor.dataSync(); } getFields() { return this.fields; }; getFieldsValue() { return this.fieldsValue; }; predict(value) { value = parseInt(value); return tf.tidy(() => { const inputTensor = tf.tensor1d([value]); const normalizedInput = normalize(inputTensor, this.normalizedFeatureTensor.min, this.normalizedLabelTensor); const normalizedOutputTensor = this.model.predict(normalizedInput.tensor); const outPutTensor = deNormalize(normalizedOutputTensor, this.normalizedLabelTensor.min, this.normalizedLabelTensor.max); const outPutValue = outPutTensor.dataSync()[0] return (outPutValue / 1000).toFixed(0) * 1000; }); } }
library(tidyverse) library(lubridate) #IMPORT MET DATA FROM TOWERS (met_RD <- read_csv("Met_data_RD_2015-2017.csv", col_names = c("yr", "mo", "dy", "dec.hr", "RH", "VPD", "BP_kPa", "ppt_mm", "WndSpd_mps", "WndDir_deg"), skip=3) %>% mutate(site = "RD")) (met_BW <- read_csv("Met_data_BW_2015-2017.csv", col_names = c("yr", "mo", "dy", "dec.hr", "RH", "VPD", "BP_kPa", "ppt_mm", "WndSpd_mps", "WndDir_deg"), skip=3) %>% mutate(site = "BW")) # CONVERT INTEGER DATES AND DECIMAL HRS TO DATETIME STAMP. # USE DATETIME TO GENERATE DATE and JULIAN DATE COLUMNS. (met_RD <- met_RD %>% mutate(hr = dec.hr %/% 1, min = ((dec.hr %% 1)*60), dec.hr=NULL) %>% mutate(DATETIME = make_datetime(yr, mo, dy, hr, min)) %>% mutate(DATE = make_date(yr, mo, dy)) %>% mutate(DOY = yday(DATE)) %>% arrange(DATETIME)) (met_BW <- met_BW %>% mutate(hr = dec.hr %/% 1, min = ((dec.hr %% 1)*60), dec.hr=NULL) %>% mutate(DATETIME = make_datetime(yr, mo, dy, hr, min)) %>% mutate(DATE = make_date(yr, mo, dy)) %>% mutate(DOY = yday(DATE)) %>% arrange(DATETIME)) # Generate a sequential vector of all times between data start and data end. timespan <- as.tibble(seq((met_RD$DATETIME[1]), (met_RD$DATETIME[nrow(met_RD)]), by = as.difftime(minutes(30)))) timespan <- timespan %>% dplyr::rename(DATETIME = value) ###NEXT: Check that there are no missing times/dates, # and then join to the full timespan (this is a kinda redundant for tower data but good practice) anti_join(timespan, met_RD) # Will return all times where there is no matching value for the met data file. left_join(timespan, met_RD) anti_join(timespan, met_BW) left_join(timespan, met_BW) ##NEED TO GAPFILL BEFORE COMBINING TABLES AND PROCEEDING TO ANALYSIS # create subset of tables to make join simpler RD_ppt <- met_RD %>% select(DATETIME, ppt_mm) BW_ppt <- met_BW %>% select(DATETIME, ppt_mm) # Join BW ppt data to RD and copy where RD ppt is NA, documenting which records are altered. (and vice-versa with BW) met_RD <- met_RD %>% mutate(gap_fill = ifelse(is.na(ppt_mm), "BW", NA)) %>% # Create a column to find null ppt_mm records and ID gap-filled data source. left_join(BW_ppt, by="DATETIME") %>% # Join BW_ppt to main met_RD mutate(ppt_mm = ifelse(is.na(ppt_mm.x), ppt_mm.y, ppt_mm.x)) %>% # Create new "ppt_mm" column filled with ppt.data based on logical argument select(-ppt_mm.x, -ppt_mm.y) # remove excess columns left over from join met_BW <- met_BW %>% mutate(gap_fill = ifelse(is.na(ppt_mm), "RD", NA)) %>% left_join(RD_ppt, by="DATETIME") %>% mutate(ppt_mm = ifelse(is.na(ppt_mm.x), ppt_mm.y, ppt_mm.x)) %>% select(-ppt_mm.x, -ppt_mm.y) # Confirm each table is sufficiantly gap-filled. met_RD %>% filter(is.na(ppt_mm)) met_BW %>% filter(is.na(ppt_mm)) # and then remove excess subset tables rm(BW_ppt, RD_ppt) #Generate daily precip summaries (met_RD_daily <- met_RD %>% group_by(DATE) %>% summarise_at(vars(RH, VPD, WndSpd_mps, ppt_mm), funs(min, max, sum)) %>% mutate(DOY = yday(DATE)) %>% select(-c(RH_sum, VPD_sum, WndSpd_mps_sum, ppt_mm_min))) (met_BW_daily <- met_BW %>% group_by(DATE) %>% summarise_at(vars(RH, VPD, WndSpd_mps, ppt_mm), funs(min, max, sum)) %>% mutate(DOY = yday(DATE)) %>% select(-c(RH_sum, VPD_sum, WndSpd_mps_sum, ppt_mm_min))) # Run daily summaries through assign event function: met_RD_daily <- assign.events(met_RD_daily, datetime.name = "DATE", value.name = "ppt_mm_sum", interevent = 1, threshold = 0.1, timestep = 1) str(met_RD_daily) met_RD_daily[[DATE]] # Write to project. write_csv(met_BW_daily, paste0("met_BW_daily_", today(), ".csv")) write_csv(met_RD_daily, paste0("met_RD_daily_", today(), ".csv")) #ADD one tbl to the other (append): met_twr<- bind_rows(met_RD, met_BW) %>% select(DATETIME, yr, mo, dy, hr, min, site, RH, VPD, BP_kPa, ppt_mm, WndSpd_mps, WndDir_deg, gap_fill) View(met_twr) #Generate a daily ppt Summar ppt_daysumm <- met_twr %>% group_by(site, yr, mo, dy) %>% summarise(sum(ppt_mm)) %>% mutate(dt = make_date(year=yr, month = mo, day = dy)) %>% group_by(site) %>% select(dt, yr, mo, dy, site, dyly_ppt = 'sum(ppt_mm)') %>% mutate(cum_ppt = cumsum(dyly_ppt)) #Quick plot of annual cumulative precip; needs work. ppt_daysumm %>% group_by(site, yr) %>% mutate(cum_ppt_yr = cumsum(dyly_ppt)) %>% ggplot(aes(dt, cum_ppt_yr, color=site))+ facet_wrap(~yr)+ geom_line()
import Card from "@/components/common/Card"; import { IRowTheme } from "@/types/row"; import ServiceChecklistItem from "./ServiceChecklistItem"; interface IServiceCard extends IRowTheme { objService: { title: string; list: string[]; }; } export default function ServiceCard(props: IServiceCard) { return ( <Card theme={props.theme} className="!p-0 !bg-bgDarkLight !text-left"> <div className="rounded-lg"> <div className={`flex items-center space-x-4 px-5 md:px-6 py-4 md:py-6 bg-gradient-to-br from-primaryDark via-secondaryDark to-accentDark border-b border-black`} > <h2 className="text-2xl text-left font-semibold text-textLight"> {props.objService.title} </h2> </div> {props.objService?.list && !!props.objService.list.length && ( <> <hr /> <div className="p-5 md:p-6 bg-bgDarkLight"> <ul role="list" className="space-y-2"> {props.objService?.list?.map((item, index) => ( <ServiceChecklistItem key={index} checklistItem={item} /> ))} </ul> </div> </> )} </div> </Card> ); }
import pandas as pd from monai.utils import set_determinism from monai.transforms import ( AsDiscrete, Compose, EnsureType, ) from monai.networks.nets import UNet, UNETR from monai.networks.layers import Norm, Act from monai.metrics import DiceMetric, HausdorffDistanceMetric, SurfaceDistanceMetric from monai.losses import DiceLoss, DiceFocalLoss, MaskedDiceLoss, DiceCELoss from monai.inferers import sliding_window_inference from monai.data import CacheDataset, DataLoader, Dataset, decollate_batch from torch.optim.lr_scheduler import ReduceLROnPlateau, StepLR, CosineAnnealingLR from torch.utils.tensorboard import SummaryWriter from utils.DataLoad import Data_Loader import torch import os import glob import time set_determinism(seed=0) device = torch.device("cuda:0") torch.backends.cudnn.enable = True torch.backends.cudnn.benchmark = True def train(train_files, val_files): train_loader, train_lenth = Data_Loader(train_files, data='train') val_loader, val_lenth = Data_Loader(val_files, data='val') model = UNet(dimensions=3 , in_channels=1 , out_channels=2 , channels=(32, 64, 128, 256, 512) , strides=(2, 2, 2, 2) , num_res_units=0 # , dropout=0.5 , norm=Norm.BATCH).to(device) # model.load_state_dict(torch.load('pretrain_model/Unet.pth'), strict=False) # 定义损失函数 # loss_function = DiceLoss(to_onehot_y=True, softmax=True) loss_function = DiceFocalLoss(to_onehot_y=True, softmax=True) # 定义优化器 optimizer = torch.optim.Adam(model.parameters(), 3e-4) # DiceMetric:比较两特征张量之间的差别 dice_metric = DiceMetric(include_background=False, reduction="mean") # hausdorff = HausdorffDistanceMetric(include_background=False, distance_metric='euclidean', percentile=95, # reduction='mean', ) # surface = SurfaceDistanceMetric(include_background=False, distance_metric='euclidean', reduction='mean') # 定义学习率下降策略 scheduler = StepLR(optimizer, step_size=20, gamma=0.90) # scheduler = ReduceLROnPlateau(optimizer, 'min', factor=0.5, patience=20, verbose=True) # scheduler = CosineAnnealingLR(optimizer, T_max=50, eta_min=5e-6) # # 训练参数 max_epochs = 200 val_interval = 1 best_metric = -1 best_metric_epoch = -1 metric_values = [] step_total = 0 post_pred = Compose([EnsureType(), AsDiscrete(argmax=True, to_onehot=True, num_classes=2)]) post_label = Compose([EnsureType(), AsDiscrete(to_onehot=True, num_classes=2)]) # 训练日志保存 log_dir = 'LOG/res=2256' writer = SummaryWriter(log_dir) # 开始训练 for epoch in range(max_epochs): print("-" * 10) print(f"epoch {epoch + 1}/{max_epochs}") model.train() epoch_loss = 0 step = 0 for batch_data in train_loader: epoch_start = time.time() step_start = time.time() step_total += 1 step += 1 inputs, labels = ( batch_data["image"].to(device), batch_data["label"].to(device), ) optimizer.zero_grad() outputs = model(inputs) loss = loss_function(outputs, labels) train_outputs = [post_pred(i) for i in decollate_batch(outputs)] train_labels = [post_label(i) for i in decollate_batch(labels)] dice_metric(y_pred=train_outputs, y=train_labels) # hausdorff(y_pred=train_outputs, y=train_labels) # surface(y_pred=train_outputs, y=train_labels) print(dice_metric.aggregate().item()) loss.backward() optimizer.step() epoch_loss += loss.item() writer.add_scalar('Training/Step loss', loss.item(), step_total + 1) print('{}/{}, train_loss: {:.4f}, step time: {:.4f} '.format( step, train_lenth // train_loader.batch_size, loss.item(), time.time() - step_start)) train_metric = dice_metric.aggregate().item() # train_hs = hausdorff.aggregate().item() # train_surface = surface.aggregate().item() writer.add_scalar('Training/Dice metric', train_metric, epoch + 1) # writer.add_scalar('Training/Hausdorff', train_hs, epoch + 1) # writer.add_scalar('Training/Surface', train_surface, epoch + 1) print(train_metric) print('**************************') # print(train_hs) print('**************************') # print(train_surface) dice_metric.reset() # hausdorff.reset() # surface.reset() lr_rate = scheduler.get_last_lr()[0] writer.add_scalar('Training/Learning Rate', lr_rate, epoch + 1) print(lr_rate) scheduler.step() epoch_loss /= step writer.add_scalar("Training/Epoch Average Loss", epoch_loss, epoch + 1) print(f"epoch {epoch + 1} average loss: {epoch_loss:.4f}") if (epoch + 1) % val_interval == 0: model.eval() with torch.no_grad(): for val_data in val_loader: val_inputs, val_labels = ( val_data["image"].to(device), val_data["label"].to(device), ) # print(val_inputs.shape,val_labels.shape) roi_size = (96, 96, 96) sw_batch_size = 8 val_outputs = sliding_window_inference(val_inputs, roi_size, sw_batch_size, model, overlap=0.5) val_outputs = [post_pred(i) for i in decollate_batch(val_outputs)] val_labels = [post_label(i) for i in decollate_batch(val_labels)] # 计算当前batch的metric dice_metric(y_pred=val_outputs, y=val_labels) # hausdorff(y_pred=val_outputs, y=val_labels) # surface(y_pred=val_outputs, y=val_labels) print(dice_metric.aggregate().item()) # 统计最终metric结果 val_metric = dice_metric.aggregate().item() # val_hs = hausdorff.aggregate().item() # val_surface = surface.aggregate().item() writer.add_scalar("Validation/Dice metric", val_metric, epoch + 1) # writer.add_scalar("Validation/Hausdorff", val_hs, epoch + 1) # writer.add_scalar("Validation/Surface", val_surface, epoch + 1) # 重置dice矩阵 dice_metric.reset() # hausdorff.reset() # surface.reset() metric_values.append(val_metric) if val_metric > best_metric: best_metric = val_metric best_metric_epoch = epoch + 1 save_dir = 'model_save/res=2256/' save_path = save_dir + str(epoch + 1) + "best_model_dice_v{:.4f}t{:.4f}.pth".format( val_metric, train_metric) torch.save(model.state_dict(), save_path) print("saved new best metric model") print( f"current epoch: {epoch + 1} current mean dice: {val_metric:.4f}" f"\nbest mean dice: {best_metric:.4f} " f"at epoch: {best_metric_epoch}" ) writer.close() if __name__ == '__main__': os.environ["CUDA_VISIBLE_DEVICES"] = "0" # 加载训练集数据 train_root = r'Q:\deep\train' train_images = sorted(glob.glob(os.path.join(train_root, 'images', '*.nii'))) train_labels = sorted(glob.glob(os.path.join(train_root, 'masks', '*.nii.gz'))) train_files = [{'image': image_name, 'label': label_name} for image_name, label_name in zip(train_images, train_labels)] # 加载验证集数据 valid_root = r'Q:\deep\valid' valid_images = sorted(glob.glob(os.path.join(valid_root, 'images', '*.nii'))) valid_labels = sorted(glob.glob(os.path.join(valid_root, 'masks', '*.nii.gz'))) valid_files = [{'image': image_name, 'label': label_name} for image_name, label_name in zip(valid_images, valid_labels)] train(train_files, valid_files) # for item in val_files: # print(item['image']) # test(test_files)
<!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> <?php function sumadivisores($n) { $suma = 0; for ($i = 1; $i <= $n / 2; $i++) { if ($n % $i == 0) { $suma += $i; } } return $suma; } function esperfecto($n) { return $n === sumadivisores($n); } // Programa que prueba las funciones $numero = 28; // Puedes cambiar este número para probar otras entradas if (esperfecto($numero)) { echo "$numero es un número perfecto. Su suma de divisores es " . sumadivisores($numero) . "\n"; } else { echo "$numero no es un número perfecto. Su suma de divisores es " . sumadivisores($numero) . "\n"; } // Encontrar y mostrar los números perfectos entre 1 y 1000 echo "Números perfectos entre 1 y 1000:\n"; for ($i = 1; $i <= 1000; $i++) { if (esperfecto($i)) { echo "$i es un número perfecto. Su suma de divisores es " . sumadivisores($i) . "\n"; } } ?> </body> </html>
--- tags: - GADA - coursera - note Links: - "[[AI and ML Engineer]]" - "[[Data Scientist]]" --- Previously, you learned about gradient boosting machine models and studied how to build and tune them with XGBoost’s scikit-learn API. This reading is a quick-reference guide to help you when you’re building XGBoost models of your own. It includes information on the following components: - Import statements - Hyperparameters ## **Save this course item** You may want to save a copy of this guide for future reference. You can use it as a resource for additional practice or in your future professional projects. To access a downloadable version of this course item, click the following link and select “Use Template.”  ![[Reference guide_ XGBoost tuning.docx]] ## Import statements The following are some of the most commonly used import statements for gradient boosting models using the XGBoost library together with scikit-learn. ### Models For classification tasks:  ```python from xgboost import XGBClassifier ``` For regression tasks: ```python from xgboost import XGBRegressor ``` ## Evaluation metrics  ### For classification tasks:  from sklearn.metrics import | | | |---|---| |[**accuracy_score**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html#sklearn.metrics.accuracy_score) (y_true, y_pred, *[, ...])|Accuracy classification score| |[**average_precision_score**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precision_score)(y_true, ...)|Compute average precision (AP) from prediction scores| |[**confusion_matrix**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html#sklearn.metrics.confusion_matrix)(y_true, y_pred, *)|Compute confusion matrix to evaluate the performance of the training of a model| |[**f1_score**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html#sklearn.metrics.f1_score)(y_true, y_pred, *[, ...])|Compute the F1 score, also known as balanced F-score or F-measure| |[**fbeta_score**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.fbeta_score.html#sklearn.metrics.fbeta_score)(y_true, y_pred, *, beta)|Compute the F-beta score| |[**metrics.log_loss**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html#sklearn.metrics.log_loss)(y_true, y_pred, *[, eps, ...])|Log loss, aka logistic loss or cross-entropy loss| |[**multilabel_confusion_matrix**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.multilabel_confusion_matrix.html#sklearn.metrics.multilabel_confusion_matrix)(y_true, ...)|Compute a confusion matrix for each class or sample| |[**precision_recall_curve**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_curve.html#sklearn.metrics.precision_recall_curve)(y_true, ...)|Compute precision-recall pairs for different probability thresholds| |[**precision_score**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html#sklearn.metrics.precision_score)(y_true, y_pred, *[, ...])|Compute the precision| |[**recall_score**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html#sklearn.metrics.recall_score)(y_true, y_pred, *[, ...])|Compute the recall| |[**roc_auc_score**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html#sklearn.metrics.roc_auc_score)(y_true, y_score, *[, ...])|Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores| **For regression tasks**: from sklearn.metrics import  | | | |---|---| |[**mean_absolute_error**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html#sklearn.metrics.mean_absolute_error)(y_true, y_pred, *)|Mean absolute error regression loss| |[**mean_squared_error**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html#sklearn.metrics.mean_squared_error)(y_true, y_pred, *)|Mean squared error regression loss| |[**mean_squared_log_error**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_log_error.html#sklearn.metrics.mean_squared_log_error)(y_true, y_pred, *)|Mean squared logarithmic error regression loss| |[**median_absolute_error**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.median_absolute_error.html#sklearn.metrics.median_absolute_error)(y_true, y_pred, *)|Median absolute error regression loss| |[**mean_absolute_percentage_error**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_percentage_error.html#sklearn.metrics.mean_absolute_percentage_error)(...)|Mean absolute percentage error (MAPE) regression loss| |[**r2_score**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.html#sklearn.metrics.r2_score)(y_true, y_pred, *[, ...])|_R_2 (coefficient of determination) regression score function| ## Hyperparameters The following are some of the most important hyperparameters for gradient boosting machine classification models built with the XGBoost library. These are the hyperparameters that data professionals typically reach for first, because they are among the most intuitive and they control the model at different levels using a diverse variety of mechanisms. ### n_estimators |**Hyperparameter**|**What it does**|**Input type**|**Default Value**| |---|---|---|---| |n_estimators|Specifies the number of boosting rounds (i.e., the number of trees your model will build in its ensemble)|int|100| **Considerations:**  A typical range is 50–500. Consider how much data you have, how deep the trees are allowed to grow, and how many samples are bootstrapped from the overall data to grow each tree (you generally need more trees if they’re shallow, and more trees if your bootstrap sample size represents just a small fraction of your overall data). For an extreme but illustrative example, if you have a dataset of 10,000, and each tree only bootstraps 20 samples, you'll need more trees than if you gave each tree 5,000 samples. Also keep in mind that, unlike random forest, which can grow base learners in parallel, gradient boosting grows base learners successively, so training can take longer for more trees. ### max_depth |**Hyperparameter**|**What it does**|**Input type**|**Default Value**| |---|---|---|---| |max_depth|Specifies how many levels your base learner trees can have. If None, <br><br>trees grow until leaves are pure or until all leaves have less than min_child_weight.|int|6| **Considerations:** Controls complexity of the model. Gradient boosting typically uses weak learners, or “decision stumps” (i.e., shallow trees). Restricting tree depth can reduce training times and serving latency as well as prevent overfitting. Consider values 2–6. ### min_child_weight |**Hyperparameter**|**What it does**|**Input type**|**Default Value**| |---|---|---|---| |min_child_weight|Controls threshold below which a node becomes a leaf, based on the combined weight of the samples it contains.  <br><br>For regression models, this value is functionally equivalent to a number of samples. <br><br>For the binary classification objective, the weight of a sample in a node is dependent on its probability of response as calculated by that tree. The weight of the sample decreases the more certain the model is (i.e., the closer the probability of response is to 0 or 1).|int or float|1| **Considerations:** Higher values will stop trees splitting further, and lower values will allow trees to continue to split further. If your model is underfitting, then you may want to lower it to allow for more complexity. Conversely, increase this value to stop your trees from getting too finely divided.  ### learning_rate |**Hyperparameter**|**What it does**|**Input type**|**Default Value**| |---|---|---|---| |learning_rate|Controls how much importance is given to each consecutive base learner in the ensemble’s final prediction. Also known as _eta_ or _shrinkage_.|float|0.3| **Considerations:** Values can range from (0–1]. Typical values range from 0.01 to 0.3. Lower values mean less weight is given to each consecutive base learner. Consider how many trees are in your ensemble. Lower values typically benefit from more trees.  ### colsample_bytree* |**Hyperparameter**|**What it does**|**Input type**|**Default Value**| |---|---|---|---| |colsample_bytree*|Specifies the percentage (0–1.0] of features that each tree randomly selects during training|float|1.0| **Considerations:** Adds randomness to the model to make it robust to noise. Consider how many features the dataset has and how many trees will be grown. Fewer features sampled means more base learners might be needed. Small colsample_bytree values on datasets with many features mean more unpredictive trees in the ensemble.  ### subsample* |**Hyperparameter**|**What it does**|**Input type**|**Default Value**| |---|---|---|---| |subsample*|Specifies the percentage (0–1.0] of observations sampled from the dataset to train each base model.|float|1.0| **Considerations:** Adds randomness to the model to make it robust to noise. Consider the size of your dataset. When working with large datasets, it can be beneficial to limit the number of samples in each tree, because doing so can greatly reduce training time and yet still result in a robust model. For example, 20% of 1 billion might be enough to capture patterns in the data, but if you only have 1,000 samples in your dataset then you’ll probably need to use them all.  *Note that colsample_bytree and subsample were not used in the [Tune a GBM model](https://www.coursera.org/learn/the-nuts-and-bolts-of-machine-learning/item/bmlVU) video and its accompanying notebook; they are included here so you can use these hyperparameters in your own work. Remember that using fractions of the data to train each base learner can possibly improve model predictions and certainly speed up training times. ## Key takeaways When building machine learning models, it’s essential to have the right tools and understand how to use them. Although there are numerous other hyperparameters to explore, the ones in this reference guide are among the most important. Be inquisitive and try different approaches. Discovering ways to improve your model is a lot of fun! ## Resources for more information More detailed information about XGBoost can be found here: - [scikit-learn model metrics](https://scikit-learn.org/stable/modules/classes.html?highlight=metrics#sklearn-metrics-metrics): documentation for evaluation metrics in scikit-learn - [XGBoost classifier](https://xgboost.readthedocs.io/en/stable/python/python_api.html#xgboost.XGBClassifier): XGBoost documentation for classification tasks using the scikit-learn API - [XGBoost Regressor](https://xgboost.readthedocs.io/en/stable/python/python_api.html#module-xgboost.sklearn): XGBoost documentation for regression tasks using the scikit-learn API - [Notes on parameter tuning from XGBoost](https://xgboost.readthedocs.io/en/stable/tutorials/param_tuning.html) - [XGBoost parameters](https://xgboost.readthedocs.io/en/stable/parameter.html): XGBoost parameters guide. **NOTE:** The information in this link is not specific to the scikit-learn API. **The default values listed in this resource are not always the same as the ones in the scikit-learn API.**
using System; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Linq; using System.Text; namespace T0yK4T.Data { /// <summary> /// An interface that can be used to implement a simple data store adapter /// </summary> /// <typeparam name="T"></typeparam> public interface IDataAdapter<T> { /// <summary> /// Stores the generic type <typeparamref name="T"/> in the datastore /// </summary> /// <param name="value">The value to store</param> void Store(T value); /// <summary> /// Gets the first instance of <typeparamref name="T"/> available in the datastore /// </summary> /// <returns></returns> T GetFirst(); /// <summary> /// Attempts to get all instances of <typeparamref name="T"/> /// </summary> /// <returns></returns> IEnumerable<T> GetAll(); /// <summary> /// Attempts to find a single element in the underlying datastore with the specified <paramref name="property"/> set /// </summary> /// <param name="property"></param> /// <returns></returns> T FindOne(IDataProperty<T> property); /// <summary> /// Attempts to find a single element in the underlying datastore with the specified <paramref name="properties"/> set /// </summary> /// <param name="properties"></param> /// <returns></returns> T FindOne(params IDataProperty<T>[] properties); /// <summary> /// Attempts to update the specified value in the underlying datastore /// </summary> /// <param name="value"></param> void Update(T value); /// <summary> /// Attempts to find instances of <typeparamref name="T"/> in the underlying datastore that have the specified <see cref="DataProperty{T}"/> /// </summary> /// <param name="property"></param> /// <returns></returns> IEnumerable<T> Find(IDataProperty<T> property); /// <summary> /// Deletes all records containing the specified property with it's value /// </summary> /// <param name="property"></param> void Delete(IDataProperty<T> property); /// <summary> /// Attempts to find instances of <typeparamref name="T"/> in the underlying datastore using the specified <see cref="DataProperty{T}"/> as a filter /// </summary> /// <param name="properties"></param> /// <param name="op"></param> /// <returns></returns> IEnumerable<T> Find(IEnumerable<IDataProperty<T>> properties, BooleanOperator op); /// <summary> /// Deletes all records in the underlying datasource that match the specified properties, combining them with the specified boolean operator /// </summary> /// <param name="properties"></param> /// <param name="op"></param> void Delete(IEnumerable<IDataProperty<T>> properties, BooleanOperator op); /// <summary> /// Attempts to find instances of <typeparamref name="T"/> in the underlying datastore who's <paramref name="KeyName"/> property match the specified <paramref name="searchPattern"/> /// <para/> /// (Please note that this may only be possible on string types! /// </summary> /// <param name="KeyName"></param> /// <param name="searchPattern"></param> /// <returns></returns> IEnumerable<T> Find(string KeyName, Regex searchPattern); /// <summary> /// Deletes all records that have key <paramref name="keyName"/> set to a value that matches <paramref name="searchPattern"/> /// </summary> /// <param name="keyName"></param> /// <param name="searchPattern"></param> void Delete(string keyName, Regex searchPattern); /// <summary> /// Attempts to find a collection of <typeparamref name="T"/>s in the underlying collection using the specified <paramref name="matchFields"/> to make matches /// </summary> /// <param name="matchFields"></param> /// <param name="op"></param> /// <returns></returns> IEnumerable<T> Find(BooleanOperator op, params KeyValuePair<string, Regex>[] matchFields); /// <summary> /// This method combines the funcionality of <see cref="Delete(string, Regex)"/> with <see cref="Find(BooleanOperator, KeyValuePair{string, Regex}[])"/> /// </summary> /// <param name="op"></param> /// <param name="matchFields"></param> void Delete(BooleanOperator op, params KeyValuePair<string, Regex>[] matchFields); /// <summary> /// Attempts to find every unique value of <paramref name="key"/> /// <para/> /// Possibly very volatile! /// </summary> /// <param name="key">The key to look for</param> /// <returns></returns> IEnumerable<T2> Distinct<T2>(string key); /// <summary> /// Attempts to find every unique value in the database using the specified filters /// </summary> /// <typeparam name="T2"></typeparam> /// <param name="key"></param> /// <param name="matchFields"></param> /// <param name="op"></param> /// <returns></returns> IEnumerable<T2> Distinct<T2>(string key, BooleanOperator op, params KeyValuePair<string, Regex>[] matchFields); /// <summary> /// /// </summary> /// <param name="op"></param> /// <param name="matchFields"></param> /// <returns></returns> int Count(BooleanOperator op, params KeyValuePair<string, Regex>[] matchFields); } /// <summary> /// Used to define a boolean operator (And / Or) /// </summary> public enum BooleanOperator { /// <summary> /// ... /// </summary> AND, /// <summary> /// ... /// </summary> OR, } }
import { Controller, Get } from '@nestjs/common'; import { AsynchronousOperationsService } from './asynchronous-operations.service'; import { ApiTags } from "@nestjs/swagger"; @Controller('asynchronous-operations') export class AsynchronousOperationsController { constructor(private readonly asynchronousOperationsService: AsynchronousOperationsService) { } @ApiTags('asynchronous-operations') @Get('download') async downloadContents() { const urlsToDownload = [ 'https://picsum.photos/id/237/200/300', ]; try { const downloadedContents = await this.asynchronousOperationsService.downloadContentsFromUrls(urlsToDownload); return { downloadedContents }; } catch (error) { return { error: 'Failed to download contents' }; } } }
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; class TopicCard extends StatelessWidget { final String imagePath; final String title; TopicCard({required this.imagePath, required this.title}); @override Widget build(BuildContext context) { return Stack( alignment: AlignmentDirectional.bottomStart, children: [ // Image Container( width: MediaQuery.sizeOf(context).width * 0.7, height: 200, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(15)), ), // Blurred Container Container( alignment: Alignment.topLeft, padding: EdgeInsets.all(10), height: 70.0, width: MediaQuery.sizeOf(context).width * 0.7, decoration: BoxDecoration( color: Colors.black.withOpacity(0.3), borderRadius: BorderRadius.only( bottomLeft: Radius.circular(15), bottomRight: Radius.circular(15)), ), child: Text( title, style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.w500, color: Colors.white), ), ), // Title ], ); } }
import React from "react"; import Snackbar from "@material-ui/core/Snackbar"; import MuiAlert from "@material-ui/lab/Alert"; const Alert = React.forwardRef(function Alert(props, ref) { return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />; }); // アラートメッセージ(何かアクションを行なった際の案内用に使い回す) const AlertMessage = ({ open, setOpen, severity, message }) => { const handleCloseAlertMessage = (e, reason) => { if (reason === "clickaway") return; setOpen(false); }; return ( <> <Snackbar open={open} autoHideDuration={6000} anchorOrigin={{ vertical: "bottom", horizontal: "center" }} onClose={handleCloseAlertMessage} > <Alert onClose={handleCloseAlertMessage} severity={severity}> {message} </Alert> </Snackbar> </> ); }; export default AlertMessage;
package ru.lm359.shotclockbanking.controller; import org.springframework.web.bind.annotation.*; import ru.lm359.shotclockbanking.controller.exception.NotFoundException; import ru.lm359.shotclockbanking.dtos.create.CreateAccountDto; import ru.lm359.shotclockbanking.models.Account; import ru.lm359.shotclockbanking.models.Customer; import ru.lm359.shotclockbanking.service.AccountService; import ru.lm359.shotclockbanking.service.CustomerService; import java.util.List; @RestController @RequestMapping("/v1/accounts") public class AccountController { private final AccountService accountService; private final CustomerService customerService; public AccountController(AccountService accountService, CustomerService customerService) { this.accountService = accountService; this.customerService = customerService; } @PostMapping public Account createAccount(@RequestBody CreateAccountDto accountDto) { Customer customer = customerService.getCustomerById(accountDto.getOwnerId()); if(customer==null) throw new NotFoundException("Customer not found"); Account account = new Account( accountDto.getAccountNumber(), accountDto.getAccountType(), accountDto.getBalance(), customer, accountDto.getMonthlyPayment() ); return accountService.createAccount(account); } @GetMapping("/{accountId}") public Account getAccountById(@PathVariable Long accountId) { return accountService.getAccountById(accountId); } @GetMapping public List<Account> getAllCustomers() { return accountService.getAllAccounts(); } @PutMapping("/{accountId}") public Account updateAccount(@PathVariable Long accountId, @RequestBody Account updatedAccount) { Account existingAccount = accountService.getAccountById(accountId); if(existingAccount==null) throw new NotFoundException("Customer not found"); if(updatedAccount.getAccountType()!=null) existingAccount.setAccountType(updatedAccount.getAccountType()); if(updatedAccount.getBalance()!=null) existingAccount.setBalance(updatedAccount.getBalance()); if(updatedAccount.getMonthlyPayment()!=null) existingAccount.setMonthlyPayment(updatedAccount.getMonthlyPayment()); return accountService.updateAccount(existingAccount); } @DeleteMapping("/{accountId}") public void deleteAccount(@PathVariable Long accountId) { accountService.deleteAccount(accountId); } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AdminAuthGuard } from './admin-auth.guard'; import { HomeComponent } from './home/home.component'; import { LoginComponent } from './login/login.component'; import { ProductsComponent } from './products/products.component'; import { RegisterComponent } from './register/register.component'; import { CartComponent } from './userprofile/cart/cart.component'; const routes: Routes = [ {path:'home',component:HomeComponent}, {path:'login',component:LoginComponent}, {path:'',redirectTo:'home',pathMatch:'full'}, {path:'products',component:ProductsComponent}, {path:'signup', component:RegisterComponent}, {path:'userprofile/cart/:firstName',component:CartComponent}, { path: 'userprofile/:firstName', loadChildren: () => import('./userprofile/userprofile.module').then(m => m.UserprofileModule) }, { path: 'adminprofile/:admin', loadChildren: () => import('./adminprofile/adminprofile.module').then(m => m.AdminprofileModule) } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import { useState } from 'react'; import {Button, Card, Checkbox, Container, Stack, Table, TableBody, TableCell, TableContainer, TablePagination, TableRow, Typography } from '@mui/material' /* import DeleteIcon from '@mui/icons-material/Delete'; import { Alert, Box, Button, Card, Checkbox, CircularProgress, Container, Divider, IconButton, List, ListItem, ListItemButton, ListItemText, Stack, Table, TableBody, TableCell, TableContainer, TablePagination, TableRow, TextField, Typography } from '@mui/material' import EditIcon from '@mui/icons-material/Edit'; import { useFormik } from 'formik' import { useAddCategoryMutation, useUpdateCategoryMutation } from '../../features/api/propertyApiService' import * as Yup from 'yup' */ import { filter } from "lodash" import {useGetCategoriesQuery } from '../../features/api/propertyApiService' /* import isEmptyObject from '../../utils/isEmptyObject' import RenderServerErrorMessage from '../../components/RenderServerErrorMessage' */ import CategoryListToolbar from "../dashboard/categories/CategoryListToolbar"; import { CategoryListHead, CategoryMoreMenu } from './categories'; import SearchNotFound from '../../components/SearchNotFound'; /* import { Link as RouterLink } from 'react-router-dom'; import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline'; */ import EmptyList from '../../components/EmptyList'; import CategoryFormDialog from './categories/CategoryFormDialog'; const TABLE_HEAD = [ { id: 'title', label: 'Title', alignRight: false }, { id: '', label: 'No. of Properties', alignRight: true }, { id: '' }, ]; function descendingComparator(a, b, orderBy) { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0; } function getComparator(order, orderBy) { return order === 'desc' ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy); } function applySortFilter(array = [], comparator, query) { const stabilizedThis = array?.map((el, index) => [el, index]); stabilizedThis?.sort((a, b) => { const order = comparator(a[0], b[0]); if (order !== 0) return order; return a[1] - b[1]; }); if (query) { return filter(array, (_property) => _property.title.toLowerCase().indexOf(query.toLowerCase()) !== -1); } return stabilizedThis?.map((el) => el[0]); } const CreatePropertyCategory = () => { const { data, refetch, isLoading } = useGetCategoriesQuery() const [edit, setEdit] = useState(false) const [open, setOpen] = useState(false) const userProperties = data ? data.categories : null; const [page, setPage] = useState(0); const [order, setOrder] = useState('asc'); const [selected, setSelected] = useState([]); const [orderBy, setOrderBy] = useState('title'); const [filterTitle, setFilterTitle] = useState(''); const [rowsPerPage, setRowsPerPage] = useState(5); const handleRequestSort = (event, property) => { const isAsc = orderBy === property && order === 'asc'; setOrder(isAsc ? 'desc' : 'asc'); setOrderBy(property); }; const handleSelectAllClick = (event) => { if (event.target.checked) { const newSelecteds = userProperties.map((n) => n.id); setSelected(newSelecteds); return; } setSelected([]); }; const handleClick = (event, title) => { const selectedIndex = selected.indexOf(title); let newSelected = []; if (selectedIndex === -1) { newSelected = newSelected.concat(selected, title); } else if (selectedIndex === 0) { newSelected = newSelected.concat(selected.slice(1)); } else if (selectedIndex === selected.length - 1) { newSelected = newSelected.concat(selected.slice(0, -1)); } else if (selectedIndex > 0) { newSelected = newSelected.concat(selected.slice(0, selectedIndex), selected.slice(selectedIndex + 1)); } setSelected(newSelected); }; const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; const handleFilterByTitle = (event) => { setFilterTitle(event.target.value); }; const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - userProperties.length) : 0; const filteredProperties = applySortFilter(userProperties, getComparator(order, orderBy), filterTitle); const isPropertyNotFound = filteredProperties?.length === 0; const handleClickOpen = () => { setEdit(false) setOpen(true) } /* const handleClickOpenEdit = () => { setEdit(true) setOpen(true) } */ return ( <Container sx={{ px: { xs: 0, sm: 0, md: 2 } }} > <Stack sx={{ backgroundColor: '#ededed', px: 1, py: 1.5 }} direction="row" alignItems="center" justifyContent="space-between" mt={5}> <Typography className='sub-header2'> Categories </Typography> <Button variant="contained" onClick={handleClickOpen}> New Category </Button> </Stack> <CategoryFormDialog open={open} setOpen={setOpen} edit={edit} refetch={refetch} /> { isLoading ? (<span>Loading data</span>) : userProperties?.length > 0 ? ( <Card elevation={0}> <CategoryListToolbar selectedIds={selected} numSelected={selected.length} filterName={filterTitle} onFilterName={handleFilterByTitle} refetch={refetch} setSelectedIds={setSelected} /> <TableContainer className='custom-scroll-bar'> <Table> <CategoryListHead order={order} orderBy={orderBy} headLabel={TABLE_HEAD} rowCount={userProperties.length} numSelected={selected.length} onRequestSort={handleRequestSort} onSelectAllClick={handleSelectAllClick} /> <TableBody> {filteredProperties.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => { const { id, title } = row; const isItemSelected = selected.indexOf(id) !== -1; return ( <TableRow hover key={id} tabIndex={-1} role="checkbox" selected={isItemSelected} aria-checked={isItemSelected} > <TableCell padding="checkbox"> <Checkbox checked={isItemSelected} onChange={(event) => handleClick(event, id)} /> </TableCell> <TableCell component="th" scope="row" padding="none"> <Stack direction="row" alignItems="center" spacing={2}> <Typography variant="subtitle2" noWrap> {title} </Typography> </Stack> </TableCell> <TableCell align="right">{20}</TableCell> <TableCell align="right"> <CategoryMoreMenu refetch={refetch} id={id} /> </TableCell> </TableRow> ); })} {emptyRows > 0 && ( <TableRow style={{ height: 53 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} </TableBody> {isPropertyNotFound && ( <TableBody> <TableRow> <TableCell align="center" colSpan={6} sx={{ py: 3 }}> <SearchNotFound searchQuery={filterTitle} /> </TableCell> </TableRow> </TableBody> )} </Table> </TableContainer> <TablePagination rowsPerPageOptions={[5, 10, 25]} component="div" count={userProperties.length} rowsPerPage={rowsPerPage} page={page} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} /> </Card> ) : ( <EmptyList title="No Categories" description="There are no categories. Add a property category" sx={{ height: '15rem !important', mt: 1 }} /> ) } </Container> ) } export default CreatePropertyCategory
"use client"; import { useState, useEffect, useContext } from "react"; import Tracklist from "@/components/TrackList"; import { type Song, type Album } from "@/types"; import { get } from "@/lib/requests"; import AuthContext from "@/context/AuthContext"; const Album = ({ params }: { params: { id: string } }) => { const [album, setAlbum] = useState<Album>(); const [songs, setSongs] = useState<Song[]>([]); const authContext = useContext(AuthContext); useEffect(() => { if (album?.id) { get( `/songsByAlbumId?albumId=${album.id}&userId=${authContext?.user?.id}`, ).then((res) => setSongs(res)); } }, [album?.id]); useEffect(() => { get(`/album?id=${params.id}`).then((res) => setAlbum(res)); }, [params.id]); console.log(album); return album ? ( <div className="pt-8 w-2/3 mx-auto"> <Tracklist data={songs} type="专辑" title={album.title} coverImage={album.coverImage} creator={{ name: album.artist.name, profileImage: album.artist.profileImage, id: album.artist.id, }} /> </div> ) : null; }; export default Album;
import './App.css' import Home from './components/Home' import SignUp from './components/SignUp'; import SignIn from './components/SignIn'; import Navbar from './components/Navbar'; import { useState, useEffect } from 'react'; import {Routes, Route } from "react-router-dom"; import {Toaster} from 'react-hot-toast' function App() { const [logged , setLogged] = useState(false) const loggedIn = () => { localStorage.getItem('token') ? setLogged(true) : setLogged(false) } useEffect(() => { loggedIn(); }, [logged]); return ( <div> <Toaster /> <Navbar logged={logged} loggedIn={loggedIn} /> <Routes> <Route path="/" element={<Home />} /> <Route path="/signup" element={<SignUp />} /> <Route path="/signin" element={<SignIn loggedIn={loggedIn} />} /> </Routes> </div> ); } export default App;
package com.snowflake.kafka.connector.internal; import com.snowflake.kafka.connector.internal.InternalUtils.IngestedFileStatus; import com.snowflake.kafka.connector.internal.telemetry.SnowflakeTelemetryService; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import net.snowflake.ingest.connection.HistoryResponse; /** Ingestion service manages snow pipe */ public interface SnowflakeIngestionService { /** * Set telemetry client * * @param telemetry telemetry client */ void setTelemetry(SnowflakeTelemetryService telemetry); /** * Ingest single file * * @param fileName file name */ void ingestFile(String fileName); /** * Ingest a list of files * * @param fileNames file name List */ void ingestFiles(List<String> fileNames); /** @return corresponding stage name */ String getStageName(); /** * retrieve status of given files from the ingest report * * @param files a list of file name * @return a map contains all file status */ Map<String, IngestedFileStatus> readIngestReport(List<String> files); /** * retrieve status of given files from load history in one hour time window * * @param files a list of file name * @param startTime the start time stamp of time window in ms * @return a map contains all file status */ Map<String, IngestedFileStatus> readOneHourHistory(List<String> files, long startTime); /** * Retrieve a collection of all ingested files with their status from load history. Fetching can * be further customized by: * <li>history marker - when content is null, entire available history is loaded and upon method * return, marker will be updated to the last available marker. Subsequent calls will fetch * only history entries created after the marker. * <li>limit the history depth by querying only the last N seconds since now. NOTE: this is not * absolute timestamp, so adjust for potential latency by adding some buffer * <li>filter the returned file history by supplying a fileFilter predicate. NOTE: this filtering * takes place at client side, so first - try limiting the result set size by providing * history marker / history depth in seconds Important thing - supplied storage container is * mutated by this call by: * <li>adding new file entry if none exist * <li>updating the state of the file, if file entry exists The method wil never delete any entry * from the map. * * @param storage - reference to the map where to store status updates for the tracked files * @param fileFilter - filter predicate - if provided will be used to filter only files matching * the criteria. * @param historyMarker - reference to the history marker - provide null as reference's value for * the first call, method will update the reference with most recent marker, so the next call * will resume with that specific marker * @param lastNSeconds - optionally narrow down history to just last N seconds. null for max * history range * @return number of loaded history entries */ int readIngestHistoryForward( Map<String, IngestedFileStatus> storage, Predicate<HistoryResponse.FileEntry> fileFilter, AtomicReference<String> historyMarker, Integer lastNSeconds); /** close ingest service */ void close(); }
# api_server.py from fastapi import FastAPI, HTTPException, Body, Response from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from pydantic import BaseModel import os import requests app = FastAPI() # Enable CORS origins = ["*"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Define constants NTFY_HOST = os.environ.get('NTFY_HOST', "https://ntfy.sh") TOPIC = os.environ.get('TOPIC', "mytopic") @app.get("/logo.png") def plugin_logo(): filename = 'logo.png' return FileResponse(filename, media_type='image/png') @app.get("/.well-known/ai-plugin.json") def plugin_manifest(): with open("./ai-plugin.json") as f: text = f.read() return Response(content=text, media_type="application/json") @app.get("/openapi.yaml") def openapi_spec(): with open("openapi.yaml") as f: text = f.read() return Response(content=text, media_type="text/yaml") from typing import Optional, List class Message(BaseModel): message: str tags: Optional[str] = None @app.post("/send") def send_notification(message: Message): # If tags are provided, send the message and tags as JSON if message.tags: data = { "message": message.message, "tags": message.tags.split(',') } response = requests.post(f"{NTFY_HOST}/{TOPIC}", json=data) # If no tags are provided, send only the message as data else: data = message.message response = requests.post(f"{NTFY_HOST}/{TOPIC}", data=data.encode('utf-8')) if response.status_code != 200: raise HTTPException(status_code=response.status_code, detail="Failed to send notification: " + response.text) return {'status': 'success', 'message': data} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=5003)
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { WelcomeComponent } from './welcome/welcome.component'; import { ErrorComponent } from './error/error.component'; import { SeccionUsuariosComponent } from './seccion-usuarios/seccion-usuarios.component'; import { MiPerfilComponent } from './mi-perfil/mi-perfil.component'; const routes: Routes = [ { path:"home", component:WelcomeComponent }, { path:'usuarios', component:SeccionUsuariosComponent }, { path:'perfil', component:MiPerfilComponent }, { path:"error", component:ErrorComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class HomeRoutingModule { }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="../css/bootstrap.min.css"/> <style> body { padding-top: 80px; } #search-btn { margin-top: 20px; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3 col-md-offset-3"> <form class="form-horizontal"> <input id="place-input" type="text" class="form-control" value="广州" placeholder="请输入地址"> <button type="button" id="search-btn" class="btn btn-success"> 查询 </button> </form> </div> <div class="col-md-6"> <div id="main" style="height:500px;"></div> </div> </div> </div> <script src="../jquery.min.js"></script> <script src="../echarts.min.js"></script> <script src="../china.js"></script> <script> // 画地图必须要经纬度数据 // 百度地图的开发者秘钥 var token = 'EljztUFFnLlRFS4wj3ngXZPwpp57TQUU'; var url = 'http://api.map.baidu.com/geocoder/v2/?output=json&ak=' + token + '&address='; var ePlaceInput = $('#place-input'); var eSearchBtn = $('#search-btn'); var myChart = echarts.init(document.getElementById('main')); var chartData = []; eSearchBtn.click(function () { //获取输入框的值 var place = ePlaceInput.val(); if (place) { $.getJSON(url + place + '&callback=?', function (res) { if (res.status === 0) { // drawMap(place, res.result.location); // console.log(place, res.result); loc = res.result.location; chartData.push({ name: name, value: [loc.lng, loc.lat] }); drawMap(place); } else { alert('百度没有找到地址信息') } }) } }); //画地图 function drawMap(name) { var option = { backgroundColor: '#404a59', title: { text: '2017要去的地方', left: 'center', textStyle: { color: '#fff' } }, tooltip: { trigger: 'item', feature: { saveImage: { show: true } } }, geo: { map: 'china', label: { emphasis: { show: false } }, roam: true, itemStyle: { normal: { areaColor: '#323c48', borderColor: '#111' }, emphasis: { areaColor: '#2a333d' } } }, series: [{ name: '地址', type: 'scatter', coordinateSystem: 'geo', data: chartData, symbolSize: function (val) { return 10; }, }] }; myChart.setOption(option) } </script> </body> </html>
// // messageController.h // BlackFireIM // // Created by benny wang on 2021/3/4. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class MSMessageController; @class MSMessageCell; @class MSMessageCellData; @class MSIMMessage; @protocol MSMessageControllerDelegate <NSObject> /** * 每条新消息在进入气泡展示区之前,都会通知给您 */ - (MSMessageCellData *)messageController:(MSMessageController *)controller prepareForMessage:(MSIMMessage *)data; /** * 显示消息数据委托 * 您可以通过该回调实现:根据传入的 data 初始化消息气泡并进行显示 */ - (Class)messageController:(MSMessageController *)controller onShowMessageData:(MSMessageCellData *)data; /** 收到信令消息 */ - (void)messageController:(MSMessageController *)controller onRecieveSignalMessage:(NSArray <MSIMMessage *>*)messages; /** * 控制器点击回调 * 您可以通过该回调实现:重置 InputControoler,收起键盘。 */ - (void)didTapInMessageController:(MSMessageController *)controller; /** * 点击消息头像委托 * 您可以通过该回调实现:跳转到对应用户的详细信息界面。 */ - (void)messageController:(MSMessageController *)controller onSelectMessageAvatar:(MSMessageCell *)cell; /** * 点击消息内容委托 */ - (void)messageController:(MSMessageController *)controller onSelectMessageContent:(MSMessageCell *)cell; /** * 显示长按菜单前的回调函数 * 您可以根据您的需求个性化实现该委托函数。 * * @param controller 委托者,消息控制器 * @param view 控制器所在view */ - (BOOL)messageController:(MSMessageController *)controller willShowMenuInCell:(UIView *)view; /** * 隐藏长按菜单后的回调函数 * 您可以根据您的需求个性化实现该委托函数。 * * @param controller 委托者,消息控制器 */ - (void)didHideMenuInMessageController:(MSMessageController *)controller; @end @interface MSMessageController : UITableViewController @property(nonatomic,weak) id<MSMessageControllerDelegate> delegate; @property(nonatomic,copy) NSString *partner_id; @property (nonatomic, strong,readonly) NSMutableArray<MSMessageCellData *> *uiMsgs; - (void)scrollToBottom:(BOOL)animate; @end NS_ASSUME_NONNULL_END
package match import ( "context" "github.com/josephnormandev/murder/client/drawer" "github.com/josephnormandev/murder/client/engine" "github.com/josephnormandev/murder/client/input" "github.com/josephnormandev/murder/client/worldin" "github.com/josephnormandev/murder/client/ws" "github.com/josephnormandev/murder/common/game" "github.com/josephnormandev/murder/common/types" "github.com/josephnormandev/murder/common/world" "golang.org/x/sync/errgroup" "syscall/js" ) type Manager struct { world.World game.Game Username types.UserID engine *engine.Manager packets *ws.Manager drawer *drawer.Drawer inputs *input.Manager worldIn *worldin.Manager wsClient *ws.Client RunContext context.Context RunGroup *errgroup.Group } func NewManager() *Manager { var m = &Manager{ Game: *game.NewGame(), } var spawner = world.Spawner(m) m.World = *world.NewWorld(&spawner) var gEngine = engine.NewManager() var gDrawer = drawer.NewDrawer() var packets = ws.NewManager() var inputs = input.NewManager() var worldOutput = worldin.Output(&m.World) var worldIn = worldin.NewManager(packets, &worldOutput) m.drawer = gDrawer m.engine = gEngine m.packets = packets m.inputs = inputs m.worldIn = worldIn return m } func (m *Manager) ExposeFunctions(doc js.Value, group *errgroup.Group, ctx context.Context) { doc.Set("connectToServer", js.FuncOf(func(this js.Value, values []js.Value) interface{} { var hostname = values[0].String() var port = values[1].Int() var username = types.UserID(values[2].String()) group.Go(func() error { return m.Connect(ctx, hostname, port, username) }) return nil })) doc.Set("setInputs", js.FuncOf(m.inputs.SetInputs)) doc.Set("drawUpdate", js.FuncOf(m.drawer.DrawUpdate)) doc.Set("centerUpdate", js.FuncOf(m.drawer.CenterUpdate)) doc.Set("engineUpdate", js.FuncOf(m.Update)) }
import React from "react"; import { useSearchParams } from "react-router-dom"; import Select from "./Select"; interface SortByProps { options: { value: string; label: string }[]; } const SortBy: React.FC<SortByProps> = ({ options }) => { const [searchParams, setSearchParams] = useSearchParams(); const sortBy = searchParams.get("sortBy") || ""; function handleChange(e: React.ChangeEvent<HTMLSelectElement>) { searchParams.set("sortBy", e.target.value); setSearchParams(searchParams); } return <Select options={options} type="white" value={sortBy} onChange={handleChange} />; }; export default SortBy;