text
stringlengths 184
4.48M
|
|---|
class Solution {
public:
vector<pair<int,int>>disp{{1,0},{0,1},{0,-1},{-1,0}};
bool isValid(int x,int y,int m,int n)
{
return x>=0 && x<m && y>=0 && y<n;
}
void bfs(int i,int j,vector<vector<char>>& grid,vector<vector<bool>>& vis,int m,int n)
{
vis[i][j]=true;
queue<pair<int,int>>qu;
qu.push({i,j});
pair<int,int>pr;
int x,y;
while(!qu.empty())
{
pr=qu.front();
for(auto dp:disp)
{
x=pr.first+dp.first;
y=pr.second+dp.second;
if(isValid(x,y,m,n) && grid[x][y]=='1' && !vis[x][y])
{ vis[x][y]=true;
qu.push({x,y});
}
}
qu.pop();
}
}
int numIslands(vector<vector<char>>& grid)
{
int ans=0;
vector<vector<bool>>vis(grid.size(),vector<bool>(grid[0].size(),false));
int m=grid.size();
int n=grid[0].size(),i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(grid[i][j]=='1' && !vis[i][j])
{
ans++;
bfs(i,j,grid,vis,m,n);
}
}
}
return ans;
}
};
|
import { useState, useEffect} from "react";
import CartProduct from "../Components/CartProduct";
import CartSummary from "../Components/CartSummary";
import { Loading } from "../Components/Loading";
import { getProducts } from "../Services/ProductServices";
import "../Static/Cart.css"
import CartContext from "../Context/CartContext"
export function Cart(){
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true)
useEffect(()=>{
async function request(){
try {
const res = await getProducts()
setProducts(res)
setLoading(false)
} catch (error) {
console.error(error)
}
}
request()
}, [])
return (
<Loading loading={loading}>
<CartContext.Consumer>
{
context =>
<main>
<header className="header-container">
<h5 className="section-title">Shopping Cart</h5>
<span className="count">{context.cart.length} items in the bag</span>
</header>
<section className="container">
<ul className="products">
{products.map(product => {return <CartProduct key={product.id}
data={{...product.data(), id: product.id}}/>})
.filter(product=>context.cart.includes(product.props.data.id))}
</ul>
</section>
{
(context.cart && <CartSummary cart={products
.filter(product=>context.cart.includes(product.id))}/>) ||
<CartSummary/>
}
</main>
}
</CartContext.Consumer>
</Loading>
)}
|
import React, { useState, useEffect } from "react";
import axios from 'axios';
import { FaSave } from 'react-icons/fa';
import Sidebar from "../../../components/sidebar/Sidebar";
import Topbar from "../../../components/topbar/Topbar";
import DialpadIcon from '@mui/icons-material/Dialpad';
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
import EventIcon from '@mui/icons-material/Event';
import DateRangeIcon from '@mui/icons-material/DateRange';
import CalendarViewWeekIcon from '@mui/icons-material/CalendarViewWeek';
import ReduceCapacityIcon from '@mui/icons-material/ReduceCapacity';
function Edit(props) {
const { id } = props;
const [isEditDone, setIsEditDone] = useState(false);
useEffect(() => {
axios.get(`http://localhost:8080/api/visit/read/${id}`)
.then(res => {
console.log(res);
setValues({
...values,
id: res.data[0].ID,
visitDate: res.data[0].VisitDate,
availableDate: res.data[0].AvailableDate,
day: res.data[0].Day,
reserveNumber: res.data[0].ReserveNumber,
prison: res.data[0].Prison
});
})
.catch(err => console.log(err));
}, [id]);
const [values, setValues] = useState({
id: '',
visitDate: '',
availableDate: '',
day: '',
reserveNumber: '',
prison: ''
});
const styles = {
borderRadius: "10px",
padding: "20px",
width: "100%",
height: "600px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
marginTop: '5px'
};
const handleUpdate = (event) => {
event.preventDefault();
axios.put(`http://localhost:8080/api/visit/edit/${id}`, {
ID: values.id,
VisitDate: values.visitDate,
AvailableDate: values.availableDate,
Day: values.day,
ReserveNumber: values.reserveNumber,
Prison: values.prison
})
.then(res => {
console.log(res);
setIsEditDone(true); // Set the flag to indicate edit is done
})
.catch(err => console.log(err));
};
return (
<>
<Topbar />
<div className="homeContainer">
<Sidebar />
<div className="vcontainer">
<form onSubmit={handleUpdate} style={styles}>
<h2 style={{ marginBottom: '0px' }}>Edit Information</h2>
<div className="filde" style={{ marginTop: '0px' }}>
<label className="fildelable" htmlFor="">ID</label>
<div className="input-field">
<i className="fas fa-envelope"> <DialpadIcon /></i>
<input
type="text"
placeholder="ID"
value={values.id}
onChange={(e) =>
setValues({ ...values, id: e.target.value })
}
/>
</div>
<label className="fildelable" htmlFor="">Visit Date</label>
<div className="input-field">
<i className="fas fa-envelope"><CalendarMonthIcon /></i>
<input
type="text"
placeholder="Visit Date"
value={values.visitDate}
onChange={(e) =>
setValues({ ...values, visitDate: e.target.value })
}
/>
</div>
</div>
<div className="filde">
<label className="fildelable" htmlFor="">Available Date</label>
<div className="input-field">
<i className="fas fa-user"><DateRangeIcon /></i>
<input
type="text"
placeholder="Available Date"
value={values.availableDate}
onChange={(e) =>
setValues({ ...values, availableDate: e.target.value })
}
/>
</div>
<label className="fildelable" htmlFor="">Day</label>
<div className="input-field">
<i className="fas fa-lock"><EventIcon /></i>
<input
type="text"
placeholder="Day"
value={values.day}
onChange={(e) =>
setValues({ ...values, day: e.target.value })
}
/>
</div>
</div>
<div className="filde">
<label className="fildelable" htmlFor="">Reserve Number</label>
<div className="input-field">
<i className="fas fa-envelope"><ReduceCapacityIcon /></i>
<input
type="text"
placeholder="Reserve Number"
value={values.reserveNumber}
onChange={(e) =>
setValues({ ...values, reserveNumber: e.target.value })
}
/>
</div>
<label className="fildelable" htmlFor="">Prison</label>
<div className="input-field">
<i className="fas fa-envelope"><CalendarViewWeekIcon /></i>
<input
type="text"
placeholder="Enter"
value={values.prison}
onChange={(e) =>
setValues({ ...values, prison: e.target.value })
}
/>
</div>
</div>
{isEditDone && <p >Edit is done!</p>}
<button className="btn solid">
<FaSave /> save
</button>
</form>
</div>
</div>
</>
);
}
export default Edit;
|
import "./ModalLogin.css";
import { RdButton, RdInput, RdModal } from "readmedev-ds";
import { useState } from "react";
import { useSaveToken } from "../../hooks/token";
import api from "../../lib/axios";
interface PropsModalLogin {
open: boolean;
onClose: () => void;
onLogin: () => void;
fallbackModalNewUser: () => void;
}
const ModalLogin = ({
open,
onClose,
onLogin,
fallbackModalNewUser,
}: PropsModalLogin) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const setToken = useSaveToken();
const onSubmitForm = (evento: React.FormEvent<HTMLFormElement>) => {
evento.preventDefault();
const usuario = {
email: email,
senha: password,
};
api()
.post("public/login", usuario)
.then((response) => {
setToken(response.data.access_token);
setEmail("");
setPassword("");
onLogin();
})
.catch((err) => {
if (err?.response?.data?.message) {
alert(err?.response?.data?.message);
} else {
alert("OPS! Alguma coisa deu errado!");
}
});
};
return (
<RdModal title="Login de Usuário" open={open} onClose={onClose}>
<div className="container-modal-login">
<form onSubmit={onSubmitForm}>
<RdInput
label="E-mail"
value={email}
onChange={setEmail}
shadowEffect={false}
/>
<RdInput
label="Senha"
type="password"
value={password}
onChange={setPassword}
shadowEffect={false}
/>
<footer>
<div>
<RdButton text="Entrar" onClick={() => {}} btnType="secondary" />
</div>
<div className="container-register">
<span>Ainda não tem um conta?</span>
<RdButton
text="Criar conta"
onClick={() => {
onClose();
fallbackModalNewUser();
}}
btnType="secondary"
/>
</div>
</footer>
</form>
</div>
</RdModal>
);
};
export default ModalLogin;
|
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:metadata_god/metadata_god.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:salomon_bottom_bar/salomon_bottom_bar.dart';
import 'package:tuneload/local_notifications.dart';
import 'package:tuneload/pages/aboutpage.dart';
import 'package:tuneload/pages/downloadspage.dart';
import 'package:tuneload/pages/favouritespage.dart';
import 'package:tuneload/pages/homepage.dart';
import 'package:tuneload/pages/topbar.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
MetadataGod.initialize();
await LocalNotification.init();
await Hive.initFlutter();
await Hive.openBox('favourites');
runApp(
const ProviderScope(
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
systemNavigationBarColor: Color.fromARGB(255, 35, 37, 46),
// systemNavigationBarDividerColor: Colors.white,
// statusBarColor: Colors.pink, // status bar color
// systemNavigationBarIconBrightness: Brightness.light,
));
return GetMaterialApp(
theme: ThemeData(
fontFamily: 'Circular',
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _currentIndex = 0;
@override
Widget build(BuildContext context) {
final GlobalKey<ScaffoldState> _key = GlobalKey(); // Create a key
return Scaffold(
key: _key,
body: Container(
width: double.infinity,
// height: MediaQuery.of(context).size.height,
decoration: const BoxDecoration(
gradient: LinearGradient(
stops: [0.6, 1],
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [Color(0xFF101115), Color(0xFF832F47)],
),
),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10),
child: Container(
color: Colors.black
.withOpacity(0.3), // You can adjust the opacity to your liking
child: SafeArea(
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
child: ListView(
children: [
// App bar
Topbar(_key),
if (_currentIndex == 0) const Homepage(),
if (_currentIndex == 1) const Favouritespage(),
if (_currentIndex == 2) const Downloadspage(),
if (_currentIndex == 3) const Aboutpage(),
],
),
),
),
),
),
),
// bottomNavigationBar: ,
bottomNavigationBar: SalomonBottomBar(
unselectedItemColor: Colors.white,
backgroundColor: const Color.fromARGB(255, 35, 37, 46),
currentIndex: _currentIndex,
onTap: (i) => setState(() => _currentIndex = i),
items: [
/// Home
SalomonBottomBarItem(
icon: const Icon(
PhosphorIconsBold.house,
// size: 18,
color: Colors.white,
),
title: const Text("Home"),
selectedColor: const Color.fromARGB(255, 224, 224, 224),
),
/// Search
SalomonBottomBarItem(
icon: const Icon(PhosphorIconsBold.heart),
title: const Text("Favourites"),
selectedColor: Colors.white,
),
/// Profile
SalomonBottomBarItem(
icon: const Icon(PhosphorIconsBold.downloadSimple),
title: const Text("Downloads"),
selectedColor: Colors.white,
),
/// Profile
SalomonBottomBarItem(
icon: const Icon(PhosphorIconsBold.user),
title: const Text("Profile"),
selectedColor: Colors.white,
),
],
),
drawer: Drawer(
shape: const Border(
right: BorderSide.none,
),
backgroundColor: Colors.black,
child: CustomScrollView(
shrinkWrap: true,
physics: const BouncingScrollPhysics(),
slivers: [
SliverAppBar(
backgroundColor: Colors.transparent,
automaticallyImplyLeading: false,
elevation: 0,
stretch: true,
expandedHeight: MediaQuery.of(context).size.height * 0.2,
flexibleSpace: FlexibleSpaceBar(
title: RichText(
text: const TextSpan(
text: "TuneLoad",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w900,
),
children: <TextSpan>[
TextSpan(
text: "1.0.0",
style: TextStyle(
fontSize: 7.0,
),
),
],
),
textAlign: TextAlign.end,
),
titlePadding: const EdgeInsets.only(bottom: 40.0),
centerTitle: true,
background: ShaderMask(
shaderCallback: (rect) {
return LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black.withOpacity(0.8),
Colors.black.withOpacity(0.1),
],
).createShader(
Rect.fromLTRB(0, 0, rect.width, rect.height),
);
},
blendMode: BlendMode.dstIn,
child: const Image(
fit: BoxFit.cover,
alignment: Alignment.topCenter,
image: AssetImage('assets/images/header.jpg'),
),
),
),
),
SliverList(
delegate: SliverChildListDelegate(
[
ListTile(
title: const Text(
"Home",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
),
),
contentPadding:
const EdgeInsets.symmetric(horizontal: 20.0),
leading: const Icon(
PhosphorIconsFill.house,
color: Colors.white,
),
selected: true,
onTap: () {},
),
ListTile(
title: const Text(
"About",
style: TextStyle(
color: Colors.white,
),
),
contentPadding:
const EdgeInsets.symmetric(horizontal: 20.0),
leading: const Icon(
PhosphorIconsFill.info,
color: Colors.white,
),
onTap: () {},
),
ListTile(
title: const Text(
"Developer website",
style: TextStyle(
color: Colors.white,
),
),
subtitle: const Text(
"https://anuragmagar.com.np",
style: TextStyle(
color: Colors.white60,
),
),
contentPadding:
const EdgeInsets.symmetric(horizontal: 20.0),
leading: const Icon(
PhosphorIconsFill.globe,
color: Colors.white,
),
onTap: () {},
),
],
),
),
const SliverFillRemaining(
hasScrollBody: false,
child: Column(
children: <Widget>[
Spacer(),
Padding(
padding: EdgeInsets.fromLTRB(5, 30, 5, 20),
child: Center(
child: Text(
"Made with ❤️ by Anurag Magar",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
color: Colors.white,
),
),
),
),
],
),
),
],
),
),
// ),
);
}
}
|
import React, { useState,useEffect } from "react";
import classes from './ProfileStatus.module.css'
const ProfileStatusWIthHooks=(props)=> {
let [editMode,setEditMode] = useState(false);
let [status,setStatus] = useState(props.status);
useEffect(()=>{
setStatus(props.status);
},[props.status])
const activateEditMode=()=>{
setEditMode(true);
}
const deactivateEditMode=()=>{
setEditMode(false);
props.updateStatus(status);
}
const onStatusChange=(e)=>{
setStatus(e.currentTarget.value);
}
return (
<div>
{!editMode &&
<div className={classes.status}>
<span onDoubleClick={activateEditMode}>{props.status || '-----'}</span>
</div>
}
{editMode &&
<div>
<input
onChange={onStatusChange}
autoFocus={true}
onBlur={deactivateEditMode}
value={status}
/>
</div>
}
</div>
)
}
export default ProfileStatusWIthHooks;
|
import { useEffect, useState } from 'react'
import { CloseOutline } from 'react-ionicons'
import styles from './styles/AddCategory.module.css'
import axios from 'axios';
import Loader from '../../UI/Loader/Loader'
import { useNavigate } from 'react-router-dom';
import CyrillicToTranslit from 'cyrillic-to-translit-js';
import SmallButton from '../../UI/Buttons/SmallButton/SmallButton';
import BigButton from '../../UI/Buttons/BigButton/BigButton';
import { useDispatch, useSelector } from 'react-redux';
import { addCategoryElement } from '../../reducers/componentTransferReducer';
interface Field {
id: number
}
interface FieldState extends Field {
error: boolean
}
interface FieldData {
name: string,
type: string
}
interface FormValues {
name: string,
desc: string,
field1: FieldData | any,
}
function AddCategory() {
const [loading, setLoading] = useState(false)
const [fields, setFields] = useState<FieldState[]>([{id: 1, error: true}])
const [isFormValid, setIsFormValid] = useState<boolean>(false)
const navigate = useNavigate()
const dispatch = useDispatch()
const linksList = useSelector((state: any) => state.transfer.menuElements).map((el:any) => el.link)
const fieldTypeOptions = [
{value: 'text', label: 'Текст'},
{value: 'image', label: 'Изображение'},
{value: 'select', label: 'Выбор'},
{value: 'category', label: 'Категория'},
]
const [formData, setFormData] = useState<FormValues>({
name: '',
desc: '',
field1: {name: '', type: 'text'},
})
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
let { name, value } = event.target
if (name === 'name' || name === 'desc') {
setFormData((prevData) => ({ ...prevData, [name]: value}))
} else {
// Добавляем field в объект, если поле не первое
const field = 'field' + name
let fieldId:string;
let fieldName:string;
if (field.indexOf('_type') !== -1) {
fieldId = name[0];
fieldName = `field${fieldId}`;
setFormData((prevData:any) => ({
...prevData,
[fieldName]: { ...prevData[fieldName], type: value },
}));
} else {
fieldId = field.substring(5);
fieldName = `field${fieldId}`;
setFormData((prevData:any) => ({
...prevData,
[fieldName]: { ...prevData[fieldName], name: value, type: 'text' },
}));
}
}
}
const handleFieldTypeChange = (
event: React.ChangeEvent<HTMLSelectElement>,
fieldId: number
) => {
const fieldName = `field${fieldId}`;
setFormData((prevData:any) => ({
...prevData,
[fieldName]: { ...prevData[fieldName], type: event.target.value },
}));
};
const handleAddField = (event:React.MouseEvent) => {
event.preventDefault()
setFields([...fields, {id: fields.length + 1, error: true}]);
}
const handleRemoveField = (id:number) => {
const newFields = fields.filter(field => field.id != id)
setFields(newFields)
}
const handleBlurField = (event: React.FocusEvent<HTMLInputElement>) => {
const id = Number(event.target.name)
const value = event.target.value
const fieldIndex = fields.findIndex(field => field.id === id)
if (value.trim() === '') {
setFields([
...fields.slice(0, fieldIndex),
{ ...fields[fieldIndex], error: true },
...fields.slice(fieldIndex + 1)
]);
} else {
setFields([
...fields.slice(0, fieldIndex),
{ ...fields[fieldIndex], error: false },
...fields.slice(fieldIndex + 1)
]);
}
}
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault()
console.log('linksList: ', linksList)
const apiuUrl = process.env.REACT_APP_API_URL
const apiPort = process.env.REACT_APP_API_PORT
const cyrillicToTranslit = new (CyrillicToTranslit as any)();
const transliterationName = cyrillicToTranslit.transform(formData.name, '_').toLowerCase()
console.log('transliteraionName', transliterationName)
if (linksList.includes(`/${transliterationName}`)) {
alert('Категория с таким именем уже существует!')
return
}
axios.post(
`${apiuUrl}:${apiPort}/addCollection`,
{...formData, transliterationName},
{headers: {'Content-Type': 'application/json'}}
)
.then((res) => {
// В случае успеха получаем созданную коллекцию, обновляем навбар
// и редиректим
console.log(res.data)
dispatch(addCategoryElement(res.data))
navigate(`/${res.data}`)
})
.catch((err) => {
// Если ошибка отрисовываем заглушку (500)
// или алертим что коллекция с таким именем уже существует
console.error(err)
})
setLoading(true)
// TODO: Тут должно быть значение равное name из объекта formData
}
const isButtonDisabled = fields.some(field => field.error !== false);
return (
<div className={styles.Container}>
{
loading ? <Loader /> :
<div className={styles.Forms}>
<h1 className={styles.PageTitle}>Добавить страницу</h1>
<form className={styles.PageForm} onSubmit={handleSubmit}>
<label>
<span className={styles.LabelTitle}>Название страницы:</span>
<input
className={styles.Input}
type="text"
name='name'
placeholder='Введите название...'
value={formData.name}
onChange={handleInputChange}
/>
<div style={{width: '160px'}}/>
<div style={{width: '24px'}}/>
</label>
<label>
<span className={styles.LabelTitle}>Описание страницы:</span>
<textarea
placeholder='Введите описание...'
name='desc'
value={formData.desc}
onChange={handleInputChange}
/>
<div style={{width: '160px'}}/>
<div style={{width: '24px'}}/>
</label>
<div className={styles.LabelColumns}>
<h2 className={styles.LabelColumnsTitle}>Поля таблицы</h2>
<SmallButton onClick={handleAddField} fields={fields}>Добавить поле</SmallButton>
</div>
<div className={styles.Fields}>
{fields.map((field, key) => (
<label key={field.id}>
<span className={styles.LabelTitle}>Имя колонки {field.id}:<i className={field.error ? styles.SpanError : ''}> *</i></span>
<input
type="text"
className={styles.Input}
placeholder='Введите имя колонки...'
name={field.id.toString()}
onBlur={handleBlurField}
value={formData[`field${(field.id).toString}` as keyof FormValues]}
onChange={handleInputChange}
/>
<select
name={field.id.toString() + '_type'}
placeholder='Введите имя колонки...'
defaultValue={'text'}
onChange={handleInputChange}
>
<option value="text">Текст</option>
<option value="image">Изображение (ссылка)</option>
<option value="select">Выбор</option>
<option value="category">Категория</option>
</select>
{
field.id != 1 ?
<div className={styles.CloseIcon} onClick={() => handleRemoveField(field.id)}>
<CloseOutline width="24px" height="24px" />
</div> : <div style={{width: '24px'}} />
}
</label>
))}
</div>
<BigButton disabled={isButtonDisabled} type="submit">Создать страницу</BigButton>
</form>
</div>
}
</div>
)
}
export default AddCategory
|
<template>
<div class="patient-list">
<el-breadcrumb class="info-detail-breadcrumb">
<el-breadcrumb-item
v-for="bread in breadcrumb"
:key="bread">
{{ bread }}
</el-breadcrumb-item>
</el-breadcrumb>
<sib-common-page
ref="pageComponent"
:permission-prefix="permissionPrefix"
:permissions="permissions"
:main-table-config="mainTableConfig"
:main-dialog-config="mainDialogConfig">
<template #operate="{ row }">
<el-button
type="text"
@click.native="handlerUpdateStatus(row)">
更新状态
</el-button>
</template>
<template #code="{ row }">
<el-button
type="text"
@click.native="handlerSkipDetail(row)">
{{ row.code }}
</el-button>
</template>
</sib-common-page>
<el-dialog
class="center"
width="500px"
title="更新状态"
append-to-body
lock-scroll
v-dialogDrag
v-if="updateStatusVisible"
:visible.sync="updateStatusVisible"
:close-on-click-modal="false"
:close-on-press-escape="false">
<sib-form
submit-text="确定"
cancel-text="取消"
:item-info="statusItemInfo"
:form="statusForm"
@submit="handlerSubmitStatus"
@reset="updateStatusVisible = false" />
</el-dialog>
</div>
</template>
<script>
export default {
name: 'PatientList',
data() {
return {
permissionPrefix: 'patient_list',
permissions: {
patient_list_view: {
id: 63,
name: '查看患者列表',
permission: 'patient_list_view',
url: `${window.testProtocol}/siit-profile-service/patientBaseInfo/findPage`,
status: 1,
parentId: 62,
requestConfig: {},
isMenu: 2,
children: null,
sort: 1,
createTime: '2022-05-16 14:25:54',
},
},
// 主列表查询配置
mainTableConfig: {
searchInfo: [
{
label: '患者编号',
code: 'code',
type: 'text',
maxlength: 50,
},
{
label: '患者姓名',
code: 'name',
type: 'text',
maxlength: 30,
},
{
label: '患者状态',
code: 'status',
type: 'select',
dataType: 'number',
options: [
{
key: 1,
value: '进行中',
},
{
key: 2,
value: '未开始',
},
{
key: 3,
value: '已结束',
},
],
},
{
label: '所属机构',
code: 'orgId',
type: 'cascader',
options: [],
props: {
emitPath: false,
checkStrictly: true,
label: 'name',
value: 'id',
},
dataType: 'number',
requestConfig: {
url: `${window.testProtocol}/siit-user-service/organization/currentOrgTree`,
method: 'get',
params: {},
callback: (res) => (res.data || {}).data || [],
},
},
],
// 列表的列配置项
tableColumn: [
{
label: '患者编号',
code: 'code',
type: 'slot',
},
{
label: '姓名',
code: 'name',
},
{
label: '性别',
code: 'gender',
formatter: ({ gender }) => ({ 1: '男', 2: '女' })[gender],
},
{
label: '年龄',
code: 'age',
},
{
label: '患者状态',
code: 'status',
formatter: ({ status }) => ({ 1: '进行中', 2: '未开始', 3: '已结束' })[status],
},
{
label: '所属机构',
code: 'orgName',
},
{
label: '创建人',
code: 'createUser',
},
{
label: '创建时间',
code: 'createTime',
// sortable: true,
width: 150,
},
{
label: '操作',
code: 'operate',
type: 'slot',
width: 150,
showOverflowTooltip: false,
},
],
buttonConfig: {
// 主列表头部的新增行按钮名称
add: {
name: '新增患者',
},
},
rowSize: 4,
},
// 主列表的新增、修改、复制弹窗表单配置
mainDialogConfig: {
getItemInfo: () => ([
{
label: '患者姓名',
code: 'name',
type: 'text',
maxlength: 30,
required: true,
},
{
label: '患者编号',
code: 'code',
type: 'text',
valueType: 'letter-number',
maxlength: 30,
required: true,
},
{
label: '性别',
code: 'gender',
type: 'select',
dataType: 'number',
required: true,
options: [
{
key: 1,
value: '男',
},
{
key: 2,
value: '女',
},
],
},
{
label: '年龄',
code: 'age',
type: 'text',
dataType: 'number',
valueType: 'number',
maxlength: 6,
min: 0,
required: true,
},
]),
},
updateStatusVisible: false,
statusItemInfo: [
{
label: '患者状态',
code: 'status',
type: 'select',
dataType: 'number',
options: [
{
key: 1,
value: '进行中',
},
{
key: 2,
value: '未开始',
},
{
key: 3,
value: '已结束',
},
],
},
],
statusForm: {},
detailData: {},
};
},
computed: {
// 面包屑配置
breadcrumb() {
return [(this.permissions[`${this.permissionPrefix}`] || {}).name || '患者列表'];
},
},
methods: {
handlerUpdateStatus(row) {
this.statusForm = JSON.parse(JSON.stringify(row || {}));
this.updateStatusVisible = true;
},
},
};
</script>
<style lang="scss">
</style>
|
import {APP_INITIALIZER, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {HttpClientModule} from "@angular/common/http";
import {FormsModule} from "@angular/forms";
import {EnvLoaderService} from "./env-loader.service";
import { ComponentComponent } from './component/component.component';
@NgModule({
declarations: [
AppComponent,
ComponentComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: (envLoaderService: EnvLoaderService) => () => envLoaderService.init(),
deps: [EnvLoaderService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
|
<template>
<div>
<h2>My Notes</h2>
<div class="notes">
<NotePad v-for="(note, index) in notes" :key="index" :text="note.note" />
</div>
<h2>Add a New Note</h2>
<form @submit.prevent="addNote">
<textarea v-model="newNote" placeholder="Note Content..."> </textarea>
<button>Add Note</button>
</form>
</div>
</template>
<script>
import { mapMutations } from "vuex";
import NotePad from "./NotePad.vue";
export default {
name: "DashBoard",
components: {
NotePad,
},
data() {
return {
notes: [],
newNote: "",
};
},
mounted() {
this.created();
},
methods: {
...mapMutations(["showLoader", "stopLoader", "showError"]),
addNote() {
let url = "/api/v1/notes/";
this.showLoader();
this.$axios
.post(url, { note: this.newNote })
.then((resp) => {
console.log("get notes data response =", resp);
if (resp.data) {
this.newNote = "";
this.notes.push(resp.data);
}
})
.catch((err) => {
console.log(err);
this.showError(true);
})
.finally(() => {
console.log("stop loading now ...");
this.stopLoader();
});
},
loadNotes() {
let url = "/api/v1/notes/";
this.showLoader();
this.$axios
.get(url)
.then((resp) => {
console.log("get notes data response =", resp);
if (resp.data) {
this.notes = resp.data;
}
})
.catch((err) => {
console.log(err);
this.showError(true);
})
.finally(() => {
console.log("stop loading now ...");
this.stopLoader();
});
},
created() {
this.loadNotes();
},
},
};
</script>
<style>
html,
body {
margin: 0;
padding: 0;
font-family: Avenir, Helvetica, Arial, sans-serif;
}
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: left;
color: #2c3e50;
width: 100vw;
min-width: 300px;
max-width: 1000px;
margin: 0 auto;
}
.notes {
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin: 20px;
justify-content: center;
}
h2 {
margin: 10px;
}
form {
margin: 20px;
display: flex;
flex-direction: column;
}
form textarea {
resize: none;
height: 220px;
margin: 0 10px;
background: beige;
outline: none !important;
border: none;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.4);
border-radius: 5px;
padding: 10px;
font-family: Avenir, Helvetica, Arial, sans-serif;
font-size: 1em;
}
form button {
background: lightgreen;
color: darkgreen;
padding: 10px;
border: none;
border-radius: 5px;
margin: 10px;
cursor: pointer;
outline: none !important;
}
form button:hover {
background-color: #a0fea0;
}
</style>
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract Blog {
string public name;
address public owner;
using Counters for Counters.Counter;
Counters.Counter private _postIds;
struct Post {
uint id;
string title;
string content;
bool published;
}
mapping(uint => Post) private idToPost;
mapping(string => Post) private hashToPost;
event PostCreated(uint id, string title, string hash);
event PostUpdated(uint id, string title, string hash, bool published);
// I think what's going on here is that you can add the optional variable "memory" to ensure that the data is not stored in either (1) storage which is expensive or (2) calldata. Not sure why it shouldn't just be stored as calldata.
constructor(string memory _name) {
console.log("Deploying blog with name:", _name);
name = _name;
owner = msg.sender;
}
// what does this actually do when the function updateName("testName") is called? specifically the variable declaration. Does this change anything in storage? Where? I don't get it
function updateName(string memory _name) public {
name = _name;
}
// Ah - name is not a property of a post. It's more like metadata and is associated with the contract itself. This Blog contract has a 'name' property, think of it like the name of the blog itself. Since you are changing the string defined in 8, you are changing the name
// ditto here
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
// Neat, I didn't know about modifiers before. Handy.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// weird that you don't use the ID but use a hash instead to search your posts...
// And why do we specify that the Post object we return has to be in memory? W e i r d
function fetchPost(string memory hash) public view returns(Post memory) {
return hashToPost[hash];
}
function createPost(string memory title, string memory hash) public onlyOwner {
_postIds.increment();
uint postId = _postIds.current();
// first, since you created a struct earlier, you can just create an object and ensure it's stored in storage (as opposed to memory or calldata) by writing Post storage <variableName> = <theThingYou'reCreating>
// here we define <theThingYou'reCreating> by using the mapping idToPost and feeding it the new id
// really don't understand this. Which bit is actually doing the creating? shouldn't it be << idToPost[postId] = Post storage post >> ? Since we know what is on the right side but not what is on the left?
// ah - from the docs: Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros: a type’s default value.
// so basically idToPost[withLiterallyAnythingInHere] returns a post, and that post will almost always have null values for every property
// Post storage post = somePostObject will take that object, whack it in storage, and assign it to the variable name "post". Since solidity is statically typed, we can't just declare a variable without also declaring its type, so we declare it - as Post. In the same way that you'd write "string public name"
Post storage post = idToPost[postId];
// this is the standard way to create objects in Solidity (see https://docs.soliditylang.org/en/v0.8.13/types.html#structs)
post.id = postId;
post.title = title;
post.published = true;
post.content = hash;
// note there is no sense of pressing the 'save' button - when you perform operations on post, it's saved in storage
// here we update the hashToPost mapping too, since it currently points at a post with null values
hashToPost[hash] = post;
emit PostCreated(postId, title, hash);
}
// I don't understand why some of these variables are declared with memory and some not
function updatePost(uint postId, string memory title, string memory hash, bool published) public onlyOwner {
// I think another reason specifying storage here may be important is so that when you do make modifications to post, you're not making modiciations to a separate carbon copy object in memory called post but rather the original post itself in storage
Post storage post = idToPost[postId];
post.title = title;
post.content = hash;
post.published = published;
// what is super weird is that we have to update the mappings as well as the storage itself...
idToPost[postId] = post;
hashToPost[hash] = post;
emit PostUpdated(postId, title, hash, published);
}
// I think the syntax here is that when you want to return an array of a type rather than a single object of that type, you just write Struct [] and if you want to specify that it comes from (or is stored in?) memory rather than e.g. storage you write memory afterwards?
function fetchPosts() public view returns (Post [] memory) {
uint itemCount = _postIds.current();
// I think new Post[](num) just creates an array of Post objects with length num, and Post[] memory posts puts that thing in memory and lets you play with it with the variable 'posts'
Post[] memory posts = new Post[](itemCount);
for (uint i = 0; i < itemCount; i++) {
uint currentId = i + 1;
Post storage currentItem = idToPost[currentId];
posts[i] = currentItem;
}
return posts;
}
}
|
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/02/FullAdder.hdl
/**
* Computes the sum of three bits.
*/
// a b c sum carry
// 0 0 0 0 0
// 0 0 1 1 0
// 0 1 0 1 0
// 0 1 1 0 1
// 1 0 0 1 0
// 1 0 1 0 1
// 1 1 0 0 1
// 1 1 1 1 1
CHIP FullAdder {
IN a, b, c; // 1-bit inputs
OUT sum, // Right bit of a + b + c
carry; // Left bit of a + b + c
PARTS:
HalfAdder(a=a, b=b, sum=sum1, carry=carry1);
HalfAdder(a=sum1, b=c, sum=sum, carry=carry2);
Or(a=carry1, b=carry2, out=carry);
}
|
import os
import pandas as pd
import requests
from tqdm import tqdm
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import networkx
import obonet
bigP = pd.read_csv("data/datasets/huge_proteins_dataset.tsv",sep='\t', usecols=['prot_id','gos_id','superkingdom']).dropna(subset='gos_id')
bigP['gos_id'] = bigP['gos_id'].apply(lambda x: x.split('; '))
def correct_gos(go_term):
try:
id_to_name[go_term]
except:
#print(f"Failed for {go_term}")
requestURL = "https://www.ebi.ac.uk/QuickGO/services/ontology/go/terms/"
tool = "/secondaryids"
r = requests.get(requestURL + go_term + tool, headers={ "Accept" : "application/json"})
if not r.ok:
print(r.headers)
response = r.json()['results'][0]
return response['id']
else:
return go_term
def check_obsolete(maindf):
m_df = maindf.copy()
for go in tqdm(m_df.columns, desc='obsolete:'):
requestURL = "https://www.ebi.ac.uk/QuickGO/services/ontology/go/terms/"
tool = "/secondaryids"
r = requests.get(requestURL + go + tool, headers={ "Accept" : "application/json"})
if not r.ok:
print(r.headers)
response = r.json()['results'][0]
if response['isObsolete'] == True:
m_df = m_df.drop(go, axis=1)
return m_df
def get_sublevels(df, gotype, graph):
#get all the level 2 go terms
node = name_to_id[mapping_names[gotype]]
level = [parent for parent, child, key in graph.in_edges(node, keys=True)]
specify = mapping_specificity[gotype]
level_updated = []
for fun in level:
if fun in specify:
sub_level =[parent for parent, child, key in graph.in_edges(fun, keys=True)]
level_updated = level_updated + sub_level
continue
level_updated.append(fun)
#for every protein, check associated go terms
function_groups = {}
for row in tqdm(df.iterrows(), total=len(df), desc='associated'):
prot_id = row[0]
prot_gos = [go for go, v in row[1].items() if v == 1.0]
function_groups[prot_id]=[]
for go in prot_gos:
if go in specify:
#print(id_to_name[go])
function_groups[prot_id].append(id_to_name[go])
else:
try:
parents = [superterm for superterm in networkx.descendants(graph, go)]
except Exception as e:
continue
else:
for parent in parents:
if parent in level_updated and parent not in function_groups[prot_id]:
function_groups[prot_id].append(id_to_name[parent])
return function_groups
def find_uniques(df) -> pd.DataFrame:
df = df.groupby(by=['function']).count().sort_values(by='prot_id', ascending=False)
df_uniques = df.reset_index()
unique_gos_dict = {}
for i in tqdm(df_uniques.iterrows(), desc='uniques'):
s = i[1][0]
function_list = s.strip('[').strip(']').replace("'","").split(", ")
counts = int(i[1][1])
## Get all the unique GOs
for z in function_list:
if z in unique_gos_dict:
unique_gos_dict[z][0] += counts
else:
unique_gos_dict[z] = [counts]
return pd.DataFrame.from_dict(unique_gos_dict).T.sort_values(0,ascending=False)
def plot_together(df,gotype):
to_use_df = df.copy()
to_use_df = find_uniques(to_use_df)
data = to_use_df[to_use_df.index != ''].sort_values(0,ascending=False).head(15).sort_values(0,ascending=True).rename(columns={0:'counts'})
fig = px.bar(
data,
x='counts',
# facet_col='superkingdom',
orientation='h',
labels={
'counts':"Counts",
"index":f"Go terms - {gotype[0].upper() + gotype[2].upper()}"
},
height=500,
width=1000
)
fig.update_layout(
template='plotly_white',
)
fig.update_traces(marker_color='#f9c8a0',marker_line_color='#A4968A',
marker_line_width=1.5)
fig.write_html(f"data/results/go_distribution/{gotype}_groups_unique.html")
def plot(df, gotype):
print(df)
fig = make_subplots(
rows=3, subplot_titles=tuple(df.superkingdom.unique()))
for i, sk in enumerate(df.superkingdom.unique()):
to_use_df = df[df.superkingdom == sk]
to_use_df = find_uniques(to_use_df)
data = to_use_df[to_use_df.index != ''].sort_values(0,ascending=False).head(15).sort_values(0,ascending=True).rename(columns={0:'counts'})
print(data)
fig.add_trace(go.Bar(
x=data.counts,
y=data.index,
orientation='h',
), row=i+1, col=1)
fig.update_layout(template='plotly_white', title=f"Go terms - {gotype[0].upper() + gotype[2].upper()}",showlegend=False)
fig.update_traces(marker_color='#f9c8a0',marker_line_color='#A4968A',
marker_line_width=1.5)
fig.write_html(f"data/results/go_distribution/{gotype}_groups_unique_by_sk.html")
def generate_go_terms_dataset(graph):
heads = {
'GO:0003674':'m_function',
'GO:0008150':'b_process',
'GO:0005575':'c_component'
}
df = pd.DataFrame(columns=heads.values(), index=bigP.prot_id)
for idx, row in tqdm(bigP.set_index('prot_id').iterrows(), desc='building dataset', total=len(bigP)):
for go in row.gos_id:
try:
descendts = networkx.descendants(graph, go)
except:
continue
gotype = [heads[x] for x in descendts if x in heads.keys()][0]
if isinstance(df.loc[idx, gotype], list):
df.loc[idx, gotype].append(go)
else:
df.loc[idx, gotype] = go
df.to_csv(f"data/outputs/go_terms/go_terms_dataset.tsv", sep='\t', index=False)
def main():
url = 'http://purl.obolibrary.org/obo/go.obo'
graph = obonet.read_obo(url)
global id_to_name
global name_to_id
id_to_name = {id_: data.get('name') for id_, data in graph.nodes(data=True)}
name_to_id = {data['name']: id_ for id_, data in graph.nodes(data=True) if 'name' in data}
global mapping_specificity
mapping_specificity = {
'b_process':[
name_to_id['regulation of biological process'],
name_to_id['multicellular organismal process'],
name_to_id['developmental process'],
name_to_id['biological regulation'],
name_to_id['metabolic process'],
name_to_id['cellular process'],
name_to_id['cellular component organization or biogenesis']
],
'm_function':[name_to_id['binding'], name_to_id['catalytic activity']],
'c_component':[name_to_id['cellular anatomical entity'],name_to_id['protein-containing complex'],name_to_id['intracellular anatomical structure']]
}
global mapping_names
mapping_names = {
'b_process':'biological_process',
'm_function':'molecular_function',
'c_component':'cellular_component'
}
for gotype in ['b_process','m_function','c_component']:
if os.path.exists(f"data/outputs/go_terms/function_groups_{gotype}.pkl"):
prot_func_df = pd.read_pickle(f"data/outputs/go_terms/function_groups_{gotype}.pkl")
else:
print(gotype)
if not os.path.exists(f"data/outputs/go_terms/go_terms_dataset.tsv"):
generate_go_terms_dataset(graph)
functiondf = (
pd.read_csv(f"data/outputs/go_terms/go_terms_dataset.tsv", sep='\t', usecols=['prot_id',gotype])
)
functiondf = pd.crosstab(functiondf['prot_id'],functiondf[gotype])
else:
functiondf = (
pd.read_csv(f"data/outputs/go_terms/go_terms_dataset.tsv", sep='\t', usecols=['prot_id',gotype])
)
functiondf = pd.crosstab(functiondf['prot_id'],functiondf[gotype])
functiondf.columns = [correct_gos(x) for x in tqdm(functiondf.columns, desc='correcting')]
functiondf = check_obsolete(functiondf)
function_groups = get_sublevels(functiondf,gotype, graph)
prot_func_df = bigP.merge(pd.Series(function_groups, name='function'), left_on='prot_id', right_index=True).astype('str')
prot_func_df.to_pickle(f"data/outputs/go_terms/function_groups_{gotype}.pkl")
plot(prot_func_df, gotype)
plot_together(prot_func_df, gotype)
if __name__ == "__main__":
main()
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wicketstuff.jmx.markup.html.tree.detail;
import javax.management.MBeanOperationInfo;
import javax.management.ObjectName;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.wicketstuff.jmx.markup.html.tree.DetailPanel;
import org.wicketstuff.jmx.util.JmxMBeanWrapper;
/**
* This panel renders all available operations ({@link MBeanOperationInfo}) of
* an {@link ObjectName} instance (wrapped by {@link JmxMBeanWrapper}).
*
* @author Gerolf Seitz
*
*/
public class OperationsOverviewPanel extends DetailPanel
{
private static final long serialVersionUID = 1L;
public OperationsOverviewPanel(String id, JmxMBeanWrapper bean)
{
super(id);
setOutputMarkupId(true);
RepeatingView view = new RepeatingView("operations");
for (int i = 0; i < bean.getOperations().length; i++)
{
Panel panel = new OperationPanel(view.newChildId(), bean, bean.getOperations()[i]);
if (i == bean.getOperations().length - 1)
{
panel.add(new AttributeModifier("class", true, new Model("operation-last")));
}
view.add(panel);
}
add(view);
}
}
|
export type Json =
| string
| number
| boolean
| null
| { [key: string]: Json | undefined }
| Json[]
export interface Database {
public: {
Tables: {
directories: {
Row: {
id: number
name: string
parentId: number | null
userId: string | null
}
Insert: {
id?: number
name: string
parentId?: number | null
userId?: string | null
}
Update: {
id?: number
name?: string
parentId?: number | null
userId?: string | null
}
Relationships: [
{
foreignKeyName: 'directories_parentId_fkey'
columns: ['parentId']
referencedRelation: 'directories'
referencedColumns: ['id']
},
{
foreignKeyName: 'directories_userId_fkey'
columns: ['userId']
referencedRelation: 'users'
referencedColumns: ['id']
}
]
}
group: {
Row: {
createdAt: string | null
description: string
id: string
isPrivate: boolean
name: string
owner: string
}
Insert: {
createdAt?: string | null
description: string
id?: string
isPrivate?: boolean
name: string
owner: string
}
Update: {
createdAt?: string | null
description?: string
id?: string
isPrivate?: boolean
name?: string
owner?: string
}
Relationships: [
{
foreignKeyName: 'group_owner_fkey'
columns: ['owner']
referencedRelation: 'profiles'
referencedColumns: ['id']
}
]
}
messages: {
Row: {
content: string
created_at: string
id: string
read: boolean
receiver: string
sender: string
}
Insert: {
content: string
created_at?: string
id?: string
read?: boolean
receiver: string
sender: string
}
Update: {
content?: string
created_at?: string
id?: string
read?: boolean
receiver?: string
sender?: string
}
Relationships: [
{
foreignKeyName: 'messages_receiver_fkey'
columns: ['receiver']
referencedRelation: 'profiles'
referencedColumns: ['id']
},
{
foreignKeyName: 'messages_sender_fkey'
columns: ['sender']
referencedRelation: 'profiles'
referencedColumns: ['id']
}
]
}
notes: {
Row: {
content: string
folderId: number | null
id: string
title: string
updatedAt: number
userId: string
}
Insert: {
content: string
folderId?: number | null
id?: string
title: string
updatedAt: number
userId: string
}
Update: {
content?: string
folderId?: number | null
id?: string
title?: string
updatedAt?: number
userId?: string
}
Relationships: [
{
foreignKeyName: 'notes_folderId_fkey'
columns: ['folderId']
referencedRelation: 'directories'
referencedColumns: ['id']
},
{
foreignKeyName: 'notes_userId_fkey'
columns: ['userId']
referencedRelation: 'profiles'
referencedColumns: ['id']
}
]
}
posts: {
Row: {
content: string
createdAt: string
groupId: string
id: string
parentId: string | null
title: string | null
userId: string
}
Insert: {
content: string
createdAt?: string
groupId: string
id?: string
parentId?: string | null
title?: string | null
userId: string
}
Update: {
content?: string
createdAt?: string
groupId?: string
id?: string
parentId?: string | null
title?: string | null
userId?: string
}
Relationships: [
{
foreignKeyName: 'posts_groupId_fkey'
columns: ['groupId']
referencedRelation: 'group'
referencedColumns: ['id']
},
{
foreignKeyName: 'posts_parentId_fkey'
columns: ['parentId']
referencedRelation: 'posts'
referencedColumns: ['id']
},
{
foreignKeyName: 'posts_userId_fkey'
columns: ['userId']
referencedRelation: 'profiles'
referencedColumns: ['id']
}
]
}
profiles: {
Row: {
avatar: string
firstName: string | null
id: string
name: string | null
updatedAt: string
username: string
}
Insert: {
avatar?: string
firstName?: string | null
id: string
name?: string | null
updatedAt: string
username: string
}
Update: {
avatar?: string
firstName?: string | null
id?: string
name?: string | null
updatedAt?: string
username?: string
}
Relationships: [
{
foreignKeyName: 'profiles_id_fkey'
columns: ['id']
referencedRelation: 'users'
referencedColumns: ['id']
}
]
}
subscription: {
Row: {
groupId: string
id: number
userId: string
}
Insert: {
groupId: string
id?: number
userId: string
}
Update: {
groupId?: string
id?: number
userId?: string
}
Relationships: [
{
foreignKeyName: 'subscription_groupId_fkey'
columns: ['groupId']
referencedRelation: 'group'
referencedColumns: ['id']
},
{
foreignKeyName: 'subscription_userId_fkey'
columns: ['userId']
referencedRelation: 'profiles'
referencedColumns: ['id']
}
]
}
tasks: {
Row: {
complete: boolean
completedBy: string | null
createdBy: string
deadline: string
id: number
name: string
toDoListId: number
}
Insert: {
complete?: boolean
completedBy?: string | null
createdBy: string
deadline: string
id?: number
name: string
toDoListId: number
}
Update: {
complete?: boolean
completedBy?: string | null
createdBy?: string
deadline?: string
id?: number
name?: string
toDoListId?: number
}
Relationships: [
{
foreignKeyName: 'tasks_completedBy_fkey'
columns: ['completedBy']
referencedRelation: 'profiles'
referencedColumns: ['id']
},
{
foreignKeyName: 'tasks_createdBy_fkey'
columns: ['createdBy']
referencedRelation: 'profiles'
referencedColumns: ['id']
},
{
foreignKeyName: 'tasks_toDoListId_fkey'
columns: ['toDoListId']
referencedRelation: 'toDoList'
referencedColumns: ['id']
}
]
}
test: {
Row: {
id: number
text: string | null
}
Insert: {
id?: number
text?: string | null
}
Update: {
id?: number
text?: string | null
}
Relationships: []
}
toDoList: {
Row: {
id: number
isPrivate: boolean
name: string
ownerId: string
}
Insert: {
id?: number
isPrivate?: boolean
name: string
ownerId: string
}
Update: {
id?: number
isPrivate?: boolean
name?: string
ownerId?: string
}
Relationships: [
{
foreignKeyName: 'toDoList_ownerId_fkey'
columns: ['ownerId']
referencedRelation: 'profiles'
referencedColumns: ['id']
}
]
}
userToDoList: {
Row: {
toDoListId: number
userId: string
}
Insert: {
toDoListId: number
userId: string
}
Update: {
toDoListId?: number
userId?: string
}
Relationships: [
{
foreignKeyName: 'userToDoList_toDoListId_fkey'
columns: ['toDoListId']
referencedRelation: 'toDoList'
referencedColumns: ['id']
},
{
foreignKeyName: 'userToDoList_userId_fkey'
columns: ['userId']
referencedRelation: 'profiles'
referencedColumns: ['id']
}
]
}
}
Views: {
[_ in never]: never
}
Functions: {
[_ in never]: never
}
Enums: {
[_ in never]: never
}
CompositeTypes: {
[_ in never]: never
}
}
}
|
from math import atan2, cos, hypot, pi, sin, sqrt
import time
from geodesy.utm import UTMPoint, fromLatLong
import numpy as np
from sklearn.neighbors import KDTree
from tf2_ros import TransformBroadcaster
from transforms3d.euler import euler2quat, quat2euler
import message_filters
import rclpy
from rclpy.node import Node
from rclpy.publisher import Publisher
from driverless_msgs.msg import ConeDetectionStamped, ConeWithCovariance, Reset, TrackDetectionStamped
from geometry_msgs.msg import Point, PoseStamped, PoseWithCovarianceStamped, Quaternion, TransformStamped
from sbg_driver.msg import SbgEkfEuler, SbgEkfNav, SbgGpsPos
from driverless_common.common import QOS_ALL, QOS_LATEST
from py_slam.cone_props import ConeProps
from typing import Optional, Tuple
R = np.diag([0.01, 0.1]) ** 2 # motion model
Q_LIDAR = np.diag([0.5, 0.5]) ** 2
RADIUS = 1.5 # nn kdtree nearch
LEAF_SIZE = 50 # nodes per tree before it starts brute forcing?
FRAME_COUNT = 15 # minimum frames before confirming cones
FRAME_REM_COUNT = 30 # minimum frames that cones have to be seen in to not be removed
X_RANGE = 15 # max x distance from car
Y_RANGE = 10 # max y distance from car
def wrap_to_pi(angle: float) -> float: # in rads
return (angle + pi) % (2 * pi) - pi
# SLAM with the SBG GPS and internal orientation
class SBGSlam(Node):
initial_pos: Optional[Tuple[float, float]] = None
prev_pos: Optional[Tuple[float, float]] = None
initial_ang: Optional[float] = None
state = np.array([0.0, 0.0, 0.0]) # initial pose
sigma = np.diag([0.0, 0.0, 0.0])
properties = np.array([])
def __init__(self):
super().__init__("sbg_slam_node")
# sync subscribers
# pos_sub = message_filters.Subscriber(self, SbgEkfNav, "/sbg/ekf_nav")
pos_sub = message_filters.Subscriber(self, SbgGpsPos, "/sbg/gps_pos") # use gps rather than filtered
ang_sub = message_filters.Subscriber(self, SbgEkfEuler, "/sbg/ekf_euler")
ins_synchronizer = message_filters.ApproximateTimeSynchronizer(fs=[pos_sub, ang_sub], queue_size=20, slop=0.2)
ins_synchronizer.registerCallback(self.ins_callback)
self.create_subscription(ConeDetectionStamped, "/lidar/cone_detection", self.callback, QOS_ALL)
self.create_subscription(ConeDetectionStamped, "/vision/cone_detection", self.callback, QOS_ALL)
self.create_subscription(Reset, "/system/reset", self.reset_callback, QOS_LATEST)
# slam publisher
self.slam_publisher: Publisher = self.create_publisher(ConeDetectionStamped, "/slam/global_map", 1)
self.local_publisher: Publisher = self.create_publisher(ConeDetectionStamped, "/slam/local_map", 1)
self.pose_publisher: Publisher = self.create_publisher(PoseWithCovarianceStamped, "/slam/car_pose", 1)
# Initialize the transform broadcaster
self.broadcaster = TransformBroadcaster(self)
self.get_logger().info("---SBG SLAM node initialised---")
def ins_callback(self, gps_msg: SbgGpsPos, ekf_euler_msg: SbgEkfEuler):
if not self.initial_pos and not self.initial_ang:
coords: UTMPoint = fromLatLong(gps_msg.latitude, gps_msg.longitude, gps_msg.altitude)
self.prev_pos = (coords.easting, coords.northing)
self.initial_ang = ekf_euler_msg.angle.z # - pi
return
# https://answers.ros.org/question/50763/need-help-converting-lat-long-coordinates-into-meters/
coords: UTMPoint = fromLatLong(gps_msg.latitude, gps_msg.longitude, gps_msg.altitude)
# get relative to initial position and last state prediction
d_e = coords.easting - self.prev_pos[0]
d_n = coords.northing - self.prev_pos[1]
self.prev_pos = (coords.easting, coords.northing)
# get magnitude by prev angle
d_mag = hypot(d_e, d_n)
d_x = d_mag * cos(self.state[2])
d_y = d_mag * sin(self.state[2])
# current angle
imu_ang = ekf_euler_msg.angle.z
# get relative to initial angle and last state prediction
d_th = wrap_to_pi(imu_ang - self.initial_ang - self.state[2])
self.predict(d_x, d_y, d_th)
self.publish_localisation(gps_msg.header.stamp)
def reset_callback(self, msg):
self.get_logger().info("Resetting Map")
self.initial_pos = None
self.state = np.array([0.0, 0.0, 0.0])
self.sigma = np.diag([0.0, 0.0, 0.0])
self.properties = np.array([])
self.initial_pos = None
self.initial_ang = None
def callback(self, msg: ConeDetectionStamped):
self.get_logger().debug("Received detection")
start: float = time.perf_counter()
# process detected cones
track_as_2d = np.array([])
for detection in msg.cones:
detection = ConeProps(detection, msg.header.frame_id) # detection with properties
# transform detection to map
rotation_mat = np.array(
[
[cos(self.state[2]), -sin(self.state[2])],
[sin(self.state[2]), cos(self.state[2])],
]
)
map_coords = rotation_mat @ np.array([detection.local_x, detection.local_y]).T + self.state[:2]
track_as_2d = np.array([])
for i in range(3, len(self.state), 2):
track_as_2d = np.append(track_as_2d, [self.state[i], self.state[i + 1]])
if len(track_as_2d) != 0:
neighbourhood = KDTree(track_as_2d.reshape(-1, 2), leaf_size=LEAF_SIZE)
check: np.ndarray = map_coords.reshape(1, -1) # turn into a 2D row array
ind: np.ndarray = neighbourhood.query_radius(check, r=RADIUS) # check neighbours in radius
close: np.ndarray = ind[0] # index from the single colour list
if close.size != 0:
# update step
prev_mu = self.state[0:3]
prev_sigma = self.sigma[0:3, 0:3]
updated_detection: ConeProps = self.properties[close[0]]
if detection.sensor == "lidar":
self.update(close[0], detection, Q_LIDAR)
updated_detection.sensor = "lidar"
# reset car state if this isn't a confirmed cone
# only update states on confirmed cones not noise
if not updated_detection.confirmed:
self.state[0:3] = prev_mu
self.sigma[0:3, 0:3] = prev_sigma
idx = close[0] * 2 + 3
state = self.state[idx : idx + 2]
cov = self.sigma[idx : idx + 2, idx : idx + 2]
updated_detection.update(state, cov, detection.colour, FRAME_COUNT)
detection = updated_detection
if not detection.tracked and msg.header.frame_id == "velodyne":
detection.set_world_coords(map_coords)
self.properties = np.append(self.properties, detection)
# initialise new landmark
self.init_landmark(detection, Q_LIDAR)
# remove noise
self.flush_map(track_as_2d.reshape(-1, 2))
# publish track msg
track_msg = ConeDetectionStamped()
track_msg.header.stamp = msg.header.stamp
track_msg.header.frame_id = "track"
for detection in self.properties:
if detection.confirmed:
track_msg.cones.append(detection.cone_as_msg)
track_msg.cones_with_cov.append(
ConeWithCovariance(cone=detection.cone_as_msg, covariance=detection.cov_as_msg)
)
self.slam_publisher.publish(track_msg)
# publish local map msg
local_map_msg = ConeDetectionStamped()
local_map_msg.header.stamp = msg.header.stamp
local_map_msg.header.frame_id = "base_footprint"
for detection in self.get_local_map(track_as_2d.reshape(-1, 2)):
if detection.confirmed:
local_map_msg.cones.append(detection.local_cone_as_msg)
local_map_msg.cones_with_cov.append(
ConeWithCovariance(cone=detection.local_cone_as_msg, covariance=detection.cov_as_msg)
)
self.local_publisher.publish(local_map_msg)
# publish localisation msg
self.publish_localisation(msg.header.stamp)
self.get_logger().debug(f"Wait time: {str(time.perf_counter()-start)}") # log time
def publish_localisation(self, timestamp):
# publish pose msg
pose_msg = PoseWithCovarianceStamped()
pose_msg.header.stamp = timestamp
pose_msg.header.frame_id = "track"
pose_msg.pose.pose.position = Point(x=self.state[0], y=self.state[1], z=0.2)
quaternion = euler2quat(0.0, 0.0, self.state[2])
pose_msg.pose.pose.orientation = Quaternion(x=quaternion[1], y=quaternion[2], z=quaternion[3], w=quaternion[0])
# covariance as a 6x6 matrix
cov = np.zeros((6, 6))
cov[0:2, 0:2] = self.sigma[0:2, 0:2]
cov[0:2, 5] = self.sigma[0:2, 2]
cov[5, 0:2] = self.sigma[2, 0:2]
cov[5, 5] = self.sigma[2, 2]
pose_msg.pose.covariance = cov.flatten().tolist()
self.pose_publisher.publish(pose_msg)
# send transformation
t = TransformStamped()
# read message content and assign it to corresponding tf variables
t.header.stamp = timestamp
t.header.frame_id = "track"
t.child_frame_id = "base_footprint"
t.transform.translation.x = self.state[0]
t.transform.translation.y = self.state[1]
t.transform.translation.z = 0.0
t.transform.rotation = Quaternion(x=quaternion[1], y=quaternion[2], z=quaternion[3], w=quaternion[0])
self.broadcaster.sendTransform(t)
def predict(self, x_delta: float, y_delta: float, theta_delta: float):
"""
Predict step of the EKF.
Updates the state and covariance matrix by adding pose delta onto last state.
"""
Jx = np.array([[1, 0, -x_delta], [0, 1, y_delta], [0, 0, 1]])
Ju = np.array([[cos(self.state[2]), 0], [sin(self.state[2]), 0], [0, 1]])
self.state[0:3] += np.array([x_delta, y_delta, theta_delta])
self.state[2] = wrap_to_pi(self.state[2])
self.sigma[0:3, 0:3] = Jx @ self.sigma[0:3, 0:3] @ Jx.T + Ju @ R @ Ju.T
def update(self, index: int, detection: ConeProps, Q: np.ndarray):
"""
Update step of the EKF
* param index: index of the cone in the map
* param cone: tuple of (x, y) of the cone
"""
i = index * 2 + 3 # landmark index, first 3 are vehicle, each landmark has 2 values
mu_cone = self.state[i : i + 2] # omit colour from location mean
r = hypot(self.state[0] - mu_cone[0], self.state[1] - mu_cone[1]) # range to landmark
b = wrap_to_pi(atan2(mu_cone[1] - self.state[1], mu_cone[0] - self.state[0]) - self.state[2]) # bearing to lm
h = [r, b]
sig_len = len(self.sigma) # length of vehicle+landmarks we've seen so far
Gt = np.zeros((2, sig_len))
# vehicle jacobian
Gt[0:2, 0:3] = [
[-(mu_cone[0] - self.state[0]) / r, -(mu_cone[1] - self.state[1]) / r, 0],
[(mu_cone[1] - self.state[1]) / (r**2), -(mu_cone[0] - self.state[0]) / (r**2), 1],
]
# landmark jacobian
Gt[0:2, i : i + 2] = [
[(mu_cone[0] - self.state[0]) / r, (mu_cone[1] - self.state[1]) / r],
[-(mu_cone[1] - self.state[1]) / (r**2), (mu_cone[0] - self.state[0]) / (r**2)],
]
Kt = self.sigma @ Gt.T @ np.linalg.inv(Gt @ self.sigma @ Gt.T + Q)
# update state, wrap bearing to pi, wrap heading to pi
self.state = self.state + (Kt @ np.array([detection.range - h[0], wrap_to_pi(detection.bearing - h[1])])).T
self.state[2] = wrap_to_pi(self.state[2])
# update cov
self.sigma = (np.eye(sig_len) - Kt @ Gt) @ self.sigma
def init_landmark(self, detection: ConeProps, Q: np.ndarray):
"""
Add new landmark to state
* param detection: ConeProps object containing the cone properties
* param Q: measurement noise covariance matrix for this sensor
"""
self.state = np.append(self.state, detection.map_coords) # append new landmark
# landmark Jacobian
Lz = np.array(
[
[cos(self.state[2] + detection.bearing), detection.range * -sin(self.state[2] + detection.bearing)],
[sin(self.state[2] + detection.bearing), detection.range * cos(self.state[2] + detection.bearing)],
]
)
sig_len = len(self.sigma)
new_sig = np.zeros((sig_len + 2, sig_len + 2)) # create zeros
new_sig[0:sig_len, 0:sig_len] = self.sigma # top left corner is existing sigma
new_sig[sig_len : sig_len + 2, sig_len : sig_len + 2] = Lz @ Q @ Lz.T # bottom right is new lm
self.sigma = new_sig
def flush_map(self, track_as_2d: np.ndarray):
"""
Remove landmarks not seen for a number of frames and only behind the car
* param track_as_2d: track as a 2d array
"""
if len(self.properties) == 0:
return
heading = np.array([cos(self.state[2]), sin(self.state[2])])
position = np.array([self.state[0], self.state[1]])
# get the landmark position vectors
# if the landmark is behind car, the dot product will be negative
landmark_position_vectors = track_as_2d - position
dot_products = np.dot(landmark_position_vectors, heading)
behind_idxs = np.where(dot_products < 0)[0]
# get indexes of landmarks that have been seen for a number of frames
noisy_idxs = np.array([i for i, cone in enumerate(self.properties) if cone.frame_count < FRAME_REM_COUNT])
# remove noisy and behind landmarks
idxs_to_remove = np.concatenate((behind_idxs, noisy_idxs))
unique, count = np.unique(idxs_to_remove, return_counts=True) # gets unique indexes
duplicated_idxs = unique[count > 1] # only gets indexes that are duplicated (behind and noisy)
if len(duplicated_idxs) > 0:
self.state = np.delete(self.state, [duplicated_idxs * 2 + 3, duplicated_idxs * 2 + 4], axis=0)
self.sigma = np.delete(self.sigma, [duplicated_idxs * 2 + 3, duplicated_idxs * 2 + 4], axis=0) # rows
self.sigma = np.delete(self.sigma, [duplicated_idxs * 2 + 3, duplicated_idxs * 2 + 4], axis=1) # columns
self.properties = np.delete(self.properties, duplicated_idxs, axis=0)
def get_local_map(self, rotation_mat) -> np.ndarray:
"""
Get cones within view of the car
* param rotation_mat: rotation matrix to rotate the map to the car's heading
* return: array of (x, y) of these cones
"""
# transform detection to map
rotation_mat = np.array(
[
[cos(self.state[2]), -sin(self.state[2])],
[sin(self.state[2]), cos(self.state[2])],
]
)
local_coords = np.array([])
for i in range(len(self.properties)):
local = np.linalg.inv(rotation_mat) @ (self.properties[i].map_coords - self.state[0:2])
local_coords = np.append(local_coords, [local])
self.properties[i].local_x = local[0]
self.properties[i].local_y = local[1]
local_coords = local_coords.reshape(-1, 2)
# get any cones that are within -10m to 10m beside car
side_idxs = np.where(np.logical_and(local_coords[:, 1] > -Y_RANGE, local_coords[:, 1] < Y_RANGE))[0]
# get any cones that are within 15m in front of car
forward_idxs = np.where(np.logical_and(local_coords[:, 0] > 0, local_coords[:, 0] < X_RANGE))[0]
# combine indexes
idxs = np.intersect1d(side_idxs, forward_idxs)
return self.properties[idxs]
def main(args=None):
rclpy.init(args=args)
node = SBGSlam()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
|
package com.me.security.security.provider;
import com.me.security.security.exception.BadTokenAuthorizationException;
import com.me.security.security.exception.ClientNotFoundAuthenticationException;
import com.me.security.security.exception.ClientStatusAuthenticationException;
import com.me.security.security.model.AttemptAuthenticationToken;
import com.me.security.security.model.ClientAuthInfo;
import com.me.security.security.model.ClientAuthenticationToken;
import com.me.security.security.model.VerifyResult;
import com.me.security.security.service.AccessAuthorizationService;
import com.me.security.security.service.AuthenticationTokenVerifier;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import java.util.Optional;
@RequiredArgsConstructor
public class TokenAuthenticationProvider implements AuthenticationProvider {
private final AuthenticationTokenVerifier verifyService;
private final AccessAuthorizationService authorizationService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
AttemptAuthenticationToken authenticationToken = (AttemptAuthenticationToken) authentication;
String accessToken = authenticationToken.getAccessToken();
//User Token or Server Token 검증
Optional<VerifyResult> verify = verifyService.verify(accessToken);
if (verify.isEmpty()) {
throw new BadTokenAuthorizationException("The token is invalid. token : \"" + accessToken + "\"");
}
Long clientId = verify.get().getId();
try {
ClientAuthInfo access = authorizationService.getAccessClient(clientId);
return new ClientAuthenticationToken(access, accessToken);
} catch (ClientNotFoundAuthenticationException e) {
throw new BadCredentialsException("Bad Credential Authorization! clientId : \"" + clientId + "\" accessToken : \"" + accessToken + "\"", e);
} catch (ClientStatusAuthenticationException e2) {
throw new BadCredentialsException("Bad Credential Authorization Token Expired! clientId : \"" + clientId + "\" accessToken : \"" + accessToken + "\"", e2);
}
}
@Override
public boolean supports(Class<?> authentication) {
return AttemptAuthenticationToken.class.isAssignableFrom(authentication);
}
}
|
import {
AnnouncementDetailTypeMobile,
AnnouncementFindManyTypeMobile,
LoadDetailTypeMobile,
} from "@anysoftuz/carting-shared/dist/types/mobile";
// import { AnnouncementSearchFilterRequest } from "./announcements";
export type MyTruck = {
id: number;
photos: string[];
model: string;
auto_number: string;
};
export type Item = {
id: number;
name: string;
};
export type LoadSearchFilterRequest = {
filter: {
loads?: {
load_type?: string[];
body_height?: number;
body_width?: number;
body_length?: number;
price?: {
max?: number;
min?: number;
};
currency?: string[];
pickup_region_id?: number[];
delivery_region_id?: number[];
vehicle_type?: string[];
capacity?: {
min?: number;
max?: number;
};
created_at?: {
min?: string;
max?: string;
};
};
search?: {
value: string;
};
};
};
export type AnnouncementSearchFilterRequest = {
filter: {
vacancies?: {
salary?: {
min?: number;
max?: number;
};
experience?: number[];
created_at?: {
min?: string;
max?: string;
};
};
search?: {
value: string;
};
};
};
export interface SearchStoreType {
isLoad: {
loads: boolean;
announcements: boolean;
regions: boolean;
trucks: boolean;
detail: boolean;
};
orderDetail: LoadDetailTypeMobile;
load: LoadDetailTypeMobile | object;
myTrucks: MyTruck[] | [];
regions: Item[] | [];
filterLoadValue: LoadSearchFilterRequest["filter"]["loads"];
filterAnnouncementValue: AnnouncementSearchFilterRequest["filter"]["vacancies"];
tabValue: string;
searchValue: string;
handleSearch: (value: string) => void;
handleTabName: (value: string) => void;
handleFilterValue: (
value: LoadSearchFilterRequest["filter"]["loads"]
) => void;
handleFilterAnnouncementValue: (
value: AnnouncementSearchFilterRequest["filter"]["vacancies"]
) => void;
getLoad: (id: number) => void;
getMyTrucks: () => void;
getRegions: () => void;
clear: (value: LoadSearchFilterRequest["filter"]["loads"]) => void;
clearAnnouncement: (
value: AnnouncementSearchFilterRequest["filter"]["vacancies"]
) => void;
getOrderDetails: (orderId: number) => void;
}
|
package com.practice.springbootjwt.models;
import jakarta.persistence.*;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@Entity
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Builder
@EqualsAndHashCode(of = "id")
public class Member implements UserDetails {
@Id
@GeneratedValue
private Long id;
@Column(unique = true, nullable = false)
private String loginId;
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String password;
@ElementCollection(fetch = FetchType.EAGER)
@Builder.Default
private List<String> roles = new ArrayList<>();
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
}
@Override
public String getUsername() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return false;
}
}
|
var errorString = "" ;
var isError = false;
class chip8Compiler{
//Class takes in chip 8 assembly and outputs opcodes
compileMneonicToOpcodes(code){
//split the commands into array
let assemblyArray = code.split("\n");
//remove comments including spaces in front and end of line
assemblyArray = this.removeComments(assemblyArray);
//compile opcodes which include addresses
assemblyArray = this.compileSYS_JP_CALL_LDI(assemblyArray);
//compiling main opcodes
assemblyArray = this.assemblyToOpcode(assemblyArray);
//compiling sprites
assemblyArray = this.compileSpritesBinToHex(assemblyArray);
//final opcodes is the good version of the opcodes
let finalOpcodes = "";
let memmoryAddresses = 510; //this is memory address 200 in decimal
let regEmptyLine = /^\s*\n?$/im;
for(var x=0 ; x< assemblyArray.length ; x++){
let command = assemblyArray[x];
if(!regEmptyLine.test(command)){ //skip empty lines
memmoryAddresses += 2;
//**********UN-COMMENT NEXT LINE FOR DEBUGGING********///////
//finalOpcodes += memmoryAddresses.toString(16)+ " " + command + "\n"; //
finalOpcodes += command + " ";
}
}
if(isError){
isError = false;
return errorString;
}
else{
return finalOpcodes;
}
}
removeComments(assemblyArray){
let result;
for(var x=0 ; x< assemblyArray.length ; x++){
result = assemblyArray[x];
result = result.replace(/\s*;.*\n?$/gim, "\n"); //remove removeComments
result = result.replace(/\t+/g,""); //remove tabs
result = result.replace(/\s*$/im,""); //remove spaces in back
result = result.replace(/^\s*/im,""); //remove spaces in front
assemblyArray[x] = result;
}
return assemblyArray;
}
compileSYS_JP_CALL_LDI(assemblyArray){
//0nnn - SYS addr
//1nnn - JP addr
let regJP = /^jp\s*[a-z0-9_]+$/im;
//2nnn - CALL addr
let regCALL = /^call\s*[a-z0-9_]+$/im;
//Annn - LD I, addr
let regLDI = /^ld\s*i\s*,\s*[a-z0-9_]+$/mi;
//Bnnn - JP V0, addr
console.log("compiling SYS, JP, CALL, LD I, and JP V0");
//var addressOfMemory = 512;
var addrNameArray= []; //need to store the names of places to jump in order to delete later
let regEmptyLine = /^\s*\n?$/im;
for(var x=0 ; x< assemblyArray.length ; x++){
let code = assemblyArray[x];
if(!regEmptyLine.test(code)){ //skip empty lines
if(regJP.test(code)){//1nnn - JP addr
let nameLocation = code.match(/[a-z1-9_]+\s*$/im)[0]; //name of location where to jump to
let addressOfJump = this.findNameLocation(nameLocation, assemblyArray);
addrNameArray.push(nameLocation);
addressOfJump = parseInt(addressOfJump);
let addressOfJumpInHex = addressOfJump.toString(16); //convert to hexidecimal
//1nnn - JP addr
assemblyArray[x] = "1" + addressOfJumpInHex; //replace with opcode
}
else if(regCALL.test(code)){
//console.log("so far so good " + code);
let nameLocation = code.match(/[a-z1-9_]+$/im)[0]; //name of location where function declaration to
let addressOfCall = this.findNameLocation(nameLocation, assemblyArray); //finding where the function is located
addrNameArray.push(nameLocation);
addressOfCall = parseInt(addressOfCall);
let addressOfCallInHex = addressOfCall.toString(16); //convert to hexidecimal
//1nnn - JP addr
assemblyArray[x] = "2" + addressOfCallInHex; // replacing with opcodes
}
else if(regLDI.test(code)){
let nameLocation = code.match(/[a-z1-9_]+$/im)[0]; //name of location where to sprite is declared
addrNameArray.push(nameLocation);
let addressOfCall = this.findNameLocation(nameLocation, assemblyArray);
addressOfCall = parseInt(addressOfCall);
let addressOfCallInHex = addressOfCall.toString(16); //convert to hexidecimal
//1nnn - JP addr
assemblyArray[x] = "A" + addressOfCallInHex;
}
}
}
console.log(assemblyArray);
console.log(addrNameArray);
var reg;
//removing all the places we jumped to
for(var m=0 ; m< addrNameArray.length ; m++){
for(var n=0 ; n< assemblyArray.length ; n++){
reg = new RegExp("^"+addrNameArray[m]+ " *","im");
if( reg.test(assemblyArray[n]) ){
assemblyArray[n] = " " ;
}
}
}
console.log("done compiling jumps and calls and LD I");
return assemblyArray;
}
findNameLocation(nameLocation, assemblyArray){
//returning memory address of where nameLocation is found in the code
var addressOfMemory = 512; //200 in hex
var r = new RegExp("^\\s*"+nameLocation+"\\s*$","im");
let regEmptyLine = /^\s*\n?$/im;
for(var x=0 ; x< assemblyArray.length ; x++){
let code = assemblyArray[x];
if(!regEmptyLine.test(code)){ //skip empty lines
let inHex = addressOfMemory.toString(16);
if(!this.isChip8Instruction(code)){ // if not assembly then increase addressOfMemory
if(r.test(code)){ //if the address of the name is found then return
return addressOfMemory;
}
}
else{
addressOfMemory= addressOfMemory+2;
let byteReg = /^byte\s*%/im
if(byteReg.test(code)){
addressOfMemory--;
}
}
}
}
}
assemblyToOpcode(assemblyArray){
let lineNumber = 0;
let regEmptyLine = /^\s*\n?$/im;
for(var x=0 ; x< assemblyArray.length ; x++){
lineNumber++;
let code = assemblyArray[x];
let opcode = "";
if(!regEmptyLine.test(code)){ //skip empty lines
let opcode= "";
let code = assemblyArray[x];
//00E0 - CLS
let r = /CLS/im;
if(r.test(code)){
opcode = code.replace(/CLS/, "00E0");
}
//00EE - RET
r = /^ret$/im;
if(r.test(code)){
opcode = code.replace(r, "00EE");
}
//******all opcodes with addr ****** //taken care with
//0nnn - SYS addr
//1nnn - JP addr //this is delt with in seperate function
//2nnn - CALL addr //this is delt with in a seperate function
//Annn - LD I, addr //delt with this in seperate function/////
//Bnnn - JP V0, addr
///////
//3xkk - SE Vx, byte
//4xkk - SNE Vx, byte
//6xkk - LD Vx, byte
//7xkk - ADD Vx, byte
//Cxkk - RND Vx, byte
let regNegOrPosByte = /^(se|Sne|ld|add|rnd)\s*v[0-9a-f]\s*,\s*-?(1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$/im; //for catching negative bytes and positive bytes
//regPosByte = /^(se|Sne|ld|add|rnd)\s*v[0-9a-f]\s*,\s*(1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$/im;
if(regNegOrPosByte.test(code)){
var byte;
let regPosByte = /^(se|Sne|ld|add|rnd)\s*v[0-9a-f]\s*,\s*(1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$/im; //for catching positive bytes
let regNegByte = /^(se|Sne|ld|add|rnd)\s*v[0-9a-f]\s*,\s*-(1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$/im;
let register = code.replace(/^[a-z]{2,3}\s*v/im, "")[0];//for catching negative bytes
if(regPosByte.test(code)){
//console.log("regPosByte " + code);
byte = code.match(/(1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$/im)[0];
byte = parseInt(byte);
byte = byte.toString(16);
}
else if(regNegByte.test(code)){
//console.log("regNegByte " + code);
byte = code.match(/(1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$/im)[0];
byte = this.decToHexWithTwoComp(byte);
}
if(byte.length ==1){
byte = "0" + byte;
}
if(/^se/im.test(code)){
opcode = code.replace(regNegOrPosByte, "3"+ register + byte);
}
else if(/^sne/im.test(code)){//4xkk - SNE Vx, byte
opcode = code.replace(regNegOrPosByte, "4"+ register + byte);
}
else if(/^ld/im.test(code)){//6xkk - LD Vx, byte
opcode = code.replace(regNegOrPosByte, "6"+ register + byte);
}
else if(/^add/im.test(code)){//7xkk - ADD Vx, byte
opcode = code.replace(regNegOrPosByte, "7"+ register + byte);
}
else if(/^rnd/im.test(code)){ //Cxkk - RND Vx, byte
opcode = code.replace(regNegOrPosByte, "C"+ register + byte);
}
}
//8xy0 - LD Vx, Vy
//8xy1 - OR Vx, Vy
//8xy2 - AND Vx, Vy
//8xy3 - XOR Vx, Vy
//8xy4 - ADD Vx, Vy
//8xy5 - SUB Vx, Vy
//5xy0 - SE Vx, Vy
//8xy7 - SUBN Vx, Vy
//9xy0 - SNE Vx, Vy
r = /^(LD|OR|AND|XOR|ADD|SUB|SE|SUBN|SNE)\s*v[0-9a-f]\s*,\s*v[0-9a-f]$/im;
if(r.test(code)){
//let firstTerm = code.match(/^[a-z_]+/im)[0]);
let register1 = code.replace(/^[a-z0-9_]+\s*v/im, "")[0];
let regester2 = code.replace(/^[a-z_]+\s*v[0-9a-f]\s*,\s*v/im,"")[0];
let number = 0;
if(/^LD\s*V[0-9a-f],\s*v[0-9a-f]/im.test(code)){
number = 0;
opcode = code.replace(r, "8"+ register1+ regester2 +number);
}
if(/^OR/im.test(code)){
number = 1;
opcode = code.replace(r, "8"+ register1+ regester2 +number);
}
if(/^AND/im.test(code)){
number = 2;
opcode = code.replace(r, "8"+ register1+ regester2 +number);
}
if(/^XOR/im.test(code)){
number = 3;
opcode = code.replace(r, "8"+ register1+ regester2 +number);
}
if(/^ADD/im.test(code)){
number = 4;
opcode = code.replace(r, "8"+ register1+ regester2 +number);
}
if(/^SUB/im.test(code)){
number = 5;
opcode = code.replace(r, "8"+ register1+ regester2 +number);
}
if(/^SUBN/im.test(code)){
number = 5;
opcode = code.replace(r, "8"+ register1+ regester2 +number);
}
if(/^SE/im.test(code)){
number = 0;
opcode = code.replace(r, "5"+ register1+ regester2 +number);
}
if(/^SNE/im.test(code)){
number = 0;
opcode = code.replace(r, "9"+ register1+ regester2 +number);
}
}
//Dxyn - DRW Vx, Vy, nibble
r = /^drw\s*v[0-9a-f]\s*,\s*v[0-9a-f]\s*,\s*(1[0-5]|[1-9])$/im;
if(r.test(code)){
let register1 = code.replace(/^[a-z0-9_]+\s*v/im, "")[0];
let regester2 = code.replace(/^[a-z0-9_]+\s*v[0-9a-f]\s*,\s*v/im,"")[0];
let nibble = code.match(/(1[0-5]|[1-9])$$/)[0];
nibble = parseInt(nibble).toString(16);
//console.log("nibble is " + nibble);
opcode = code.replace(r, "D"+ register1+ regester2 + nibble);
}
//Ex9E - SKP Vx
//ExA1 - SKNP Vx
r = /^(skp|sknp)\s*v[0-9a-f]$/im;
if(r.test(code)){
let register = code.replace(/^(skp|sknp)\s*v/im, "")[0];
if(/^skp\s*v[0-9a-f]$/im.test(code)){
opcode = code.replace(r, "E"+ register + "9E");
}
if(/^sknp\s*v[0-9a-f]$/im.test(code)){
opcode = code.replace(r, "E"+ register + "A1");
}
}
r = /^sknp\s*v[0-9a-f]$/im;
if(r.test(code)){
let register = code.match(/[0-9a-f]$/im)[0];
opcode = code.replace(r, "E"+ register+ "A1");
}
//Fx07 - LD Vx, DT
r = /^ld\s*v[0-9a-f]\s*,\s*dt$/im;
if(r.test(code)){
let register = code.replace(/^ld\s*v/im, "")[0];
opcode = code.replace(r, "F"+ register + "07");
}
//Fx0A - LD Vx, K
//Fx15 - LD DT, Vx
r = /ld\s*dt\s*,\s*v[0-9a-f]$/im;
if(r.test(code)){
let register = code.replace(/ld\s*dt\s*,\s*v/im, "")[0];
opcode = code.replace(r, "F"+ register + "15");
}
//ALL THESE TOGETHER//////
//Fx18 - LD ST, Vx
//Fx29 - LD F, Vx
//Fx33 - LD B, Vx
//Fx55 - LD [I], Vx
// ----------------------
//Fx65 - LD Vx, [I]
//Fx1E - ADD I, Vx
r = /^LD\s*(ST|F|B|\[I\]|V)\s*,\s*V[0-9a-f]/im;
if(r.test(code)){
let register = code.replace(/^LD\s*(ST|F|B|\[I\]|V)\s*,\s*V/im, "")[0];
//Fx18 - LD ST, Vx
if(/^LD\s*ST\s*,\s*V[0-9a-f]/im.test(code)){
opcode = code.replace(r, "F"+ register + "18");
}
//Fx29 - LD F, Vx
if(/^LD\s*F\s*,\s*V[0-9a-f]/im.test(code)){
opcode = code.replace(r, "F"+ register + "29");
}
//Fx33 - LD B, Vx
if(/^LD\s*B\s*,\s*V[0-9a-f]/im.test(code)){
opcode = code.replace(r, "F"+ register + "33");
}
//Fx55 - LD [I], Vx
if(/^LD\s*\[I\]\s*,\s*V[0-9a-f]/im.test(code)){
opcode = code.replace(r, "F"+ register + "55");
}
}
//Fx65 - LD Vx, [I]
r = /^LD\s*V[0-9a-f],\s*\[I\]/im;
if(r.test(code)){
let register = code.replace(/^LD\s*V/im, "")[0];
opcode = code.replace(r, "F"+ register+ "65");
}
//Fx1E - ADD I, Vx
r = /^add\s*I\s*,\s*v[0-9a-f]/im;
if(r.test(code)){
let register = code.replace(/^add\s*I\s*,\s*v/im, "")[0];
opcode = code.replace(r, "F"+ register + "1E");
}
/*
3.2 - Super Chip-48 Instructions
00Cn - SCD nibble
00FB - SCR
00FC - SCL
00FD - EXIT
00FE - LOW
00FF - HIGH
Dxy0 - DRW Vx, Vy, 0
Fx30 - LD HF, Vx
Fx75 - LD R, Vx
Fx85 - LD Vx, R
*/
let regJumpCallByte = /^(a|1|2|byte).*/im;
if(!opcode == "" ){ //if matched with some instruction the its valid
assemblyArray[x] = opcode;
}
else if(regJumpCallByte.test(code)){
//do nothing
}
else{ //if did not match with anything then its not valid
console.log("ERROR IN LINE: " + lineNumber + "\n" + code);
isError = true;
errorString = errorString + "\nERROR IN LINE: " + lineNumber + "\n" + code;
}
}
}
return assemblyArray;
}
compileSpritesBinToHex(assemblyArray){
console.log("turning sprites binary to hex" );
let r = /^byte\s*%[01]{8}$/im;
let regEmptyLine = /^\s*\n?$/im;
var code;
var code2;
for(var x=0 ; x< assemblyArray.length ; x++){
//console.log("x is ................." + x);
code = assemblyArray[x];
let m = x+1;
let aCode = assemblyArray[m];
while(regEmptyLine.test(aCode)){
m++;
aCode = assemblyArray[m];
}
code2 = assemblyArray[m];
if(!regEmptyLine.test(code)){ //skip empty lines
if(r.test(code)){
let regBin = /[10]{8}$/im;
let spriteBin = code.match(regBin)[0];
let spriteHex = parseInt(spriteBin, 2).toString(16);
if(spriteHex.length ==1){
spriteHex = "0" + spriteHex;
}
if(r.test(code2)){
let spriteBin = code2.match(regBin)[0];
let spriteHex2 = parseInt(spriteBin, 2).toString(16);
if(spriteHex2.length ==1){
spriteHex2 = "0" + spriteHex2;
}
let combinedHex = spriteHex + spriteHex2;
assemblyArray[x] = combinedHex;
assemblyArray[m] = " ";
x++;
}
else{
while(spriteHex.length != 4){
spriteHex = spriteHex + "0";
}
assemblyArray[x]= spriteHex;
}
}
}
}
return assemblyArray;
}
isChip8Instruction(code){
let r = /\b(?:CLS|BYTE|RET|SYS|JP|LD|SE|CALL|SNE|ADD|OR|AND|XOR|SUB|SHR|SUBN|SHL|RND|DRW|SKP|SKNP|SCD|SCR|SCL|EXIT|LOW|HIGH)\b/i;
if(r.test(code)){
return true;
}
else{
//need to also return true if it is jump, call , or LD i because we did these steps simaltaniously and are still considered instruction
//can improve this making changes in another array instead of original.
let regexJumpOpcodes = /^(1|2|a)[0-9a-f]{3}$/im
if(regexJumpOpcodes.test(code)){
return true;
}
else{
return false;
}
}
}
//helper
decToHexWithTwoComp(byte){ //using twos compliment
var flipbits = function flipbits(str) {
return str.split('').map(function (b) {
return (1 - b).toString();
}).join('');
};
byte = Math.abs(parseInt(byte));
byte = byte.toString(2);
byte = this.pad(byte,8);
byte = byte.toString();
byte = flipbits(byte);
byte = parseInt(byte,2);
byte = 1+byte;
//turn the decimal back to binary
byte = byte.toString(2);
byte = parseInt(byte);
byte = parseInt(byte, 2).toString(16).toUpperCase()
return byte;
}
//helper
pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
}
|
package br.com.dbc.vemser.pessoaapi.dto;
import br.com.dbc.vemser.pessoaapi.entity.TipoContato;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Data
public class ContatoCreateDTO {
@NotNull
@Schema(description = "Tipo de contato")
private TipoContato tipoContato;
@NotNull
@Size(max=13)
@Schema(description = "Número do telefone")
private String numero;
@NotNull
@NotBlank
@Schema(description = "Descrição")
private String descricao;
@NotNull
@Schema(description = "id da pessoa")
private Integer idPessoa;
}
|
package com.example.redditclone.service.elasticsearch;
import com.example.redditclone.models.Reader;
import com.example.redditclone.repository.elasticsearch.ReaderRepository;
import com.example.redditclone.service.SearchQueryGenerator;
import com.example.redditclone.web.dto.ReaderDTO;
import com.example.redditclone.web.dto.SimpleQueryEs;
import com.example.redditclone.web.dto.mapper.ReaderMapper;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ReaderService {
private final ReaderRepository readerRepository;
private final ElasticsearchRestTemplate elasticsearchRestTemplate;
public ReaderService(ReaderRepository readerRepository, ElasticsearchRestTemplate elasticsearchRestTemplate) {
this.readerRepository = readerRepository;
this.elasticsearchRestTemplate = elasticsearchRestTemplate;
}
public void index(ReaderDTO readerDTO){
readerRepository.save(new Reader("123", readerDTO.getName(), readerDTO.getLastName(), readerDTO.getAddress()));
}
public List<ReaderDTO> findByFirstNameAndLastName(String firstName, String lastName){
QueryBuilder firstNameQuery = SearchQueryGenerator.createMatchQueryBuilder(new SimpleQueryEs("name", firstName));
QueryBuilder lastNameQuery = SearchQueryGenerator.createMatchQueryBuilder(new SimpleQueryEs("lastName", lastName));
BoolQueryBuilder boolQueryFirstNameAndLastName = QueryBuilders
.boolQuery()
.must(firstNameQuery)
.must(lastNameQuery);
return ReaderMapper.mapDtos(searchByBoolQuery(boolQueryFirstNameAndLastName));
}
private SearchHits<Reader> searchByBoolQuery(BoolQueryBuilder boolQueryBuilder) {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(boolQueryBuilder)
.build();
return elasticsearchRestTemplate.search(searchQuery, Reader.class, IndexCoordinates.of("readers"));
}
}
|
package main
import (
"time"
"github.com/gin-gonic/gin"
)
type Produto struct {
ID int `json:"id"`
Nome string `json:"nome"`
Cor string `json:"cor"`
Preco float64 `json:"preco"`
Estoque int `json:"estoque"`
Codigo string `json:"codigo"`
Tamanho string `json:"tamanho"`
Publicacao bool `json:"publicacao"`
DataCriacao time.Time `json:"data_criacao"`
}
var produtos = []Produto{
{
ID: 1,
Nome: "Camiseta",
Cor: "Azul",
Preco: 25.99,
Estoque: 100,
Codigo: "ABC123",
Tamanho: "M",
Publicacao: true,
DataCriacao: time.Now(),
},
{
ID: 2,
Nome: "Sapato",
Cor: "Vermelho",
Preco: 67.99,
Estoque: 56,
Codigo: "DFG123",
Tamanho: "38",
Publicacao: true,
DataCriacao: time.Now(),
},
{
ID: 3,
Nome: "Sapato",
Cor: "Vermelho",
Preco: 67.99,
Estoque: 56,
Codigo: "DLK123",
Tamanho: "40",
Publicacao: true,
DataCriacao: time.Now(),
},
{
ID: 4,
Nome: "Nike",
Cor: "Vermelho",
Preco: 97.99,
Estoque: 26,
Codigo: "DHG123",
Tamanho: "40",
Publicacao: true,
DataCriacao: time.Now(),
},
}
func SearchProduct(c *gin.Context) {
cor := c.Query("cor")
tamanho := c.Query("tamanho")
var produtosFiltrados []Produto
for _, produto := range produtos {
if (produto.Cor != cor && cor != "") || (produto.Tamanho != tamanho && tamanho != "") {
continue
}
produtosFiltrados = append(produtosFiltrados, produto)
}
c.JSON(200, produtosFiltrados)
}
func HandleRequest() {
r := gin.Default()
r.GET("/produtos", SearchProduct)
r.Run(":8000")
}
func main() {
HandleRequest()
}
|
import { useState, useCallback } from 'react';
import './Counter.css';
import CounterChild from './CounterChild';
const Counter = () => {
const [counter, setCounter] = useState(0);
const [inputValue, setInputValue] = useState('');
// Without memorization
// const add = () => setCounter(counter + 1);
// const subtract = () => setCounter(counter - 1);
// With memorization. We prevent that when the state of 'inputValue' changes, the CounterChild component rendered again.
const add = useCallback(() => setCounter(counter + 1), [counter]);
const subtract = useCallback(() => setCounter(counter - 1), [counter]);
const handleInputChange = (e) => setInputValue(e.target.value);
return (
<>
<div className="container">
<h2>Counter</h2>
<button className="btn" onClick={add}>
+
</button>
<button className="btn" onClick={subtract}>
-
</button>
<p>{counter}</p>
</div>
<div className="container">
<h2>Input</h2>
<form>
<input type="text" onChange={handleInputChange} value={inputValue} />
</form>
</div>
<div className="container">
<CounterChild counter={counter} add={add} subtract={subtract} />
</div>
</>
);
};
export default Counter;
|
import {
validConfirmPassword,
validEmail,
validName,
validOldPassword,
validPassword,
} from "../../utils/validation";
import { Dispatch, FC, SetStateAction, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { z, ZodError } from "zod";
import "./styles.css";
import { useUsers } from "../../context/Users";
import { Link } from "react-router-dom";
const User: FC = () => {
const { id } = useParams();
const usersContext = useUsers();
const [name, setName] = useState<string>("");
const [email, setEmail] = useState<string>("");
const [oldPassword, setOldPassword] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [confirmPassword, setConfirmPassword] = useState<string>("");
const [nameError, setNameError] = useState<string | null>(null);
const [emailError, setEmailError] = useState<string | null>(null);
const [oldPasswordError, setOldPasswordError] = useState<string | null>(null);
const [passwordError, setPasswordError] = useState<string | null>(null);
const [confirmPasswordError, setConfirmPasswordError] = useState<
string | null
>(null);
const [userNotFound, setUserNotFound] = useState<boolean>(false);
const validFields = async (
validation: Function,
validationArgs: Array<any>,
setError: Dispatch<SetStateAction<string | null>>
) => {
try {
await validation(...validationArgs);
setError(null);
} catch (err) {
if (err instanceof ZodError) {
setError(err.issues[0].message);
} else if (err instanceof Error) {
console.error(err.message, err.stack);
} else {
console.error(err);
}
}
};
useEffect(() => {
if (id) {
const user = usersContext?.users.find((x) => x.id === id);
if (!user) setUserNotFound(true);
setName(user?.name ?? "");
setEmail(user?.email ?? "");
}
}, [id]);
if (userNotFound)
return (
<main>
<h1>User not found!</h1>
<Link to="/">Back</Link>
</main>
);
return (
<main className="user-page">
<header>
<h1>User:</h1>
<p>{id ?? "New"}</p>
</header>
<form
onSubmit={(e) => {
e.preventDefault();
if (
!!(nameError || emailError || passwordError || confirmPasswordError)
)
return;
id
? usersContext?.updateUser(oldPassword, {
id,
name,
email,
password,
})
: usersContext?.createUser({
name,
email,
password,
});
}}
>
<section>
<label>Name</label>
<input
type="text"
autoFocus
value={name}
onChange={(e) => setName(e.target.value)}
onBlur={() => validFields(validName, [name], setNameError)}
/>
{!!nameError && <small>{nameError}</small>}
</section>
<section>
<label>E-mail</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
onBlur={() => validFields(validEmail, [email], setEmailError)}
/>
{!!emailError && <small>{emailError}</small>}
</section>
{!!id && (
<section>
<label>Old Password</label>
<input
type="password"
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
onBlur={() =>
validFields(
validOldPassword,
[oldPassword],
setOldPasswordError
)
}
/>
{!!passwordError && <small>{oldPasswordError}</small>}
</section>
)}
<section>
<label>{!!id ? "New " : ""}Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
onBlur={() =>
validFields(validPassword, [password], setPasswordError)
}
/>
{!!passwordError && <small>{passwordError}</small>}
</section>
<section>
<label>Confirm Password</label>
<input
type="password"
value={confirmPassword}
onChange={(e) => {
setConfirmPassword(e.target.value);
validFields(
validConfirmPassword,
[e.target.value, password],
setConfirmPasswordError
);
}}
/>
{!!confirmPasswordError && <small>{confirmPasswordError}</small>}
</section>
<footer>
<Link to="/">
<button className="secondary" type="button">
Back
</button>
</Link>
<button type="submit">Save</button>
</footer>
</form>
</main>
);
};
export default User;
|
// SPDX-License-Identifier: MIT
// ERC20 stablecoin mockup based on DAI
pragma solidity =0.8.7;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol";
contract Stablecoin is ERC20 {
modifier auth() {
_authenticate();
_;
}
string public constant version = "1";
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
// keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
bytes32 public immutable DOMAIN_SEPARATOR;
mapping (address => uint) public auths;
mapping (address => uint) public nonces;
event Authorization(address authFrom, address authTo, uint authType, uint authTime);
constructor(
string memory name_,
string memory symbol_
) ERC20(name_, symbol_) {
auths[msg.sender] = 1;
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name_)),
keccak256(bytes(version)),
block.chainid,
address(this)
));
}
function _authenticate() private view { require(auths[msg.sender] == 1, "unauthorized"); }
function rely(address account) external auth {
auths[account] = 1;
emit Authorization(msg.sender, account, 1, block.timestamp);
}
function deny(address account) external auth {
auths[account] = 0;
emit Authorization(msg.sender, account, 0, block.timestamp);
}
function mint(address account, uint amount) external auth {
_mint(account, amount);
}
function burn(address account, uint amount) external {
_spendAllowance(account, msg.sender, amount);
_burn(account, amount);
}
// --- Alias ---
function push(address to, uint amount) external {
transferFrom(msg.sender, to, amount);
}
function pull(address from, uint amount) external {
transferFrom(from, msg.sender, amount);
}
function move(address from, address to, uint amount) external {
transferFrom(from, to, amount);
}
/// @notice Approve via signature
function permit(
address holder, address spender, uint256 nonce, uint256 expiry, bool allowed,
uint8 v, bytes32 r, bytes32 s
) external {
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed))
));
require(holder != address(0), "holder invalid");
require(holder == ecrecover(digest, v, r, s), "permit invalid");
require(expiry == 0 || block.timestamp <= expiry, "permit expired");
require(nonce == nonces[holder]++, "nonce invalid");
_approve(holder, spender, allowed ? type(uint256).max : 0);
}
}
|
<?php
use App\Http\Controllers\Admin\DashboardController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/dashboard', [DashboardController::class, 'index'])->name('home')->middleware('auth', 'isAdmin');
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
// Route::prefix()->group(function(){
// });
|
require("dotenv").config();
// notion client
const notionSDK = require("@notionhq/client");
const notionClient = new notionSDK.Client({
auth: process.env.NOTION_TOKEN,
});
// notion block parser
const notionBlocks = require("@notion-stuff/blocks-html-parser");
const notionBlockParser = notionBlocks.NotionBlocksHtmlParser.getInstance({
mdParserOptions: { emptyParagraphToNonBreakingSpace: true },
});
const getDrinks = async function (category) {
if (!category.has_children) return undefined;
let children = await notionClient.blocks.children.list({
block_id: category.id,
});
category.children = [...children.results];
let options = category.children.map((child) => {
return child.paragraph.rich_text[0].plain_text;
});
return {
name: category.toggle.rich_text[0].plain_text,
options: options,
};
};
const getCocktailDetails = async function (cocktail) {
var blocks = [],
dividers = [],
i;
let blockPage = await notionClient.blocks.children.list({
block_id: cocktail.id,
});
blocks = [...blockPage.results];
for (i = 0; i < blocks.length; i++) {
if (blocks[i].type === "divider") dividers.push(i);
}
cocktail.ingredients = [];
cocktail.instructions = [];
cocktail.notes = dividers[1] == blocks.length - 1 ? null : [];
blocks.forEach(async (block, index) => {
if (index < dividers[0]) {
let ingredient = block.paragraph.rich_text[0].plain_text.split(", ");
cocktail.ingredients.push({
measure: ingredient[0],
name: ingredient[1],
});
} else if (index > dividers[0] && index < dividers[1]) {
cocktail.instructions.push(block.paragraph.rich_text[0].plain_text);
} else if (index > dividers[1]) {
cocktail.notes.push(block.paragraph.rich_text[0].plain_text);
}
});
return cocktail;
};
exports.notionClient = notionClient;
exports.notionBlockParser = notionBlockParser;
exports.getDrinks = getDrinks;
exports.getCocktailDetails = getCocktailDetails;
|
import { render, screen } from '@testing-library/react'
import { MemoryRouter, Route } from 'react-router-dom'
import TeamPlanSpecialOffer from './TeamPlanSpecialOffer'
jest.mock('./TeamPlanCard', () => () => 'Team Plan Card')
const wrapper: React.FC<React.PropsWithChildren> = ({ children }) => (
<MemoryRouter initialEntries={['/gh/codecov/cancel']}>
<Route path="/:provider/:owner/cancel">{children}</Route>
</MemoryRouter>
)
describe('TeamPlanSpecialOffer', () => {
it('renders the header', async () => {
render(<TeamPlanSpecialOffer />, { wrapper })
const header = await screen.findByRole('heading', {
name: 'Alternative plan offer',
})
expect(header).toBeInTheDocument()
})
it('renders team plan card', async () => {
render(<TeamPlanSpecialOffer />, { wrapper })
const teamPlanCard = await screen.findByText('Team Plan Card')
expect(teamPlanCard).toBeInTheDocument()
})
it('renders link to change plan', async () => {
render(<TeamPlanSpecialOffer />, { wrapper })
const link = await screen.findByRole('link', {
name: /No thanks, I'll proceed with cancellation/,
})
expect(link).toBeInTheDocument()
expect(link).toHaveAttribute('href', '/plan/gh/codecov/cancel/downgrade')
})
})
|
// 插入页面的额外脚本或者style
export const EXTRA_CONFIG = [
// 百度统计
[
'script',
{},
`
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?f00a6211b690ac3505105511f6b90b30";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
`
],
// 微信图片防盗链处理:是被服务器判断了header中的referer的,这里处理不发送 referer 解决
[
'meta',
{
name: 'referrer',
content: 'origin'
}
]
]
// 渲染 loading
export function renderLoading() {
// 插入样式
createStyleSheet(
`.loading-container{position:fixed;top:0;left:0;z-index:10000;margin:0 auto;height:100%;width:100%;pointer-events:none;}.loading-container .loading-left-bg,.loading-container .loading-right-bg{position:fixed;width:50%;height:100%;background-color:#333;transition:all 0.75s cubic-bezier(0.42,0,0,1.01);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);}.loading-container .loading-right-bg{right:0;}.loaded .loading-left-bg{transform:translate(-100%,0);}.loaded .loading-right-bg{transform:translate(100%,0);}.loaded .container{display:none;}.loading-container .out{height:100vh;}.loading-container .container{position:fixed;width:40vw;height:45vw;left:0;right:0;top:0;bottom:0;margin:auto;z-index:666;}.loading-container .common{position:absolute;overflow:auto;margin:auto;width:2vw;max-width:100%;height:5vw;max-height:100%;border-radius:0 10vw 0 10vw;box-shadow:inset 0 0 0 0.1vw #e645d0,0 0 1.5vw 0 #e645d0;}.loading-container .one{transform:rotate(45deg);left:0;right:0;top:0;bottom:7.5vw;}.loading-container .two{transform:rotate(90deg);left:5.5vw;right:0;top:0;bottom:5.5vw;}.loading-container .three{transform:rotate(135deg);left:7.5vw;right:0;top:0;bottom:0;}.loading-container .four{transform:rotate(180deg);left:5.5vw;right:0;top:5.5vw;bottom:0;}.loading-container .five{transform:rotate(225deg);left:0;right:0;top:7.5vw;bottom:0;}.loading-container .six{transform:rotate(270deg);left:0;right:5.5vw;top:5.5vw;bottom:0;}.loading-container .seven{transform:rotate(315deg);left:0;right:7.5vw;top:0;bottom:0;}.loading-container .eight{transform:rotate(360deg);left:0;right:5.5vw;top:0;bottom:5.5vw;}.loading-container .one{animation:one 1s ease infinite;-moz-animation:one 1s ease infinite;-webkit-animation:one 1s ease infinite;-o-animation:one 1s ease infinite;}@keyframes one{50%{box-shadow:inset 0 0 0 0.1vw var(--vp-c-brand-light),0 0 1.5vw 0 var(--vp-c-brand-light);}}.loading-container .two{animation:two 1s 0.125s ease infinite;-moz-animation:two 1s 0.125s ease infinite;-webkit-animation:two 1s 0.125s ease infinite;-o-animation:two 1s 0.125s ease infinite;}@keyframes two{50%{box-shadow:inset 0 0 0 0.1vw var(--vp-c-brand-light),0 0 1.5vw 0 var(--vp-c-brand-light);}}.loading-container .three{animation:three 1s 0.25s ease infinite;-moz-animation:three 1s 0.25s ease infinite;-webkit-animation:three 1s 0.25s ease infinite;-o-animation:three 1s 0.25s ease infinite;}@keyframes three{50%{box-shadow:inset 0 0 0 0.1vw var(--vp-c-brand-light),0 0 1.5vw 0 var(--vp-c-brand-light);}}.loading-container .four{animation:four 1s 0.375s ease infinite;-moz-animation:four 1s 0.375s ease infinite;-webkit-animation:four 1s 0.375s ease infinite;-o-animation:four 1s 0.375s ease infinite;}@keyframes four{50%{box-shadow:inset 0 0 0 0.1vw var(--vp-c-brand-light),0 0 1.5vw 0 var(--vp-c-brand-light);}}.loading-container .five{animation:five 1s 0.5s ease infinite;-moz-animation:five 1s 0.5s ease infinite;-webkit-animation:five 1s 0.5s ease infinite;-o-animation:five 1s 0.5s ease infinite;}@keyframes five{50%{box-shadow:inset 0 0 0 0.1vw var(--vp-c-brand-light),0 0 1.5vw 0 var(--vp-c-brand-light);}}.loading-container .six{animation:six 1s 0.625s ease infinite;-moz-animation:six 1s 0.625s ease infinite;-webkit-animation:six 1s 0.625s ease infinite;-o-animation:six 1s 0.625s ease infinite;}@keyframes six{50%{box-shadow:inset 0 0 0 0.1vw var(--vp-c-brand-light),0 0 1.5vw 0 var(--vp-c-brand-light);}}.loading-container .seven{animation:seven 1s 0.75s ease infinite;-moz-animation:seven 1s 0.75s ease infinite;-webkit-animation:seven 1s 0.75s ease infinite;-o-animation:seven 1s 0.75s ease infinite;}@keyframes seven{50%{box-shadow:inset 0 0 0 0.1vw var(--vp-c-brand-light),0 0 1.5vw 0 var(--vp-c-brand-light);}}.loading-container .eight{animation:eight 1s 0.875s ease infinite;-moz-animation:eight 1s 0.875s ease infinite;-webkit-animation:eight 1s 0.875s ease infinite;-o-animation:eight 1s 0.875s ease infinite;}@keyframes eight{50%{box-shadow:inset 0 0 0 0.1vw var(--vp-c-brand-light),0 0 1.5vw 0 var(--vp-c-brand-light);}}.loading-container .container{animation:container 5s linear infinite;-moz-animation:container 5s linear infinite;-webkit-animation:container 5s linear infinite;-o-animation:container 5s linear infinite;}@keyframes container{from{transform:rotate(0deg);}to{transform:rotate(-360deg);}}@media screen and (min-width:960px){.loading-container .out{transform:scale(0.6);}}`
)
// 插入 dom
const body = document.getElementsByTagName('body')[0]
const loading = document.createElement('div')
loading.className = 'loading-container'
loading.innerHTML =
'' +
'<div class="loading-left-bg"></div>' +
'<div class="loading-right-bg"></div>' +
'<div class="out">' +
'<div class="container">' +
'<div class="one common"></div>' +
'<div class="two common"></div>' +
'<div class="three common"></div>' +
'<div class="four common"></div>' +
'<div class="five common"></div>' +
'<div class="six common"></div>' +
'<div class="seven common"></div>' +
'<div class="eight common"></div>' +
'</div>' +
'</div>'
body.classList.add('loading')
body.appendChild(loading)
// 加定时移除 loading
setTimeout(function () {
loading.classList.add('loaded')
body.classList.remove('loading')
}, 2000)
}
function createStyleSheet(css: string) {
try {
const sheet = new CSSStyleSheet()
sheet.replaceSync(css)
document.adoptedStyleSheets = [sheet]
} catch (e) {
const style = document.createElement('style')
style.type = 'text/css'
style.textContent = css
const head = document.getElementsByTagName('HEAD')[0]
if (head != null) {
head.appendChild(style)
}
}
}
/**
* 格式化日期
* @param time
* @param cFormat
*/
export function parseTime(time: any, cFormat: string) {
if (arguments.length === 0 || time === '0' || !time) {
return '无'
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
date = new Date(time * 1000)
}
const formatObj: FormatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
return format.replace(/{(y|m|d|h|i|s|a)+}/g, (result: string, key: keyof FormatObj) => {
let value: string | number = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value] || ''
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value.toString() || ''
})
}
interface FormatObj {
y: number
m: number
d: number
h: number
i: number
s: number
a: number
}
// 由于markdown-it-mathjax3使用svg渲染,增加了一些自定义标签,配置时同样需要将这些标签标记为自定义标签,防止编译出错
export const CUSTOM_ELEMENTS = [
'math',
'maction',
'maligngroup',
'malignmark',
'menclose',
'merror',
'mfenced',
'mfrac',
'mi',
'mlongdiv',
'mmultiscripts',
'mn',
'mo',
'mover',
'mpadded',
'mphantom',
'mroot',
'mrow',
'ms',
'mscarries',
'mscarry',
'mscarries',
'msgroup',
'mstack',
'mlongdiv',
'msline',
'mstack',
'mspace',
'msqrt',
'msrow',
'mstack',
'mstack',
'mstyle',
'msub',
'msup',
'msubsup',
'mtable',
'mtd',
'mtext',
'mtr',
'munder',
'munderover',
'semantics',
'math',
'mi',
'mn',
'mo',
'ms',
'mspace',
'mtext',
'menclose',
'merror',
'mfenced',
'mfrac',
'mpadded',
'mphantom',
'mroot',
'mrow',
'msqrt',
'mstyle',
'mmultiscripts',
'mover',
'mprescripts',
'msub',
'msubsup',
'msup',
'munder',
'munderover',
'none',
'maligngroup',
'malignmark',
'mtable',
'mtd',
'mtr',
'mlongdiv',
'mscarries',
'mscarry',
'msgroup',
'msline',
'msrow',
'mstack',
'maction',
'semantics',
'annotation',
'annotation-xml',
'mjx-container',
'mjx-assistive-mml'
]
|
#pragma once
#include <stdint.h>
#define TSIG_DATETIME_NOT_SOON UINT32_MAX
#define TSIG_DATETIME_MSECS_DAY 86400000
#define TSIG_DATETIME_MSECS_HOUR 3600000
#define TSIG_DATETIME_MSECS_MIN 60000
/**
* Date and time. Presented in a friendlier manner than a raw timestamp.
* @note The original timestamp used to initialize this struct is found in
* `timestamp`. Partial milliseconds are not preserved in `msec`.
*/
typedef struct tsig_datetime_t {
double timestamp; /** Unix timestamp in milliseconds. */
uint16_t year; /** Year (0 and up). */
uint8_t mon; /** Month (1-12). */
uint8_t day; /** Day of month (1-31). */
uint16_t doy; /** Day of year (1-366). */
uint8_t dow; /** Day of week (0-6, Sunday-Saturday). */
uint8_t hour; /** Hour (0-23). */
uint8_t min; /** Minute (0-59). */
uint8_t sec; /** Second (0-59). */
uint16_t msec; /** Millisecond (0-999). */
} tsig_datetime_t;
#ifdef TSIG_DEBUG
static void datetime_print(tsig_datetime_t datetime) {
printf("datetime = {\n");
printf(" .year = %u\n", datetime.year);
printf(" .mon = %u\n", datetime.mon);
printf(" .day = %u\n", datetime.day);
printf(" .doy = %u\n", datetime.doy);
printf(" .dow = %u\n", datetime.dow);
printf(" .hour = %u\n", datetime.hour);
printf(" .min = %u\n", datetime.min);
printf(" .sec = %u\n", datetime.sec);
printf(" .msec = %u\n", datetime.msec);
printf("};\n");
}
#endif /* TSIG_DEBUG */
/**
* Determine whether a year is a leap year.
* @param year Gregorian year.
* @return Whether the year is a Gregorian leap year.
*/
uint8_t tsig_datetime_is_leap(uint16_t year) {
return !(year % 4) && ((year % 100) || !(year % 400));
}
/**
* Parse a timestamp into a date and time.
* @param timestamp Unix timestamp in milliseconds.
* @return A tsig_datetime_t structure.
*/
tsig_datetime_t tsig_datetime_parse_timestamp(double timestamp) {
tsig_datetime_t datetime = {.timestamp = timestamp};
uint64_t msec = timestamp;
/*
* Certain date calculations are simplified by shifting the
* epoch to begin on March 1, 0000 instead of January 1, 1970.
* cf. https://howardhinnant.github.io/date_algorithms.html
*/
uint64_t day = msec / TSIG_DATETIME_MSECS_DAY;
uint64_t dse = day + 719468;
uint32_t era = dse / 146097;
uint32_t doe = dse - era * 146097;
uint32_t yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
uint32_t y = yoe + era * 400;
uint32_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
uint32_t m = (5 * doy + 2) / 153;
datetime.year = y + (m >= 10);
datetime.mon = m < 10 ? m + 3 : m - 9; /* 1-12 */
datetime.day = doy - (153 * m + 2) / 5 + 1; /* 1-31 */
datetime.doy =
m < 10 ? doy + 60 + tsig_datetime_is_leap(datetime.year) : doy - 305;
datetime.dow = (day + 4) % 7;
datetime.hour = (msec %= TSIG_DATETIME_MSECS_DAY) / TSIG_DATETIME_MSECS_HOUR;
datetime.min = (msec %= TSIG_DATETIME_MSECS_HOUR) / TSIG_DATETIME_MSECS_MIN;
datetime.sec = (msec %= TSIG_DATETIME_MSECS_MIN) / 1000;
datetime.msec = msec % 1000;
return datetime;
}
/**
* Check if Summer Time is in effect in Germany or the United Kingdom.
*
* For Germany and the UK, as well as for many other countries in Europe,
* summer time begins/ends at 01:00 UTC on the last Sunday of March/October.
*
* @param datetime UTC datetime to be checked.
* @param[out] out_in_mins Optional out pointer to the count of minutes
* remaining until the next changeover at the beginning of the provided
* minute. `TSIG_DATETIME_NOT_SOON`, a large value, is stored if the next
* changeover will occur in more than 25 hours.
* @return Whether CEST/BST are in effect in Germany/the UK at `datetime`.
*/
uint8_t tsig_datetime_is_eu_dst(tsig_datetime_t datetime,
uint32_t *out_in_mins) {
uint32_t in_mins = TSIG_DATETIME_NOT_SOON;
uint8_t mon = datetime.mon;
uint8_t is_est = 0;
if (3 < mon && mon < 10) {
is_est = 1;
} else if (mon == 3 || mon == 10) {
uint8_t hour = datetime.hour;
uint8_t min = datetime.min;
uint8_t day = datetime.day;
uint8_t dow = datetime.dow;
uint8_t fsom = (((day - 1) + (dow ? 7 - dow : 0)) % 7) + 1;
uint8_t lsom = fsom + ((31 - fsom) / 7) * 7;
uint8_t is_changed = (day == lsom && hour >= 1) || day > lsom;
is_est = (mon == 3) != is_changed;
if (day == lsom - 1)
in_mins = 60 * (24 - hour) + 60 - min;
else if (day == lsom && hour < 1)
in_mins = 60 - min;
}
if (out_in_mins)
*out_in_mins = in_mins;
return is_est;
}
/**
* Check if Daylight Saving Time is in effect in the United States.
*
* Daylight Saving Time begins/ends at 02:00 local time on the second Sunday
* of March/the first Sunday of November.
*
* @param datetime UTC datetime to be checked.
* @param[out] out_end Optional out pointer to whether DST will be in effect
* at the end of the provided UTC day.
* @return Whether DST is in effect in the United States at the beginning of
* the provided UTC day.
*/
uint8_t tsig_datetime_is_us_dst(tsig_datetime_t datetime, uint8_t *out_end) {
uint8_t mon = datetime.mon;
uint8_t is_dst_end = 0;
uint8_t is_dst = 0;
if (3 < mon && mon < 11) {
is_dst_end = 1;
is_dst = 1;
} else if (mon == 3 || mon == 11) {
uint8_t sunday = mon == 3 ? 8 : 1;
uint8_t hour = datetime.hour;
uint8_t day = datetime.day;
uint8_t dow = datetime.dow;
uint8_t change_day = (((day - 1) + (dow ? 7 - dow : 0)) % 7) + sunday;
is_dst_end = mon == 3 ? day >= change_day : day < change_day;
is_dst = mon == 3 ? day > change_day : day <= change_day;
}
if (out_end)
*out_end = is_dst_end;
return is_dst;
}
|
import psycopg2
from psycopg2 import Error
# Function to establish a connection to the PostgreSQL database
def create_connection(db_name, user, password, host, port):
connection = None
try:
connection = psycopg2.connect(
dbname=db_name,
user=user,
password=password,
host=host,
port=port
)
print("Connection to the database successful")
except Error as e:
print(f"The error '{e}' occurred")
return connection
# Function to insert a record into the database
def insert_record(connection, record):
cursor = connection.cursor()
try:
cursor.execute("""
INSERT INTO til.notes (start_message_id, telegram_user_id, telegram_username, telegram_first_name, telegram_last_name, doc_text, telegram_creation_date)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""", record)
connection.commit()
print("Record inserted successfully")
except Error as e:
connection.rollback()
print(f"The error '{e}' occurred")
# Function to read records from the database
def read_records(connection):
cursor = connection.cursor()
try:
cursor.execute("SELECT * FROM til.notes")
records = cursor.fetchall()
print("Retrieved records:")
for record in records:
print(record)
except Error as e:
print(f"The error '{e}' occurred")
# Function to update doc_text for a given start_message_id
def update_doc_text(connection, telegram_user_id, new_doc_text):
cursor = connection.cursor()
try:
cursor.execute("""
UPDATE til.notes
SET doc_text = doc_text || '\n' || %s
WHERE telegram_user_id = %s AND is_draft = true
""", (new_doc_text, telegram_user_id))
connection.commit()
print("Doc_text updated successfully")
except Error as e:
connection.rollback()
print(f"The error '{e}' occurred")
# Function to retrieve a draft message by telegram_user_id
def retrieve_draft_message(connection, telegram_user_id):
cursor = connection.cursor()
try:
cursor.execute("""
SELECT * FROM til.notes
WHERE telegram_user_id = %s AND is_draft = true
""", (telegram_user_id,))
record = cursor.fetchone()
return record
# print("Retrieved record:")
# print(record)
except Error as e:
print(f"The error '{e}' occurred")
# Function to retrieve a draft message by telegram_user_id
def retrieve_user_messages(connection, telegram_username):
cursor = connection.cursor()
try:
cursor.execute("""
SELECT * FROM til.notes
WHERE telegram_username = %s AND is_draft = true
""", (telegram_username,))
record = cursor.fetchone()
return record
# print("Retrieved record:")
# print(record)
except Error as e:
print(f"The error '{e}' occurred")
# Function to update doc_text for a given start_message_id
def mark_note_as_completed(connection, telegram_user_id):
cursor = connection.cursor()
try:
cursor.execute("""
UPDATE til.notes
SET is_draft = false
WHERE telegram_user_id = %s AND is_draft = true
""", (telegram_user_id, ))
connection.commit()
print("Doc_text updated successfully")
except Error as e:
connection.rollback()
print(f"The error '{e}' occurred")
# Example usage
if __name__ == "__main__":
# Modify these variables according to your database configuration
dbname = os.getenv('NEXT_DBNAME')
user = os.getenv('NEXT_DB_USER')
password = os.getenv('NEXT_DB_PASSWORD')
host = os.getenv('NEXT_DB_HOST')
port = os.getenv('NEXT_DB_PORT')
# Sample record to insert
record_to_insert = (12345, 1620133321, "johndoe", "John", "Doe", "Sample document text", 123456789)
# Connect to the database
connection = create_connection(dbname, user, password, host, port)
if connection:
# Insert a record
insert_record(connection, record_to_insert)
# Update doc_text for a given start_message_id
update_doc_text(connection, 12345, "Updated document text")
# Read records
read_records(connection)
# Close the connection
connection.close()
|
#ifndef Account_h
#define Account_h
#include "Fund.h"
#include "Transaction.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Account
{
static const int MAX_FUNDS = 10;
public:
Account();
~Account();
Account(string firstName, string lastName, int accNum);
// access fund with fundID and add amount
bool addFunds(int fundID, int amount);
// access fund with fundID and remove amount
bool removeFunds(int fundID, int amount);
// bool add(int fundID, int amount);
// bool remove(int fundID, int amount);
// bool recordTransaction(char identifier, int accNum, int fundID, int amount, int transAccNum, int transFundID, bool validTransaction);
// if transfer is not possible between funds
// return false
// transfer amount from fundID to transFundID
bool transferFunds(int fundID, int transFundID, int amount);
bool transferRemove(int fundID, int amount);
bool transferAdd(int fundID, int amount);
void recordTrans(Transaction t, int fundID);
bool transfer(Account acc1, Account acc2, int fundID, int transFundID, int amount);
// transfer amount for joint funds
bool withdrawFromJointFunds(int fundIDX, int fundIDY, int amount);
// prints fund history
void printFundHistory(int fundID);
// print entire account transaction history
void printAllHistory();
// if an error occurs don't allow the transaction and record it
void error(string firstName, string lastName, int fundID, int amount);
// Setter
void setFundBalance(int fundID);
// Getters
int getAccNum() const;
int getBalance(int fundID) const;
string getFirstName() const;
string getLastName() const;
string getFundName(int fundID) const;
vector<Transaction> getTransactionRecords() const;
friend ostream &operator<<(ostream &out, Account &account);
bool operator==(Account &list);
bool operator<(Account &list);
bool operator>(Account &list);
private:
string firstName;
string lastName;
int accNum;
Fund fundList[MAX_FUNDS];
vector<Transaction> transactionRecords;
};
#endif /* Account_h */
|
### comparing wetland restoration scenarios of different intensity
# from 1% increase in wetland area to 50%
setwd("C:/Users/uryem/OneDrive - University of Waterloo/Desktop/LEB_Wetland_P/Datasets")
library(ggplot2)
library(tidyverse)
library(cowplot)
df <- read.csv("Scenarios/Scenario_compare.csv", stringsAsFactors = TRUE)
df <- df[df$Wetland_percent_increase < 31,]
ggplot(df, aes(x = Wetland_percent_increase, y = P_retention_kg_yr, color = Strategy)) +
geom_point() +
geom_line() +
facet_grid(CWAR~Runoff)
# ggplot(df, aes(x = Wetland_percent_increase, y = P_retention_kg_yr, color = Strategy)) +
# geom_area() +
# #geom_line() +
# facet_grid(CWAR~Runoff)
df <- df %>%
mutate(CWAR = recode(CWAR, "median" = "CWAR", "conservative" = "Small CWAR"))%>%
mutate(Runoff = recode(Runoff, "high" = "High Runoff", "median" = "Median Runoff")) %>%
mutate(Strategy = fct_reorder(Strategy, desc(Strategy)))
tiff(filename = "figures/Fig_scenario_comp.tif", height = 8, width = 16, units = "in", res = 800, compression = "lzw")
ggplot(df, aes(x = Wetland_percent_increase, fill = Strategy)) +
geom_area(aes(y = P_retention_kg_yr/1000000), color = NA, alpha = 1, position = "identity") +
geom_area(aes(y = (-1*P_released_kg_yr)/1000000), color = NA, alpha = 1, position = "identity") +
geom_line(aes(y = P_retention_kg_yr/1000000)) +
geom_line(aes(y = (-1*P_released_kg_yr)/1000000)) +
scale_fill_manual(values = c("#FD8D3C", "#FFFFCD")) +
facet_grid(factor(Runoff)~factor(CWAR, levels = c("CWAR", "Small CWAR")), switch = "y")+
scale_y_continuous(position = "right") +
geom_hline(yintercept=0) +
theme_bw(base_size = 28) +
ylab(expression("P retained (10"^6*" kg/yr)"))+
xlab("Wetland area increase (%)") +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
strip.background = element_rect(fill = "gray99"))
dev.off()
|
import { useEffect, useState } from "react";
import { PaymentListTabs } from "../components/Payment/PaymentListTabs";
import PaymentDetailsTabs from "../components/Payment/PaymentsDetailsTabs";
import Accordion from "../components/Utils/Accordion";
import { useSelector } from "react-redux";
import { Link, useNavigate } from "react-router-dom";
import AddressCard from "../components/Card/AddressCard";
import TrustBagge from "../components/Utils/TrustBagge";
import CartInfoCard from "../components/Card/CartInfoCard";
const Payment = () => {
const { user, activeAddress } = useSelector(state => state.auth);
const { totalPrice } = useSelector(state => state.cart);
const { cartItems } = useSelector(state => state.cart);
const [activeTab, setActiveTab] = useState(4);
const DetailsActiveTab = PaymentDetailsTabs?.[activeTab]?.Component;
const navigate = useNavigate();
useEffect(() => {
if (user?.address?.length === 0) {
navigate('/cart');
}
}, [user])
const addressCard = <div className="flex flex-col gap-2">
<div className="addressType w-full">
{
activeAddress &&
<AddressCard {...activeAddress} />
}
</div>
<Link to={'/account/address'}>
<button className="px-4 py-2 hover:opacity-90 border text-white bg-[#42a2a2] font-semibold rounded-md w-full">CHANGE ADDRESS</button>
</Link>
</div>
const cartProducts = <div className="flex flex-col gap-4 pb-4">
{
cartItems?.map(({ _id, product, quantity }) => (
<CartInfoCard key={_id} quantity={quantity} {...product} />
))
}
</div>
return (
<div className="pt-9 pb-12 bg-[#f7f7f7] lg:bg-white">
<div className="lg:container flex lg:flex-row flex-col-reverse lg:px-4 ">
<div className="pmt-left md:sticky md:top-28 h-max lg:flex-[2] p-4 lg:pr-4 lg:border-r border-[#d6d6d6] bg-white">
<p className="my-3 font-bold">Choose your payment method</p>
<div className="paymentListTabs border flex border-[#d6d6d6] w-full">
<PaymentListTabs activeTab={activeTab} setActiveTab={setActiveTab} />
<div className="paymentTabDetails flex-[2] px-4">
{DetailsActiveTab}
</div>
</div>
</div>
{/* ! right side ! */}
<div className="pmt-right md:flex-1 px-4 lg:px-0 lg:pl-4 mb-4 lg:border-l bg-[#f7f7f7] lg:bg-white border-[#d6d6d6]">
<div className="border bg-white border-[#d6d6d6] px-4 rounded-md mb-4 hover:shadow-md transition-all">
<Accordion initialExpanded={true} title={'Address'} description={addressCard} />
</div>
<div className="border bg-white border-[#d6d6d6] px-4 rounded-md mb-4 hover:shadow-md transition-all">
<Accordion title={'You are paying for these items'} description={cartProducts} />
</div>
<div className="summaryBorderBox md:sticky md:top-24 md:mb-8">
<div className="sectionHeading py-3 px-5 text-xs font-bold">
<h4 className="">PRICE SUMMARY</h4>
</div>
<div className="paymentBox bg-white font-medium">
<div className="pmtsWrap p-4">
<div className="flex justify-between pb-3 text-xs">
<p>Total MRP (Incl. of taxes)</p>
<p>₹{totalPrice}</p>
</div>
<div className="flex justify-between pb-3 text-xs">
<p>Shipping Charges</p>
<p className="text-[#42a2a2]">FREE</p>
</div>
<div className="justify-between pb-3 text-xs hidden">
<p>Discount on MRP</p>
<p>- ₹{totalPrice}</p>
</div>
<div className="flex border-t-2 justify-between py-3 text-sm font-semibold">
<p>Final amount</p>
<p>₹{totalPrice}</p>
</div>
</div>
</div>
<TrustBagge />
</div>
</div>
</div>
</div>
)
}
export default Payment;
|
import torch
import numpy as np
from sentence_transformers import SentenceTransformer, util
from langchain.text_splitter import CharacterTextSplitter
from bs4 import BeautifulSoup
import requests
from PyPDF2 import PdfReader
try:
pdf = PdfReader('./dataset.pdf')
result = ''
for i in range(len(pdf.pages)):
result += pdf.pages[i].extract_text()
except Exception as e:
print('Error:', e)
exit(0)
text_splitter = CharacterTextSplitter(
separator="\n",
chunk_size=1000,
chunk_overlap=200,
length_function=len
)
chunks = text_splitter.split_text(result)
model = SentenceTransformer("sentence_transformer_model")
AI21_api_key = '<Enter API Key>'
url = "https://api.ai21.com/studio/v1/answer"
def query(texts):
embeddings = model.encode(texts)
return embeddings
def get_output_embedding(chunks):
try:
output_embedding = torch.load('output_embedding.pt')
except FileNotFoundError:
output_embedding = query(chunks)
torch.save(output_embedding, 'output_embedding.pt')
return output_embedding
def get_response_from_query(user_query):
question_embedding = query([user_query])
output_embedding = get_output_embedding(chunks)
result = util.semantic_search(question_embedding, output_embedding, top_k=2)
final = [chunks[result[0][i]['corpus_id']] for i in range(len(result[0]))]
payload = {
"context": ' '.join(final),
"question": user_query
}
headers = {
"accept": "application/json",
"content-type": "application/json",
"Authorization": f"Bearer {AI21_api_key}"
}
response = requests.post(url, json=payload, headers=headers)
print("Response", response)
if response.json()['answerInContext']:
return response.json()['answer']
else:
print('The answer is not found in the document ⚠️, '
'please reformulate your question.')
# user_query = "I am sad. What should I do?"
# print(get_response_from_query(user_query))
|
---
tags:
- docker
- public
create: 2024-06-04 09:17:03
---
## 조회
- 입력
```sh
docker volume ls
```
- 출력
```sh
DRIVER VOLUME NAME
local 017e81633e49fe45ddb6bba787e35e1808c6bac4f41cd00de119de5b53fdd29a
local 671ee4a6da4fbbef319421e4b72d86c8b8a7097a87692871f7f6140842dc3464
local c530219b8e489e5120e024a8120f566a53670af51676b6bfe46b4b09f0ceb6d2
```
---
## 생성
```sh
docker volume create myvolume01
```
---
## 정보 출력
- 입력
```sh
docker volume inspect myvolume01
```
- 출력
```sh
[
{
"CreatedAt": "2024-06-04T00:22:24Z",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/myvolume01/_data",
"Name": "myvolume01",
"Options": null,
"Scope": "local"
}
]
```
```ad-important
`"Mountpoint": "/var/lib/docker/volumes/myvolume01/_data"`
요 부분을 실행할 때 씀
```
----
## 컨테이너
### 생성
- 입력
```sh
docker container run -e POSTGRES_PASSWORD=mysecretpassword -v myvolume01:/var/lib/postgresql/data -d postgres
```
- 출력
```sh
e0d2b80f0a0af6ed07b7e0f583873e7c74ffd097960c66c097909345ff671bfb
```
### 조회
- 입력
```sh
docker container ls
```
- 출력
```sh
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
eb8a80dcd9d2 postgres "docker-entrypoint.s…" 5 seconds ago Up 4 seconds 5432/tcp sweet_goodall
```
### 진입
```sh
docker container exec -it eb8a80dcd9d2 /bin/bash
psql -U postgres
```
### Postgres user
#### 생성
- 입력
```sql
CREATE USER cheolwon PASSWORD '1234' SUPERUSER;
postgres=# \du
```
- 출력
```sh
List of roles
Role name | Attributes
-----------+------------------------------------------------------------
cheolwon | Superuser
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS
```
### 삭제
#### 아이디 확인
- 입력
```sh
docker container ls
```
- 출력
```
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
39e32b2aaf25 postgres "docker-entrypoint.s…" 4 minutes ago Up 55 seconds 5432/tcp some-postgres
```
#### 실행
- 입력
```sh
docker container stop 39e32b2aaf25
docker container rm 39e32b2aaf25
```
- 출력
```sh
39e32b2aaf25
```
### 재실행
[[#컨테이너]]
### 컨테이너 조회
- 입력
```sh
docker container ls
```
- 출력
```sh
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
666c91149b9d postgres "docker-entrypoint.s…" About a minute ago Up About a minute 5432/tcp sweet_mccarthy
ubuntu@ip-172-31-8-194:~$ docker container exec -it 666c91149b9d /bin/bash
```
### postgres user list 조회
- 입력
```sh
psql -U postgres
postgres=# psql
postgres-# \du
```
- 출력
```sh
List of roles
Role name | Attributes
-----------+------------------------------------------------------------
cheolwon | Superuser
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS
```
```ad-note
컨테이너를 삭제 했음에도 불구하고 psql의 cheolwon 계정이 살아있다.
```
---
## 확인
### Mountpoint
- 입력
```sh
docker volume inspect myvolume01
```
- 출력
```sh
[
{
"CreatedAt": "2024-06-04T00:22:24Z",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/myvolume01/_data",
"Name": "myvolume01",
"Options": null,
"Scope": "local"
}
]
```
```ad-check
title: 이 부분 확인
`"Mountpoint": "/var/lib/docker/volumes/myvolume01/_data"`
```
### 진입
- 입력
```sh
sudo -i
cd /var/lib/docker/volumes/myvolume01/_dat
ls
```
- 출력
```sh
PG_VERSION pg_dynshmem pg_multixact pg_snapshots pg_tblspc postgresql.auto.conf
base pg_hba.conf pg_notify pg_stat pg_twophase postgresql.conf
global pg_ident.conf pg_replslot pg_stat_tmp pg_wal postmaster.opts
pg_commit_ts pg_logical pg_serial pg_subtrans pg_xact
```
|
package entities;
import jakarta.persistence.*;
import java.util.Set;
@Entity
@Table(name = "teachers")
public class Teacher extends Person {
@Column(nullable = false, unique = true)
private String email;
@Column(name = "salary_per_hour", nullable = false)
private float salaryPerHour;
@OneToMany
@JoinColumn(name = "course_id", referencedColumnName = "id")
private Set<Course> courses;
public Teacher() {
super();
}
public Teacher(String firstName, String lastName, String phoneNumber, String email, float salaryPerHour) {
super(firstName, lastName, phoneNumber);
this.email = email;
this.salaryPerHour = salaryPerHour;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public float getSalaryPerHour() {
return salaryPerHour;
}
public void setSalaryPerHour(float salaryPerHour) {
this.salaryPerHour = salaryPerHour;
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
background-color:#56b7dd;
background-image:linear-gradient(1000deg,#4e5ac9 0%,#8945b6 100%);
display:flex;
flex-direction:column;
align-items:center;
line-height:2;
text-align: center;
}
form{
background-color:whitesmoke;
max-width:360px;
width:100%;
padding: 58px 45px;
border-radius: 5px;
box-shadow: 0 0 5px 0 rgba(185, 148, 207, 0.9);
}
.row{
display:flex;
flex-direction:column;
margin-bottom: 20px;
}
.row label{
font-size: 17px;
}
.row input{
flex:1;
padding:13px;
border:1px #6dacc4;
border-radius:5px;
}
.btn{
width:100%;
padding:9px;
font-size:13px;
border:none;
border-radius:25px;
background-color: #e0b6e0 ;
cursor:pointer;
margin-top:15px;
}
@media(max-width: 458px){
body{
margin:0 18px;
}
form{
background-color:#efecf5;
border:none;
padding:10px 0;
box-shadow:none;
}
}
</style>
</head>
<body>
<h1>
Login
</h1>
<form onsubmit="return validate()">
<div class="row">
<label>username</label>
<input type="text" id="username" placeholder="enter your name"/>
</div>
<div class="row">
<label>
password
</label>
<input id="password" type="password" placeholder="enter your password"/>
</div>
<button class="btn">login</button>
</form>
<script>
function validate(){
var username=document.getElementById("username").value;
var password=document.getElementById("password").value;
var usernameCheck=/^[a-zA-Z0-9]+@[a-z]+\.[a-z]{2,3}$/
var passwordCheck=/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{4,6}$/
console.log(username,password)
if(username=="")
{
alert("please enter username")
return false
}
if(!username.match(usernameCheck))
{ alert("check your username")
return false
}
if(!password.match(passwordCheck))
{ alert("password must carry one uppercase,lowercase and a number")
return false
}
return true
}
</script>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bai+Jamjuree:wght@400;600&family=Open+Sans:wght@300;400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/style.css" />
<title>Clipboard Website</title>
</head>
<body>
<!-- Hero Section -->
<section id="hero">
<div class="section-container mb-40 pt-16">
<img src="images/logo.svg" alt="" class="mx-auto my-16">
<!-- Button Container -->
<div class="btn-container">
<a href="#" class="btn-download bg-strongCyan p-4 px-8 rounded-full shadow-lg duration-200 hover:opacity-80">Download For iOS</a>
<a href="#" class="btn-download bg-lightBlue p-4 px-8 rounded-full shadow-lg duration-200 hover:opacity-80">Download For Windows</a>
</div>
</div>
</section>
<!-- Snippets -->
<section id="snippets">
<div class="section-container my-20">
<h3>
Keep track of your snippets.
</h3>
<p class="section-content text-xl mb-24">
Clipboard instantly stores any item you copy in the cloud, meaning you can access your snippets immediately on all your devices. Our iOS and Windows apps will help you organise everything.
</p>
</div>
</section>
<!-- Features -->
<section id="features">
<div class="section-container my-20">
<div class="relative flex flex-col md:flex-row md:space-x-32">
<!-- Image -->
<div class="md:w-1/2">
<img src="./images/image-computer.png" alt="" class="md:absolute top-0 right-[50%]">
</div>
<!-- Items Container -->
<div class="flex flex-col mt-16 mb-24 space-y-12 text-xl md:mb-60 md:text-left md:pl-16 md:w-1/2">
<!-- Item 1 -->
<div>
<h5>Quick Search</h5>
<p class="max-w-md text-grayishBlue">
Easily search your snippets by content, category, web address, application and more.
</p>
</div>
<!-- Item 2 -->
<div>
<h5>iCloud Sync</h5>
<p class="max-w-md text-grayishBlue">
Instantly saves and syncs snippets across all of your devices.
</p>
</div>
<!-- Item 3 -->
<div>
<h5>Complete History</h5>
<p class="max-w-md text-grayishBlue">
Retrieve any snippets from the moment you started using the app.
</p>
</div>
</section>
<!-- Access Anywhere -->
<section id="access">
<div class="section-container my-20">
<h3>
Access Clipboard Anywhere
</h3>
<p class="section-content text-xl mb-24">
Whether you're on the go or at your computer, you can access all your Clipboard snippets in just a few clicks.
</p>
<img src="images/image-devices.png" alt="" class="mx-auto">
</div>
</section>
<!-- Supercharge -->
<section id="supercharge">
<div class="section-container my-20">
<h3>Supercharge your workflow</h3>
<p class="section-content text-xl mb-16">
We've got the tools to boost your productivity.
</p>
<!-- Items Container -->
<div class="flex flex-col items-center justify-between space-y-16 md:flex-row md:space-y-0 md:space-x-12">
<!-- Item 1 -->
<div class="flex flex-col items-center space-y-5">
<img src="images/icon-blacklist.svg" alt="" class="mb-6">
<h5>Create Blacklists</h5>
<p class="max-w-md text-grayishBlue">
Easily create blacklists and more.
</p>
</div>
<!-- Item 2 -->
<div class="flex flex-col items-center space-y-5">
<img src="images/icon-text.svg" alt="" class="mb-6">
<h5>Plain Text Snippets</h5>
<p class="max-w-md text-grayishBlue">
Remove unwanted formatting for a clean, consistent look.
</p>
</div>
<!-- Item 3 -->
<div class="flex flex-col items-center space-y-5">
<img src="images/icon-preview.svg" alt="" class="mb-6">
<h5>Sneak Preview</h5>
<p class="max-w-md text-grayishBlue">
Quick preview of a snippet for easy access.
</p>
</div>
</div>
</div>
</section>
<!-- References -->
<section id="references">
<div class="flex flex-col items-center justify-between max-w-6xl px-10 mx-auto space-y-16 my-44 md:flex-row md:space-y-0">
<img src="images/logo-google.png" alt="">
<img src="images/logo-ibm.png" alt="">
<img src="images/logo-microsoft.png" alt="">
<img src="images/logo-hp.png" alt="">
<img src="images/logo-vector-graphics.png" alt="">
</div>
</section>
<!-- Bottom CTA Section -->
<section id="bottom">
<div class="section-container my-20">
<h3>Clipboard for iOS and Windows</h3>
<p class="section-content text-xl mb-10">
Available for free on the App Store. Download for Windows or iOS and sync with your iCloud or Windows Cloud.
</p>
<!-- Button Container -->
<div class="btn-container">
<a href="#" class="btn-download bg-strongCyan p-4 px-8 rounded-full shadow-lg duration-200 hover:opacity-80">Download For iOS</a>
<a href="#" class="btn-download bg-lightBlue p-4 px-8 rounded-full shadow-lg duration-200 hover:opacity-80">Download For Windows</a>
</div>
</div>
</section>
<footer class="bg-gray-50">
<div class="section-container">
<div class="flex flex-col items-center justify-between md:flex-row">
<!-- Image -->
<img src="images/logo.svg" alt="" class="scale-50">
<!-- Container for Menus and Social -->
<div class="flex flex-col items-center justify-between flex-1 mb-10 space-y-6 md:flex-row md:mb-0 md:space-y-0 text-grayishBlue">
<!-- Menus -->
<div class="flex flex-col space-y-4 md:flex-row md:ml-24 md:space-x-24 md:space-y-0">
<!-- Menu 1 -->
<div class="flex flex-col space-y-4 text-center md:text-left">
<div>
<a href="#" class="hover:text-strongCyan">FAQs</a>
</div>
<div>
<a href="#" class="hover:text-strongCyan">Contact Us</a>
</div>
</div>
<!-- Menu 2 -->
<div class="flex flex-col space-y-4 text-center md:text-left">
<div>
<a href="#" class="hover:text-strongCyan">Privacy Policy</a>
</div>
<div>
<a href="#" class="hover:text-strongCyan">Disclaimer</a>
</div>
</div>
<!-- Menu 3 -->
<div class="flex flex-col space-y-4 text-center md:text-left">
<div>
<a href="#" class="hover:text-strongCyan ">Press Kit</a>
</div>
<div>
<a href="#" class="hover:text-strongCyan">Install Guide</a>
</div>
</div>
<!-- Social Icons -->
<div class="flex justify-between w-32 py-1">
<a href="#">
<img src="images/icon-facebook.svg" alt="" class="duration-200 ficon">
</a>
<a href="#">
<img src="images/icon-twitter.svg" alt="" class="duration-200 ficon">
</a>
<a href="#">
<img src="images/icon-instagram.svg" alt="" class="duration-200 ficon">
</a>
</div>
</div>
</div>
</footer>
</div>
</div>
</div>
</body>
</html>
|
<template>
<div>
<img
:src="qrImage"
:width="width"
:height="height"
:style="border ? 'border: 1px solid #222' : ''">
</div>
</template>
<script>
/*!
* Copyright (c) 2020-2022 Digital Bazaar, Inc. All rights reserved.
*/
import {computedAsync} from '@vueuse/core';
import qrcode from 'qrcode';
import {toRef} from 'vue';
export default {
name: 'QrCode',
props: {
url: {
type: String,
required: true
},
width: {
type: String,
default: '250px',
required: false
},
height: {
type: String,
default: '250px',
required: false
},
border: {
type: Boolean,
default: true,
required: false
},
},
setup(props) {
const url = toRef(props, 'url');
const qrImage = computedAsync(async () => qrcode.toDataURL(url.value));
return {
qrImage
};
}
};
</script>
<style scoped>
</style>
|
import React, { useEffect } from 'react';
import { styled } from '@mui/system';
import SideBar from './sidebar/SideBar';
import FriendsSideBar from './FriendsSideBar';
import Messenger from './messenger/Messenger';
import AppBar from './AppBar';
import { logout } from '../../utils/auth';
import { connect } from 'react-redux';
import { getActions } from '../../store/actions/authActions';
import { connectWithSocketServer } from '../../sockets/socketConnection';
import Room from './room/Room';
const Wrapper = styled('div')({
width: '100%',
height: '100vh',
display: 'flex',
});
const DashboardPage = ({ isUserInRoom, setUserDetails }) => {
useEffect(() => {
const token = localStorage.getItem('token');
const user = localStorage.getItem('user');
if (!token || !user) {
logout();
} else {
const userDetails = JSON.parse(user);
setUserDetails(userDetails);
connectWithSocketServer(userDetails, token);
}
}, []);
return (
<Wrapper>
<SideBar />
<FriendsSideBar />
<Messenger />
<AppBar />
{isUserInRoom && <Room />}
</Wrapper>
);
};
const mapStateToProps = ({ room }) => ({
...room,
});
const mapActionsToProps = (dispatch) => {
return {
...getActions(dispatch),
};
};
export default connect(mapStateToProps, mapActionsToProps)(DashboardPage);
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
late List _imageName;
late int selectedItem;
@override
void initState() {
// TODO: implement initState
super.initState();
_imageName = [
'images/flower_01.png',
'images/flower_02.png',
'images/flower_03.png',
'images/flower_04.png',
'images/flower_05.png',
'images/flower_06.png'
];
selectedItem = 0;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Picker View로 이미지 선택'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Picker View로 이미지 선택',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: SizedBox(
width: 300,
height: 250,
child: CupertinoPicker(
backgroundColor: Colors.amber,
itemExtent: 30,
scrollController:
FixedExtentScrollController(initialItem: 0),
onSelectedItemChanged: ((value) {
setState(() {
selectedItem = value;
});
}),
children: [
Text(_imageName[0]),
Text(_imageName[1]),
Text(_imageName[2]),
Text(_imageName[3]),
Text(_imageName[4]),
Text(_imageName[5]),
]),
),
),
Text('Selected Item : ${_imageName[selectedItem]}'),
Image.asset(
'${_imageName[selectedItem]}',
width: 200,
height: 200,
),
],
),
),
);
}
}
|
package com.example.exception.advice;
import com.example.exception.errors.MyException;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExceptionControllerAdvice {
@ExceptionHandler(value = java.lang.Exception.class)
public ResponseEntity exception(java.lang.Exception e){ // 리턴타입 json
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); // 500번대 에러
}
@ExceptionHandler(value = ConstraintViolationException.class) // 흔히 걸리는 익셉션 이 익셉션을 상속받는 익셉션들은 글로벌하게 이 핸들러로 빠진다.
public ResponseEntity constraintViolationException(ConstraintViolationException e){
return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage()); // 400 번대 에러
}
@ExceptionHandler(value = MyException.class)
public ResponseEntity myException(java.lang.Exception e){
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
}
}
|
#include "menu.h"
Item::Item(const std::string& name, const std::function<void()>& action) : name(name), action(action) {}
Menu::Menu(const std::string& name, const std::string& close_option, const std::vector<Item>& v_items) :
name(name), close_option(close_option), v_items(v_items) {}
void Menu::display(const std::string& message = "") const {
std::cout << name << '\n';
for (size_t i = 0; i < v_items.size(); ++i)
std::cout << i + 1 << ". " << v_items[i].name << '\n';
std::cout << 0 << ". " << close_option << '\n';
if (!message.empty())
std::cout << "Message: " << message << '\n';
}
bool Menu::execute_request(const int& request) const {
if (request > 0 && request <= v_items.size())
v_items[request - 1].action();
else if (request != 0)
throw std::out_of_range("There is no option with this number");
return request == 0;
}
size_t select_option() {
int request;
std::cout << "Select: ";
InputError input_error = input(std::cin, request);
if (input_error != InputError::ERROR_NORMAL) {
if (input_error == InputError::ERROR_INVALID || input_error == InputError::ERROR_TRASH)
throw std::invalid_argument("Invalid value was entered");
else
throw std::invalid_argument("Nothing was entered");
}
return request;
}
void menu_process(const Menu& menu) {
bool is_close = false;
std::string message;
do {
system("cls");
menu.display(message);
try {
message = "";
size_t request = select_option();
is_close = menu.execute_request(request);
}
catch (std::exception& ex) {
message = ex.what();
}
} while (!is_close);
}
|
//OBJETOS EN JAVASCRIPT
//Creacion de objetos
// La forma mas comun de crear objetos es usando la notación de llaves {}
let persona = {
nombre: "Juan",
edad: 30,
saludar: function() {
console.log("Hola, me llamo " + this.nombre);
}
};
//Tambien podemos usar un metodo constructor 'Object'
let persona2 = new Object();
persona2.nombre = "Juan";
persona2.edad = 30;
persona2.saludar = function() {
console.log("Hola, me llamo " + this.nombre);
};
//Propiedades y metodos de los objetos
/* Las propiedades de un objeto son características o atributos que describen el estado o las características de ese objeto. En programación orientada a objetos, las propiedades se utilizan para almacenar datos relacionados con el objeto. A continuación te explico con un ejemplo en JavaScript: */
// Se pueden acceder a las propiedades de un objeto utilizando la notaccion de corchetes
// Definición de un objeto coche con sus propiedades
const coche = {
marca: "Toyota", // esto son las propiedades del coche
modelo: "Corolla",
año: 2021
};
// Accediendo a las propiedades del objeto
console.log(coche.marca); // "Toyota"
console.log(coche.modelo); // "Corolla"
console.log(coche.año); // 2021
// Como se usan las propiedades
/*
1.- Acceder a las Propiedades: Puedes acceder a una propiedad del objeto utilizando el punto (.) seguido del nombre de la propiedad.
2.- Modificar las Propiedades: También puedes cambiar el valor de una propiedad asignándole un nuevo valor.
*/
// Modificar una propiedad del objeto
coche.año = 2022;
console.log(coche.año); // 2022
//Eliminar propiedad
delete persona.ciudad;
/*
Los métodos son funciones asociadas a un objeto. En programación orientada a objetos, los métodos permiten que los objetos realicen acciones o comportamientos. Los métodos pueden acceder y modificar las propiedades del objeto, y pueden recibir parámetros para realizar tareas específicas.
*/
// Definición de un objeto coche con propiedades y métodos
const coche = {
marca: "Toyota",
modelo: "Corolla",
año: 2021,
// Método para arrancar el coche
arrancar: function() {
console.log("El coche ha arrancado.");
},
// Método para detener el coche
detener: function() {
console.log("El coche se ha detenido.");
}
};
// Usando los métodos del objeto
coche.arrancar(); // "El coche ha arrancado."
coche.detener(); // "El coche se ha detenido."
/*
Propiedades: marca, modelo, año (almacenan información sobre el coche).
Métodos: arrancar, detener (realizan acciones relacionadas con el coche).
*/
// Iterar entre las propiedades de un objeto
// for...in es una manera directa de iterar sobre las propiedades enumerables de un objeto
const coche = {
marca: "Toyota",
modelo: "Corolla",
año: 2021
};
for (let propiedad in coche) {
console.log(`${propiedad}: ${coche[propiedad]}`);
}
// Salida:
// marca: Toyota
// modelo: Corolla
// año: 2021
// Object.keys() Devuelve un array de las propiedades enumerables propias del objeto. Puedes usar este array con forEach u otro tipo de bucle
const propiedades = Object.keys(coche);
propiedades.forEach(propiedad => {
console.log(`${propiedad}: ${coche[propiedad]}`);
});
// Salida:
// marca: Toyota
// modelo: Corolla
// año: 2021
// Object.entries() devuelve un array de pares [clave, valor] de las propiedades enumerables propias del objeto.
Object.entries(coche).forEach(([propiedad, valor]) => {
console.log(`${propiedad}: ${valor}`);
});
// Salida:
// marca: Toyota
// modelo: Corolla
// año: 2021
//Métodos utiles para Objetos
// Object.keys() Retorna un array con las claves (propiedades) del objeto.
let propiedades = Object.keys(persona);
console.log(propiedades); // ["nombre", "edad", "apellido"]
//Object.values() Retorna un array con los valores de las propiedades del objeto.
let valores = Object.values(persona);
console.log(valores); // ["Carlos", 31, "Pérez"]
// Object.entries() Retorna un array de arrays, cada uno con la clave y el valor de las propiedades del objeto.
let entradas = Object.entries(persona);
console.log(entradas); // [["nombre", "Carlos"], ["edad", 31], ["apellido", "Pérez"]]
// Object.assign() Copia todas las propiedades enumerables de uno o más objetos fuente a un objeto destino.
let destino = {};
let fuente = { a: 1, b: 2 };
Object.assign(destino, fuente);
console.log(destino); // { a: 1, b: 2 }
//Ejercicios
let estudiante = {
nombre: "Ana",
edad: 20,
curso: "Matemáticas"
};
estudiante.curso = "Física";
estudiante.notaFinal = 95;
console.log(estudiante);
estudiante.describir = function() {
console.log(`Estudiante: ${this.nombre}, Edad: ${this.edad}, Curso: ${this.curso}, Nota Final: ${this.notaFinal}`);
};
estudiante.describir();
for (let propiedad in estudiante) {
console.log(`${propiedad}: ${estudiante[propiedad]}`);
}
|
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { ARInvoice, ARLineItem } from '@services/app-layer/entities/accounts-receivable';
import { ARInvoiceStateEnum, ARLineItemTypeEnum } from '@services/app-layer/app-layer.enums';
import { AccountEntity } from '@services/app-layer/entities/account';
import { ObjectUtil } from '@services/helpers/utils/object-util';
import { Environment } from '@services/app-layer/app-layer.environment';
@Component({
selector: 'app-ar-line-item-form',
templateUrl: './ar-line-item-form.component.html',
styleUrls: ['./ar-line-item-form.component.scss']
})
export class ARLineItemFormComponent implements OnInit, OnDestroy {
@Input() parentForm: FormGroup;
@Input() accounts: AccountEntity[] = [];
@Input() invoice: ARInvoice;
@Input() editMode = false;
@Input() set lineItemData(value: ARLineItem) {
this._lineItemData = value;
}
get lineItemData(): ARLineItem {
return this._lineItemData;
}
constructor(private fb: FormBuilder) {}
private _lineItemData: ARLineItem;
public form: FormGroup;
receivableFormGroup: FormGroup;
revenueAccount: FormControl;
wipAccount: FormControl;
receivableAmount: FormControl;
costOfSaleFormGroup: FormGroup;
cogAccount: FormControl;
valueAccount: FormControl;
costOfSaleAmount: FormControl;
public initialData: ARLineItem;
readonly types = ObjectUtil.enumToArray(ARLineItemTypeEnum);
private destroy$ = new Subject<void>();
ngOnInit() {
this.initForm();
this.extendParentFormGroup();
if (this.editMode) {
this.setInitialData();
} else {
this.accounts = this.accounts.filter(item => !item.system && !item.archived);
}
}
public ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.unsubscribe();
this.removeCurrentFormControl();
}
archivedAccountValidator = (control: FormControl) =>
this.isArchivedAccount(control.value) ? { system: 'Archived account is not allowed' } : null;
isArchivedAccount(accountId: string) {
return this.accounts.find(item => item.id === accountId)?.archived || false;
}
private initForm() {
this.revenueAccount = new FormControl(null, [Validators.required, this.archivedAccountValidator]);
this.wipAccount = new FormControl(null, [Validators.required, this.archivedAccountValidator]);
this.receivableAmount = new FormControl(0, [
Validators.required,
Validators.min(0),
Validators.max(Environment.maxSafeNumber)
]);
this.cogAccount = new FormControl(null, [Validators.required, this.archivedAccountValidator]);
this.valueAccount = new FormControl(null, [Validators.required, this.archivedAccountValidator]);
this.costOfSaleAmount = new FormControl(0, [
Validators.required,
Validators.min(0),
Validators.max(Environment.maxSafeNumber)
]);
this.receivableFormGroup = new FormGroup({
revenueAccount: this.revenueAccount,
wipAccount: this.wipAccount,
amount: this.receivableAmount,
currency: new FormControl('USD')
});
this.costOfSaleFormGroup = new FormGroup({
cogAccount: this.cogAccount,
valueAccount: this.valueAccount,
amount: this.costOfSaleAmount,
currency: new FormControl('USD')
});
const config = {
type: ['', Validators.required],
quantity: [null, [Validators.required, Validators.min(1), Validators.max(Environment.maxIntegerSafeNumber)]],
receivable: this.receivableFormGroup,
costOfSale: this.costOfSaleFormGroup,
poRef: [{ value: null, disabled: true }, Validators.required],
description: ['', [Validators.required, Validators.maxLength(500)]]
};
this.form = this.fb.group(config);
this.form
.get('type')
.valueChanges.pipe(takeUntil(this.destroy$))
.subscribe(type => this.onTypeChange(type));
this.revenueAccount.valueChanges
.pipe(takeUntil(this.destroy$))
.subscribe(revenueAccount => this.onReceivableAccountChange(revenueAccount, this.wipAccount));
this.wipAccount.valueChanges
.pipe(takeUntil(this.destroy$))
.subscribe(wipAccount => this.onReceivableAccountChange(wipAccount, this.revenueAccount));
}
private onTypeChange(type: ARLineItemTypeEnum) {
if (type === ARLineItemTypeEnum.INTERNAL_EXPENSE) {
this.receivableFormGroup.disable();
this.receivableFormGroup.reset({ amount: 0, currency: 'USD' });
} else if (type === ARLineItemTypeEnum.CUSTOMER_PAID_EXPENSE) {
this.enableReceivableAccountControl(this.revenueAccount, this.wipAccount);
this.enableReceivableAccountControl(this.wipAccount, this.revenueAccount);
this.receivableAmount.enable();
this.receivableFormGroup.get('currency').enable();
this.receivableAmount.setValidators([Validators.min(0), Validators.max(Environment.maxSafeNumber)]);
} else {
this.enableReceivableAccountControl(this.revenueAccount, this.wipAccount, true);
this.enableReceivableAccountControl(this.wipAccount, this.revenueAccount, true);
this.receivableAmount.enable();
this.receivableFormGroup.get('currency').enable();
this.receivableAmount.setValidators([
Validators.required,
Validators.min(0),
Validators.max(Environment.maxSafeNumber)
]);
}
}
private onReceivableAccountChange(account, formControl: FormControl) {
const isNotInternalExpense = this.form.get('type').value !== ARLineItemTypeEnum.INTERNAL_EXPENSE;
this.receivableAmount.setValidators([
Validators.required,
Validators.min(0),
Validators.max(Environment.maxSafeNumber)
]);
if (account && !formControl.disabled) {
formControl.clearValidators();
formControl.disable();
} else if (isNotInternalExpense && !account && formControl.disabled) {
formControl.enable();
formControl.setValidators([Validators.required, this.archivedAccountValidator]);
}
}
private enableReceivableAccountControl(formControl: FormControl, relatedFormControl: FormControl, require = false) {
if (!relatedFormControl?.value) {
formControl.enable();
if (require) {
formControl.setValidators([Validators.required]);
} else {
formControl.clearValidators();
}
}
}
private setInitialData(): void {
const { receivable, costOfSale } = this.lineItemData;
const accountIds = [
receivable?.revenueAccount,
receivable?.wipAccount,
costOfSale?.cogAccount,
costOfSale?.valueAccount
];
this.accounts = this.accounts.filter(item => accountIds.includes(item.id) || (!item.system && !item.archived));
this.form.patchValue(this.lineItemData);
}
private extendParentFormGroup(): void {
this.parentForm.addControl('lineItem', this.form || new FormGroup({}));
}
private removeCurrentFormControl(): void {
this.parentForm.removeControl('lineItem');
}
typeOptionDisabledTooltip(type: ARLineItemTypeEnum) {
switch (type) {
case ARLineItemTypeEnum.INVENTORY:
return 'Inventory is not available for manual entry';
case ARLineItemTypeEnum.SERVICE:
case ARLineItemTypeEnum.CUSTOMER_PAID_EXPENSE: {
const currentInvoiceState = this.invoice?.state;
if (currentInvoiceState === ARInvoiceStateEnum.ISSUED) {
return 'Only INTERNAL_EXPENSE line item is accepted for invoice in ISSUED state.';
}
break;
}
default:
return null;
}
}
}
|
package leetcode.medium;
import java.util.List;
import java.util.ArrayList;
import java.lang.Math;
/*
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Constraints:
- 1 <= num1.length, num2.length <= 200
- num1 and num2 consist of digits only.
- Both num1 and num2 do not contain any leading zero, except the number 0 itself.
*/
public class MultiplyStrings {
public String multiply(String num1, String num2) {
List<String> numsToAdd = new ArrayList<>();
for (int i = num2.length() - 1; i >= 0; i--) {
String num = "";
int remainder = 0;
for (int j = num1.length() - 1; j >= 0; j--) {
int result = (Integer.parseInt(String.valueOf(num2.charAt(i))) * Integer.parseInt(String.valueOf(num1.charAt(j)))) + remainder;
if (result >= 10) {
num = String.valueOf(result % 10) + num;
remainder = result / 10;
} else {
num = String.valueOf(result) + num;
remainder = 0;
}
}
if (remainder != 0) num = String.valueOf(remainder) + num;
numsToAdd.add(num);
}
// Add the appropriate zeroes on the right side of each number
// Example: [738, 615, 492] becomes [738, 6150, 49200]
for (int i = 0; i < numsToAdd.size(); i++) {
String toAdd = "0".repeat(i);
numsToAdd.set(i, numsToAdd.get(i) + toAdd);
}
// Add the numbers of the list up
String output = numsToAdd.get(0);
for (int i = 1; i < numsToAdd.size(); i++) {
String curr = numsToAdd.get(i);
// Add zeroes on the left side of the shorter number
int maxLength = Math.max(output.length(), curr.length());
output = "0".repeat(maxLength - output.length()) + output;
curr = "0".repeat(maxLength - curr.length()) + curr;
// Add the two numbers up
String currSum = "";
int remainder = 0;
for (int j = maxLength - 1; j >= 0; j--) {
int result = (Integer.parseInt(String.valueOf(output.charAt(j))) + Integer.parseInt(String.valueOf(curr.charAt(j)))) + remainder;
if (result >= 10) {
currSum = String.valueOf(result % 10) + currSum;
remainder = result / 10;
} else {
currSum = String.valueOf(result) + currSum;
remainder = 0;
}
}
if (remainder != 0) currSum = String.valueOf(remainder) + currSum;
output = currSum;
}
// Remove any leftover zeroes on the left side
int subStart = output.length() - 1;
for (int i = 0; i < output.length() - 1; i++) {
if (output.charAt(i) != '0') {
subStart = i;
break;
}
}
return output.substring(subStart, output.length());
}
}
|
function read_flow_file(Storage,filename)
%read_flow_file Чтение векторной карты из .flo файла
% Считывает данные из файла и записывает в класс Storage
% Код взят с Github: https://github.com/seungryong/FCSS
% @InProceedings{kim2017,
% author = {Seungryong Kim and Dongbo Min and Bumsub Ham and Sangryul Jeon and Stephen Lin and Kwanghoon Sohn},
% title = {FCSS: Fully Convolutional Self-Similarity for Dense Semantic Correspondence},
% booktitle = {Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), IEEE},
% year = {2017}}
TAG_FLOAT = 202021.25; % check for this when READING the file
% sanity check
if isempty(filename) == 1
error('readFlowFile: empty filename');
end
idx = strfind(filename, '.');
idx = idx(end);
if length(filename(idx:end)) == 1
error('readFlowFile: extension required in filename %s', filename);
end
if strcmp(filename(idx:end), '.flo') ~= 1
error('readFlowFile: filename %s should have extension ''.flo''', filename);
end
fid = fopen(filename, 'r');
if (fid < 0)
error('readFlowFile: could not open %s', filename);
end
tag = fread(fid, 1, 'float32');
width = fread(fid, 1, 'int32');
height = fread(fid, 1, 'int32');
% sanity check
if (tag ~= TAG_FLOAT)
error('readFlowFile(%s): wrong tag (possibly due to big-endian machine?)', filename);
end
if (width < 1 || width > 99999)
error('readFlowFile(%s): illegal width %d', filename, width);
end
if (height < 1 || height > 99999)
error('readFlowFile(%s): illegal height %d', filename, height);
end
nBands = 2;
% arrange into matrix form
tmp = fread(fid, inf, 'float32');
tmp = reshape(tmp, [width*nBands, height]);
tmp = tmp';
% Запись векторного поля в класс Storage
Storage.vectors_map_last_pass = zeros(height,width,nBands);
Storage.vectors_map_last_pass(:,:,1) = tmp(:, (1:width)*nBands-1);
Storage.vectors_map_last_pass(:,:,2) = tmp(:, (1:width)*nBands);
Storage.vectors_map = Storage.vectors_map_last_pass;
% Инициализация новых масок
size_map = size(Storage.vectors_map,1:2);
Storage.outliers_map = zeros(size_map);
Storage.replaces_map = zeros(size_map);
fclose(fid);
end
|
import os
import json
import getpass
import hashlib
import random
import argparse
try:
from cryptography.fernet import Fernet
except ImportError:
print("The 'cryptography' library is not installed. Please install it using:")
print("pip install cryptography")
exit(1)
# Define the path to the password storage file
PASSWORD_FILE = "passwords.json"
# Check if the password storage file exists, and create it if it doesn't
if not os.path.exists(PASSWORD_FILE):
with open(PASSWORD_FILE, "w") as file:
json.dump({}, file)
# Define functions for encryption and decryption
def generate_key(password):
"""Generate an encryption key based on the user's password."""
password = password.encode()
key = hashlib.sha256(password).digest()
return key
def encrypt(data, key):
"""Encrypt data using Fernet symmetric encryption."""
fernet = Fernet(key)
encrypted_data = fernet.encrypt(data.encode())
return encrypted_data
def decrypt(encrypted_data, key):
"""Decrypt data using Fernet symmetric encryption."""
fernet = Fernet(key)
decrypted_data = fernet.decrypt(encrypted_data).decode()
return decrypted_data
def save_password(service, username, password, key):
"""Save a password in the password storage file."""
with open(PASSWORD_FILE, "r") as file:
passwords = json.load(file)
# Encrypt the password before saving it
encrypted_password = encrypt(password, key)
passwords[service] = {"username": username, "password": encrypted_password}
with open(PASSWORD_FILE, "w") as file:
json.dump(passwords, file)
def get_password(service, key):
"""Retrieve a password from the password storage file."""
with open(PASSWORD_FILE, "r") as file:
passwords = json.load(file)
if service in passwords:
encrypted_password = passwords[service]["password"]
decrypted_password = decrypt(encrypted_password, key)
return decrypted_password
else:
return None
def generate_random_password(length=12):
"""Generate a random password with a specified length."""
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_-+=<>?"
password = "".join([random.choice(characters) for _ in range(length)])
return password
def main():
parser = argparse.ArgumentParser(description="PasswordWizardScript - A user-friendly password manager and generator.")
parser.add_argument("--help", action="help", help="Show this help message and exit.")
args = parser.parse_args()
print("Welcome to PasswordWizardScript!")
password = getpass.getpass("Enter your master password: ")
key = generate_key(password)
while True:
print("\nMenu:")
print("1. Store a new password")
print("2. Retrieve a password")
print("3. Generate a random password")
print("4. Exit")
choice = input("Enter your choice (1/2/3/4): ")
if choice == "1":
service = input("Enter the service name: ")
username = input("Enter your username: ")
password = getpass.getpass("Enter your password: ")
save_password(service, username, password, key)
print("Password saved successfully!")
elif choice == "2":
service = input("Enter the service name: ")
password = get_password(service, key)
if password:
print(f"Password for {service}: {password}")
else:
print("Password not found.")
elif choice == "3":
length = int(input("Enter the length of the password: "))
password = generate_random_password(length)
print(f"Generated password: {password}")
elif choice == "4":
print("Exiting PasswordWizardScript. Goodbye!")
break
else:
print("Invalid choice. Please choose a valid option.")
if __name__ == "__main__":
main()
|
/*
* Copyright(c) 2023 NeatLogic Co., Ltd. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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 neatlogic.module.deploy.api.appconfig.env;
import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.deploy.auth.DEPLOY_BASE;
import neatlogic.framework.deploy.dto.app.DeployAppEnvironmentVo;
import neatlogic.framework.restful.annotation.*;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.module.deploy.dao.mapper.DeployAppConfigMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author longrf
* @date 2022/8/23 15:10
*/
@Service
@AuthAction(action = DEPLOY_BASE.class)
@OperationType(type = OperationTypeEnum.SEARCH)
public class ListDeployAppConfigWithoutConfigEnvApi extends PrivateApiComponentBase {
@Resource
private DeployAppConfigMapper deployAppConfigMapper;
@Override
public String getName() {
return "获取没有继承应用配置的环境列表";
}
@Override
public String getConfig() {
return null;
}
@Override
public String getToken() {
return "deploy/app/config/without/config/env/list";
}
@Input({
@Param(name = "appSystemId", type = ApiParamType.LONG, desc = "应用系统id"),
@Param(name = "appModuleId", type = ApiParamType.LONG, desc = "应用模块id"),
@Param(name = "envId", type = ApiParamType.LONG, desc = "环境id")
})
@Output({
@Param(explode = DeployAppEnvironmentVo[].class, desc = "没有继承应用配置的环境列表")
})
@Description(desc = "获取没有继承应用配置的环境列表(复制配置到现有环境时的环境下拉)")
@Override
public Object myDoService(JSONObject paramObj) throws Exception {
return deployAppConfigMapper.getDeployHasNotConfigAppEnvListByAppSystemIdAndAppModuleIdAndEnvId(paramObj.getLong("appSystemId"), paramObj.getLong("appModuleId"), paramObj.getLong("envId"));
}
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: qdenizar <qdenizar@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/18 10:21:07 by qdenizar #+# #+# */
/* Updated: 2023/09/29 14:39:15 by qdenizar ### ########.fr */
/* */
/* ************************************************************************** */
#include "Zombie.hpp"
int main()
{
std::string buffStack;
std::string buffHeap;
Zombie zombie;
Zombie *zombieH;
std::cout << "\033[32mPauvre fou, tu viens de donner vie a : ";
std::cout << "\033[35mPatrick le papa Zombie du main\033[0m" << std::endl;
std::cout << "\033[32mNow, it's your responsability to feed him" << std::endl;
std::cout << std::endl;
std::cout << "Name the Zombie for the stack 🧟♂️ :" << std::endl;
std::cout << "=> \033[0m";
if (!std::getline(std::cin, buffStack) || buffStack.length() <= 0 || (buffStack.find('\t') != std::string::npos))
{
if ((buffStack.find('\t') != std::string::npos))
{
std::cout << "If you cant name a Zombie, i do the job for you" << std::endl;
zombie.randomChump("Caroline");
}
else if (buffStack.length() <= 0)
{
std::cout << "If you cant name a Zombie, i do the job for you" << std::endl;
zombie.randomChump("Caroline");
}
else
{
std::cout << "Error :invalid name" << std::endl;
return (0);
}
}
else
zombie.randomChump(buffStack);
std::cout << "\033[32m Name the Zombie for the heap 🧟♂️ :" << std::endl;
std::cout << "=> \033[0m";
if (!std::getline(std::cin, buffHeap) || buffHeap.length() <= 0 || (buffHeap.find('\t') != std::string::npos))
{
if ((buffHeap.find('\t') != std::string::npos))
{
std::cout << "If you cant name a Zombie, i do the job for you" << std::endl;
zombieH = zombie.newZombie("Nathan");
zombieH->announce();
delete zombieH;
}
else if (buffHeap.length() <= 0)
{
std::cout << "If you cant name a Zombie, i do the job for you" << std::endl;
zombieH = zombie.newZombie("Ali");
zombieH->announce();
delete zombieH;
}
else
{
std::cout << "Error: invalid name" << std::endl;
return (0);
}
}
else
{
zombieH = zombie.newZombie(buffHeap);
zombieH->announce();
delete zombieH;
}
return (0);
}
|
#ifndef TINYLANG_BACK_TAC_CODEGEN_H_
#define TINYLANG_BACK_TAC_CODEGEN_H_
#include <ostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <cstddef>
#include "back/tac/ir/tac.h"
#include "back/tac/define.h"
#include "back/tac/codegen/tmgen.h"
#include "back/tac/codegen/varalloc.h"
namespace tinylang::back::tac {
class CodeGenerator {
public:
CodeGenerator();
// visitor methods
void GenerateOn(BinaryTAC &tac);
void GenerateOn(UnaryTAC &tac);
void GenerateOn(LoadTAC &tac);
void GenerateOn(StoreTAC &tac);
void GenerateOn(ArgSetTAC &tac);
void GenerateOn(JumpTAC &tac);
void GenerateOn(BranchTAC &tac);
void GenerateOn(CallTAC &tac);
void GenerateOn(ReturnTAC &tac);
void GenerateOn(AssignTAC &tac);
void GenerateOn(VarRefTAC &tac);
void GenerateOn(DataTAC &tac);
void GenerateOn(LabelTAC &tac);
void GenerateOn(ArgGetTAC &tac);
void GenerateOn(NumberTAC &tac);
// run code generation
void Generate();
// dump generated assembly code
void Dump(std::ostream &os);
// set entry function's info
void set_entry(FuncInfo *entry) {
entry_ = entry;
var_alloc_.set_entry_func(entry);
}
// set function info map
void set_funcs(FuncInfoMap *funcs) { funcs_ = funcs; }
// set data info list
void set_datas(DataInfoList *datas) { datas_ = datas; }
private:
// generate all global variables
void GenerateGlobalVars();
// generate all arrays
void GenerateArrayData();
// generate a specific function
void GenerateFunc(const std::string &name, const FuncInfo &info);
// generate info in function's header
void GenerateHeaderInfo();
// generate prologue
void GeneratePrologue(const FuncInfo &info);
// generate epilogue
void GenerateEpilogue();
// put variable name to stream
std::string GetVarName(std::size_t id);
// put data name to stream
std::string GetDataName(std::size_t id);
// put label name to stream
std::string GetLabelName(std::size_t id);
// get current epilogue label and switch to next
std::string NextEpilogueLabel();
// get current epilogue label
std::string GetEpilogueLabel();
// get size of current frame
std::size_t GetFrameSize();
// get TAC's value
TinyMIPSReg GetValue(const TACPtr &tac);
// set register's value to TAC
void SetValue(const TACPtr &tac, TinyMIPSReg value);
// function info of entry function
FuncInfo *entry_;
// function info map in TAC builder
FuncInfoMap *funcs_;
// data info in TAC builder
DataInfoList *datas_;
// string stream of generated code
std::ostringstream code_;
// info of all funtion declarations
std::unordered_map<TACPtr, std::string> decls_;
// assembly code generator of function body
TinyMIPSAsmGen asm_gen_;
// variable allocator
VarAllocationPass var_alloc_;
// last TACs
VarRefTAC *last_var_;
DataTAC *last_data_;
LabelTAC *last_label_;
ArgGetTAC *last_arg_get_;
NumberTAC *last_num_;
// id of epilogue label
std::size_t epilogue_id_;
};
} // namespace tinylang::back::tac
#endif // TINYLANG_BACK_TAC_CODEGEN_H_
|

# bomber
Reinforcement learning project with own gym. This is the self chosen final assignment of an advanced machine learning course at IDSIA, SUPSI Lugano.
## Bomber Environment
Given a simple 10 x 10 gridword, there is an agent surrounded by rocks.
The main goal of the agent is to blast all the rocks.
The agent's actions are moving up, down, left, right and detonate a bomb.
The detonation destroys all rocks within a 3x3 square around the bomb, respectively the agent.
The agent gets a reward for each blasted rock and a special reward when all rocks are destroyed.
On the other side, the agent gets a penalty when colliding with the walls or rocks, when planting a bomb and for each move.
All these environment properties can be customized.
<img src="https://github.com/eidelen/bomber/blob/main/rsc/explanation.png" width="460">
## The Simple Bomber
In the simple bomber case, the bomb blasts immediatly after the agent plants the bomb.
Therefore the agent does not get a penalty when being close to the blasts.
I tried many different varations of learning, like agent dies or gets penalty when colliding with rocks and wall.
<img src="https://github.com/eidelen/bomber/blob/main/rsc/simple-episode.gif" width="365">
## The Reduced Simple Bomber
The reduced simple bomber has the same properties as the above simple bomber.
But the reduced bomber agent only observes its surrounding fields - therefore the observation space is reduced to a patch of 3x3.
This leads to a lack of knowledge for the agent, but also increases the learning speed and most importantly, one agent can be applied on different grid sizes.
<img src="https://github.com/eidelen/bomber/blob/main/rsc/trained6x6-put-6x6.gif" width="270"><img src="https://github.com/eidelen/bomber/blob/main/rsc/trained6x6-put-8x8.gif" width="270"><img src="https://github.com/eidelen/bomber/blob/main/rsc/trained6x6-put-10x10.gif" width="270">
Above agent was trained on a **6x6 grid**, but then also tested on an 8x8 and 10x10 play area.
Unlike the simple bomber, the model here uses an additional LSTM layer.
One can see that the agent isn't performing great on unknown grid sizes.
Next step was to train the agent with reduced observation space on different grid sizes, where the penalties and rewards have to be scaled related to the grid size.
In particular, below agent was trained on randomly selected **6x6 grids** and **8x8 grids**.
This resulted in much better performance on unknown grid.
<img src="https://github.com/eidelen/bomber/blob/main/rsc/6,8x6,8-trained-6x6.gif" width="270"><img src="https://github.com/eidelen/bomber/blob/main/rsc/6,8x6,8-trained-7x7.gif" width="270"><img src="https://github.com/eidelen/bomber/blob/main/rsc/6,8x6,8-trained-8x8.gif" width="270"><img src="https://github.com/eidelen/bomber/blob/main/rsc/6,8x6,8-trained-9x9.gif" width="270"><img src="https://github.com/eidelen/bomber/blob/main/rsc/6,8x6,8-trained-10x10.gif" width="270"><img src="https://github.com/eidelen/bomber/blob/main/rsc/6,8x6,8-trained-12x12.gif" width="270">
Even on ultra large grids the agent performs not bad.
However, it suddenly makes a stupid mistake in an actual easy situation.
<img src="https://github.com/eidelen/bomber/blob/main/rsc/6,8x6,8-trained-20x20.gif" width="450">
## The Smart Bomber
In the smart bomber environment, a bomb is first placed and two steps later, the bomb explodes.
The agent receives a penalty if it is within a certain range of the blast.
Therefore the smart bomber agent escapes the blast after placing the bomb (see image below).
<img src="https://github.com/eidelen/bomber/blob/main/rsc/smartbomber-intro.png" width="450">
The learning performance was best when using a reduced observation space and a LSTM layer.
Below examples is an agent which was trained on 6x6, 8x8 and 10x10 grid sizes.
<img src="https://github.com/eidelen/bomber/blob/main/rsc/smart-bomber6x6.gif" width="350">
<img src="https://github.com/eidelen/bomber/blob/main/rsc/smart-10x10.gif" width="350">
## Installation Notes
### Windows (Python 3.9 and 3.10)
```
python -m venv venv
.\venv\Scripts\activate.ps1 # if problem: Open Powershell as Admin: > Set-ExecutionPolicy RemoteSigned
python -m pip install -U pip
python -m pip install -U setuptools
pip install torch torchvision
pip install -U "ray[rllib]"
pip install tqdm tensorboard matplotlib
```
### OSX
```
python -m venv venv
source venv/bin/activate
python -m pip install -U pip
python -m pip install -U setuptools
pip install torch torchvision
pip install -U "ray[rllib]"
pip install tqdm tensorboard matplotlib
```
|
<h1> [Linux] 리눅스 Web 서비스 : apache </h1>
<h3>📌INDEX</h3>
- [웹 서버란?](#웹-서버란)
- [정적 웹 서버 동작 방식](#정적-웹-서버-동작-방식)
- [동적 웹 서버 동작 방식](#동적-웹-서버-동작-방식)
- [apache](#apache)
- [apache 설정](#apache-설정)
- [apache 구성](#apache-구성)
- [apache 웹페이지 설정](#apache-웹페이지-설정)
- [가상 호스트(Virtual Hosts)](#가상-호스트)
- [실습](#실습)
<br>
<br>
<h2>웹 서버란?</h2>
- **웹(Web) 서버**
- 웹 서비스(Web Service)를 제공하는 서버
- 인터넷만 연결되어 있다면, 어느 곳에서든 웹 서버에 방문 가능
- 네트워크를 통해 약속된 주소로 요쳥 시 지정된 컨텐츠를 제공
- 기본적으로 정적인 컨텐츠만 제공
- 별도의 구성 시 동적인 컨텐츠 제공 가능
- 모듈을 추가함으로써 ex) python, php 등
- **웹 서버의 기본적인 동작**
- 웹 브라우저로 Client가 페이지 요청
- HTTP (Hypertext Transfer Protocol)을 사용하여 웹 브라우저와 웹 서버간 의사소통
- Client가 페이지 요청 시 웹 서버는 요청 받은 페이지를 보내줌
<h4>정적 웹 서버 동작 방식</h4>
- 정적 웹이란?
- 언제나 동일한 값을 표시(static)
- HTTP 서버(SW)가 있는 컴퓨터(하드웨어)로 구성
- 서버가 불려진 파일을 클라이언트의 브라우저로 전송
<img src="https://user-images.githubusercontent.com/64996121/157681662-1dfa7de7-a8da-4df7-95cd-2e7188a9f00b.PNG" width=500 height=220 />
1. 클라이언트 즉, 웹 브라우저를 통해 80번 포트로 웹 서버에 연결
2. 사용자 문서 (index.html)를 요청
3. 웹 서버가 클라이언트가 요청한 파일을 시스템에서 검색
4. 웹 서버가 요청한 파일을 읽음
5. 웹 서버가 파일을 클라이언트의 웹 브라우저에게 제공
<h4>동적 웹 서버 동작 방식</h4>
- 동적 웹이란?
- 매번 웹 페이지를 불러올 때마다 새로운 내용을 표시 (dynamic)
- 정적 웹 서버와 추가적인 소프트웨어로 구성
- 서버가 HTTP서버를 통해 클라이언트의 브라우저로 전송하기 전에, 서버가 업데이트를 하기 때문에 동적이라 칭함
<img src="https://user-images.githubusercontent.com/64996121/157681901-1d7cd4ff-c66a-4ad6-a5a9-8117ba2cf6b9.PNG" width=500 height=220 />
1. 클라이언트 즉, 웹 브라우저를 통해 80번 포트로 웹 서버에 연결
2. 사용자 문서에 동적인 페이지를 표현하는 php 프로그램 요청
3. 웹 서버가 php 프로그램을 실행시킨 후 클라이언트가 요청한 매개변수 넘겨줌
4. 웹 서버가 php 프로그램으로부터 생성된 결과를 읽어들임
5. php 프로그램으로부터의 결과를 웹 서버는 클라이언트의 브라우저에 전송
<br>
<br>
<h2>apache</h2>
- **Apache란?**
- 월드 와이드 웹(www) 서버용 소프트웨어
- 일반적으로 리눅스에서는 apache 사용
- **Apache 특징**
- 매우 뛰어난 성능과 기능을 가지고 있는 공개형 웹 서버 프로그램
- 다양한 플랫폼에서 동작할 수 있도록 강력하고 유연하게 설계
- 보조적 프로그램이 다양
- 공개된 형태로 개발
- 다양한 상황에 따른 서비스 지원
- 동적 공유 객체 지원
- 모듈 사용으로 기능 추가가 용이
- php, python 등의 모듈 사용 가능
- 유연한 설정
<h4>apache 설정</h4>
- 패키지 설치
```shell
[root@server ~]# yum -y install httpd
```
- 서비스 시작 및 활성화
```shell
[root@server ~]# systemctl start httpd
[root@server ~]# systemctl enable httpd
```
- 방화벽 설정
```shell
[root@server ~]# firewall-cmd --add-service=http --permanent
[root@server ~]# firewall-cmd --reload
```
<h4>apache 구성</h4>
- 리눅스 아파치 웹 서버의 메인 설정 파일 : **/etc/httpd/conf/httpd.conf**
- /etc/httpd/conf/httpd.conf에 직접 설정
- 또는 /etc/httpd/conf.d/ 에 추가적인 설정파일 생성 후, 서비스를 재시작하면 적용됨
- 키/값 구성 지시문과 HTML과 유사
- <Blockname parameter> 블록 2부분으로 구성
- **블록 외부**의 키/값 구성은 **전체 서버 구성에 영향**
- **블록 내부**의 지시문은 **지정된 구성이나 설정한 요구 조건이 충족될 때만 적용**
```shell
ServerRoot "/etc/httpd" # 구성 파일이 참조하는 위치의 기준점
Listetn 80 # httpd에 모든 인터페이스의 포트 80/TCP에서 수신 대기(중복 사용 금지)
Include conf.modules.d/*.conf # 모듈을 로드할 구성파일
User apache # httpd 데몬이 시작되면 실행되는사용자 및 그룹 지정
Group apache
ServerAdmin root@localhost # httpd에서 오류가 발생했을 때 문제를 보고 하는 곳
# 지정된 디렉토리및 모든 하위 디렉토리에 대한 구성 지시문 설정
# 블록 내부 지시문 : 세부 설정
<Directory />
AllowOverride none
Require all denied
</Directory>
```
- **ServerRoot** : apache의 기본 root 경로이며, 절대 경로로 설정해주어야함
- **Listen** [ip주소] [포트번호] : 사용할 포트 지정
- ip주소를 적지 않는 경우, 모든 주소에 대해서 허용
- **ServerAdmin** [이메일 또는 호스트] : 서버 관리자 이메일(주소) 입력
- 오류가 발생했을 때 문제 보고하는 곳
- **<Directory [위치] >** ~ </Directory> : [위치]에 대한 접근 제어
```shell
DocumentRoot "/var/www/html" # httpd가 요청된 파일을 검색할 위치 결정
<Directory "/var/www/">
AllowOverride None
Require all granted
</Directory>
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
<IfModule dir_module> # 지정된 디렉토리가 요청될 때 사용할 파일을 지정
DirectoryIndex index.html
</IfModule>
```
- **DocumentRoot** : 웹 문서가 위치하는 디렉토리를 지정
- httpd가 요청된 파일을 검색할 위치
- **/var/www/html 이 default**
- **<IfModule dir_module>** [파일] </IfModule> : 지정된 디렉토리가 요청될 때 사용할 파일을 지정
- **ServerName** : 서버 네임 지정
- DNS에 등록 해둬야함
<br>
<br>
<h4>apache 웹페이지 설정</h4>
- /var/www/html/에 사용하고자하는 웹 페이지를 저장
```shell
[root@server ~]# echo "test page" > /var/www/html/index.html
[root@server ~]# cat /var/www/html/index.html
test page
[root@server ~]# curl [서버 IP]
test page
```
- 직접 브라우저에 검색해보기
- 방화벽 설정 : 80번 포트 열어주기
- 방화벽 설정 후 브라우저에 "http://[ip주소]" 입력하면 정상적으로 출력
```shell
[root@server ~]# firewall-cmd --add-port=80/tcp --permanent
success
[root@server ~]# firewall-cmd --reload
success
```
<img src="https://user-images.githubusercontent.com/64996121/157681976-114e11a4-45b9-416f-8fa0-8ad00817f0ab.PNG" witdh=300 height=200 />
<br>
<br>
<h2>가상 호스트</h2>
- **가상 호스트**
- **한 시스템에서 여러개의 도메인과 호스트 이름을 구분하여 웹 서비스** 가능
- 연결된 서버의 IP주소와 클라이언트가 요청한 호스트 이름의 조합에 따라 다양한 구성 설정 가능
- 이름 기반의 가상 호스팅
- 네임 서버가 각 호스트명이 올바른 IP주소로 대응하도록 가상 호스트 설정
- 하나의 IP 주소를 가지고 여러 호스트에 대해서 웹 서비스 제공
- IP 기반의 가상 호스팅
- 하나의 아파치 웹 서버에서 물리적인 네트워크 카드에 여러 개의 IP 할당
- 각 호스트들이 서로 다른 IP 주소를 이용할 수 있도록 하는 방식
- **가상 호스트 구성**
- 기본 구성 내에 <VirtualHost> 블록을 사용하여 구성 가능
- 편리한 관리를 위해 /etc/httpd/conf/httpd.conf 내에 정의하지 않고, **/user/share/doc/httpd-2.4.6/ 디렉토리 내의 템플릿 파일로 구성**
```shell
[root@server ~]# ls /usr/share/doc/httpd-2.4.6/
ABOUT_APACHE httpd-info.conf httpd-multilang-errordoc.conf proxy-html.conf
CHANGES httpd-languages.conf httpd-vhosts.conf README
httpd-dav.conf httpd-manual.conf LICENSE VERSIONING
httpd-default.conf httpd-mpm.conf NOTICE
```
- 가상 호스트 구성 템플릿 파일인 **/usr/share/doc/httpd-2.4.6/httpd-vhosts.conf 을 이용**
```shell
<VirtualHost *:@@Port@@> # 모든 IP(*)에 대해 해당 포트 열어줌
ServerAdmin webmaster@dummy-host.example.com #관리자 설정-> 이미 httpd.conf 파일에 설정
DocumentRoot "@@ServerRoot@@/docs/dummy-host.example.com" #어디에 있는 데이터 사용할 것인지
ServerName dummy-host.example.com #서버네임 지정
ServerAlias www.dummy-host.example.com #서버네임 전환
ErrorLog "/var/log/httpd/dummy-host.example.com-error_log" #에러 로그
CustomLog "/var/log/httpd/dummy-host.example.com-access_log" common #커스텀 로그
</VirtualHost>
```
- 해당 파일을 **/etc/httpd/conf.d/ 디렉토리 내에** 이름을 바꾸어 복사
- **/etc/httpd/conf.d/site1.conf 파일에 정의**
```shell
[root@server ~]# cp /usr/share/doc/httpd-2.4.6/httpd-vhosts.conf /etc/httpd/conf.d/site1.conf
```
```shell
<Directory /srv/site1/www> # 아래 정의된 DocumentRoot에 엑세스 가능
Require all granted # 디렉토리를 따로 생성할 것
AllowOverride None
</Directory>
<VirtualHost 192.168.0.1:80> # 블록의 기본 태그, 해당 IP와 포트 고려
DocumentRoot /srv/site1/www # DocumentRoot 정의 가상호스트 내에서만 유효
ServerName site1.example.com # 가상호스트 도메인네임 ServerAlias문이 사용될 수도 있음
ServerAdmin webmaster@site1.example.com # 가상 호스트 관리자의 이메일 주소
ErrorLog "logs/site1_error_log" # 가상호스트 오류 메시지 위치
CustomLog "logs/site1_access_log" combined # 가상 호스트 액세스 메시지
</VirtualHost>
```
<h4>실습</h4>
- /etc/httpd/conf.d/00-vhost.conf 파일 생성
- 모든 주소에 대해서 80포트 열어줌
- httpd가 요청된 파일을 검색할 위치 : /var/www/html0
- 서버 이름 : vhost0.test.example.com
- 또 다른 서버 이름 : vhost0
- 해당 디렉토리 : /var/www/html0
```shell
[root@server ~]# vim /etc/httpd/conf.d/00-vhost.conf
<VirtualHost *:80>
DocumentRoot /var/www/html0
ServerName vhost0.test.example.com
ServerAlias vhost0
</VirtualHost>
<Directory /var/www/html0>
AllowOverride none
Require all granted
</Directory>
```
- /etc/httpd/conf.d/01-vhost.conf 파일 생성
- 00-vhost.conf 파일 복사해서 사용
```shell
[root@server ~]# cp /etc/httpd/conf.d/00-vhost.conf /etc/httpd/conf.d/01-vhost.conf
```
```shell
[root@server ~]# cat /etc/httpd/conf.d/01-vhost.conf
<VirtualHost *:80>
DocumentRoot /var/www/html1
ServerName vhost1.test.example.com
ServerAlias vhost1
</VirtualHost>
<Directory /var/www/html1>
AllowOverride none
Require all granted
</Directory>
```
- 파일 생성(웹 페이지 저장)
```shell
[root@server ~]# mkdir /var/www/html{0..1}
[root@server ~]# echo vhost0 test > /var/www/html0/index.html
[root@server ~]# echo vhost1 test > /var/www/html1/index.html
[root@server ~]# cat /var/www/html0/index.html
vhost0 test
[root@server ~]# cat /var/www/html1/index.html
vhost1 test
```
- /etc/hosts에 등록
```shell
[root@server ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.238.100 server.test.example.com server vhost1.test.example.com vhost1 vhost0.test.example.com vhost0
```
- httpd 서비스 재시작
```shell
[root@server ~]# systemctl restart httpd
```
- 확인
- IP 주소로 curl 했을 때에는 0번에 있는 것을 default값 보다 우선 시해서 적용
```shell
[root@server ~]# curl vhost0
vhost0 test
[root@server ~]# curl vhost1
vhost1 test
[root@server ~]# curl 192.168.238.100
vhost0 test
[root@server ~]# curl vhost0.test.example.com
vhost0 test
[root@server ~]# curl vhost1.test.example.com
vhost1 test
```
|
import React, { useEffect, useState } from "react";
import Topbar from './Topbar'
import { useSelector, useDispatch } from "react-redux";
import { deleteNotification } from '../../redux/action/notification'
import { Close } from '@mui/icons-material'
import { IconButton } from '@mui/material'
import ViewNotification from './Notification'
function Notifications({ }) {
const { notifications } = useSelector(state => state.notification)
const dispatch = useDispatch()
const [openNotification, setOpenNotification] = useState(false)
const [notificationId, setNotificationId] = useState('')
const handleDelete = (notificationId) => {
dispatch(deleteNotification(notificationId))
}
const Notification = ({ notification }) => {
const [showCloseButton, setShowCloseButton] = useState(false)
return (
<div
onClick={() => { setNotificationId(notification._id); setOpenNotification(true) }}
onMouseEnter={() => setShowCloseButton(true)}
onMouseLeave={() => setShowCloseButton(false)}
className={`${notification.isRead ? 'bg-gray-100' : 'bg-gray-200'} hover:bg-gray-50 relative cursor-pointer flex flex-col w-full p-[8px] rounded-[6px] `}
>
{showCloseButton && <IconButton onClick={() => handleDelete(notification._id)} style={{ position: 'absolute' }} className='absolute top-[5px] right-[5px] ' > <Close /></IconButton>}
<div>
<span className="text-lg font-extralight text-sky-400">{notification.title}</span>
<br />
{notification.description}
<br />
</div>
</div>
)
}
return (
<div className="w-full h-fit bg-inherit flex flex-col gap-[1rem] ">
<Topbar />
<ViewNotification open={openNotification} setOpen={setOpenNotification} notificationId={notificationId} />
{
notifications.map((notification, index) => (
<div key={index} className="w-[48%] ">
<Notification notification={notification} />
</div>
))
}
</div>
);
}
export default Notifications;
|
import React, { useState } from "react";
import { Route, BrowserRouter as Router, Routes } from "react-router-dom";
import Activities from "./components/Activities";
import Footer from "./components/Footer";
import Gallery from "./components/Gallery";
import Hero from "./components/Hero";
import Navbar from "./components/Navbar";
import TopBar from "./components/TopBar";
import RegisterForm from "./components/RegisterForm";
function App() {
// Add state to manage whether the user is on the login page
const [isLoginPage, setIsLoginPage] = useState(false);
// Function to set isLoginPage to true when the user clicks the "Logheaza-te" link
const handleLoginClick = () => {
setIsLoginPage(true);
};
// Function to set isLoginPage to false when the user navigates away from the login page
const handleNavigateAway = () => {
setIsLoginPage(false);
};
return (
<Router>
<div>
<Navbar />
<TopBar />
<Routes>
{/* Placeholder for the root URL */}
<Route path="/" element={<div />} />
{/* Route for the login page */}
<Route
path="/register"
element={<RegisterForm setIsLoginPage={handleNavigateAway} />}
/>
</Routes>
{/* Conditionally render content based on isLoginPage */}
{!isLoginPage && (
<>
<Hero />
<Activities onLoginClick={handleLoginClick} />
<Gallery />
<Footer />
</>
)}
</div>
</Router>
);
}
export default App;
|
@extends('layouts.app')
@section('title', 'Edit Question')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-8">
<div class="h1Panel">
<h3>EDIT QUESTION</h3>
</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-8">
<div>
<div class="panel">
<form action="{{route('forum.update', $forums->id)}}" method="POST" enctype="multipart/form-data">
@csrf
@method("PUT")
<div class="form-group">
<input type="text" class="form-control createInput" placeholder="Title" name="title"
value="{{$forums->title}}">
@if ($errors->has('title'))
<div class="text-danger">
{{$errors->first('title')}}
</div>
@endif
</div>
<div class="ckEditor">
<div class="form-group">
<textarea type="text" name="description"
class="form-control createInput">{{$forums->description}}</textarea>
@if ($errors->has('description'))
<div class="text-danger">
{{$errors->first('description')}}
</div>
@endif
</div>
</div>
<div class="select2Tags">
<div class="form-group">
<select name="tags[]" id="" class="form-control createInput tags" multiple="multiple">
@foreach($tags as $tag)
<option value="{{$tag->id}}">{{$tag->name}}</option>
@endforeach
</select>
@if ($errors->has('tags'))
<div class="text-danger">
{{$errors->first('tags')}}
</div>
@endif
</div>
</div>
<div class="imageUpload">
<div class="row justify-content-center">
<div class="col-1">
<img src="{{asset('img/file-upload.png')}}" alt="">
</div>
<div class="col-11" style="margin-right: 25px;">
<div class="form-group">
<input type="file" class="form-control createInput" name="image"
placeholder="image">
@if ($errors->has('image'))
<div class="text-danger">
{{$errors->first('image')}}
</div>
@endif
</div>
</div>
</div>
</div>
<div class="viewImageEdit tengah">
@if (empty($forums->image))
<small><i class="fas fa-info-circle"></i> There are No Images in This Post</small>
@else
<div class="form-group">
<div class="col-md-4 tengah">
<img src="{{asset('img/'.$forums->image)}}" alt="" width="100%">
</div>
</div>
@endif
</div>
<div class="form-group tengah">
<button type="submit" class="createButton">EDIT QUESTION</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
@section('js')
<script type="text/javascript">
$(".tags").select2().val({!!json_encode($forums->tags()->allRelatedIds()) !!}).trigger('change');
CKEDITOR.replace('description', {
extraPlugins: 'codesnippet',
codeSnippet_theme: 'dark'
});
</script>
@endsection
|
class GuidesController < ApplicationController
before_action :set_guide, only: %i[ show edit update destroy ]
# GET /guides or /guides.json
def index
@guides = Guide.all
end
# GET /guides/1 or /guides/1.json
def show
@mihan_mowatan = MihanMowatan.find(params[:id])
@result = JSON.parse(@mihan_mowatan.result) # Parse the JSON string
end
# GET /guides/new
def new
@guide = Guide.new
end
# GET /guides/1/edit
def edit
end
# POST /guides or /guides.json
def create
@guide = Guide.new(guide_params)
respond_to do |format|
if @guide.save
format.html { redirect_to guide_url(@guide), notice: "Guide was successfully created." }
format.json { render :show, status: :created, location: @guide }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @guide.errors, status: :unprocessable_entity }
end
end
end
def generate_report
xlsx_file = params[:xlsx_file]
if xlsx_file.present? && xlsx_file.content_type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
# Process .xlsx file
workbook = Roo::Spreadsheet.open(xlsx_file.tempfile.path, headers: true)
worksheet = workbook.sheet(0)
# Extract the data from Excel file
excel_data = worksheet.to_a
# Convert the Excel data to JSON
excel_data_json = excel_data.to_json
# Create a Guide record with the JSON data
Guide.create(file: excel_data_json)
redirect_to root_path, notice: 'Reports generated successfully!'
else
redirect_to root_path, alert: 'Please upload valid .xlsx'
end
end
# PATCH/PUT /guides/1 or /guides/1.json
def update
respond_to do |format|
if @guide.update(guide_params)
format.html { redirect_to guide_url(@guide), notice: "Guide was successfully updated." }
format.json { render :show, status: :ok, location: @guide }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @guide.errors, status: :unprocessable_entity }
end
end
end
# DELETE /guides/1 or /guides/1.json
def destroy
@guide.destroy
respond_to do |format|
format.html { redirect_to guides_url, notice: "Guide was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_guide
@guide = Guide.find(params[:id])
end
# Only allow a list of trusted parameters through.
def guide_params
params.require(:guide).permit(:file)
end
end
|
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 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="style.css">
<title>Lenguaje de señas</title>
</head>
<body>
<header>
<nav class="navbar navbar-dark bg-dark" aria-label="First navbar example">
<div class="container-fluid">
<a class="navbar-brand" href="index.html">Lenguaje de señas</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarsExample01" aria-controls="navbarsExample01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExample01">
<ul class="navbar-nav me-auto mb-2">
<li class="nav-item">
<a class="nav-link" href="abecedario.html">Abecedario</a>
</li>
<li class="nav-item">
<a class="nav-link" href="familia.html">Miembros de la familia</a>
</li>
<li class="nav-item">
<a class="nav-link" href="diassemana.html">Días de la semana</a>
</li>
<li class="nav-item">
<a class="nav-link" href="meses.html">Meses</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="./img/Slides/slide1.jpg" class="d-block w-100" alt="...">
<br>
<div class="carousel-caption d-none d-md-block">
<h5>Existen aproximadamente 466 millones de personas en todo el mundo que tiene algún tipo de problema auditivo.</h5>
</div>
</div>
<div class="carousel-item">
<img src="./img/Slides/slide2.jpg" class="d-block w-100" alt="...">
<br>
<div class="carousel-caption d-none d-md-block">
<h5>El 60% de todos los casos de sordera que existen en la actualidad se podían haber prevenido si se hubiesen diagnosticado a tiempo.</h5>
</div>
</div>
<div class="carousel-item">
<img src="./img/Slides/slide3.jpg" class="d-block w-100" alt="...">
<br>
<div class="carousel-caption d-none d-md-block">
<h5>Se estima que para el año 2050, 1 de cada 10 personas tendrá algún tipo de discapacidad auditiva.</h5>
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<br><br><br>
<h1 class="text-center display-1">Abecedario</h1>
<br><br><br>
<div class="container">
<div class="row">
<div class="col-lg-3">
<div class="card">
<img id="myImgA" src="./img/Abecedario/a.png" class="card-img-top myImg" alt="Con la mano cerrada, se muestran las uñas y se estira el dedo pulgar
hacia un lado. La palma mira al frente.">
<div class="card-body">
<h5 class="card-title">A</h5>
<p id="textA" class="card-text">Con la mano cerrada, se muestran las uñas y se estira el dedo pulgar
hacia un lado. La palma mira al frente. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgB" src="./img/Abecedario/b.png" class="card-img-top myImg" alt="Los dedos índice, medio, anular y meñique se
estiran bien unidos y el pulgar se dobla hacia
la palma, la cual mira al frente.">
<div class="card-body">
<h5 class="card-title">B</h5>
<p class="card-text">Los dedos índice, medio, anular y meñique se
estiran bien unidos y el pulgar se dobla hacia
la palma, la cual mira al frente. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgC" src="./img/Abecedario/c.png" class="card-img-top myImg" alt="Los dedos índice, medio, anular y meñique se
mantienen bien unidos y en posición cóncava;
el pulgar también se pone en esa posición. La
palma mira a un lado.">
<div class="card-body">
<h5 class="card-title">C</h5>
<p class="card-text">Los dedos índice, medio, anular y meñique se
mantienen bien unidos y en posición cóncava;
el pulgar también se pone en esa posición. La
palma mira a un lado.</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgD" src="./img/Abecedario/d.png" class="card-img-top myImg" alt="Los dedos medio, anular, meñique y pulgar se
unen por las puntas y el dedo índice se estira.
La palma mira al frente.">
<div class="card-body">
<h5 class="card-title">D</h5>
<p class="card-text">Los dedos medio, anular, meñique y pulgar se
unen por las puntas y el dedo índice se estira.
La palma mira al frente. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
</div>
<br><br>
<div class="row">
<div class="col-lg-3">
<div class="card">
<img id="myImgE" src="./img/Abecedario/e.png" class="card-img-top myImg" alt="Se doblan los dedos completamente, y se
muestran las uñas. La palma mira al frente.">
<div class="card-body">
<h5 class="card-title">E</h5>
<p class="card-text">Se doblan los dedos completamente, y se
muestran las uñas. La palma mira al frente. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgF" src="./img/Abecedario/f.png" class="card-img-top myImg" alt="Con la mano abierta y los dedos bien unidos,
se dobla el índice hasta que su parte lateral
toque la yema del pulgar. La palma mira a un
lado.">
<div class="card-body">
<h5 class="card-title">F</h5>
<p class="card-text">Con la mano abierta y los dedos bien unidos,
se dobla el índice hasta que su parte lateral
toque la yema del pulgar. La palma mira a un
lado. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgG" src="./img/Abecedario/g.png" class="card-img-top myImg" alt="Se cierra la mano y los dedos índice y pulgar
se estiran. La palma mira hacia usted.">
<div class="card-body">
<h5 class="card-title">G</h5>
<p class="card-text">Se cierra la mano y los dedos índice y pulgar
se estiran. La palma mira hacia usted. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgH" src="./img/Abecedario/h.png" class="card-img-top myImg" alt="Con la mano cerrada y los dedos índice y
medio bien estirados y unidos, se extiende el
dedo pulgar señalando hacia arriba. La palma
mira hacia usted.">
<div class="card-body">
<h5 class="card-title">H</h5>
<p class="card-text">Con la mano cerrada y los dedos índice y
medio bien estirados y unidos, se extiende el
dedo pulgar señalando hacia arriba. La palma
mira hacia usted.</p>
</div>
</div>
</div>
</div>
<br><br>
<div class="row">
<div class="col-lg-3">
<div class="card">
<img id="myImgI" src="./img/Abecedario/i.png" class="card-img-top myImg" alt="Con la mano cerrada, el dedo meñique se
estira señalando hacia arriba. La palma se
pone de lado.">
<div class="card-body">
<h5 class="card-title">I</h5>
<p class="card-text">Con la mano cerrada, el dedo meñique se
estira señalando hacia arriba. La palma se
pone de lado. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<div id="carouselExampleCaptionsJ" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img id="myImgJ" src="./img/Abecedario/j.png" class="d-block w-100 card-img-top myImg" alt="Con la mano cerrada, el dedo meñique bien
estirado señalando hacia arriba y la palma a
un lado dibuja una j en el aire.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
<div class="carousel-item">
<img id="myImgJ2" src="./img/Abecedario/j.gif" class="d-block w-100 card-img-top myImg" alt="Con la mano cerrada, el dedo meñique bien
estirado señalando hacia arriba y la palma a
un lado dibuja una j en el aire.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptionsJ" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptionsJ" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="card-body">
<h5 class="card-title">J</h5>
<p class="card-text">Con la mano cerrada, el dedo meñique bien
estirado señalando hacia arriba y la palma a
un lado dibuja una j en el aire. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<div id="carouselExampleCaptionsK" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img id="myImgK" src="./img/Abecedario/k.png" class="d-block w-100 card-img-top myImg" alt="Se cierra la mano con los dedos índice, medio
y pulgar estirados. La yema del pulgar se
pone entre el índice y el medio. Se mueve la
muñeca hacia arriba.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
<div class="carousel-item">
<img id="myImgK2" src="./img/Abecedario/k.gif" class="d-block w-100 card-img-top myImg" alt="Se cierra la mano con los dedos índice, medio
y pulgar estirados. La yema del pulgar se
pone entre el índice y el medio. Se mueve la
muñeca hacia arriba.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptionsK" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptionsK" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="card-body">
<h5 class="card-title">K</h5>
<p class="card-text">Se cierra la mano con los dedos índice, medio
y pulgar estirados. La yema del pulgar se
pone entre el índice y el medio. Se mueve la
muñeca hacia arriba.</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgL" src="./img/Abecedario/l.png" class="card-img-top myImg" alt=">Con la mano cerrada y los dedos índice y
pulgar estirados, se forma una l. La palma
mira al frente.">
<div class="card-body">
<h5 class="card-title">L</h5>
<p class="card-text">Con la mano cerrada y los dedos índice y
pulgar estirados, se forma una l. La palma
mira al frente. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
</div>
<br><br>
<div class="row">
<div class="col-lg-3">
<div class="card">
<img id="myImgM" src="./img/Abecedario/m.png" class="card-img-top myImg" alt="Con la mano cerrada, se ponen los dedos
índice, medio y anular sobre el pulgar.">
<div class="card-body">
<h5 class="card-title">M</h5>
<p class="card-text">Con la mano cerrada, se ponen los dedos
índice, medio y anular sobre el pulgar.</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgN" src="./img/Abecedario/n.png" class="card-img-top myImg" alt="Con la mano cerrada, se ponen los dedos
índice y medio sobre el pulgar.">
<div class="card-body">
<h5 class="card-title">N</h5>
<p class="card-text">Con la mano cerrada, se ponen los dedos
índice y medio sobre el pulgar. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<div id="carouselExampleCaptionsÑ" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img id="myImgÑ" src="./img/Abecedario/ñ.png" class="d-block w-100 card-img-top myImg" alt="Con la mano cerrada, se ponen los dedos
índice y medio sobre el pulgar. Se mueve la
muñeca a los lados.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
<div class="carousel-item">
<img id="myImgÑ2" src="./img/Abecedario/ñ.gif" class="d-block w-100 card-img-top myImg" alt="Con la mano cerrada, se ponen los dedos
índice y medio sobre el pulgar. Se mueve la
muñeca a los lados.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptionsÑ" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptionsÑ" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="card-body">
<h5 class="card-title">Ñ</h5>
<p class="card-text">Con la mano cerrada, se ponen los dedos
índice y medio sobre el pulgar. Se mueve la
muñeca a los lados.</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgO" src="./img/Abecedario/o.png" class="card-img-top myImg" alt="Con la mano se forma una letra o. Todos los
dedos se tocan por las puntas.">
<div class="card-body">
<h5 class="card-title">O</h5>
<p class="card-text">Con la mano se forma una letra o. Todos los
dedos se tocan por las puntas.</p>
</div>
</div>
</div>
</div>
<br><br>
<div class="row">
<div class="col-lg-3">
<div class="card">
<img id="myImgP" src="./img/Abecedario/p.png" class="card-img-top myImg" alt="Con la mano cerrada y los dedos índice, medio
y pulgar estirados, se pone la yema del pulgar
entre el índice y el medio.">
<div class="card-body">
<h5 class="card-title">P</h5>
<p class="card-text">Con la mano cerrada y los dedos índice, medio
y pulgar estirados, se pone la yema del pulgar
entre el índice y el medio.</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<div id="carouselExampleCaptionsQ" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img id="myImgQ" src="./img/Abecedario/q.png" class="d-block w-100 card-img-top myImg" alt="Con la mano cerrada, se ponen los dedos
índice y pulgar en posición de garra. La palma
mira hacia abajo, y se mueve la muñeca hacia
los lados.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
<div class="carousel-item">
<img id="myImgQ2" src="./img/Abecedario/q.gif" class="d-block w-100 card-img-top myImg" alt="Con la mano cerrada, se ponen los dedos
índice y pulgar en posición de garra. La palma
mira hacia abajo, y se mueve la muñeca hacia
los lados.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptionsQ" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptionsQ" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="card-body">
<h5 class="card-title">Q</h5>
<p class="card-text">Con la mano cerrada, se ponen los dedos
índice y pulgar en posición de garra. La palma
mira hacia abajo, y se mueve la muñeca hacia
los lados.</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgR" src="./img/Abecedario/r.png" class="card-img-top myImg" alt="Con la mano cerrada, se estiran y entrelazan
los dedos índice y medio. La palma mira al
frente.">
<div class="card-body">
<h5 class="card-title">R</h5>
<p class="card-text">Con la mano cerrada, se estiran y entrelazan
los dedos índice y medio. La palma mira al
frente. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgS" src="./img/Abecedario/s.png" class="card-img-top myImg" alt="Con la mano cerrada, se pone el pulgar sobre
los otros dedos. La palma mira al frente.">
<div class="card-body">
<h5 class="card-title">S</h5>
<p class="card-text">Con la mano cerrada, se pone el pulgar sobre
los otros dedos. La palma mira al frente. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
</div>
<br><br>
<div class="row">
<div class="col-lg-3">
<div class="card">
<img id="myImgT" src="./img/Abecedario/t.png" class="card-img-top myImg" alt="Con la mano cerrada, el pulgar se pone entre
el índice y el medio. La palma mira al frente.">
<div class="card-body">
<h5 class="card-title">T</h5>
<p class="card-text">Con la mano cerrada, el pulgar se pone entre
el índice y el medio. La palma mira al frente.</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgU" src="./img/Abecedario/u.png" class="card-img-top myImg" alt="Con la mano cerrada, se estiran los dedos
índice y medio unidos. La palma mira al frente.">
<div class="card-body">
<h5 class="card-title">U</h5>
<p class="card-text">Con la mano cerrada, se estiran los dedos
índice y medio unidos. La palma mira al frente.</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgV" src="./img/Abecedario/v.png" class="card-img-top myImg" alt="Con la mano cerrada, se estiran los dedos
índice y medio separados. La palma mira al
frente.">
<div class="card-body">
<h5 class="card-title">V</h5>
<p class="card-text">Con la mano cerrada, se estiran los dedos
índice y medio separados. La palma mira al
frente.</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgW" src="./img/Abecedario/w.png" class="card-img-top myImg" alt="Con la mano cerrada, se estiran los dedos
índice, medio y anular separados. La palma
mira al frente.">
<div class="card-body">
<h5 class="card-title">W</h5>
<p class="card-text">Con la mano cerrada, se estiran los dedos
índice, medio y anular separados. La palma
mira al frente.</p>
</div>
</div>
</div>
</div>
<br><br>
<div class="row">
<div class="col-lg-3">
<div class="card">
<div id="carouselExampleCaptionsX" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img id="myImgX" src="./img/Abecedario/x.png" class="d-block w-100 card-img-top myImg" alt="Con la mano cerrada, el índice y el pulgar
en posición de garra y la palma dirigida a un
lado, se realiza un movimiento al frente y de
regreso.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
<div class="carousel-item">
<img id="myImgX2" src="./img/Abecedario/x.gif" class="d-block w-100 card-img-top myImg" alt="Con la mano cerrada, el índice y el pulgar
en posición de garra y la palma dirigida a un
lado, se realiza un movimiento al frente y de
regreso.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptionsX" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptionsX" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="card-body">
<h5 class="card-title">X</h5>
<p class="card-text">Con la mano cerrada, el índice y el pulgar
en posición de garra y la palma dirigida a un
lado, se realiza un movimiento al frente y de
regreso.</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<img id="myImgY" src="./img/Abecedario/y.png" class="card-img-top myImg" alt="Con la mano cerrada, se estira el meñique
y el pulgar. La palma mira hacia usted.">
<div class="card-body">
<h5 class="card-title">Y</h5>
<p class="card-text">Con la mano cerrada, se estira el meñique
y el pulgar. La palma mira hacia usted. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="card">
<div id="carouselExampleCaptionsZ" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img id="myImgZ" src="./img/Abecedario/z.png" class="d-block w-100 card-img-top myImg" alt="Con la mano cerrada, el dedo índice estirado
y la palma al frente, se dibuja una letra z en
el aire.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
<div class="carousel-item">
<img id="myImgZ2" src="./img/Abecedario/z.gif" class="d-block w-100 card-img-top myImg" alt="Con la mano cerrada, el dedo índice estirado
y la palma al frente, se dibuja una letra z en
el aire.">
<div class="carousel-caption d-none d-md-block">
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptionsZ" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptionsZ" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="card-body">
<h5 class="card-title">Z</h5>
<p class="card-text">Con la mano cerrada, el dedo índice estirado
y la palma al frente, se dibuja una letra z en
el aire. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
</div>
</div>
</div>
</div>
<br><br>
<div class="text-center">
<iframe width="560" height="315" src="https://www.youtube.com/embed/2VOteEbKV_c" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>
<div class="container">
<footer class="row row-cols-4 py-4 my-4 border-top">
<div class="col">
<a href="/" class="d-flex align-items-center mb-3 link-dark text-decoration-none">
<svg class="bi me-2" width="40" height="32"><use xlink:href="#bootstrap"/></svg>
</a>
<p class="text-muted">© 2022</p>
</div>
<div class="col">
</div>
<div class="col">
<h5>Nuestras redes</h5>
<ul class="nav flex-column">
<li><a href=""><img src="./img/Redes sociales/facebook.png" width="40" height="40" alt=""></a></li>
<li><a href=""><img src="./img/Redes sociales/twitter.png" width="40" height="40" alt=""></a></li>
<li><a href=""><img src="./img/Redes sociales/whatsapp.png" width="40" height="40" alt=""></a></li>
</ul>
</div>
<div class="col">
<h5>Contacto</h5>
<ul class="nav flex-column">
<li><p>📧 contacto@lenguajedesenas.com</p></li>
<li><p>📞 +52 47 4743 94 36</p></li>
<li><p>📍 Lagos de Moreno, Jalisco, México</p></li>
</ul>
</div>
</footer>
</div>
<div id="myModal" class="modal">
<!-- The Close Button -->
<span class="close" onclick="document.getElementById('myModal').style.display='none'">×</span>
<!-- Modal Content (The Image) -->
<img class="modal-content" id="img01">
<!-- Modal Caption (Image Text) -->
<div class="caption" id="caption"></div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the image and insert it inside the modal - use its "alt" text as a caption
var imgA = document.getElementById('myImgA');
imgA.onclick = miFuncion;
var imgB = document.getElementById('myImgB');
imgB.onclick = miFuncion;
var imgC = document.getElementById('myImgC');
imgC.onclick = miFuncion;
var imgD = document.getElementById('myImgD');
imgD.onclick = miFuncion;
var imgE = document.getElementById('myImgE');
imgE.onclick = miFuncion;
var imgF = document.getElementById('myImgF');
imgF.onclick = miFuncion;
var imgG = document.getElementById('myImgG');
imgG.onclick = miFuncion;
var imgH = document.getElementById('myImgH');
imgH.onclick = miFuncion;
var imgI = document.getElementById('myImgI');
imgI.onclick = miFuncion;
var imgJ = document.getElementById('myImgJ');
imgJ.onclick = miFuncion;
var imgJ2 = document.getElementById('myImgJ2');
imgJ2.onclick = miFuncion;
var imgK = document.getElementById('myImgK');
imgK.onclick = miFuncion;
var imgK2 = document.getElementById('myImgK2');
imgK2.onclick = miFuncion;
var imgL = document.getElementById('myImgL');
imgL.onclick = miFuncion;
var imgM = document.getElementById('myImgM');
imgM.onclick = miFuncion;
var imgN = document.getElementById('myImgN');
imgN.onclick = miFuncion;
var imgÑ = document.getElementById('myImgÑ');
imgÑ.onclick = miFuncion;
var imgÑ2 = document.getElementById('myImgÑ2');
imgÑ2.onclick = miFuncion;
var imgO = document.getElementById('myImgO');
imgO.onclick = miFuncion;
var imgP = document.getElementById('myImgP');
imgP.onclick = miFuncion;
var imgQ = document.getElementById('myImgQ');
imgQ.onclick = miFuncion;
var imgQ2 = document.getElementById('myImgQ2');
imgQ2.onclick = miFuncion;
var imgR = document.getElementById('myImgR');
imgR.onclick = miFuncion;
var imgS = document.getElementById('myImgS');
imgS.onclick = miFuncion;
var imgT = document.getElementById('myImgT');
imgT.onclick = miFuncion;
var imgU = document.getElementById('myImgU');
imgU.onclick = miFuncion;
var imgV = document.getElementById('myImgV');
imgV.onclick = miFuncion;
var imgW = document.getElementById('myImgW');
imgW.onclick = miFuncion;
var imgX = document.getElementById('myImgX');
imgX.onclick = miFuncion;
var imgX2 = document.getElementById('myImgX2');
imgX2.onclick = miFuncion;
var imgY = document.getElementById('myImgY');
imgY.onclick = miFuncion;
var imgZ = document.getElementById('myImgZ');
imgZ.onclick = miFuncion;
var imgZ2 = document.getElementById('myImgZ2');
imgZ2.onclick = miFuncion;
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
function miFuncion(){
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
</script>
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and 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>
-->
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div>
code1
<input type="text" id="info"/><!--这个盒子是装用户输入的验证码的-->
<div id="code" style="width: 100px;height: 30px;border: 1px solid rgb(204,204,204);display: inline-block;position: relative;overflow: hidden;cursor: pointer;background: rgb(255,255,255);"></div>
<!--这个盒子是图片呈现的盒子,这个盒子是可以点击的,点击就会更改图片-->
<button id="btn">验证123</button><!--点击这个按钮的时候,就会进行验证-->
</div>
</body>
<script type="text/javascript">
(function() {
var randstr = function(length) {
var key = {
str: [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'o', 'p', 'q', 'r', 's', 't', 'x', 'u', 'v', 'y', 'z', 'w', 'n',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
],
randint: function(n, m) {
var c = m - n + 1;
var num = Math.random() * c + n;
return Math.floor(num);
},
randStr: function() {
var _this = this;
var leng = _this.str.length - 1;
var randkey = _this.randint(0, leng);
return _this.str[randkey];
},
create: function(len) {
var _this = this;
var l = len || 10;
var str = '';
for (var i = 0; i < l; i++) {
str += _this.randStr();
}
return str;
}
};
length = length ? length : 10;
return key.create(length);
};
var randint = function(n, m) {
var c = m - n + 1;
var num = Math.random() * c + n;
return Math.floor(num);
};
var vCode = function(dom, options) {
this.codeDoms = [];
this.lineDoms = [];
this.initOptions(options);
this.dom = dom;
this.init();
this.addEvent();
this.update();
this.mask();
};
vCode.prototype.init = function() {
this.dom.style.position = "relative";
this.dom.style.overflow = "hidden";
this.dom.style.cursor = "pointer";
this.dom.title = "点击更换验证码";
this.dom.style.background = this.options.bgColor;
this.w = this.dom.clientWidth;
this.h = this.dom.clientHeight;
this.uW = this.w / this.options.len;
};
vCode.prototype.mask = function() {
var dom = document.createElement("div");
dom.style.cssText = [
"width: 100%",
"height: 100%",
"left: 0",
"top: 0",
"position: absolute",
"cursor: pointer",
"z-index: 9999999"
].join(";");
dom.title = "点击更换验证码";
this.dom.appendChild(dom);
};
vCode.prototype.addEvent = function() {
var _this = this;
_this.dom.addEventListener("click", function() {
_this.update.call(_this);
});
};
vCode.prototype.initOptions = function(options) {
var f = function() {
this.len = 4;
this.fontSizeMin = 20;
this.fontSizeMax = 48;
this.colors = [
"green",
"red",
"blue",
"#53da33",
"#AA0000",
"#FFBB00"
];
this.bgColor = "#FFF";
this.fonts = [
"Times New Roman",
"Georgia",
"Serif",
"sans-serif",
"arial",
"tahoma",
"Hiragino Sans GB"
];
this.lines = 8;
this.lineColors = [
"#888888",
"#FF7744",
"#888800",
"#008888"
];
this.lineHeightMin = 1;
this.lineHeightMax = 3;
this.lineWidthMin = 1;
this.lineWidthMax = 60;
};
this.options = new f();
if (typeof options === "object") {
for (i in options) {
this.options[i] = options[i];
}
}
};
vCode.prototype.update = function() {
for (var i = 0; i < this.codeDoms.length; i++) {
this.dom.removeChild(this.codeDoms[i]);
}
for (var i = 0; i < this.lineDoms.length; i++) {
this.dom.removeChild(this.lineDoms[i]);
}
this.createCode();
this.draw();
};
vCode.prototype.createCode = function() {
this.code = randstr(this.options.len);
};
vCode.prototype.verify = function(code) {
return this.code === code;
};
vCode.prototype.draw = function() {
this.codeDoms = [];
for (var i = 0; i < this.code.length; i++) {
this.codeDoms.push(this.drawCode(this.code[i], i));
}
this.drawLines();
};
vCode.prototype.drawCode = function(code, index) {
var dom = document.createElement("span");
dom.style.cssText = [
"font-size:" + randint(this.options.fontSizeMin, this.options.fontSizeMax) + "px",
"color:" + this.options.colors[randint(0, this.options.colors.length - 1)],
"position: absolute",
"left:" + randint(this.uW * index, this.uW * index + this.uW - 10) + "px",
"top:" + randint(0, this.h - 30) + "px",
"transform:rotate(" + randint(-30, 30) + "deg)",
"-ms-transform:rotate(" + randint(-30, 30) + "deg)",
"-moz-transform:rotate(" + randint(-30, 30) + "deg)",
"-webkit-transform:rotate(" + randint(-30, 30) + "deg)",
"-o-transform:rotate(" + randint(-30, 30) + "deg)",
"font-family:" + this.options.fonts[randint(0, this.options.fonts.length - 1)],
"font-weight:" + randint(400, 900)
].join(";");
dom.innerHTML = code;
this.dom.appendChild(dom);
return dom;
};
vCode.prototype.drawLines = function() {
this.lineDoms = [];
for (var i = 0; i < this.options.lines; i++) {
var dom = document.createElement("div");
dom.style.cssText = [
"position: absolute",
"opacity: " + randint(3, 8) / 10,
"width:" + randint(this.options.lineWidthMin, this.options.lineWidthMax) + "px",
"height:" + randint(this.options.lineHeightMin, this.options.lineHeightMax) + "px",
"background: " + this.options.lineColors[randint(0, this.options.lineColors.length - 1)],
"left:" + randint(0, this.w - 20) + "px",
"top:" + randint(0, this.h) + "px",
"transform:rotate(" + randint(-30, 30) + "deg)",
"-ms-transform:rotate(" + randint(-30, 30) + "deg)",
"-moz-transform:rotate(" + randint(-30, 30) + "deg)",
"-webkit-transform:rotate(" + randint(-30, 30) + "deg)",
"-o-transform:rotate(" + randint(-30, 30) + "deg)",
"font-family:" + this.options.fonts[randint(0, this.options.fonts.length - 1)],
"font-weight:" + randint(400, 900)
].join(";");
this.dom.appendChild(dom);
this.lineDoms.push(dom);
}
};
this.vCode = vCode;
}).call(this);
</script>
<script type="text/javascript">
onload = function () {
var code = document.getElementById("code");//获得容器的盒子
var code1 = new vCode(code);//code为验证码的DOM节点,现在保存的就是图片的正确验证信息
document.getElementById("btn").addEventListener('click',function () {
alert(code1.verify(document.getElementById("info").value));//info是input的内容,和之前图片的进行匹配
},false);
}
</script>
</html>
|
;
;+
; NAME:
; masklinesqso.pro
;
; PURPOSE:
; Identify and mask emission/absorption features in a QSO
; spectrum. Differs from masklines.pro in having maximum
; linemask size depending on filter size used in median filter.
;
;
; CALLING SEQUENCE:
;
; pixel_mask = MASKLINES_QSO(Flux, Wave, Z, Linefile, Nfilt, /SILENT)
;
;
; INPUTS:
; Flux: spectrum
; Wave: observed wavelength array (Angstroms)
; Z: redshift of QSO
; Linefile: Path and name of file containing array of
; wavelengths to be masked.
; Nfilt: Size of median filter used on spectrum before masking.
;
; KEYWORD PARAMETERS:
; SILENT: Stop program writing warnings
;
; OUTPUTS:
; This function returns an array the same length of flux where 1
; identifies a pixel with a line, and 0 a pixel without a line.
;
;
; MODIFICATION HISTORY: Vivienne Wild, vw@ast.cam.ac.uk, 05/01/05
;
;****************************************************************************************
FUNCTION MASKLINESQSO, Flux, Wave, Z, Linefile, Nfilt, silent=silent
if N_ELEMENTS(wave) ne N_ELEMENTS(flux) then message, 'flux and wave must be same size'
;read in line file:
;Note the broad lines have a single wavelength, the width of the mask
;is then set by the median filter size. The narrow lines have an upper
;and lower wavelength
OPENR, lun, linefile, /get_lun
nlines = 0
READF, lun, nlines
emlines = FLTARR(2,nlines)
READF, lun, emlines
FREE_LUN, lun
;create pixel mask
nbin = N_ELEMENTS(wave)
pixel_mask = FLTARR(nbin)
for i=0, nlines-1 do begin
ind = WHERE(wave/(1+z) ge emlines[0,i], count)
;the approx. size of the median filter in angstroms, observed frame
if count gt 2 then a = nfilt*(wave[ind[1]]-wave[ind[0]]) else continue
if emlines[0,i] eq emlines[1,i] then begin ;the broad lines
emlines[0,i] = emlines[0,i]*(1+z)-a/3.
emlines[1,i] = emlines[1,i]*(1+z)+a/3.
endif else begin ;the narrow lines
emlines[0,i] = emlines[0,i]*(1+z)
emlines[1,i] = emlines[1,i]*(1+z)
endelse
index = where(wave gt emlines[0,i] and wave lt emlines[1,i],count)
if count gt 0 then pixel_mask[index] = 1.
endfor
;warnings
junk = WHERE(pixel_mask eq 1,n)
if n eq 0 and NOT(KEYWORD_SET(silent)) then print, 'masklines_qso.pro: no qso lines masked'
return, pixel_mask
end
|
import axios, { AxiosResponse } from "axios";
import { components } from "./models";
const API_BASE_URL =
process.env.NODE_ENV === "production"
? "https://pizzariag2api.herokuapp.com/api"
: "http://localhost:1337/api"; // URL base da API em ambiente local
// Função utilitária para realizar chamadas à API
async function apiRequest<T>(
path: string,
method: string,
data?: any
): Promise<AxiosResponse<T>> {
try {
const response = await axios.request<T>({
url: `${API_BASE_URL}${path}`,
method,
data,
});
return response;
} catch (error: any) {
throw new Error(error.response?.data?.message || "Error");
}
}
// Função para buscar todas as bebidas
export async function getBebidas(): Promise<components["schemas"]["Bebida"][]> {
const response = await apiRequest<components["schemas"]["Bebida"][]>(
"/bebidas",
"GET"
);
return response.data;
}
// Função para criar uma nova bebida
export async function criarBebida(
data: components["schemas"]["Bebida"]
): Promise<components["schemas"]["Bebida"]> {
const response = await apiRequest<components["schemas"]["Bebida"]>(
"/bebidas",
"POST",
data
);
return response.data;
}
// Função para buscar uma bebida por ID
export async function getBebidaById(
id: string
): Promise<components["schemas"]["Bebida"]> {
const response = await apiRequest<components["schemas"]["Bebida"]>(
`/bebidas/${id}`,
"GET"
);
return response.data;
}
// Função para atualizar uma bebida por ID
export async function atualizarBebidaById(
id: string,
data: components["schemas"]["Bebida"]
): Promise<components["schemas"]["Bebida"]> {
const response = await apiRequest<components["schemas"]["Bebida"]>(
`/bebidas/${id}`,
"PUT",
data
);
return response.data;
}
// Função para deletar uma bebida por ID
export async function deletarBebidaById(id: string): Promise<void> {
await apiRequest<void>(`/bebidas/${id}`, "DELETE");
}
// Função para buscar todos os cardápios
export async function getCardapios(): Promise<
components["schemas"]["Cardapio"][]
> {
const response = await apiRequest<components["schemas"]["Cardapio"][]>(
"/cardapios",
"GET"
);
return response.data;
}
// Função para criar um novo cardápio
export async function criarCardapio(
data: components["schemas"]["Cardapio"]
): Promise<components["schemas"]["Cardapio"]> {
const response = await apiRequest<components["schemas"]["Cardapio"]>(
"/cardapios",
"POST",
data
);
return response.data;
}
// Função para buscar um cardápio por ID
export async function getCardapioById(
id: string
): Promise<components["schemas"]["Cardapio"]> {
const response = await apiRequest<components["schemas"]["Cardapio"]>(
`/cardapios/${id}`,
"GET"
);
return response.data;
}
// Função para atualizar um cardápio por ID
export async function atualizarCardapioById(
id: string,
data: components["schemas"]["Cardapio"]
): Promise<components["schemas"]["Cardapio"]> {
const response = await apiRequest<components["schemas"]["Cardapio"]>(
`/cardapios/${id}`,
"PUT",
data
);
return response.data;
}
// Função para deletar um cardápio por ID
export async function deletarCardapioById(id: string): Promise<void> {
await apiRequest<void>(`/cardapios/${id}`, "DELETE");
}
// Função para fazer upload de arquivos
export async function uploadFiles(
data: FormData
): Promise<components["schemas"]["UploadFile"][]> {
const response = await apiRequest<components["schemas"]["UploadFile"][]>(
"/upload",
"POST",
data
);
return response.data;
}
// Função para buscar todos os arquivos
export async function getAllFiles(): Promise<
components["schemas"]["UploadFile"][]
> {
const response = await apiRequest<components["schemas"]["UploadFile"][]>(
"/upload/files",
"GET"
);
return response.data;
}
// Função para buscar um arquivo por ID
export async function getFileById(
id: string
): Promise<components["schemas"]["UploadFile"]> {
const response = await apiRequest<components["schemas"]["UploadFile"]>(
`/upload/files/${id}`,
"GET"
);
return response.data;
}
// Função para deletar um arquivo por ID
export async function deleteFileById(
id: string
): Promise<components["schemas"]["UploadFile"]> {
const response = await apiRequest<components["schemas"]["UploadFile"]>(
`/upload/files/${id}`,
"DELETE"
);
return response.data;
}
// Função para buscar todos os combos
export async function getCombos(): Promise<components["schemas"]["Combo"][]> {
const response = await apiRequest<components["schemas"]["Combo"][]>(
"/combos",
"GET"
);
return response.data;
}
// Função para criar um novo combo
export async function criarCombo(
data: components["schemas"]["Combo"]
): Promise<components["schemas"]["Combo"]> {
const response = await apiRequest<components["schemas"]["Combo"]>(
"/combos",
"POST",
data
);
return response.data;
}
// Função para buscar um combo por ID
export async function getComboById(
id: string
): Promise<components["schemas"]["Combo"]> {
const response = await apiRequest<components["schemas"]["Combo"]>(
`/combos/${id}`,
"GET"
);
return response.data;
}
// Função para atualizar um combo por ID
export async function atualizarComboById(
id: string,
data: components["schemas"]["Combo"]
): Promise<components["schemas"]["Combo"]> {
const response = await apiRequest<components["schemas"]["Combo"]>(
`/combos/${id}`,
"PUT",
data
);
return response.data;
}
// Função para deletar um combo por ID
export async function deletarComboById(id: string): Promise<void> {
await apiRequest<void>(`/combos/${id}`, "DELETE");
}
// Função para buscar todos os pedidos
export async function getPedidos(): Promise<components["schemas"]["Pedido"][]> {
const response = await apiRequest<components["schemas"]["Pedido"][]>(
"/pedidos",
"GET"
);
return response.data;
}
// Função para criar um novo pedido
export async function criarPedido(
data: components["schemas"]["Pedido"]
): Promise<components["schemas"]["Pedido"]> {
const response = await apiRequest<components["schemas"]["Pedido"]>(
"/pedidos",
"POST",
data
);
return response.data;
}
// Função para buscar um pedido por ID
export async function getPedidoById(
id: string
): Promise<components["schemas"]["Pedido"]> {
const response = await apiRequest<components["schemas"]["Pedido"]>(
`/pedidos/${id}`,
"GET"
);
return response.data;
}
// Função para atualizar um pedido por ID
export async function atualizarPedidoById(
id: string,
data: components["schemas"]["Pedido"]
): Promise<components["schemas"]["Pedido"]> {
const response = await apiRequest<components["schemas"]["Pedido"]>(
`/pedidos/${id}`,
"PUT",
data
);
return response.data;
}
// Função para deletar um pedido por ID
export async function deletarPedidoById(id: string): Promise<void> {
await apiRequest<void>(`/pedidos/${id}`, "DELETE");
}
// Função para buscar todos os sabores
export async function getSabores(): Promise<components["schemas"]["Sabor"][]> {
const response = await apiRequest<components["schemas"]["Sabor"][]>(
"/sabors",
"GET"
);
return response.data;
}
// Função para criar um novo sabor
export async function criarSabor(
data: components["schemas"]["Sabor"]
): Promise<components["schemas"]["Sabor"]> {
const response = await apiRequest<components["schemas"]["Sabor"]>(
"/sabors",
"POST",
data
);
return response.data;
}
// Função para buscar um sabor por ID
export async function getSaborById(
id: string
): Promise<components["schemas"]["Sabor"]> {
const response = await apiRequest<components["schemas"]["Sabor"]>(
`/sabors/${id}`,
"GET"
);
return response.data;
}
// Função para atualizar um sabor por ID
export async function atualizarSaborById(
id: string,
data: components["schemas"]["Sabor"]
): Promise<components["schemas"]["Sabor"]> {
const response = await apiRequest<components["schemas"]["Sabor"]>(
`/sabors/${id}`,
"PUT",
data
);
return response.data;
}
// Função para deletar um sabor por ID
export async function deletarSaborById(id: string): Promise<void> {
await apiRequest<void>(`/sabors/${id}`, "DELETE");
}
// Função para fazer login local
export async function localLogin(data: {
identifier: string;
password: string;
}): Promise<components["schemas"]["Users-Permissions-UserRegistration"]> {
const response = await apiRequest<
components["schemas"]["Users-Permissions-UserRegistration"]
>("/auth/local", "POST", data);
return response.data;
}
// Função para registrar um usuário localmente
export async function localRegister(data: {
username: string;
email: string;
password: string;
}): Promise<components["schemas"]["Users-Permissions-UserRegistration"]> {
const response = await apiRequest<
components["schemas"]["Users-Permissions-UserRegistration"]
>("/auth/local/register", "POST", data);
return response.data;
}
|
/**
* 1. 문제정보
* - 제목 : 동명 동물 수 찾기
* - 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/59041
* 2. 풀이핵심
* - GROUP BY, HAVING을 같이 봐야함
* 3. 풀이후기
* - GROUP BY를 자주해본적이 없어 또 어색한 문법은 만났다.
*/
SELECT A.NAME, COUNT(A.NAME) AS COUNT
FROM ANIMAL_INS A
WHERE A.NAME IS NOT NULL
GROUP BY A.NAME
HAVING COUNT >= 2
ORDER BY A.NAME;
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint
from generators import tissue_image_generator, pix2pix_generator
def extract_patches_2ds(x, kernel_size, padding=0, stride=1):
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
if isinstance(padding, int):
padding = (padding, padding, padding, padding)
if isinstance(stride, int):
stride = (stride, stride)
channels = x.shape[1]
x = torch.nn.functional.pad(x, padding)
# (B, C, H, W)
x = x.unfold(2, kernel_size[0], stride[0]).unfold(3, kernel_size[1], stride[1])
# (B, C, h_dim_out, w_dim_out, kernel_size[0], kernel_size[1])
# x = x.contiguous().view(-1, channels, kernel_size[0], kernel_size[1])
# (B * h_dim_out * w_dim_out, C, kernel_size[0], kernel_size[1])
x = x.permute(0, 2, 3, 1, 4, 5).contiguous()
return x
def combine_patches_2d(x, kernel_size, output_shape, stride=1, padding=0, dilation=0):
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
if isinstance(padding, int):
padding = (padding, padding)
if isinstance(stride, int):
stride = (stride, stride)
if isinstance(dilation, int):
dilation = (dilation, dilation)
def get_dim_blocks(dim_in, dim_kernel_size, dim_padding=0, dim_stride=1, dim_dilation=1):
dim_out = (dim_in + 2 * dim_padding - dim_dilation * (dim_kernel_size - 1) - 1) // dim_stride + 1
return dim_out
channels = x.shape[3]
h_dim_out, w_dim_out = output_shape[2:]
h_dim_in = get_dim_blocks(h_dim_out, kernel_size[0], padding[0], stride[0], dilation[0])
w_dim_in = get_dim_blocks(w_dim_out, kernel_size[1], padding[1], stride[1], dilation[1])
# (B * h_dim_in * w_dim_in, C, kernel_size[0], kernel_size[1])
x = x.permute(0, 3, 1, 2, 4, 5)
# x = x.view(-1, channels, h_dim_in, w_dim_in, kernel_size[0], kernel_size[1])
# (B, C, h_dim_in, w_dim_in, kernel_size[0], kernel_size[1])
x = x.permute(0, 1, 4, 5, 2, 3)
# (B, C, kernel_size[0], kernel_size[1], h_dim_in, w_dim_in)
x = x.contiguous().view(-1, channels * kernel_size[0] * kernel_size[1], h_dim_in * w_dim_in)
# (B, C * kernel_size[0] * kernel_size[1], h_dim_in * w_dim_in)
x = torch.nn.functional.fold(x, (h_dim_out, w_dim_out), kernel_size=(kernel_size[0], kernel_size[1]),
padding=padding, stride=stride, dilation=dilation)
# (B, C, H, W)
return x
class SAFRONModel(nn.Module):
def __init__(self, generator='pix2pix',
mode='train',
normalization='instance', activation='leakyrelu-0.2',
**kwargs):
super(SAFRONModel, self).__init__()
self.mode = mode
self.generator = generator
self.context_encoder_block = self.build_context_encoder_block(3)
if(self.generator == 'pix2pix'):
self.image_generator = pix2pix_generator(in_channels=3)
elif(self.generator == 'residual'):
self.image_generator = tissue_image_generator(input_nc=3,
output_nc=3,
n_blocks_global=5,
n_downsample_global=3,
ngf=64,
norm=normalization)
else:
raise "Give valid generator name"
self.context_encoder_block.cuda()
self.image_generator.cuda()
def build_context_encoder_block(self, dim):
layers = []
layers.append(nn.Conv2d(dim, dim, kernel_size=41))
layers.append(nn.BatchNorm2d(dim))
layers.append(nn.ReLU())
return nn.Sequential(*layers)
def forward(self, mask, generator_mode = "safron"):
if(generator_mode == "pix2pix"):
return self.image_generator(mask)
if(self.mode == 'train'):
mask = nn.ConstantPad2d(20, 0)(mask)
patches = extract_patches_2ds(mask, kernel_size=296, stride=236)
num_patches = patches.shape[1]
output_patches = []
for i in range(0,num_patches):
output_patches_in = []
for j in range(0,num_patches):
input_mask_patch = patches[0][i][j].unsqueeze(0)
patch_pred = self.context_encoder_block(input_mask_patch)
patch_pred = self.image_generator(patch_pred)
output_patches_in.append(patch_pred)
output_patches_in = torch.cat(output_patches_in)
output_patches.append(output_patches_in)
output_patches = torch.stack(output_patches).unsqueeze(0)
divider_tensor = torch.ones_like(output_patches).cuda()
divider_tensor = combine_patches_2d(divider_tensor, kernel_size=256, stride=236, output_shape=(1, 3, 728, 728), dilation=1)
image_pred = combine_patches_2d(output_patches, kernel_size=256, stride=236, output_shape=(1, 3, 728, 728), dilation=1)
image_pred = image_pred / divider_tensor
else:
patch_pred = self.context_encoder_block(mask)
image_pred = self.image_generator(patch_pred)
return image_pred
|
import {
APIGatewayProxyHandler,
APIGatewayProxyEvent,
APIGatewayProxyResult,
} from 'aws-lambda';
import { z } from 'zod';
import {
BaseError,
InternalError,
NotFoundError,
ValidationError,
} from 'src/errors/errors';
import { UserRepository } from 'src/db/Repository/UserRepository';
import { ProfileRepository } from 'src/db/Repository/ProfileRepository';
import { Profile } from 'src/entity';
const createProfileBodySchema = z.object({
userEmail: z.string(),
profileImage: z.string().nullable(),
bannerImage: z.string().nullable(),
bannerColor: z.string(),
profileName: z.string().min(1, 'Name must be included'),
bio: z.string().min(1, 'Bio must be included'),
designation: z.string().min(1, 'Designation must be included'),
phone: z.string().min(1, 'Phone number must be included'),
profileEmail: z
.string()
.min(1, 'Email must be included')
.email('Invalid email'),
widgetProps: z.string().optional(),
});
export const createProfile: APIGatewayProxyHandler = async (
event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
try {
const body = JSON.parse(event.body || '{}');
try {
createProfileBodySchema.parse(body);
} catch (e) {
console.log(e);
if (e instanceof Error) {
throw new ValidationError(e.message);
}
throw new ValidationError('Bad request');
}
try {
const userRepository = new UserRepository();
const profileRepository = new ProfileRepository();
const userEmail = body.userEmail;
const user = await userRepository.getUserByEmail(userEmail);
if (!user) throw new NotFoundError('User not found');
console.log('Successfully retrieved user');
let profile = await user.profile;
console.log('Profile: ' + profile);
if (!profile) {
profile = new Profile();
}
profile.profileName = body.profileName;
profile.bio = body.bio;
profile.designation = body.designation;
profile.phone = body.phone;
profile.profileEmail = body.profileEmail;
profile.widgetProps = body.widgetProps;
profile.profileImage = body.profileImage;
profile.bannerImage = body.bannerImage;
profile.bannerColor = body.bannerColor;
console.log('Updated profile: ' + profile);
const savedProfile = await profileRepository.saveProfile(profile);
console.log('Saved profile');
user.profile = Promise.resolve(savedProfile);
await userRepository.saveUser(user);
return {
statusCode: 200,
body: JSON.stringify({ message: 'Success', savedProfile }),
};
} catch (e) {
console.log(e);
throw new InternalError('Error while saving profile');
}
} catch (e) {
console.log(e);
if (e instanceof BaseError)
return {
statusCode: e.httpCode,
body: JSON.stringify({ message: e.message }),
};
return {
statusCode: 500,
body: JSON.stringify({ message: 'Internal Server Error' }),
};
}
};
const getProfileBodySchema = z.object({
type: z.enum(['email']),
identifier: z.string(),
});
export const getProfile: APIGatewayProxyHandler = async (
event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
try {
const body = JSON.parse(event.body || '{}');
try {
getProfileBodySchema.parse(body);
} catch (e) {
console.log(e);
if (e instanceof Error) {
throw new ValidationError(e.message);
}
throw new ValidationError('Bad request');
}
try {
const profileRepository = new ProfileRepository();
let profile: Profile | null = null;
if (body.type === 'email') {
profile = await profileRepository.getProfileByUserEmail(
body.identifier
);
}
if (body.type === 'id') {
profile = await profileRepository.getProfile(body.identifier);
}
if (!profile) {
throw new NotFoundError('Profile not found');
}
return {
statusCode: 200,
body: JSON.stringify({ profile }),
};
} catch (e) {
console.log(e);
throw new InternalError('Error while retrieving profile');
}
} catch (e) {
console.log(e);
if (e instanceof BaseError)
return {
statusCode: e.httpCode,
body: JSON.stringify({ message: e.message }),
};
return {
statusCode: 500,
body: JSON.stringify({ message: 'Internal Server Error' }),
};
}
};
|
//
// KeyGenerator.swift
// JSONToStrings
//
// Created by Csaba Gyarmati on 2022. 05. 17..
// Copyright © 2022. Csaba Gyarmati. All rights reserved.
//
import Foundation
class KeyGenerator {
let stringKeys: [LocalizationKey]
let dirURL: URL
private var localizationKeys: [String: Any] = [:]
init(stringKeys: Set<LocalizationKey>, dirURL: URL) {
self.stringKeys = stringKeys.sorted()
self.dirURL = dirURL
}
func generateKeys() {
for key in stringKeys {
let keyComponents = key.split(separator: ".")
localizationKeys = addComponent(keyComponents, to: localizationKeys, key: key)
}
saveKeys(into: dirURL)
}
private func addComponent(_ keyComponents: [String.SubSequence], to dict: [String: Any], key: String) -> [String: Any] {
var components = keyComponents
var keyDict = dict
let rootComponent = String(components.removeFirst()).camelized
if keyDict.keys.contains(rootComponent) {
if let dict = keyDict[rootComponent] as? [String: Any] {
keyDict[rootComponent] = addComponent(components, to: dict, key: key)
} else if let keyString = keyDict[rootComponent] as? String {
if components.count > 0 {
assertionFailure("Key and dictionary conflict at \(keyString) in \(key)")
} else {
if keyString == key {
assertionFailure("Duplicated key \(key)")
}
}
}
} else {
if components.count > 0 {
keyDict[rootComponent] = addComponent(components, to: [:], key: key)
} else {
keyDict[rootComponent] = key
}
}
return keyDict
}
private func saveKeys(into dirURL: URL) {
var stringFile = "// Generated from Localizable.json\n\nimport Foundation\n\n// swiftlint:disable all\nstruct L {\n"
stringFile += createLine(from: localizationKeys, indent: 4)
stringFile += "}\n"
let fileURL = dirURL.appendingPathComponent("Localizable.swift")
do {
try stringFile.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("Error creating keys file.")
}
}
private func createLine(from keyDict: [String: Any], indent: Int) -> String {
var line = ""
for key in keyDict.keys.sorted() {
var allIndent = ""
for _ in 0..<indent { allIndent += " " }
if let dict = keyDict[key] as? [String: Any] {
line += "\(allIndent)struct \(key) {\n"
line += createLine(from: dict, indent: indent + 4)
line += "\(allIndent)}\n"
} else if let keyString = keyDict[key] as? String {
line += "\(allIndent)static let \(key) = \"\(keyString)\"\n"
}
}
return line
}
}
|
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:task/features/auth/registration.dart';
import '../../constants.dart';
import '../../core/provider/auth_provider.dart';
import '../../core/router/router.dart';
import '../../core/validate/validation.dart';
import '../../widgets/customButton.dart';
import '../../widgets/customScaffold.dart';
import '../../widgets/customTextFeild.dart';
import '../../widgets/main_text.dart';
class Login extends StatefulWidget {
const Login({Key? key}) : super(key: key);
@override
State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
final GlobalKey<FormState> _form = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
final auth = AuthProvider.get(context);
return CustomScaffold(
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 15.h),
child: AnimationConfiguration.synchronized(
duration: const Duration(milliseconds: 375),
child: SlideAnimation(
verticalOffset: 50.h,
child: FadeInAnimation(
child: Column(
children: [
60.h.hSpace,
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
MainText(
text: 'Sign In',
font: 24.sp,
color: kBlackColor,
weight: FontWeight.w600,
),
],
),
80.h.hSpace,
Form(
key: _form,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CustomTextField(
controller: auth.loginEmailController,
prefix: 'email_icon',
hint: 'Email',
type: TextInputType.emailAddress,
valid: (String? v) =>
!Validations.validateUserEmail(v!)
? 'Please Check Your Email Address'
: null,
),
20.h.hSpace,
CustomTextField(
controller: auth.loginPasswordController,
hint: 'Password',
prefix: 'password_icon',
type: TextInputType.visiblePassword,
isPassword: true,
valid: (String? v) => v!.isEmpty
? 'Please Enter your password'
: v.length < 8
? 'Make sure your password is not less than 8 characters'
: null,
),
25.h.hSpace,
CustomButton(
title: 'Sign In',
onPressed: () async {
if (_form.currentState!.validate()) {
await auth.login();
}
},
),
50.h.hSpace,
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
MainText(
text: 'Dont have an account' + '?',
font: 17.sp,
color: kBlackColor,
weight: FontWeight.w400,
),
GestureDetector(
onTap: () {
MagicRouter.navigateAndPopAll(Register());
},
child: MainText(
text: ' Sign Up',
font: 17.sp,
color: kMainColor,
weight: FontWeight.w500,
),
),
],
),
],
),
),
),
],
),
),
),
),
),
);
}
}
|
import React from "react";
import { pacienteModelo } from "../utilidades/modelos";
import { Button, ButtonGroup, Card, Col, Container, ListGroup, Row } from "react-bootstrap";
import CitasPaciente from "../componentes/Citas.jsx";
import { useNavigate, useParams } from "react-router";
import AdvertenciaModal from "../modales/AdvertenciaModal.jsx";
import { borraHistoria, borraTokenIfUnauth, descargarArchivo, tokenHeader } from "../utilidades/funciones.js";
import HistoriaModal from "../modales/HistoriaModal";
import PacienteModal from "../modales/PacienteModal.jsx";
import AgregarCitaModal from "../modales/AgregarCitaModal.jsx";
class ClasePaciente extends React.Component{
constructor(props = {
idPaciente : 0,
nav : () => {}
}
){
super(props)
this.idPaciente = props.idPaciente,
this.nav=props.nav
this.state = {
paciente : pacienteModelo,
pacienteModal : {
paciente : {},
modoForm : true,
show: false
},
advertenciaModal : {
mensaje : "",
show : false,
funcion : () => {}
},
historiaModal : {
paciente : {},
rewrite: false,
show: false
},
agregarCitaModal : {
paciente : {},
show : false
}
}
}
borraPaciente(idPaciente = 0){
try{
fetch(`http://localhost:8080/api/pacientes?idPaciente=${idPaciente}`, {
method: 'DELETE',
...tokenHeader
})
.then(res => {
borraTokenIfUnauth(res)
if(res.ok){
this.nav("/", {replace : true})
}else{
throw new Error("no se pudo borrar el paciente")
}
})
}catch(e){
console.log(e)
}
}
fetchPaciente(){
try{
if(!parseInt(this.idPaciente)) throw new Error()
fetch(`http://localhost:8080/api/pacientes/id?idPaciente=${this.idPaciente}`, tokenHeader)
.then(res => {
borraTokenIfUnauth(res)
if (res.status == 204 || !res.ok) throw new Error()
return res.json()
})
.then((resJson) => {
if (!Object.values(resJson)) throw new Error()
this.setState({paciente : resJson})
})
.catch(e => {
return this.nav("/", {replace : true})
})
}catch(e){
return this.nav("/", {replace : true})
}
}
handleDescarga(paciente = pacienteModelo){
try{
descargarArchivo(paciente.historia.urlDocumentoHistoria)
}catch(e){
console.log(e)
}
}
componentDidMount(){
try{
this.fetchPaciente();
}catch(e){
console.log(e);
}
}
render(){
let {paciente} = this.state;
let setBorraPaciente = () => {
this.setState({
...this.state,
advertenciaModal : {
mensaje : "¿Seguro de que quieres borrar este paciente?",
funcion : () => this.borraPaciente(paciente.idPaciente),
show : true
}
})
}
let setBorraHistoria = () => {
this.setState({
...this.state,
advertenciaModal : {
mensaje : "¿Seguro de que quieres borrar esta historia?",
funcion : () => borraHistoria(paciente.historia),
show : true
}
})
}
let setAgregarCita = () => {
this.setState({
...this.state,
agregarCitaModal : {
paciente : paciente,
show : true
}
})
}
const UltimaCita = () => {
if(!!paciente && !!paciente.citas && !!paciente.citas.length){
const ultimaCita = new Date(Math.max(...paciente.citas.map(cita => new Date(cita.fechaCita))));
return(
<ListGroup.Item className="text-white bg-info">
Ultima cita: {ultimaCita.toLocaleDateString('es-US', {timeZone: 'UTC'})}
</ListGroup.Item>
)
}else{
return
}
};
const DatosDelPaciente = (props = {className : ""}) => {
return (
<Container {...props}>
<Card>
<Card.Body>
<Card.Title className="d-flex justify-content-between align-items-center">
Datos personales
<Button size="sm" onClick={() => this.setState({pacienteModal : {paciente : paciente, show : true, modoForm :true}})}>
Cambiar datos
</Button>
</Card.Title>
<ListGroup className="mt-3">
<UltimaCita />
{
!!paciente.cedulaPaciente && <ListGroup.Item className="list-group-item">Cédula: {paciente.cedulaPaciente}</ListGroup.Item>
}
{
!!paciente.telefonoPaciente && <ListGroup.Item className="list-group-item">Teléfono: {paciente.telefonoPaciente}</ListGroup.Item>
}
</ListGroup>
</Card.Body>
<Card.Footer>
<ButtonGroup className="w-100">
{
paciente.historia ?
<>
<Button onClick={() => this.handleDescarga(paciente)}>
Descargar historia
</Button>
<Button className="border" variant="light" onClick={() => this.setState({historiaModal : {paciente : paciente, rewrite : true, show : true}})}>
Modificar historia
</Button>
<Button variant="danger" onClick={setBorraHistoria}>
Borrar historia
</Button>
</>
:
<Button onClick={() => this.setState({historiaModal : {paciente : paciente, show : true}})}>
Agregar historia
</Button>
}
</ButtonGroup>
</Card.Footer>
</Card>
</Container>
)
}
const Botonera = (props = {size : undefined, className : ""}) => {
return (
<div className={props.className}>
<ButtonGroup className="w-100 mt-2">
<Button size={props.size} onClick={setAgregarCita}>Agregar cita</Button>
</ButtonGroup>
<ButtonGroup className="w-100 mt-2">
<Button size={props.size} variant="danger" onClick={setBorraPaciente}>Borrar paciente</Button>
</ButtonGroup>
</div>
)
}
const Body = () => {
if(!!paciente.citas.length){
return (
<Row className="mt-2">
<Col lg={8}>
<CitasPaciente citas={paciente.citas} />
</Col>
<Col lg={4}>
<Row>
<DatosDelPaciente/>
<Botonera/>
</Row>
</Col>
</Row>
)
}else{
return (
<Row>
<Col lg={8}>
<Row>
<Botonera size={"lg"} className="mb-3 w-100"/>
</Row>
</Col>
<Col lg={4}>
<Row>
<DatosDelPaciente className="mt-2"/>
</Row>
</Col>
</Row>
)
}
}
return(
<Container>
<h1 className="display-4">
{`${paciente.nombrePaciente} ${paciente.apellidoPaciente}`}
</h1>
<hr className="mt-2" />
<Body />
<AdvertenciaModal
mensaje={this.state.advertenciaModal.mensaje}
show = {this.state.advertenciaModal.show}
funcion={this.state.advertenciaModal.funcion}
onHide={() => this.setState({ ...this.state, advertenciaModal : {...this.state.advertenciaModal, show : false}})}
/>
<HistoriaModal
paciente={this.state.historiaModal.paciente}
rewrite={this.state.historiaModal.rewrite}
show = {this.state.historiaModal.show}
onHide={() => this.setState({historiaModal : {...this.state.historiaModal, show :false}})}
/>
<PacienteModal
paciente={this.state.pacienteModal.paciente}
show = {this.state.pacienteModal.show}
modoForm={this.state.pacienteModal.modoForm}
setModoForm={(val = false) => this.setState({pacienteModal : {...this.state.pacienteModal, show :false, modoForm :true}})}
//oculta
onHide={() => {
this.setState({pacienteModal : {...this.state.pacienteModal, show :false, modoForm :true}})
}}
/>
<AgregarCitaModal
paciente={this.state.agregarCitaModal.paciente}
show = {this.state.agregarCitaModal.show}
onHide={() => {
this.setState({agregarCitaModal : {...this.state.agregarCitaModal, show :false}})
}}
/>
</Container>
)
}
}
export default function Paciente (props){
const {idPaciente} = useParams()
const nav = useNavigate()
return (
<ClasePaciente idPaciente={idPaciente} {...props} nav={nav}/>
)
}
|
import 'package:flutter/material.dart';
import 'package:portefolio/common/objects.dart';
import 'package:portefolio/common/style.dart';
class MyDrawer extends StatefulWidget {
final Color backgroundColor;
final int selectedIndex;
final ValueChanged<int> onDestinationSelected;
final VoidCallback callback;
const MyDrawer(
{required this.backgroundColor,
required this.onDestinationSelected,
required this.selectedIndex,
required this.callback,
super.key});
@override
State<MyDrawer> createState() => _MyDrawerState();
}
class _MyDrawerState extends State<MyDrawer> {
bool _isReorder = false;
@override
Widget build(BuildContext context) {
return Drawer(
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ReorderableListView.builder(
shrinkWrap: true,
itemCount: pages.value.length,
itemBuilder: (context, index) {
return TextButton(
key: pages.value[index].key,
onPressed: () => widget.onDestinationSelected(index),
child: Text(
pages.value[index].label,
style: subtitle.copyWith(
color: index == widget.selectedIndex
? Theme.of(context).primaryColor
: null),
),
);
},
header: const Column(
children: [
Center(
child: SizedBox(
height: 150,
width: 150,
child: CircleAvatar(
backgroundImage: AssetImage("assets/photo.png"),
),
),
),
SizedBox(
height: 30,
)
],
),
footer: _isReorder
? TextButton(
onPressed: widget.callback,
child: const Text("Valider la réorganisation"),
)
: null,
onReorder: (int oldIndex, int newIndex) {
setState(() {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final MyPages item = pages.value.removeAt(oldIndex);
pages.value.insert(newIndex, item);
_isReorder = true;
});
}),
),
));
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>路由管理</title>
</head>
<body>
<div id="app">
<div class="header">
<h1>头部</h1>
</div>
<div class="left">
<p>
<ul>
<li><a href="#/foo">Go Foo</a></li>
<li><a href="#/bar">Go Bar</a></li>
<!--
官方推荐:
通过 router-link 标签会默认渲染出 a 标签来
其中 通过 to 属性指定跳转链接,不用带上 # 号
-->
<li>
<router-link to="/foo">Go to Foo</router-link>
</li>
<li>
<router-link to="/bar">Go to Bar</router-link>
</li>
</ul>
</p>
</div>
<div class="main">
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/vue-router/dist/vue-router.js"></script>
<script>
// 1. 定义组件
const Foo = {
template: '<div> 我是 Foo 组件</div>'
}
const Bar = {
template: '<div> 我是 Bar 组件</div>'
}
// 2. 配置路由表: 当点击指定 url 时,显示对应的那个组件
const router = new VueRouter({
routes: [ // 注意单词复数形式,是 routes 不是 router
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
})
// 3. 将路由器注入到实例中
new Vue({
el: '#app',
router // router: router
})
</script>
</body>
</html>
|
//Program Name: Minimum Spanning Tree
//Programmer Name: Aleks Savich
//Description:Program will determine the minimum spanning tree of a complete tree from an input file and determine the weight.
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <string>
#include <vector>
#include <queue>
# define INF 0x3f3f3f3f
using namespace std;
typedef pair<int, int> iPair;
class AdjacencyList {
int V; // No. of vertices
list< pair<int, int> >* adj; // creates a list pair called adj
public:
AdjacencyList(int V); // Constructor
void addEdge(int u, int v, int w); // function to add an edge to AdjacencyList
void primMST(int a, int b, int c); //function for prims minimum spanning tree
void shortestPath(int a, int b); // creates shortest path using Dijkstras algorithm
};
// Pre-condition: integer v which is number of vertices
// Post-condition: this pointer to V and a new list called adj
AdjacencyList::AdjacencyList(int V) { // constructor
this->V = V;
adj = new list<iPair>[V];
}
// Pre-condition: integer u which is vertex 1, integer v ehich is vertex 2, and weight which is weight of edge between u and v
// Post-condition: make two pairs, (v,w) and (u,w)
void AdjacencyList::addEdge(int u, int v, int w) { // creates edge between two vertices with a weight
adj[u].push_back(make_pair(v, w));
adj[v].push_back(make_pair(u, w));
}
// Pre-condition: int a,b,c and char d
// Post-condition: A MST is created using a priority queue and the total weight of that MST
void AdjacencyList::primMST(int a, int b, int c) // prims minimum spanning tree
{
int totalWeight = 0;
priority_queue< iPair, vector <iPair>, greater<iPair> > pq; // creates priority queue
int src = 0; // Taking vertex 0 as source
// Create a vector for keys and initialize all
// keys as infinite (INF)
vector<int> key(V, INF); // creates vector for key
vector<int> parent(V, -1); // To store parent array which in turn store MST
vector<int> weightMST(V, -1);
vector<bool> inMST(V, false); // keeps track of vertices in MST
// Insert source itself in priority queue and initialize
// its key as 0.
pq.push(make_pair(0, src));
key[src] = 0; // makes source of graph 0
while (!pq.empty()) // loop until priority queue is empty
{
int u = pq.top().second; // takes first vertex from pair
pq.pop(); // pop pq
inMST[u] = true; // Include vertex in MST
// 'i' is used to get all adjacent vertices of a vertex
list< pair<int, int> >::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i){
int v = (*i).first; // Get vertex of current adjacent of u
int weight = (*i).second; // Get weight of current adjacent of u
/* a and b are vertices that want to be edited by user */
if (((a == u) && (b == v)) || ((a == v) && (b == u))) { // checks if vertices equal to edited vertices and adds or subtracts the weight from what user enters.
weight += c; // c is the weight the user wants to add/subtract to the edge
}
if (weight <= 0) { // if the new weight is less than 0 tell user the error and return
cout << "Error! The weight is <= 0" << endl;
return; // return since if weight is <= 0 it cant be added
}
else {
// If v is not in MST and weight of (u,v) is smaller
// than current key of v
if (inMST[v] == false && key[v] > weight) {
key[v] = weight; // Updating key of v
pq.push(make_pair(key[v], v));// make pair
parent[v] = u;
weightMST[v] = weight; // keeps track of weight of MST
}
}
}
}
for (int i = 1; i < V; ++i) { // Print edges of MST using parent array
totalWeight += weightMST[i]; // adds total weight from MST
if (i == V - 1) { // prints out to user the sum of the MST
cout << weightMST[i] << "=";
cout << weightMST[i] << "=";
}
else {
cout << weightMST[i] << "+";
}
}
cout << totalWeight << endl; // outputs final sum of MST
}
// Pre-condition: int a and int b where a is vertex 1 and b is vertex 2
// Post-condition: The shortest path(least weight) Between vertex a and b that is made using Djikstra's algorithm
void AdjacencyList::shortestPath(int a, int b) { // shortest path using Djikstars Algorithm
int shortWeight = 100;// used to compare weights from each edge
int shortWeightTotal = 0; // counts total weight of the shortest path
int place = a; // keeps track of which node is being added to the shortest path and only to make comparisons including that node
int holdPlace = 0;
priority_queue< iPair, vector <iPair>, greater<iPair> > cq;
vector<int> dist(V, INF);
cq.push(make_pair(0, a));
dist[a] = 0;
while (!cq.empty()){
int u = cq.top().second; // extract from priority queue
cq.pop();
// 'i' is used to get all adjacent vertices of a vertex
list< pair<int, int> >::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i){
// Get vertex label and weight of current adjacent
// of u.
int v = (*i).first;
int weight = (*i).second;
// If there is shorted path to v through u.
if (((u >= a) && (u <= b)) && ((v >= a) && (v <= b))) { // will only use the range of nodes the user has specified to use.
if (dist[v] > dist[u] + weight)
{
// Updating distance of v
dist[v] = dist[u] + weight;
cq.push(make_pair(dist[v], v));
if ((dist[v] - shortWeightTotal < shortWeight) && (u == place)) {
shortWeight = dist[v] - shortWeightTotal;
holdPlace = v;
}
}
}
}
place = holdPlace;
if (shortWeight != 100) {
shortWeightTotal += shortWeight;
if (place == b) {
cout << shortWeight << "=";
}
else {
cout << shortWeight << "+";
}
}
shortWeight = 100;
}
cout << shortWeightTotal << endl; // outputs total weight of shortest path to user
}
int main() {
int V; // # of vertices in program
int E; // # of edges in program
int vertex; // first vertex from each line from input file
int editVertex; // first vertex user wants to edit
int vertex2; // second vertex from each line of input file
int editVertex2; // second vertex user wants to edit
int weight; // weight from each line of input file
int editWeight; // weight user wants to edit
int numLines = -1; // counts number of lines in file to check if empty or not
char editChar; // command user wanst to use
bool eExists = false; // checkif edge exists or not
string unused; // used for getline to count lines in file
string fileName; // input file
string ofsFileName; // output file
ifstream file;
ofstream ofsFile;
cout << "Welcome to Internet Grid Optimization Program" << endl;
cout << "Enter in input file: ";
cin >> fileName; // input file name
file.open(fileName); // open input file
if (!file.is_open()) { // if file cannot open, tell user file doesn exist
cout << "Input file name provided does not exist";
exit(0);
}
while (file.good()) { // while file has lines, keep adding one to numLines to get total number of lines in file.
getline(file, unused);
numLines++;
}
cout << "Enter in output file: ";
cin >> ofsFileName; // input outfile name
ofsFile.open(ofsFileName); // create and open outfile name
ofsFile << "Welcome to Internet Grid Optimization Program" << endl;
if (numLines == 0) { // if the number of lines is 0 in the input file, tell user file exists with no data.
cout << "Input file exists but contains no data - program ended"; // output to user
ofsFile << "Input file exists but contains no data - program ended"; //output to file
file.close(); // close input file
ofsFile.close(); // close output file
return 0; // since no data exists, end program
}
file.close();
file.open(fileName);
file >> V;
file >> E;
AdjacencyList g(V);
vector< list< pair<int, int> > > adjacencyList(V + 1);
cout << "Creating file from " << fileName << endl;
cout << "Graph will contain " << V << " verticies and " << E << " edges" << endl;
cout << "Verticies: ";
for (int i = 0; i < V; i++) {
cout << i;
if (i != V - 1) {
cout << ",";
}
}
cout << endl;
for (int i = 0; i < E; i++) { // takes each line of input file and sets them to the appropiate variable
file >> vertex;
file >> vertex2;
file >> weight;
cout << "Vertex 1: " << vertex;
ofsFile << "Vertex 1: " << vertex;
cout << " Vertex 2: " << vertex2;
ofsFile << " Vertex 2: " << vertex2;
cout << " Weight: " << weight << " ";
ofsFile << " Weight: " << weight << " ";
if ((vertex >= V) || (vertex < 0)) { // If first vertex is not within range of available verticies
cout << "Error! Invalid vertex: " << vertex << " is not a valid vertex" << endl;; // tell user vertex is not valid
ofsFile << "Error! Invalid vertex: " << vertex << " is not a valid vertex" << endl; // tell user vertex is not valid
E--; // decrease edges by one since an edge is not created.
}
else if ((vertex2 >= V) || (vertex2 < 0)) { // If second vertex is not within range of available verticies
cout << "Error! Invalid vertex: " << vertex2 << " is not a valid vertex " << endl;; // tell user vertex is not valid
ofsFile << "Error! Invalid vertex: " << vertex2 << " is not a valid vertex" << endl; // tell user vertex is not valid
E--; // decrease edges by one since an edge is not created.
}
else if (weight <= 0) {
cout << "Error! Invalid weight(<=0): " << weight << " is not a valid weight" << endl;
ofsFile << "Error! Invalid weight(<=0): " << weight << " is not a valid weight" << endl;
E--; // decrease edges by one since an edge is not created.
}
else { // output on screen the two verticies and the weight
cout << endl;
ofsFile << endl;
g.addEdge(vertex, vertex2, weight); // add edge in tree
adjacencyList[vertex].push_back(make_pair(vertex2, weight)); // add to the adjacency list
}
}
ofsFile << "File has " << V << " vertices and " << E << " edges." << endl;
for (int i = 0; i < adjacencyList.size() - 1; ++i) { // prints adjacency list
printf("adj[%d]", i);
list< pair<int, int> >::iterator itr = adjacencyList[i].begin();
while (itr != adjacencyList[i].end()) { // while adjacency list is not at the end, out output adjacency list
printf(" -> [%d,%d]", (*itr).first, (*itr).second);
++itr;
}
printf("\n");
}
g.primMST(0, 0, 0);
file.close(); //close input file
cout << "Enter in the edit you would like to make or X if you would like to exit program: ";
ofsFile << "Enter in the edit you would like to make or X if you would like to exit program: ";
cin >> editChar;
while (editChar != 'X') {
if (editChar == 'E') { // creates new edge in tree only if edge doesnt currently exist
cout << "Vertex 1: ";
ofsFile << "Vertex 1: ";
cin >> editVertex; // enter in the vertices and the weight you would like to edit
while ((editVertex < 0) || (editVertex > V)) {
cout << "Invalid Vertex. Please enter in a valid vertex: ";
ofsFile << "Invalid Vertex. Please enter in a valid vertex: ";
cin >> editVertex;
}
cout << "Vertex 2: ";
ofsFile << "Vertex 2: ";
cin >> editVertex2;
while ((editVertex2 < 0) || (editVertex2 > V) || (editVertex == editVertex2)) {
cout << "Invalid Vertex. Please enter in a valid vertex: ";
ofsFile << "Invalid Vertex. Please enter in a valid vertex: ";
cin >> editVertex2;
}
cout << "Weight: ";
ofsFile << "Weight: ";
cin >> editWeight;
while (editWeight < 0) {
cout << "Invalid Weight. Please enter in a valid Weight ";
ofsFile << "Invalid Weight. Please enter in a valid Weight ";
cin >> editVertex;
}
file.open(fileName); // open input file and getline once
getline(file, unused);
for (int i = 0; i < E; i++) { // goes through each line of input file to check if the vertices that wante to be edited already exist
file >> vertex;
file >> vertex2;
file >> weight;
if (((editVertex == vertex) && (editVertex2 == vertex2)) || ((editVertex == vertex2) && (editVertex2 == vertex))) {
cout << "The edge you are trying to add already exists" << endl;
ofsFile << "The edge you are trying to add already exists" << endl;
eExists = true;
i = E;
}
}
if (eExists == false) { // if the edge does not exist, then create a new edge
g.addEdge(editVertex, editVertex2, editWeight); // calls add edge function with new vertices and new weights as parameters
adjacencyList[editVertex].push_back(make_pair(editVertex2, editWeight)); // add to the adjacency list
g.primMST(0, 0, 0);
for (int i = 0; i < adjacencyList.size() - 1; ++i) { // prints adjacency list
printf("adj[%d]", i);
list< pair<int, int> >::iterator itr = adjacencyList[i].begin();
while (itr != adjacencyList[i].end()) { // while adjacency list is not at the end, out output adjacency list
printf(" -> [%d,%d]", (*itr).first, (*itr).second);
++itr;
}
printf("\n");
}
}
file.close(); // close input file
}
else if (editChar == 'I') { // increase existing edge by a certain weight
cout << "Vertex 1: ";
ofsFile << "Vertex 1: ";
cin >> editVertex;
while ((editVertex < 0) || (editVertex > V)) {
cout << "Invalid Vertex. Please enter in a valid vertex ";
ofsFile << "Invalid Vertex. Please enter in a valid vertex ";
cin >> editVertex;
}
cout << "Vertex 2: ";
cin >> editVertex2;
while ((editVertex2 < 0) || (editVertex2 > V) || (editVertex == editVertex2)) {
cout << "Invalid Vertex. Please enter in a valid vertex ";
ofsFile << "Invalid Vertex. Please enter in a valid vertex ";
cin >> editVertex2;
}
cout << "Weight: ";
ofsFile << "Weight: ";
cin >> editWeight;
while (editWeight < 0) {
cout << "Invalid Weight. Please enter in a valid Weight ";
ofsFile << "Invalid Weight. Please enter in a valid Weight ";
cin >> editVertex;
}
file.open(fileName);
getline(file, unused);
for (int i = 0; i < E; i++) {
file >> vertex;
file >> vertex2;
file >> weight;
if (((editVertex == vertex) && (editVertex2 == vertex2)) || ((editVertex == vertex2) && (editVertex2 == vertex))) {
eExists = true;
g.primMST(editVertex, editVertex2, editWeight);
}
}
if (eExists == false) { // if edge does not exist, tell user the edge does not exist
cout << "The edge you are trying to edit does not exist" << endl;
ofsFile << "The edge you are trying to edit does not exist" << endl;
}
file.close(); // file close
}
else if (editChar == 'D') { // Command D is to decrease the weight of an existing edge
cout << "Vertex 1: ";
ofsFile << "Vertex 1: ";
cin >> editVertex;
while ((editVertex < 0) || (editVertex > V)) {
cout << "Invalid Vertex. Please enter in a valid vertex ";
ofsFile << "Invalid Vertex. Please enter in a valid vertex ";
cin >> editVertex;
}
cout << "Vertex 2: ";
ofsFile << "Vertex 2: ";
cin >> editVertex2;
while ((editVertex2 < 0) || (editVertex2 > V) || (editVertex == editVertex2)) {
cout << "Invalid Vertex. Please enter in a valid vertex ";
ofsFile << "Invalid Vertex. Please enter in a valid vertex ";
cin >> editVertex2;
}
cout << "Weight: ";
cin >> editWeight;
while (editWeight < 0) {
cout << "Invalid Weight. Please enter in a valid Weight ";
ofsFile << "Invalid Weight. Please enter in a valid Weight ";
cin >> editVertex;
}
file.open(fileName);
getline(file, unused);
for (int i = 0; i < E; i++) {
file >> vertex;
file >> vertex2;
file >> weight;
if (((editVertex == vertex) && (editVertex2 == vertex2)) || ((editVertex == vertex2) && (editVertex2 == vertex))) {
eExists = true;
editWeight *= -1;
g.primMST(editVertex, editVertex2, editWeight); // call prims MST with new vertices and weight parameters
}
}
if (eExists == false) { // if edge does not exist, tell user edge does not exist
cout << "The edge you are trying to edit does not exist" << endl;
ofsFile << "The edge you are trying to edit does not exist" << endl;
}
file.close(); // files close
}
else if (editChar == 'S') { // If S is entered print the shortest path from vertex one to vertex 2
cin >> editVertex;
cin >> editVertex2;
g.shortestPath(editVertex, editVertex2);
}
else {
cout << "Command you have entered is invalid: " << editChar << endl;
ofsFile << "Command you have entered is invalid: " << editChar << endl;
}
cout << "Enter in the edit you would like to make or X if you would like to exit program: ";
ofsFile << "Enter in the edit you would like to make or X if you would like to exit program: ";
cin >> editChar;
}
return 0;
}
|
package com.lavajato.spring.api.controllers;
import java.util.Collection;
import javax.validation.Valid;
import com.lavajato.spring.api.entity.Cliente;
import com.lavajato.spring.api.security.services.exceptions.ConstraintException;
import com.lavajato.spring.api.security.services.ClienteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "/cliente")
public class ClienteController {
@Autowired
private ClienteService service;
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Collection<Cliente>> findAll() {
Collection<Cliente> collection = service.findAll();
return ResponseEntity.ok().body(collection);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Cliente> find(@PathVariable Long id) {
Cliente obj = service.findById(id);
return ResponseEntity.ok().body(obj);
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Cliente> insert(@Valid @RequestBody Cliente obj, BindingResult br) {
if (br.hasErrors())
throw new ConstraintException(br.getAllErrors().get(0).getDefaultMessage());
obj = service.insert(obj);
return ResponseEntity.ok().body(obj);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
public ResponseEntity<Cliente> saveManager(@Valid @RequestBody Cliente obj, BindingResult br) {
if (br.hasErrors())
throw new ConstraintException(br.getAllErrors().get(0).getDefaultMessage());
obj = service.update(obj);
return ResponseEntity.ok().body(obj);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity<Cliente> update(@Valid @RequestBody Cliente obj, BindingResult br) {
if (br.hasErrors())
throw new ConstraintException(br.getAllErrors().get(0).getDefaultMessage());
obj = service.update(obj);
return ResponseEntity.ok().body(obj);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Void> delete(@PathVariable Long id) {
service.delete(id);
return ResponseEntity.noContent().build();
}
}
|
<div class="container">
<mat-toolbar color="primary" *ngIf="canEdit">
<mat-toolbar-row>
<span class="example-spacer"></span>
<button class="button" mat-stroked-button color="basic" (click)="openDialog()">Add new item to Product Catalogue</button>
</mat-toolbar-row>
</mat-toolbar>
<mat-card class="example-card" *ngFor="let product of products">
<mat-card-title>{{product.title}}</mat-card-title>
<mat-card-subtitle>Product category</mat-card-subtitle>
<img class="image" mat-card-image src="{{product.image}}"/>
<mat-card-actions>
<button class="button" mat-stroked-button (click)="addToBasket(product)" type="button">Add to basket</button>
<button class="button" mat-stroked-button [routerLink]="['/product', product.id]">More details</button>
<button class="button" mat-stroked-button mat-button [matMenuTriggerFor]="menu">Edit</button>
<mat-menu #menu="matMenu">
<button mat-menu-item (click)="deleteItem(product.id)">Delete</button>
<button mat-menu-item (click)="openDialog(product)">Update</button>
</mat-menu>
</mat-card-actions>
</mat-card>
</div>
|
#version 330 core
out vec4 FragColor;
in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoords;
struct Material {
sampler2D diffuse;
sampler2D specular;
float shininess;
};
struct Directional_Light {
vec3 ambient;
vec3 specular;
vec3 diffuse;
vec3 direction;
};
struct Point_Light {
vec3 ambient;
vec3 specular;
vec3 diffuse;
vec3 position;
float constant;
float linear;
float quadratic;
};
struct Spot_Light {
vec3 ambient;
vec3 specular;
vec3 diffuse;
vec3 position;
vec3 direction;
vec3 cutoff;
};
struct Light {
vec3 ambient;
vec3 diffuse;
vec3 specular;
vec3 position;
vec3 direction;
float cutoff;
float constant;
float linear;
float quadratic;
int type;
};
uniform vec3 lookPos;
uniform Material material;
uniform Directional_Light default_light;
uniform vec3 lightColour;
void main()
{
// calculate ambient lighting
float ambientStrength = 0.1;
vec3 ambient = ambientStrength * vec3(texture(material.diffuse, TexCoords));
// calculate diffuse lighting
vec3 norm = normalize(Normal);
// vec3 lightDir = normalize(default_light.position - FragPos);
vec3 lightDir = normalize(-default_light.direction);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = default_light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));
// calculate specular lighting
vec3 lookDir = normalize(lookPos - FragPos);
vec3 reflectDir = normalize(reflect(-lightDir, norm));
float spec = pow(max(dot(lookDir, reflectDir), 0.0), material.shininess);
vec3 specular = default_light.specular * texture(material.specular,TexCoords).rgb * spec;
// calculate final lighting
vec3 result = ambient + diffuse + specular;
FragColor = vec4(result,1.0);
}
|
import React, {useEffect, useMemo, useState} from 'react'
import {getAuth } from 'firebase/auth'
import './NavBar.css';
import {BsFillHeartPulseFill} from 'react-icons/bs'
import {Link} from 'react-router-dom';
import {useNavigate} from 'react-router-dom'
type NavbarLink = {
id:number;
name:string;
path:string;
}
function NavBar() {
const navigate = useNavigate();
const [isLoggedIn, setLoggedIn] = useState(false);
const signOut = async () =>{
await getAuth().signOut();
navigate('/');
};
useEffect(()=>{
getAuth().onAuthStateChanged((user: any)=>{
setLoggedIn(!!user);
});
}, []);
const links: NavbarLink[] = useMemo <NavbarLink[]> (() => {
const _links = [
{ id: 1, name: 'home', path:'/'},
{id:2, name:'about', path:'/about'},
{id:3, name: 'Find Hospital', path: '/find'},
];
if(!isLoggedIn){
_links.push({id:4, name: 'login', path:'/login'});
_links.push({id:5, name:'sign up', path: '/sign'});
} else{
_links.push({id:6, name:'admin', path:'/admin'});
}
return _links;
}, [isLoggedIn])
return (
<nav>
<div className="logo-wrap">
<div className="logo">
<p>LOGO</p>
</div>
</div>
<div className="links">
{links.map((link) =>(
<Link key={link.id} to={link.path}>{link.name}</Link>
))}
{isLoggedIn && (
<button className ="out-btn" onClick={signOut}>
Sign out
</button>
)}
</div>
</nav>
)
}
export default NavBar
|
import { Flex, Span } from "../../../GlobalStyles/CustomizableGlobal.style";
import cancel from "../../../assets/cancel.svg";
import Timer from "../../../assets/timer.svg";
import { Colors } from "../../../GlobalStyles/theme";
import { Button } from "../../../components/button/Button";
import { IBatch } from "../../../interfaces/batch.interface";
import moment from "moment";
const BatchDetailModal = ({
setIsEdit,
setIsDelete,
selectedBatch,
setBatchDetailModal,
}: {
setIsEdit: Function;
setIsDelete: Function;
selectedBatch?: IBatch;
setBatchDetailModal: Function;
}) => {
const targetDate = moment(selectedBatch?.expiryDate);
const today = moment();
const remainingDays = targetDate.diff(today, "days");
return (
<Flex direction="column" alignItems="center" width="100%" gap="1em">
<Flex alignItems="center" justifyContent="space-between" margin="0 0 1em 0" width="100%">
<Span color={Colors.blackishBlue} fontSize="1.2em" fontWeight="700">
{selectedBatch?.batchNumber}
</Span>
<div
onClick={() => {
setBatchDetailModal(false);
}}
style={{ cursor: "pointer" }}
>
<img src={cancel} alt="close" />
</div>
</Flex>
<Flex width="100%" alignItems="center" justifyContent="space-between" gap="1em">
<Flex width="50%" alignItems="flex-start" justifyContent="space-between" direction="column">
<Span color={Colors.grey} fontSize="0.8em">
Batch No
</Span>
<Span color={Colors.blackLight} fontWeight="600">
{" "}
{selectedBatch?.batchNumber}
</Span>
</Flex>
<Flex width="50%" alignItems="flex-start" justifyContent="space-between" direction="column">
<Span color={Colors.grey} fontSize="0.8em">
Manufacturer Number
</Span>
<Span color={Colors.blackLight} fontWeight="600">
{" "}
{selectedBatch?.manufacturerNumber}
</Span>
</Flex>
</Flex>
<Flex width="100%" alignItems="center" justifyContent="space-between" gap="1em">
<Flex width="50%" alignItems="flex-start" justifyContent="space-between" direction="column">
<Span color={Colors.grey} fontSize="0.8em">
Date Added
</Span>
<Span color={Colors.blackLight} fontWeight="600">
{selectedBatch?.dateAdded
? moment(selectedBatch?.dateAdded).format("Do MMM YYYY")
: "Not Added"}
</Span>
</Flex>
<Flex width="50%" alignItems="flex-start" justifyContent="space-between" direction="column">
<Span color={Colors.grey} fontSize="0.8em">
Expiry Date
</Span>
<Span color={Colors.blackLight} fontWeight="600">
{selectedBatch?.expiryDate
? moment(selectedBatch?.expiryDate).format("Do MMM YYYY")
: "Not Added"}
</Span>
</Flex>
</Flex>
<Flex width="100%" alignItems="flex-start" justifyContent="space-between" direction="column">
<Span color={Colors.grey} fontSize="0.8em">
Countdown
</Span>
<Flex alignItems="flex-start">
<Span color={Colors.blackLight} fontWeight="600" textAlign="start">
Batch products will expire in{" "}
</Span>
<img src={Timer} alt="timer" style={{ margin: "0 10px" }} />
<Span fontWeight="600" color={Colors.red}>
{" "}
{remainingDays} days{" "}
</Span>
</Flex>
</Flex>
<Flex width="100%" alignItems="flex-start" justifyContent="space-between" direction="column">
<Span color={Colors.grey} fontSize="0.8em">
Description
</Span>
<Span color={Colors.blackLight} fontWeight="600">
{selectedBatch?.description}
</Span>
</Flex>
<Flex alignItems="center" width="100%" gap="1em" margin="2em 0 0 0">
<Button
type="button"
label="Edit Batch"
backgroundColor="#e0eaff"
color={Colors.secondaryColor}
borderColor="none"
borderRadius="12px"
borderSize="1px"
fontSize="16px"
width="100%"
height="50px"
onClick={() => {
setIsEdit(true);
setBatchDetailModal(false);
}}
/>
<Button
type="button"
label="Delete Batch"
backgroundColor={Colors.red}
color="#fff"
borderColor="none"
borderRadius="12px"
borderSize="1px"
fontSize="16px"
width="100%"
height="50px"
onClick={() => {
setIsDelete(true);
}}
/>
</Flex>
</Flex>
);
};
export default BatchDetailModal;
|
import React, { useEffect, useState } from 'react'
import { StyleSheet, Text, SafeAreaView, View, Alert } from 'react-native'
import { useDispatch } from 'react-redux'
import { useSelector } from 'react-redux'
import { setBudget, setInfo } from '../../Redux/actions/movieActions'
import Button from '../Reusable/Button'
import InfoModal from '../Reusable/InfoModal'
import StudioCard from '../Reusable/StudioCard'
import { requestOffer, resetData, studios } from './studioData'
const Funding = ({ navigation }) => {
const [modal, showModal] = useState(false);
const [offerInfo, setOfferInfo] = useState({});
const movieInfo = useSelector((state) => state.info)
const dispatch = useDispatch();
useEffect(() => {
resetData();
}, [])
const handleBid = (id) => {
if(studios[id].offerRequested) {
setOfferInfo(studios[id]);
Alert.alert(
"Are you sure?",
`Do you want to accept the offer from ${studios[id].companyName} for $${studios[id].offer} million?`,
[
{
text: "Yes",
onPress: () => finalizeOffer()
},
{
text: "No"
}
]
)
} else {
requestOffer(id);
setOfferInfo(studios[id]);
showModal(true);
}
}
const finalizeOffer = () => {
dispatch(setBudget(offerInfo.offer));
dispatch(setInfo({
...movieInfo,
companyName: offerInfo.companyName,
}))
navigation.navigate('actorselect');
}
return (
<SafeAreaView style={styles.container}>
{modal ? <InfoModal setModalVisible={showModal} modalVisible={modal} offerInfo={offerInfo} /> : null}
<View>
<Text>Fund your Film!</Text>
<Text>{movieInfo.title}</Text>
</View>
<View>
<StudioCard companyName={studios[0].companyName} offer={studios[0].offer} onPress={() => handleBid(0)} />
<StudioCard companyName={studios[1].companyName} offer={studios[1].offer} onPress={() => handleBid(1)} />
<StudioCard companyName={studios[2].companyName} offer={studios[2].offer} onPress={() => handleBid(2)} />
<StudioCard companyName={studios[3].companyName} offer={studios[3].offer} onPress={() => handleBid(3)} />
<StudioCard companyName={studios[4].companyName} offer={studios[4].offer} onPress={() => handleBid(4)} />
<StudioCard companyName={studios[5].companyName} offer={studios[5].offer} onPress={() => handleBid(5)} />
<StudioCard companyName={studios[6].companyName} offer={studios[6].offer} onPress={() => handleBid(6)} />
</View>
<Button onPress={() => resetData()} label="RESET" />
</SafeAreaView>
)
}
export default Funding
const styles = StyleSheet.create({
container: {
flex: 1
}
})
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mapbox Maps API</title>
<!-- Mapbox CSS -->
<link href='https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.css' rel='stylesheet' />
<!-- Custom CSS -->
<style>
#map {
/* the width and height may be set to any size */
width: 100%;
flex-grow: 1;
}
header.container {
border-bottom: 1px solid rgba(0, 0, 0, 0.78);
}
main.container, main.container>.row {
padding: 0;
flex-grow: 1;
column-gap: 0px;
}
aside.column {
width: 300px;
flex: none;
}
/* reset*/
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
img {
max-width: 100%;
}
body {
font-family: 'Open Sans', sans-serif;
font-size: 16px;
line-height: 1.5;
color: #333;
background-color: #fff;
}
/* THE PAGE WRAPPER MIMICS THE BODY, ONLY WE ARE ABLE TO DO MORE WITH IT IF NECESSARY */
.page-wrapper {
display:flex;
flex-direction: column;
min-height: 100vh;
}
/* THE CONTAINER -- ALSO KNOWN AS A "SECTION" or "WRAPPER" -- IS A FULL WIDTH DIV THAT
SEPARATES SECTIONS OF A WEBSITE. IT ALIGNS IT'S CHILD(REN), THE ROW, TO ITS CENTER,
ALLOWING THE ROW TO PROPERLY CONTROL MAX-WIDTH ON SITE CONTENT */
.container {
display: flex;
flex-direction: column;
align-items:center;
flex: 0 0 auto;
padding: 20px;
}
/* THE ROW ESTABLISHES MAXIMUM WIDTH ON SITE CONTENT, AND ORGANIZES ITS CHILD(REN), THE
COLUMN, HORIZONTALLY. */
.row {
display: flex;
width: 100%;
max-width: 900px;
padding: 0 20px;
column-gap: 20px;
}
/* OPTIONAL COMBO CLASS TO MAKE ROW FULL-WIDTH */
.row.full-width {
max-width: unset;
}
/* OPTIONAL COMBO CLASS TO MAKE ROW COLUMNS SPACED APART */
.row.space-between {
justify-content: space-between;
}
/* COLUMNS WILL, BY DEFAULT, SHARE SPACE EQUALLY HORIZONTALLY WITHIN THE ROW WITH
THEIR SIBLINGS. CONTENT PUT INSIDE THEM WILL STACK VERTICALLY. */
.column {
display:flex;
flex-direction: column;
flex: 1 0;
min-width: 0px;
}
/* OPTIONAL COMBO CLASS TO MAKE A COLUMN SHRINK INSTEAD OF GROW */
.column.col-shrink {
flex: 0 1 auto;
}
</style>
</head>
<body>
<h1>Mapbox Map API</h1>
<!-- The HTML element that serves as the Mapbox container -->
<div class="page-wrapper">
<header class="container">
<div class="row full-width">
<div class="column">
Decent restaurants
</div>
<div class="column">
</div>
</div>
</header>
<main class="container">
<div class="row full-width">
<aside class="column">
</aside>
<div class="column">
<div id='map'></div>
</div>
</div>
</main>
</div>
<!--keys-->
<script src="./js/keys.js"></script>
<!--Mapbox geocoder-->
<script src="js/mapbox-geocoder-utils.js"></script>
<!-- Mapbox JS -->
<script src='https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.js'></script>
<!-- Custom JS -->
<script>
let favFoods=[
{
name: "Taco Blvd",
address: "18360 Blanco Rd #116, San Antonio, TX 78258",
},
{
name: "Chick fil a",
address: "106 E Houston St, San Antonio, TX 78205",
},
{
name: "Chama Gaucha",
address: "18318 Sonterra Pl, San Antonio, TX 78258",
}
];
mapboxgl.accessToken = keys.mapbox;
let map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
zoom: 13,
center: [-98.4916, 29.4252]
});
favFoods.forEach(function(favFoods) {
geocode(favFoods.address, keys.mapbox).then(function (result) {
console.log(result[0]);
console.log(result[1]);
let marker = new mapboxgl.Marker()
.setLngLat([result[0],result[1]])
.addTo(map);
let tacoPopup = new mapboxgl.Popup()
.setHTML(favFoods.name);
// map.setCenter(result);
map.setZoom(10);
marker.setPopup(tacoPopup);
});
})
</script>
</body>
</html>
|
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
import { getFirestore, doc, getDoc, getDocs, updateDoc, collection } from 'firebase/firestore';
import './SignupPreferences.css';
function SignupPreferences() {
const navigate = useNavigate()
const auth = getAuth();
const db = getFirestore();
const [isSelectingPreferences, setIsSelectingPreferences] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [categories, setCategories] = useState([]);
const [isLoadingCategories, setLoadingCategories] = useState(true); // manage loading state here
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, async user => {
if (user) {
const docRef = doc(db, "users", user.uid);
console.log(user.uid);
const docSnap = await getDoc(docRef);
if (docSnap.exists() && docSnap.data().isSelectingPreferences) {
setIsSelectingPreferences(true);
} else {
navigate('/signup-preferences'); //
setIsSelectingPreferences(false);
}
} else {
navigate('/login');
}
fetchCategories();
setIsLoading(false);
}, [auth, db, navigate]);
return () => unsubscribe();
}, [auth, db, navigate]); // Corrected dependency array
function disableUserSelectingPreferences() {
const user = auth.currentUser;
if (user) {
const docRef = doc(db, "users", user.uid);
updateDoc(docRef, {
isSelectingPreferences: false
}).then(() => {
console.log("Preferences updated");
}).catch(error => {
console.error("Error updating preferences: ", error);
});
}
}
function addPreferenceCategories() {
const user = auth.currentUser;
if (user) {
const docRef = doc(db, "users", user.uid);
updateDoc(docRef, {
preferences: Array.from(selectedCategories)
}).then(() => {
console.log("Preferences updated");
}).catch(error => {
console.error("Error updating preferences: ", error);
});
}
}
async function fetchCategories() {
try {
setLoadingCategories(true); // Start loading
const categoriesRef = collection(db, "categories");
const querySnapshot = await getDocs(categoriesRef);
const categoryList = querySnapshot.docs.map(doc => doc.data().name); // Assuming each document has a 'name' field
setCategories(categoryList);
setLoadingCategories(false); // End loading
} catch (error) {
console.error("Error fetching categories: ", error);
setLoadingCategories(false); // End loading on error
}
}
// const categories = [
// 'Health', 'International Relations', 'Economics', 'Environment',
// 'Technology', 'Politics', 'Social Justice', 'Space Exploration',
// 'Cybersecurity', 'Entertainment', 'Sports', 'Education',
// 'Science', 'Business and Finance', 'Humanitarian Crises',
// 'Artificial Intelligence', 'Weather/Climate', 'Travel and Tourism',
// 'Cultural Events'
// ];
// const categories = fetchCategories();
const minSelection = 5;
const [selectedCategories, setSelectedCategories] = useState(new Set());
const toggleCategory = (category) => {
setSelectedCategories(prevSelected => {
const newSelected = new Set(prevSelected);
if (newSelected.has(category)) {
newSelected.delete(category);
} else {
newSelected.add(category);
}
console.log(newSelected);
return newSelected;
});
};
if (isLoadingCategories) {
return <div>Loading categories...</div>; // Display a loading message or spinner
}
return (
<div>
<div id="categories">
{categories.map(category => (
<button
key={category}
onClick={() => toggleCategory(category)}
className={`category-btn ${selectedCategories.has(category) ? 'selected' : ''}`}
>
{category}
</button>
))}
</div>
<button
id="nextButton"
disabled={selectedCategories.size < minSelection}
onClick={() => {
disableUserSelectingPreferences();
addPreferenceCategories();
navigate('/feed');
}}
>
Next
</button>
</div>
);
}
export default SignupPreferences;
|
import React from 'react';
import { createFromIconfontCN } from '@ant-design/icons';
/**
* 菜单图标,需要上传到https://www.iconfont.cn/
*/
const Icon = createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/c/font_3041065_869q5mjeen4.js',
});
interface Props {
/**
* @description 图标样式
* */
className?: React.CSSProperties;
/**
* @description IconFont中上传的图标名称
* */
type?: string;
/**
* @description 图标样式
* */
style?: object;
/**
* @description 图标大小
* */
size?: string;
/**
* @description 点击回调
* */
onClick?: () => void;
}
export default function IconFont(props: Props) {
const { type, className, style, size = 'inherit', onClick } = props;
return (
<Icon
role={type}
type={type}
className={className}
style={{ ...style, fontSize: size }}
onClick={onClick}
/>
);
}
|
<?php
if (!class_exists('Magnitude_Posts_List')) :
/**
* Adds Magnitude_Posts_List widget.
*/
class Magnitude_Posts_List extends AFthemes_Widget_Base
{
/**
* Sets up a new widget instance.
*
* @since 1.0.0
*/
function __construct()
{
$this->text_fields = array('magnitude-categorised-posts-title', 'magnitude-posts-number');
$this->select_fields = array('magnitude-select-category', 'magnitude-show-category');
$widget_ops = array(
'classname' => 'magnitude_posts_list list-layout',
'description' => __('Displays posts from selected category in a list.', 'magnitude'),
'customize_selective_refresh' => false,
);
parent::__construct('magnitude_posts_list', __('AFTM Posts List', 'magnitude'), $widget_ops);
}
/**
* Front-end display of widget.
*
* @see WP_Widget::widget()
*
* @param array $args Widget arguments.
* @param array $instance Saved values from database.
*/
public function widget($args, $instance)
{
$instance = parent::magnitude_sanitize_data($instance, $instance);
/** This filter is documented in wp-includes/default-widgets.php */
$title = apply_filters('widget_title', $instance['magnitude-categorised-posts-title'], $instance, $this->id_base);
$category = isset($instance['magnitude-select-category']) ? $instance['magnitude-select-category'] : '0';
$show_categories = isset($instance['magnitude-show-category']) ? $instance['magnitude-show-category'] : 'true';
$show_categories = true;
// open the widget container
echo $args['before_widget'];
?>
<?php if (!empty($title)): ?>
<div class="af-title-subtitle-wrap">
<?php if (!empty($title)): ?>
<h4 class="widget-title header-after1">
<span class="header-after">
<?php echo esc_html($title); ?>
</span>
</h4>
<?php endif; ?>
</div>
<?php endif; ?>
<?php
$all_posts = magnitude_get_posts(6, $category);
?>
<div class="widget-block widget-wrapper af-widget-body magnitude-widget">
<div class="af-container-row clearfix">
<?php
$count = 1;
if ($all_posts->have_posts()) :
while ($all_posts->have_posts()) : $all_posts->the_post();
global $post;
$url = magnitude_get_freatured_image_url($post->ID, 'thumbnail');
$thumb_id = get_post_thumbnail_id($post->ID);
?>
<div class="col-2 pad float-l af-double-column list-style" data-mh="af-feat-list">
<div class="af-double-column list-style clearfix">
<div class="read-single color-pad">
<div class="data-bg read-img pos-rel col-4 float-l read-bg-img"
data-background="<?php echo esc_url($url); ?>">
<?php if(!empty($url)): ?>
<img src="<?php echo esc_url($url); ?>" alt="<?php echo esc_attr(magnitude_get_img_alt($thumb_id));?>">
<?php endif; ?>
<a class="aft-post-image-link" href="<?php the_permalink(); ?>">
<?php if (get_field('custom_title',$post->ID) != '') { ?>
<?=str_replace(array('[', ']'), '', get_field('custom_title',$post->ID));?>
<?php } else { ?>
<?php the_title(); ?>
<?php } ?>
</a>
</div>
<div class="read-details col-75 float-l pad color-tp-pad">
<?php if ($show_categories == 'true'): ?>
<div class="read-categories">
<?php magnitude_post_categories(); ?>
</div>
<?php endif; ?>
<div class="read-title">
<h4>
<a href="<?php the_permalink(); ?>">
<?php if (get_field('custom_title',$post->ID) != '') { ?>
<?=str_replace(array('[', ']'), '', get_field('custom_title',$post->ID));?>
<?php } else { ?>
<?php the_title(); ?>
<?php } ?>
</a>
</h4>
</div>
</div>
</div>
</div>
</div>
<?php
$count++;
endwhile;
endif;
wp_reset_postdata();
?>
</div>
</div>
<?php
// close the widget container
echo $args['after_widget'];
}
/**
* Back-end widget form.
*
* @see WP_Widget::form()
*
* @param array $instance Previously saved values from database.
*/
public function form($instance)
{
$this->form_instance = $instance;
$categories = magnitude_get_terms();
if (isset($categories) && !empty($categories)) {
// generate the text input for the title of the widget. Note that the first parameter matches text_fields array entry
echo parent::magnitude_generate_text_input('magnitude-categorised-posts-title', __('Title', 'magnitude'), __('Posts List', 'magnitude'));
echo parent::magnitude_generate_select_options('magnitude-select-category', __('Select category', 'magnitude'), $categories);
}
//print_pre($terms);
}
}
endif;
|
<template>
<div class="container">
<div class="row">
<div class="col-md-3">
<ElearningManagerSide :group="12" :active="12" />
</div>
<div class="col-md-9">
<sub-block-section :title="nameGroup" has-icon>
<template v-slot:content>
<div class="group-students">
<div class="d-flex">
<div class="group-students__wrap-search">
<app-search
placeholder="Nhập để tìm kiếm"
bordered
class="w-100"
color="primary"
@input="handleChangeKeyword"
></app-search>
</div>
<filter-button
@click="clickFilterSubmit"
size="lg"
class="btn-filter"
:color="filterSelect ? 'primary' : 'white'"
></filter-button>
<app-select
v-if="filterSelect"
:options="classList"
placeholder="Lớp"
class="select-class"
@change="handleChangeClass"
/>
<app-button class="ml-auto" @click="showModalAddStudent">
<IconAdd24px height="16" />
Thêm mới học sinh
</app-button>
</div>
<div>
<app-button
color="secondary"
class="mt-5"
:disabled="!canDeleteMember"
@click="modalConfirmDelete = true"
>
<IconDelete24px height="16" />
Xóa
</app-button>
</div>
<div class="mt-5">
<vcl-table v-if="loading" />
<app-table
v-else
multiple-selection
:heads="heads"
:pagination="get(memberGroups, 'page', {})"
:data="get(memberGroups, 'content', [])"
@selectionChange="selectRow"
@pagechange="onPageChange"
primaryKey="user_id"
>
<template slot="cell(joined)" slot-scope="{ row }">
<td>
{{ row.joined}}
</td>
</template>
<template slot="cell(student)" slot-scope="{ row }">
<td>
{{ get(row,"student",get(row,"name",''))}}
</td>
</template>
</app-table>
</div>
</div>
</template>
</sub-block-section>
</div>
<ModalAddStudent
v-if="showModal"
@close="closeModal"
:group_id="payload.group_id"
@search="handleSearch"
/>
<app-modal-confirm
v-if="modalConfirmDelete"
okText="Xác nhận"
title="Bạn chắc chắn muốn xoá học sinh này?"
:confirmLoading="loadingDel"
@cancel="modalConfirmDelete = false"
@ok="handleDeleteGroupMember"
></app-modal-confirm>
</div>
</div>
</template>
<script>
import ElearningManagerSide from "~/components/page/elearning/manager/ElearningManagerSide";
import ModalAddStudent from "~/components/page/elearning/Students/ModalAddStudents";
import IconAdd24px from "~/assets/svg/v2-icons/add_24px.svg?inline";
import IconDelete24px from "~/assets/svg/v2-icons/delete_24px.svg?inline";
import * as actionTypes from "~/utils/action-types";
import { RESPONSE_SUCCESS } from "~/utils/config";
import { mapState, mapActions } from "vuex";
import { get } from "lodash";
import { VclTable } from "vue-content-loading";
import { allOptionSelect } from "~/utils/common";
export default {
components: {
ElearningManagerSide,
ModalAddStudent,
IconAdd24px,
IconDelete24px,
VclTable
},
data() {
return {
showModal: false,
filterSelect: false,
loading: false,
selectedStudentIds: [],
payload: {
keyword: "",
group_id: null,
class_id: "",
page: 1,
size: 10
},
heads: [
{
name: "",
text: "",
selectAll: true
},
{
name: "student",
text: "Họ và tên",
sort: false
},
{
name: "email",
text: "Email",
sort: false
},
{
name: "phone",
text: "Số điện thoại",
sort: false
},
{
name: "class_name",
text: "Lớp",
sort: false
},
{
name: "joined",
text: "Ngày tham gia",
sort: false
}
],
loadingDel: false,
modalConfirmDelete: false,
};
},
asyncData({ params }) {
return {
payload: {
group_id: params.id
}
};
},
computed: {
...mapState("elearning/study-group/member", ["memberGroups"]),
...mapState("auth", {
userLogin: "token"
}),
...mapState("elearning/study-group/group", [
"classes",
"students",
"participants",
"detailGroup"
]),
canDeleteMember() {
return this.selectedStudentIds && this.selectedStudentIds.length > 0;
},
classList() {
console.log("[classList]", this.classes);
return !this.classes
? []
: allOptionSelect(
this.classes.map(item => {
return {
value: item.id,
text: item.name
};
}),
"lớp"
);
},
allSelected: {
set(value) {
return value;
},
get() {
return this.students && isEqual(this.selectedItems, this.students);
}
},
nameGroup(){
return this.detailGroup ? this.detailGroup.name : '';
}
},
async created() {
this.handleSearch();
const params = {
school_id: get(this, "userLogin.organization.id", "")
};
this.$store.dispatch("elearning/study-group/group/getClasses", params);
this.$store.dispatch("elearning/study-group/group/getDetailGroup",this.$route.params.id)
},
methods: {
...mapActions("elearning/study-group/member", [
"getListStudyGroupMember",
"deleteStudyGroupMember"
]),
async handleDeleteGroupMember() {
console.log("[handleDeleteGroupMember]", this.selectedStudentIds);
this.loadingDel = true;
const payload = {
group_id: this.payload.group_id,
user_ids: this.selectedStudentIds
};
const result = await this.deleteStudyGroupMember(payload);
if (result.success == RESPONSE_SUCCESS) {
this.selectedStudentIds = [];
this.handleSearch();
} else {
this.$toasted.error("Xoá thành viên trong nhóm thất bại");
}
this.loadingDel = false;
this.modalConfirmDelete = false;
},
handleChangeClass(data) {
console.log("[handleChangeClass]", data);
this.payload.class_id = data;
this.handleSearch();
},
async handleSearch() {
this.loading = true;
await this.getListStudyGroupMember(this.payload);
this.loading = false;
},
handleChangeKeyword(data) {
console.log("[handleChangeKeyword]", data);
this.payload.keyword = data;
this.handleSearch();
},
async onPageChange(e) {
console.log("[onPageChange]", e);
const { number, size } = e;
this.payload.page = +number + 1;
this.payload.size = +size;
this.handleSearch();
},
clickFilterSubmit() {
this.filterSelect = !this.filterSelect;
if (!this.filterSelect) {
// reset search result
this.payload = {
...this.payload,
...{
class_id: "",
page: 1,
size: 10
}
};
this.handleSearch();
}
},
closeModal(invite) {
this.showModal = invite;
},
showModalAddStudent() {
this.showModal = true;
},
selectRow(row) {
this.selectedStudentIds = _.map(row, "user_id");
console.log("[selectRow]", this.selectedStudentIds);
},
get
}
};
</script>
<style lang="scss">
@import "~/assets/scss/components/elearning/students/_group-study-detail.scss";
</style>
|
class Solution {
// 其实就是找第一个大于target数的位置
public int searchInsert(int[] nums, int target) {
if(nums[nums.length - 1] < target) {
return nums.length;
}
int left = 0;
int right = nums.length - 1; // 也可以是right = nums.length,这样就省了上面的判断
while(left < right) {
int mid = left + (right - left) / 2;
if(nums[mid] == target) {
return mid;
}else if(nums[mid] > target) {
right = mid;
}else {
left = mid + 1;
}
}
return left;
}
}
|
/*******************************************************************************
* This file is part of the EEG-database project
*
*
* Copyright (C) 2013 by University of West Bohemia (http://www.zcu.cz/en/)
*
* ***********************************************************************************************************************
*
* 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.
*
* ***********************************************************************************************************************
*
* FullTextSearchUtils.java, 2013/10/02 00:01 Jakub Rinkes
******************************************************************************/
package cz.zcu.kiv.eegdatabase.logic.search;
import cz.zcu.kiv.eegdatabase.data.pojo.*;
import cz.zcu.kiv.eegdatabase.wui.components.page.UnderConstructPage;
import cz.zcu.kiv.eegdatabase.wui.ui.articles.ArticlesPage;
import cz.zcu.kiv.eegdatabase.wui.ui.experiments.ExperimentsDetailPage;
import cz.zcu.kiv.eegdatabase.wui.ui.groups.ResearchGroupsDetailPage;
import cz.zcu.kiv.eegdatabase.wui.ui.people.PersonDetailPage;
import cz.zcu.kiv.eegdatabase.wui.ui.scenarios.ScenarioDetailPage;
import org.apache.wicket.Page;
import java.util.HashMap;
import java.util.Map;
/**
* Utility class containing a set of useful methods and constants related to full-text search.
* Date: 25.3.13
* Time: 23:00
*/
public class FullTextSearchUtils {
public final static int AUTOCOMPLETE_ROWS = 10;
public static final String HIGHLIGHTED_TEXT_BEGIN = "<span class=\"hilite\">";
public static final String HIGHLIGHTED_TEXT_END = "</span>";
public static final String HIGHLIGHT_MERGE_SEQUENCE = HIGHLIGHTED_TEXT_END + " " + HIGHLIGHTED_TEXT_BEGIN;
/**
* Maps result categories to Page classes
*/
private static Map<String, Class<? extends Page>> categoryToPageMap = initializeClassMap();
/**
* Maps Page classes to names of their documents in the index.
*/
private static Map<Class<?>, String> pojoToCategoryMap = initializeResultTypes();
/**
* Maps result categories to their application properties
private static Map<String, String> categoryToPropertyMap = initializeResultProperties();
*/
/**
* Sets the POJO - Page class mapping.
* @return POJO classes to Page classes mapping.
*/
private static final Map<String, Class<? extends Page>> initializeClassMap() {
Map<String, Class<? extends Page>> map = new HashMap<String, Class<? extends Page>>();
map.put(ResultCategory.ARTICLE.getValue(), ArticlesPage.class);
map.put(ResultCategory.EXPERIMENT.getValue(), ExperimentsDetailPage.class);
map.put(ResultCategory.PERSON.getValue(), PersonDetailPage.class);
map.put(ResultCategory.RESEARCH_GROUP.getValue(), ResearchGroupsDetailPage.class);
map.put(ResultCategory.SCENARIO.getValue(), ScenarioDetailPage.class);
return map;
}
/**
* Sets page - result type mapping.
* @return Page - result type mapping.
*/
private static final Map<Class<?>, String> initializeResultTypes() {
Map<Class<?>, String> map = new HashMap<Class<?>, String>();
map.put(Article.class, ResultCategory.ARTICLE.getValue());
map.put(Experiment.class, ResultCategory.EXPERIMENT.getValue());
map.put(Person.class, ResultCategory.PERSON.getValue());
map.put(ResearchGroup.class, ResultCategory.RESEARCH_GROUP.getValue());
map.put(Scenario.class, ResultCategory.SCENARIO.getValue());
return map;
}
/**
* Gets a page class for a given POJO class.
* @param type The POJO class.
* @return The Wicket Page class.
*/
public static Class<? extends Page> getTargetPage(String type) {
for(String typeValue : categoryToPageMap.keySet()) {
if(typeValue.equals(type)) {
return categoryToPageMap.get(typeValue);
}
}
return UnderConstructPage.class;
}
/**
* Gets a type of the document from a given Wicket Page class.
* @param clazz The Wicket Page class.
* @return The document type.
*/
public static String getDocumentType(Class<? extends Page> clazz) {
if(pojoToCategoryMap.containsKey(clazz)) {
return pojoToCategoryMap.get(clazz);
}
else {
return "Other";
}
}
/**
* Gets a type of the document from a given fulltext result instance.
* @param result The fulltext result.
* @return The document type.
*/
public static String getDocumentType(FullTextResult result) {
if(result.getTargetPage() == null) {
return "Other";
}
return getDocumentType(result.getTargetPage());
}
}
|
import commentContext from "./commentContext";
import { useContext } from "react";
import axios from "axios";
import userContext from "../users/userContext";
const CommentState = (props) => {
const usercontext = useContext(userContext);
const { User } = usercontext;
let token = localStorage.getItem("comment_system");
const fetchComment = async (pageId, setBackendComments) => {
try {
const response = await axios.get(
"http://localhost:3000/api/comments/allcomments",
{
params: { pageId },
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}
);
console.log(response.data);
if (response.status === 200) {
setBackendComments(response.data);
}else{
console.log("Thier is error from server side :");
}
} catch (error) {
console.log(error);
}
};
const addComment = async (
body,
parentId = null,
rootparentId = null,
setActiveComment,
pageId,
setBackendComments
) => {
let userId = User.id;
let username = User.username;
let createdAt = new Date().toISOString();
try {
const response = await axios.post(
"http://localhost:3000/api/comments/add",
{ body, username, userId, parentId, createdAt, rootparentId, pageId },
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}
);
// console.log(response);
if (response.status === 200) {
console.log("Comment created");
} else {
console.log("Comment is not created");
}
} catch (error) {
console.error("Error creating comment:", error);
}
fetchComment(pageId, setBackendComments);
setActiveComment(null);
};
const updateComment = async (
body,
id,
deleted = false,
setActiveComment,
pageId,
setBackendComments
) => {
let createdAt = new Date().toISOString();
try {
const response = await axios.put(
"http://localhost:3000/api/comments/update",
{ body, id, createdAt, deleted },
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}
);
if (response.status === 200) {
console.log("Comment Updated");
} else {
console.log("Comment not Updated");
}
fetchComment(pageId, setBackendComments);
setActiveComment(null);
} catch (error) {
console.error("Error creating comment:", error);
}
};
const deleteComment = async (
id,
setActiveComment,
pageId,
setBackendComments
) => {
let body = "This comment was deleted";
updateComment(body, id, true, setActiveComment, pageId, setBackendComments);
};
const reportComment = async (id, backendComments, setBackendComments) => {
const userId = User.id;
try {
const response = await axios.post(
"http://localhost:3000/api/comments/report",
{ id, userId },
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}
);
if (response.status === 200) {
let commment = response.data;
const updatedBackendComments = backendComments.map((backendComment) => {
if (backendComment.id === commment.id) {
return { ...backendComment, spam: commment.spam };
}
return backendComment;
});
setBackendComments(updatedBackendComments);
} else if (response.status === 201) {
console.log("Unauthorized");
}else{
console.log("Their is issue in server side");
}
} catch (error) {
console.error("Error creating comment:", error);
}
};
const handleLikeClick = async (id) => {
let userId = User.id;
try {
const response = await axios.post(
"http://localhost:3000/api/likes/like",
{ id, userId },
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}
);
console.log(response);
} catch (error) {
console.error("Error creating comment:", error);
}
};
const findTotalreply = (rootId, backendComments) => {
let reply = 0;
for (let i = 0; i < backendComments.length; i++) {
if (backendComments[i].rootparentId === rootId) reply++;
}
return reply;
};
const getReplies = (commentId, backendComments) =>
backendComments
.filter((backendComment) => backendComment.parentId === commentId)
.sort(
(a, b) =>
new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
);
return (
<commentContext.Provider
value={{
fetchComment,
deleteComment,
addComment,
updateComment,
reportComment,
handleLikeClick,
findTotalreply,
getReplies,
}}
>
{props.children}
</commentContext.Provider>
);
};
export default CommentState;
|
import { useForm } from "react-hook-form";
import axios from "axios";
import { useEffect, useState } from "react";
function CreateTask() {
const { register, handleSubmit } = useForm();
const [task, getTasks] = useState([]);
const onSubmit = (data) => {
axios.post("http://localhost:4000/api/tasks", data)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
};
useEffect(() => {
axios.get("http://localhost:4000/api/tasks")
.then((response) => {
getTasks(response.data);
})
.catch((error) => {
console.log(error);
});
});
const handleDelete = (id) => {
axios.delete("http://localhost:4000/api/tasks/${id}")
.then(() => getTasks(task.filter((task) => {
task._id !== id
})))
.catch((error) => {
console.error(error)
});
};
return (
<div className="">
<h1 className="text-3xl text-yellow-500">Agregar tarea</h1>
<form onSubmit={handleSubmit(onSubmit)} className="flex w-80 flex-col space-y-2">
<label htmlFor="">Usuario</label>
<input type="text" {...register("user")} className="text-black" />
<label htmlFor="">Titulo de la tarea</label>
<input type="text" {...register("title")} className="text-black" />
<label htmlFor="">Descripción</label>
<input type="text" {...register("description")} className="text-black" />
<button className=" text-white rounded bg-blue-500 border border-blue-500 hover:bg-white hover:text-blue-500 transition-all">Enviar</button>
</form>
<table className="w-2/4 text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400 my-3">
<thead className=" text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
<tr>
<th>Usuario</th>
<th>Tarea</th>
<th>Descripción</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
{task.map((item) => (
<tr key={item._id} className="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<td className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">{item.user}</td>
<td className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">{item.title}</td>
<td className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">{item.description}</td>
<td className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
<a href={`/update/${item._id}`}>
<button className="bg-yellow-500 p-4 rounded text-white hover:bg-white hover:text-yellow-500 hover:border-yellow-500 border transition-all">Editar</button>
</a>
<button className="bg-red-500 p-4 rounded text-white hover:bg-white hover:text-red-500 hover:border-red-500 border transition-all" onClick={() => handleDelete(task._id)}>Borrar</button></td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default CreateTask;
|
<?php
declare(strict_types=1);
use TechWilk\PhpTools\SettingsInterface;
use DI\ContainerBuilder;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\UidProcessor;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Slim\Views\PhpRenderer;
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
LoggerInterface::class => function (ContainerInterface $c) {
$settings = $c->get(SettingsInterface::class);
$loggerSettings = $settings->get('logger');
$logger = new Logger($loggerSettings['name']);
$processor = new UidProcessor();
$logger->pushProcessor($processor);
$handler = new StreamHandler($loggerSettings['path'], $loggerSettings['level']);
$logger->pushHandler($handler);
return $logger;
},
PhpRenderer::class => function (ContainerInterface $c) {
$settings = $c->get(SettingsInterface::class);
$rendererSettings = $settings->get('renderer');
return new PhpRenderer($rendererSettings['template_path']);
},
]);
};
|
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:minimalistic_telegram/controllers/tdlib_controller.dart';
import 'package:minimalistic_telegram/services/locator.dart';
import 'package:minimalistic_telegram/stores/application_store.dart';
import 'package:minimalistic_telegram/stores/chat_store.dart';
import 'package:minimalistic_telegram/stores/file_store.dart';
import 'package:minimalistic_telegram/stores/filter_store.dart';
import 'package:minimalistic_telegram/stores/message_store.dart';
import 'package:minimalistic_telegram/utils/const.dart';
import 'package:minimalistic_telegram/utils/router.dart' as util_router;
import 'package:palestine_console/palestine_console.dart';
import 'package:provider/provider.dart';
import 'package:tdlib/td_client.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:tdlib/td_api.dart' as td_api;
void main() async {
await dotenv.load();
WidgetsFlutterBinding.ensureInitialized();
Provider.debugCheckInvalidValueType = null;
await TdPlugin.initialize();
setupLocator();
runApp(
MultiProvider(
providers: [
Provider<TdLibController>(
create: (_) => TdLibController(),
lazy: false,
),
Provider<ApplicationStore>(
create: (_) => ApplicationStore(),
lazy: false,
),
Provider<ChatStore>(
create: (_) => ChatStore(),
lazy: false,
),
Provider<MessageStore>(
create: (_) => MessageStore(),
lazy: false,
),
Provider<FilterStore>(
create: (_) => FilterStore(),
lazy: false,
),
Provider<FileStore>(
create: (_) => FileStore(),
lazy: false,
),
],
child: const MyNewApp(),
),
);
}
class MyNewApp extends StatefulWidget {
const MyNewApp({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _MyNewAppState();
}
class _MyNewAppState extends State<MyNewApp> {
String lastRoute = '';
List<StreamSubscription> subscriptions = [];
@override
void initState() {
super.initState();
TdLibController().initClient();
var appStore = context.read<ApplicationStore>();
var subscription = appStore
.on<td_api.UpdateAuthorizationState>()
.listen(onAuthStateChange);
subscriptions.add(subscription);
}
@override
void dispose() {
var controller = TdLibController();
controller.stop();
controller.destroyClient();
for (var element in subscriptions) {
element.cancel();
}
subscriptions = [];
super.dispose();
}
void onAuthStateChange(event) {
final constructorToAction = {
td_api.AuthorizationStateWaitPhoneNumber: navigateToLogin,
td_api.AuthorizationStateClosed: navigateToLogin,
td_api.AuthorizationStateReady: goToMainPage,
td_api.AuthorizationStateWaitCode: goToOtpPage,
};
final type = event.authorizationState.runtimeType;
final action = constructorToAction[type];
action?.call();
}
void goToOtpPage() {
setState(() {
lastRoute = otpRoute;
});
locator<NavigationService>().navigator.pushNamed(otpRoute);
return;
}
void goToMainPage() {
setState(() {
lastRoute = homeRoute;
});
locator<NavigationService>()
.navigator
.pushNamedAndRemoveUntil(homeRoute, (route) => false);
}
void navigateToLogin() {
setState(() {
lastRoute = loginRoute;
});
locator<NavigationService>()
.navigator
.pushNamedAndRemoveUntil(loginRoute, (route) => false);
Print.green("new route is: $loginRoute");
}
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: locator<NavigationService>().navigatorKey,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
onGenerateRoute: util_router.Router.generateRoute,
initialRoute: initRoute,
);
}
}
|
package resolvers
import (
"context"
"encoding/json"
"fmt"
"io"
"time"
"github.com/mitchellh/mapstructure"
runtimev1 "github.com/rilldata/rill/proto/gen/rill/runtime/v1"
"github.com/rilldata/rill/runtime"
compilerv1 "github.com/rilldata/rill/runtime/compilers/rillv1"
"github.com/rilldata/rill/runtime/drivers"
"github.com/rilldata/rill/runtime/pkg/duckdbsql"
"github.com/rilldata/rill/runtime/queries"
"google.golang.org/protobuf/types/known/structpb"
)
const sqlResolverInteractiveRowLimit = 10000
func init() {
runtime.RegisterResolverInitializer("sql", newSQL)
}
type sqlResolver struct {
sql string
refs []*runtimev1.ResourceName
olap drivers.OLAPStore
olapRelease func()
priority int
}
type sqlProps struct {
Connector string `mapstructure:"connectors"`
SQL string `mapstructure:"sql"`
}
type sqlArgs struct {
Priority int `mapstructure:"priority"`
// NOTE: Not exhaustive. Any other args are passed to the "args" property when resolving the SQL template.
}
// newSQL creates a resolver that executes a SQL query.
// It supports the use of templating in the SQL string to inject user attributes and args into the SQL query.
func newSQL(ctx context.Context, opts *runtime.ResolverOptions) (runtime.Resolver, error) {
return newSQLWithRefs(ctx, opts, nil)
}
// newSQLWithRefs is similar to newSQL, but allows providing extra refs.
// This capability is required by the metrics SQL resolver to wrap this regular SQL resolver.
func newSQLWithRefs(ctx context.Context, opts *runtime.ResolverOptions, extraRefs []*runtimev1.ResourceName) (runtime.Resolver, error) {
props := &sqlProps{}
if err := mapstructure.Decode(opts.Properties, props); err != nil {
return nil, err
}
args := &sqlArgs{}
if err := mapstructure.Decode(opts.Args, args); err != nil {
return nil, err
}
olap, release, err := opts.Runtime.OLAP(ctx, opts.InstanceID, props.Connector)
if err != nil {
return nil, err
}
resolvedSQL, refs, err := buildSQL(props.SQL, olap.Dialect(), opts.Args, opts.UserAttributes, opts.ForExport)
if err != nil {
return nil, err
}
if extraRefs != nil {
refs = append(refs, extraRefs...)
refs = normalizeRefs(refs)
}
return &sqlResolver{
sql: resolvedSQL,
refs: refs,
olap: olap,
olapRelease: release,
priority: args.Priority,
}, nil
}
func (r *sqlResolver) Close() error {
r.olapRelease()
return nil
}
func (r *sqlResolver) Key() string {
return r.sql
}
func (r *sqlResolver) Refs() []*runtimev1.ResourceName {
return r.refs
}
func (r *sqlResolver) Validate(ctx context.Context) error {
_, err := r.olap.Execute(ctx, &drivers.Statement{
Query: r.sql,
DryRun: true,
})
return err
}
func (r *sqlResolver) ResolveInteractive(ctx context.Context) (*runtime.ResolverResult, error) {
// Wrap the SQL with an outer SELECT to limit the number of rows returned in interactive mode.
// Adding +1 to the limit so we can return a nice error message if the limit is exceeded.
sql := fmt.Sprintf("SELECT * FROM (%s) LIMIT %d", r.sql, sqlResolverInteractiveRowLimit+1)
res, err := r.olap.Execute(ctx, &drivers.Statement{
Query: sql,
Priority: r.priority,
})
if err != nil {
return nil, err
}
defer res.Close()
var out []map[string]any
for res.Rows.Next() {
if len(out) >= sqlResolverInteractiveRowLimit {
return nil, fmt.Errorf("sql resolver: interactive query limit exceeded: returned more than %d rows", sqlResolverInteractiveRowLimit)
}
row := make(map[string]any)
err = res.Rows.MapScan(row)
if err != nil {
return nil, err
}
out = append(out, row)
}
data, err := json.Marshal(out)
if err != nil {
return nil, err
}
// This is a little hacky, but for now we only cache results from DuckDB queries that have refs.
var cache bool
if r.olap.Dialect() == drivers.DialectDuckDB {
cache = len(r.refs) != 0
}
return &runtime.ResolverResult{
Data: data,
Schema: res.Schema,
Cache: cache,
}, nil
}
func (r *sqlResolver) ResolveExport(ctx context.Context, w io.Writer, opts *runtime.ResolverExportOptions) error {
exportOpts := &runtime.ExportOptions{
Format: opts.Format,
Priority: r.priority,
PreWriteHook: opts.PreWriteHook,
}
filename := "api_export_" + time.Now().Format("2006-01-02T15-04-05.000Z")
switch r.olap.Dialect() {
case drivers.DialectDuckDB:
if opts.Format == runtimev1.ExportFormat_EXPORT_FORMAT_CSV || opts.Format == runtimev1.ExportFormat_EXPORT_FORMAT_PARQUET {
return queries.DuckDBCopyExport(ctx, w, exportOpts, r.sql, nil, filename, r.olap, opts.Format)
}
return r.generalExport(ctx, w, filename, exportOpts)
case drivers.DialectDruid, drivers.DialectClickHouse:
return r.generalExport(ctx, w, filename, exportOpts)
default:
return fmt.Errorf("export not available for dialect %q", r.olap.Dialect().String())
}
}
func (r *sqlResolver) generalExport(ctx context.Context, w io.Writer, filename string, opts *runtime.ExportOptions) error {
res, err := r.olap.Execute(ctx, &drivers.Statement{
Query: r.sql,
Priority: opts.Priority,
})
if err != nil {
return err
}
meta := make([]*runtimev1.MetricsViewColumn, len(res.Schema.Fields))
for i, f := range res.Schema.Fields {
meta[i] = &runtimev1.MetricsViewColumn{
Name: f.Name,
Type: f.Type.Code.String(),
}
}
var data []*structpb.Struct
for res.Rows.Next() {
row := make(map[string]any)
err = res.Rows.MapScan(row)
if err != nil {
return err
}
curr, err := structpb.NewStruct(row)
if err != nil {
return err
}
data = append(data, curr)
}
if opts.PreWriteHook != nil {
err = opts.PreWriteHook(filename)
if err != nil {
return err
}
}
switch opts.Format {
case runtimev1.ExportFormat_EXPORT_FORMAT_UNSPECIFIED:
return fmt.Errorf("unspecified format")
case runtimev1.ExportFormat_EXPORT_FORMAT_CSV:
return queries.WriteCSV(meta, data, w)
case runtimev1.ExportFormat_EXPORT_FORMAT_XLSX:
return queries.WriteXLSX(meta, data, w)
case runtimev1.ExportFormat_EXPORT_FORMAT_PARQUET:
return queries.WriteParquet(meta, data, w)
}
return nil
}
// buildSQL resolves the SQL template and returns the resolved SQL and the resource names it references.
func buildSQL(sqlTemplate string, dialect drivers.Dialect, args, userAttributes map[string]any, forExport bool) (string, []*runtimev1.ResourceName, error) {
// Resolve the SQL template
var refs []*runtimev1.ResourceName
sql, err := compilerv1.ResolveTemplate(sqlTemplate, compilerv1.TemplateData{
User: userAttributes,
ExtraProps: map[string]any{
"args": args,
"export": forExport,
},
Resolve: func(ref compilerv1.ResourceName) (string, error) {
// Add to the list of potential refs
if ref.Kind == compilerv1.ResourceKindUnspecified {
// We don't know if it's a source or model (or neither), so we add both. Refs are just approximate.
refs = append(refs,
&runtimev1.ResourceName{Kind: runtime.ResourceKindSource, Name: ref.Name},
&runtimev1.ResourceName{Kind: runtime.ResourceKindModel, Name: ref.Name},
)
} else {
refs = append(refs, runtime.ResourceNameFromCompiler(ref))
}
// Return the escaped identifier
return dialect.EscapeIdentifier(ref.Name), nil
},
})
if err != nil {
return "", nil, err
}
// For DuckDB, we can do ref inference using the SQL AST (similar to the rillv1 compiler).
if dialect == drivers.DialectDuckDB {
ast, err := duckdbsql.Parse(sql)
if err != nil {
return "", nil, err
}
for _, t := range ast.GetTableRefs() {
if !t.LocalAlias && t.Name != "" && t.Function == "" && len(t.Paths) == 0 {
// We don't know if it's a source or model (or neither), so we add both. Refs are just approximate.
refs = append(refs,
&runtimev1.ResourceName{Kind: runtime.ResourceKindSource, Name: t.Name},
&runtimev1.ResourceName{Kind: runtime.ResourceKindModel, Name: t.Name},
)
}
}
}
return sql, normalizeRefs(refs), nil
}
|
<!DOCTYPE html>
<html lang="en">
<!--
有些元素默认不能拖,如果希望它有拖动效果
就给它写个属性叫 draggable = 'true'
ondragstart 当元素开始拖拽触发
ondrag 当元素正在拖拽触发
ondragend 当元素停止拖拽触发
ondrop 当某个容器检测到有元素移入并且松手后触发
但是要让这个事件触发,必须先实现这个容器的ondragover事件,并且这个事件需要一个event参数,再调用event.preventDefault()方法
-->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
width: 150px;
height: 150px;
background: red;
}
.container {
width: 300px;
height: 400px;
border: 1px solid black;
position: absolute;
top: 50px;
right: 20px;
}
</style>
</head>
<body>
<!--元素不是你想拖,想拖就能拖,让我写个属性draggable -->
<img src="img/shq.jpg" alt="">
<div class="box" draggable="true"></div>
<div class="container"></div>
</body>
<script>
var boxDom = document.querySelector('.box');
// 当某个被拖拽的元素开始拖拽触发
boxDom.ondragstart = function () {
console.log('你开始拖我了');
}
// 当某个被拖拽元素正在拖拽时触发
boxDom.ondrag = function () {
console.log('你正在拖我');
}
// 当某个被拖拽元素结束拖拽(松手)时触发
boxDom.ondragend = function () {
console.log('你不拖我了');
}
var containerDom = document.querySelector('.container');
// 检测我这个容器有没有元素进来
containerDom.ondragenter = function () {
console.log('有元素进来了');
}
// 检测我这个容器有没有元素出去
containerDom.ondragleave = function () {
console.log('有元素离开了');
}
// 当有元素拖拽到容器里面并且松手后才触发
// 但是这个事件使用之前必须先使用ondragover的事件,并且这个over事件必须接收参数,再调用参数的preventDefault()方法,否则这个事件永远不会触发
containerDom.ondrop = function () {
// console.log('..................');
// 写死了,永远加的都是红色的盒子
this.appendChild(boxDom);
}
// 这个方法仅仅只是为了让ondrop事件能触发
containerDom.ondragover = function (event) {
event.preventDefault();
}
</script>
</html>
|
<script lang="ts">
import { faker } from '@faker-js/faker';
import type { AccountsFragment } from '../graphql/graphql';
import { graphqlInsertTransactions } from '../graphql/graphqlApi';
import { transactionStore } from '../store';
export let accounts: AccountsFragment[]
$: transactions = $transactionStore
function generateTransaction() {
const transactionDate = faker.date.between('2023-02-13', '2023-04-13');
const status = faker.helpers.arrayElement(['pending', 'completed']);
let postDate: Date | null = null;
if (status === 'completed') {
postDate = transactionDate;
postDate.setDate(transactionDate.getDate() + faker.datatype.number({ min: 1, max: 3 }));
}
const category = faker.helpers.arrayElement(['food', 'entertainment', 'utilities']);
const description = faker.helpers.arrayElement(
{
food: ['coffee', 'groceries', 'burritos'],
entertainment: ['streaming', 'movies', 'pickleball'],
utilities: ['electricity', 'water', 'gas']
}[category]
);
let accountId = accounts.find(acct => acct.name === accountName)?.id ?? -1
return {
amount: faker.finance.amount(),
description,
category,
status,
transactionDate,
postDate,
accountId
};
}
$: {
if (accountName !== '') disabled=false
else disabled = true
}
let result = '';
let statusCode = '';
let accountName: string = '';
let disabled = true;
async function generate() {
disabled = true;
const response = await graphqlInsertTransactions({object: [...Array(10).keys()].map(generateTransaction)})
if (response.errors) {
statusCode = 'Error'
result = 'GraphQL Errors :(. Please see console';
console.error('Genertion error - open me!', response.errors);
} else if (response.data.insert_Transactions?.returning) {
let insertedTrans = response.data.insert_Transactions?.returning
statusCode = 'OK'
result = JSON.stringify(insertedTrans.map((transaction) => transaction.id));
transactions = [...transactions, ...insertedTrans]
}
disabled = false;
}
</script>
<div class="m-1 p-2 rounded-lg border border-cyan-500 shadow-md mt-4">
<input class="h-8 m-1 p-2 rounded-lg outline outline-1 outline-gray-300 bg-gray-50 shadow-md" placeholder="Account Name" bind:value={accountName} />
<div class=''>
<button
class="rounded-lg border border-cyan-600 bg-cyan-500 p-2 m-1 hover:bg-cyan-400 hover:outline-cyan-100 {disabled
? 'opacity-50 cursor-not-allowed'
: ''}"
on:click={generate}
{disabled}>Generate 10 Transactions</button
>
<p class="opacity-0 ml-1 text-sm {disabled
? 'opacity-100'
: ''
}"
>Please enter a valid Account Name to Generate Transactions.</p>
</div>
<div class="mt-4">
<div>Response</div>
<div>Status: {statusCode}</div>
<div>{result}</div>
</div>
</div>
|
//
// Day43View.swift
// SwiftUIof100Days
//
// Created by Ray on 2022/5/26.
//
import SwiftUI
struct Day43View: View {
var body: some View {
VStack(spacing: 20.0) {
Triangle()
.stroke(.blue, style: StrokeStyle(lineWidth: 10.0, lineCap: .round, lineJoin: .round))
.frame(width: 120, height: 120)
Arc(startAngle: .degrees(-90), endAngle: .degrees(140), clockwise: true)
.strokeBorder(.red, style: StrokeStyle(lineWidth: 5.0, dash: [2.0, 4.0]))
.frame(width: 120, height: 120.0)
// .stroke = 繪製時會超出邊界
// .strokeBorder = 繪製時會符合邊界
Circle()
//.stroke(.green, lineWidth: 5.0)
.strokeBorder(.green, lineWidth: 5.0)
.frame(width: 120.0, height: 120.0)
Spacer()
}
}
}
struct Day43View_Previews: PreviewProvider {
static var previews: some View {
Day43View()
}
}
// MARK: - View
struct Triangle: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: rect.midX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.midX, y: rect.minY))
return path
}
}
struct Arc: Shape, InsettableShape {
var startAngle: Angle
var endAngle: Angle
var clockwise: Bool
var insetAmoun = 0.0
func path(in rect: CGRect) -> Path {
// What’s happening here is two-fold:
// In the eyes of SwiftUI 0 degrees is not straight upwards, but instead directly to the right.
// Shapes measure their coordinates from the bottom-left corner rather than the top-left corner, which means SwiftUI goes the other way around from one angle to the other. This is, in my not very humble opinion, extremely alien.
let rotationAdjustment = Angle.degrees(90)
let modifiedStart = startAngle - rotationAdjustment
let modifiedEnd = endAngle - rotationAdjustment
var path = Path()
path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: rect.width / 2 - insetAmoun, startAngle: modifiedStart, endAngle: modifiedEnd, clockwise: !clockwise)
return path
}
// 將繪製範圍符合目前的frame
func inset(by amount: CGFloat) -> some InsettableShape {
var arc = self
arc.insetAmoun += amount
return arc
}
}
|
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $table = 'users';
protected $primaryKey = 'id';
protected $fillable = [
'fio',
'date_of_birth',
'country',
'city',
'citizenship',
'gender',
'phone',
'email',
'education',
'employment',
'work_experience',
'skills',
'achievements',
'presence_team',
'role_team',
'patent',
'company',
'role',
'password',
'profile_image',
'id_team',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/*public function currentIdea(){
return $this->belongsTo(CurrentIdea::class, 'id_current_idea','id');
}
public function sciencetIdea(){
return $this->belongsTo(ScienceIdea::class, 'id_science_idea','id');
}*/
public function comments(){
return $this->hasMany(Comment::class, 'id_user','id');
}
public function any_idea()
{
return $this->belongsToMany(AnyIdea::class);
}
}
|
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import HomePage from "./routes/homePage/HomePage";
import ListPage from "./routes/listPage/ListPage";
import { Layout, RequireAuth } from "./routes/layout/Layout";
import SinglePage from "./routes/singlePage/SinglePage";
import ProfilePage from "./routes/profilePage/ProfilePage";
import ProfileUpdatePage from "./routes/profileUpdatePage/ProfileUpdatePage";
import Login from "./routes/login/Login";
import Register from "./routes/register/Register";
import NewPostPage from "./routes/newPostPage/NewPostPage";
import {
agentsLoader,
listPageLoader,
profilePageLoader,
singlePageLoader,
userProfileLoader,
} from "./lib/loaders";
import UserProfile from "./routes/userProfile/UserProfile";
import AgentsPage from "./routes/agentsPage/AgentsPage";
import AboutPage from "./routes/aboutPage/AboutPage";
import ContactPage from "./routes/contactPage/ContactPage";
import PromotePage from "./routes/promotePage/PromotePage";
import SuccessPromotionPage from "./routes/successPromotionPage/SuccessPromotionPage";
import EditPostPage from "./routes/EditPostPage/EditPostPage";
import CancelPaymentPage from "./routes/cancelPaymentPage/CancelPaymentPage";
function App() {
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{
path: "/",
element: <HomePage />,
},
{
path: "/list",
element: <ListPage />,
loader: listPageLoader,
},
{
path: "/:id",
element: <SinglePage />,
loader: singlePageLoader
},
{
path: "/login",
element: <Login />,
},
{
path: "/register",
element: <Register />,
},
{
path: "/about",
element: <AboutPage />,
},
{
path: "/agents",
element: <AgentsPage />,
loader: agentsLoader,
},
{
path: "/userProfile/:id",
element: <UserProfile />,
loader: userProfileLoader,
},
{
path: "/contact",
element: <ContactPage />,
},
],
},
{
path: "/",
element: <RequireAuth />,
children: [
{
path: "/profile",
element: <ProfilePage />,
loader: profilePageLoader,
},
{
path: "/profile/update",
element: <ProfileUpdatePage />,
},
{
path: "/add",
element: <NewPostPage />,
},
{
path: "/promote",
element: <PromotePage />,
},
{
path: "/promote/successPromotion",
element: <SuccessPromotionPage />,
},
{
path: "/editPost/:id",
element: <EditPostPage />,
},
{
path: "/promote/failedPromotion",
element: <CancelPaymentPage />,
},
],
},
]);
return <RouterProvider router={router} />;
}
export default App;
|
/******************************************************************************
* Copyright 2023 NVIDIA Corporation. All rights reserved.
******************************************************************************/
mdl 1.2;
// import all modules that shall be available in distilling rules
import ::limits::*;
import ::anno::*;
import ::state::*;
import ::math::*;
import ::tex::*;
import ::df::*;
import ::base::*;
// --------------------------------------------------------------------------------------------
// Distiller support functions, added to Release 2017.1 (296300) unless noted otherwise
// functions for helping with color arrays in curve df
//ADDED 2022.1
export int size( color[<L>] a)
{
return L;
}
export color last( color[<L>] a)
{
return a[L-1];
}
// Returns a color IOR value to match a given normal incidence direction reflectivity value R_0.
export color ior_from_refl(float R_0)
{
// ior = (1+sqrt(R_0))/(1-sqrt(R_0))
float root_r = math::sqrt(R_0);
float i = ((root_r > 0.98) ? 100 : (1+root_r)/(1-root_r)); // clamp ior to 100
return color(i);
}
// Returns a color IOR value to match a given normal incidence direction reflectivity value R_0.
export color ior_from_refl(color R_0)
{
// ior = (1+sqrt(R_0))/(1-sqrt(R_0))
color root_r = math::sqrt( R_0 );
root_r = math::clamp(root_r,color(0.0),color(.98));
color i = (1+root_r)/(1-root_r);
return i;
}
//access last element of an array, workaround for distiller rules not having context
export float last_element(float[<count>] values)
{
return values[count-1];
}
export color last_element(color[<count>] values)
{
return values[count-1];
}
// Returns a scalar IOR value to match a given normal incidence direction reflectivity value R_0.
// ADDED for Release 2018.0
export float float_ior_from_refl(float R_0)
{
// ior = (1+sqrt(R_0))/(1-sqrt(R_0))
float root_r = math::sqrt(R_0);
float i = ((root_r > 0.98) ? 100 : (1+root_r)/(1-root_r)); // clamp ior to 100
return i;
}
// Returns a scalar IOR value to match a given normal incidence direction reflectivity value R_0.
// ADDED for Release 2018.0
export float float_ior_from_refl(color R_0)
{
// ior = (1+sqrt(R_0))/(1-sqrt(R_0))
float root_r = math::sqrt( math::luminance( R_0));
root_r = math::clamp(root_r, 0.0, .98);
float i = (1+root_r)/(1-root_r);
return i;
}
// Returns a normal incidence direction reflectivity value for a given IOR.
// ADDED for Release 2018.0
export float refl_from_ior(float ior)
{
// R_0=((ior-1)/(ior+1))^2
float root_r = (ior-1)/(ior+1);
return root_r*root_r;
}
// Returns a normal incidence direction reflectivity value for a given IOR.
export color refl_from_ior(color ior)
{
// R_0=((ior-1)/(ior+1))^2
color root_r = (ior-1)/(ior+1);
return root_r*root_r;
}
// Returns a normal incidence direction reflectivity value for a given complex IOR.
// For incident direction, both polarization cases give the same result
export color refl_from_ior_k(color ior, color k)
{
color k2=k*k;
color ior2 = ior*ior;
color rs_num = ior2 + k2 - 2*ior + 1;
color rs_den = ior2 + k2 + 2*ior + 1;
color rs = rs_num/rs_den ;
return math::clamp(rs, 0.0, 1.0);
}
// Returns a Gulbrandsen edge color for a given complex IOR.
//ADDED 2022.0
export color g_from_ior_k(color ior, color k)
{
//edge_tint = ((1+sqrt(r))/(1-sqrt(r)) -ior )
// /
// ((1+sqrt(r))/(1-sqrt(r)) - (1-r)/(1+r) )
color r = refl_from_ior_k(ior,k);
color sr = math::sqrt(r);
color t1 = (1.+sr)/(1.-sr);
color t2 = (1.-r)/(1.+r);
return (t1-ior)/(t1-t2);
}
// A helper function, marked as "noinline", to communicate directional dependent coloring
// information to be picked up by later passes and integration code. Note: this cannot
// be expressed fully functional in MDL itself, it targets a different model.
export color directional_coloring(color C_0, color C_90 [[anno::unused()]], float e [[anno::unused()]])
[[
anno::noinline()
]]
{
return (C_0);
}
// A helper function, marked as "noinline", to communicate directional dependent coloring
// information to be picked up by later passes and integration code. Note: this cannot
// be expressed fully functional in MDL itself, it targets a different model.
export float directional_weighting(float W_0, float W_90 [[anno::unused()]], float e [[anno::unused()]])
[[
anno::noinline()
]]
{
return (W_0);
}
// Combines the two anisotropic roughness values into one. The current heuristic
// chooses the lower roughness. Just averaging leads to too dull looking materials.
export float combine_anisotropic_roughness(float r1, float r2)
{
return (r1>r2)?r2:r1;
}
// Returns the weighted and re-normalized average of r1 and r2. Returns 0 if w1 + w2 is too small.
export float average(float w1, float r1, float w2, float r2)
{
w1=math::saturate(w1);
w2=math::saturate(w2);
return math::abs(w1+w2)>.00001 ? (w1*r1+w2*r2)/(w1+w2) : 0.0;
}
// Returns the weighted and re-normalized average of r1 and r2. Returns 0 if w1 + w2 is too small.
export color average(float w1, color r1, float w2, color r2)
{
w1=math::saturate(w1);
w2=math::saturate(w2);
return math::abs(w1+w2)>.00001 ? (w1*r1+w2*r2)/(w1+w2) : color(0.0);
}
// prevent dull looking materials when combining 2 custom curve layered bsdf into one
// take weight and roughness into account
export float combine_glossy(float w1, float r1, float v1, float w2, float r2, float v2)
{
float g1 = 1.-r1;
float g2 = 1.-r2;
return average(w1*g1*g1*g1,v1,w2*g2*g2*g2,v2);
}
export color combine_glossy(float w1, float r1, color v1, float w2, float r2, color v2)
{
float g1 = 1.-r1;
float g2 = 1.-r2;
return average(w1*g1*g1*g1,v1,w2*g2*g2*g2,v2);
}
// Returns the weighted and re-normalized average of r1, r2, and r3.
// Returns 0 if w1 + w2 + w3 is too small.
export float average(float w1, float r1, float w2, float r2, float w3, float r3)
{
return math::abs(w1+w2+w3)>.00001 ? (w1*r1+w2*r2+w3*r3)/(w1+w2+w3) : 0.0;
}
// Returns the weighted and re-normalized average of r1, r2, and r3.
// Returns 0 if w1 + w2 + w3 is too small.
export color average(float w1, color r1, float w2, color r2, float w3, color r3)
{
return math::abs(w1+w2+w3)>.00001 ? (w1*r1+w2*r2+w3*r3)/(w1+w2+w3) : color(0.0);
}
// Returns the weighted and re-normalized average of r1 and r2. Returns 0 if w1 + w2 is too small.
// ADDED for Release 2018.0
export float color_average(color cw1, float r1, color cw2, float r2)
{
float w1 = math::luminance( cw1);
float w2 = math::luminance( cw2);
return math::abs(w1+w2)>.00001 ? (w1*r1+w2*r2)/(w1+w2) : 0.0;
}
// Returns the weighted and re-normalized average of r1, r2, and r3.
// Returns 0 if w1 + w2 + w3 is too small.
// ADDED for Release 2018.0
export float color_average(color cw1, float r1, color cw2, float r2, color cw3, float r3)
{
float w1 = math::luminance( cw1);
float w2 = math::luminance( cw2);
float w3 = math::luminance( cw3);
return math::abs(w1+w2+w3)>.00001 ? (w1*r1+w2*r2+w3*r3)/(w1+w2+w3) : 0.0;
}
// Returns a normalized against w1 + w2, or 0 if w1 + w2 is too small.
export float part_normalized(float a,float w1,float w2)
{
return math::abs(w1+w2)>.00001?a/(w1+w2):0.0;
}
// Returns the normal n in tangent space, given n is in internal space.
export float3 transform_internal_to_tangent(float3 n)
{
return
n.x* float3(state::texture_tangent_u(0).x,state::texture_tangent_v(0).x,state::normal().x)+
n.y* float3(state::texture_tangent_u(0).y,state::texture_tangent_v(0).y,state::normal().y)+
n.z* float3(state::texture_tangent_u(0).z,state::texture_tangent_v(0).z,state::normal().z);
}
// Returns the normal n in internal space, given n is in tangent space.
export float3 transform_tangent_to_internal(float3 n)
{
return state::texture_tangent_u(0) * n.x +
state::texture_tangent_v(0) * n.y +
state::normal() * n.z ;
}
// Returns a normal as a weighted combination of two normals.
//a blended normal will usually not be satisfactory, works mostly for "sticker" type situations
export float3 combine_normals(
float w1 = 1.0, float3 n1 = state::normal(),
float w2 = 1.0, float3 n2 = state::normal())
{
// http://blog.selfshadow.com/publications/blending-in-detail/
float3 n1_t = transform_internal_to_tangent(n1);
float3 n2_t = transform_internal_to_tangent(n2);
n1_t = math::normalize(math::lerp(float3(0,0,1.),n1_t,w1));
n2_t = math::normalize(math::lerp(float3(0,0,1.),n2_t,w2));
n1_t = n1_t + float3(0.,0.,1.);
n2_t = n2_t * float3(-1.,-1.,1.);
float3 n = n1_t*math::dot(n1_t, n2_t)/n1_t.z - n2_t;
return math::normalize(transform_tangent_to_internal(n));
}
// Returns a normal as a weighted combination of two normals.
//a blended normal will usually not be satisfactory, works mostly for "sticker" type situations
export float3 combine_tangent_normals(
float w1 = 1.0, float3 n1 = float3(0.,0.,1.),
float w2 = 1.0, float3 n2 = float3(0.,0.,1.))
{
// http://blog.selfshadow.com/publications/blending-in-detail/
float3 n1_t = math::normalize(math::lerp(float3(0,0,1.),n1,w1));
float3 n2_t = math::normalize(math::lerp(float3(0,0,1.),n2,w2));
n1_t = n1_t + float3(0.,0.,1.);
n2_t = n2_t * float3(-1.,-1.,1.);
float3 n = n1_t*math::dot(n1_t, n2_t)/n1_t.z - n2_t;
return math::normalize(n);
}
// this is a compromise. a blended normal will usually not be satisfactory,.
// we would often want the visualy predominant normal unaltered, like the flake normal
// for carpaints. still
export float3 layer_normals(
float w1 = 1.0, float3 n1 = state::normal(),
float3 n2 = state::normal())
{
// http://blog.selfshadow.com/publications/blending-in-detail/
float3 n1_t = transform_internal_to_tangent(n1);
float3 n2_t = transform_internal_to_tangent(n2);
float v = math::smoothstep( 0.4,0.6,w1 );
n1_t = math::normalize(math::lerp(float3(0,0,1.),n1_t,v));
n2_t = math::normalize(math::lerp(float3(0,0,1.),n2_t,1.0-v));
n1_t = n1_t + float3(0.,0.,1.);
n2_t = n2_t * float3(-1.,-1.,1.);
float3 n = n1_t*math::dot(n1_t, n2_t)/n1_t.z - n2_t;
return math::normalize(transform_tangent_to_internal(n));
}
// Returns a normal by adding a detail normal to a global normal.
export float3 add_detail_normal(float3 nd = state::normal(), float3 n = state::normal())
{
// http://blog.selfshadow.com/publications/blending-in-detail/
float3 n_t = transform_internal_to_tangent(n);
float3 nd_t = transform_internal_to_tangent(nd);
n_t=n_t + float3(0.,0.,1.);
nd_t = nd_t * float3(-1.,-1.,1.);
n = n_t*math::dot(n_t, nd_t)/n_t.z - nd_t;
return math::normalize(transform_tangent_to_internal(n));
}
// Used in dist_rules.mdltl
// ------------------------
// Returns a normal for a weighted normal map.
export float3 affine_normal_sum(float w1, float3 n1)
{
// f_n in the techreport
float3 n = state::normal();
return math::normalize( n + w1 * (n1 - n));
}
// Returns a normal for a weighted combination of two normal maps.
export float3 affine_normal_sum( float w1, float3 n1, float w2, float3 n2)
{
float3 n = state::normal();
return math::normalize( n + w1 * (n1 - n) + w2 * (n2 - n));
}
// Returns a normal for a weighted combination of three normal maps.
export float3 affine_normal_sum( float w1, float3 n1, float w2, float3 n2, float w3, float3 n3)
{
float3 n = state::normal();
return math::normalize( n + w1 * (n1 - n) + w2 * (n2 - n) + w3 * (n3 - n));
}
// Returns the combined roughness of two diffuse BSDFs.
// Chooses the maximum roughness as the current heuristic.
export float combine_diffuse_roughness(float w1 [[anno::unused()]], float r1,
float w2 [[anno::unused()]], float r2)
{
return math::max(r1,r2);
}
// Returns the combined roughness of three diffuse BSDFs.
// Chooses the maximum roughness as the current heuristic.
export float combine_diffuse_roughness(float w1 [[anno::unused()]], float r1,
float w2 [[anno::unused()]], float r2,
float w3 [[anno::unused()]], float r3)
{
return math::max(r1,math::max(r2,r3));
}
// Returns the combined roughness of two diffuse BSDFs.
// Chooses the maximum roughness as the current heuristic.
// ADDED for Release 2018.0
export float combine_diffuse_roughness(color w1 [[anno::unused()]], float r1,
color w2 [[anno::unused()]], float r2)
{
return math::max(r1,r2);
}
// Returns the combined roughness of three diffuse BSDFs.
// Chooses the maximum roughness as the current heuristic.
// ADDED for Release 2018.0
export float combine_diffuse_roughness(color w1 [[anno::unused()]], float r1,
color w2 [[anno::unused()]], float r2,
color w3 [[anno::unused()]], float r3)
{
return math::max(r1,math::max(r2,r3));
}
// Used in dist_rules_dg.mdltl
// ---------------------------
// Returns the normalized weighted sum of normal vectors.
export float3 affine_sum_normalized(float w1, float3 t1, float w2, float3 t2)
{
return math::normalize(w1*t1+w2*t2);
}
// Returns the normalized weighted sum of normal vectors.
export float3 affine_sum_normalized(float w1, float3 t1, float w2, float3 t2, float w3, float3 t3)
{
// f_tangent in the techreport
return math::normalize(w1*t1+w2*t2+w3*t3);
}
// Returns the normalized weighted sum of normal vectors.
// ADDED for Release 2018.0
export float3 affine_sum_normalized(color w1, float3 t1, color w2, float3 t2)
{
return math::normalize(math::luminance(w1)*t1+math::luminance(w2)*t2);
}
// Returns the normalized weighted sum of normal vectors.
// ADDED for Release 2018.0
export float3 affine_sum_normalized(color w1, float3 t1, color w2, float3 t2, color w3, float3 t3)
{
// f_tangent in the techreport
return math::normalize(math::luminance(w1)*t1+math::luminance(w2)*t2+math::luminance(w3)*t3);
}
// Helper struct for the combined results of combining two Fresnel layers into one.
export struct combined_fresnel_result
{
color ior;
float w1;
float w2;
};
// Returns the new IOR and two helper weights for combining two Fresnel layerers into one.
export combined_fresnel_result combined_fresnel(color ior1, color ior2, float w)
{
// f_ii in the techreport
float r1 = w * float3(refl_from_ior(ior1)).y;
float r2 = float3(refl_from_ior(ior2)).y;
float new_r = r1 * (1 + r2);
color ior = ior_from_refl(new_r);
float w1 = w/(1.0+r2);
float w2 = w*r2/(1.0+r2) + 1.0 - w;
return combined_fresnel_result(ior,w1,w2);
}
// Helper struct for the combined results of combining two Fresnel layers into one.
// ADDED for Release 2018.0
export struct combined_fresnel_result_2
{
float ior;
float w1;
float w2;
};
// Returns the new IOR and two helper weights for combining two Fresnel layerers into one.
// ADDED for Release 2018.0
export combined_fresnel_result_2 combined_fresnel_diffuse(
float ior1, float w1, float ior2, float w2)
{
// fresnel(ior1,w1,diffuse1,fresnel(ior2,w2,glossy2,diffuse2))
// --> fresnel(ior,1,glossy2,w_d1*diffuse1+w_d2*diffuse2)
float r1 = w1 * refl_from_ior(ior1);
float r2 = (1-r1)* w2 * refl_from_ior(ior2);
float ior = float_ior_from_refl(r2);
float r3 = (1-r1-r2);
float f = 1.0/(r1+r3);
float w_d1 = r1*f;
float w_d2 = r3*f;
return combined_fresnel_result_2(ior,w_d1,w_d2);
}
export combined_fresnel_result_2 combined_fresnel_glossy(
float ior1, float w1, float ior2, float w2)
{
// fresnel(ior1,w1,glossy1,fresnel(ior2,w2,glossy2,diffuse2))
// --> fresnel(ior,1,wg1*glossy1+wg2*glossy2,diffuse2)
float r1 = w1 * refl_from_ior(ior1);
float r2 = (1-r1)* w2 * refl_from_ior(ior2);
float sum_refl = r1 + r2;
float ior = float_ior_from_refl(sum_refl);
float f = 1.0/(r1+r2);
float wg1 = r1*f;
float wg2 = r2*f;
return combined_fresnel_result_2(ior,wg1,wg2);
}
// Helper struct for the combined results of combining three Fresnel layers into one.
// ADDED for Release 2018.0
export struct combined_fresnel_result_4
{
float ior;
float w;
float g1;
float g2;
float d1;
float d2;
};
// Returns the new IOR and four helper weights for combining three Fresnel layerers into one.
// ADDED for Release 2018.0
export combined_fresnel_result_4 combined_fresnel_4(
float ior, float w, float ior1, float w1, float ior2, float w2)
{
// fresnel(ior,w,fresnel1(ior1,w1,glossy1,diffuse1),fresnel2(ior2,w2,glossy2,diffuse2))
// --> fresnel(ior',w',g1*glossy1+g2*glossy2,d1*diffuse1+d2*diffuse2)
float r1 = w * refl_from_ior(ior);
float r2 = (1-r1);
float r11 = w1 * refl_from_ior(ior1);
float r22 = w2 * refl_from_ior(ior2);
float rG1 = r1 * r11;
float rD1 = r1 * (1-r11);
float rG2 = r2 * r22;
float rD2 = r2 * (1-r22);
float rG = rG1 + rG2;
float i_rG = 1.0/rG;
float i_rD = 1.0/(rD1 + rD2);
float w_p = w*w1 + (1-w)*w2;
float ior_p = float_ior_from_refl(rG/w_p);
float g1 = rG1*i_rG;
float g2 = rG2*i_rG;
float d1 = rD1*i_rD;
float d2 = rD2*i_rD;
return combined_fresnel_result_4(ior_p,w_p,g1,g2,d1,d2);
}
// Returns an IOR for a Fresnel layerer to match a normal incident reflectivity of a Fresnel
// layerer with given ior weighted by w.
export color ior_from_weighted_refl_from_ior(float w, color ior)
{
// f_i in the techreport
return ior_from_refl( w * refl_from_ior( ior));
}
// Returns an IOR for a Fresnel layerer to match a normal incident reflectivity of a Fresnel
// layerer with given ior weighted by w.
// ADDED for Release 2018.0
export float ior_from_weighted_refl_from_ior(float w, float ior)
{
// f_i in the techreport
return float_ior_from_refl( w * refl_from_ior( ior));
}
// Internal helper function to aggregate local normal maps in a separate pass to combine
// them with the global normal map. Will be completely removed after the distillation pass,
// i.e., it will never show up in a distilled result.
export color local_normal(float weight [[ anno::unused() ]], float3 normal [[ anno::unused() ]])
[[
anno::noinline()
]]
{
return color(0.0); // dummy code, never executed
}
// Returns the corresponding roughness value for simple_glossy_bsdf given a
// shininess value n from a Phong or Ashikhmin - Shirley model.
export float roughness_from_n(float n)
{
return math::sqrt(2.0 / n);
}
// --------------------------------------------------------------------------------------------
// transformations from one set of parameters into a different one. used for transmissive_pbr
export struct roughness_info{
float roughness_u;
float roughness_v;
float3 tangent;
};
export struct user_roughness_info{
float roughness;
float anisotropy;
float rotation;
};
float3 rotated_tangent(float rotation)
{
return(math::cos(2*math::PI*rotation)*state::texture_tangent_u(0)+ math::sin(2*math::PI*rotation)*state::texture_tangent_v(0));
}
export roughness_info transform_aniso_semantics(user_roughness_info r)
{
float r_v = r.roughness*(1.0-r.anisotropy);
return roughness_info(r.roughness,r_v, rotated_tangent(r.rotation));
}
export user_roughness_info transform_inverse_aniso_semantics(float roughness_u, float roughness_v, float3 tangent)
{
float roughness = roughness_u;
float rotation_offset = 0.0;
float anisotropy=roughness_u > 0.0? 1.0 - roughness_v/roughness_u:0.0;
if(roughness_v>roughness_u)
{
anisotropy = roughness_v > 0.0?1.0 - roughness_u/roughness_v:0.0;
rotation_offset = .25;
roughness = roughness_v;
}
float rotation = rotation_offset - math::atan2(math::length(math::cross(tangent, state::texture_tangent_u(0))),math::dot(tangent, state::texture_tangent_u(0)))/(2.0*math::PI);
if(rotation < 0) rotation +=1.0;
if(rotation >1.0) rotation -=1.0;
return user_roughness_info(roughness,math::saturate(anisotropy),rotation);
}
export struct volume_info{
color absorption_coefficient;
color scattering_coefficient;
};
export struct user_volume_info{
color attenuation;
color subsurface;
float distance;
};
//see https://blog.selfshadow.com/publications/s2017-shading-course/imageworks/s2017_pbs_imageworks_slides_v2.pdf p44
//valid for eccentricity/anisotropy = 0. anisotropy will result in darkening but imho that's positive
//since artists dont deal with semiinfinite volumes
export volume_info transform_volume_semantics(user_volume_info v)
{
color extinction_coefficient=math::log(v.attenuation) / -v.distance;
color s = color(4.09712)+4.20863*v.subsurface-math::sqrt(9.59217+41.6808*v.subsurface+17.7126*v.subsurface*v.subsurface);
color ss_albedo = color(1.0)-s*s;
color absorption_coefficient = extinction_coefficient*(color(1.0)-ss_albedo);
return volume_info( absorption_coefficient , extinction_coefficient- absorption_coefficient);
}
export user_volume_info transform_inverse_volume_semantics(color absorption_coefficient, color scattering_coefficient)
{
//some user functions might create coefficients containing inf. take care:
color absorption_coefficient2 =math::min(absorption_coefficient,color(10000.));
color scattering_coefficient2 =math::min(scattering_coefficient,color(10000.));
color extinction_coefficient = absorption_coefficient2+scattering_coefficient2;
//prevent /0.0. if extinction is 0, absorption is also 0. we can force divisor to any non zero value
//and get an sss _albedo of 1. This won't hurt because extinction will still lead to scattering coefficient of 0
color ss_albedo = color(1.0)-absorption_coefficient2/math::max(extinction_coefficient, color(limits::FLOAT_MIN));
color s = math::sqrt(color(1.0)-ss_albedo);
color subsurface =(color(1.0)-s)*(color(1.0)-0.139*s)/(color(1.0)+1.17*s);
float max = math::max_value(extinction_coefficient);
//if extinction_coefficient is 0, distance does not really matter anymore
float distance = max != 0.0? 1.0/math::max_value(extinction_coefficient):1.0;
return user_volume_info( math::exp(-extinction_coefficient*distance) , subsurface , distance);
}
|
import * as React from "react"
import useListRestQuery from "../queries/useListRestQuery"
import Layout from "../components/layout"
import Seo from "../components/seo"
import useWindowSize from "../hooks/useWindowSize"
import ProjectItem from "../components/ProjectItem/ProjectItem"
import Carousel from "../components/Carousel/Carousel"
import useViewport from "../hooks/useViewport"
import useRestsPageQuery from "../queries/useRestsPageQuery"
import { Script } from "gatsby"
const Restaurantes = () => {
const data = useListRestQuery()
const seoData = useRestsPageQuery()
const size = useWindowSize()
useViewport()
function eliminarDuplicados(arr) {
const uniqueArray = []
for (const obj of arr) {
if (
!uniqueArray.some(item => JSON.stringify(item) === JSON.stringify(obj))
) {
uniqueArray.push(obj)
}
}
return uniqueArray
}
const arraySinDuplicados = eliminarDuplicados(data)
return (
<Layout>
<Seo
title="Restaurantes"
lang="es"
titleSEO={seoData.seoTitle}
description={seoData.seoMetaDescription.seoMetaDescription}
/>
<Script>
{`function loadScript(a){var b=document.getElementsByTagName("head")[0],c=document.createElement("script");c.type="text/javascript",c.src="https://tracker.metricool.com/resources/be.js",c.onreadystatechange=a,c.onload=a,b.appendChild(c)}loadScript(function(){beTracker.t({hash:"c7083958ef736a97d794353925bdd4b9"})});`}
</Script>
<div className="Main__titles displayNoneXL">
<h1>Nuestros restaurantes</h1>
<h6>Grupo El Rincón</h6>
</div>
<div className="Main__text">
{size > 880 // ------------------------------ PROJECT ITEM DESKTOP
? arraySinDuplicados.map((rest, i) => (
<ProjectItem
key={i}
name={rest.node.nombre}
year={rest.node.zona}
slug={rest.node.url}
imgs={rest.node.desktopDetalleImgs.slice(0, 4)}
dir1={rest.node.direccionLinea1}
dir2={rest.node.direccionLinea2}
time1={rest.node.horarioLinea1}
time2={rest.node.horarioLinea2}
menu={rest.node.carta}
booking={rest.node.reservar}
bookGroup={rest.node.reservasDeGrupoONo}
/>
))
: // ------------------------------------------ CAROUSEL MOBILE
arraySinDuplicados.map((rest, i) => (
<div className="container">
<Carousel
key={i}
images={rest.node.mobileListadoImg.slice(0, 4)}
linked={true}
slug={`restaurantes/${rest.node.url}`}
dir1={rest.node.direccionLinea1}
dir2={rest.node.direccionLinea2}
time1={rest.node.horarioLinea1}
time2={rest.node.horarioLinea2}
menu={rest.node.carta}
booking={rest.node.reservar}
bookGroup={rest.node.reservasDeGrupoONo}
/>
<div className="justify-content-center text-center mb-5 mt-2">
<p>
<b style={{ fontSize: 16, lineHeight: 0 }}>
{rest.node.nombre}
</b>
<br />
{rest.node.zona}
</p>
</div>
</div>
))}
</div>
</Layout>
)
}
export default Restaurantes
|
import asyncio
import re
from collections.abc import Awaitable, Callable
from functools import partial
from typing import Any, TypeVar
import httpx
import jsonpath_ng
from jsonpath_ng.exceptions import JsonPathParserError
from tracecat.auth import AuthenticatedAPIClient
from tracecat.contexts import ctx_session_role
from tracecat.db import Secret
from tracecat.logger import standard_logger
logger = standard_logger(__name__)
JSONPATH_TEMPLATE_PATTERN = re.compile(r"{{\s*(?P<jsonpath>.*?)\s*}}")
SECRET_TEMPLATE_PATTERN = re.compile(r"{{\s*SECRETS\.(?P<secret_name>.*?)\s*}}")
T = TypeVar("T", str, list[Any], dict[str, Any])
def _evaluate_jsonpath_str(
match: re.Match[str],
action_trail: dict[str, Any],
regex_group: str = "jsonpath",
) -> str:
"""Replacement function to be used with re.sub().
Note
----
This function only gets called when there's a match, i.e. match is not None.
This means we don't have to deal with the case where there are no templates.
Cases
-----
1. Input was just a plan string. Return the original string.
2. Input was a jsonpath. Return the value found in the action trail.
"""
jsonpath = match.group(regex_group)
logger.debug(f"{"*"*10} Evaluating jsonpath {jsonpath} {"*"*10}")
try:
jsonpath_expr = jsonpath_ng.parse(jsonpath)
except JsonPathParserError as e:
raise ValueError(f"Invalid jsonpath {jsonpath!r}.") from e
logger.debug(f"{jsonpath_expr = }")
matches = [found.value for found in jsonpath_expr.find(action_trail)]
if len(matches) == 1:
logger.debug(f"Match found for {jsonpath}: {matches[0]}.")
return str(matches[0])
elif len(matches) > 1:
logger.debug(f"Multiple matches found for {jsonpath}: {matches}.")
return str(matches)
else:
# We know that if this function is called, there was a templated field.
# Therefore, it means the jsonpath was valid but there was no match.
raise ValueError(
f"jsonpath has no field {jsonpath!r}. Action trail: {action_trail}."
)
def _evaluate_templated_dict(
obj: dict[str, T], operator: Callable[[re.Match[str]], str]
) -> dict[str, T]:
return {
_evaluate_nested_templates_rec(k, operator): _evaluate_nested_templates_rec(
v, operator
)
for k, v in obj.items()
}
def _evaluate_nested_templates_rec(
obj: T,
operator: Callable[[re.Match[str]], str],
) -> T:
"""Process jsonpaths in strings, lists, and dictionaries."""
match obj:
case str():
# Matches anything in {{ ... }}
return operator(obj)
case list():
return [_evaluate_nested_templates_rec(item, operator) for item in obj]
case dict():
return _evaluate_templated_dict(obj, operator)
case _:
return obj
def evaluate_templated_fields(
*,
templated_fields: dict[str, Any],
source_data: dict[str, Any],
template_pattern: re.Pattern[str] = JSONPATH_TEMPLATE_PATTERN,
) -> dict[str, Any]:
"""Populate templated fields with actual values."""
jsonpath_str_evaluator = partial(_evaluate_jsonpath_str, action_trail=source_data)
def operator(obj: T) -> str:
return template_pattern.sub(jsonpath_str_evaluator, obj)
logger.debug(f"{"*"*10} Evaluating templated fields {"*"*10}")
processed_kwargs = _evaluate_templated_dict(templated_fields, operator)
return processed_kwargs
async def _load_secret(secret_name: str) -> str:
"""Load a secret on behalf of the current workflow run."""
try:
# NOTE(perf): We can frontload these requests before starting
# the workflow, then look up the encrypted secrets in a local cache.
role = ctx_session_role.get()
async with AuthenticatedAPIClient(role=role, http2=True) as client:
response = await client.get(f"/secrets/{secret_name}")
response.raise_for_status()
secret = Secret.model_validate_json(response.content)
return secret.key # Decrypt secret value
except httpx.HTTPStatusError as e:
msg = f"Error loading {secret_name!r}. {response.text}"
logger.error(msg)
raise ValueError(msg) from e
except ValueError as e:
msg = f"Could not parse secret response for {secret_name!r}."
logger.error(msg)
raise ValueError(msg) from e
except Exception as e:
logger.error(e)
raise ValueError(f"Secret {secret_name!r} could not be loaded.") from e
async def _evaluate_secret_str(
templated_str: str,
*,
template_pattern: re.Pattern[str] = SECRET_TEMPLATE_PATTERN,
regex_group: str = "secret_name",
secret_getter: Awaitable[str, str] = _load_secret,
) -> str:
"""2 pass: 1. Compute all the secret values 2. Substitute the secret value."""
# NOTE: Need to call a funciton repl to evaluate multiple appearances
matches = [
match.group(regex_group) for match in template_pattern.finditer(templated_str)
]
logger.debug(f"{"*"*10} Evaluating secrets {"*"*10}")
tasks = [secret_getter(m) for m in matches]
secret_values = await asyncio.gather(*tasks)
replacement_map = dict(zip(matches, secret_values, strict=True))
def evaluator(match: re.Match[str]) -> str:
key = match.group(regex_group)
return replacement_map[key]
replaced_str = template_pattern.sub(evaluator, templated_str)
return replaced_str
async def _async_evaluate_dict(
obj: dict[str, T], operator: Awaitable[re.Match[str], str]
) -> dict[str, T]:
"""Parallelize the evaluation of the keys and values of a dictionary."""
task_dict = {}
async with asyncio.TaskGroup() as tg:
for k, v in obj.items():
key_task = tg.create_task(_async_evaluate_nested_templates_rec(k, operator))
value_task = tg.create_task(
_async_evaluate_nested_templates_rec(v, operator)
)
task_dict[key_task] = value_task
# At this point, all the tasks have completed. Safe to call result on all.
return {k.result(): v.result() for k, v in task_dict.items()}
async def _async_evaluate_nested_templates_rec(
obj: T,
operator: Awaitable[re.Match[str], str],
) -> T:
"""Process jsonpaths in strings, lists, and dictionaries."""
match obj:
case str():
# Matches anything in {{ ... }}
return await operator(obj)
case list():
tasks = [
_async_evaluate_nested_templates_rec(item, operator) for item in obj
]
return await asyncio.gather(*tasks)
case dict():
return await _async_evaluate_dict(obj, operator)
case _:
return obj
async def evaluate_templated_secrets(
*,
templated_fields: dict[str, Any],
template_pattern: re.Pattern[str] = SECRET_TEMPLATE_PATTERN,
) -> dict[str, Any]:
"""Populate templated secrets with actual values."""
operator = partial(_evaluate_secret_str, template_pattern=template_pattern)
logger.debug(f"{"*"*10} Evaluating templated secrets {"*"*10}")
processed_kwargs = await _async_evaluate_dict(templated_fields, operator)
return processed_kwargs
|
//
// ViewController.swift
// Quiz
//
// Created by Alexis Kirkman on 1/11/17.
// Copyright © 2017 Alexis Kirkman. All rights reserved.
// Displays quiz questions and answers.
import UIKit
class ViewController: UIViewController {
@IBOutlet var currentQuestionLabel: UILabel!
@IBOutlet var nextQuestionLabel: UILabel!
@IBOutlet var answerLabel: UILabel!
@IBOutlet var currentQuestionLabelCenterXConstraint: NSLayoutConstraint!
@IBOutlet var nextQuestionLabelCenterXConstraint: NSLayoutConstraint!
var labelSpace = UILayoutGuide() // UI Layout Guide
var statusCount: Int = 1 // answer display count
let questions: [String] = [
"What is 7+7?",
"What is the capital of Vermont?",
"What is cognac made from?"
]
let answers: [String] = [
"14",
"Montpelier",
"Grapes"
]
var currentQuestionIndex: Int=0
override func viewDidLoad() {
super.viewDidLoad()
currentQuestionLabel.text = questions[currentQuestionIndex]
//UILayoutGuide
self.view.addLayoutGuide(labelSpace)
labelSpace.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
nextQuestionLabel.centerXAnchor.constraint(equalTo: labelSpace.leadingAnchor).isActive = true
currentQuestionLabel.centerXAnchor.constraint(equalTo: labelSpace.trailingAnchor).isActive = true
updateOffScreenLabel()
}
func updateOffScreenLabel() {
let screenWidth = view.frame.width
nextQuestionLabelCenterXConstraint.constant = -screenWidth
}
@IBAction func showNextQuestion(_ sender: UIButton){
currentQuestionIndex += 1
if currentQuestionIndex == questions.count{
currentQuestionIndex = 0
}
let question: String = questions[currentQuestionIndex]
nextQuestionLabel.text = question
answerLabel.text = "???"
animateLabelTransitions()
}
// Adjusts answer display. Doesn't show anwer when
// statusCount % 2 doesn't equal 0
@IBAction func showAnswer(_ sender: UIButton){
if(statusCount%2 != 0) {
let answer: String = answers[currentQuestionIndex]
answerLabel.text = answer
}
else{
answerLabel.text = "???"
}
}
func animateLabelTransitions(){
// Force any outstanding layout changes to occur
view.layoutIfNeeded()
// Animate the alpha
// and the center X constraints
//let screenWidth = view.frame.width
self.nextQuestionLabelCenterXConstraint.constant = 0
//self.currentQuestionLabelCenterXConstraint.constant += screenWidth
statusCount = statusCount + 1
UIView.animate( withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.5,//adds spring effect to questions
initialSpringVelocity: 0.5,
options: [.curveLinear],
animations: {
self.currentQuestionLabel.alpha = 0
self.nextQuestionLabel.alpha = 1
self.view.layoutIfNeeded()
}, completion: { _ in
swap(&self.currentQuestionLabel,
&self.nextQuestionLabel)
swap(&self.currentQuestionLabelCenterXConstraint,
&self.nextQuestionLabelCenterXConstraint)
self.updateOffScreenLabel()
})
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Set the label's initial alpha
nextQuestionLabel.alpha = 0
}
}
|
# STABILITY SELECTION-------------------------
library(glmnet)
library(stabs)
# DATA GENERATION-----------------------------
set.seed(123)
n = 100
p = 200
s = 5
X = matrix(runif(n*p), ncol=p)
colnames(X) = paste0("X",1:p)
beta = c(rep(2,s),rep(0,p-s))
y = 2 + X %*% beta + rnorm(n)
yX = data.frame(y,X)
varType <- rep("N",p)
varType[which(beta!=0)] <- "S"
colnames(X) <- paste0("x", 1:p)
# REGULARIZATION PATH--------------------------
fit <- glmnet(X, y)
plot(fit, xvar="lambda", col=(varType=="S")+1)
l <- cv.glmnet(X, y)$lambda.min
abline(v=log(l))
# STABILITY PATH--------------------------------
B = 100
fit <- glmnet(X, y)
SS <- array(NA, dim=c(B, p, length(fit$lambda)), dimnames=list(1:B, colnames(X), fit$lambda))
Q <- matrix(NA, B, length(fit$lambda))
for (i in 1:B) {
ind <- as.logical(sample(rep(0:1, each=n/2)))
fit.i <- glmnet(X[ind,], y[ind], lambda=fit$lambda)
SS[i,,] <- as.matrix(coef(fit.i)[-1,]!=0)
}
S <- apply(SS, 2:3, mean)
l <- fit$lambda
col <- rep("gray", p)
col[which(beta!=0)]<-"red"
matplot(l, t(S), type="l", lty=1, xlim=rev(range(l)), col=col, lwd=2, las=1, bty="n", xlab=expression(lambda), ylab="Estimated probability")
abline(h=0.6)
# STABS R PACKAGE---------------------------------
fit <- stabsel(x = X, y = y,
fitfun = glmnet.lasso,
q = 20,
cutoff = 0.6)
plot(fit)
fit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.